Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save piq9117/06e659563b720e5d505a282b55fa3e40 to your computer and use it in GitHub Desktop.
Save piq9117/06e659563b720e5d505a282b55fa3e40 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