Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@MaxGabriel
Last active October 31, 2019 22:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save MaxGabriel/9e757f2da60ac53b45bb06b2b097d86b to your computer and use it in GitHub Desktop.
Save MaxGabriel/9e757f2da60ac53b45bb06b2b097d86b to your computer and use it in GitHub Desktop.
persistent-postgresql case insensitive text
-- First enable citext in psql: CREATE EXTENSION IF NOT EXISTS citext;
-- Create Model/CustomTypes.hs
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Model.CustomTypes where
import Data.CaseInsensitive (CI)
import qualified Data.CaseInsensitive as CI
import Data.Text (Text)
import qualified Data.Text as T
import Database.Persist.Sql
import qualified Data.Aeson as J
import Data.Aeson (ToJSON, FromJSON)
import qualified Data.Text.Encoding as TE
instance PersistField (CI Text) where
toPersistValue ciText = PersistDbSpecific $ TE.encodeUtf8 (CI.original ciText)
fromPersistValue (PersistDbSpecific bs) = Right $ CI.mk (TE.decodeUtf8 bs)
fromPersistValue x = Left $ T.pack $ "Expected PersistDbSpecific, received: " ++ show x
instance PersistFieldSql (CI Text) where
sqlType _ = SqlOther "citext"
instance (ToJSON (CI Text)) where
toJSON a = J.String (CI.original a)
instance (FromJSON (CI Text)) where
parseJSON (J.String text) = pure $ CI.mk text
parseJSON v = fail $ "Expected String, encountered " ++ (show v)
-- In Model.hs
import Data.CaseInsensitive (CI)
import Model.CustomTypes ()
-- In models
Comment json -- Adding "json" causes ToJSON and FromJSON instances to be derived.
message Text
insensitive (CI Text)
userId UserId Maybe
deriving Eq
deriving Show
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment