lpsmith / postgresql-simple

Mid-level client library for accessing PostgreSQL from Haskell
Other
206 stars 71 forks source link

PGJSON wrapper? #239

Open michalrus opened 6 years ago

michalrus commented 6 years ago

Wouldn’t that be useful to have in core?

-- |Instances to simplify (de-)serializing JSONB from/to DB.
newtype PGJSON a = PGJSON a deriving (Eq, Show)

instance (FromJSON a, Typeable a) => FromField (PGJSON a) where
  fromField a b = PGJSON <$> fromJSONField a b

instance (ToJSON a) => ToField (PGJSON a) where
  toField (PGJSON a) = toJSONField a

Then one can simply use them ad hoc:

do
  [Only (PGJSON xs)] <- query_ c "select jsonb_build_object('key', 'value')"
  assert (xs == Map.fromList [("key", "value")])

… and similarly, without manually defining To-/FromField instances for all used types.

michalrus commented 6 years ago

(A bit similar to how you can use the PGArray wrapper.)