packages feed

hpgsql-0.4.0: src/Hpgsql/Types.hs

module Hpgsql.Types
  ( Only (..),
    Aeson (..),
    PgJson, -- Do not export ctor
    PGArray (..),
    (:.) (..),
    pgJsonByteString,
  )
where

import Control.Monad (replicateM)
import Data.Aeson (FromJSON, ToJSON)
import qualified Data.Aeson as Aeson
import qualified Data.Aeson.Encoding as AesonInternal
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Builder as Builder
import qualified Data.ByteString.Lazy as LBS
import Data.Tuple.Only (Only (..))
import Data.Typeable (Proxy (..))
import Hpgsql.Builder (BinaryField (..))
import Hpgsql.Encoding.Internal (FieldDecoder (..), FieldEncoder (..), FieldInfo (..), FromPgField (..), FromPgRow (..), RowEncoder (..), ToPgField (..), ToPgRow (..), arrayFieldRowDec, nullableField, parsePgType, rootBaseTypeOf, singleField, toPgVectorField)
import qualified Hpgsql.Internal.PinnedByteArray as PBA
import qualified Hpgsql.SimpleParser as Parser
import Hpgsql.TypeInfo (EncodingContext (..), TypeInfo (..), jsonOid, jsonbOid, lookupTypeByOid)

-- | Encodes a Haskell list as a postgres array. You can also use `Vector` if you prefer.
-- The reason for this type instead of allowing @[a]@ to be a field is that an instance
-- for @[a]@ would require an overlappable instance for @String@, and that is not ideal.
newtype PGArray a = PGArray {fromPGArray :: [a]}
  deriving (Eq, Ord, Read, Show, Functor)

instance forall a. (ToPgField a) => ToPgField (PGArray a) where
  fieldEncoder =
    let fe = fieldEncoder @a
     in FieldEncoder
          { toTypeOid = \encodingContext -> do
              elOid <- fe.toTypeOid encodingContext
              arrayTypInfo <- lookupTypeByOid elOid encodingContext.typeInfoCache
              arrayTypInfo.oidOfArrayType,
            toPgField = \encCtx -> toPgVectorField encCtx . fromPGArray
          }

{-# RULES
"singleField pgArrayFieldDecoder" singleField pgArrayFieldDecoder = fieldRowDecoder
"singleField (nullableField pgArrayFieldDecoder)" singleField (nullableField pgArrayFieldDecoder) = fieldRowDecoder
  #-}

{-# NOINLINE pgArrayFieldDecoder #-} -- See Note [singleField fieldDecoder rewrite rules]
pgArrayFieldDecoder :: (FromPgField a) => FieldDecoder (PGArray a)
pgArrayFieldDecoder = PGArray <$> fst (arrayFieldRowDec replicateM)

instance forall a. (FromPgField a) => FromPgField (PGArray a) where
  {-# INLINE fieldDecoder #-}
  fieldDecoder = pgArrayFieldDecoder
  {-# INLINE specializedFieldDecoder #-}
  specializedFieldDecoder = \finfo -> do
    len <- Parser.takeInt32BE
    case len of
      (-1) -> pure Nothing
      _ -> Just . PGArray <$> snd (arrayFieldRowDec replicateM) finfo

-- | A way to compose two rows.
data h :. t = !h :. !t deriving (Eq, Ord, Show, Read)

infixr 3 :.

instance forall a b. (ToPgRow a, ToPgRow b) => ToPgRow (a :. b) where
  rowEncoder =
    let !re1 = rowEncoder @a
        !re2 = rowEncoder @b
     in RowEncoder
          { toPgParams = \(a :. b) -> re1.toPgParams a ++ re2.toPgParams b,
            toTypeOids = \_ -> re1.toTypeOids (Proxy @a) ++ re2.toTypeOids (Proxy @b),
            toBinaryCopyBytes = \encCtx ->
              let !toBytes1 = re1.toBinaryCopyBytes encCtx
                  !toBytes2 = re2.toBinaryCopyBytes encCtx
               in \(a :. b) -> toBytes1 a <> toBytes2 b
          }

instance (FromPgRow a, FromPgRow b) => FromPgRow (a :. b) where
  rowDecoder = (:.) <$> rowDecoder <*> rowDecoder

-- | A JSON type that does not incur the costs of JSON/aeson deserializing
-- in its `FromPgField` instance because it assumes postgres only generates
-- valid JSON. Useful for extra performance if its opaqueness is not a problem.
-- Although it does have a `toJSON` method, using it will incur a
-- deserialization cost, so if you find yourself using that too much consider just using
-- `Aeson.Value` or the `Aeson` newtype instead of this.
newtype PgJson = PgJson ByteString

instance ToJSON PgJson where
  toJSON (PgJson bs) = case Aeson.eitherDecodeStrict' bs of
    Left err -> error $ "Bug in Hpgsql. PgJson not valid JSON: " ++ err
    Right v -> v

  toEncoding (PgJson bs) = AesonInternal.unsafeToEncoding (Builder.byteString bs)

-- | A valid UTF8 representation of the JSON value.
pgJsonByteString :: PgJson -> ByteString
pgJsonByteString (PgJson bs) = bs

{-# RULES
"singleField pgJsonFieldDecoder" singleField pgJsonFieldDecoder = fieldRowDecoder
"singleField (nullableField pgJsonFieldDecoder)" singleField (nullableField pgJsonFieldDecoder) = fieldRowDecoder
  #-}

{-# NOINLINE pgJsonFieldDecoder #-} -- See Note [singleField fieldDecoder rewrite rules]
pgJsonFieldDecoder :: FieldDecoder PgJson
pgJsonFieldDecoder = parsePgType "PgJson" [jsonOid, jsonbOid] $ \finfo ->
  let
    -- jsonb has a byte prepended to the contents and json does not
    !fixJsonb = if rootBaseTypeOf finfo == jsonbOid then BS.drop 1 else Prelude.id
   in
    \case
      Nothing -> Left "Cannot decode SQL null as the Haskell PgJson type. Use a `Maybe PgJson` if you want SQL nulls"
      Just bs -> Right $ PgJson $ fixJsonb bs

instance FromPgField PgJson where
  {-# INLINE fieldDecoder #-}
  fieldDecoder = pgJsonFieldDecoder

  {-# INLINE specializedFieldDecoder #-}
  specializedFieldDecoder finfo = do
    len <- fromIntegral <$> Parser.takeInt32BE
    if len == (-1)
      then pure Nothing
      else
        fmap (Just . PgJson . PBA.toByteString) $
          if finfo.fieldTypeOid == jsonbOid
            then Parser.skip 1 >> Parser.take (len - 1)
            else Parser.take len

-- | A newtype wrapper to decode a JSON value with Aeson
-- into your type (from either json or jsonb), and to encode
-- to jsonb.
newtype Aeson a = Aeson {getAeson :: a}
  deriving stock (Functor, Read, Show)
  deriving newtype (Eq)

{-# RULES
"singleField aesonFieldDecoder" singleField aesonFieldDecoder = fieldRowDecoder
"singleField (nullableField aesonFieldDecoder)" singleField (nullableField aesonFieldDecoder) = fieldRowDecoder
  #-}

{-# NOINLINE aesonFieldDecoder #-} -- See Note [singleField fieldDecoder rewrite rules]
aesonFieldDecoder :: (FromJSON a) => FieldDecoder (Aeson a)
aesonFieldDecoder = parsePgType "(Aeson a)" [jsonOid, jsonbOid] $ \finfo ->
  let
    -- jsonb has a byte prepended to the contents and json does not
    !fixJsonb = if rootBaseTypeOf finfo == jsonbOid then BS.drop 1 else Prelude.id
   in
    \case
      Nothing -> Left "Cannot decode SQL null as a Haskell (Aeson a) type. Use a `Maybe (Aeson a)` if you want SQL nulls"
      Just bs -> case Aeson.decodeStrict $ fixJsonb bs of
        Just v -> Right $ Aeson v
        Nothing -> Left "Failed to decode the postgres JSON value into your `Aeson a` type with aeson"

instance (FromJSON a) => FromPgField (Aeson a) where
  {-# INLINE fieldDecoder #-}
  fieldDecoder = aesonFieldDecoder
  {-# INLINE specializedFieldDecoder #-}
  specializedFieldDecoder finfo =
    specializedFieldDecoder finfo >>= \case
      Nothing -> pure Nothing
      Just (PgJson jsonBs) ->
        case Aeson.decodeStrict jsonBs of
          Just v -> pure $ Just $ Aeson v
          Nothing -> fail "Failed to decode the postgres JSON value into your `Aeson a` type with aeson"

instance (ToJSON a) => ToPgField (Aeson a) where
  fieldEncoder =
    FieldEncoder
      { toTypeOid = \_ -> Just jsonbOid,
        toPgField = \_ (Aeson v) ->
          NotNull $ BS.cons 1 (LBS.toStrict $ Aeson.encode v)
      }