diff --git a/src/Data.Postgres.js b/src/Data.Postgres.js index c5100b1..2d63f3a 100644 --- a/src/Data.Postgres.js +++ b/src/Data.Postgres.js @@ -1,5 +1,9 @@ import Pg from 'pg' import Range from 'postgres-range' +import { Buffer } from 'buffer' + +/** @type {(a: unknown) => boolean} */ +export const isInstanceOfBuffer = a => a instanceof Buffer export const modifyPgTypes = () => { // https://github.com/brianc/node-pg-types/blob/master/lib/textParsers.js diff --git a/src/Data.Postgres.purs b/src/Data.Postgres.purs index d10b9c2..2a3e439 100644 --- a/src/Data.Postgres.purs +++ b/src/Data.Postgres.purs @@ -3,7 +3,7 @@ module Data.Postgres where import Prelude import Control.Alt ((<|>)) -import Control.Monad.Error.Class (liftEither, liftMaybe) +import Control.Monad.Error.Class (liftEither, liftMaybe, throwError) import Control.Monad.Except (ExceptT, runExceptT) import Control.Monad.Morph (hoist) import Control.Monad.Trans.Class (lift) @@ -19,7 +19,7 @@ import Data.RFC3339String as DateTime.ISO import Data.Traversable (traverse) import Effect (Effect) import Effect.Exception (error) -import Foreign (ForeignError(..), unsafeToForeign) +import Foreign (ForeignError(..), tagOf, unsafeFromForeign, unsafeToForeign) import Foreign as F import JS.BigInt (BigInt) import JS.BigInt as BigInt @@ -40,6 +40,8 @@ derive newtype instance ReadForeign a => ReadForeign (JSON a) -- | for some types to unmarshal as strings rather than JS values. foreign import modifyPgTypes :: Effect Unit +foreign import isInstanceOfBuffer :: F.Foreign -> Boolean + -- | The serialization & deserialization monad. type RepT = ExceptT (NonEmptyList ForeignError) Effect @@ -142,7 +144,12 @@ instance ReadForeign a => Deserialize (JSON a) where -- | `bytea` instance Deserialize Buffer where - deserialize = (F.unsafeReadTagged "Buffer") <<< Raw.asForeign + deserialize = + let + notBuffer a = pure $ TypeMismatch (tagOf a) "Buffer" + readBuffer a = when (not $ isInstanceOfBuffer a) (throwError $ notBuffer a) $> unsafeFromForeign a + in + readBuffer <<< Raw.asForeign -- | `int2`, `int4` instance Deserialize Int where diff --git a/src/Pipes.Postgres.purs b/src/Pipes.Postgres.purs index f329d50..7b3f53a 100644 --- a/src/Pipes.Postgres.purs +++ b/src/Pipes.Postgres.purs @@ -41,9 +41,9 @@ stdin q = do pipe = Pipes.mapM releaseOnEOS >-> fromWritable (O.fromBufferWritable stream) err e = do - liftAff $ void $ Client.exec "rollback" client - liftEffect $ Pool.release pool client - throwError e + liftAff $ void $ Client.exec "rollback" client + liftEffect $ Pool.release pool client + throwError e catchError pipe err