| Safe Haskell | Safe-Inferred |
|---|---|
| Language | Haskell2010 |
Composite.Opaleye.TH
Documentation
getLastComponent :: String -> String Source #
deriveOpaleyeEnum :: Name -> String -> (String -> Maybe String) -> Q [Dec] Source #
Derive the various instances required to make a Haskell enumeration map to a PostgreSQL enum type.
In deriveOpaleyeEnum ''HaskellType "schema.sqltype" hsConToSqlValue, ''HaskellType is the sum type (data declaration) to make instances for,
"schema.sqltype" is the PostgreSQL type name, and hsConToSqlValue is a function to map names of constructors to SQL values.
The function hsConToSqlValue is of the type String -> Maybe String in order to make using stripPrefix convenient. The function is applied to each
constructor name and for Just value that value is used, otherwise for Nothing the constructor name is used.
For example, given the Haskell type:
data MyEnum = MyFoo | MyBar
And PostgreSQL type:
CREATE TYPE myenum AS ENUM(foo,bar);
The splice:
deriveOpaleyeEnum ''MyEnum "myschema.myenum" (stripPrefix"my" .maptoLower)
Will create PGMyEnum and instances required to use MyEnum / Field MyEnum in Opaleye.
The Haskell generated by this splice for the example is something like:
data PGMyEnum
instance IsSqlType PGMyEnum where
showSqlType _ = "myschema.myenum"
instance FromField MyEnum where
fromField f mbs = do
tname <- typename f
case mbs of
_ | getLastComponent (unpack tname) /= "myenum" -> returnError Incompatible f ""
Just "foo" -> pure MyFoo
Just "bar" -> pure MyBar
Just other -> returnError ConversionFailed f ("Unexpected myschema.myenum value: " <> unpack other)
Nothing -> returnError UnexpectedNull f ""
instance DefaultFromField PGMyEnum MyEnum where
defaultFromField = fromPGSFromField
instance Default ToFields MyEnum (Field PGMyEnum) where
def = toToFields $ a ->
literalColumn . stringLit $ case a of
MyFoo -> "foo"
MyBar -> "bar"