git.iko.soy/typeable/postgresql-simple
on master help sign in
Add the toJSONField and fromJSONField functions
cb552f9Bas van Dijk
src/Database/PostgreSQL/Simple/FromField.hs+19
@@ -87,6 +87,8 @@ module Database.PostgreSQL.Simple.FromField
87 , typeOid
87 , typeOid
88 , PQ.Oid(..)
88 , PQ.Oid(..)
89 , PQ.Format(..)
89 , PQ.Format(..)
90+
91+ , fromJSONField
90 ) where
92 ) where
91
93
92#include "MachDeps.h"
94#include "MachDeps.h"
@@ -453,6 +455,23 @@ instance FromField JSON.Value where
453 Left err -> returnError ConversionFailed f err
455 Left err -> returnError ConversionFailed f err
454 Right val -> pure val
456 Right val -> pure val
455
457
458+-- | Parse a field to a JSON 'JSON.Value' and convert that into a
459+-- Haskell value using 'JSON.fromJSON'.
460+--
461+-- This can be used as the default implementation for the 'fromField'
462+-- method for Haskell types that have a JSON representation in
463+-- PostgreSQL.
464+--
465+-- The 'Typeable' constraint is required to show more informative
466+-- error messages when parsing fails.
467+fromJSONField :: (JSON.FromJSON a, Typeable a) => FieldParser a
468+fromJSONField f mbBs = do
469+ value <- fromField f mbBs
470+ case JSON.fromJSON value of
471+ JSON.Error err -> returnError ConversionFailed f $
472+ "JSON decoding error: " ++ err
473+ JSON.Success x -> pure x
474+
456type Compat = PQ.Oid -> Bool
475type Compat = PQ.Oid -> Bool
457
476
458okText, okText', okBinary, ok16, ok32, ok64, okInt :: Compat
477okText, okText', okBinary, ok16, ok32, ok64, okInt :: Compat
src/Database/PostgreSQL/Simple/ToField.hs+10
@@ -18,6 +18,7 @@ module Database.PostgreSQL.Simple.ToField
18 (
18 (
19 Action(..)
19 Action(..)
20 , ToField(..)
20 , ToField(..)
21+ , toJSONField
21 , inQuotes
22 , inQuotes
22 ) where
23 ) where
23
24
@@ -234,6 +235,15 @@ instance (ToField a) => ToField (Vector a) where
234instance ToField JSON.Value where
235instance ToField JSON.Value where
235 toField = toField . JSON.encode
236 toField = toField . JSON.encode
236
237
238+-- | Convert a Haskell value to a JSON 'JSON.Value' using
239+-- 'JSON.toJSON' and convert that to a field using 'toField'.
240+--
241+-- This can be used as the default implementation for the 'toField'
242+-- method for Haskell types that have a JSON representation in
243+-- PostgreSQL.
244+toJSONField :: JSON.ToJSON a => a -> Action
245+toJSONField = toField . JSON.toJSON
246+
237-- | Surround a string with single-quote characters: \"@'@\"
247-- | Surround a string with single-quote characters: \"@'@\"
238--
248--
239-- This function /does not/ perform any other escaping.
249-- This function /does not/ perform any other escaping.