Skip to content

Instantly share code, notes, and snippets.

@MaxGabriel
Created February 27, 2018 02:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MaxGabriel/d30dd874dc6c38b194749c15989dd353 to your computer and use it in GitHub Desktop.
Save MaxGabriel/d30dd874dc6c38b194749c15989dd353 to your computer and use it in GitHub Desktop.
Without helper functions
derivePostgresEnum :: String -> String -> Q [Dec]
derivePostgresEnum s postgresType = do
ss <- [|SqlOther (pack postgresType)|]
tpv <- [|PersistText . pack . show|]
fpv <- [|\dt v ->
case fromPersistValue v of
Left e -> Left e
Right s' ->
case reads $ unpack s' of
(x, _):_ -> Right x
[] -> Left $ pack "Invalid " <> pack dt <> pack ": " <> s'|]
return
[ InstanceD Nothing [] (ConT ''PersistField `AppT` (ConT $ mkName s)) [ FunD 'toPersistValue
[ Clause [] (NormalB tpv) []
]
, FunD 'fromPersistValue
[ Clause [] (NormalB (fpv `AppE` LitE (StringL s))) []
]
]
, InstanceD Nothing [] (ConT ''PersistFieldSql `AppT` (ConT $ mkName s)) [ FunD 'sqlType [ Clause [WildP] (NormalB ss) [] ] ]
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment