git.iko.soy/typeable/postgresql-simple
on master help sign in
Add FromField.optionalField
be8a00fLeon P Smith
src/Database/PostgreSQL/Simple/FromField.hs+15−4
@@ -107,6 +107,7 @@ module Database.PostgreSQL.Simple.FromField
107 , PQ.Format(..)
107 , PQ.Format(..)
108 , pgArrayFieldParser
108 , pgArrayFieldParser
109
109
110+ , optionalField
110 , fromJSONField
111 , fromJSONField
111 ) where
112 ) where
112
113
@@ -268,9 +269,20 @@ instance FromField () where
268-- compatible with type @a@. Note that the type is not checked if
269-- compatible with type @a@. Note that the type is not checked if
269-- the value is null, although it is inadvisable to rely on this
270-- the value is null, although it is inadvisable to rely on this
270-- behavior.
271-- behavior.
271−instance (FromField a) => FromField (Maybe a) where
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
272− fromField _ Nothing = pure Nothing
283+ Nothing -> pure Nothing
273− fromField f bs = Just <$> fromField f bs
284+ Just _ -> Just <$> p f mv
285+{-# INLINE optionalField #-}
274
286
275-- | compatible with any data type, but the value must be null
287-- | compatible with any data type, but the value must be null
276instance FromField Null where
288instance FromField Null where
@@ -567,7 +579,6 @@ fromJSONField f mbBs = do
567 "JSON decoding error: " ++ err
579 "JSON decoding error: " ++ err
568 JSON.Success x -> pure x
580 JSON.Success x -> pure x
569
581
570−
571-- | Compatible with the same set of types as @a@. Note that
582-- | Compatible with the same set of types as @a@. Note that
572-- modifying the 'IORef' does not have any effects outside
583-- modifying the 'IORef' does not have any effects outside
573-- the local process on the local machine.
584-- the local process on the local machine.