postgresqlhaskellopaleye

How to reference newtyped key in Opaleye as nullable?


I'm using newtyped keys for all my tables

newtype Key' a = Key a deriving (Show, Generic, Functor)
type Key = Key' Int64
type KeyR = Key' (Column PGInt8)
type KeyW = Key' (Maybe (Column PGInt8))
$(makeAdaptorAndInstance "pKey" ''Key')

I now want to have a nullable referece to such a key in a different table but I'm struggling. How can I reference a key as nullable?


Solution

  • To combine my comments with @ForestPhoenix's answer:

    Opaleye allows you to convert Column PGInt8 into Int64 when you run the query.

    That means it also allows you to convert Column (Nullable PGInt8) into Maybe Int64.

    You are wrapping Column (Nullable PGInt8) in the Key' newtype (for type safety) which gives you Key' (Column (Nullable PGInt8)). That means when you run the query you need to read it as a Key' (Maybe Int64).

    Maybe this little table makes the correspondence clearer:

    Opaleye side                  | Haskell side
    ----------------------------- | -------------
    Column PGInt8                 | Int64
    Column (Nullable PGInt)       | Maybe Int64
    Key' (Column (Nullable PGInt) | Key' (Maybe Int64) 
    

    In general:

    Opaleye side                    | Haskell side
    ------------------------------- | -------------
    Column o                        | h
    Column (Nullable o)             | Maybe h
    MyNewype' (Column (Nullable o)) | MyNewType' (Maybe h)