module Hasql.Engine.Contexts.Pipeline
  ( Pipeline,
    run,
    statement,
  )
where

import Data.HashMap.Strict qualified as HashMap
import Data.HashSet qualified as HashSet
import Hasql.CodecsVocab qualified as CodecsVocab
import Hasql.CodecsVocab.QualifiedTypeName qualified as CodecsVocab.QualifiedTypeName
import Hasql.Comms.Roundtrip qualified as Comms.Roundtrip
import Hasql.ConnectionState qualified as ConnectionState
import Hasql.ConnectionState.OidCache qualified as OidCache
import Hasql.ConnectionState.StatementCache qualified as StatementCache
import Hasql.Engine.Errors qualified as Errors
import Hasql.Engine.PqProcedures.SelectTypeInfo qualified as PqProcedures.SelectTypeInfo
import Hasql.Engine.Statement qualified as Statement
import Hasql.Platform.Prelude
import Pqi qualified as Pq

run ::
  Pipeline a ->
  ConnectionState.ConnectionState ->
  IO (Either Errors.UseError a, ConnectionState.ConnectionState)
run :: forall a.
Pipeline a
-> ConnectionState -> IO (Either UseError a, ConnectionState)
run (Pipeline Int
totalStatements HashSet QualifiedTypeName
unknownTypes Int
-> Bool
-> OidCache
-> StatementCache
-> (Roundtrip StatementTag a, StatementCache)
runPipeline) connectionState :: ConnectionState
connectionState@ConnectionState.ConnectionState {Bool
OidCache
StatementCache
Connection
preparedStatements :: Bool
statementCache :: StatementCache
oidCache :: OidCache
connection :: Connection
connection :: ConnectionState -> Connection
oidCache :: ConnectionState -> OidCache
statementCache :: ConnectionState -> StatementCache
preparedStatements :: ConnectionState -> Bool
..} = do
  let missingTypes :: HashSet QualifiedTypeName
missingTypes = HashSet QualifiedTypeName -> OidCache -> HashSet QualifiedTypeName
OidCache.selectUnknownNames HashSet QualifiedTypeName
unknownTypes OidCache
oidCache
  Either UseError OidCache
resolvedOidCache <-
    if HashSet QualifiedTypeName -> Bool
forall a. HashSet a -> Bool
HashSet.null HashSet QualifiedTypeName
missingTypes
      then Either UseError OidCache -> IO (Either UseError OidCache)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (OidCache -> Either UseError OidCache
forall a b. b -> Either a b
Right OidCache
oidCache)
      else do
        Either UseError SelectTypeInfoResult
oidCacheUpdates <-
          Connection
-> SelectTypeInfo -> IO (Either UseError SelectTypeInfoResult)
PqProcedures.SelectTypeInfo.run Connection
connection (HashSet QualifiedTypeName -> SelectTypeInfo
PqProcedures.SelectTypeInfo.SelectTypeInfo HashSet QualifiedTypeName
missingTypes)
        pure $ case Either UseError SelectTypeInfoResult
oidCacheUpdates of
          Left UseError
err -> UseError -> Either UseError OidCache
forall a b. a -> Either a b
Left UseError
err
          Right SelectTypeInfoResult
oidCacheUpdates ->
            let foundTypes :: HashSet QualifiedTypeName
foundTypes = SelectTypeInfoResult -> HashSet QualifiedTypeName
forall k a. HashMap k a -> HashSet k
HashMap.keysSet SelectTypeInfoResult
oidCacheUpdates
                notFoundTypes :: HashSet QualifiedTypeName
notFoundTypes = HashSet QualifiedTypeName
-> HashSet QualifiedTypeName -> HashSet QualifiedTypeName
forall a. Hashable a => HashSet a -> HashSet a -> HashSet a
HashSet.difference HashSet QualifiedTypeName
missingTypes HashSet QualifiedTypeName
foundTypes
             in if Bool -> Bool
not (HashSet QualifiedTypeName -> Bool
forall a. HashSet a -> Bool
HashSet.null HashSet QualifiedTypeName
notFoundTypes)
                  then UseError -> Either UseError OidCache
forall a b. a -> Either a b
Left (SessionError -> UseError
Errors.SessionUseError (HashSet (Maybe Text, Text) -> SessionError
Errors.MissingTypesSessionError ((QualifiedTypeName -> (Maybe Text, Text))
-> HashSet QualifiedTypeName -> HashSet (Maybe Text, Text)
forall b a. Hashable b => (a -> b) -> HashSet a -> HashSet b
HashSet.map QualifiedTypeName -> (Maybe Text, Text)
CodecsVocab.QualifiedTypeName.toNameTuple HashSet QualifiedTypeName
notFoundTypes)))
                  else OidCache -> Either UseError OidCache
forall a b. b -> Either a b
Right (OidCache
oidCache OidCache -> OidCache -> OidCache
forall a. Semigroup a => a -> a -> a
<> SelectTypeInfoResult -> OidCache
OidCache.fromHashMap SelectTypeInfoResult
oidCacheUpdates)
  case Either UseError OidCache
resolvedOidCache of
    Left UseError
err -> (Either UseError a, ConnectionState)
-> IO (Either UseError a, ConnectionState)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (UseError -> Either UseError a
forall a b. a -> Either a b
Left UseError
err, ConnectionState
connectionState)
    Right OidCache
newOidCache -> do
      let (Roundtrip StatementTag a
roundtrip, StatementCache
newStatementCache) =
            Int
-> Bool
-> OidCache
-> StatementCache
-> (Roundtrip StatementTag a, StatementCache)
runPipeline Int
0 Bool
preparedStatements OidCache
newOidCache StatementCache
statementCache

      -- Statements carry their tag; the pipeline bookend commands below get none.
      Either (Error (Maybe StatementTag)) a
executionResult <- Roundtrip (Maybe StatementTag) a
-> Maybe StatementTag
-> Connection
-> IO (Either (Error (Maybe StatementTag)) a)
forall tag a.
Roundtrip tag a -> tag -> Connection -> IO (Either (Error tag) a)
Comms.Roundtrip.toPipelineIO ((StatementTag -> Maybe StatementTag)
-> Roundtrip StatementTag a -> Roundtrip (Maybe StatementTag) a
forall a b c. (a -> b) -> Roundtrip a c -> Roundtrip b c
forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first StatementTag -> Maybe StatementTag
forall a. a -> Maybe a
Just Roundtrip StatementTag a
roundtrip) Maybe StatementTag
forall a. Maybe a
Nothing Connection
connection

      let result :: Either UseError a
result =
            (Error (Maybe StatementTag) -> UseError)
-> Either (Error (Maybe StatementTag)) a -> Either UseError a
forall a b c. (a -> b) -> Either a c -> Either b c
forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first
              ( \case
                  Comms.Roundtrip.ClientError Maybe StatementTag
_tag Text
details ->
                    Text -> UseError
Errors.fromSendError Text
details
                  Comms.Roundtrip.ServerError Error (Maybe StatementTag)
recvError ->
                    Error (Maybe (Int, Int, ByteString, [Text], Bool)) -> UseError
Errors.fromRecvError ((Maybe StatementTag -> Maybe (Int, Int, ByteString, [Text], Bool))
-> Error (Maybe StatementTag)
-> Error (Maybe (Int, Int, ByteString, [Text], Bool))
forall a b. (a -> b) -> Error a -> Error b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ((StatementTag -> (Int, Int, ByteString, [Text], Bool))
-> Maybe StatementTag -> Maybe (Int, Int, ByteString, [Text], Bool)
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (\(StatementTag Int
index ByteString
sql [Text]
params Bool
prepared StatementCache
_ StatementCache
_) -> (Int
totalStatements, Int
index, ByteString
sql, [Text]
params, Bool
prepared))) Error (Maybe StatementTag)
recvError)
              )
              Either (Error (Maybe StatementTag)) a
executionResult
          finalStatementCache :: StatementCache
finalStatementCache =
            case Either (Error (Maybe StatementTag)) a
executionResult of
              Right a
_ -> StatementCache
newStatementCache
              Left Error (Maybe StatementTag)
executionError ->
                case Error (Maybe StatementTag) -> Maybe StatementTag
forall a. Error a -> a
forall (w :: * -> *) a. Comonad w => w a -> a
extract Error (Maybe StatementTag)
executionError of
                  Maybe StatementTag
Nothing -> StatementCache
statementCache
                  Just (StatementTag Int
_ ByteString
_ [Text]
_ Bool
_ StatementCache
soFarStatementCache StatementCache
collisionStatementCache) ->
                    -- 42P05 can only be reported in response to our own
                    -- Parse, so the collision cache (with this statement's
                    -- own mapping committed) is safe to adopt whenever it
                    -- occurs.
                    if Error (Maybe StatementTag) -> Bool
forall tag. Error tag -> Bool
Errors.isPrepareCollision Error (Maybe StatementTag)
executionError
                      then StatementCache
collisionStatementCache
                      else StatementCache
soFarStatementCache

      (Either UseError a, ConnectionState)
-> IO (Either UseError a, ConnectionState)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure
        ( Either UseError a
result,
          ConnectionState
connectionState
            { ConnectionState.oidCache = newOidCache,
              ConnectionState.statementCache = finalStatementCache
            }
        )

-- |
-- Composable abstraction over the execution of queries in [the pipeline mode](https://www.postgresql.org/docs/current/libpq-pipeline-mode.html).
--
-- It allows you to issue multiple queries to the server in much fewer network transactions.
-- If the amounts of sent and received data do not surpass the buffer sizes in the driver and on the server it will be just a single roundtrip.
-- Typically the buffer size is 8KB.
--
-- This execution mode is much more efficient than running queries directly from 'Hasql.Session.Session', because in session every statement execution involves a dedicated network roundtrip.
--
-- An obvious question rises then: why not execute all queries like that?
-- In situations where the parameters depend on the result of another query it is impossible to execute them in parallel, because the client needs to receive the results of one query before sending the request to execute the next.
-- This reasoning is essentially the same as the one for the difference between 'Applicative' and 'Monad'.
-- That's why 'Pipeline' does not have the 'Monad' instance.
--
-- To execute 'Pipeline' lift it into 'Hasql.Session.Session' via 'Hasql.Session.pipeline'.
--
-- == Examples
--
-- === Insert-Many or Batch-Insert
--
-- You can use pipeline to turn a single-row insert query into an efficient multi-row insertion session.
-- In effect this should be comparable in performance to issuing a single multi-row insert statement.
--
-- Given the following definition in a Statements module:
--
-- @
-- insertOrder :: 'Hasql.Statement.Statement' OrderDetails OrderId
-- @
--
-- You can lift it into the following session
--
-- @
-- insertOrders :: [OrderDetails] -> 'Hasql.Session.Session' [OrderId]
-- insertOrders orders =
--   'Hasql.Session.pipeline' $
--     for orders $ \order ->
--       'Hasql.Pipeline.statement' order Statements.insertOrder
-- @
--
-- === Combining Queries
--
-- Given the following definitions in a Statements module:
--
-- @
-- selectOrderDetails :: 'Hasql.Statement.Statement' OrderId (Maybe OrderDetails)
-- selectOrderProducts :: 'Hasql.Statement.Statement' OrderId [OrderProduct]
-- selectOrderFinancialTransactions :: 'Hasql.Statement.Statement' OrderId [FinancialTransaction]
-- @
--
-- You can combine them into a session using the `ApplicativeDo` extension as follows:
--
-- @
-- selectEverythingAboutOrder :: OrderId -> 'Hasql.Session.Session' (Maybe OrderDetails, [OrderProduct], [FinancialTransaction])
-- selectEverythingAboutOrder orderId =
--   'Hasql.Session.pipeline' $ do
--     details <- 'Hasql.Pipeline.statement' orderId Statements.selectOrderDetails
--     products <- 'Hasql.Pipeline.statement' orderId Statements.selectOrderProducts
--     transactions <- 'Hasql.Pipeline.statement' orderId Statements.selectOrderFinancialTransactions
--     pure (details, products, transactions)
-- @
data Pipeline a
  = Pipeline
      -- | Amount of statements in this pipeline.
      Int
      -- | Names of types that are used in this pipeline.
      --
      -- They will be used to pre-resolve type OIDs before running the pipeline providing them in OidCache.
      -- It can be assumed in the execution function that these types are always present in the cache.
      -- To achieve that property we will be validating the presence of all requested types in the database or failing before running the pipeline.
      -- In the execution function we will be defaulting to OID 0 for unknown types as a fallback in case of bugs.
      (HashSet CodecsVocab.QualifiedTypeName)
      -- | Function that runs the pipeline.
      --
      -- The integer parameter indicates the current offset of the statement in the pipeline (0-based).
      --
      -- The boolean parameter indicates whether preparable statements should be prepared.
      --
      -- OidCache is provided in which the names of types used in this pipeline are already resolved.
      --
      -- The function takes the current statement cache and returns a tuple of:
      -- 1. The actual roundtrip action to be executed in the pipeline.
      -- 2. The updated statement cache after composing this part of the pipeline.
      --
      -- The resulting cache is optimistic: on failure we recover the last known
      -- committed cache from statement tag carried by roundtrip errors.
      ( Int ->
        Bool ->
        OidCache.OidCache ->
        StatementCache.StatementCache ->
        (Comms.Roundtrip.Roundtrip StatementTag a, StatementCache.StatementCache)
      )

-- | Tag of a statement execution in a pipeline,
-- carried by roundtrip errors to identify the statement and recover the cache.
data StatementTag
  = StatementTag
      -- | Offset of the statement in the pipeline (0-based).
      Int
      -- | SQL.
      ByteString
      -- | Parameters in a human-readable form.
      [Text]
      -- | Whether the statement is prepared.
      Bool
      -- | The cache to recover to on an ordinary failure.
      StatementCache.StatementCache
      -- | The cache to recover to when the failure is a @Parse@ hitting a
      -- 42P05 name collision, i.e., with this statement's own mapping
      -- committed. Since 42P05 can only ever be reported in response to our
      -- own @Parse@, this is only consulted for the tag attached to the
      -- @Parse@ step; elsewhere it's the same as the ordinary recovery
      -- cache.
      StatementCache.StatementCache
  deriving stock (Int -> StatementTag -> ShowS
[StatementTag] -> ShowS
StatementTag -> String
(Int -> StatementTag -> ShowS)
-> (StatementTag -> String)
-> ([StatementTag] -> ShowS)
-> Show StatementTag
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> StatementTag -> ShowS
showsPrec :: Int -> StatementTag -> ShowS
$cshow :: StatementTag -> String
show :: StatementTag -> String
$cshowList :: [StatementTag] -> ShowS
showList :: [StatementTag] -> ShowS
Show, StatementTag -> StatementTag -> Bool
(StatementTag -> StatementTag -> Bool)
-> (StatementTag -> StatementTag -> Bool) -> Eq StatementTag
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: StatementTag -> StatementTag -> Bool
== :: StatementTag -> StatementTag -> Bool
$c/= :: StatementTag -> StatementTag -> Bool
/= :: StatementTag -> StatementTag -> Bool
Eq)

-- * Instances

instance Functor Pipeline where
  fmap :: forall a b. (a -> b) -> Pipeline a -> Pipeline b
fmap a -> b
f (Pipeline Int
count HashSet QualifiedTypeName
unknownTypes Int
-> Bool
-> OidCache
-> StatementCache
-> (Roundtrip StatementTag a, StatementCache)
run) = Int
-> HashSet QualifiedTypeName
-> (Int
    -> Bool
    -> OidCache
    -> StatementCache
    -> (Roundtrip StatementTag b, StatementCache))
-> Pipeline b
forall a.
Int
-> HashSet QualifiedTypeName
-> (Int
    -> Bool
    -> OidCache
    -> StatementCache
    -> (Roundtrip StatementTag a, StatementCache))
-> Pipeline a
Pipeline Int
count HashSet QualifiedTypeName
unknownTypes \Int
offset Bool
usePreparedStatements OidCache
oidCache StatementCache
cache ->
    let (Roundtrip StatementTag a
roundtrip, StatementCache
newStatementCache) = Int
-> Bool
-> OidCache
-> StatementCache
-> (Roundtrip StatementTag a, StatementCache)
run Int
offset Bool
usePreparedStatements OidCache
oidCache StatementCache
cache
     in ((a -> b) -> Roundtrip StatementTag a -> Roundtrip StatementTag b
forall a b.
(a -> b) -> Roundtrip StatementTag a -> Roundtrip StatementTag b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap a -> b
f Roundtrip StatementTag a
roundtrip, StatementCache
newStatementCache)

instance Applicative Pipeline where
  pure :: forall a. a -> Pipeline a
pure a
a =
    Int
-> HashSet QualifiedTypeName
-> (Int
    -> Bool
    -> OidCache
    -> StatementCache
    -> (Roundtrip StatementTag a, StatementCache))
-> Pipeline a
forall a.
Int
-> HashSet QualifiedTypeName
-> (Int
    -> Bool
    -> OidCache
    -> StatementCache
    -> (Roundtrip StatementTag a, StatementCache))
-> Pipeline a
Pipeline Int
0 HashSet QualifiedTypeName
forall a. Monoid a => a
mempty (\Int
_ Bool
_ OidCache
_ StatementCache
cache -> (a -> Roundtrip StatementTag a
forall a. a -> Roundtrip StatementTag a
forall (f :: * -> *) a. Applicative f => a -> f a
pure a
a, StatementCache
cache))

  Pipeline Int
lCount HashSet QualifiedTypeName
leftUnknownTypes Int
-> Bool
-> OidCache
-> StatementCache
-> (Roundtrip StatementTag (a -> b), StatementCache)
lRun <*> :: forall a b. Pipeline (a -> b) -> Pipeline a -> Pipeline b
<*> Pipeline Int
rCount HashSet QualifiedTypeName
rightUnknownTypes Int
-> Bool
-> OidCache
-> StatementCache
-> (Roundtrip StatementTag a, StatementCache)
rRun =
    let unknownTypes :: HashSet QualifiedTypeName
unknownTypes = HashSet QualifiedTypeName
leftUnknownTypes HashSet QualifiedTypeName
-> HashSet QualifiedTypeName -> HashSet QualifiedTypeName
forall a. Semigroup a => a -> a -> a
<> HashSet QualifiedTypeName
rightUnknownTypes
     in Int
-> HashSet QualifiedTypeName
-> (Int
    -> Bool
    -> OidCache
    -> StatementCache
    -> (Roundtrip StatementTag b, StatementCache))
-> Pipeline b
forall a.
Int
-> HashSet QualifiedTypeName
-> (Int
    -> Bool
    -> OidCache
    -> StatementCache
    -> (Roundtrip StatementTag a, StatementCache))
-> Pipeline a
Pipeline (Int
lCount Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
rCount) HashSet QualifiedTypeName
unknownTypes \Int
offset Bool
usePreparedStatements OidCache
oidCache StatementCache
statementCache ->
          let (Roundtrip StatementTag (a -> b)
lRoundtrip, StatementCache
statementCache1) = Int
-> Bool
-> OidCache
-> StatementCache
-> (Roundtrip StatementTag (a -> b), StatementCache)
lRun Int
offset Bool
usePreparedStatements OidCache
oidCache StatementCache
statementCache
              offset1 :: Int
offset1 = Int
offset Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
lCount
              (Roundtrip StatementTag a
rRoundtrip, StatementCache
statementCache2) = Int
-> Bool
-> OidCache
-> StatementCache
-> (Roundtrip StatementTag a, StatementCache)
rRun Int
offset1 Bool
usePreparedStatements OidCache
oidCache StatementCache
statementCache1
           in (Roundtrip StatementTag (a -> b)
lRoundtrip Roundtrip StatementTag (a -> b)
-> Roundtrip StatementTag a -> Roundtrip StatementTag b
forall a b.
Roundtrip StatementTag (a -> b)
-> Roundtrip StatementTag a -> Roundtrip StatementTag b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> Roundtrip StatementTag a
rRoundtrip, StatementCache
statementCache2)

-- * Construction

-- |
-- Execute a statement in pipelining mode.
statement ::
  Statement.Statement params result ->
  params ->
  Pipeline result
statement :: forall params result.
Statement params result -> params -> Pipeline result
statement Statement params result
stmt params
params =
  Int
-> HashSet QualifiedTypeName
-> (Int
    -> Bool
    -> OidCache
    -> StatementCache
    -> (Roundtrip StatementTag result, StatementCache))
-> Pipeline result
forall a.
Int
-> HashSet QualifiedTypeName
-> (Int
    -> Bool
    -> OidCache
    -> StatementCache
    -> (Roundtrip StatementTag a, StatementCache))
-> Pipeline a
Pipeline Int
1 (Statement params result -> HashSet QualifiedTypeName
forall params result.
Statement params result -> HashSet QualifiedTypeName
Statement.unknownTypes Statement params result
stmt) Int
-> Bool
-> OidCache
-> StatementCache
-> (Roundtrip StatementTag result, StatementCache)
run
  where
    sql :: ByteString
sql = Statement params result -> ByteString
forall params result. Statement params result -> ByteString
Statement.sql Statement params result
stmt
    run :: Int
-> Bool
-> OidCache
-> StatementCache
-> (Roundtrip StatementTag result, StatementCache)
run Int
offset Bool
usePreparedStatements OidCache
oidCache =
      if Bool
prepare
        then StatementCache -> (Roundtrip StatementTag result, StatementCache)
runPrepared
        else StatementCache -> (Roundtrip StatementTag result, StatementCache)
runUnprepared
      where
        resolve :: QualifiedTypeName -> TypeInfo
resolve = OidCache -> QualifiedTypeName -> TypeInfo
OidCache.toResolver OidCache
oidCache

        ([Word32]
oidList, [Maybe (ByteString, Bool)]
valueAndFormatList) =
          Statement params result
-> (QualifiedTypeName -> TypeInfo)
-> params
-> ([Word32], [Maybe (ByteString, Bool)])
forall params result.
Statement params result
-> (QualifiedTypeName -> TypeInfo)
-> params
-> ([Word32], [Maybe (ByteString, Bool)])
Statement.compilePreparedStatementData Statement params result
stmt QualifiedTypeName -> TypeInfo
resolve params
params

        prepare :: Bool
prepare =
          Bool
usePreparedStatements Bool -> Bool -> Bool
&& Statement params result -> Bool
forall params result. Statement params result -> Bool
Statement.isPrepared Statement params result
stmt

        tag :: StatementCache -> StatementCache -> StatementTag
tag StatementCache
soFarStatementCache StatementCache
collisionStatementCache =
          Int
-> ByteString
-> [Text]
-> Bool
-> StatementCache
-> StatementCache
-> StatementTag
StatementTag
            Int
offset
            ByteString
sql
            (Statement params result -> params -> [Text]
forall params result. Statement params result -> params -> [Text]
Statement.printer Statement params result
stmt params
params)
            Bool
prepare
            StatementCache
soFarStatementCache
            StatementCache
collisionStatementCache

        runPrepared :: StatementCache -> (Roundtrip StatementTag result, StatementCache)
runPrepared StatementCache
statementCache =
          (Roundtrip StatementTag result
roundtrip, StatementCache
newStatementCache)
          where
            (Bool
isNew, ByteString
remoteKey, StatementCache
newStatementCache) =
              case ByteString -> [Word32] -> StatementCache -> Maybe ByteString
StatementCache.lookup ByteString
sql [Word32]
oidList StatementCache
statementCache of
                Just ByteString
remoteKey -> (Bool
False, ByteString
remoteKey, StatementCache
statementCache)
                Maybe ByteString
Nothing ->
                  let (ByteString
remoteKey, StatementCache
newStatementCache) = ByteString
-> [Word32] -> StatementCache -> (ByteString, StatementCache)
StatementCache.insert ByteString
sql [Word32]
oidList StatementCache
statementCache
                   in (Bool
True, ByteString
remoteKey, StatementCache
newStatementCache)

            roundtrip :: Roundtrip StatementTag result
roundtrip =
              Bool -> Roundtrip StatementTag () -> Roundtrip StatementTag ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when
                Bool
isNew
                (StatementTag
-> ByteString
-> ByteString
-> [Word32]
-> Roundtrip StatementTag ()
forall tag.
tag -> ByteString -> ByteString -> [Word32] -> Roundtrip tag ()
Comms.Roundtrip.prepare (StatementCache -> StatementCache -> StatementTag
tag StatementCache
statementCache StatementCache
newStatementCache) ByteString
remoteKey ByteString
sql [Word32]
oidList)
                Roundtrip StatementTag ()
-> Roundtrip StatementTag result -> Roundtrip StatementTag result
forall a b.
Roundtrip StatementTag a
-> Roundtrip StatementTag b -> Roundtrip StatementTag b
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
*> StatementTag
-> ByteString
-> [Maybe (ByteString, Format)]
-> Format
-> ResultDecoder result
-> Roundtrip StatementTag result
forall tag a.
tag
-> ByteString
-> [Maybe (ByteString, Format)]
-> Format
-> ResultDecoder a
-> Roundtrip tag a
Comms.Roundtrip.queryPrepared (StatementCache -> StatementCache -> StatementTag
tag StatementCache
newStatementCache StatementCache
newStatementCache) ByteString
remoteKey [Maybe (ByteString, Format)]
encodedParams Format
Pq.Binary ResultDecoder result
decoder'
              where
                encodedParams :: [Maybe (ByteString, Format)]
encodedParams =
                  [Maybe (ByteString, Bool)]
valueAndFormatList
                    [Maybe (ByteString, Bool)]
-> ([Maybe (ByteString, Bool)] -> [Maybe (ByteString, Format)])
-> [Maybe (ByteString, Format)]
forall a b. a -> (a -> b) -> b
& (Maybe (ByteString, Bool) -> Maybe (ByteString, Format))
-> [Maybe (ByteString, Bool)] -> [Maybe (ByteString, Format)]
forall a b. (a -> b) -> [a] -> [b]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (((ByteString, Bool) -> (ByteString, Format))
-> Maybe (ByteString, Bool) -> Maybe (ByteString, Format)
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (\(ByteString
bytes, Bool
format) -> (ByteString
bytes, Format -> Format -> Bool -> Format
forall a. a -> a -> Bool -> a
bool Format
Pq.Binary Format
Pq.Text Bool
format)))

        runUnprepared :: StatementCache -> (Roundtrip StatementTag result, StatementCache)
runUnprepared StatementCache
statementCache =
          (Roundtrip StatementTag result
roundtrip, StatementCache
statementCache)
          where
            roundtrip :: Roundtrip StatementTag result
roundtrip =
              StatementTag
-> ByteString
-> [Maybe (Word32, ByteString, Format)]
-> Format
-> ResultDecoder result
-> Roundtrip StatementTag result
forall tag a.
tag
-> ByteString
-> [Maybe (Word32, ByteString, Format)]
-> Format
-> ResultDecoder a
-> Roundtrip tag a
Comms.Roundtrip.queryParams (StatementCache -> StatementCache -> StatementTag
tag StatementCache
statementCache StatementCache
statementCache) ByteString
sql [Maybe (Word32, ByteString, Format)]
encodedParams Format
Pq.Binary ResultDecoder result
decoder'
              where
                encodedParams :: [Maybe (Word32, ByteString, Format)]
encodedParams =
                  Statement params result
-> (QualifiedTypeName -> TypeInfo)
-> params
-> [Maybe (Word32, ByteString, Bool)]
forall params result.
Statement params result
-> (QualifiedTypeName -> TypeInfo)
-> params
-> [Maybe (Word32, ByteString, Bool)]
Statement.compileUnpreparedStatementData Statement params result
stmt QualifiedTypeName -> TypeInfo
resolve params
params
                    [Maybe (Word32, ByteString, Bool)]
-> ([Maybe (Word32, ByteString, Bool)]
    -> [Maybe (Word32, ByteString, Format)])
-> [Maybe (Word32, ByteString, Format)]
forall a b. a -> (a -> b) -> b
& (Maybe (Word32, ByteString, Bool)
 -> Maybe (Word32, ByteString, Format))
-> [Maybe (Word32, ByteString, Bool)]
-> [Maybe (Word32, ByteString, Format)]
forall a b. (a -> b) -> [a] -> [b]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (((Word32, ByteString, Bool) -> (Word32, ByteString, Format))
-> Maybe (Word32, ByteString, Bool)
-> Maybe (Word32, ByteString, Format)
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (\(Word32
oid, ByteString
bytes, Bool
format) -> (Word32
oid, ByteString
bytes, Format -> Format -> Bool -> Format
forall a. a -> a -> Bool -> a
bool Format
Pq.Binary Format
Pq.Text Bool
format)))

        decoder' :: ResultDecoder result
decoder' =
          Statement params result
-> (QualifiedTypeName -> TypeInfo) -> ResultDecoder result
forall params result.
Statement params result
-> (QualifiedTypeName -> TypeInfo) -> ResultDecoder result
Statement.decoder Statement params result
stmt QualifiedTypeName -> TypeInfo
resolve