1

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?

Tom Ellis
  • 9,224
  • 1
  • 29
  • 54
  • What's the context for this question? What packages / libraries are you using? What are your imports? – ErikR Aug 05 '16 at 16:11
  • sorry. The only import needed here except Opaleye is Data.Profunctor.Product.TH (makeAdaptorAndInstance) – Tommy Engström Aug 05 '16 at 17:51
  • How about `type KeyN = Key' (Column (Nullable PGInt8))`? – Tom Ellis Aug 05 '16 at 21:16
  • Okay, so I defined the key like that and the write key as `Key' (Maybe (Column (Nullable PGInt8)))`. Then I ran into: `No instance for (Default QueryRunner (Key' (Column (Nullable PGInt8))) (Maybe Key))`. Is that expected? I just assumed I had done something wrong in defining the types since I thought that default instance would be available to me. – Tommy Engström Aug 08 '16 at 07:14
  • As @ForestPhoenix says below, you need to convert to `Key' (Maybe Int64)`. – Tom Ellis Aug 09 '16 at 18:19
  • Also, on the Opaleye side it should be `Key' (Column (Nullable PGInt8))` (no `Maybe` in there). – Tom Ellis Aug 09 '16 at 18:20

2 Answers2

0

Opaleye has a default instance for Nullable PGInt8 to Maybe Int64.

What you are trying to do is converting from Key' (Column (Nullable PGInt8)) to Maybe Key = Maybe (Key' Int64).

For the default instances to work, you need to either convert

  • from Key' (Column (Nullable PGInt8))) to Key' (Maybe Int64)

  • from Column (Nullable (Key' PGInt8)) to Maybe Key = Maybe (Key' Int64)

ForestPhoenix
  • 155
  • 2
  • 9
0

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)
Tom Ellis
  • 9,224
  • 1
  • 29
  • 54