on 1eaa683 help sign in
rel8/src/Rel8/Type/ReadShow.hs
32 lines 1.0 kB history raw
1{-# language ScopedTypeVariables #-}
2{-# language TypeApplications #-}
3{-# language ViewPatterns #-}
5module Rel8.Type.ReadShow ( ReadShow(..) ) where
7-- base
8import Data.Proxy ( Proxy( Proxy ) )
9import Data.Typeable ( Typeable, typeRep )
10import Prelude
11import Text.Read ( readMaybe )
13-- rel8
14import Rel8.Type ( DBType( typeInformation ) )
15import Rel8.Type.Information ( parseTypeInformation )
17-- text
18import qualified Data.Text as Text
21-- | A deriving-via helper type for column types that store a Haskell value
22-- using a Haskell's 'Read' and 'Show' type classes.
23newtype ReadShow a = ReadShow { fromReadShow :: a }
26instance (Read a, Show a, Typeable a) => DBType (ReadShow a) where
27 typeInformation = parseTypeInformation parser printer typeInformation
28 where
29 parser (Text.unpack -> t) = case readMaybe t of
30 Just ok -> Right $ ReadShow ok
31 Nothing -> Left $ "Could not read " <> t <> " as a " <> show (typeRep (Proxy @a))
32 printer = Text.pack . show . fromReadShow