git.iko.soy/typeable/postgresql-simple
on master help sign in
Add FromField.optionalField

Inspired by an email conversation with Ian Wagner

commitbe8a00fca6982c869f4abad1f704e8cee77d5bff authorLeon P Smith <leon@melding-monads.com> dateThu 19 May 2016, 13:47 (10 years ago) parent999d70f
1 file changed+15−4
src/Database/PostgreSQL/Simple/FromField.hs+15−4
src/Database/PostgreSQL/Simple/FromField.hs+15−4
@@ -107,6 +107,7 @@ module Database.PostgreSQL.Simple.FromField
107107 , PQ.Format(..)
108108 , pgArrayFieldParser
109109
110+ , optionalField
110111 , fromJSONField
111112 ) where
112113
@@ -268,9 +269,20 @@ instance FromField () where
268269-- compatible with type @a@. Note that the type is not checked if
269270-- the value is null, although it is inadvisable to rely on this
270271-- behavior.
271−instance (FromField a) => FromField (Maybe a) where
272− fromField _ Nothing = pure Nothing
273− fromField f bs = Just <$> fromField f bs
272+instance FromField a => FromField (Maybe a) where
273+ fromField = optionalField fromField
274+
275+-- | For dealing with SQL @null@ values outside of the 'FromField' class.
276+-- Alternatively, one could use 'Control.Applicative.optional', but that
277+-- also turns type and conversion errors into 'Nothing', whereas this is
278+-- more specific and turns only @null@ values into 'Nothing'.
279+
280+optionalField :: FieldParser a -> FieldParser (Maybe a)
281+optionalField p f mv =
282+ case mv of
283+ Nothing -> pure Nothing
284+ Just _ -> Just <$> p f mv
285+{-# INLINE optionalField #-}
274286
275287-- | compatible with any data type, but the value must be null
276288instance FromField Null where
@@ -567,7 +579,6 @@ fromJSONField f mbBs = do
567579 "JSON decoding error: " ++ err
568580 JSON.Success x -> pure x
569581
570−
571582-- | Compatible with the same set of types as @a@. Note that
572583-- modifying the 'IORef' does not have any effects outside
573584-- the local process on the local machine.