如何将 Opaleye 中的新类型键引用为可为空?

How to reference newtyped key in Opaleye as nullable?

我为所有 table

使用新类型的密钥
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')

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

Opaleye 有 Nullable PGInt8Maybe 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)

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

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

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

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

也许这个table使对应关系更清楚:

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)