on 8fefc24 help sign in
rel8/src/Rel8/Type/ReadShow.hs
43 lines 1.2 kB history raw
1module Rel8.Type.ReadShow ( ReadShow(..) ) where
3-- base
4import Prelude
5import Text.Read ( readEither )
7-- rel8
8import Rel8.Type ( DBType( typeInformation ) )
9import Rel8.Type.Information ( parseTypeInformation )
11-- text
12import qualified Data.Text as Text
15-- | A deriving-via helper type for column types that store a Haskell value
16-- using a Haskell's 'Read' and 'Show' type classes.
17--
18-- The declaration:
19--
20-- >>> :{
21-- data Color = Red | Green | Blue
22-- deriving (Read, Show)
23-- deriving PrimitiveType via ReadShow Color
24-- :}
25--
26-- will allow you to store @Color@ values in a single SQL column (stored as
27-- @text@).
28newtype ReadShow a = ReadShow { fromReadShow :: a }
31-- | The 'PrimitiveType' instance for 'ReadShow' allows you to serialize a type using
32-- Haskell's 'Read' and 'Show' instances:
33--
34-- @
35-- data Color = Red | Green | Blue
36-- deriving (Read, Show)
37-- deriving PrimitiveType via ReadShow Color
38-- @
39instance (Read a, Show a) => DBType (ReadShow a) where
40 typeInformation = parseTypeInformation parser printer typeInformation
41 where
42 parser = fmap ReadShow . readEither . Text.unpack
43 printer = Text.pack . show . fromReadShow