@@ -1,4 +1,6 @@
1−{-# LANGUAGE RecordWildCards, FlexibleInstances #-}
1+{-# LANGUAGE FlexibleContexts #-}
2+{-# LANGUAGE RecordWildCards, FlexibleInstances, DefaultSignatures #-}
3+
24
35------------------------------------------------------------------------------
46-- |
@@ -27,7 +29,7 @@ module Database.PostgreSQL.Simple.FromRow
2729 ) where
2830
2931import Prelude hiding (null)
30−import Control.Applicative (Applicative(..), (<$>), (<|>), (*>))
32+import Control.Applicative (Applicative(..), (<$>), (<|>), (*>), liftA2)
3133import Control.Monad (replicateM, replicateM_)
3234import Control.Monad.Trans.State.Strict
3335import Control.Monad.Trans.Reader
@@ -45,6 +47,9 @@ import Database.PostgreSQL.Simple.Ok
4547import Database.PostgreSQL.Simple.Types ((:.)(..), Null)
4648import Database.PostgreSQL.Simple.TypeInfo
4749
50+import GHC.Generics
51+
52+
4853-- | A collection type that can be converted from a sequence of fields.
4954-- Instances are provided for tuples up to 10 elements and lists of any length.
5055--
@@ -68,6 +73,8 @@ import Database.PostgreSQL.Simple.TypeInfo
6873
6974class FromRow a where
7075 fromRow :: RowParser a
76+ default fromRow :: (Generic a, GFromRow (Rep a)) => RowParser a
77+ fromRow = to <$> gfromRow
7178
7279getvalue :: PQ.Result -> PQ.Row -> PQ.Column -> Maybe ByteString
7380getvalue result row col = unsafeDupablePerformIO (PQ.getvalue' result row col)
@@ -252,3 +259,21 @@ instance FromField a => FromRow (Maybe (Vector a)) where
252259
253260instance (FromRow a, FromRow b) => FromRow (a :. b) where
254261 fromRow = (:.) <$> fromRow <*> fromRow
262+
263+
264+
265+-- Type class for default implementation of FromRow using generics
266+class GFromRow f where
267+ gfromRow :: RowParser (f p)
268+
269+instance GFromRow f => GFromRow (M1 c i f) where
270+ gfromRow = M1 <$> gfromRow
271+
272+instance (GFromRow f, GFromRow g) => GFromRow (f :*: g) where
273+ gfromRow = liftA2 (:*:) gfromRow gfromRow
274+
275+instance (FromField a) => GFromRow (K1 R a) where
276+ gfromRow = K1 <$> field
277+
278+instance GFromRow U1 where
279+ gfromRow = pure U1