git.iko.soy/typeable/postgresql-simple
on master help sign in
Add ToField and FromField instances for aeson's JSON Value
commit63a00b2584f39850579a8ab844fded49ed961852 authorBas van Dijk <v.dijk.bas@gmail.com> dateThu 12 Sep 2013, 00:23 (13 years ago) parent0551b67
3 files changed+18−1
postgresql-simple.cabal+2−1 src/Database/PostgreSQL/Simple/FromField.hs+12 src/Database/PostgreSQL/Simple/ToField.hs+4
postgresql-simple.cabal+2−1
@@ -52,11 +52,12 @@ Library
5252 Database.PostgreSQL.Simple.TypeInfo.Types
5353
5454 Build-depends:
55+ aeson >= 0.6,
5556 attoparsec >= 0.10.3,
5657 base < 5,
5758 blaze-builder,
5859 blaze-textual,
59− bytestring >= 0.9,
60+ bytestring >= 0.10,
6061 containers,
6162 postgresql-libpq >= 0.6.2,
6263 template-haskell,
src/Database/PostgreSQL/Simple/FromField.hs+12
@@ -94,6 +94,7 @@ module Database.PostgreSQL.Simple.FromField
9494import Control.Applicative
9595 ( Applicative, (<|>), (<$>), pure )
9696import Control.Exception (Exception)
97+import qualified Data.Aeson as JSON
9798import Data.Attoparsec.Char8 hiding (Result)
9899import Data.ByteString (ByteString)
99100import qualified Data.ByteString.Char8 as B
@@ -441,6 +442,17 @@ fromArray typeInfo f = sequence . (parseIt <$>) <$> array delim
441442 where f' | Arrays.Array _ <- item = f
442443 | otherwise = fElem
443444
445+-- | json
446+instance FromField JSON.Value where
447+ fromField f Nothing = returnError UnexpectedNull f ""
448+ fromField f (Just bs)
449+ | typeOid f /= $(inlineTypoid TI.json) =
450+ returnError Incompatible f ""
451+ | otherwise =
452+ case JSON.eitherDecode' $ LB.fromStrict bs of
453+ Left err -> returnError ConversionFailed f err
454+ Right val -> pure val
455+
444456type Compat = PQ.Oid -> Bool
445457
446458okText, okText', okBinary, ok16, ok32, ok64, okInt :: Compat
src/Database/PostgreSQL/Simple/ToField.hs+4
@@ -24,6 +24,7 @@ module Database.PostgreSQL.Simple.ToField
2424import Blaze.ByteString.Builder (Builder, fromByteString, toByteString)
2525import Blaze.ByteString.Builder.Char8 (fromChar)
2626import Blaze.Text (integral, double, float)
27+import qualified Data.Aeson as JSON
2728import Data.ByteString (ByteString)
2829import Data.Int (Int8, Int16, Int32, Int64)
2930import Data.List (intersperse)
@@ -230,6 +231,9 @@ instance (ToField a) => ToField (Vector a) where
230231 -- Because the ARRAY[...] input syntax is being used, it is possible
231232 -- that the use of type-specific separator characters is unnecessary.
232233
234+instance ToField JSON.Value where
235+ toField = toField . JSON.encode
236+
233237-- | Surround a string with single-quote characters: \"@'@\"
234238--
235239-- This function /does not/ perform any other escaping.