@@ -0,0 +1,43 @@
1+module Rel8.Type.ReadShow ( ReadShow(..) ) where
2+
3+-- base
4+import Prelude
5+import Text.Read ( readEither )
6+
7+-- rel8
8+import Rel8.Type ( DBType( typeInformation ) )
9+import Rel8.Type.Information ( parseTypeInformation )
10+
11+-- text
12+import qualified Data.Text as Text
13+
14+
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@).
28+newtype ReadShow a = ReadShow { fromReadShow :: a }
29+
30+
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+-- @
39+instance (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