HORIZON HASKELLDocslts/ghc-10.0.x8c2f8e82026-10-19Search names, modules, packages, or :: a typeCtrl K

GHC 10.0.0.20260917 · lts/ghc-10.0.x · 8c2f8e8 · 2026-10-19

Moduleopaleye-0.10.8.0Haskell2010

Opaleye.Experimental.Enum

  • 1 type
  • 5 values
  • Packageopaleye-0.10.8.0
  • Exports6
  • LanguageHaskell2010
  • LicenceBSD-3-Clause
  • SourceEnum.hs
valueenumMapper
  1. :: String

    The name of the ENUM type

  2. -> (String -> Maybe haskellSum)

    A function which converts from the string representation of the ENUM field

  3. -> (haskellSum -> String)

    A function which converts to the string representation of the ENUM field

  4. -> EnumMapper sqlEnum haskellSum

    The sqlEnum type variable is phantom. To protect yourself against type mismatches you should set it to the Haskell type that you use to represent the ENUM.

#

Create a mapping between a Postgres ENUM type and a Haskell type. Also works for DOMAIN types. For example, if you have the following ENUM

CREATE TYPE public.mpaa_rating AS ENUM (
   'G',
   'PG',
   'PG-13',
   'R',
   'NC-17'
);

then you can define data types to represent the enum on the SQL side and Haskell side respectively

data SqlRating
data Rating = G | PG | PG13 | R | NC17 deriving Show

and functions to map between them

toSqlRatingString :: Rating -> String
toSqlRatingString r = case r of
    G    -> "G"
    PG   -> "PG"
    PG13 -> "PG-13"
    R    -> "R"
    NC17 -> "NC-17"

fromSqlRatingString :: String -> Maybe Rating
fromSqlRatingString s = case s of
    "G"     -> Just G
    "PG"    -> Just PG
    "PG-13" -> Just PG13
    "R"     -> Just R
    "NC-17" -> Just NC17
    _       -> Nothing

Then you can use the mappings as follows

import qualified Opaleye as O
import qualified Data.Profunctor.Product.Default as D

sqlRatingMapper :: EnumMapper SqlRating Rating
sqlRatingMapper = enumMapper "mpaa_rating" fromSqlRatingString toSqlRatingString

instance O.DefaultFromField SqlRating Rating where
  defaultFromField = enumFromField sqlRatingMapper

instance rating ~ Rating
  => D.Default (Inferrable O.FromField) SqlRating rating where
  def = inferrableDef

instance D.Default O.ToFields Rating (O.Field SqlRating) where
  def = enumToFields sqlRatingMapper

instance IsSqlType SqlRating where
  showSqlType = enumShowSqlType sqlRatingMapper
valueenumMapperWithSchema
  1. :: String

    The schema of the ENUM type

  2. -> String

    The name of the ENUM type

  3. -> (String -> Maybe haskellSum)

    A function which converts from the string representation of the ENUM field

  4. -> (haskellSum -> String)

    A function which converts to the string representation of the ENUM field

  5. -> EnumMapper sqlEnum haskellSum

    The sqlEnum type variable is phantom. To protect yourself against type mismatches you should set it to the Haskell type that you use to represent the ENUM.

#