| Safe Haskell | None |
|---|---|
| Language | Haskell2010 |
Composite.Opaleye.TH
Documentation
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 "sqltype" hsConToSqlValue, ''HaskellType is the sum type (data declaration) to make instances for, "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 "myenum" (stripPrefix"my" .maptoLower)
Will create PGMyEnum and instances required to use MyEnum / Column MyEnum in Opaleye.
The Haskell generated by this splice for the example is something like:
data PGMyEnum
instance FromField MyEnum where
fromField f mbs = do
tname <- typename f
case mbs of
_ | tname /= "myenum" -> returnError Incompatible f ""
Just "foo" -> pure MyFoo
Just "bar" -> pure MyBar
Just other -> returnError ConversionFailed f ("Unexpected myenum value: " <> unpack other)
Nothing -> returnError UnexpectedNull f ""
instance QueryRunnerColumnDefault PGMyEnum MyEnum where
queryRunnerColumnDefault = fieldQueryRunnerColumn
instance Default Constant MyEnum (Column PGMyEnum) where
def = constantColumnUsing (def :: Constant String (Column PGText)) $ case
MyFoo -> "foo"
MyBar -> "bar"