Skip to content

Add Any type to handle values without knowing their types #138

@zouppen

Description

@zouppen

I have a code which I'd like to keep compatible if key type changes. For example the primary key of a table can be changed from integer to text without any code changes and I can use the value to insert rows to another table which references that column by doing only database schema changes without affecting the code.

I made a small module to demonstrate the usage. If you'd like to include it to the library, I can make a PR for it.

-- |Implements type which is unparsed. The Any type is intentionally
-- opaque to prevent SQL injections. It's primary purpose is to get a
-- value which is used for future inserts without knowing anything
-- about its type.
module Any (Any) where

import Data.ByteString (ByteString)
import Database.PostgreSQL.Simple
import Database.PostgreSQL.Simple.FromField
import Database.PostgreSQL.Simple.ToField
import Data.ByteString.Builder (byteString)

newtype Any = Any ByteString

instance FromField Any where
  fromField f Nothing = returnError ConversionFailed f ""
  fromField _ (Just bs) = pure $ Any bs

instance ToField Any where
  toField (Any bs) = Plain (byteString bs)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions