How do you work with enum types? #28
-
This is likely not a pg-entity specific question, probably more related to postgres-simple, but maybe you can share tips or advice. How do you map postgres enum types to haskell types? I saw this code example online data TenantStatus = TenantStatusActive | TenantStatusInActive | TenantStatusNew
instance FromField TenantStatus where
fromField field mb_bytestring = makeTenantStatus mb_bytestring
where
makeTenantStatus :: Maybe ByteString -> Conversion TenantStatus
makeTenantStatus (Just "active") = return TenantStatusActive
makeTenantStatus (Just "inactive") = return TenantStatusInActive
makeTenantStatus (Just "new") = return TenantStatusNew
makeTenantStatus (Just _) = returnError ConversionFailed field "Unrecognized tenant status"
makeTenantStatus Nothing = returnError UnexpectedNull field "Empty tenant status" Is this the recommended approach? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Here is what I usually do: data NotificationStatusEnum = NotificationRead | NotificationUnread deriving (Eq, Generic, Show)
instance ToField NotificationStatusEnum where
toField NotificationRead = Escape "Read"
toField NotificationUnread = Escape "Unread"
instance FromField NotificationStatusEnum where
fromField f mdata =
case mdata of
Nothing -> returnError UnexpectedNull f ""
Just bs ->
case parseNotificationStatusEnum bs of
Just a -> pure a
Nothing -> returnError ConversionFailed f $ "Conversion error: Expected 'status' enum, got " <> decodeUtf8 bs <> " instead."
parseNotificationStatusEnum :: (Eq s, IsString s) => s -> Maybe NotificationStatusEnum
parseNotificationStatusEnum "Read" = Just NotificationRead
parseNotificationStatusEnum "Unread" = Just NotificationUnread
parseNotificationStatusEnum _ = Nothing So, fairly close to what you found, except maybe that the failure logic is bundled in the last branch of the |
Beta Was this translation helpful? Give feedback.
-
Thanks 🙏
…On Thu, 20 Jan 2022 at 11:24, Théophile Choutri ***@***.***> wrote:
-
Escape:
https://hackage.haskell.org/package/postgresql-simple-0.6.4/docs/Database-PostgreSQL-Simple-ToField.html#v:Escape
-
UnexpectedNull & ConversionFailed:
https://hackage.haskell.org/package/postgresql-simple-0.6.4/docs/Database-PostgreSQL-Simple.html#t:ResultError
—
Reply to this email directly, view it on GitHub
<#28 (reply in thread)>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/ABSCVATOG4CUFCGCEQXXXDLUW7PERANCNFSM5MGULMLQ>
.
You are receiving this because you authored the thread.Message ID:
***@***.***>
|
Beta Was this translation helpful? Give feedback.
Here is what I usually do: