1

我正在为我的所有表使用新类型的键

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')

我现在想在另一个表中对这样的键有一个可为空的引用,但我正在努力。如何将键引用为可为空的?

4

2 回答 2

0

Opaleye 有一个Nullable PGInt8to的默认实例Maybe Int64

您要做的是从 转换Key' (Column (Nullable PGInt8))Maybe Key = Maybe (Key' Int64).

要使默认实例正常工作,您需要转换

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

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

于 2016-08-09T14:27:06.567 回答
0

将我的评论与@ForestPhoenix 的回答结合起来:

Opaleye 允许您在运行查询时转换Column PGInt8为。Int64

这意味着它还允许您转换Column (Nullable PGInt8)Maybe Int64.

您正在包装Column (Nullable PGInt8)Key'类型(为了类型安全),它为您提供Key' (Column (Nullable PGInt8)). 这意味着当您运行查询时,您需要将其读取为Key' (Maybe Int64).

或许这张小表让对应关系更清晰:

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

一般来说:

Opaleye side                    | Haskell side
------------------------------- | -------------
Column o                        | h
Column (Nullable o)             | Maybe h
MyNewype' (Column (Nullable o)) | MyNewType' (Maybe h)
于 2016-08-09T18:25:19.437 回答