packages feed

hasql 2.0.1.0 → 2.1.0.0

raw patch · 55 files changed

+2670/−1607 lines, 55 filesdep +base16-bytestringdep +cryptohash-sha256dep +testcontainersdep ~iproutedep ~pqi-native

Dependencies added: base16-bytestring, cryptohash-sha256, testcontainers

Dependency ranges changed: iproute, pqi-native

Files

CHANGELOG.md view
@@ -1,3 +1,58 @@+# v2.1.0.0++## Breaking++- `Hasql.Decoders.rowVector` now decodes into any `Data.Vector.Generic` vector (`Vector`, unboxed, storable, primitive) instead of only the boxed `Data.Vector.Vector`, picked by the type the result is consumed as. Call sites that left the vector type to be inferred with nothing pinning it down (no type signature, no boxed-`Vector`-specific downstream use) will now hit an ambiguous type error and need an explicit annotation. (#336)++- `Hasql.Connection.use` now returns `UseError` instead of a single session-error type. `UseError` has two constructors:++  - `SessionUseError` wraps a `SessionError` - the session ran but reported a recoverable error (a server error, a decode failure). The connection is still live.+  - `ConnectionUseError` - the connection is gone, for any reason: a dropped socket, a request libpq refused to send outright, an unexpected response, a bug in Hasql. `use` has closed the handle before returning; every subsequent `use` on the same `Connection` reports this error again.++  Code that pattern-matched on the old session-error type now matches on `UseError`. The `SessionUseError` arm covers the recoverable errors that `SessionError` already expressed; `ConnectionUseError` replaces every constructor that meant the connection was gone.++- `Hasql.Errors.IsError` no longer has an `isTransient` method. Whether a failure is worth retrying depends on the caller's retry policy and, for server errors, the SQLSTATE reported through `toSqlState` - not on a verdict the driver hands out. No replacement is provided.++- `Hasql.Connection.acquire` now returns `AcquireError` instead of a plain `Text` message. The five constructors are organized by which stage of `acquire` failed - connecting, checking the server version, or initializing session settings - since that is what the driver actually observes, rather than by a best-effort classification of `libpq`'s (locale-dependent, adapter-dependent) error text:++  - `ConnectionAcquireError` - the connection could not be established, and no structured signal exists to say why. This is the residual case at the connection stage: DNS failure, connection refused, TLS negotiation failure, a rejected password, a missing database, and any other rejection all land here alike.+  - `ConnectionPasswordRequiredAcquireError` - the server demanded a password and none was available, reported from `libpq`'s own flag rather than inferred from message text.+  - `VersionTooOldAcquireError` - the server's version is below the minimum this driver supports, carrying the server's major, minor and patch version as `Int`s rather than formatted prose.+  - `InitializationConnectionLossAcquireError` - session initialization failed and the connection died, with prose and nothing else.+  - `InitializationServerErrorAcquireError` - session initialization failed and the server said why, carrying a structured `ServerError` with a SQLSTATE.++- A `ConnectionUseError` now closes the connection before returning. `Hasql.Connection.release` on a spent handle does nothing. Pools already discarded connections on fatal errors, so this makes the driver keep the contract its callers were already assuming.++  As a consequence `Hasql.Connection.release` is idempotent, and a released connection can no longer be reached through `use`. Both were undefined behaviour before: `libpq` forbids touching a connection after `PQfinish`, and the driver already closed connections it could not clean up.++  The driver no longer attempts to repair a connection it failed to send on. There is nothing it can assume about the protocol state of such a connection, and the only repair available - pushing a Sync - has the side effect of flushing and committing whatever the failed session had queued. Closing it is both simpler and more honest.++- An exception that cuts a session short - one thrown by the session itself, or an interruption delivered from another thread by `timeout`, `race` or `killThread` - now closes the connection. It propagates as before, but the handle it fired on is spent from then on, so a `timeout` around a session costs a connection rather than returning one. Pools reconnect; code holding a `Hasql.Connection.Connection` directly has to acquire a new one. Server-side session state - anything `set` on the connection - goes with it, where it used to be deliberately preserved across an interruption.++  The driver used to bring such a connection back to a clean state instead - draining results, aborting the transaction, deallocating prepared statements. That repair is blocking network IO performed under a mask, so on a connection whose peer has gone away it never returns and the very interruption being handled never lands. It could also report its own failure as a returned error without rethrowing, which made `timeout` yield `Just (Left _)` instead of `Nothing`. Neither is worth the connection it saves.++## Non-breaking++- Support `iproute-1.8`.++- Prepared statement names are now content-addressed (`hasql_` plus a SHA-256 digest of the SQL and parameter OIDs) rather than per-connection counters. The Haskell API is unchanged. (#324)++- `42P05` ("prepared statement already exists") no longer forces the driver to evict the statement cache entry, and the mapping survives it. (#331)++## Fixes++- `Hasql.Connection.acquire` now finishes the underlying connection on every failure path, and no longer ignores the result of its session-init statements.++- Send requests libpq refuses outright (e.g. over 65535 parameters) now close the connection, so a retry wrapper cannot resend the identical rejected request against the same handle forever. (#327)++- A send failure partway through a pipeline left the connection stuck in pipeline mode with undrained results, so every later session on it failed too. The connection is now closed rather than handed back. (#326)++- A pipeline whose send fails partway through no longer applies the statements preceding the failure. In pipeline mode libpq buffers until a Sync, so those statements had not reached the server; what put them there was the recovery attempt, whose Sync flushed and committed them on the way to reclaiming the connection. Such a pipeline is now discarded whole, matching what a pipeline that fails on a server error already did.++- A session that catches a pipeline failure and carries on no longer runs the rest of itself against a connection the send failed on. The remaining operations report `ConnectionUseError` instead, and the connection is closed however the session ends - including when it swallows the failure and succeeds. Previously the first serial statement after such a catch blocked forever on results the server had never been asked for.++- A connection lost while receiving results is now reported as `ConnectionUseError`, matching how the send side already classified a lost socket. It used to surface as a `StatementSessionError` carrying `UnexpectedRowCountStatementError` - "expected 1 row, got 0" - which is not transient, so retry wrappers did not retry it and pools returned the dead connection for reuse.+ # v2.0.1.0  ## New Features
README.md view
@@ -5,17 +5,17 @@  PostgreSQL driver for Haskell, that prioritizes: -- Reliability-- Flexibility-- Performance+- **Reliability.** Failures come back as values, and the type says whether the connection survived them. See [Errors](#errors).+- **Flexibility.** Sessions compose, codecs are assembled from parts, and even the transport is a choice you make. See [Ecosystem](#ecosystem).+- **Performance.** Statements are prepared by default and can be pipelined into a single round-trip via `Hasql.Session.pipeline`. -# Status+Hasql is production-ready and actively maintained. It's used by many companies and most notably by the [Postgrest](https://github.com/PostgREST/postgrest) project. The API changes at major versions and each major release is supported for at least a year, as described under [Support policy](#support-policy). Every change is recorded in the [changelog](CHANGELOG.md). -Hasql is production-ready, actively maintained and the API is moderately stable. It's used by many companies and most notably by the [Postgrest](https://github.com/PostgREST/postgrest) project.+Upgrading from 1.x? `Hasql.Connection.acquire` now takes a transport adapter as its first argument, so switching is a one-argument change, and the error types have been reshaped. The [changelog](CHANGELOG.md) lists every break. -# Pluggable Transport+## Getting started -Hasql's transport is pluggable via [`pqi`](https://github.com/nikita-volkov/pqi). Hasql itself carries no C dependency. It programs against the `pqi` interface, and you pick the adapter that implements it. That means you depend on two packages, not one:+Hasql carries no C dependency. It programs against the ["pqi"](https://github.com/nikita-volkov/pqi) interface, and you pick the adapter that implements it. That means you depend on two packages, not one:  ```cabal build-depends:@@ -26,89 +26,17 @@ `Hasql.Connection.acquire` then takes the adapter explicitly, as its first argument:  ```haskell-import Pqi.Ffi qualified    -- the C-backed libpq transport-import Pqi.Native qualified -- alpha: pure-Haskell, no C dependency, interchangeable with Pqi.Ffi- connection <- Hasql.Connection.acquire Pqi.Ffi.adapter settings--- or-connection <- Hasql.Connection.acquire Pqi.Native.adapter settings ``` -[`pqi-ffi`](https://github.com/nikita-volkov/pqi-ffi) is the stable, production-proven default. It binds the C `libpq` library, so it requires `libpq` of at least version 14 to be installed to compile - which typically just means having a recent PostgreSQL distro installed. Through it Hasql is tested against a wide range of PostgreSQL servers, starting from version 9.--[`pqi-native`](https://github.com/nikita-volkov/pqi-native) is a from-scratch, pure-Haskell implementation of the Postgres wire protocol, with no C dependency at all. It is thoroughly tested: [`pqi-conformance`](https://github.com/nikita-volkov/pqi-conformance) runs it side by side with `libpq` on the same inputs and checks that the results agree, and the test-suites of `hasql`, [`hasql-pool`](https://github.com/nikita-volkov/hasql-pool) and [`hasql-transaction`](https://github.com/nikita-volkov/hasql-transaction) now run against both adapters, so the whole stack above the transport is exercised on `pqi-native` too. **It's still labelled alpha** - not yet proven at production scale. The two adapters are fully interchangeable: swapping between them is a one-line change (a different `Adapter` value, nothing else), so you can try `pqi-native` today with no lock-in and no rewrite to fall back if needed.--# Ecosystem--Hasql is not just a single library, it is a granular ecosystem of composable libraries, each isolated to perform its own task and stay simple.--- ["hasql"](https://github.com/nikita-volkov/hasql) - the root of the ecosystem, which provides the essential abstraction over the PostgreSQL client functionality and mapping of values. Everything else revolves around that library.--- ["hasql-transaction"](https://github.com/nikita-volkov/hasql-transaction) - an STM-inspired composable abstraction over database transactions providing automated conflict resolution.--- ["hasql-pool"](https://github.com/nikita-volkov/hasql-pool) - a Hasql-specialized abstraction over the connection pool.--- ["hasql-postgresql-types"](https://github.com/nikita-volkov/hasql-postgresql-types) - integration with the ["postgresql-types"](https://github.com/nikita-volkov/postgresql-types) library, which is a collection of Haskell types precisely modeling PostgreSQL types without data loss or compromise.--- ["hasql-dynamic-statements"](https://github.com/nikita-volkov/hasql-dynamic-statements) - a toolkit for generating statements based on the parameters.--- ["hasql-th"](https://github.com/nikita-volkov/hasql-th) - Template Haskell utilities, providing compile-time syntax checking and easy statement declaration. --- ["hasql-cursor-query"](https://github.com/nikita-volkov/hasql-cursor-query) - a declarative abstraction over cursors.--- ["hasql-cursor-transaction"](https://github.com/nikita-volkov/hasql-cursor-transaction) - a lower-level abstraction over cursors, which however allows to fetch from multiple cursors simultaneously. Generally though "hasql-cursor-query" is the recommended alternative.--- ["hasql-migration"](https://github.com/tvh/hasql-migration) - A port of postgresql-simple-migration for use with hasql.--- ["hasql-listen-notify"](https://github.com/awkward-squad/hasql-listen-notify) / ["hasql-notifications"](https://github.com/diogob/hasql-notifications) - Support for PostgreSQL asynchronous notifications.--- ["hasql-optparse-applicative"](https://github.com/sannsyn/hasql-optparse-applicative) - "optparse-applicative" parsers for Hasql.--- ["hasql-implicits"](https://github.com/nikita-volkov/hasql-implicits) - implicit definitions, such as default codecs for standard types.--- ["hasql-interpolate"](https://github.com/awkward-squad/hasql-interpolate) - a QuasiQuoter that supports interpolating Haskell expressions into Hasql queries.--<sup>Want to list your package or correct something here? Make a PR.</sup>--## Transport adapters--Unlike the extension libraries above, which are optional, a transport adapter is mandatory: Hasql needs one to talk to the server at all. See [Pluggable Transport](#pluggable-transport) for how to pick one.--- ["pqi"](https://github.com/nikita-volkov/pqi) - the driver-agnostic interface that Hasql programs against. Pulled in automatically. You don't depend on it directly.--- ["pqi-ffi"](https://github.com/nikita-volkov/pqi-ffi) - the stable adapter, backed by the C `libpq` library.--- ["pqi-native"](https://github.com/nikita-volkov/pqi-native) - an alpha pure-Haskell adapter speaking the PostgreSQL wire protocol directly, with no C dependency.--## Why make it an ecosystem?--- **Focus.**-Each library in isolation provides a simple API, which is focused on a specific task or a few related tasks.--- **Flexibility.**-The user picks and chooses the features, thus precisely matching the level of abstraction that he needs for his task.--- **Much more stable and descriptive semantic versioning.**-E.g., a change in the API of the "hasql-transaction" library won't affect any of the other libraries and it gives the user a more precise information about which part of his application he needs to update to conform.--- **Interchangeability and competition of the ecosystem components.**-E.g., [not everyone will agree](https://github.com/nikita-volkov/hasql/issues/41) with the restrictive design decisions made in the "hasql-transaction" library. However those decisions are not imposed on the user, and instead of having endless debates about how to abstract over transactions, another extension library can simply be released, which will provide a different interpretation of what the abstraction over transactions should be.--- **Horizontal scalability of the ecosystem.**-Instead of posting feature- or pull-requests, the users are encouraged to release their own small extension-libraries, with themselves becoming the copyright owners and taking on the maintenance responsibilities. Compare this model to the classical one, where some core-team is responsible for everything. One is scalable, the other is not.--# Documentation--- [**Data-Access Architecture**](https://github.com/nikita-volkov/hasql-docs/blob/main/data-access-architecture.md) — a normative reference for organising database integration code built on Hasql. It specifies how to layer types, statements, transactions and sessions, where the application domain enters the picture, how the three error channels differ, and what to test at each level. Every rule carries its rationale and derives from the capability differences between Hasql's four constructs.--The reference is written to be consumed directly by coding agents as well as by people. Point an agent at [the raw file](https://raw.githubusercontent.com/nikita-volkov/hasql-docs/main/data-access-architecture.md) and it has the whole system in context, with the rules numbered so they can be cited back in review.+["pqi-ffi"](https://github.com/nikita-volkov/pqi-ffi) is the stable, production-proven default. ["pqi-native"](https://github.com/nikita-volkov/pqi-native) is a pure-Haskell alpha with no C dependency at all. [Transport adapters](#transport-adapters) covers how to choose. -# Short Example+## Example -Following is a complete application, which performs some arithmetic in Postgres using Hasql.+Following is a complete application, which sums three numbers in Postgres by running one statement twice on the same connection.  ```haskell-{-# LANGUAGE OverloadedStrings, QuasiQuotes #-}+{-# LANGUAGE OverloadedStrings #-}  import Data.Functor.Contravariant import Data.Int@@ -120,15 +48,18 @@ import qualified Hasql.Encoders as Encoders import qualified Hasql.Session as Session import qualified Hasql.Statement as Statement-import qualified Pqi.Ffi -- from "pqi-ffi" (stable). Swap for "Pqi.Native" from "pqi-native" (alpha, fully interchangeable) to try the pure-Haskell backend+import qualified Pqi.Ffi  main :: IO () main = do-  Right connection <- Connection.acquire Pqi.Ffi.adapter connectionSettings-  result <- Connection.use connection (sumAndDivModSession 3 8 3)-  print result+  acquisition <- Connection.acquire Pqi.Ffi.adapter settings+  case acquisition of+    Left err -> fail (show err)+    Right connection -> do+      result <- Connection.use connection (sumSession 3 8 4)+      print result   where-    connectionSettings =+    settings =       mconcat         [ Settings.hostAndPort "localhost" 5432,           Settings.user "postgres",@@ -139,97 +70,122 @@           -- Settings.noPreparedStatements True         ] --- * Sessions---- Session abstracts over the execution of operations on a database connection.--- It is composable and has a Monad instance.----------------------------sumAndDivModSession :: Int64 -> Int64 -> Int64 -> Session (Int64, Int64)-sumAndDivModSession a b c = do-  -- Get the sum of a and b-  sumOfAAndB <- Session.statement (a, b) sumStatement-  -- Divide the sum by c and get the modulo as well-  Session.statement (sumOfAAndB, c) divModStatement---- * Statements---- Statement is a definition of an individual SQL-statement,--- accompanied by a specification of how to encode its parameters and--- decode its result.--------------------------+-- | Session abstracts over the execution of operations on a connection.+-- It has a Monad instance, so statements compose.+sumSession :: Int64 -> Int64 -> Int64 -> Session Int64+sumSession a b c = do+  ab <- Session.statement (a, b) sumStatement+  Session.statement (ab, c) sumStatement --- | A statement with two integer parameters and an integer result.+-- | Statement is a definition of an individual SQL-statement, accompanied by+-- a specification of how to encode its parameters and decode its result. sumStatement :: Statement.Statement (Int64, Int64) Int64 sumStatement = Statement.preparable sql encoder decoder   where-    -- The SQL of the statement, with $1, $2, ... placeholders for parameters.     sql =       "select $1 + $2"-    -- Specification of how to encode the parameters of the statement-    -- where the association with placeholders is achieved by order.     encoder =       mconcat-        [ -- Encoder of the first parameter as a non-nullable int8.-          -- It extracts the first element of the tuple using the contravariant functor-          -- instance.-          fst >$< Encoders.param (Encoders.nonNullable Encoders.int8),-          -- Encoder of the second parameter,-          -- which extracts the second element of the tuple.-          snd >$< Encoders.param (Encoders.nonNullable Encoders.int8)-        ]-    -- Specification of how to decode the result of the statement.-    -- States that we expect a single row with a single non-nullable int8 column.-    decoder =-      Decoders.singleRow-        (Decoders.column (Decoders.nonNullable Decoders.int8))--divModStatement :: Statement.Statement (Int64, Int64) (Int64, Int64)-divModStatement = Statement.preparable sql encoder decoder-  where-    sql =-      "select $1 / $2, $1 % $2"-    encoder =-      mconcat         [ fst >$< Encoders.param (Encoders.nonNullable Encoders.int8),           snd >$< Encoders.param (Encoders.nonNullable Encoders.int8)         ]-    -- Decoder that expects a single row with two non-nullable int8 columns,-    -- returning the result as a tuple.-    -- Uses the applicative functor instance to combine two column decoders.     decoder =       Decoders.singleRow-        ( (,)-            <$> Decoders.column (Decoders.nonNullable Decoders.int8)-            <*> Decoders.column (Decoders.nonNullable Decoders.int8)-        )+        (Decoders.column (Decoders.nonNullable Decoders.int8)) ``` -For the general use-case it is advised to prefer declaring statements using the "hasql-th" library, which validates the statements at compile-time and generates codecs automatically. So the above two statements could be implemented the following way:+[Your First Statement](https://github.com/nikita-volkov/hasql-docs/blob/main/your-first-statement.md) is the same program with the annotations left in, explaining the encoder and decoder vocabulary line by line. -```haskell-import qualified Hasql.TH as TH -- from "hasql-th"+## Errors -sumStatement :: Statement.Statement (Int64, Int64) Int64-sumStatement =-  [TH.singletonStatement|-    select ($1 :: int8 + $2 :: int8) :: int8-  |]+Every operation reports its failures as values. There are three error types, in `Hasql.Errors`, and which one you get tells you what state you're left in. -divModStatement :: Statement.Statement (Int64, Int64) (Int64, Int64)-divModStatement =-  [TH.singletonStatement|-    select-      (($1 :: int8) / ($2 :: int8)) :: int8,-      (($1 :: int8) % ($2 :: int8)) :: int8-  |]+`Hasql.Connection.acquire` returns `AcquireError`, organized by the stage that failed: connecting, checking the server version, or initializing session settings.++`Hasql.Connection.use` returns `UseError`, which splits on the only distinction the caller can act on:++```haskell+result <- Connection.use connection session+case result of+  Right a -> pure a+  -- The session failed, the connection is still live and reusable.+  Left (Errors.SessionUseError err) -> ...+  -- The connection is gone. Hasql has already closed it.+  Left (Errors.ConnectionUseError reason) -> ... ``` -# Discussions+A `ConnectionUseError` means the handle is spent. Hasql finished the connection before returning, so every later `use` on it reports the same error and `release` is a no-op. Pools must discard it rather than return it. A `SessionUseError` carries a `SessionError` and leaves the connection untouched. +All three types implement `IsError`, which renders a message and details for logging and exposes the server's SQLSTATE through `toSqlState` where one was reported.++## Documentation++The long-form material lives in [hasql-docs](https://github.com/nikita-volkov/hasql-docs).++- [**Your First Statement**](https://github.com/nikita-volkov/hasql-docs/blob/main/your-first-statement.md) - an annotated walkthrough of a complete Hasql program, explaining the encoder and decoder vocabulary line by line. Start here if the [Example](#example) above went past too fast.++- [**Data-Access Architecture**](https://github.com/nikita-volkov/hasql-docs/blob/main/data-access-architecture.md) - a normative reference for organizing database integration code built on Hasql. It specifies how to layer types, statements, transactions and sessions, where the application domain enters the picture, how the three error channels differ, and what to test at each level. Every rule carries its rationale and derives from the capability differences between Hasql's four constructs.++- [**Why Make It an Ecosystem?**](https://github.com/nikita-volkov/hasql-docs/blob/main/why-an-ecosystem.md) - the rationale for splitting Hasql into many small, separately-versioned libraries instead of one large one.++The architecture reference is written to be consumed directly by coding agents as well as by people. Point an agent at [the raw file](https://raw.githubusercontent.com/nikita-volkov/hasql-docs/main/data-access-architecture.md) and it has the whole system in context, with the rules numbered so they can be cited back in review.++Per-module API docs are on [Hackage](https://hackage.haskell.org/package/hasql), and the [continuous Haddock](https://nikita-volkov.github.io/hasql/) tracks `master`.++## Ecosystem++Hasql is not just a single library, it is a granular ecosystem of composable libraries, each isolated to perform its own task and stay simple. Each one is separately versioned and separately owned, so a change in one doesn't ripple into the others and anyone can publish an alternative without asking. Instead of debating how transactions or cursors should be abstracted, the ecosystem carries competing answers side by side. [Why Make It an Ecosystem?](https://github.com/nikita-volkov/hasql-docs/blob/main/why-an-ecosystem.md) gives the full argument.++<!-- TODO: curate this list. Every published extension is still on a pre-2.x+     release, and at least one entry below redirects the reader elsewhere. -->++- ["hasql"](https://github.com/nikita-volkov/hasql) - the root of the ecosystem, which provides the essential abstraction over the PostgreSQL client functionality and mapping of values. Everything else revolves around that library.++- ["hasql-transaction"](https://github.com/nikita-volkov/hasql-transaction) - an STM-inspired composable abstraction over database transactions providing automated conflict resolution.++- ["hasql-pool"](https://github.com/nikita-volkov/hasql-pool) - a Hasql-specialized abstraction over the connection pool.++- ["hasql-postgresql-types"](https://github.com/nikita-volkov/hasql-postgresql-types) - integration with the ["postgresql-types"](https://github.com/nikita-volkov/postgresql-types) library, which is a collection of Haskell types precisely modeling PostgreSQL types without data loss or compromise.++- ["hasql-dynamic-statements"](https://github.com/nikita-volkov/hasql-dynamic-statements) - a toolkit for generating statements based on the parameters.++- ["hasql-th"](https://github.com/nikita-volkov/hasql-th) - Template Haskell utilities, providing compile-time syntax checking and easy statement declaration.++- ["hasql-cursor-query"](https://github.com/nikita-volkov/hasql-cursor-query) - a declarative abstraction over cursors.++- ["hasql-cursor-transaction"](https://github.com/nikita-volkov/hasql-cursor-transaction) - a lower-level abstraction over cursors, which however allows to fetch from multiple cursors simultaneously. Generally though "hasql-cursor-query" is the recommended alternative.++- ["hasql-migration"](https://github.com/tvh/hasql-migration) - A port of postgresql-simple-migration for use with hasql.++- ["hasql-listen-notify"](https://github.com/awkward-squad/hasql-listen-notify) / ["hasql-notifications"](https://github.com/diogob/hasql-notifications) - Support for PostgreSQL asynchronous notifications.++- ["hasql-optparse-applicative"](https://github.com/sannsyn/hasql-optparse-applicative) - "optparse-applicative" parsers for Hasql.++- ["hasql-implicits"](https://github.com/nikita-volkov/hasql-implicits) - implicit definitions, such as default codecs for standard types.++- ["hasql-interpolate"](https://github.com/awkward-squad/hasql-interpolate) - a QuasiQuoter that supports interpolating Haskell expressions into Hasql queries.++<sup>Want to list your package or correct something here? Make a PR.</sup>++### Transport adapters++Unlike the extension libraries above, which are optional, a transport adapter is mandatory: Hasql needs one to talk to the server at all.++- ["pqi"](https://github.com/nikita-volkov/pqi) - the driver-agnostic interface that Hasql programs against. Pulled in automatically. You don't depend on it directly.++- ["pqi-ffi"](https://github.com/nikita-volkov/pqi-ffi) - the stable adapter, backed by the C "libpq" library. It requires "libpq" of at least version 14 to be installed to compile, which typically just means having a recent PostgreSQL distro installed. Through it Hasql is tested against a wide range of PostgreSQL servers, starting from version 9.++- ["pqi-native"](https://github.com/nikita-volkov/pqi-native) - a from-scratch, pure-Haskell implementation of the Postgres wire protocol, with no C dependency at all.++"pqi-native" is thoroughly tested: ["pqi-conformance"](https://github.com/nikita-volkov/pqi-conformance) runs it side by side with "libpq" on the same inputs and checks that the results agree, and the test-suites of "hasql", ["hasql-pool"](https://github.com/nikita-volkov/hasql-pool) and ["hasql-transaction"](https://github.com/nikita-volkov/hasql-transaction) now run against both adapters, so the whole stack above the transport is exercised on it too. It's still labelled **alpha**, because it is not yet proven at production scale. That status lifts when it gets traction and successful usage reports.++The two adapters are fully interchangeable. Swapping between them is a one-argument change, nothing else, so you can try "pqi-native" today with no lock-in and fall back without a rewrite.++## Discussions+ Join [GitHub Discussions](https://github.com/nikita-volkov/hasql/discussions) to ask questions, provide feedback, suggest and vote on features, and help shape the future of Hasql. -# Support Policy+## Support policy  This policy is intended to balance stability for users with the ability to evolve the library. 
hasql.cabal view
@@ -1,6 +1,6 @@ cabal-version: 3.0 name: hasql-version: 2.0.1.0+version: 2.1.0.0 category: Hasql, Database, PostgreSQL synopsis: Fast PostgreSQL driver with a flexible mapping API description:@@ -161,7 +161,7 @@     hasql:connection-state,     hasql:platform,     hasql:to-be-resolved,-    iproute >=1.7 && <1.8,+    iproute >=1.7 && <1.9,     postgresql-binary ^>=0.15,     postgresql-connection-string ^>=0.1,     pqi >=1.0 && <1.2,@@ -229,6 +229,10 @@     Hasql.ConnectionState.StatementCache    build-depends:+    base16-bytestring >=1.0 && <1.1,+    bytestring >=0.10 && <0.13,+    bytestring-strict-builder >=0.4.5.4 && <0.5,+    cryptohash-sha256 >=0.11 && <0.12,     hasql:codecs-vocab,     hasql:platform,     pqi >=1.0 && <1.2,@@ -244,7 +248,6 @@     Hasql.Comms.RowDecoder     Hasql.Comms.RowReader     Hasql.Comms.Send-    Hasql.Comms.Session    build-depends:     attoparsec >=0.10 && <0.15,@@ -262,7 +265,7 @@     criterion >=1.6 && <2,     hasql,     pqi-ffi ^>=1.0,-    pqi-native ^>=1.0,+    pqi-native ^>=1.0.1.0,     rerebase <2,  test-suite profiling@@ -281,27 +284,6 @@     rerebase >=1 && <2,     testcontainers-postgresql ^>=0.2, -test-suite comms-tests-  import: test-  type: exitcode-stdio-1.0-  hs-source-dirs: src/comms-tests-  main-is: Main.hs-  other-modules:-    Hasql.Comms.Session.CleanUpAfterInterruptionSpec-    Hasql.Comms.SpecHook--  build-tool-depends:-    hspec-discover:hspec-discover ^>=2.11.12--  build-depends:-    hasql:comms,-    hasql:platform,-    hspec ^>=2.11.12,-    pqi >=1.0 && <1.2,-    pqi-ffi ^>=1.0,-    testcontainers-postgresql ^>=0.2,-    text-builder >=1 && <1.1,- test-suite connection-state-tests   import: test   type: exitcode-stdio-1.0@@ -316,6 +298,7 @@    build-depends:     base >=4.14 && <5,+    bytestring >=0.10 && <0.13,     hasql:codecs-vocab,     hasql:connection-state,     hspec ^>=2.11.12,@@ -330,6 +313,7 @@     Helpers.Adapters     Helpers.Dsls.Execution     Helpers.Dsls.Statement+    Helpers.PostgresContainer     Helpers.Scripts     Helpers.Statements     Helpers.Statements.BrokenSyntax@@ -337,12 +321,14 @@     Helpers.Statements.CurrentSetting     Helpers.Statements.GenerateSeries     Helpers.Statements.SelectOne+    Helpers.Statements.SelectPreparedStatementNames     Helpers.Statements.SelectProvidedInt8     Helpers.Statements.SetConfig     Helpers.Statements.Sleep+    Helpers.Statements.TooManyParams     Helpers.Statements.WrongDecoder     Integration.Isolated.Connection.AcquireSpec-    Integration.Sharing.Connection.Use.PipelineAbortedInterruptionCleanupSpec+    Integration.Sharing.Connection.Use.InterruptionSpec     Integration.Sharing.Connection.UseSpec     Integration.Sharing.Decoders.CitextSpec     Integration.Sharing.Decoders.Composite.OidMismatchSpec@@ -371,14 +357,19 @@     Integration.Sharing.Encoders.UnknownSpec     Integration.Sharing.Encoders.UuidSpec     Integration.Sharing.ErrorsSpec+    Integration.Sharing.Pipeline.Statement.SendFailureSpec     Integration.Sharing.PipelineSpec     Integration.Sharing.Session.CatchErrorSpec+    Integration.Sharing.Session.OnLibpqConnection.DirtyReturnCleanupSpec+    Integration.Sharing.Session.RecoveredPipelineFailureSpec     Integration.Sharing.Session.ScriptSpec     Integration.Sharing.Session.StatementSpec     Integration.Sharing.SessionSpec     Integration.Sharing.SpecHook+    Integration.Sharing.Statement.PreparedStatementNamingSpec     Integration.Sharing.StatementSpec     Integration.SpecHook+    Pure.Connection.AcquireSpec     Pure.ErrorsSpec    build-tool-depends:@@ -391,11 +382,12 @@     iproute,     pqi >=1.0 && <1.2,     pqi-ffi ^>=1.0,-    pqi-native ^>=1.0,+    pqi-native ^>=1.0.1.0,     QuickCheck,     quickcheck-instances >=0.3.11 && <0.4,     random >=1.3 && <1.4,     random ^>=1.3.1,     rerebase >=1 && <2,+    testcontainers ^>=0.5,     testcontainers-postgresql ^>=0.2,     text-builder >=1 && <1.1,
− src/comms-tests/Hasql/Comms/Session/CleanUpAfterInterruptionSpec.hs
@@ -1,238 +0,0 @@-module Hasql.Comms.Session.CleanUpAfterInterruptionSpec (spec) where--import Hasql.Comms.Session qualified as Session-import Hasql.Platform.Prelude-import Pqi qualified as Pq-import Pqi.Ffi qualified-import Test.Hspec-import TextBuilder qualified--spec :: SpecWith (Text, Word16)-spec = do-  describe "cleanUpAfterInterruption" do-    it "cleans up when in pipeline mode" \config -> do-      withConnection config \connection -> do-        -- Enter pipeline mode-        success <- Pq.enterPipelineMode connection-        success `shouldBe` True--        -- Verify we're in pipeline mode-        status <- Pq.pipelineStatus connection-        status `shouldBe` Pq.PipelineOn--        -- Run cleanup-        result <- Session.toHandler Session.cleanUpAfterInterruption connection-        result `shouldBe` Right ()--        -- Verify we're out of pipeline mode-        status <- Pq.pipelineStatus connection-        status `shouldBe` Pq.PipelineOff--    it "cleans up when the pipeline is aborted with no pending transaction or sync" \config -> do-      withConnection config \connection -> do-        success <- Pq.enterPipelineMode connection-        success `shouldBe` True--        sent <- Pq.sendQueryParams connection "SELECT * FROM nonexistent_table" [] Pq.Text-        sent `shouldBe` True-        flushRequestSent <- Pq.sendFlushRequest connection-        flushRequestSent `shouldBe` True-        flushStatus <- Pq.flush connection-        flushStatus `shouldBe` Pq.FlushOk--        let waitForResult attempts = do-              when (attempts <= 0) do-                expectationFailure "Timed out waiting for libpq result after flushing pipeline query"-              consumed <- Pq.consumeInput connection-              consumed `shouldBe` True-              busy <- Pq.isBusy connection-              if busy-                then threadDelay 1000 >> waitForResult (attempts - 1)-                else Pq.getResult connection--        result <- waitForResult (10000 :: Int)-        resultStatus <- traverse Pq.resultStatus result-        resultStatus `shouldBe` Just Pq.FatalError-        pipelineStatus <- Pq.pipelineStatus connection-        pipelineStatus `shouldBe` Pq.PipelineAborted--        cleanupResult <- Session.toHandler Session.cleanUpAfterInterruption connection-        cleanupResult `shouldBe` Right ()-        finalPipelineStatus <- Pq.pipelineStatus connection-        finalPipelineStatus `shouldBe` Pq.PipelineOff--    -- Deterministic counterpart to the timing-based reproduction in-    -- "Sharing.Connection.Use.PipelineAbortedInterruptionCleanupSpec": instead of-    -- racing an async exception into the narrow window during which libpq's-    -- pipeline is in the aborted state, we put the connection into that state-    -- directly and invoke the cleanup that an interruption would have-    -- invoked. This exercises the `leavePipeline` branch that used to only-    -- handle `PipelineOn`, leaving an aborted pipeline to fall through to-    -- `bringTransactionStatusToIdle`, which then tried to send "ABORT" as a-    -- serial command while still in pipeline mode.-    it "cleans up when the pipeline is aborted" \config -> do-      withConnection config \connection -> do-        -- Open a transaction, so that the failing statement below leaves the-        -- connection in the error transaction status -- the status that makes-        -- `bringTransactionStatusToIdle` want to send "ABORT" as a serial-        -- command, which libpq refuses while pipeline mode is still on-        _ <- Pq.exec connection "BEGIN"--        -- Enter pipeline mode-        success <- Pq.enterPipelineMode connection-        success `shouldBe` True--        -- Queue a statement that is guaranteed to fail on the server,-        -- followed by another one. The trailing statement matters: it makes-        -- the abort survive the drains that `cleanUpAfterInterruption`-        -- performs before reaching `leavePipeline`, since `drainResults`-        -- stops at each command boundary-        success <- Pq.sendQueryParams connection "select 1/0" [] Pq.Text-        success `shouldBe` True--        success <- Pq.sendQueryParams connection "select 1" [] Pq.Text-        success `shouldBe` True--        -- Flush the queued statements to the server-        success <- Pq.pipelineSync connection-        success `shouldBe` True--        -- Consume results until libpq registers the error and flips the-        -- pipeline into the aborted state, leaving the trailing sync marker-        -- undrained -- exactly the state an interruption would leave behind-        consumeUntilPipelineAborted connection--        -- Run cleanup-        result <- Session.toHandler Session.cleanUpAfterInterruption connection-        result `shouldBe` Right ()--        -- Verify we're out of pipeline mode and usable again-        status <- Pq.pipelineStatus connection-        status `shouldBe` Pq.PipelineOff--        transStatus <- Pq.transactionStatus connection-        transStatus `shouldBe` Pq.TransIdle--    it "cleans up when in an open transaction" \config -> do-      withConnection config \connection -> do-        -- Start a transaction-        _ <- Pq.exec connection "BEGIN"--        -- Verify we're in a transaction-        transStatus <- Pq.transactionStatus connection-        transStatus `shouldBe` Pq.TransInTrans--        -- Run cleanup-        result <- Session.toHandler Session.cleanUpAfterInterruption connection-        result `shouldBe` Right ()--        -- Verify transaction was aborted (idle state)-        transStatus <- Pq.transactionStatus connection-        transStatus `shouldBe` Pq.TransIdle--    it "cleans up when in error state within transaction" \config -> do-      withConnection config \connection -> do-        -- Start a transaction-        _ <- Pq.exec connection "BEGIN"--        -- Cause an error-        _ <- Pq.exec connection "SELECT * FROM nonexistent_table"--        -- Verify we're in error state-        transStatus <- Pq.transactionStatus connection-        transStatus `shouldBe` Pq.TransInError--        -- Run cleanup-        result <- Session.toHandler Session.cleanUpAfterInterruption connection-        result `shouldBe` Right ()--        -- Verify transaction was aborted (idle state)-        transStatus <- Pq.transactionStatus connection-        transStatus `shouldBe` Pq.TransIdle--    it "cleans up with pending results" \config -> do-      withConnection config \connection -> do-        -- Send a query without retrieving results-        success <- Pq.sendQuery connection "SELECT 1"-        success `shouldBe` True--        -- Run cleanup (should drain results)-        result <- Session.toHandler Session.cleanUpAfterInterruption connection-        result `shouldBe` Right ()--        -- Verify connection is in idle state-        transStatus <- Pq.transactionStatus connection-        transStatus `shouldBe` Pq.TransIdle--    it "cleans up with prepared statements" \config -> do-      withConnection config \connection -> do-        -- Create a prepared statement-        mResult <- Pq.prepare connection "test_stmt" "SELECT $1::int" Nothing-        case mResult of-          Just _ -> pure ()-          Nothing -> expectationFailure "Expected result from prepare"--        -- Consume any remaining results-        _ <- Pq.getResult connection--        -- Verify the prepared statement exists by using it-        _ <- Pq.execPrepared connection "test_stmt" [Just ("42", Pq.Text)] Pq.Text--        -- Run cleanup (should deallocate all statements)-        cleanupResult <- Session.toHandler Session.cleanUpAfterInterruption connection-        cleanupResult `shouldBe` Right ()--        -- Try to execute the prepared statement - it should fail now-        mResult2 <- Pq.execPrepared connection "test_stmt" [Just ("42", Pq.Text)] Pq.Text-        case mResult2 of-          Just result -> do-            status <- Pq.resultStatus result-            -- Should get an error status because the statement was deallocated-            status `shouldBe` Pq.FatalError-          Nothing -> expectationFailure "Expected error result from exec prepared after deallocation"---- * Helpers---- | Pull results from a pipelined connection until libpq reports the pipeline--- as aborted, failing the example if that never happens.-consumeUntilPipelineAborted :: Pq.Connection -> IO ()-consumeUntilPipelineAborted connection =-  go (10 :: Int)-  where-    go attemptsLeft = do-      status <- Pq.pipelineStatus connection-      case status of-        Pq.PipelineAborted -> pure ()-        _-          | attemptsLeft <= 0 ->-              expectationFailure-                ("Pipeline did not reach the aborted state. Last status: " <> show status)-          | otherwise -> do-              _ <- Pq.getResult connection-              go (pred attemptsLeft)--withConnection :: (Text, Word16) -> (Pq.Connection -> IO a) -> IO a-withConnection (host, port) action =-  let connectionString =-        (encodeUtf8 . TextBuilder.toText . mconcat)-          [ "host=",-            TextBuilder.text host,-            " port=",-            TextBuilder.decimal port,-            " user=postgres",-            " password=postgres",-            " dbname=postgres"-          ]-   in bracket-        (Pq.connectdb Pqi.Ffi.adapter connectionString)-        ( \connection -> do-            Pq.finish connection-        )-        ( \connection -> do-            status <- Pq.status connection-            case status of-              Pq.ConnectionOk -> action connection-              _ -> do-                errorMessage <- Pq.errorMessage connection-                fail ("Connection failed: " <> show errorMessage)-        )
− src/comms-tests/Hasql/Comms/SpecHook.hs
@@ -1,25 +0,0 @@--- Docs: https://hspec.github.io/hspec-discover.html-module Hasql.Comms.SpecHook where--import Hasql.Platform.Prelude-import Test.Hspec-import TestcontainersPostgresql qualified--type HookedSpec = SpecWith (Text, Word16)--hook :: HookedSpec -> Spec-hook hookedSpec = parallel do-  byDistro "postgres:9"-  byDistro "postgres:18"-  where-    byDistro tagName =-      describe (toList tagName) do-        aroundAll-          ( TestcontainersPostgresql.run-              TestcontainersPostgresql.Config-                { tagName,-                  auth = TestcontainersPostgresql.CredentialsAuth "postgres" "postgres",-                  forwardLogs = False-                }-          )-          (parallel hookedSpec)
− src/comms-tests/Main.hs
@@ -1,1 +0,0 @@-{-# OPTIONS_GHC -F -pgmF hspec-discover #-}
src/comms/Hasql/Comms/Recv.hs view
@@ -11,11 +11,15 @@ import Hasql.Platform.Prelude import Pqi qualified as Pq -newtype Recv context a-  = Recv (Pq.Connection -> IO (Either (Error context) a))+-- | An action that receives and decodes results from a connection.+--+-- The @tag@ type parameter is a value attached at construction,+-- which the error carries if receiving or decoding fails.+newtype Recv tag a+  = Recv (Pq.Connection -> IO (Either (Error tag) a))   deriving stock (Functor) -instance Applicative (Recv context) where+instance Applicative (Recv tag) where   {-# INLINE pure #-}   pure x = Recv \_ -> pure (Right x)   {-# INLINE (<*>) #-}@@ -29,28 +33,47 @@   {-# INLINE bimap #-}   bimap f g (Recv recv) = Recv (fmap (bimap (fmap f) g) . recv) -toHandler :: Recv context a -> Pq.Connection -> IO (Either (Error context) a)+toHandler :: Recv tag a -> Pq.Connection -> IO (Either (Error tag) a) toHandler (Recv recv) = recv  -- | Exactly one result.-singleResult :: context -> ResultDecoder.ResultDecoder a -> Recv context a-singleResult context handler = Recv \connection -> runExceptT do+singleResult :: tag -> ResultDecoder.ResultDecoder a -> Recv tag a+singleResult tag handler = Recv \connection -> runExceptT do   result <- ExceptT do     result <- Pq.getResult connection     case result of       Nothing -> do         errorMessage <- Pq.errorMessage connection-        pure (Left (NoResultsError context errorMessage))+        status <- Pq.status connection+        pure (Left (NoResultsError tag (status == Pq.ConnectionBad) errorMessage))       Just result -> pure (Right result)   ExceptT do     result <- Pq.getResult connection     case result of-      Nothing -> pure (Right result)-      Just _ -> pure (Left (TooManyResultsError context 1))+      Nothing -> do+        status <- Pq.status connection+        if status == Pq.ConnectionBad+          then do+            errorMessage <- Pq.errorMessage connection+            pure (Left (NoResultsError tag True errorMessage))+          else pure (Right result)+      Just _ -> do+        -- Unreachable today: 'singleResult' backs 'queryParams' and+        -- 'queryPrepared', which go through the extended protocol where+        -- Postgres rejects multi-statement SQL outright. Draining anyway+        -- keeps this branch correct on its own terms rather than relying on+        -- that non-local argument to hold forever.+        drainRemaining connection+        pure (Left (TooManyResultsError tag 1))   result <- ExceptT do     result <- ResultDecoder.toHandler handler result-    pure (first (ResultError context 0) result)+    pure (first (ResultError tag 0) result)   pure result+  where+    drainRemaining connection =+      Pq.getResult connection >>= \case+        Nothing -> pure ()+        Just _ -> drainRemaining connection  -- | Consume all results from a multi-statement query (e.g., scripts). -- Each result is decoded using the provided handler.@@ -58,18 +81,24 @@ -- where each statement produces a result that needs to be validated. -- All results are consumed even if an error occurs, to leave the connection -- in a clean state.-allResults :: context -> ResultDecoder.ResultDecoder a -> Recv context ()-allResults context handler = Recv \connection -> do+allResults :: tag -> ResultDecoder.ResultDecoder a -> Recv tag ()+allResults tag handler = Recv \connection -> do   let loop resultIndex maybeError = do         result <- Pq.getResult connection         case result of-          Nothing -> pure maybeError+          Nothing -> do+            status <- Pq.status connection+            if status == Pq.ConnectionBad+              then do+                errorMessage <- Pq.errorMessage connection+                pure (Just (NoResultsError tag True errorMessage))+              else pure maybeError           Just result -> do             decodedResult <- ResultDecoder.toHandler handler result             case decodedResult of               Left err ->                 -- Continue consuming results even after error to clean up connection-                loop (resultIndex + 1) (Just (ResultError context resultIndex err))+                loop (resultIndex + 1) (Just (ResultError tag resultIndex err))               Right _ ->                 loop (resultIndex + 1) maybeError   errorOrUnit <- loop 0 Nothing@@ -77,19 +106,32 @@  -- * Errors -data Error context+-- | Error of receiving results, carrying the tag of the action that caused it.+data Error tag   = ResultError-      context+      tag       -- | Offset of the result in the series.       Int       -- | Underlying error.       ResultDecoder.Error   | NoResultsError-      context+      tag+      -- | Whether @PQstatus@ reported the connection as bad when the results+      -- failed to arrive.+      --+      -- 'True' means the socket is gone: the results are not late, they are+      -- never coming, and the connection has to be replaced. 'False' means+      -- the connection is intact and the server genuinely produced nothing+      -- where a result was expected.+      --+      -- The send side reports the same distinction (see+      -- 'Hasql.Comms.Roundtrip.ClientError'); without it here a dropped+      -- socket is indistinguishable from a statement that returned no rows.+      Bool       -- | Details about the error. Possibly empty.       (Maybe ByteString)   | TooManyResultsError-      context+      tag       -- | Expected count.       Int   deriving stock (Show, Eq, Functor)@@ -97,12 +139,12 @@ instance Comonad Error where   {-# INLINE extract #-}   extract = \case-    ResultError context _ _ -> context-    NoResultsError context _ -> context-    TooManyResultsError context _ -> context+    ResultError tag _ _ -> tag+    NoResultsError tag _ _ -> tag+    TooManyResultsError tag _ -> tag    {-# INLINE duplicate #-}   duplicate e = case e of     ResultError _ resultIndex resultError -> ResultError e resultIndex resultError-    NoResultsError _ details -> NoResultsError e details+    NoResultsError _ connectionLost details -> NoResultsError e connectionLost details     TooManyResultsError _ expectedCount -> TooManyResultsError e expectedCount
src/comms/Hasql/Comms/ResultDecoder.hs view
@@ -34,8 +34,8 @@  import Data.Attoparsec.ByteString.Char8 qualified as Attoparsec import Data.ByteString qualified as ByteString-import Data.Vector qualified as Vector-import Data.Vector.Mutable qualified as MutableVector+import Data.Vector.Generic qualified as GenericVector+import Data.Vector.Generic.Mutable qualified as GenericMutableVector import Hasql.Comms.RowDecoder qualified as RowDecoder import Hasql.Platform.Prelude hiding (foldl, foldr, maybe) import Hasql.Platform.Prelude qualified as Prelude@@ -215,7 +215,7 @@           _ -> return (Left (UnexpectedRowCount (fromIntegral maxRows)))  {-# INLINE vector #-}-vector :: RowDecoder.RowDecoder a -> ResultDecoder (Vector a)+vector :: (GenericVector.Vector vector a) => RowDecoder.RowDecoder a -> ResultDecoder (vector a) vector rowDec =   do     checkExecStatus [Pq.TuplesOk]@@ -223,15 +223,15 @@     ResultDecoder       $ \result -> do         maxRows <- Pq.ntuples result-        mvector <- MutableVector.unsafeNew (fromIntegral maxRows)+        mvector <- GenericMutableVector.unsafeNew (fromIntegral maxRows)         failureRef <- newIORef Nothing         forMFromZero_ (fromIntegral maxRows) $ \rowIndex -> do           rowResult <- RowDecoder.toDecoder rowDec result (fromIntegral rowIndex)           case rowResult of             Left !err -> writeIORef failureRef (Just (RowError rowIndex err))-            Right !x -> MutableVector.unsafeWrite mvector rowIndex x+            Right !x -> GenericMutableVector.unsafeWrite mvector rowIndex x         readIORef failureRef >>= \case-          Nothing -> Right <$> Vector.unsafeFreeze mvector+          Nothing -> Right <$> GenericVector.unsafeFreeze mvector           Just x -> pure (Left x)  {-# INLINE foldl #-}
src/comms/Hasql/Comms/Roundtrip.hs view
@@ -1,17 +1,18 @@ module Hasql.Comms.Roundtrip   ( Roundtrip,-    toPipelineIO,-    toSerialIO,      -- * Constructors     prepare,     queryPrepared,     queryParams,-    query,     script,      -- * Errors     Error (..),++    -- * Execution+    toPipelineIO,+    toSerialIO,   ) where @@ -21,11 +22,15 @@ import Hasql.Platform.Prelude import Pqi qualified as Pq -data Roundtrip context a-  = Roundtrip (Send.Send context) (Recv.Recv context a)+-- | A send action paired with the matching receive action, forming a single protocol round trip.+--+-- The @tag@ type parameter is a value attached at construction,+-- which the error carries if the round trip fails.+data Roundtrip tag a+  = Roundtrip (Send.Send tag) (Recv.Recv tag a)   deriving stock (Functor) -instance Applicative (Roundtrip context) where+instance Applicative (Roundtrip tag) where   {-# INLINE pure #-}   pure x = Roundtrip mempty (pure x)   {-# INLINE (<*>) #-}@@ -39,45 +44,14 @@       (fmap f send)       (bimap f g recv) -toPipelineIO :: Roundtrip context a -> context -> Pq.Connection -> IO (Either (Error context) a)-toPipelineIO sendAndRecv context connection = mask \restore -> do-  sendResult <- Send.toHandler (Send.enterPipelineMode context <> send) connection-  case sendResult of-    Send.Error context details -> pure (Left (ClientError context details))-    Send.Ok -> do-      recvResult <- first ServerError <$> restore (Recv.toHandler recv connection)-      exitResult <- do-        result <- Send.toHandler (Send.exitPipelineMode context) connection-        case result of-          Send.Error context details -> pure (Left (ClientError context details))-          Send.Ok -> pure (Right ())-      pure (recvResult <* exitResult)-  where-    Roundtrip send recv = sendAndRecv <* pipelineSync context--toSerialIO :: Roundtrip context a -> Pq.Connection -> IO (Either (Error context) a)-toSerialIO (Roundtrip send recv) connection = do-  sendResult <- Send.toHandler send connection-  case sendResult of-    Send.Error context details -> pure (Left (ClientError context details))-    Send.Ok -> do-      recvResult <- Recv.toHandler recv connection-      pure (first ServerError recvResult)--pipelineSync :: context -> Roundtrip context ()-pipelineSync context =-  Roundtrip-    (Send.pipelineSync context)-    (Recv.singleResult context ResultDecoder.pipelineSync)--prepare :: context -> ByteString -> ByteString -> [Word32] -> Roundtrip context ()-prepare context statementName sql oidList =+prepare :: tag -> ByteString -> ByteString -> [Word32] -> Roundtrip tag ()+prepare tag statementName sql oidList =   Roundtrip-    (Send.prepare context statementName sql (Just oidList))-    (Recv.singleResult context ResultDecoder.ok)+    (Send.prepare tag statementName sql (Just oidList))+    (Recv.singleResult tag ResultDecoder.ok)  queryPrepared ::-  context ->+  tag ->   -- | Prepared statement name.   ByteString ->   -- | Parameters.@@ -86,14 +60,14 @@   Pq.Format ->   -- | Result decoder.   ResultDecoder.ResultDecoder a ->-  Roundtrip context a-queryPrepared context statementName params resultFormat resultDecoder =+  Roundtrip tag a+queryPrepared tag statementName params resultFormat resultDecoder =   Roundtrip-    (Send.queryPrepared context statementName params resultFormat)-    (Recv.singleResult context resultDecoder)+    (Send.queryPrepared tag statementName params resultFormat)+    (Recv.singleResult tag resultDecoder)  queryParams ::-  context ->+  tag ->   -- | SQL.   ByteString ->   -- | Parameters.@@ -102,39 +76,104 @@   Pq.Format ->   -- | Result decoder.   ResultDecoder.ResultDecoder a ->-  Roundtrip context a-queryParams context sql params resultFormat resultDecoder =-  Roundtrip-    (Send.queryParams context sql params resultFormat)-    (Recv.singleResult context resultDecoder)--query :: context -> ByteString -> Roundtrip context ()-query context sql =+  Roundtrip tag a+queryParams tag sql params resultFormat resultDecoder =   Roundtrip-    (Send.query context sql)-    (Recv.singleResult context ResultDecoder.ok)+    (Send.queryParams tag sql params resultFormat)+    (Recv.singleResult tag resultDecoder)  -- | Execute a script (multi-statement SQL).--- Unlike 'query', this consumes all results from the execution,+-- It consumes all results from the execution, -- which is necessary for scripts containing multiple statements.-script :: context -> ByteString -> Roundtrip context ()-script context sql =+script :: tag -> ByteString -> Roundtrip tag ()+script tag sql =   Roundtrip-    (Send.query context sql)-    (Recv.allResults context ResultDecoder.ok)+    (Send.query tag sql)+    (Recv.allResults tag ResultDecoder.ok) -data Error context-  = ClientError context (Maybe ByteString)-  | ServerError (Recv.Error context)+-- | Error of a round trip, carrying the tag of the action that caused it.+--+-- A 'ClientError' means the send itself failed - either nothing reached the+-- server and nothing will until the connection is replaced, or the+-- connection is still usable but libpq refused the request outright (e.g.+-- more than 65535 parameters, or a command issued while another is in+-- progress). Both finish the connection the same way (see+-- 'Hasql.Engine.Errors.fromSendError'), so this carries no further+-- distinction between them.+data Error tag+  = ClientError+      tag+      Text+  | ServerError (Recv.Error tag)   deriving stock (Show, Eq, Functor)  instance Comonad Error where   {-# INLINE extract #-}   extract = \case-    ClientError context _ -> context+    ClientError tag _ -> tag     ServerError recvError -> extract recvError    {-# INLINE duplicate #-}   duplicate = \case     clientError@(ClientError _ details) -> ClientError clientError details     ServerError recvError -> ServerError (fmap ServerError (duplicate recvError))++-- | Run a round trip in pipeline mode, entering the mode and leaving it+-- again before returning.+--+-- The exit is attempted whether or not the receive succeeded, because a+-- failing receive still leaves the mode on and the connection unusable for+-- serial commands. It is viable on that path because 'Recv' does not+-- short-circuit: its 'Applicative' runs every step, so the results of every+-- dispatched command are consumed even when one of them decodes into an+-- error, and the queue libpq requires empty before it permits the exit is+-- empty by the time we ask.+--+-- A failed /send/ is the one case with no exit attempt, and deliberately so.+-- It strands commands that earlier callers in the same batch queued but+-- never flushed, and no amount of draining makes that connection's protocol+-- state something we can vouch for. Such a connection is finished by+-- 'Hasql.Connection.use' rather than repaired: both errors a send failure+-- can produce say so (see 'ClientError'), and pushing a Sync to salvage it+-- would flush and commit the very commands the caller's pipeline never got+-- to complete.+--+-- Of the two errors an unhappy path can carry, the exit failure wins. It is+-- both the rarer and the graver: a mode that cannot be left means the+-- connection serves nothing serial from then on, whereas the failure that got+-- us here is quite possibly an ordinary server error the caller is meant to+-- catch and carry on from. Reporting the latter would return a+-- 'Hasql.Engine.Errors.SessionUseError' - catchable, connection retained -+-- and hand it back still in pipeline mode, which is+-- <https://github.com/nikita-volkov/hasql/issues/326> over again.+toPipelineIO :: Roundtrip tag a -> tag -> Pq.Connection -> IO (Either (Error tag) a)+toPipelineIO (Roundtrip send recv) tag connection = runExceptT do+  ExceptT (runSend (Send.enterPipelineMode tag <> send <> Send.pipelineSync tag) connection)+  recvResult <- lift (first ServerError <$> Recv.toHandler (recv <* Recv.singleResult tag ResultDecoder.pipelineSync) connection)+  exitResult <- lift (runSend (Send.exitPipelineMode tag) connection)+  ExceptT (pure (exitResult *> recvResult))++-- | Unlike 'toPipelineIO', this never enters pipeline mode, so there is no+-- mode to leave: every call site sends a single operation and there is+-- nothing queued after it.+toSerialIO :: Roundtrip tag a -> Pq.Connection -> IO (Either (Error tag) a)+toSerialIO (Roundtrip send recv) connection = do+  sendResult <- runSend send connection+  case sendResult of+    Left err -> pure (Left err)+    Right () -> do+      recvResult <- Recv.toHandler recv connection+      pure (first ServerError recvResult)++-- | Execute a send action on a connection, turning a failed send into an 'Error',+-- which consults the connection for the diagnostic details+-- (the send result itself no longer carries them).+runSend :: Send.Send tag -> Pq.Connection -> IO (Either (Error tag) ())+runSend send connection = do+  sendResult <- Send.toHandler send connection+  case sendResult of+    Right () -> pure (Right ())+    Left tag -> do+      errorMessage <- Pq.errorMessage connection+      let message = maybe "" decodeUtf8Lenient errorMessage+      pure (Left (ClientError tag message))
src/comms/Hasql/Comms/RowReader.hs view
@@ -1,4 +1,19 @@ -- | Lower level context focused on just the actual decoding of values. No metadata involved.+--+-- The reader is in continuation-passing style rather than a+-- @StateT \/ ReaderT \/ ExceptT@ stack. The stack is the more readable+-- formulation, but its 'Applicative' allocates for every column of every row:+-- @StateT@'s bind returns a @(value, columnIndex)@ pair and @ExceptT@'s wraps+-- that pair in an 'Either', so a three-column row decoder built with @<*>@+-- allocates three pairs, three 'Either's and the partial applications of the+-- constructor being filled -- all of it dead the instant the row is consumed.+--+-- In CPS there is nothing to allocate: the column index is an argument rather+-- than state threaded through a pair, and failure is a continuation rather than+-- an 'Either' to inspect. With the 'Functor' \/ 'Applicative' methods inlined, a+-- decoder whose shape is known at its definition site collapses into+-- straight-line code that reads each column and hands the finished value to the+-- success continuation. module Hasql.Comms.RowReader   ( RowReader,     nullableColumn,@@ -32,62 +47,95 @@   | UnexpectedNullCellError   deriving stock (Eq, Show) +-- | Decoder of one row, as a function awaiting its continuations.+--+-- The success continuation takes the index of the next unread column along with+-- the decoded value, which is what replaces the state in the transformer+-- formulation. newtype RowReader a-  = RowReader (StateT Int32 (ReaderT Env (ExceptT Error IO)) a)-  deriving-    (Functor, Applicative)-    via (StateT Int32 (ReaderT Env (ExceptT Error IO)))--data Env-  = Env-      Pq.Result-      Int32+  = RowReader+      ( forall r.+        Pq.Result ->+        -- Row index.+        Int32 ->+        -- Index of the next column to read.+        Int32 ->+        -- Failure.+        (Error -> IO r) ->+        -- Success, given the next unread column and the value.+        (Int32 -> a -> IO r) ->+        IO r+      )  -- * Instances +instance Functor RowReader where+  {-# INLINE fmap #-}+  fmap fn (RowReader run) =+    RowReader \result row col onError onSuccess ->+      run result row col onError \col' a -> onSuccess col' (fn a)++instance Applicative RowReader where+  {-# INLINE pure #-}+  pure a =+    RowReader \_result _row col _onError onSuccess -> onSuccess col a+  {-# INLINE (<*>) #-}+  RowReader runFn <*> RowReader runArg =+    RowReader \result row col onError onSuccess ->+      runFn result row col onError \col' fn ->+        runArg result row col' onError \col'' a ->+          onSuccess col'' (fn a)+ instance Filterable RowReader where   {-# INLINE mapMaybe #-}   mapMaybe fn (RowReader run) =-    RowReader do-      result <- run-      case fn result of-        Just refined -> pure refined-        Nothing -> throwError (RefinementError "Filtration failed")+    RowReader \result row col onError onSuccess ->+      run result row col onError \col' a ->+        case fn a of+          Just refined -> onSuccess col' refined+          Nothing -> onError (RefinementError "Filtration failed")  -- * Functions +-- |+-- Run the reader over one row, collecting the outcome into an 'Either'.+--+-- Kept for callers that want the row as a value. The one in the hot path+-- (@ResultDecoder.vector@) uses the 'RowReader' directly instead, so that the+-- decoded row is handed straight to its consumer without an 'Either' in+-- between. {-# INLINE toHandler #-} toHandler :: RowReader a -> Pq.Result -> Int32 -> IO (Either Error a)-toHandler (RowReader f) result row =-  let env = Env result row-   in runExceptT (runReaderT (evalStateT f 0) env)+toHandler (RowReader run) result row =+  run result row 0 (pure . Left) (\_col a -> pure (Right a))  -- | -- Next value, decoded using the provided value decoder. {-# INLINE column #-} column :: (Maybe a -> Maybe b) -> (ByteString -> Either Text a) -> RowReader b-column processNullable valueDec = RowReader do-  col <- get-  Env result row <- ask-  let colInt = fromIntegral col-  put (succ col)--  valueMaybe <- liftIO ({-# SCC "getvalue'" #-} Pq.getvalue' result row col)+column processNullable valueDec =+  RowReader \result row col onError onSuccess ->+    let colInt = fromIntegral col+        col' = succ col -  valueMaybe <- case valueMaybe of-    Nothing -> pure Nothing-    Just v ->-      case {-# SCC "decode" #-} valueDec v of-        Left err -> do-          oid <- liftIO (Pq.ftype result col)-          throwError (CellError colInt oid (DecodingCellError err))-        Right decoded -> pure (Just decoded)+        unexpectedNull = do+          oid <- Pq.ftype result col+          onError (CellError colInt oid UnexpectedNullCellError) -  case processNullable valueMaybe of-    Nothing -> do-      oid <- liftIO (Pq.ftype result col)-      throwError (CellError colInt oid UnexpectedNullCellError)-    Just decoded -> pure decoded+        emit valueMaybe =+          case processNullable valueMaybe of+            Just decoded -> onSuccess col' decoded+            Nothing -> unexpectedNull+     in do+          valueMaybe <- {-# SCC "getvalue'" #-} Pq.getvalue' result row col+          case valueMaybe of+            Nothing -> emit Nothing+            Just v ->+              case {-# SCC "decode" #-} valueDec v of+                Left err -> do+                  oid <- Pq.ftype result col+                  onError (CellError colInt oid (DecodingCellError err))+                Right decoded -> emit (Just decoded)  -- | -- Next value, decoded using the provided value decoder.
src/comms/Hasql/Comms/Send.hs view
@@ -1,67 +1,78 @@-module Hasql.Comms.Send where+module Hasql.Comms.Send+  ( Send, +    -- * Execution+    toHandler,++    -- * Constructors+    prepare,+    query,+    queryPrepared,+    queryParams,+    pipelineSync,+    enterPipelineMode,+    exitPipelineMode,+  )+where+ import Hasql.Platform.Prelude import Pqi qualified as Pq -data Result context-  = Ok-  | Error context (Maybe ByteString)-  deriving stock (Eq, Show, Functor)+-- | An action that sends commands to a connection without receiving the results.+--+-- The @err@ type parameter is a value attached to the commands,+-- which the error carries if sending fails.+newtype Send err+  = Send (Pq.Connection -> IO (Either err ())) -newtype Send context-  = Send (Pq.Connection -> IO (Result context))-  deriving stock (Functor)+instance Functor Send where+  {-# INLINE fmap #-}+  fmap f (Send send) = Send \connection -> first f <$> send connection -instance Semigroup (Send context) where+instance Semigroup (Send err) where   {-# INLINE (<>) #-}   Send send1 <> Send send2 = Send \cs -> do     result <- send1 cs     case result of-      Error context details -> pure (Error context details)-      Ok -> do-        result2 <- send2 cs-        pure result2+      Left err -> pure (Left err)+      Right () -> send2 cs -instance Monoid (Send context) where+instance Monoid (Send err) where   {-# INLINE mempty #-}-  mempty = Send \_ -> pure Ok+  mempty = Send \_ -> pure (Right ()) -toHandler :: Send context -> Pq.Connection -> IO (Result context)+toHandler :: Send err -> Pq.Connection -> IO (Either err ()) toHandler (Send send) = send -liftPqSend :: context -> (Pq.Connection -> IO Bool) -> Send context-liftPqSend context pqSend = Send \connection -> do+liftPqSend :: err -> (Pq.Connection -> IO Bool) -> Send err+liftPqSend err pqSend = Send \connection -> do   success <- pqSend connection-  if success-    then pure Ok-    else do-      errorMessage <- Pq.errorMessage connection-      pure (Error context errorMessage)+  pure (if success then Right () else Left err) -prepare :: context -> ByteString -> ByteString -> Maybe [Word32] -> Send context-prepare context statementName sql oidList =-  liftPqSend context \connection -> Pq.sendPrepare connection statementName sql oidList+prepare :: err -> ByteString -> ByteString -> Maybe [Word32] -> Send err+prepare err statementName sql oidList =+  liftPqSend err \connection -> Pq.sendPrepare connection statementName sql oidList -query :: context -> ByteString -> Send context-query context sql =-  liftPqSend context \connection -> Pq.sendQuery connection sql+query :: err -> ByteString -> Send err+query err sql =+  liftPqSend err \connection -> Pq.sendQuery connection sql -queryPrepared :: context -> ByteString -> [Maybe (ByteString, Pq.Format)] -> Pq.Format -> Send context-queryPrepared context statementName params resultFormat =-  liftPqSend context \connection -> Pq.sendQueryPrepared connection statementName params resultFormat+queryPrepared :: err -> ByteString -> [Maybe (ByteString, Pq.Format)] -> Pq.Format -> Send err+queryPrepared err statementName params resultFormat =+  liftPqSend err \connection -> Pq.sendQueryPrepared connection statementName params resultFormat -queryParams :: context -> ByteString -> [Maybe (Word32, ByteString, Pq.Format)] -> Pq.Format -> Send context-queryParams context sql params resultFormat =-  liftPqSend context \connection -> Pq.sendQueryParams connection sql params resultFormat+queryParams :: err -> ByteString -> [Maybe (Word32, ByteString, Pq.Format)] -> Pq.Format -> Send err+queryParams err sql params resultFormat =+  liftPqSend err \connection -> Pq.sendQueryParams connection sql params resultFormat -pipelineSync :: context -> Send context-pipelineSync context =-  liftPqSend context \connection -> Pq.pipelineSync connection+pipelineSync :: err -> Send err+pipelineSync err =+  liftPqSend err \connection -> Pq.pipelineSync connection -enterPipelineMode :: context -> Send context-enterPipelineMode context =-  liftPqSend context \connection -> Pq.enterPipelineMode connection+enterPipelineMode :: err -> Send err+enterPipelineMode err =+  liftPqSend err \connection -> Pq.enterPipelineMode connection -exitPipelineMode :: context -> Send context-exitPipelineMode context =-  liftPqSend context \connection -> Pq.exitPipelineMode connection+exitPipelineMode :: err -> Send err+exitPipelineMode err =+  liftPqSend err \connection -> Pq.exitPipelineMode connection
− src/comms/Hasql/Comms/Session.hs
@@ -1,176 +0,0 @@-module Hasql.Comms.Session-  ( Session,--    -- * Constructors-    cleanUpAfterInterruption,--    -- * Executors-    toHandler,-  )-where--import Hasql.Comms.Roundtrip qualified as Roundtrip-import Hasql.Platform.Prelude-import Pqi qualified as Pq---- | Serial execution of commands in the scope of a connection.-newtype Session a = Session (Pq.Connection -> IO (Either Error a))-  deriving-    (Functor, Applicative, Monad, MonadError Error)-    via (ExceptT Error (ReaderT Pq.Connection IO))--type Error = Text---- * Constructors---- | Bring the connection to a clean state after an interruption.------ This includes:--- - Leaving pipeline mode if we are in it.--- - Bringing the transaction status to idle if we are in a transaction.--- - Deallocating all prepared statements.-cleanUpAfterInterruption :: Session ()-cleanUpAfterInterruption = do-  drainResults-  cancel-  drainResults-  -- Ensure we are out of pipeline mode.-  leavePipeline-  -- Ensure we are in idle transaction state.-  bringTransactionStatusToIdle-  deallocateAllPreparedStatements--bringTransactionStatusToIdle :: Session ()-bringTransactionStatusToIdle = do-  transactionStatus <- getTransactionStatus-  case transactionStatus of-    Pq.TransIdle -> pure ()-    Pq.TransInTrans -> do-      runScript "ABORT"-    Pq.TransActive -> do-      -- A command is still in progress.-      drainResults-      -- Check status again after draining.-      transactionStatus <- getTransactionStatus-      case transactionStatus of-        Pq.TransIdle -> pure ()-        Pq.TransInTrans -> do-          runScript "ABORT"-        Pq.TransActive -> do-          -- If we're still active, there's not much we can do.-          -- The connection is probably in a bad state.-          throwError "Failed to bring transaction status to idle after draining results"-        Pq.TransInError -> do-          runScript "ABORT"-        Pq.TransUnknown -> do-          -- Unknown state (connection issue), there's not much we can do.-          throwError "Transaction status is unknown, connection is corrupted"-    Pq.TransInError -> do-      -- Transaction is in error state, we need to abort it.-      runScript "ABORT"-    Pq.TransUnknown -> do-      -- Unknown state (connection issue), there's not much we can do.-      throwError "Transaction status is unknown, connection is corrupted"--leavePipeline :: Session ()-leavePipeline = do-  pipelineStatus <- getPipelineStatus-  -- PipelineAborted is still pipeline mode. It must reach a sync point before-  -- libpq permits serial queries such as ABORT or DEALLOCATE ALL again.-  when (pipelineStatus /= Pq.PipelineOff) do-    -- In pipeline mode, we need to ensure the pipeline is synchronized before exiting.-    -- Send a pipeline sync marker to flush any pending operations.-    syncSuccess <- sendPipelineSync-    when syncSuccess drainResults-    -- After sync, send a flush to ensure all queued commands are sent to the server.-    flushSuccess <- sendFlushRequest-    when flushSuccess drainResults-    -- Try to exit pipeline mode.-    -- This might fail if there are pending results that need to be consumed.-    success <- exitPipelineMode-    unless success do-      -- If exit failed, drain results and try again.-      drainResults-      success <- exitPipelineMode-      unless success do-        -- If it still fails, there's not much we can do.-        -- The connection is probably in a bad state.-        errorMessage <- getErrorMessage-        let message = case errorMessage of-              Nothing -> "Failed to exit pipeline mode after draining results"-              Just details -> "Failed to exit pipeline mode after draining results: " <> decodeUtf8Lenient details-        throwError message--deallocateAllPreparedStatements :: Session ()-deallocateAllPreparedStatements =-  runScript "DEALLOCATE ALL"--cancel :: Session ()-cancel = Session \connection -> do-  mCancel <- Pq.getCancel connection-  case mCancel of-    Just cancel -> do-      result <- Pq.cancel cancel-      case result of-        Left errorMessage ->-          pure (Left ("Failed to cancel: " <> decodeUtf8Lenient errorMessage))-        Right () ->-          pure (Right ())-    Nothing -> pure (Right ())--getErrorMessage :: Session (Maybe ByteString)-getErrorMessage = Session \connection -> do-  Right <$> Pq.errorMessage connection--getTransactionStatus :: Session Pq.TransactionStatus-getTransactionStatus = Session \connection -> do-  Right <$> Pq.transactionStatus connection--getPipelineStatus :: Session Pq.PipelineStatus-getPipelineStatus = Session \connection -> do-  Right <$> Pq.pipelineStatus connection--exitPipelineMode :: Session Bool-exitPipelineMode = Session \connection -> do-  Right <$> Pq.exitPipelineMode connection--sendPipelineSync :: Session Bool-sendPipelineSync = Session \connection -> do-  Right <$> Pq.pipelineSync connection--sendFlushRequest :: Session Bool-sendFlushRequest = Session \connection -> do-  Right <$> Pq.sendFlushRequest connection---- Drain all pending results from the connection.-drainResults :: Session ()-drainResults = Session \connection ->-  let go = do-        mResult <- Pq.getResult connection-        case mResult of-          Nothing -> pure ()-          Just _ -> go-   in go $> Right ()--runScript :: ByteString -> Session ()-runScript script = runRoundtrip (Roundtrip.query () script)--runRoundtrip :: Roundtrip.Roundtrip () a -> Session a-runRoundtrip roundtrip = Session \connection -> do-  result <- Roundtrip.toSerialIO roundtrip connection-  case result of-    Left err ->-      let message = case err of-            Roundtrip.ClientError () Nothing ->-              "Unknown client error occurred"-            Roundtrip.ClientError () (Just details) ->-              "Client error occurred: " <> decodeUtf8Lenient details-            Roundtrip.ServerError recvError ->-              "Server error occurred: " <> fromString (show recvError)-       in pure (Left message)-    Right value -> pure (Right value)---- * Executors--toHandler :: Session a -> Pq.Connection -> IO (Either Text a)-toHandler (Session run) = run
src/connection-state-tests/Hasql/ConnectionState/StatementCacheSpec.hs view
@@ -1,11 +1,61 @@ module Hasql.ConnectionState.StatementCacheSpec (spec) where +import Data.ByteString qualified as ByteString+import Data.ByteString.Char8 qualified as ByteString.Char8 import Data.Maybe import Hasql.ConnectionState.StatementCache qualified as StatementCache+import Prelude import Test.Hspec  spec :: Spec spec = do+  describe "remote key format" do+    it "is prefixed with \"hasql_\"" do+      let (key, _) = StatementCache.insert "SELECT 1" [] StatementCache.empty+      ByteString.Char8.isPrefixOf "hasql_" key `shouldBe` True++    it "is 63 bytes long" do+      let (key, _) = StatementCache.insert "SELECT 1" [] StatementCache.empty+      ByteString.length key `shouldBe` 63++    it "is deterministic across independent caches" do+      let (key1, _) = StatementCache.insert "SELECT 1" [] StatementCache.empty+          (key2, _) = StatementCache.insert "SELECT 1" [] StatementCache.empty+      key1 `shouldBe` key2++    it "is deterministic for statements with parameter OIDs" do+      let (key1, _) = StatementCache.insert "SELECT $1" [23] StatementCache.empty+          (key2, _) = StatementCache.insert "SELECT $1" [23] StatementCache.empty+      key1 `shouldBe` key2++    it "distinguishes statements by their parameter OIDs" do+      let (key1, _) = StatementCache.insert "SELECT $1" [23] StatementCache.empty+          (key2, _) = StatementCache.insert "SELECT $1" [25] StatementCache.empty+      key1 `shouldNotBe` key2++    it "distinguishes statements by their parameter count" do+      let (key1, _) = StatementCache.insert "SELECT 1" [] StatementCache.empty+          (key2, _) = StatementCache.insert "SELECT 1" [23] StatementCache.empty+      key1 `shouldNotBe` key2++    -- Golden values. The name is what the server sees and what a pooler+    -- tracks statements by, so changing any of it — the serialization, the+    -- digest, the truncation, the prefix — is a wire-visible change that+    -- needs a version bump and a changelog entry. Do not update these to+    -- make a build pass; work out first why the name moved.+    --+    -- Serialization under test: the SQL length as a big-endian Word64, the+    -- SQL, the parameter count as a big-endian Word64, then each OID as a+    -- big-endian Word32. SHA-256 of that, hex, first 57 characters, prefixed+    -- with "hasql_".+    it "matches the golden name for a statement without parameters" do+      let (key, _) = StatementCache.insert "SELECT 1" [] StatementCache.empty+      key `shouldBe` "hasql_5edac06ba8f1fb3b8ad72465f3cffb0adb965e440bcd7712e33606b97"++    it "matches the golden name for a statement with parameters" do+      let (key, _) = StatementCache.insert "SELECT $1" [23] StatementCache.empty+      key `shouldBe` "hasql_7497628d7431d49f8722fb860c35ebdc96c758a01032b58812c38ecaf"+   describe "empty" do     it "returns Nothing on lookup" do       StatementCache.lookup "SELECT 1" [] StatementCache.empty
src/connection-state/Hasql/ConnectionState.hs view
@@ -11,7 +11,6 @@     mapStatementCache,     mapOidCache,     traverseStatementCache,-    resetPreparedStatementsCache,   ) where @@ -92,7 +91,3 @@           }     )     (f statementCache)--resetPreparedStatementsCache :: ConnectionState -> ConnectionState-resetPreparedStatementsCache =-  mapStatementCache (const StatementCache.empty)
src/connection-state/Hasql/ConnectionState/StatementCache.hs view
@@ -1,6 +1,5 @@ module Hasql.ConnectionState.StatementCache-  ( -- * Pure registry operations-    StatementCache,+  ( StatementCache,     empty,     lookup,     insert,@@ -8,40 +7,51 @@   ) where +import ByteString.StrictBuilder qualified+import Crypto.Hash.SHA256 qualified+import Data.ByteString qualified as ByteString+import Data.ByteString.Base16 qualified as Base16 import Data.HashMap.Strict qualified as HashMap import Hasql.Platform.Prelude hiding (empty, insert, lookup, reset) --- | Pure registry state containing the hash map and counter-data StatementCache = StatementCache (HashMap LocalKey ByteString) Word+-- | Pure registry state mapping local statement keys to their deterministic remote names+newtype StatementCache = StatementCache (HashMap LocalKey ByteString)   deriving stock (Show, Eq)  -- | Create an empty registry state {-# INLINEABLE empty #-} empty :: StatementCache-empty = StatementCache HashMap.empty 0+empty = StatementCache HashMap.empty  -- | Pure lookup operation {-# INLINEABLE lookup #-} lookup :: ByteString -> [Word32] -> StatementCache -> Maybe ByteString-lookup sql oids (StatementCache hashMap _) = HashMap.lookup localKey hashMap-  where-    localKey = LocalKey sql oids+lookup sql oids (StatementCache hashMap) = HashMap.lookup (LocalKey sql oids) hashMap  -- | Pure insert operation that returns new state and the generated remote key {-# INLINEABLE insert #-} insert :: ByteString -> [Word32] -> StatementCache -> (ByteString, StatementCache)-insert sql oids (StatementCache hashMap counter) = (remoteKey, newState)+insert sql oids (StatementCache hashMap) = (remoteKey, newState)   where-    remoteKey = fromString $ show $ newCounter-    newHashMap = HashMap.insert localKey remoteKey hashMap-    newCounter = counter + 1-    newState = StatementCache newHashMap newCounter     localKey = LocalKey sql oids+    remoteKey =+      "hasql_" <> ByteString.take 57 (Base16.encode (Crypto.Hash.SHA256.hash hashInput))+      where+        hashInput =+          ByteString.StrictBuilder.builderBytes+            ( mconcat+                [ ByteString.StrictBuilder.word64BE (fromIntegral (ByteString.length sql)),+                  ByteString.StrictBuilder.bytes sql,+                  ByteString.StrictBuilder.word64BE (fromIntegral (length oids)),+                  foldMap ByteString.StrictBuilder.word32BE oids+                ]+            )+    newState = StatementCache (HashMap.insert localKey remoteKey hashMap)  -- | Pure reset operation {-# INLINEABLE reset #-} reset :: StatementCache -> StatementCache-reset _ = StatementCache HashMap.empty 0+reset _ = StatementCache HashMap.empty  -- | -- Local statement key.
src/library-tests/Helpers/Adapters.hs view
@@ -1,7 +1,5 @@ module Helpers.Adapters-  ( adapters,-    byAdapter,-    hook,+  ( hook,   ) where @@ -22,7 +20,8 @@ byAdapter :: (Pqi.Adapter -> Spec) -> Spec byAdapter f =   for_ adapters \adapter ->-    describe (toList (Pqi.name adapter)) (f adapter)+    describe (toList (Pqi.name adapter)) do+      f adapter  hook :: SpecWith Pqi.Adapter -> Spec hook hookedSpec =
+ src/library-tests/Helpers/PostgresContainer.hs view
@@ -0,0 +1,33 @@+module Helpers.PostgresContainer (run) where++import Control.Exception qualified as Exception+import Data.Text qualified as Text+import Prelude+import TestContainers qualified as Docker+import TestcontainersPostgresql qualified++-- |+-- Like 'TestcontainersPostgresql.run', but retries container startup a few+-- times when Docker fails to bind the automatically assigned host port.+--+-- Docker picks the host port at container creation but only reserves it at+-- container start, so when multiple containers get created around the same+-- time (as happens across our isolated tests), two of them can race for the+-- same port and fail with \"address already in use\". Retrying with a fresh+-- container sidesteps the race.+run :: TestcontainersPostgresql.Config -> ((Text, Word16) -> IO ()) -> IO ()+run config action =+  go (3 :: Int)+  where+    go retriesLeft =+      Exception.catch+        (TestcontainersPostgresql.run config action)+        \exception ->+          if retriesLeft > 0 && isPortConflict exception+            then go (retriesLeft - 1)+            else Exception.throwIO exception++    isPortConflict = \case+      Docker.DockerException {stderr} ->+        "address already in use" `Text.isInfixOf` stderr+      _ -> False
src/library-tests/Helpers/Statements.hs view
@@ -4,9 +4,11 @@     module Helpers.Statements.CurrentSetting,     module Helpers.Statements.GenerateSeries,     module Helpers.Statements.SelectOne,+    module Helpers.Statements.SelectPreparedStatementNames,     module Helpers.Statements.SelectProvidedInt8,     module Helpers.Statements.SetConfig,     module Helpers.Statements.Sleep,+    module Helpers.Statements.TooManyParams,     module Helpers.Statements.WrongDecoder,   ) where@@ -16,7 +18,9 @@ import Helpers.Statements.CurrentSetting import Helpers.Statements.GenerateSeries import Helpers.Statements.SelectOne+import Helpers.Statements.SelectPreparedStatementNames import Helpers.Statements.SelectProvidedInt8 import Helpers.Statements.SetConfig import Helpers.Statements.Sleep+import Helpers.Statements.TooManyParams import Helpers.Statements.WrongDecoder
+ src/library-tests/Helpers/Statements/SelectPreparedStatementNames.hs view
@@ -0,0 +1,17 @@+module Helpers.Statements.SelectPreparedStatementNames where++import Hasql.Decoders qualified as Decoders+import Hasql.Statement qualified as Statement+import Helpers.Dsls.Statement+import Prelude++data SelectPreparedStatementNames = SelectPreparedStatementNames++type SelectPreparedStatementNamesResult = [Text]++instance StatementModule SelectPreparedStatementNames SelectPreparedStatementNamesResult where+  statement =+    Statement.unpreparable+      "select name from pg_prepared_statements order by name"+      mempty+      (Decoders.rowList (Decoders.column (Decoders.nonNullable Decoders.text)))
+ src/library-tests/Helpers/Statements/TooManyParams.hs view
@@ -0,0 +1,37 @@+module Helpers.Statements.TooManyParams where++import Hasql.Decoders qualified as Decoders+import Hasql.Encoders qualified as Encoders+import Hasql.Statement qualified as Statement+import Helpers.Dsls.Statement+import Prelude++-- | A statement with more parameters than libpq accepts in a single command.+--+-- The wire protocol counts parameters in an @int16@, so a list longer than+-- 65535 is rejected by the client before anything reaches the socket.+--+-- That makes it the reproduction trigger of+-- <https://github.com/nikita-volkov/hasql/issues/326>: placed in the middle+-- of a pipeline it makes the batched send of the whole pipeline fail+-- halfway through, with the commands preceding it already dispatched to the+-- server and the ones following it never sent.+--+-- Kept unpreparable so that the failing send is the statement's own+-- execution rather than a @PARSE@ preceding it, and so that the spec reads+-- the same on preparable and unpreparable connections.+data TooManyParams = TooManyParams++type TooManyParamsResult = ()++instance StatementModule TooManyParams TooManyParamsResult where+  statement =+    Statement.unpreparable+      "select 1"+      (foldMap (const param) [1 .. paramCount])+      Decoders.noResult+    where+      -- One more than the maximum amount of parameters libpq accepts.+      paramCount = 65536 :: Int++      param = contramap (const 1) (Encoders.param (Encoders.nonNullable Encoders.int8))
src/library-tests/Integration/Isolated/Connection/AcquireSpec.hs view
@@ -4,6 +4,7 @@ import Hasql.Connection qualified as Connection import Hasql.Connection.Settings qualified as Settings import Hasql.Errors qualified as Errors+import Helpers.PostgresContainer qualified as PostgresContainer import Pqi qualified import Prelude import Test.Hspec@@ -21,15 +22,15 @@           case result of             Right conn -> do               Connection.release conn-              expectationFailure "Expected connection to fail with authentication error, but it succeeded"-            Left (Errors.NetworkingConnectionError _) ->+              expectationFailure "Expected connection to fail with ConnectionAcquireError, but it succeeded"+            Left (Errors.ConnectionAcquireError _) ->               pure ()             Left err ->-              expectationFailure ("Expected NetworkingConnectionError, but got: " <> show err)+              expectationFailure ("Expected ConnectionAcquireError, but got: " <> show err)    describe "postgres:9" do     it "Succeeds" \adapter -> do-      TestcontainersPostgresql.run+      PostgresContainer.run         TestcontainersPostgresql.Config           { tagName = "postgres:9",             auth = TestcontainersPostgresql.CredentialsAuth "postgres" "postgres",@@ -52,7 +53,7 @@    describe "postgres:18" do     it "Succeeds" \adapter -> do-      TestcontainersPostgresql.run+      PostgresContainer.run         TestcontainersPostgresql.Config           { tagName = "postgres:18",             auth = TestcontainersPostgresql.CredentialsAuth "postgres" "postgres",@@ -73,8 +74,8 @@             Left err -> do               expectationFailure ("Expected connection to succeed, but it failed with error: " <> show err) -    it "Fails with authentication error on incorrect password" \adapter -> do-      TestcontainersPostgresql.run+    it "Reports ConnectionPasswordRequiredAcquireError when no password is supplied" \adapter -> do+      PostgresContainer.run         TestcontainersPostgresql.Config           { tagName = "postgres:18",             auth = TestcontainersPostgresql.CredentialsAuth "postgres" "postgres",@@ -92,14 +93,14 @@           case result of             Right conn -> do               Connection.release conn-              expectationFailure "Expected connection to fail with authentication error, but it succeeded"-            Left (Errors.AuthenticationConnectionError _) ->+              expectationFailure "Expected connection to fail with ConnectionPasswordRequiredAcquireError, but it succeeded"+            Left (Errors.ConnectionPasswordRequiredAcquireError _) ->               pure ()             Left err ->-              expectationFailure ("Expected AuthenticationConnectionError, but got: " <> show err)+              expectationFailure ("Expected ConnectionPasswordRequiredAcquireError, but got: " <> show err) -    it "Fails with authentication error on incorrect user" \adapter -> do-      TestcontainersPostgresql.run+    it "Reports ConnectionAcquireError on a wrong password" \adapter -> do+      PostgresContainer.run         TestcontainersPostgresql.Config           { tagName = "postgres:18",             auth = TestcontainersPostgresql.CredentialsAuth "postgres" "postgres",@@ -109,19 +110,19 @@           let settings =                 mconcat                   [ Settings.hostAndPort host port,-                    Settings.user "postgres1",-                    Settings.password "",+                    Settings.user "postgres",+                    Settings.password "wrongpassword",                     Settings.dbname "postgres"                   ]           result <- Connection.acquire adapter settings           case result of             Right conn -> do               Connection.release conn-              expectationFailure "Expected connection to fail with authentication error, but it succeeded"-            Left (Errors.AuthenticationConnectionError _) ->+              expectationFailure "Expected connection to fail with ConnectionAcquireError, but it succeeded"+            Left (Errors.ConnectionAcquireError _) ->               pure ()             Left err ->-              expectationFailure ("Expected AuthenticationConnectionError, but got: " <> show err)+              expectationFailure ("Expected ConnectionAcquireError, but got: " <> show err)    describe "postgres:9" do     byDistro "postgres:9"@@ -136,7 +137,7 @@         describe ("username: " <> toList username) do           describe ("password: " <> toList password) do             it "connects" \adapter -> do-              TestcontainersPostgresql.run+              PostgresContainer.run                 TestcontainersPostgresql.Config                   { tagName,                     auth = TestcontainersPostgresql.CredentialsAuth username password,@@ -165,7 +166,7 @@         itConnects "new user" "password"    describe "Connection errors" do-    describe "NetworkingConnectionError" do+    describe "ConnectionAcquireError" do       it "is reported for invalid host" \adapter -> do         result <-           Hasql.Connection.acquire@@ -177,8 +178,8 @@                 ]             )         case result of-          Left (Errors.NetworkingConnectionError _) -> pure ()-          Left err -> expectationFailure ("Expected NetworkingConnectionError, got: " <> show err)+          Left (Errors.ConnectionAcquireError _) -> pure ()+          Left err -> expectationFailure ("Expected ConnectionAcquireError, got: " <> show err)           Right _conn -> expectationFailure "Expected connection to fail"        it "is reported for connection refused" \adapter -> do@@ -192,13 +193,12 @@                 ]             )         case result of-          Left (Errors.NetworkingConnectionError _) -> pure ()-          Left err -> expectationFailure ("Expected NetworkingConnectionError, got: " <> show err)+          Left (Errors.ConnectionAcquireError _) -> pure ()+          Left err -> expectationFailure ("Expected ConnectionAcquireError, got: " <> show err)           Right _conn -> expectationFailure "Expected connection to fail" -    describe "AuthenticationConnectionError" do-      it "is reported for invalid credentials" \adapter -> do-        TestcontainersPostgresql.run+      it "is reported for a wrong password" \adapter -> do+        PostgresContainer.run           TestcontainersPostgresql.Config             { tagName,               auth = TestcontainersPostgresql.CredentialsAuth "password" "correctpassword",@@ -210,11 +210,34 @@                 adapter                 ( mconcat                     [ Settings.hostAndPort host port,-                      Settings.user "incorrectuser",+                      Settings.user "password",                       Settings.password "incorrectpassword"                     ]                 )             case result of-              Left (Errors.AuthenticationConnectionError _) -> pure ()-              Left err -> expectationFailure ("Expected AuthenticationConnectionError, got: " <> show err)-              Right _conn -> expectationFailure "Expected connection to fail with authentication error"+              Left (Errors.ConnectionAcquireError _) -> pure ()+              Left err -> expectationFailure ("Expected ConnectionAcquireError, got: " <> show err)+              Right _conn -> expectationFailure "Expected connection to fail with ConnectionAcquireError"++    describe "ConnectionPasswordRequiredAcquireError" do+      it "is reported when no password is supplied against a password-demanding server" \adapter -> do+        PostgresContainer.run+          TestcontainersPostgresql.Config+            { tagName,+              auth = TestcontainersPostgresql.CredentialsAuth "password" "correctpassword",+              forwardLogs = False+            }+          \(host, port) -> do+            result <-+              Hasql.Connection.acquire+                adapter+                ( mconcat+                    [ Settings.hostAndPort host port,+                      Settings.user "password",+                      Settings.password ""+                    ]+                )+            case result of+              Left (Errors.ConnectionPasswordRequiredAcquireError _) -> pure ()+              Left err -> expectationFailure ("Expected ConnectionPasswordRequiredAcquireError, got: " <> show err)+              Right _conn -> expectationFailure "Expected connection to fail with ConnectionPasswordRequiredAcquireError"
+ src/library-tests/Integration/Sharing/Connection/Use/InterruptionSpec.hs view
@@ -0,0 +1,194 @@+-- | What 'Hasql.Connection.use' does when an exception cuts a session short -+-- one the session threw itself, or one delivered from another thread by+-- 'timeout' or 'killThread'.+--+-- The exception propagates, and the connection is finished on the way out.+-- Nothing is repaired: an exception lands somewhere inside a round trip and+-- the driver has no way of finding out where, while the repair it could+-- attempt - draining results, aborting the transaction - is blocking network+-- IO performed under a mask, which on a connection whose peer has gone away+-- never returns. The interruption the caller asked for would then never land.+--+-- So the handle is spent from then on, exactly as it is after a failure the+-- driver could not vouch for the connection through+-- (see "Integration.Sharing.Pipeline.Statement.SendFailureSpec"), and+-- whatever the interrupted session had going on the server is rolled back+-- with the connection rather than left holding locks.+module Integration.Sharing.Connection.Use.InterruptionSpec (spec) where++import Hasql.Connection qualified as Connection+import Hasql.Decoders qualified as Decoders+import Hasql.Encoders qualified as Encoders+import Hasql.Errors qualified as Errors+import Hasql.Session qualified as Session+import Hasql.Statement qualified as Statement+import Helpers.Dsls.Execution qualified as Execution+import Helpers.Scripts qualified as Scripts+import Helpers.Statements.Sleep qualified as Statements+import Prelude+import Test.Hspec++spec :: SpecWith Scripts.ScopeParams+spec = do+  describe "An exception thrown by the session" do+    it "Propagates as itself rather than as a driver wrapper around it" \config ->+      Scripts.onPreparableConnection config \connection -> do+        -- The state a session got as far as reaches `use` on the back of an+        -- exception, so `use` has to unwrap that carrier before re-throwing.+        -- Caught here at the concrete type the session threw: were the+        -- carrier to escape instead, `try` would not match it and it would+        -- fail the example by propagating.+        result <- try @IOException do+          Connection.use connection do+            Session.script "select 1"+            liftIO (throwIO (userError "Original exception"))++        case result of+          Left err -> show err `shouldContain` "Original exception"+          Right _ -> expectationFailure "Expected the exception to propagate out of `use`"++    it "Spends the handle" \config ->+      Scripts.onPreparableConnection config \connection -> do+        interruptWith connection+        shouldReportTheConnectionAsGone connection++    it "Keeps reporting the spent handle as gone" \config ->+      -- A spent handle never carries a usable connection state again, so+      -- 'use' keeps reporting 'Errors.ConnectionUseError' however many times+      -- it is asked, rather than reconnecting.+      Scripts.onPreparableConnection config \connection -> do+        interruptWith connection+        replicateM_ 3 do+          result <- Connection.use connection (Session.script "select 1")+          case result of+            Left (Errors.ConnectionUseError _) -> pure ()+            _ -> expectationFailure ("Expected the spent handle to keep failing: " <> show result)++    it "Leaves the connection releasable" \config ->+      -- 'release' on a connection the driver already finished must not+      -- finish it a second time - libpq forbids touching a connection after+      -- PQfinish.+      Scripts.onPreparableConnection config \connection -> do+        interruptWith connection+        Connection.release connection+        Connection.release connection++  describe "Timing out" do+    describe "On a statement" do+      it "Reports the interruption and spends the handle" \config ->+        Scripts.onPreparableConnection config \connection -> do+          shouldTimeOut connection (Execution.sessionByParams (Statements.Sleep 0.1))+          shouldReportTheConnectionAsGone connection++    describe "On a transaction" do+      it "Reports the interruption and spends the handle" \config ->+        Scripts.onPreparableConnection config \connection -> do+          shouldTimeOut connection do+            Session.script "begin;"+            Execution.sessionByParams (Statements.Sleep 0.1)+            Session.script "commit;"+          shouldReportTheConnectionAsGone connection++    describe "In a pipeline" do+      it "Reports the interruption and spends the handle" \config ->+        Scripts.onPreparableConnection config \connection -> do+          shouldTimeOut connection do+            Session.pipeline+              $ Execution.pipelineByParams (Statements.Sleep 0.1)+              *> Execution.pipelineByParams (Statements.Sleep 0.1)+          shouldReportTheConnectionAsGone connection++    describe "On a statement that has never been prepared on this connection" do+      it "Reports the interruption and spends the handle" \config ->+        -- Kept apart from the case above because of what it used to guard.+        -- The driver reacted to an interruption by deallocating every+        -- prepared statement on the server and emptying the local cache to+        -- match, and a statement interrupted before it reached the cache+        -- made the two disagree - the next session got "prepared statement+        -- ... does not exist". Nothing can diverge now: the cache is part of+        -- the connection state, and the connection is discarded whole.+        Scripts.onPreparableConnection config \connection -> do+          shouldTimeOut connection (Session.statement 0.1 sleepStatement)+          shouldReportTheConnectionAsGone connection++  describe "Effects on the database state" do+    it "Rolls back the transaction the interrupted session was in" \config ->+      -- Finishing the connection is what discards the work: the server rolls+      -- the transaction back when the socket goes, so nothing the session had+      -- written survives and no backend is left idle in a transaction holding+      -- its locks.+      --+      -- Observing that takes a second connection, both because the one the+      -- session ran on is finished afterwards and because the effect has to+      -- outlive it.+      Scripts.onUnpreparableConnection config \observer -> do+        tableName <- Scripts.generateSymname+        createResult <-+          Connection.use observer (Session.script ("create table " <> tableName <> " (id int4)"))+        shouldBe createResult (Right ())++        Scripts.onUnpreparableConnection config \connection -> do+          _ <- try @SomeException do+            Connection.use connection do+              Session.script "begin;"+              Session.statement () (insertStatement tableName)+              liftIO (throwIO (userError "Simulated failure"))+          shouldReportTheConnectionAsGone connection++        countResult <- Connection.use observer (Session.statement () (countStatement tableName))+        shouldBe countResult (Right 0)++        dropResult <- Connection.use observer (Session.script ("drop table " <> tableName))+        shouldBe dropResult (Right ())++-- | Run a session that throws partway through, swallowing the exception it+-- propagates.+interruptWith :: Connection.Connection -> IO ()+interruptWith connection = do+  _ <- try @SomeException do+    Connection.use connection do+      Session.script "select 1"+      liftIO (throwIO (userError "Simulated failure"))+  pure ()++-- | Run the session under a timeout tuned to fire inside it, and assert that+-- the interruption came back out of 'Connection.use' as an exception.+--+-- 'Nothing' is what says so: had `use` reported the interruption as a+-- returned error instead, 'timeout' would have observed an ordinary return+-- and given us a 'Just'.+shouldTimeOut :: Connection.Connection -> Session.Session () -> IO ()+shouldTimeOut connection session = do+  result <- timeout 50_000 (Connection.use connection session)+  shouldBe result Nothing++-- | Assert that the handle no longer reaches a connection.+shouldReportTheConnectionAsGone :: Connection.Connection -> IO ()+shouldReportTheConnectionAsGone connection = do+  result <- Connection.use connection (Session.script "select 1")+  case result of+    Left (Errors.ConnectionUseError _) -> pure ()+    _ -> expectationFailure ("Unexpected follow-up result: " <> show result)++insertStatement :: Text -> Statement.Statement () ()+insertStatement tableName =+  Statement.unpreparable+    ("insert into " <> tableName <> " values (1)")+    mempty+    Decoders.noResult++countStatement :: Text -> Statement.Statement () Int64+countStatement tableName =+  Statement.unpreparable+    ("select count(*) from " <> tableName)+    mempty+    (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int8)))++-- | Sleeps for the given number of seconds, giving an interruption a window+-- to land in.+sleepStatement :: Statement.Statement Double ()+sleepStatement =+  Statement.preparable+    "select pg_sleep($1)"+    (Encoders.param (Encoders.nonNullable Encoders.float8))+    Decoders.noResult
− src/library-tests/Integration/Sharing/Connection/Use/PipelineAbortedInterruptionCleanupSpec.hs
@@ -1,134 +0,0 @@-module Integration.Sharing.Connection.Use.PipelineAbortedInterruptionCleanupSpec (spec) where--import Data.Text qualified as Text-import Hasql.Connection qualified as Connection-import Hasql.Decoders qualified as Decoders-import Hasql.Encoders qualified as Encoders-import Hasql.Pipeline qualified as Pipeline-import Hasql.Session qualified as Session-import Hasql.Statement qualified as Statement-import Helpers.Scripts qualified as Scripts-import Prelude-import Test.Hspec---- | A statement that sleeps for the given number of seconds and succeeds.------ Used to widen the wall-clock window during which the client is blocked--- waiting on the network/socket for a pipelined result, so that an--- asynchronous interruption has a realistic chance of landing right around--- the moment the *next* statement in the same pipeline fails.-sleepStatement :: Statement.Statement Double ()-sleepStatement =-  Statement.preparable-    "select pg_sleep($1)"-    (Encoders.param (Encoders.nonNullable Encoders.float8))-    Decoders.noResult---- | A statement that is guaranteed to fail on the server.-failingStatement :: Statement.Statement () ()-failingStatement =-  Statement.preparable-    "select 1/0"-    Encoders.noParams-    Decoders.noResult---- | A pipeline of two statements: the first sleeps and succeeds, the--- second fails. Executing this via 'Session.pipeline' drives libpq's--- pipeline status through: Off -> On -> (once the sleep result has been--- received and the divide error has been processed) Aborted -> (normally)--- Off again, via the exit sequence inside 'toPipelineIO'.------ The bug under test concerns what happens if an asynchronous exception--- interrupts execution during the narrow "Aborted" window: right after--- libpq has registered the error result for the second statement (which--- flips its internal pipeline status to `PipelineAborted`) but before the--- driver has drained the trailing pipeline-sync marker and called--- `exitPipelineMode`. That window is only a couple of FFI calls wide, so--- reliably landing an async exception inside it requires many attempts--- across a fine-grained sweep of interrupt delays (see 'spec' below).------ Note: an earlier version of this test tried to widen the window by--- appending many trivial "filler" statements after the failing one (on--- the theory that draining their results would take measurably longer).--- That approach reproduced failures reliably, but for the wrong reason:--- `Comms.Session.drainResults` only drains one queued command's worth of--- results per call, so a large backlog of undrained filler results made--- `exitPipelineMode` fail with "cannot exit pipeline mode with uncollected--- results" regardless of whether the `PipelineOn`/`PipelineAborted` bug--- under test was present or fixed. That's a real, separate limitation of--- `drainResults`, but not the bug this test is about, so the pipeline here--- is kept to exactly two statements and 'attempt' below specifically--- checks for the "not allowed in pipeline mode" signature (the one the--- one-line `leavePipeline` fix actually addresses) rather than any--- "Failed to clean up after interruption" message.-racingPipelineSession :: Double -> Session.Session ()-racingPipelineSession sleepSeconds =-  Session.pipeline do-    Pipeline.statement sleepSeconds sleepStatement-      *> Pipeline.statement () failingStatement---- | Try once to reproduce the bug: acquire a fresh connection, race a--- `timeout` against the pipelined session (sleep-then-fail) tuned to fire--- right around the moment the pipeline transitions to the aborted state,--- and report whether `Connection.use` came back with the specific driver--- error that signals the `leavePipeline` bug: it only checks for--- `PipelineOn`, so when the connection is genuinely `PipelineAborted` at--- interruption time, cleanup skips leaving the pipeline and falls through--- to `bringTransactionStatusToIdle`, which tries to send "ABORT" as a--- serial command while still in pipeline mode -- something libpq flatly--- refuses ("PQsendQuery not allowed in pipeline mode").------ Note on why checking `Connection.use`'s own return value is enough: when--- `timeout` throws its internal exception into the thread running--- `Connection.use`, that exception is caught by `use`'s own--- @try \@SomeException@. If the bug is NOT triggered, `use` cleans up--- successfully and rethrows the very same timeout exception, so `timeout`--- observes it and returns 'Nothing'. If the bug IS triggered, `use`--- reports the cleanup failure as an ordinary `Left (DriverSessionError _)`--- return value instead of rethrowing, so `timeout` observes a normal--- return and reports 'Just (Left _)'.-attempt :: Scripts.ScopeParams -> Double -> Int -> IO (Maybe Text)-attempt config sleepSeconds delayMicros =-  Scripts.onPreparableConnection config \connection -> do-    result <- timeout delayMicros do-      Connection.use connection (racingPipelineSession sleepSeconds)-    pure case result of-      Just (Left err) ->-        let rendered = Text.pack (show err)-         in if "Failed to clean up after interruption"-              `Text.isInfixOf` rendered-              && "not allowed in pipeline mode"-              `Text.isInfixOf` rendered-              then Just rendered-              else Nothing-      Just (Right ()) -> Nothing-      Nothing -> Nothing--spec :: SpecWith Scripts.ScopeParams-spec = do-  describe "Interruption of a pipeline while it is in the Aborted status" do-    it "Connection.use recovers cleanly instead of reporting a driver cleanup failure" \config -> do-      -- We sweep the timeout across a window that straddles the moment the-      -- sleep statement finishes and the failing statement's error result-      -- gets processed by libpq (which is when the pipeline status flips-      -- from `PipelineOn` to `PipelineAborted`). The genuinely vulnerable-      -- window is only a couple of FFI calls wide (nowhere near as wide as-      -- our timer granularity), so we compensate with a large number of-      -- attempts spread finely across the window and a fresh connection-      -- each time, rather than trying to widen the window itself.-      let sleepMicros = 20000 :: Int -- 20ms sleep statement duration-          sleepSeconds = fromIntegral sleepMicros / 1000000-          delays = [sleepMicros + step | step <- [(-3000), (-2900) .. 6000]]-          attemptsPerDelay = 15--      results <--        sequence-          [ attempt config sleepSeconds d-          | d <- delays,-            _ <- [1 :: Int .. attemptsPerDelay]-          ]--      let reproductions = [msg | Just msg <- results]--      reproductions-        `shouldBe` []
src/library-tests/Integration/Sharing/Connection/UseSpec.hs view
@@ -7,14 +7,12 @@ import Hasql.Connection qualified as Connection import Hasql.Decoders qualified as Decoders import Hasql.Encoders qualified as Encoders-import Hasql.Pipeline qualified as Pipeline+import Hasql.Errors qualified as Errors import Hasql.Session qualified as Session import Hasql.Statement qualified as Statement import Helpers.Dsls.Execution qualified as Execution import Helpers.Scripts qualified as Scripts-import Helpers.Statements.SelectOne qualified as Statements.SelectOne import Helpers.Statements.SelectProvidedInt8 qualified as Statements.SelectProvidedInt8-import Helpers.Statements.Sleep qualified as Statements import Prelude import Test.Hspec @@ -48,126 +46,32 @@          result `shouldBe` Right (3 :: Int64) -  describe "Pipeline Mode" do-    it "Leaves the connection usable after timeout in pipeline" \config -> do+  describe "Release" do+    it "Is idempotent on a connection that never failed" \config -> do+      -- 'release' must not touch a connection it has already finished:+      -- libpq forbids calling anything, including a second PQfinish, on a+      -- handle after PQfinish. Every other idempotency example gets there+      -- via a prior failure or exception; this is the plain path, with+      -- nothing having gone wrong first.       Scripts.onPreparableConnection config \connection -> do-        let selectStatement =-              Statement.preparable-                "select $1::int"-                (Encoders.param (Encoders.nonNullable Encoders.int4))-                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int4)))--        -- Timeout during a pipeline operation-        result <--          timeout 50_000 do-            Connection.use connection-              $ Session.pipeline-              $ (,)-              <$> Pipeline.statement 42 selectStatement-              <*> Execution.pipelineByParams (Statements.Sleep 0.1)--        result `shouldBe` Nothing--        -- Try to use pipeline again after timeout cleanup-        -- This should work but fails with "connection not idle" without the fix-        result2 <--          Connection.use connection-            $ Session.pipeline-            $ Pipeline.statement 99 selectStatement--        result2 `shouldBe` Right 99--  describe "Timing out" do-    describe "On a statement" do-      it "Leaves the connection usable" \config -> Scripts.onPreparableConnection config \connection -> do-        result <--          timeout 50_000 do-            Connection.use connection do-              Execution.sessionByParams (Statements.Sleep 0.1)--        result `shouldBe` Nothing--        result <--          Connection.use connection do-            Execution.sessionByParams Statements.SelectOne.SelectOne--        result `shouldBe` Right 1--    describe "On a transaction" do-      it "Leaves the connection usable" \config -> Scripts.onPreparableConnection config \connection -> do-        -- Start a transaction and timeout during it-        result <--          timeout 50_000 do-            Connection.use connection do-              Session.script "begin;"-              Execution.sessionByParams (Statements.Sleep 0.1)-              Session.script "commit;"--        result `shouldBe` Nothing--        -- Connection should still be usable after timeout in transaction-        result <--          Connection.use connection do-            Execution.sessionByParams Statements.SelectOne.SelectOne--        result `shouldBe` Right 1--      it "Lets us start another transaction" do-        let checkTransactionStatus =-              Statement.preparable-                "select case when pg_advisory_lock(1) is null then 0 else 1 end"-                mempty-                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int4)))-         in \config -> Scripts.onPreparableConnection config \connection -> do-              -- Timeout during a transaction-              result <--                timeout 50_000 do-                  Connection.use connection do-                    Session.script "begin;"-                    Execution.sessionByParams (Statements.Sleep 0.1)--              result `shouldBe` Nothing--              -- Verify we can start a new transaction without "already in progress" error-              result <--                Connection.use connection do-                  Session.script "begin;"-                  s <- Session.statement () checkTransactionStatus-                  Session.script "commit;"-                  return s--              result `shouldBe` Right 1--      it "Does not corrupt the prepared statement registry" do-        let returnIntStatement =-              Statement.preparable-                "select $1::int"-                (Encoders.param (Encoders.nonNullable Encoders.int4))-                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int4)))-         in \config -> Scripts.onPreparableConnection config \connection -> do-              -- Use a prepared statement first-              result <--                Connection.use connection do-                  Session.statement 42 returnIntStatement--              result `shouldBe` Right 42--              -- Timeout during transaction (causes connection reset)-              result <--                timeout 50_000 do-                  Connection.use connection do-                    Session.script "begin;"-                    Execution.sessionByParams (Statements.Sleep 0.1)-                    Session.script "commit;"+        _ <- Connection.use connection (Session.script "select 1")+        Connection.release connection+        Connection.release connection -              result `shouldBe` Nothing+    it "Makes `use` report the connection as gone rather than reconnecting" \config -> do+      -- Releasing is one of the three ways a handle goes spent (the others+      -- being a session that finishes the connection, and an exception). No+      -- other example reaches "spent by `release`" directly.+      Scripts.onPreparableConnection config \connection -> do+        Connection.release connection -              -- The prepared statement should work again without "does not exist" error-              result <--                Connection.use connection do-                  Session.statement 99 returnIntStatement+        result <- Connection.use connection (Session.script "select 1")+        case result of+          Left (Errors.ConnectionUseError _) -> pure ()+          _ -> expectationFailure ("Unexpected result: " <> show result) -              result `shouldBe` Right 99+        -- Releasing an already-spent connection remains a no-op.+        Connection.release connection    describe "Concurrency" do     it "handles concurrent connections properly" \config -> do@@ -196,77 +100,72 @@           result <- takeMVar finishVar           result `shouldBe` True -    it "Connection remains usable after exception in non-idle state with concurrent threads" \config -> Scripts.onPreparableConnection config \connection -> do-      -- This test reproduces the bug fixed in commit 62ebef2.-      -- The bug was that when an exception occurred during a session,-      -- the connection state was put back into the MVar BEFORE resetting the connection.-      -- This created a race condition where another thread could grab the corrupted connection.--      -- We'll create a scenario where:-      -- 1. Thread A starts a session that will throw an exception-      -- 2. Thread B repeatedly tries to use the connection-      -- 3. The exception in Thread A should not corrupt the connection for Thread B+    it "Reports the connection as gone to every other thread rather than deadlocking" \config -> Scripts.onPreparableConnection config \connection -> do+      -- The exception path of `use` empties the MVar before it touches the+      -- connection and fills it back in with `Nothing`, so a thread waiting+      -- on the MVar wakes up to a handle that says the connection is gone.+      -- What it must never do is wake up to the connection itself while the+      -- interrupted thread is still finishing it, or not wake up at all -+      -- which is what happened before commit 62ebef2, where the state went+      -- back into the MVar before the connection was dealt with.+      --+      -- So this pins the two halves that survive the connection no longer+      -- being repaired: every result another thread sees is either the+      -- statement's own or the verdict that the connection is gone, and no+      -- thread hangs. -      -- Counter to track successful operations by Thread B-      successCount <- newIORef (0 :: Int)-      errorCount <- newIORef (0 :: Int)+      -- Results collected by the thread using the connection alongside the+      -- one that interrupts it.+      resultsRef <- newIORef [] -      -- Barrier to synchronize threads       startBarrier <- newEmptyMVar       doneBarrier <- newEmptyMVar -      -- Thread A: Throws exceptions repeatedly+      -- Thread A: interrupts a session that is in a transaction, so the+      -- connection is left in a non-idle state.       _ <- forkIO do         takeMVar startBarrier         replicateM_ 10 do-          -- Use the connection and throw an exception during the session           _ <- try @SomeException do             Connection.use connection do-              -- Start a transaction to put connection in non-idle state               Session.script "BEGIN"-              -- Throw an exception while in transaction (non-idle state)               liftIO (throwIO (userError "Intentional exception"))-          threadDelay 1000 -- Small delay to allow interleaving+          threadDelay 1000         putMVar doneBarrier () -      -- Thread B: Tries to use connection concurrently+      -- Thread B: keeps using the connection throughout.       _ <- forkIO do         takeMVar startBarrier         replicateM_ 20 do           result <- Connection.use connection (Execution.sessionByParams (Statements.SelectProvidedInt8.SelectProvidedInt8 42))-          case result of-            Right 42 -> atomicModifyIORef' successCount (\n -> (n + 1, ()))-            _ -> atomicModifyIORef' errorCount (\n -> (n + 1, ()))+          atomicModifyIORef' resultsRef (\results -> (result : results, ()))           threadDelay 500         putMVar doneBarrier () -      -- Start both threads       putMVar startBarrier ()       putMVar startBarrier () -      -- Wait for both threads to complete with a timeout-      -- If the bug exists, threads may hang waiting for a corrupted connection-      result <- timeout (5 * 1000000) do-        -- 5 seconds timeout+      completion <- timeout (5 * 1000000) do         takeMVar doneBarrier         takeMVar doneBarrier -      case result of-        Nothing -> do-          -- Test timed out - this indicates the bug is present-          expectationFailure "Test timed out waiting for threads to complete. This indicates the connection became deadlocked due to the race condition bug."+      case completion of+        Nothing ->+          expectationFailure "Timed out waiting for the threads to complete, which means the connection deadlocked."         Just () -> do-          -- Threads completed successfully-          -- Check results-          successes <- readIORef successCount-          errors <- readIORef errorCount--          -- Thread B should have succeeded at least some times-          -- If the bug exists, we'd expect Thread B to get errors due to corrupted connection state-          successes `shouldSatisfy` (> 0)--          errors `shouldBe` 0+          results <- readIORef resultsRef+          let unexpected =+                filter+                  ( \case+                      Right 42 -> False+                      Left (Errors.ConnectionUseError _) -> False+                      _ -> True+                  )+                  results+          unexpected `shouldBe` [] -          -- Verify connection is still usable after all this+          -- Once gone, gone: the handle does not come back to life.           finalResult <- Connection.use connection (Execution.sessionByParams (Statements.SelectProvidedInt8.SelectProvidedInt8 99))-          finalResult `shouldBe` Right 99+          case finalResult of+            Left (Errors.ConnectionUseError _) -> pure ()+            _ -> expectationFailure ("Unexpected final result: " <> show finalResult)
src/library-tests/Integration/Sharing/Decoders/Composite/OidMismatchSpec.hs view
@@ -42,7 +42,7 @@                 )           -- The error should indicate a decoding failure due to type mismatch           case result of-            Left (Errors.StatementSessionError _ _ _ _ _ (Errors.RowStatementError _ (Errors.CellRowError _ _ (Errors.DeserializationCellError msg)))) -> do+            Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.RowStatementError _ (Errors.CellRowError _ _ (Errors.DeserializationCellError msg))))) -> do               -- PostgreSQL binary decoder should detect the OID mismatch               toList msg `shouldContain` "Unexpected OID"             Left err ->@@ -79,7 +79,7 @@                 )           -- The error should indicate a decoding failure due to type mismatch           case result of-            Left (Errors.StatementSessionError _ _ _ _ _ (Errors.RowStatementError _ (Errors.CellRowError _ _ (Errors.DeserializationCellError msg)))) -> do+            Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.RowStatementError _ (Errors.CellRowError _ _ (Errors.DeserializationCellError msg))))) -> do               -- PostgreSQL binary decoder should detect the OID mismatch               toList msg `shouldContain` "Unexpected OID"             Left err ->@@ -116,7 +116,7 @@                 )           -- The error should indicate a decoding failure due to type mismatch           case result of-            Left (Errors.StatementSessionError _ _ _ _ _ (Errors.RowStatementError _ (Errors.CellRowError _ _ (Errors.DeserializationCellError _msg)))) -> do+            Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.RowStatementError _ (Errors.CellRowError _ _ (Errors.DeserializationCellError _msg))))) -> do               -- PostgreSQL binary decoder should detect the type mismatch               pure ()             Left err ->@@ -157,7 +157,7 @@                 )           -- The error should indicate a decoding failure           case result of-            Left (Errors.StatementSessionError _ _ _ _ _ (Errors.RowStatementError _ (Errors.CellRowError _ _ (Errors.DeserializationCellError _msg)))) -> do+            Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.RowStatementError _ (Errors.CellRowError _ _ (Errors.DeserializationCellError _msg))))) -> do               pure ()             Left err ->               expectationFailure ("Unexpected type of error: " <> show err)
src/library-tests/Integration/Sharing/Decoders/CompositeSpec.hs view
@@ -664,7 +664,7 @@                 )           -- Should fail with a cell error because text cannot be decoded as a composite           case result of-            Left (Errors.StatementSessionError _ _ _ _ _ (Errors.UnexpectedColumnTypeStatementError 0 _ _)) ->+            Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.UnexpectedColumnTypeStatementError 0 _ _))) ->               pure ()             Left err ->               expectationFailure ("Unexpected type of error: " <> show err)@@ -710,7 +710,7 @@                 )           -- Should fail with a cell error because the field count doesn't match           case result of-            Left (Errors.StatementSessionError _ _ _ _ _ (Errors.UnexpectedColumnTypeStatementError 0 _ _)) ->+            Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.UnexpectedColumnTypeStatementError 0 _ _))) ->               pure ()             Left err ->               expectationFailure ("Unexpected type of error: " <> show err)@@ -771,7 +771,7 @@             )        case result of-        Left (Errors.MissingTypesSessionError missingTypes) ->+        Left (Errors.SessionUseError (Errors.MissingTypesSessionError missingTypes)) ->           missingTypes `shouldBe` HashSet.fromList [(Nothing, "nonexistent_composite_type")]         _ ->           expectationFailure ("Unexpected result: " <> show result)
src/library-tests/Integration/Sharing/Decoders/CustomSpec.hs view
@@ -150,7 +150,7 @@               )          case result of-          Left (Errors.MissingTypesSessionError missingTypes) ->+          Left (Errors.SessionUseError (Errors.MissingTypesSessionError missingTypes)) ->             missingTypes `shouldBe` HashSet.fromList [(Nothing, "nonexistent_custom_type")]           _ ->             expectationFailure ("Unexpected result: " <> show result)@@ -185,7 +185,7 @@               )          case result of-          Left (Errors.MissingTypesSessionError missingTypes) ->+          Left (Errors.SessionUseError (Errors.MissingTypesSessionError missingTypes)) ->             missingTypes `shouldBe` HashSet.fromList [(Nothing, "nonexistent_dependency")]           _ ->             expectationFailure ("Unexpected result: " <> show result)@@ -212,7 +212,7 @@               )          case result of-          Left (Errors.StatementSessionError {}) -> pure ()+          Left (Errors.SessionUseError (Errors.StatementSessionError {})) -> pure ()           _ ->             expectationFailure "Expected statement error" 
src/library-tests/Integration/Sharing/Decoders/EnumSpec.hs view
@@ -270,7 +270,7 @@             (Decoders.singleRow (Decoders.column (Decoders.nonNullable (Decoders.enum Nothing "nonexistent_enum_type" (Just . id)))))        case result of-        Left (Errors.MissingTypesSessionError missingTypes) ->+        Left (Errors.SessionUseError (Errors.MissingTypesSessionError missingTypes)) ->           missingTypes `shouldBe` HashSet.fromList [(Nothing, "nonexistent_enum_type")]         _ ->           expectationFailure ("Unexpected result: " <> show result)@@ -296,7 +296,7 @@             )        case result of-        Left (Errors.MissingTypesSessionError missingTypes) ->+        Left (Errors.SessionUseError (Errors.MissingTypesSessionError missingTypes)) ->           missingTypes `shouldBe` HashSet.fromList [(Nothing, "nonexistent_array_enum")]         _ ->           expectationFailure ("Unexpected result: " <> show result)
src/library-tests/Integration/Sharing/Encoders/Composite/OidMismatchSpec.hs view
@@ -47,7 +47,7 @@                 )           -- The error should indicate a type mismatch from the server           case result of-            Left (Errors.StatementSessionError _ _ _ _ _ (Errors.ServerStatementError (Errors.ServerError code _msg _detail _hint _pos))) -> do+            Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.ServerStatementError (Errors.ServerError code _msg _detail _hint _pos)))) -> do               -- PostgreSQL should reject the mismatched types               -- Error code 42804 is "datatype_mismatch"               code `shouldSatisfy` (\c -> c == "42804" || c == "42P01" || c == "22P02")@@ -89,7 +89,7 @@                 )           -- The error should indicate a type mismatch from the server           case result of-            Left (Errors.StatementSessionError _ _ _ _ _ (Errors.ServerStatementError (Errors.ServerError code _msg _detail _hint _pos))) -> do+            Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.ServerStatementError (Errors.ServerError code _msg _detail _hint _pos)))) -> do               -- PostgreSQL should reject the mismatched types               -- Error code 42804 is "datatype_mismatch"               code `shouldSatisfy` (\c -> c == "42804" || c == "42P01" || c == "22P02")@@ -131,7 +131,7 @@                 )           -- The error should indicate a type mismatch from the server           case result of-            Left (Errors.StatementSessionError _ _ _ _ _ (Errors.ServerStatementError (Errors.ServerError code _msg _detail _hint _pos))) -> do+            Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.ServerStatementError (Errors.ServerError code _msg _detail _hint _pos)))) -> do               -- PostgreSQL should reject the mismatched types               code `shouldSatisfy` (\c -> c == "42804" || c == "42P01" || c == "22P02")             Left err ->@@ -184,7 +184,7 @@                 )           -- The error should indicate a type mismatch from the server           case result of-            Left (Errors.StatementSessionError _ _ _ _ _ (Errors.ServerStatementError (Errors.ServerError code _msg _detail _hint _pos))) -> do+            Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.ServerStatementError (Errors.ServerError code _msg _detail _hint _pos)))) -> do               -- PostgreSQL should reject the mismatched types               code `shouldSatisfy` (\c -> c == "42804" || c == "42P01" || c == "22P02")             Left err ->
src/library-tests/Integration/Sharing/Encoders/CompositeSpec.hs view
@@ -801,7 +801,7 @@             (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.text)))        case result of-        Left (Errors.MissingTypesSessionError missingTypes) ->+        Left (Errors.SessionUseError (Errors.MissingTypesSessionError missingTypes)) ->           missingTypes `shouldBe` HashSet.fromList [(Nothing, "nonexistent_composite_type")]         _ ->           expectationFailure ("Unexpected result: " <> show result)
src/library-tests/Integration/Sharing/Encoders/CustomSpec.hs view
@@ -124,7 +124,7 @@               (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.text)))          case result of-          Left (Errors.MissingTypesSessionError missingTypes) ->+          Left (Errors.SessionUseError (Errors.MissingTypesSessionError missingTypes)) ->             missingTypes `shouldBe` HashSet.fromList [(Nothing, "nonexistent_custom_type")]           _ ->             expectationFailure ("Unexpected result: " <> show result)@@ -158,7 +158,7 @@               (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.text)))          case result of-          Left (Errors.MissingTypesSessionError missingTypes) ->+          Left (Errors.SessionUseError (Errors.MissingTypesSessionError missingTypes)) ->             missingTypes `shouldBe` HashSet.fromList [(Nothing, "nonexistent_dependency")]           _ ->             expectationFailure ("Unexpected result: " <> show result)@@ -335,7 +335,7 @@               (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.text)))          case result of-          Left (Errors.MissingTypesSessionError missingTypes) ->+          Left (Errors.SessionUseError (Errors.MissingTypesSessionError missingTypes)) ->             missingTypes `shouldBe` HashSet.fromList [(Just "nonexistent_schema", "nonexistent_type")]           _ ->             expectationFailure ("Unexpected result: " <> show result)
src/library-tests/Integration/Sharing/Encoders/EnumSpec.hs view
@@ -253,7 +253,7 @@             (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.text)))        case result of-        Left (Errors.MissingTypesSessionError missingTypes) ->+        Left (Errors.SessionUseError (Errors.MissingTypesSessionError missingTypes)) ->           missingTypes `shouldBe` HashSet.fromList [(Nothing, "this_enum_does_not_exist_in_db")]         _ ->           expectationFailure ("Unexpected result: " <> show result)@@ -269,7 +269,7 @@               (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.text)))          case result of-          Left (Errors.MissingTypesSessionError missingTypes) ->+          Left (Errors.SessionUseError (Errors.MissingTypesSessionError missingTypes)) ->             missingTypes `shouldBe` HashSet.fromList [(Just "nonexistent_schema", "nonexistent_type")]           _ ->             expectationFailure ("Unexpected result: " <> show result)@@ -285,7 +285,7 @@          -- The statement should fail when trying to use a non-existent type in existing schema         case result of-          Left (Errors.MissingTypesSessionError missingTypes) -> do+          Left (Errors.SessionUseError (Errors.MissingTypesSessionError missingTypes)) -> do             missingTypes `shouldBe` HashSet.fromList [(Just "public", "this_type_does_not_exist")]           _ ->             expectationFailure ("Unexpected result: " <> show result)@@ -309,7 +309,7 @@             (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.text)))        case result of-        Left (Errors.MissingTypesSessionError missingTypes) ->+        Left (Errors.SessionUseError (Errors.MissingTypesSessionError missingTypes)) ->           missingTypes `shouldBe` HashSet.fromList [(Nothing, "nonexistent_array_enum")]         _ ->           expectationFailure ("Unexpected result: " <> show result)
src/library-tests/Integration/Sharing/ErrorsSpec.hs view
@@ -1,9 +1,11 @@ module Integration.Sharing.ErrorsSpec (spec) where  import Data.Either+import Data.Functor.Contravariant import Data.Vector qualified as Vector import Hasql.Connection qualified as Connection import Hasql.Decoders qualified as Decoders+import Hasql.Encoders qualified as Encoders import Hasql.Errors qualified as Errors import Hasql.Pipeline qualified as Pipeline import Hasql.Session qualified as Session@@ -14,6 +16,35 @@  spec :: SpecWith Scripts.ScopeParams spec = do+  describe "Sends libpq refuses" do+    -- libpq rejects `sendQueryParams` outright when given more than 65535+    -- parameters, without ever talking to the server. Nevertheless the+    -- driver cannot vouch for the connection's protocol state after a+    -- refused send, so `use` finishes it rather than leaving it open for a+    -- retry wrapper to resend the identical rejected request against.+    it "reports too many parameters as fatal and closes the connection" \config -> do+      Scripts.onPreparableConnection config \connection -> do+        let tooManyParams = 65536+            statement =+              Statement.unpreparable+                "select 1"+                (mconcat (replicate tooManyParams (contramap (const (0 :: Int64)) (Encoders.param (Encoders.nonNullable Encoders.int8)))))+                Decoders.noResult+        result <- Connection.use connection (Session.statement () statement)+        case result of+          Left (Errors.ConnectionUseError _) -> pure ()+          Left err ->+            expectationFailure ("Expected ConnectionUseError, but got: " <> show err)+          Right () ->+            expectationFailure "Expected the statement to be rejected for having too many parameters"++        -- The connection is gone: a further `use` reports the same thing+        -- rather than succeeding.+        anotherResult <- Connection.use connection (Session.script "select 1")+        case anotherResult of+          Left (Errors.ConnectionUseError _) -> pure ()+          _ -> expectationFailure ("Unexpected result on the spent connection: " <> show anotherResult)+   describe "Syntax errors" do     forM_ [False, True] \inPipeline -> do       describe (if inPipeline then "Pipeline" else "Session") do@@ -33,16 +64,17 @@                 shouldBe                   result                   ( Left-                      ( (Errors.StatementSessionError 1 0 "-" [] preparable)-                          ( Errors.ServerStatementError-                              ( Errors.ServerError-                                  "42601"-                                  "syntax error at or near \"-\""-                                  Nothing-                                  Nothing-                                  (Just 1)-                              )-                          )+                      ( Errors.SessionUseError+                          $ (Errors.StatementSessionError 1 0 "-" [] preparable)+                            ( Errors.ServerStatementError+                                ( Errors.ServerError+                                    "42601"+                                    "syntax error at or near \"-\""+                                    Nothing+                                    Nothing+                                    (Just 1)+                                )+                            )                       )                   ) @@ -70,7 +102,7 @@                     (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int8)))             result <- Connection.use connection (executor statement)             case result of-              Left (Errors.StatementSessionError _ _ _ _ _ (Errors.UnexpectedColumnCountStatementError expected actual)) -> do+              Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.UnexpectedColumnCountStatementError expected actual))) -> do                 shouldBe expected 1                 shouldBe actual 2               Left err ->@@ -92,7 +124,7 @@                     )             result <- Connection.use connection (executor statement)             case result of-              Left (Errors.StatementSessionError _ _ _ _ _ (Errors.UnexpectedColumnCountStatementError expected actual)) -> do+              Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.UnexpectedColumnCountStatementError expected actual))) -> do                 shouldBe expected 2                 shouldBe actual 1               Left err ->@@ -116,7 +148,7 @@                       )               result <- Connection.use connection (executor statement)               case result of-                Left (Errors.StatementSessionError _ _ _ _ _ (Errors.UnexpectedColumnTypeStatementError column expected actual)) -> do+                Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.UnexpectedColumnTypeStatementError column expected actual))) -> do                   shouldBe column 1                   shouldBe expected 20                   shouldBe actual 25@@ -140,7 +172,7 @@                       )               result <- Connection.use connection (executor statement)               case result of-                Left (Errors.StatementSessionError _ _ _ _ _ (Errors.UnexpectedColumnTypeStatementError column expected actual)) -> do+                Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.UnexpectedColumnTypeStatementError column expected actual))) -> do                   shouldBe column 1                   (expected, actual) `shouldBe` (20, 25)                 Left err ->@@ -151,7 +183,8 @@         describe "rowVector" do           it "gets reported when column type mismatches decoder" \config -> do             Scripts.onPreparableConnection config \connection -> do-              let statement =+              let statement :: Statement.Statement () (Vector.Vector (Int64, Int64))+                  statement =                     (if preparable then Statement.preparable else Statement.unpreparable)                       "select int8 '1', text 'text'"                       mempty@@ -163,7 +196,7 @@                       )               result <- Connection.use connection (executor statement)               case result of-                Left (Errors.StatementSessionError _ _ _ _ _ (Errors.UnexpectedColumnTypeStatementError column expected actual)) -> do+                Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.UnexpectedColumnTypeStatementError column expected actual))) -> do                   shouldBe column 1                   (expected, actual) `shouldBe` (20, 25)                 Left err ->@@ -185,7 +218,7 @@                           )                   result <- Connection.use connection (executor statement)                   case result of-                    Left (Errors.StatementSessionError _ _ _ _ _ (Errors.UnexpectedColumnTypeStatementError column expected actual)) -> do+                    Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.UnexpectedColumnTypeStatementError column expected actual))) -> do                       shouldBe column 0                       (expected, actual) `shouldBe` (1016, 20)                     Left err ->@@ -220,7 +253,7 @@                           )                   result <- Connection.use connection (executor statement)                   case result of-                    Left (Errors.StatementSessionError _ _ _ _ _ (Errors.UnexpectedColumnTypeStatementError column expected actual)) -> do+                    Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.UnexpectedColumnTypeStatementError column expected actual))) -> do                       shouldBe column 0                       (expected, actual) `shouldBe` (20, 1016)                     Left err ->
+ src/library-tests/Integration/Sharing/Pipeline/Statement/SendFailureSpec.hs view
@@ -0,0 +1,164 @@+module Integration.Sharing.Pipeline.Statement.SendFailureSpec (spec) where++import Hasql.Connection qualified as Connection+import Hasql.Decoders qualified as Decoders+import Hasql.Errors qualified as Errors+import Hasql.Pipeline qualified as Pipeline+import Hasql.Session qualified as Session+import Hasql.Statement qualified as Statement+import Helpers.Dsls.Execution qualified as Execution+import Helpers.Scripts qualified as Scripts+import Helpers.Statements qualified as Statements+import Prelude+import Test.Hspec++-- | A pipeline of five statements with 'Statements.TooManyParams' in the+-- middle: statements 1 and 2 are queued, statement 3 is refused on send, and+-- statements 4 and 5 are never even queued.+--+-- This is the reproduction of <https://github.com/nikita-volkov/hasql/issues/326>.+--+-- Note what "queued" means here and what it does not. In pipeline mode+-- @PQsendQueryParams@ only appends to libpq's output buffer; libpq flushes+-- when the buffer passes a size threshold, and otherwise nothing reaches the+-- server until a Sync. Two @generate_series@ calls are nowhere near that+-- threshold, so at the moment statement 3 is refused, __nothing has left the+-- client__. The driver does not push a Sync to find out - doing so would+-- flush and commit statements 1 and 2, which is the opposite of what a+-- pipeline that failed halfway should do. It finishes the connection+-- instead, and the whole pipeline is discarded, exactly as it would be had+-- the server rejected one of the statements.+failingPipeline :: Pipeline.Pipeline ()+failingPipeline = do+  _ <- goodStatement+  _ <- goodStatement+  _ <- Execution.pipelineByParams Statements.TooManyParams+  _ <- goodStatement+  _ <- goodStatement+  pure ()+  where+    goodStatement =+      Execution.pipelineByParams Statements.GenerateSeries {start = 0, end = 2}++-- | The same failure with nothing queued before it: the send of the very+-- first statement fails, so the pipeline mode is on and the command queue is+-- empty.+failingOnFirstStatementPipeline :: Pipeline.Pipeline ()+failingOnFirstStatementPipeline = do+  _ <- Execution.pipelineByParams Statements.TooManyParams+  _ <- Execution.pipelineByParams Statements.GenerateSeries {start = 0, end = 2}+  pure ()++spec :: SpecWith Scripts.ScopeParams+spec = do+  describe "Send failure in the middle of a pipeline" do+    it "Captures the error" \config -> do+      Scripts.onUnpreparableConnection config runFailingPipeline++    it "Finishes the connection" \config -> do+      -- The driver cannot vouch for the protocol state of a connection it+      -- failed to send on: the mode is still on, commands are queued behind+      -- the refusal, and only a Sync would reveal what the server has seen+      -- - at the cost of committing them. So the connection is finished+      -- rather than repaired, and the handle it was reached through is+      -- spent.+      Scripts.onUnpreparableConnection config \connection -> do+        runFailingPipeline connection+        followUpResult <-+          Connection.use connection+            $ Session.script "select 1"+        case followUpResult of+          Left (Errors.ConnectionUseError _) -> pure ()+          _ -> expectationFailure ("Unexpected follow-up result: " <> show followUpResult)++    it "Keeps reporting the connection as gone however many times it is used" \config -> do+      Scripts.onUnpreparableConnection config \connection -> do+        runFailingPipeline connection+        replicateM_ 3 do+          result <- Connection.use connection (Session.script "select 1")+          case result of+            Left (Errors.ConnectionUseError _) -> pure ()+            _ -> expectationFailure ("Unexpected follow-up result: " <> show result)++    it "Leaves the connection releasable" \config -> do+      -- 'release' on a connection the driver already finished must not+      -- finish it a second time - libpq forbids touching a connection after+      -- PQfinish.+      Scripts.onUnpreparableConnection config \connection -> do+        runFailingPipeline connection+        Connection.release connection+        Connection.release connection++    describe "When it happens on the first statement of the pipeline" do+      it "Fails the same way" \config -> do+        -- Nothing was queued before the failure - the opposite end of the+        -- range from the mid-pipeline case above, and the same outcome.+        Scripts.onUnpreparableConnection config \connection -> do+          result <-+            Connection.use connection+              $ Session.pipeline failingOnFirstStatementPipeline+          case result of+            Left (Errors.ConnectionUseError _) -> pure ()+            _ -> expectationFailure ("Unexpected pipeline result: " <> show result)+          followUpResult <-+            Connection.use connection+              $ Session.script "select 1"+          case followUpResult of+            Left (Errors.ConnectionUseError _) -> pure ()+            _ -> expectationFailure ("Unexpected follow-up result: " <> show followUpResult)++    describe "Effects on the database state" do+      it "Discards the whole pipeline, including the statements preceding the failure" \config -> do+        -- The statements before the failure were appended to libpq's output+        -- buffer and never flushed, so the server never saw them. This+        -- matches what a query error in a pipeline already does: the+        -- implicit transaction block is rolled back whole.+        --+        -- Observing that takes a second connection, both because the one+        -- the pipeline ran on is finished afterwards and because the effect+        -- has to outlive it.+        Scripts.onUnpreparableConnection config \observer -> do+          tableName <- Scripts.generateSymname+          createResult <-+            Connection.use observer (Session.script ("create table " <> tableName <> " (id int4)"))+          shouldBe createResult (Right ())++          pipelineResult <-+            Scripts.onUnpreparableConnection config \connection ->+              (Connection.use connection . Session.pipeline)+                $ (,)+                <$> Pipeline.statement () (insertStatement tableName)+                <*> Execution.pipelineByParams Statements.TooManyParams+          case pipelineResult of+            Left (Errors.ConnectionUseError _) -> pure ()+            _ -> expectationFailure ("Unexpected pipeline result: " <> show pipelineResult)++          countResult <- Connection.use observer (Session.statement () (countStatement tableName))+          shouldBe countResult (Right 0)++          dropResult <- Connection.use observer (Session.script ("drop table " <> tableName))+          shouldBe dropResult (Right ())++insertStatement :: Text -> Statement.Statement () ()+insertStatement tableName =+  Statement.unpreparable+    ("insert into " <> tableName <> " values (1)")+    mempty+    Decoders.noResult++countStatement :: Text -> Statement.Statement () Int64+countStatement tableName =+  Statement.unpreparable+    ("select count(*) from " <> tableName)+    mempty+    (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int8)))++-- | Run 'failingPipeline' and assert it fails with the expected rejection.+runFailingPipeline :: Connection.Connection -> IO ()+runFailingPipeline connection = do+  result <-+    Connection.use connection+      $ Session.pipeline failingPipeline+  case result of+    Left (Errors.ConnectionUseError _) -> pure ()+    _ -> expectationFailure ("Unexpected pipeline result: " <> show result)
src/library-tests/Integration/Sharing/PipelineSpec.hs view
@@ -62,7 +62,7 @@                 <*> Execution.pipelineByParams Statements.BrokenSyntax {start = 0, end = 2}                 <*> Execution.pipelineByParams Statements.GenerateSeries {start = 0, end = 2}             case result of-              Left (Errors.StatementSessionError _ _ _ _ _ (Errors.ServerStatementError _)) -> pure ()+              Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.ServerStatementError _))) -> pure ()               _ -> expectationFailure $ "Unexpected result: " <> show result          it "Leaves the connection usable" \config -> do@@ -93,7 +93,7 @@                 <*> Execution.pipelineByParams Statements.WrongDecoder {start = 0, end = 2}                 <*> Execution.pipelineByParams Statements.GenerateSeries {start = 0, end = 2}             case result of-              Left (Errors.StatementSessionError _ _ _ _ _ (Errors.UnexpectedColumnTypeStatementError {})) -> pure ()+              Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.UnexpectedColumnTypeStatementError {}))) -> pure ()               _ -> expectationFailure $ "Unexpected result: " <> show result          it "Leaves the connection usable" \config -> do@@ -113,6 +113,49 @@                     (const (pure Nothing))                 Execution.sessionByParams Statements.GenerateSeries {start = 0, end = 0}             shouldBe result (Right [0])++      describe "Effects on the database state" do+        describe "With query error" do+          it "Rolls back the statements preceding the failure and skips the following ones" \config -> do+            Scripts.onPreparableConnection config \connection -> do+              varname <- Execution.generateVarname+              let setVar value =+                    Execution.pipelineByParams+                      Statements.SetConfig {name = varname, value, local = False}+              result <-+                (Connection.use connection . Session.pipeline)+                  $ (,,)+                  <$> setVar "before"+                  <*> Execution.pipelineByParams Statements.BrokenSyntax {start = 0, end = 2}+                  <*> setVar "after"+              case result of+                Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.ServerStatementError _))) -> pure ()+                _ -> expectationFailure $ "Unexpected result: " <> show result+              settingResult <-+                Connection.use connection+                  $ Execution.sessionByParams Statements.CurrentSetting {name = varname, missingOk = True}+              shouldBe settingResult (Right (Just ""))++        describe "With decoding error" do+          it "Keeps the effects of all statements" \config -> do+            Scripts.onPreparableConnection config \connection -> do+              varname <- Execution.generateVarname+              let setVar value =+                    Execution.pipelineByParams+                      Statements.SetConfig {name = varname, value, local = False}+              result <-+                (Connection.use connection . Session.pipeline)+                  $ (,,)+                  <$> setVar "before"+                  <*> Execution.pipelineByParams Statements.WrongDecoder {start = 0, end = 2}+                  <*> setVar "after"+              case result of+                Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.UnexpectedColumnTypeStatementError {}))) -> pure ()+                _ -> expectationFailure $ "Unexpected result: " <> show result+              settingResult <-+                Connection.use connection+                  $ Execution.sessionByParams Statements.CurrentSetting {name = varname, missingOk = True}+              shouldBe settingResult (Right (Just "after"))    describe "Failing pipeline" do     it "Does not cause errors in the next pipeline" \config -> do
+ src/library-tests/Integration/Sharing/Session/OnLibpqConnection/DirtyReturnCleanupSpec.hs view
@@ -0,0 +1,89 @@+module Integration.Sharing.Session.OnLibpqConnection.DirtyReturnCleanupSpec (spec) where++import Hasql.Connection qualified as Connection+import Hasql.Errors qualified as Errors+import Hasql.Session qualified as Session+import Helpers.Dsls.Execution qualified as Execution+import Helpers.Scripts qualified as Scripts+import Helpers.Statements.SelectOne qualified as Statements.SelectOne+import Pqi qualified as Pq+import Prelude+import Test.Hspec++-- | 'Session.onLibpqConnection' is a low-level escape hatch: whatever state+-- the supplied action leaves the raw libpq connection in is adopted+-- verbatim, on every path, with no check anywhere inside+-- "Hasql.Engine.Contexts.Session" or "Hasql.Comms.Roundtrip". A well-behaved+-- action would never leave the connection mid-pipeline, but nothing stops a+-- buggy one from doing so, and once it has, every subsequent operation on+-- the connection is refused by libpq until something takes it out of+-- pipeline mode.+--+-- Nothing repairs that for the caller. The driver has no way of telling a+-- connection the escape hatch quietly broke from one it left clean, and the+-- one repair it could attempt - pushing a Sync - would flush and commit+-- whatever the caller had queued. So the contract is that the escape hatch+-- restores what it breaks, and reports 'Errors.ConnectionUseError' when it+-- cannot.+--+-- These drive the connection into exactly that state directly, entering+-- pipeline mode on the raw handle without leaving it, and pin both halves:+-- the reported case is finished on the spot, and the unreported one cannot+-- poison a pool for long either, because the first operation libpq refuses+-- on it finishes it too.+spec :: SpecWith Scripts.ScopeParams+spec = do+  describe "onLibpqConnection leaving the raw connection in pipeline mode" do+    describe "Reporting a connection error" do+      it "Gets the connection finished rather than repaired" \config -> do+        Scripts.onPreparableConnection config \connection -> do+          result <- Connection.use connection (dirtyReturn (Errors.ConnectionUseError "Simulated failure"))+          case result of+            Left (Errors.ConnectionUseError _) -> pure ()+            _ -> expectationFailure ("Unexpected result: " <> show result)++          followUp <-+            Connection.use connection+              $ Execution.sessionByParams Statements.SelectOne.SelectOne+          case followUp of+            Left (Errors.ConnectionUseError _) -> pure ()+            _ -> expectationFailure ("Unexpected follow-up result: " <> show followUp)++    describe "Reporting an error that says nothing about the connection" do+      it "Leaves the connection exactly as the escape hatch left it" \config -> do+        Scripts.onPreparableConnection config \connection -> do+          result <-+            Connection.use connection+              $ dirtyReturn (Errors.SessionUseError (Errors.MissingTypesSessionError mempty))+          case result of+            Left (Errors.SessionUseError (Errors.MissingTypesSessionError _)) -> pure ()+            _ -> expectationFailure ("Unexpected result: " <> show result)++          -- Nothing repaired it: the mode the escape hatch turned on is+          -- still on. That is the whole contract - the driver finishes+          -- connections it has given up on and touches nothing else, so an+          -- error that says nothing about the connection leaves it to the+          -- caller.+          --+          -- Which is survivable here only because an empty pipeline mode+          -- happens to be harmless to hasql's own operations: libpq's+          -- enterPipelineMode succeeds with no action when the mode is+          -- already on, so the next pipeline adopts it and leaves it off+          -- again on the way out. An escape hatch that left commands queued+          -- or results undrained would not be so lucky, which is why the+          -- documented advice is to restore what you break.+          status <-+            Connection.use connection+              $ Session.onLibpqConnection \pqConnection -> do+                status <- Pq.pipelineStatus pqConnection+                pure (Right status, pqConnection)+          status `shouldNotBe` Right Pq.PipelineOff++-- | Enter pipeline mode on the raw connection and report the given error+-- without leaving it.+dirtyReturn :: Errors.UseError -> Session.Session ()+dirtyReturn err =+  Session.onLibpqConnection \pqConnection -> do+    entered <- Pq.enterPipelineMode pqConnection+    entered `shouldBe` True+    pure (Left err, pqConnection)
+ src/library-tests/Integration/Sharing/Session/RecoveredPipelineFailureSpec.hs view
@@ -0,0 +1,70 @@+module Integration.Sharing.Session.RecoveredPipelineFailureSpec (spec) where++import Hasql.Connection qualified as Connection+import Hasql.Errors qualified as Errors+import Hasql.Session qualified as Session+import Helpers.Dsls.Execution qualified as Execution+import Helpers.Scripts qualified as Scripts+import Helpers.Statements qualified as Statements+import Prelude+import Test.Hspec++-- | A pipeline of five statements with 'Statements.TooManyParams' in the+-- middle, so that the batched send of the whole pipeline fails halfway+-- through and leaves the connection in pipeline mode with commands queued+-- behind the refusal.+failingPipeline :: Execution.Pipeline ()+failingPipeline = do+  _ <- goodStatement+  _ <- goodStatement+  _ <- Execution.pipelineByParams Statements.TooManyParams+  _ <- goodStatement+  _ <- goodStatement+  pure ()+  where+    goodStatement =+      Execution.pipelineByParams Statements.GenerateSeries {start = 0, end = 2}++-- | 'Session.Session'\'s 'Control.Monad.Except.MonadError' instance ranges+-- over 'Errors.SessionError' only, so a pipeline send failure -+-- 'Errors.ConnectionUseError' - is not a value 'Control.Monad.Except.catchError'+-- can see. The handler here never runs:+-- '>>=' short-circuits on the fatal error before the handler is reached,+-- exactly as it would for any other 'Left', so the rest of the session+-- never runs against a connection still in pipeline mode, and+-- 'Hasql.Connection.use' gets the fatal error back whole.+--+-- Before the split this was the test of the opposite risk: a session that+-- caught the failure and swallowed it, leaving a serial command blocking+-- forever on results the server was never asked for. That risk is gone by+-- construction now, which is what this spec pins.+spec :: SpecWith Scripts.ScopeParams+spec = do+  describe "Pipeline send failure 'caught' within the session" do+    it "Never reaches the handler, and the rest of the session never runs" \config -> do+      Scripts.onUnpreparableConnection config \connection -> do+        result <-+          Connection.use connection do+            catchError (Session.pipeline failingPipeline) (const (pure ()))+            Execution.sessionByParams Statements.SelectOne++        case result of+          Left (Errors.ConnectionUseError _) -> pure ()+          _ -> expectationFailure ("Unexpected result: " <> show result)++    it "Finishes the connection, not merely reports the error" \config -> do+      Scripts.onUnpreparableConnection config \connection -> do+        result <-+          Connection.use connection do+            catchError (Session.pipeline failingPipeline) (const (pure ()))++        case result of+          Left (Errors.ConnectionUseError _) -> pure ()+          _ -> expectationFailure ("Unexpected result: " <> show result)++        followUp <-+          Connection.use connection+            $ Execution.sessionByParams Statements.SelectOne+        case followUp of+          Left (Errors.ConnectionUseError _) -> pure ()+          _ -> expectationFailure ("Unexpected follow-up result: " <> show followUp)
src/library-tests/Integration/Sharing/Session/ScriptSpec.hs view
@@ -14,7 +14,7 @@     Scripts.onPreparableConnection config \connection -> do       result <- Connection.use connection (Session.script "THIS IS INVALID SQL")       case result of-        Left (Errors.ScriptSessionError _ _) -> pure ()+        Left (Errors.SessionUseError (Errors.ScriptSessionError _ _)) -> pure ()         _ -> expectationFailure $ "Expected ScriptSessionError with ExecutionScriptError, got: " <> show result    it "handles multi-statement DDL scripts with comments" \config -> do
src/library-tests/Integration/Sharing/Session/StatementSpec.hs view
@@ -60,9 +60,30 @@                 (fmap (maybe False (const True)) (Decoders.rowMaybe (Decoders.column (Decoders.nonNullable Decoders.bool))))         result <- Connection.use connection (Session.statement ([3, 7] :: [Int64], "a") statement)         case result of-          Left (Errors.StatementSessionError _ _ _ _ _ (Errors.ServerStatementError _)) -> pure ()+          Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.ServerStatementError _))) -> pure ()           _ -> expectationFailure $ "Unexpected result: " <> show result +    it "reports a statement that genuinely returned no rows as a row-count mismatch, not a lost connection" \config -> do+      -- The server answering with zero rows and the socket going away both+      -- reach `use` through the same absence of a result, and only an+      -- internal flag tells them apart (see `Hasql.Comms.Recv.NoResultsError`).+      -- Getting this wrong either way is a real hazard: reporting a genuine+      -- empty result as `ConnectionUseError` would have pools discard a+      -- perfectly good connection, and reporting a dropped socket as this+      -- recoverable mismatch would have callers keep using a connection that+      -- no longer exists (see "Integration.Sharing.Connection.Use.InterruptionSpec"+      -- and "Integration.Sharing.Pipeline.Statement.SendFailureSpec" for the+      -- latter).+      Scripts.onPreparableConnection config \connection -> do+        result <- Connection.use connection (Session.statement () noRowsStatement)+        case result of+          Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.UnexpectedRowCountStatementError 1 1 0))) -> pure ()+          _ -> expectationFailure ("Unexpected result: " <> show result)++        -- The connection is still fine afterwards.+        followUp <- Connection.use connection (Session.statement (1 :: Int64) echoStatement)+        followUp `shouldBe` Right 1+ echoStatement :: Statement.Statement Int64 Int64 echoStatement =   Statement.preparable@@ -76,4 +97,13 @@   Statement.preparable     "select 1 / $1"     (Encoders.param (Encoders.nonNullable Encoders.int8))+    (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int8)))++-- | Never returns a row, so a `Decoders.singleRow` decoder always sees zero+-- where it expects exactly one.+noRowsStatement :: Statement.Statement () Int64+noRowsStatement =+  Statement.preparable+    "select 1::int8 where false"+    mempty     (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int8)))
src/library-tests/Integration/Sharing/SessionSpec.hs view
@@ -10,21 +10,9 @@  spec :: SpecWith Scripts.ScopeParams spec = do-  it "Does not lose the server-side session state on timeout" \config -> do-    Scripts.onPreparableConnection config \connection -> do-      varname <- Execution.generateVarname-      result <- timeout 50_000 do-        Connection.use connection do-          Execution.sessionByParams (Statements.SetConfig varname "1" False)-          Execution.sessionByParams (Statements.Sleep 0.1)--      result `shouldBe` Nothing--      result <- Connection.use connection do-        Execution.sessionByParams (Statements.CurrentSetting varname True)--      result `shouldBe` Right (Just "1")-+  -- Note the guarantee this does not extend to: an interruption takes the+  -- connection with it, and server-side session state goes with the+  -- connection. See "Integration.Sharing.Connection.Use.InterruptionSpec".   it "Does not lose the server-side session state between uses" \config -> do     Scripts.onPreparableConnection config \connection -> do       varname <- Execution.generateVarname
src/library-tests/Integration/Sharing/SpecHook.hs view
@@ -1,6 +1,7 @@ -- Docs: https://hspec.github.io/hspec-discover.html module Integration.Sharing.SpecHook where +import Helpers.PostgresContainer qualified as PostgresContainer import Helpers.Scripts qualified as Scripts import Pqi qualified import Prelude@@ -18,7 +19,7 @@       describe (toList tagName)         $ aroundAllWith           ( \action adapter ->-              TestcontainersPostgresql.run+              PostgresContainer.run                 TestcontainersPostgresql.Config                   { tagName,                     auth = TestcontainersPostgresql.CredentialsAuth "postgres" "postgres",
+ src/library-tests/Integration/Sharing/Statement/PreparedStatementNamingSpec.hs view
@@ -0,0 +1,87 @@+-- |+-- The names hasql prepares statements under, as the server sees them.+--+-- The unit tests in @Hasql.ConnectionState.StatementCacheSpec@ pin the naming+-- function itself. This pins the property that motivates it: the name is a+-- pure function of the statement, so it is the same on every connection.+-- PgBouncer's transaction pooling depends on that — it is how it recognises+-- that a statement is already prepared on whichever server connection a+-- transaction lands on — and a driver naming statements per connection keeps+-- working fine against a bare Postgres, so nothing else here would notice the+-- property regressing.+module Integration.Sharing.Statement.PreparedStatementNamingSpec (spec) where++import Data.Text qualified as Text+import Hasql.Connection qualified as Connection+import Hasql.Decoders qualified as Decoders+import Hasql.Encoders qualified as Encoders+import Hasql.Session qualified as Session+import Hasql.Statement qualified as Statement+import Helpers.Dsls.Execution qualified as Execution+import Helpers.Scripts qualified as Scripts+import Helpers.Statements qualified as Statements+import Prelude+import Test.Hspec++spec :: SpecWith Scripts.ScopeParams+spec =+  describe "Prepared statement naming" do+    it "gives the same statement the same name on different connections" \config -> do+      firstNames <- Scripts.onPreparableConnection config \connection -> do+        result <- Connection.use connection (Session.statement () selectFortyTwo)+        result `shouldBe` Right 42+        selectNames connection+      secondNames <- Scripts.onPreparableConnection config \connection -> do+        result <- Connection.use connection (Session.statement () selectFortyTwo)+        result `shouldBe` Right 42+        selectNames connection+      secondNames `shouldBe` firstNames++    it "gives different names to the same SQL under different parameter types" \config -> do+      Scripts.onPreparableConnection config \connection -> do+        int4Result <- Connection.use connection (Session.statement 1 selectInt4Param)+        int4Result `shouldBe` Right 1+        textResult <- Connection.use connection (Session.statement "a" selectTextParam)+        textResult `shouldBe` Right "a"+        names <- selectNames connection+        -- Two server-side plans, because the parameter OIDs are part of the+        -- statement's identity. Collapsing them onto one name is a 42P05.+        length names `shouldBe` 2++    it "names statements with an identifier-safe prefix" \config -> do+      Scripts.onPreparableConnection config \connection -> do+        _ <- Connection.use connection (Session.statement () selectFortyTwo)+        names <- selectNames connection+        -- Unquoted-legal and greppable in pg_prepared_statements and in a+        -- pooler's logs, and it cannot collide with a user's own PREPARE.+        all (Text.isPrefixOf "hasql_") names `shouldBe` True++selectNames :: Connection.Connection -> IO [Text]+selectNames connection = do+  result <-+    Connection.use connection+      $ Execution.sessionByParams Statements.SelectPreparedStatementNames+  case result of+    Right names -> pure names+    Left err -> fail ("Failed to read prepared statement names: " <> show err)++selectFortyTwo :: Statement.Statement () Int32+selectFortyTwo =+  Statement.preparable+    "select 42"+    mempty+    (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int4)))++selectInt4Param :: Statement.Statement Int32 Int32+selectInt4Param =+  Statement.preparable+    "select $1"+    (Encoders.param (Encoders.nonNullable Encoders.int4))+    (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int4)))++selectTextParam :: Statement.Statement Text Text+selectTextParam =+  Statement.preparable+    "select $1"+    (Encoders.param (Encoders.nonNullable Encoders.text))+    (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.text)))
src/library-tests/Integration/Sharing/StatementSpec.hs view
@@ -1,6 +1,9 @@ module Integration.Sharing.StatementSpec (spec) where  import Data.Either+import Data.Text qualified as Text+import Data.Vector qualified as Vector+import Data.Vector.Unboxed qualified as UnboxedVector import Hasql.Connection qualified as Connection import Hasql.Decoders qualified as Decoders import Hasql.Encoders qualified as Encoders@@ -87,6 +90,29 @@           result <- Connection.use connection (Session.statement () statement)           result `shouldBe` Right [(1 :: Int64, 2 :: Int64), (3, 4), (5, 6)] +    describe "Vector decoding" do+      it "decodes into a boxed vector correctly" \config -> do+        Scripts.onPreparableConnection config \connection -> do+          let statement :: Statement.Statement () (Vector.Vector (Int64, Int64))+              statement =+                Statement.preparable+                  "values (1 :: int8, 2 :: int8), (3,4), (5,6)"+                  mempty+                  (Decoders.rowVector ((,) <$> (Decoders.column (Decoders.nonNullable Decoders.int8)) <*> (Decoders.column (Decoders.nonNullable Decoders.int8))))+          result <- Connection.use connection (Session.statement () statement)+          result `shouldBe` Right (Vector.fromList [(1, 2), (3, 4), (5, 6)])++      it "decodes into an unboxed vector correctly" \config -> do+        Scripts.onPreparableConnection config \connection -> do+          let statement :: Statement.Statement () (UnboxedVector.Vector (Int64, Int64))+              statement =+                Statement.preparable+                  "values (1 :: int8, 2 :: int8), (3,4), (5,6)"+                  mempty+                  (Decoders.rowVector ((,) <$> (Decoders.column (Decoders.nonNullable Decoders.int8)) <*> (Decoders.column (Decoders.nonNullable Decoders.int8))))+          result <- Connection.use connection (Session.statement () statement)+          result `shouldBe` Right (UnboxedVector.fromList [(1, 2), (3, 4), (5, 6)])+     describe "IN simulation" do       it "works with arrays" \config -> do         Scripts.onPreparableConnection config \connection -> do@@ -265,7 +291,7 @@             result2 <- Connection.use connection do               Session.pipeline (Pipeline.statement () brokenStatement)             case result2 of-              Left (Errors.StatementSessionError _ _ _ _ _ (Errors.ServerStatementError (Errors.ServerError "42601" _ _ _ _))) ->+              Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.ServerStatementError (Errors.ServerError "42601" _ _ _ _)))) ->                 pure ()               Left other ->                 expectationFailure ("Unexpected error on second run: " <> show other)@@ -371,7 +397,7 @@                   <*> Pipeline.statement () broken                   <*> Pipeline.statement () ok2             case result2 of-              Left (Errors.StatementSessionError _ _ _ _ _ (Errors.ServerStatementError (Errors.ServerError "42601" _ _ _ _))) ->+              Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.ServerStatementError (Errors.ServerError "42601" _ _ _ _)))) ->                 pure ()               Left other ->                 expectationFailure ("Unexpected error on second run: " <> show other)@@ -390,10 +416,134 @@               Right val -> val `shouldBe` 2               Left err -> expectationFailure ("Unexpected error on standalone ok2: " <> show err) +    describe "42P05 (prepared statement name collision)" do+      -- Collision is induced without a pooler, because prepared statement+      -- names are content-addressed and thus deterministic: discover the+      -- name hasql gives a statement on a scratch connection, then+      -- hand-PREPARE that same name (with the same SQL) on the connection+      -- under test before letting hasql PARSE it. hasql's own PARSE then+      -- collides with a statement that is, by construction, identical to+      -- the one it was about to submit.+      let collidingStatement =+            Statement.preparable+              "select 42 :: int4"+              mempty+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int4)))++      describe "Session" do+        it "is reported as 42P05 and the cache mapping survives" \config -> do+          name <- discoverPreparedStatementName config collidingStatement+          Scripts.onPreparableConnection config \connection -> do+            seedNameCollision connection name (Statement.toSql collidingStatement)++            -- The colliding execution fails, carrying 42P05.+            result1 <- Connection.use connection (Session.statement () collidingStatement)+            case result1 of+              Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.ServerStatementError (Errors.ServerError "42P05" _ _ _ _)))) ->+                pure ()+              other ->+                expectationFailure ("Expected a 42P05 ServerError, got: " <> show other)++            -- The same statement then succeeds, warm, without another PARSE.+            result2 <- Connection.use connection (Session.statement () collidingStatement)+            result2 `shouldBe` Right 42++            -- The server still has exactly one statement under that name:+            -- hasql did not re-prepare it under a fresh name.+            names <- selectPreparedStatementNames connection+            length (filter (== name) names) `shouldBe` 1++      describe "Pipeline" do+        it "is reported as 42P05 and the cache mapping survives" \config -> do+          name <- discoverPreparedStatementName config collidingStatement+          Scripts.onPreparableConnection config \connection -> do+            seedNameCollision connection name (Statement.toSql collidingStatement)++            result1 <- Connection.use connection (Session.pipeline (Pipeline.statement () collidingStatement))+            case result1 of+              Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.ServerStatementError (Errors.ServerError "42P05" _ _ _ _)))) ->+                pure ()+              other ->+                expectationFailure ("Expected a 42P05 ServerError, got: " <> show other)++            result2 <- Connection.use connection (Session.pipeline (Pipeline.statement () collidingStatement))+            result2 `shouldBe` Right 42++            names <- selectPreparedStatementNames connection+            length (filter (== name) names) `shouldBe` 1++        it "a collision at the first statement in a pipeline still commits its own mapping" \config -> do+          let ok = Statement.preparable "select 1 :: int4" mempty (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int4)))+          name <- discoverPreparedStatementName config collidingStatement+          Scripts.onPreparableConnection config \connection -> do+            seedNameCollision connection name (Statement.toSql collidingStatement)++            result1 <-+              Connection.use connection do+                Session.pipeline do+                  (,)+                    <$> Pipeline.statement () collidingStatement+                    <*> Pipeline.statement () ok+            case result1 of+              Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.ServerStatementError (Errors.ServerError "42P05" _ _ _ _)))) ->+                pure ()+              other ->+                expectationFailure ("Expected a 42P05 ServerError, got: " <> show other)++            -- Re-running the same pipeline succeeds end-to-end: the+            -- colliding statement's mapping was kept, so it needs no PARSE+            -- this time either.+            result2 <-+              Connection.use connection do+                Session.pipeline do+                  (,)+                    <$> Pipeline.statement () collidingStatement+                    <*> Pipeline.statement () ok+            result2 `shouldBe` Right (42, 1)+     describe "Decoder compatibility cache" $ parallel do       decoderCompatibilityCacheByExecutor "Session" (Session.statement ())       decoderCompatibilityCacheByExecutor "Pipeline" (Session.pipeline . Pipeline.statement ()) +-- | The name hasql gives a statement, discovered by running it once on a+-- scratch connection and reading it back out of @pg_prepared_statements@.+-- Names are content-addressed, so this is the same name any other+-- connection will compute for the same statement.+discoverPreparedStatementName :: Scripts.ScopeParams -> Statement.Statement () a -> IO Text+discoverPreparedStatementName config stmt =+  Scripts.onPreparableConnection config \connection -> do+    _ <- Connection.use connection (Session.statement () stmt)+    names <- selectPreparedStatementNames connection+    case names of+      [name] -> pure name+      _ -> fail ("Expected exactly one prepared statement on the scratch connection, got: " <> show names)++-- | Read prepared statement names via a plain (non-pipelined) statement, so+-- this can safely be used right after a pipeline that errored.+selectPreparedStatementNames :: Connection.Connection -> IO [Text]+selectPreparedStatementNames connection = do+  result <-+    Connection.use connection+      $ Session.statement+        ()+        ( Statement.unpreparable+            "select name from pg_prepared_statements order by name"+            mempty+            (Decoders.rowList (Decoders.column (Decoders.nonNullable Decoders.text)))+        )+  case result of+    Right names -> pure names+    Left err -> fail ("Failed to read prepared statement names: " <> show err)++-- | Hand-prepare a name on a connection out-of-band, so that hasql's own+-- @Parse@ of the same statement on that connection collides with it (42P05).+seedNameCollision :: Connection.Connection -> Text -> Text -> IO ()+seedNameCollision connection name statementSql = do+  result <- Connection.use connection (Session.script (Text.concat ["PREPARE ", name, " AS ", statementSql]))+  case result of+    Right () -> pure ()+    Left err -> fail ("Failed to seed name collision: " <> show err)+ decoderCompatibilityCacheByExecutor ::   Text ->   (forall a. (Show a) => Statement.Statement () a -> Session.Session a) ->@@ -427,7 +577,7 @@         shouldBe firstResult (Right (1, "text"))         secondResult <- Connection.use connection (executor mismatchingStatement)         case secondResult of-          Left (Errors.StatementSessionError _ _ _ _ _ (Errors.UnexpectedColumnTypeStatementError column expected actual)) -> do+          Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.UnexpectedColumnTypeStatementError column expected actual))) -> do             shouldBe column 1             (expected, actual) `shouldBe` (20, 25)           Left err ->
+ src/library-tests/Pure/Connection/AcquireSpec.hs view
@@ -0,0 +1,286 @@+module Pure.Connection.AcquireSpec (spec) where++import Hasql.Connection qualified as Connection+import Hasql.Errors qualified as Errors+import Pqi qualified as Pq+import Prelude+import Test.Hspec++spec :: Spec+spec = do+  describe "acquire" do+    it "reports ConnectionAcquireError and finishes the connection when the status check fails without needing a password" do+      finishedRef <- newIORef False+      let adapter =+            fakeAdapter+              ( (fakeConnection finishedRef Pq.ConnectionBad (Just "could not connect to server: Connection refused") 180000)+                  { Pq.connectionNeedsPassword = pure False+                  }+              )+      result <- Connection.acquire adapter mempty+      case result of+        Left (Errors.ConnectionAcquireError _) -> pure ()+        Left err -> expectationFailure ("Expected ConnectionAcquireError, got: " <> show err)+        Right _ -> expectationFailure "Expected connection to fail, but it succeeded"+      readIORef finishedRef `shouldReturn` True++    it "reports ConnectionPasswordRequiredAcquireError and finishes the connection when the status check fails needing a password" do+      finishedRef <- newIORef False+      let adapter =+            fakeAdapter+              ( (fakeConnection finishedRef Pq.ConnectionBad (Just "no password supplied") 180000)+                  { Pq.connectionNeedsPassword = pure True+                  }+              )+      result <- Connection.acquire adapter mempty+      case result of+        Left (Errors.ConnectionPasswordRequiredAcquireError _) -> pure ()+        Left err -> expectationFailure ("Expected ConnectionPasswordRequiredAcquireError, got: " <> show err)+        Right _ -> expectationFailure "Expected connection to fail, but it succeeded"+      readIORef finishedRef `shouldReturn` True++    it "reports VersionTooOldAcquireError and finishes the connection when the server version check fails" do+      finishedRef <- newIORef False+      let adapter =+            fakeAdapter+              ( fakeConnection+                  finishedRef+                  Pq.ConnectionOk+                  Nothing+                  80000+              )+      result <- Connection.acquire adapter mempty+      case result of+        Left (Errors.VersionTooOldAcquireError 8 0 0) -> pure ()+        Left err -> expectationFailure ("Expected VersionTooOldAcquireError 8 0 0, got: " <> show err)+        Right _ -> expectationFailure "Expected connection to fail, but it succeeded"+      readIORef finishedRef `shouldReturn` True++    it "does not finish the pq connection when acquisition succeeds" do+      finishedRef <- newIORef False+      let adapter =+            fakeAdapter+              ( (fakeConnection finishedRef Pq.ConnectionOk Nothing 180000)+                  { Pq.exec = \_ -> pure (Just (fakeResult Pq.CommandOk Nothing))+                  }+              )+      result <- Connection.acquire adapter mempty+      case result of+        Right _ -> pure ()+        Left err -> expectationFailure ("Expected acquire to succeed, got: " <> show err)+      readIORef finishedRef `shouldReturn` False++    it "finishes the pq connection when the status check throws an exception" do+      finishedRef <- newIORef False+      let brokenConnection =+            (fakeConnection finishedRef Pq.ConnectionOk Nothing 180000)+              { Pq.status = throwIO (userError "boom")+              }+          adapter = fakeAdapter brokenConnection+      result <- try @IOException (Connection.acquire adapter mempty)+      case result of+        Left _ -> pure ()+        Right _ -> expectationFailure "Expected acquire to propagate the exception"+      readIORef finishedRef `shouldReturn` True++    it "reports InitializationConnectionLossAcquireError and finishes the connection when the session-init exec returns no result" do+      finishedRef <- newIORef False+      let brokenConnection =+            (fakeConnection finishedRef Pq.ConnectionOk Nothing 180000)+              { Pq.exec = \_ -> pure Nothing,+                Pq.errorMessage = pure (Just "server closed the connection")+              }+          adapter = fakeAdapter brokenConnection+      result <- Connection.acquire adapter mempty+      case result of+        Left (Errors.InitializationConnectionLossAcquireError _) -> pure ()+        Left err -> expectationFailure ("Expected InitializationConnectionLossAcquireError, got: " <> show err)+        Right _ -> expectationFailure "Expected connection to fail, but it succeeded"+      readIORef finishedRef `shouldReturn` True++    it "reports InitializationConnectionLossAcquireError and finishes the connection when the session-init exec reports a non-CommandOk status with no SQLSTATE" do+      finishedRef <- newIORef False+      let failedResult =+            fakeResult Pq.FatalError (Just "permission denied for SET")+          brokenConnection =+            (fakeConnection finishedRef Pq.ConnectionOk Nothing 180000)+              { Pq.exec = \_ -> pure (Just failedResult)+              }+          adapter = fakeAdapter brokenConnection+      result <- Connection.acquire adapter mempty+      case result of+        Left (Errors.InitializationConnectionLossAcquireError msg) -> msg `shouldBe` "permission denied for SET"+        Left err -> expectationFailure ("Expected InitializationConnectionLossAcquireError, got: " <> show err)+        Right _ -> expectationFailure "Expected connection to fail, but it succeeded"+      readIORef finishedRef `shouldReturn` True++    it "reports InitializationServerErrorAcquireError and finishes the connection when the session-init exec reports a non-CommandOk status with a SQLSTATE" do+      finishedRef <- newIORef False+      let failedResult =+            (fakeResult Pq.FatalError (Just "permission denied for SET"))+              { Pq.resultErrorField = \case+                  Pq.DiagSqlstate -> pure (Just "42501")+                  Pq.DiagMessagePrimary -> pure (Just "permission denied for SET")+                  Pq.DiagMessageDetail -> pure Nothing+                  Pq.DiagMessageHint -> pure Nothing+                  Pq.DiagStatementPosition -> pure Nothing+                  _ -> pure Nothing+              }+          brokenConnection =+            (fakeConnection finishedRef Pq.ConnectionOk Nothing 180000)+              { Pq.exec = \_ -> pure (Just failedResult)+              }+          adapter = fakeAdapter brokenConnection+      result <- Connection.acquire adapter mempty+      case result of+        Left (Errors.InitializationServerErrorAcquireError (Errors.ServerError "42501" "permission denied for SET" Nothing Nothing Nothing)) -> pure ()+        Left err -> expectationFailure ("Expected InitializationServerErrorAcquireError, got: " <> show err)+        Right _ -> expectationFailure "Expected connection to fail, but it succeeded"+      readIORef finishedRef `shouldReturn` True++    it "succeeds when the session-init exec reports a CommandOk status" do+      finishedRef <- newIORef False+      let okResult =+            fakeResult Pq.CommandOk Nothing+          adapter =+            fakeAdapter+              ( (fakeConnection finishedRef Pq.ConnectionOk Nothing 180000)+                  { Pq.exec = \_ -> pure (Just okResult)+                  }+              )+      result <- Connection.acquire adapter mempty+      case result of+        Right _ -> pure ()+        Left err -> expectationFailure ("Expected acquire to succeed, got: " <> show err)+      readIORef finishedRef `shouldReturn` False++fakeAdapter :: Pq.Connection -> Pq.Adapter+fakeAdapter connection =+  Pq.Adapter+    { name = "fake",+      connectdb = \_ -> pure connection,+      connectStart = \_ -> unimplemented "connectStart",+      newNullConnection = unimplementedIO "newNullConnection",+      unescapeBytea = \_ -> unimplemented "unescapeBytea",+      resStatus = \_ -> unimplemented "resStatus"+    }++fakeConnection :: IORef Bool -> Pq.ConnStatus -> Maybe ByteString -> Int -> Pq.Connection+fakeConnection finishedRef connStatus connErrorMessage connServerVersion =+  Pq.Connection+    { connectPoll = unimplementedIO "connectPoll",+      isNullConnection = False,+      finish = writeIORef finishedRef True,+      reset = unimplementedIO "reset",+      resetStart = unimplementedIO "resetStart",+      resetPoll = unimplementedIO "resetPoll",+      db = unimplementedIO "db",+      user = unimplementedIO "user",+      pass = unimplementedIO "pass",+      host = unimplementedIO "host",+      port = unimplementedIO "port",+      options = unimplementedIO "options",+      status = pure connStatus,+      transactionStatus = unimplementedIO "transactionStatus",+      parameterStatus = \_ -> unimplemented "parameterStatus",+      protocolVersion = unimplementedIO "protocolVersion",+      serverVersion = pure connServerVersion,+      errorMessage = pure connErrorMessage,+      socket = unimplementedIO "socket",+      backendPID = unimplementedIO "backendPID",+      connectionNeedsPassword = pure False,+      connectionUsedPassword = unimplementedIO "connectionUsedPassword",+      exec = \_ -> pure Nothing,+      execParams = \_ _ _ -> unimplemented "execParams",+      prepare = \_ _ _ -> unimplemented "prepare",+      execPrepared = \_ _ _ -> unimplemented "execPrepared",+      describePrepared = \_ -> unimplemented "describePrepared",+      describePortal = \_ -> unimplemented "describePortal",+      escapeStringConn = \_ -> unimplemented "escapeStringConn",+      escapeByteaConn = \_ -> unimplemented "escapeByteaConn",+      escapeIdentifier = \_ -> unimplemented "escapeIdentifier",+      sendQuery = \_ -> unimplemented "sendQuery",+      sendQueryParams = \_ _ _ -> unimplemented "sendQueryParams",+      sendPrepare = \_ _ _ -> unimplemented "sendPrepare",+      sendQueryPrepared = \_ _ _ -> unimplemented "sendQueryPrepared",+      sendDescribePrepared = \_ -> unimplemented "sendDescribePrepared",+      sendDescribePortal = \_ -> unimplemented "sendDescribePortal",+      getResult = unimplementedIO "getResult",+      consumeInput = unimplementedIO "consumeInput",+      isBusy = unimplementedIO "isBusy",+      setnonblocking = \_ -> unimplemented "setnonblocking",+      isnonblocking = unimplementedIO "isnonblocking",+      setSingleRowMode = unimplementedIO "setSingleRowMode",+      flush = unimplementedIO "flush",+      pipelineStatus = unimplementedIO "pipelineStatus",+      enterPipelineMode = unimplementedIO "enterPipelineMode",+      exitPipelineMode = unimplementedIO "exitPipelineMode",+      pipelineSync = unimplementedIO "pipelineSync",+      sendFlushRequest = unimplementedIO "sendFlushRequest",+      getCancel = unimplementedIO "getCancel",+      notifies = unimplementedIO "notifies",+      disableNoticeReporting = unimplementedIO "disableNoticeReporting",+      enableNoticeReporting = unimplementedIO "enableNoticeReporting",+      getNotice = unimplementedIO "getNotice",+      putCopyData = \_ -> unimplemented "putCopyData",+      putCopyEnd = \_ -> unimplemented "putCopyEnd",+      getCopyData = \_ -> unimplemented "getCopyData",+      loCreat = unimplementedIO "loCreat",+      loCreate = \_ -> unimplemented "loCreate",+      loImport = \_ -> unimplemented "loImport",+      loImportWithOid = \_ _ -> unimplemented "loImportWithOid",+      loExport = \_ _ -> unimplemented "loExport",+      loOpen = \_ _ -> unimplemented "loOpen",+      loWrite = \_ _ -> unimplemented "loWrite",+      loRead = \_ _ -> unimplemented "loRead",+      loSeek = \_ _ _ -> unimplemented "loSeek",+      loTell = \_ -> unimplemented "loTell",+      loTruncate = \_ _ -> unimplemented "loTruncate",+      loClose = \_ -> unimplemented "loClose",+      loUnlink = \_ -> unimplemented "loUnlink",+      clientEncoding = unimplementedIO "clientEncoding",+      setClientEncoding = \_ -> unimplemented "setClientEncoding",+      setErrorVerbosity = \_ -> unimplemented "setErrorVerbosity"+    }++fakeResult :: Pq.ExecStatus -> Maybe ByteString -> Pq.Result+fakeResult status errorMessage =+  Pq.Result+    { resultStatus = pure status,+      resultErrorMessage = pure errorMessage,+      resultErrorField = \_ -> pure Nothing,+      unsafeFreeResult = unimplementedIO "unsafeFreeResult",+      ntuples = unimplementedIO "ntuples",+      nfields = unimplementedIO "nfields",+      fname = \_ -> unimplemented "fname",+      fnumber = \_ -> unimplemented "fnumber",+      ftable = \_ -> unimplemented "ftable",+      ftablecol = \_ -> unimplemented "ftablecol",+      fformat = \_ -> unimplemented "fformat",+      ftype = \_ -> unimplemented "ftype",+      fmod = \_ -> unimplemented "fmod",+      fsize = \_ -> unimplemented "fsize",+      getvalue = \_ _ -> unimplemented "getvalue",+      getvalue' = \_ _ -> unimplemented "getvalue'",+      getisnull = \_ _ -> unimplemented "getisnull",+      getlength = \_ _ -> unimplemented "getlength",+      nparams = unimplementedIO "nparams",+      paramtype = \_ -> unimplemented "paramtype",+      cmdStatus = unimplementedIO "cmdStatus",+      cmdTuples = unimplementedIO "cmdTuples"+    }++-- | Marks a t'Pq.Connection'\/t'Pq.Adapter' field this test double doesn't+-- implement. Forcing it fails the test with a clear message instead of a+-- pattern-match error, pointing at exactly which unexpected call happened.+unimplemented :: String -> a+unimplemented fieldName =+  error ("Pure.Connection.AcquireSpec: fake connection field not implemented: " <> fieldName)++-- | Like 'unimplemented', but for @IO@-typed fields. Since @pqi@'s records+-- use @StrictData@, a bare 'unimplemented' in such a field would blow up the+-- moment the record is constructed, not when the field is actually run.+-- Wrapping it in 'pure' defers evaluation to the point of use.+unimplementedIO :: String -> IO a+unimplementedIO fieldName =+  pure (unimplemented fieldName)
src/library-tests/Pure/ErrorsSpec.hs view
@@ -7,39 +7,66 @@  spec :: Spec spec = do-  describe "ConnectionError" do+  describe "AcquireError" do     describe "toMessage" do-      it "renders NetworkingConnectionError" do-        (Errors.toMessage (Errors.NetworkingConnectionError "timeout"))-          `shouldBe` "Networking error while connecting to the database"+      it "renders ConnectionAcquireError" do+        (Errors.toMessage (Errors.ConnectionAcquireError "timeout"))+          `shouldBe` "Failed to establish a connection to the database" -      it "renders AuthenticationConnectionError" do-        (Errors.toMessage (Errors.AuthenticationConnectionError "invalid password"))-          `shouldBe` "Authentication error while connecting to the database"+      it "renders ConnectionPasswordRequiredAcquireError" do+        (Errors.toMessage (Errors.ConnectionPasswordRequiredAcquireError "no password supplied"))+          `shouldBe` "The server demanded a password and none was available" +      it "renders VersionTooOldAcquireError" do+        (Errors.toMessage (Errors.VersionTooOldAcquireError 8 0 0))+          `shouldBe` "Server version is too old"++      it "renders InitializationConnectionLossAcquireError" do+        (Errors.toMessage (Errors.InitializationConnectionLossAcquireError "server closed the connection"))+          `shouldBe` "Connection lost while initializing the session"++      it "renders InitializationServerErrorAcquireError with the wrapped message" do+        (Errors.toMessage (Errors.InitializationServerErrorAcquireError (Errors.ServerError "42501" "permission denied" Nothing Nothing Nothing)))+          `shouldBe` "Server error"+     describe "toDetails" do-      it "includes reason for NetworkingConnectionError" do-        (Errors.toDetails (Errors.NetworkingConnectionError "connection timeout"))+      it "includes reason for ConnectionAcquireError" do+        (Errors.toDetails (Errors.ConnectionAcquireError "connection timeout"))           `shouldBe` [("reason", "connection timeout")] -    describe "isTransient" do-      it "NetworkingConnectionError is transient" do-        (Errors.isTransient (Errors.NetworkingConnectionError "timeout"))-          `shouldBe` True+      it "includes reason for ConnectionPasswordRequiredAcquireError" do+        (Errors.toDetails (Errors.ConnectionPasswordRequiredAcquireError "no password supplied"))+          `shouldBe` [("reason", "no password supplied")] -      it "AuthenticationConnectionError is not transient" do-        (Errors.isTransient (Errors.AuthenticationConnectionError "invalid password"))-          `shouldBe` False+      it "includes the version for VersionTooOldAcquireError" do+        (Errors.toDetails (Errors.VersionTooOldAcquireError 8 1 5))+          `shouldBe` [("version", "8.1.5"), ("minimumVersion", "9.0.0")] +      it "includes reason for InitializationConnectionLossAcquireError" do+        (Errors.toDetails (Errors.InitializationConnectionLossAcquireError "server closed the connection"))+          `shouldBe` [("reason", "server closed the connection")]++      it "includes the wrapped server error's details for InitializationServerErrorAcquireError" do+        (Errors.toDetails (Errors.InitializationServerErrorAcquireError (Errors.ServerError "42501" "permission denied" Nothing Nothing Nothing)))+          `shouldBe` [("code", "42501"), ("message", "permission denied")]+     describe "toSqlState" do-      it "is Nothing, since connection errors carry no server code" do-        (Errors.toSqlState (Errors.NetworkingConnectionError "timeout"))+      it "is Nothing for ConnectionAcquireError" do+        (Errors.toSqlState (Errors.ConnectionAcquireError "timeout"))           `shouldBe` Nothing +      it "is Nothing for InitializationConnectionLossAcquireError" do+        (Errors.toSqlState (Errors.InitializationConnectionLossAcquireError "connection lost"))+          `shouldBe` Nothing++      it "digs the code out of InitializationServerErrorAcquireError" do+        (Errors.toSqlState (Errors.InitializationServerErrorAcquireError (Errors.ServerError "42501" "permission denied" Nothing Nothing Nothing)))+          `shouldBe` Just "42501"+     describe "toDetailedText" do-      it "renders NetworkingConnectionError with details" do-        (Errors.toDetailedText (Errors.NetworkingConnectionError "connection refused"))-          `shouldBe` "Networking error while connecting to the database\n\+      it "renders ConnectionAcquireError with details" do+        (Errors.toDetailedText (Errors.ConnectionAcquireError "connection refused"))+          `shouldBe` "Failed to establish a connection to the database\n\                      \  reason: connection refused"    describe "ServerError" do@@ -178,10 +205,6 @@         (Errors.toMessage (Errors.StatementSessionError 1 0 "SELECT 1" [] True (Errors.UnexpectedRowCountStatementError 1 1 0)))           `shouldBe` "Unexpected number of rows" -      it "renders ConnectionSessionError" do-        (Errors.toMessage (Errors.ConnectionSessionError "connection lost"))-          `shouldBe` "Connection error"-       it "renders MissingTypesSessionError" do         (Errors.toMessage (Errors.MissingTypesSessionError (HashSet.fromList [(Just "public", "custom_type"), (Nothing, "enum_type")])))           `shouldBe` "Types not found in database"@@ -210,15 +233,6 @@                        ("actual", "0")                      ] -    describe "isTransient" do-      it "ConnectionSessionError is transient" do-        (Errors.isTransient (Errors.ConnectionSessionError "connection lost"))-          `shouldBe` True--      it "StatementSessionError is not transient" do-        (Errors.isTransient (Errors.StatementSessionError 1 0 "SELECT 1" [] True (Errors.UnexpectedRowCountStatementError 1 1 0)))-          `shouldBe` False-     describe "toSqlState" do       it "digs the code out of StatementSessionError" do         (Errors.toSqlState (Errors.StatementSessionError 1 0 "INSERT INTO users (email) VALUES ($1)" ["a@b.c"] True (Errors.ServerStatementError (Errors.ServerError "23505" "duplicate key" Nothing Nothing Nothing))))@@ -232,18 +246,10 @@         (Errors.toSqlState (Errors.StatementSessionError 1 0 "SELECT 1" [] True (Errors.UnexpectedRowCountStatementError 1 1 0)))           `shouldBe` Nothing -      it "is Nothing for ConnectionSessionError" do-        (Errors.toSqlState (Errors.ConnectionSessionError "connection lost"))-          `shouldBe` Nothing-       it "is Nothing for MissingTypesSessionError" do         (Errors.toSqlState (Errors.MissingTypesSessionError (HashSet.fromList [(Just "public", "custom_type")])))           `shouldBe` Nothing -      it "is Nothing for DriverSessionError" do-        (Errors.toSqlState (Errors.DriverSessionError "unexpected response"))-          `shouldBe` Nothing-     describe "toDetailedText" do       it "renders StatementSessionError with all context" do         (Errors.toDetailedText (Errors.StatementSessionError 1 0 "SELECT * FROM users" [] True (Errors.UnexpectedRowCountStatementError 1 1 10)))@@ -256,6 +262,30 @@                      \  expectedMin: 1\n\                      \  expectedMax: 1\n\                      \  actual: 10"++  describe "UseError" do+    describe "toMessage" do+      it "renders SessionUseError with the wrapped message" do+        (Errors.toMessage (Errors.SessionUseError (Errors.StatementSessionError 1 0 "SELECT 1" [] True (Errors.UnexpectedRowCountStatementError 1 1 0))))+          `shouldBe` "Unexpected number of rows"++      it "renders ConnectionUseError" do+        (Errors.toMessage (Errors.ConnectionUseError "connection lost"))+          `shouldBe` "Connection error"++    describe "toDetails" do+      it "includes reason for ConnectionUseError" do+        (Errors.toDetails (Errors.ConnectionUseError "connection lost"))+          `shouldBe` [("reason", "connection lost")]++    describe "toSqlState" do+      it "digs the code out of a wrapped SessionUseError" do+        (Errors.toSqlState (Errors.SessionUseError (Errors.ScriptSessionError "DROP TABLE users" (Errors.ServerError "42P01" "relation does not exist" Nothing Nothing Nothing))))+          `shouldBe` Just "42P01"++      it "is Nothing for ConnectionUseError" do+        (Errors.toSqlState (Errors.ConnectionUseError "connection lost"))+          `shouldBe` Nothing    describe "toDetailedText with multiline values" do     it "indents multiline detail values correctly" do
src/library/Hasql/Connection.hs view
@@ -8,8 +8,7 @@   ) where -import Data.Text qualified as Text-import Hasql.Comms.Session qualified as Comms.Session+import Data.Text.Read qualified as Text.Read import Hasql.Connection.Config qualified as Config import Hasql.Connection.ServerVersion qualified as ServerVersion import Hasql.Connection.Settings qualified as Settings@@ -24,7 +23,17 @@ -- | -- A single connection to the database. newtype Connection-  = Connection (MVar ConnectionState.ConnectionState)+  = Connection+      -- |+      -- The state is 'Nothing' once the connection is gone. That happens when+      -- 'release' is called on it, when a session fails in a way that leaves+      -- the driver unable to vouch for the connection's protocol state (a+      -- 'ConnectionUseError' out of 'use'), and when an exception cuts a+      -- session short - in the latter two cases 'use' finishes it. @libpq@+      -- forbids touching a connection after @PQfinish@, so the handle has to+      -- remember that it did: without it a second 'release' finishes a freed+      -- connection and a later 'use' sends on one.+      (MVar (Maybe ConnectionState.ConnectionState))  -- | -- Establish a connection according to the provided settings.@@ -44,118 +53,170 @@ -- - Initializes session-level settings (encoding and message verbosity). -- -- On success, returns a 'Connection' wrapped in 'Right'.--- On failure, returns a classified 'ConnectionError' in 'Left'.+-- On failure, returns a classified 'AcquireError' in 'Left'. acquire ::   Adapter ->   Settings.Settings ->-  IO (Either ConnectionError Connection)+  IO (Either AcquireError Connection) acquire adapter settings =   {-# SCC "acquire" #-}   runExceptT do     let config = Config.construct settings      -- Connect:-    pqConnection <- lift (Pq.connectdb adapter (Config.connectionString config))+    ExceptT do+      bracketOnError+        (Pq.connectdb adapter (Config.connectionString config))+        Pq.finish+        \pqConnection -> do+          result <- runExceptT do+            -- Check status:+            status <- lift (Pq.status pqConnection)+            case status of+              Pq.ConnectionOk -> pure ()+              _ -> do+                needsPassword <- lift (Pq.connectionNeedsPassword pqConnection)+                errorMessage <- lift (Pq.errorMessage pqConnection)+                let errorText = maybe "" decodeUtf8Lenient errorMessage+                throwError+                  if needsPassword+                    then ConnectionPasswordRequiredAcquireError errorText+                    else ConnectionAcquireError errorText -    -- Check status:-    status <- lift (Pq.status pqConnection)-    case status of-      Pq.ConnectionOk -> pure ()-      _ -> do-        errorMessage <- lift (Pq.errorMessage pqConnection)-        throwError (interpretConnectionError errorMessage)+            -- Check version:+            version <- lift (ServerVersion.load pqConnection)+            when (version < ServerVersion.minimum) do+              case version of+                ServerVersion.ServerVersion major minor patch ->+                  throwError (VersionTooOldAcquireError major minor patch) -    -- Check version:-    version <- lift (ServerVersion.load pqConnection)-    when (version < ServerVersion.minimum) do-      throwError (CompatibilityConnectionError ("Server version is lower than 9: " <> ServerVersion.toText version))+            -- Initialize:+            do+              execResult <-+                lift do+                  Pq.exec pqConnection do+                    "SET client_encoding = 'UTF8';\n\+                    \SET client_min_messages TO WARNING;"+              case execResult of+                Nothing -> do+                  errorMessage <- lift (Pq.errorMessage pqConnection)+                  throwError (InitializationConnectionLossAcquireError (maybe "" decodeUtf8Lenient errorMessage))+                Just result -> do+                  status <- lift (Pq.resultStatus result)+                  case status of+                    Pq.CommandOk -> pure ()+                    _ -> do+                      sqlstate <- lift (Pq.resultErrorField result Pq.DiagSqlstate)+                      case sqlstate of+                        Just code | code /= "" -> do+                          serverError <- lift (loadServerError result (decodeUtf8Lenient code))+                          throwError (InitializationServerErrorAcquireError serverError)+                        _ -> do+                          errorMessage <- lift (Pq.resultErrorMessage result)+                          throwError (InitializationConnectionLossAcquireError (maybe "" decodeUtf8Lenient errorMessage)) -    -- Initialize:-    lift do-      Pq.exec pqConnection do-        "SET client_encoding = 'UTF8';\n\-        \SET client_min_messages TO WARNING;"+            let connectionState =+                  ConnectionState.ConnectionState+                    { ConnectionState.preparedStatements = not (Config.noPreparedStatements config),+                      ConnectionState.statementCache = StatementCache.empty,+                      ConnectionState.oidCache = mempty,+                      ConnectionState.connection = pqConnection+                    }+            connectionRef <- lift (newMVar (Just connectionState))+            pure (Connection connectionRef) -    let connectionState =-          ConnectionState.ConnectionState-            { ConnectionState.preparedStatements = not (Config.noPreparedStatements config),-              ConnectionState.statementCache = StatementCache.empty,-              ConnectionState.oidCache = mempty,-              ConnectionState.connection = pqConnection-            }-    connectionRef <- lift (newMVar connectionState)-    pure (Connection connectionRef)+          -- A classified failure (as opposed to a thrown exception, which+          -- 'bracketOnError' already finishes the connection for) still+          -- needs the connection finished, since it doesn't escape this+          -- action as an exception.+          case result of+            Left _ -> Pq.finish pqConnection+            Right _ -> pure ()+          pure result   where-    interpretConnectionError :: Maybe ByteString -> ConnectionError-    interpretConnectionError errorMessage =-      case errorMessage of-        Nothing -> OtherConnectionError "Unknown connection error"-        Just msg ->-          let msgText = decodeUtf8Lenient msg-              msgLower = Text.toLower msgText-           in if-                | any (`Text.isInfixOf` msgLower) networkingErrors -> NetworkingConnectionError msgText-                | any (`Text.isInfixOf` msgLower) authenticationErrors -> AuthenticationConnectionError msgText-                | otherwise -> OtherConnectionError (decodeUtf8Lenient msg)--    networkingErrors :: [Text]-    networkingErrors =-      [ "could not connect to server",-        "no such file or directory",-        "connection refused",-        "timeout expired",-        "host not found",-        "could not translate host name"-      ]+    -- Read the structured error report off a result, once its SQLSTATE field+    -- is known to be present.+    loadServerError :: Pq.Result -> Text -> IO ServerError+    loadServerError result code = do+      message <- fold <$> Pq.resultErrorField result Pq.DiagMessagePrimary+      detail <- Pq.resultErrorField result Pq.DiagMessageDetail+      hint <- Pq.resultErrorField result Pq.DiagMessageHint+      position <- Pq.resultErrorField result Pq.DiagStatementPosition+      pure+        $ ServerError+          code+          (decodeUtf8Lenient message)+          (fmap decodeUtf8Lenient detail)+          (fmap decodeUtf8Lenient hint)+          (parsePosition position) -    authenticationErrors :: [Text]-    authenticationErrors =-      [ "authentication failed",-        "password authentication failed",-        "no password supplied",-        "peer authentication failed"-      ]+    parsePosition :: Maybe ByteString -> Maybe Int+    parsePosition = \case+      Nothing -> Nothing+      Just bytes -> case Text.Read.decimal (decodeUtf8Lenient bytes) of+        Right (n, "") -> Just n+        _ -> Nothing  -- | -- Release the connection.+--+-- Idempotent: releasing a connection that is already gone - released+-- before, or finished by 'use' - does nothing. release :: Connection -> IO ()-release (Connection connectionRef) =+release (Connection var) =   mask_ do-    connectionState <- readMVar connectionRef-    Pq.finish (ConnectionState.connection connectionState)+    connectionState <- takeMVar var+    -- The handle is marked spent before the connection is touched, so that a+    -- 'Pq.finish' that somehow fails leaves the handle unusable rather than+    -- the MVar empty forever.+    putMVar var Nothing+    traverse_ (Pq.finish . ConnectionState.connection) connectionState  -- | -- Execute a sequence of operations with exclusive access to the connection. -- -- Blocks until the connection is available when there is another session running upon the connection on a different thread.-use :: Connection -> Session.Session a -> IO (Either SessionError a)+--+-- An exception thrown out of the session - including an interruption+-- delivered from another thread, as 'System.Timeout.timeout' and+-- 'Control.Concurrent.killThread' do - propagates, and the connection is+-- finished on the way out. See the note on the exception path below for why+-- it is not repaired instead.+use :: Connection -> Session.Session a -> IO (Either UseError a) use (Connection var) session =-  mask \restore -> do-    connectionState@ConnectionState.ConnectionState {..} <- takeMVar var-    result <- try @SomeException (restore (Session.run session connectionState))-    case result of-      Left exception -> do-        -- If an exception happened, we need to bring the connection back to idle-        -- without resetting (to preserve session state).-        result <- Comms.Session.toHandler Comms.Session.cleanUpAfterInterruption connection+  mask \unmask -> do+    takeMVar var >>= \case+      Nothing -> do+        putMVar var Nothing+        pure (Left (ConnectionUseError "The connection is no longer available"))+      Just connectionState -> do+        (result, !newState) <-+          onException (unmask (Session.run session connectionState)) do+            -- An exception leaves the connection somewhere inside a round+            -- trip, and the driver has no way of finding out where. Repairing+            -- it means draining results and aborting the transaction -+            -- blocking network IO, performed here under a mask, which on a+            -- connection whose peer has gone away never returns. The+            -- interruption being handled would then never land, which is the+            -- opposite of what the caller asked for. Finishing the connection+            -- touches nothing but the socket.+            --+            -- The connection finished here is the one taken out of the MVar. A+            -- session that replaced it through 'Hasql.Session.onLibpqConnection'+            -- loses the replacement along with the rest of the state the+            -- exception unwound past; closing that one is on the caller, which+            -- is what the escape hatch already promises.+            putMVar var Nothing+            Pq.finish (ConnectionState.connection connectionState)++        -- The driver gave up on the connection somewhere inside the session,+        -- and by construction that verdict is what 'result' says: nothing+        -- further inside the session could have caught it and carried on.+        let finish = do+              putMVar var Nothing+              Pq.finish (ConnectionState.connection newState)         case result of-          Left err -> do-            -- If cleanup failed, we have to close the connection.-            -- There's not much else we can do.-            Pq.finish connection-            putMVar var (ConnectionState.resetPreparedStatementsCache connectionState)-            let message =-                  mconcat-                    [ "Failed to clean up after interruption.\n",-                      err,-                      "\n",-                      "The following exception was raised during the operation:\n",-                      Text.pack (displayException exception)-                    ]-            pure (Left (DriverSessionError message))-          Right () -> do-            putMVar var (ConnectionState.resetPreparedStatementsCache connectionState)-            throwIO exception-      Right (result, !newState) -> do-        putMVar var newState+          Left (ConnectionUseError _) -> finish+          _ -> putMVar var (Just newState)+         pure result
src/library/Hasql/Engine/Contexts/Pipeline.hs view
@@ -10,6 +10,7 @@ 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@@ -20,16 +21,9 @@  run ::   Pipeline a ->-  Bool ->-  Pq.Connection ->-  OidCache.OidCache ->-  StatementCache.StatementCache ->-  IO-    ( Either Errors.SessionError a,-      OidCache.OidCache,-      StatementCache.StatementCache-    )-run (Pipeline totalStatements unknownTypes runPipeline) usePreparedStatements connection oidCache statementCache = do+  ConnectionState.ConnectionState ->+  IO (Either Errors.UseError a, ConnectionState.ConnectionState)+run (Pipeline totalStatements unknownTypes runPipeline) connectionState@ConnectionState.ConnectionState {..} = do   let missingTypes = OidCache.selectUnknownNames unknownTypes oidCache   resolvedOidCache <-     if HashSet.null missingTypes@@ -43,36 +37,48 @@             let foundTypes = HashMap.keysSet oidCacheUpdates                 notFoundTypes = HashSet.difference missingTypes foundTypes              in if not (HashSet.null notFoundTypes)-                  then Left (Errors.MissingTypesSessionError (HashSet.map CodecsVocab.QualifiedTypeName.toNameTuple notFoundTypes))+                  then Left (Errors.SessionUseError (Errors.MissingTypesSessionError (HashSet.map CodecsVocab.QualifiedTypeName.toNameTuple notFoundTypes)))                   else Right (oidCache <> OidCache.fromHashMap oidCacheUpdates)   case resolvedOidCache of-    Left err -> pure (Left err, oidCache, statementCache)+    Left err -> pure (Left err, connectionState)     Right newOidCache -> do       let (roundtrip, newStatementCache) =-            runPipeline 0 usePreparedStatements newOidCache statementCache-          contextualRoundtrip = first Just roundtrip+            runPipeline 0 preparedStatements newOidCache statementCache -      executionResult <- Comms.Roundtrip.toPipelineIO contextualRoundtrip Nothing connection+      -- Statements carry their tag; the pipeline bookend commands below get none.+      executionResult <- Comms.Roundtrip.toPipelineIO (first Just roundtrip) Nothing connection        let result =             first               ( \case-                  Comms.Roundtrip.ClientError _context details ->-                    Errors.ConnectionSessionError (maybe "" decodeUtf8Lenient details)+                  Comms.Roundtrip.ClientError _tag details ->+                    Errors.fromSendError details                   Comms.Roundtrip.ServerError recvError ->-                    Errors.fromRecvError (fmap (fmap (\(Context index sql params prepared _) -> (totalStatements, index, sql, params, prepared))) recvError)+                    Errors.fromRecvError (fmap (fmap (\(StatementTag index sql params prepared _ _) -> (totalStatements, index, sql, params, prepared))) recvError)               )               executionResult           finalStatementCache =             case executionResult of               Right _ -> newStatementCache               Left executionError ->-                maybe-                  statementCache-                  (\(Context _ _ _ _ statementCache) -> statementCache)-                  (extract executionError)+                case extract executionError of+                  Nothing -> statementCache+                  Just (StatementTag _ _ _ _ soFarStatementCache 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 Errors.isPrepareCollision executionError+                      then collisionStatementCache+                      else soFarStatementCache -      pure (result, newOidCache, finalStatementCache)+      pure+        ( result,+          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).@@ -158,16 +164,18 @@       -- 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 contexts carried by roundtrip errors.+      -- committed cache from statement tag carried by roundtrip errors.       ( Int ->         Bool ->         OidCache.OidCache ->         StatementCache.StatementCache ->-        (Comms.Roundtrip.Roundtrip Context a, StatementCache.StatementCache)+        (Comms.Roundtrip.Roundtrip StatementTag a, StatementCache.StatementCache)       ) -data Context-  = Context+-- | 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.@@ -176,8 +184,15 @@       [Text]       -- | Whether the statement is prepared.       Bool-      -- | The so far successfully updated statement cache.+      -- | 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 (Show, Eq)  -- * Instances@@ -224,13 +239,14 @@         prepare =           usePreparedStatements && Statement.isPrepared stmt -        context soFarStatementCache =-          Context+        tag soFarStatementCache collisionStatementCache =+          StatementTag             offset             sql             (Statement.printer stmt params)             prepare             soFarStatementCache+            collisionStatementCache          runPrepared statementCache =           (roundtrip, newStatementCache)@@ -245,8 +261,8 @@             roundtrip =               when                 isNew-                (Comms.Roundtrip.prepare (context statementCache) remoteKey sql oidList)-                *> Comms.Roundtrip.queryPrepared (context newStatementCache) remoteKey encodedParams Pq.Binary decoder'+                (Comms.Roundtrip.prepare (tag statementCache newStatementCache) remoteKey sql oidList)+                *> Comms.Roundtrip.queryPrepared (tag newStatementCache newStatementCache) remoteKey encodedParams Pq.Binary decoder'               where                 encodedParams =                   valueAndFormatList@@ -256,7 +272,7 @@           (roundtrip, statementCache)           where             roundtrip =-              Comms.Roundtrip.queryParams (context statementCache) sql encodedParams Pq.Binary decoder'+              Comms.Roundtrip.queryParams (tag statementCache statementCache) sql encodedParams Pq.Binary decoder'               where                 encodedParams =                   Statement.compileUnpreparedStatementData stmt resolve params
src/library/Hasql/Engine/Contexts/Session.hs view
@@ -23,22 +23,81 @@ -- -- To actually execute a 'Session' use 'Hasql.Connection.use', which manages -- concurrent access to the shared connection state and returns either a--- 'Errors.SessionError' or the result:+-- 'Errors.UseError' or the result: -- -- > result <- Hasql.Connection.use connection mySession --+-- The 'Control.Monad.Except.MonadError' instance ranges over+-- 'Errors.SessionError' only - the failures that leave the connection+-- usable. A failure that leaves the connection gone+-- ('Errors.ConnectionUseError') is not a value+-- 'Control.Monad.Except.throwError' can construct or+-- 'Control.Monad.Except.catchError' can see: it propagates through every+-- later 'Control.Monad.>>=' untouched and reaches 'Hasql.Connection.use'+-- whole. This is enforced structurally by this 'Monad' instance rather than+-- by a check any handler has to remember to make.+--+-- A caught error retains every connection-state change made before it -+-- both branches below thread the state through, matching @ExceptT e (State+-- s)@ rather than @StateT s (Either e)@. A statement whose @PARSE@ succeeded+-- and whose @EXECUTE@ failed has truthfully been prepared on the server, so+-- the cache entry survives the catch; only 'statement' and 'pipeline'+-- revert it themselves, on an ordinary failure, since they alone know+-- whether what they recorded was actually confirmed by the server.+-- -- Note: while most session errors are returned as values, user code executed--- inside a session may still throw exceptions; in that case the driver will--- reset the connection to a clean state.+-- inside a session may still throw exceptions, and an interruption from+-- another thread ('System.Timeout.timeout', 'Control.Concurrent.killThread')+-- arrives the same way. Such an exception propagates out of+-- 'Hasql.Connection.use', which finishes the connection on the way out rather+-- than trying to bring it back to a clean state. newtype Session a-  = Session (ConnectionState.ConnectionState -> IO (Either Errors.SessionError a, ConnectionState.ConnectionState))-  deriving-    (Functor, Applicative, Monad, MonadError Errors.SessionError, MonadIO)-    via (ExceptT Errors.SessionError (StateT ConnectionState.ConnectionState IO))+  = Session (ConnectionState.ConnectionState -> IO (Either Errors.UseError a, ConnectionState.ConnectionState)) -run :: Session a -> ConnectionState.ConnectionState -> IO (Either Errors.SessionError a, ConnectionState.ConnectionState)+run :: Session a -> ConnectionState.ConnectionState -> IO (Either Errors.UseError a, ConnectionState.ConnectionState) run (Session session) connectionState = session connectionState +instance Functor Session where+  fmap f (Session m) = Session \connectionState -> do+    (result, newConnectionState) <- m connectionState+    pure (fmap f result, newConnectionState)++instance Applicative Session where+  pure a = Session \connectionState -> pure (Right a, connectionState)++  Session mf <*> Session ma = Session \connectionState -> do+    (resultF, connectionState') <- mf connectionState+    case resultF of+      Left err -> pure (Left err, connectionState')+      Right f -> do+        (resultA, connectionState'') <- ma connectionState'+        pure (fmap f resultA, connectionState'')++instance Monad Session where+  Session m >>= f = Session \connectionState -> do+    (result, connectionState') <- m connectionState+    case result of+      Left err -> pure (Left err, connectionState')+      Right a -> run (f a) connectionState'++instance MonadIO Session where+  liftIO io = Session \connectionState -> do+    a <- io+    pure (Right a, connectionState)++-- | Ranges over 'Errors.SessionError' only. 'throwError' can only construct+-- 'Errors.SessionUseError', and 'catchError' only ever sees that+-- constructor - 'Errors.ConnectionUseError' flows past both untouched. See+-- the note on the 'Session' type.+instance MonadError Errors.SessionError Session where+  throwError err = Session \connectionState -> pure (Left (Errors.SessionUseError err), connectionState)++  catchError (Session m) handler = Session \connectionState -> do+    (result, connectionState') <- m connectionState+    case result of+      Left (Errors.SessionUseError err) -> run (handler err) connectionState'+      other -> pure (other, connectionState')+ -- | -- Possibly a multi-statement query, -- which however cannot be parameterized or prepared,@@ -52,7 +111,7 @@       Left err -> case err of         Comms.Roundtrip.ClientError _ details -> do           pure-            ( Left (Errors.ConnectionSessionError (maybe "" decodeUtf8Lenient details)),+            ( Left (Errors.fromSendError details),               connectionState             )         Comms.Roundtrip.ServerError recvError ->@@ -99,7 +158,7 @@               let foundTypes = HashMap.keysSet oidCacheUpdates                   notFoundTypes = HashSet.difference missingTypes foundTypes                in if not (HashSet.null notFoundTypes)-                    then Left (Errors.MissingTypesSessionError (HashSet.map CodecsVocab.QualifiedTypeName.toNameTuple notFoundTypes))+                    then Left (Errors.SessionUseError (Errors.MissingTypesSessionError (HashSet.map CodecsVocab.QualifiedTypeName.toNameTuple notFoundTypes)))                     else Right (oidCache <> OidCache.fromHashMap oidCacheUpdates)     case resolvedOidCache of       Left err -> pure (Left err, connectionState)@@ -107,12 +166,12 @@         let resolve = OidCache.toResolver newOidCache             decoder' = Statement.decoder stmt resolve             prepared = usePreparedStatements && Statement.isPrepared stmt-            -- Single-statement context for error reporting:+            -- Single-statement tag for error reporting:             -- total statements 1, index 0.-            context = Just (1, 0, sql, Statement.printer stmt params, prepared)+            tag = Just (1, 0, sql, Statement.printer stmt params, prepared)             mapError = \case               Comms.Roundtrip.ClientError _ details ->-                Errors.ConnectionSessionError (maybe "" decodeUtf8Lenient details)+                Errors.fromSendError details               Comms.Roundtrip.ServerError recvError ->                 Errors.fromRecvError recvError             withState (result, newStatementCache) =@@ -132,7 +191,7 @@                       & fmap (fmap (\(bytes, format) -> (bytes, bool Pq.Binary Pq.Text format)))                   execute remoteKey =                     Comms.Roundtrip.toSerialIO-                      (Comms.Roundtrip.queryPrepared context remoteKey encodedParams Pq.Binary decoder')+                      (Comms.Roundtrip.queryPrepared tag remoteKey encodedParams Pq.Binary decoder')                       connection               case StatementCache.lookup sql oidList statementCache of                 Just remoteKey -> do@@ -144,12 +203,25 @@                   -- back-to-back, so prepare in a dedicated roundtrip first.                   prepareResult <-                     Comms.Roundtrip.toSerialIO-                      (Comms.Roundtrip.prepare context remoteKey sql oidList)+                      (Comms.Roundtrip.prepare tag remoteKey sql oidList)                       connection                   case prepareResult of-                    -- PARSE failed: the statement is not on the server, so-                    -- keep the old cache (no entry committed).-                    Left err -> pure (Left err, statementCache)+                    -- PARSE failed. Ordinarily the statement is not on the+                    -- server, so the old cache is kept (no entry committed).+                    -- The one exception is 42P05 ("prepared statement+                    -- already exists"): since names are content-addressed,+                    -- a collision on the name is a collision on the+                    -- statement, so whatever the server holds under+                    -- remoteKey already is this statement. Commit the cache+                    -- so the next use finds it warm instead of failing PARSE+                    -- again.+                    Left err ->+                      pure+                        ( Left err,+                          if Errors.isPrepareCollision err+                            then newStatementCache+                            else statementCache+                        )                     Right () -> do                       -- PARSE succeeded, so the statement is on the server                       -- under remoteKey regardless of whether EXECUTE then@@ -163,27 +235,14 @@                       & fmap (fmap (\(oid, bytes, format) -> (oid, bytes, bool Pq.Binary Pq.Text format)))               result <-                 Comms.Roundtrip.toSerialIO-                  (Comms.Roundtrip.queryParams context sql encodedParams Pq.Binary decoder')+                  (Comms.Roundtrip.queryParams tag sql encodedParams Pq.Binary decoder')                   connection               pure (result, statementCache)  -- | -- Execute a pipeline. pipeline :: Pipeline.Pipeline result -> Session result-pipeline pipeline = Session \connectionState -> do-  let usePreparedStatements = ConnectionState.preparedStatements connectionState-      statementCache = ConnectionState.statementCache connectionState-      oidCache = ConnectionState.oidCache connectionState-      pqConnection = ConnectionState.connection connectionState-   in do-        (result, newOidCache, newStatementCache) <- Pipeline.run pipeline usePreparedStatements pqConnection oidCache statementCache-        let newConnectionState =-              connectionState-                { ConnectionState.oidCache = newOidCache,-                  ConnectionState.statementCache = newStatementCache-                }--        pure (result, newConnectionState)+pipeline pipeline = Session (Pipeline.run pipeline)  -- | -- Execute an operation on the raw libpq connection possibly producing an error and updating the connection.@@ -196,9 +255,24 @@ -- Producing a 'Left' value will cause the session to fail with the given error. -- Regardless of success or failure, the connection will be replaced with the one you return. ----- Throwing exceptions is okay. It will lead to the connection getting reset.+-- Throwing exceptions is okay, but it costs the connection:+-- 'Hasql.Connection.use' finishes the one it handed to the session and spends+-- the handle. It finishes that one - not any replacement you returned before+-- the exception, since an exception unwinds past the state carrying it. A+-- replacement lost that way is yours to close, like the connection it+-- displaced.+--+-- Restoring the connection is on you on the ordinary return path. Whatever+-- protocol state you leave it in - pipeline mode still on, results+-- undrained, a command in progress - is what the next session in the same+-- 'Hasql.Connection.use' inherits, and what gets handed back to the pool+-- afterwards. Nothing repairs it for you: the driver only ever finishes a+-- connection it cannot vouch for, and it has no way of telling that this+-- one is in that state. Returning a 'Left' of 'Errors.ConnectionUseError'+-- is how you say so - 'Hasql.Connection.use' finishes the connection when+-- it sees it. onLibpqConnection ::-  (Pq.Connection -> IO (Either Errors.SessionError a, Pq.Connection)) ->+  (Pq.Connection -> IO (Either Errors.UseError a, Pq.Connection)) ->   Session a onLibpqConnection f = Session \connectionState -> do   let pqConnection = ConnectionState.connection connectionState
src/library/Hasql/Engine/Decoders/Result.hs view
@@ -1,5 +1,6 @@ module Hasql.Engine.Decoders.Result where +import Data.Vector.Generic qualified as Vector import Hasql.CodecsVocab.QualifiedTypeName qualified as CodecsVocab.QualifiedTypeName import Hasql.CodecsVocab.TypeInfo qualified as CodecsVocab.TypeInfo import Hasql.Comms.ResultDecoder qualified as ResultDecoder@@ -89,7 +90,7 @@ -- It's recommended to prefer this function to 'rowList', -- since it performs notably better. {-# INLINE rowVector #-}-rowVector :: Row a -> Result (Vector a)+rowVector :: (Vector.Vector vector a) => Row a -> Result (vector a) rowVector decoder =   Result     (fmap ResultDecoder.vector (Row.toDecoder decoder))
src/library/Hasql/Engine/Decoders/Row.hs view
@@ -20,9 +20,28 @@ -- @ newtype Row a   = Row (ToBeResolved.ToBeResolved CodecsVocab.QualifiedTypeName.QualifiedTypeName CodecsVocab.TypeInfo.TypeInfo (Hasql.Comms.RowDecoder.RowDecoder a))-  deriving-    (Functor, Applicative, Filterable)-    via (Compose (ToBeResolved.ToBeResolved CodecsVocab.QualifiedTypeName.QualifiedTypeName CodecsVocab.TypeInfo.TypeInfo) Hasql.Comms.RowDecoder.RowDecoder)++-- The instances below are what @deriving via Compose@ would give, written out+-- so they can carry @INLINE@. base's 'Compose' instances have none, so a+-- derived @<*>@ here bottoms out in @liftA2 (<*>)@ behind an unknown call and+-- the row decoder never collapses into straight-line column reads.+instance Functor Row where+  {-# INLINE fmap #-}+  fmap fn (Row toBeResolved) =+    Row (fmap (fmap fn) toBeResolved)++instance Applicative Row where+  {-# INLINE pure #-}+  pure a =+    Row (pure (pure a))+  {-# INLINE (<*>) #-}+  Row lhs <*> Row rhs =+    Row (liftA2 (<*>) lhs rhs)++instance Filterable Row where+  {-# INLINE mapMaybe #-}+  mapMaybe fn (Row toBeResolved) =+    Row (fmap (mapMaybe fn) toBeResolved)  toDecoder ::   Row a ->
src/library/Hasql/Engine/Errors.hs view
@@ -12,65 +12,87 @@ -- | -- Error that occurs when attempting to establish a database connection. ----- These errors can occur when calling 'Hasql.Connection.acquire'.--- Connection errors are categorized into several types to help with--- error handling and logging.-data ConnectionError-  = -- | Network-level error while connecting to the database server.-    ---    -- This typically indicates issues like:-    ---    -- * Server is not reachable (wrong host\/port or server is down)-    -- * Network connectivity problems-    -- * Firewall blocking the connection-    -- * Connection timeout+-- These errors can occur when calling 'Hasql.Connection.acquire', which runs+-- three stages in sequence: it establishes a connection, checks the server+-- version, and initializes session settings. A constructor is named for its+-- stage, then its case: a bare stage name means nothing further is known at+-- that stage, and a stage with only one case needs no prefix. Reaching a+-- stage is therefore a claim about everything before it - a failure at+-- initialization means the connection was established and the server+-- version was accepted.+--+-- Every constructor here publishes only what the driver actually observed.+-- @libpq@ produces no structured signal for a failure while connecting - no+-- 'ServerError' is available - so 'ConnectionAcquireError' and+-- 'ConnectionPasswordRequiredAcquireError' carry prose. A failure during+-- session initialization can go either way, hence the split between+-- 'InitializationConnectionLossAcquireError' and+-- 'InitializationServerErrorAcquireError'.+data AcquireError+  = -- | The connection could not be established, and no structured signal+    -- exists to say why.     ---    -- These errors are transient and the operation can be retried.-    NetworkingConnectionError-      -- | Human readable details intended for logging.+    -- This is the residual case at the connection stage: DNS failure,+    -- connection refused, TLS negotiation failure, a rejected password, a+    -- missing database, and any other rejection @libpq@ does not surface a+    -- flag for, all land here alike.+    ConnectionAcquireError+      -- | Human readable details from @libpq@, intended for logging. May be+      -- empty.       Text-  | -- | Authentication failed when connecting to the database.-    ---    -- This typically indicates issues like:-    ---    -- * Invalid username or password-    -- * User does not have permission to access the database-    -- * Authentication method mismatch (e.g., server requires SSL but client doesn't use it)+  | -- | The server demanded a password and none was available.     ---    -- These errors are not transient and require fixing the credentials or permissions.-    AuthenticationConnectionError-      -- | Human readable details intended for logging.+    -- Reported from @PQconnectionNeedsPassword@, a flag @libpq@ sets from+    -- the authentication exchange rather than from message text. A wrong+    -- password, by contrast, reports 'False' on this flag and is+    -- indistinguishable from any other connection refusal, so it lands in+    -- 'ConnectionAcquireError' instead.+    ConnectionPasswordRequiredAcquireError+      -- | Human readable details from @libpq@, intended for logging.       Text-  | -- | Compatibility issue between client and server.-    ---    -- This typically indicates issues like:+  | -- | The server's version is below the minimum this driver supports.     ---    -- * Server version is too old or too new-    -- * Required PostgreSQL features are not available-    -- * Protocol version mismatch+    -- The three fields are the server's major, minor and patch version, in+    -- that order. The minimum required version is not carried alongside+    -- them: it is a constant of this library, currently @9.0.0@.+    VersionTooOldAcquireError+      -- | Major version.+      Int+      -- | Minor version.+      Int+      -- | Patch version.+      Int+  | -- | Session initialization failed and the connection died: there is+    -- prose and nothing else.     ---    -- These errors are not transient and require upgrading/downgrading-    -- the server or client.-    CompatibilityConnectionError-      -- | Human readable details intended for logging.+    -- This covers both @PQexec@ returning no result at all and @PQexec@+    -- returning a result @libpq@ fabricated client-side with no diagnostic+    -- fields on it - the same event either way, distinguished from+    -- 'InitializationServerErrorAcquireError' by whether the result carries+    -- a SQLSTATE, not by whether a result exists.+    InitializationConnectionLossAcquireError+      -- | Human readable details from @libpq@, intended for logging. May be+      -- empty.       Text-  | -- | Uncategorized error coming from @libpq@.-    ---    -- This is a catch-all for connection errors that don't fit into other categories.-    -- The error message may be empty if @libpq@ doesn't provide details.+  | -- | Session initialization failed and the server said why.     ---    -- These errors are not transient by default.-    OtherConnectionError-      -- | Human readable details intended for logging. May be empty.-      Text+    -- The server rejected the initialization statement and returned a real+    -- error report, readable through @PQresultErrorField@. This is the one+    -- 'AcquireError' for which 'Hasql.Errors.toSqlState' can return 'Just'.+    InitializationServerErrorAcquireError+      ServerError   deriving stock (Show, Eq)  -- |--- Error that occurs during session execution.+-- Error that occurs during session execution and leaves the connection+-- usable. -- -- A session is a batch of actions executed in a database connection context.--- Session errors can occur due to statement failures, connection issues,--- missing types, or internal driver errors.+-- Every constructor here means the connection is still fit to be handed+-- back for reuse - that is the axis 'SessionError' is narrowed on, not+-- provenance. A failure that leaves the connection gone is not a+-- 'SessionError' at all; it is one of the other two constructors of+-- 'UseError'. -- -- Session errors provide detailed context to help diagnose problems, -- including SQL text, parameters, and the location of the error within@@ -109,17 +131,6 @@       Text       -- | The server error that occurred.       ServerError-  | -- | A connection-level error occurred during session execution.-    ---    -- This indicates that the connection to the database was lost or-    -- became unusable during the session. These errors are transient-    -- and the operation can be retried with a new connection.-    ---    -- Note: As of version 1.10, connections recover from async exceptions-    -- without resetting, preserving connection-local state.-    ConnectionSessionError-      -- | Human-readable details about the connection error.-      Text   | -- | One or more types referenced in the statement could not be found in the database.     --     -- This occurs when using custom types (enums, composite types, domains) that@@ -135,16 +146,43 @@       --       -- Schema name is 'Nothing' when the type was looked up without a schema qualifier.       (HashSet (Maybe Text, Text))-  | -- | An internal driver error occurred.+  deriving stock (Show, Eq)++-- |+-- Error that 'Hasql.Connection.use' can return.+--+-- 'SessionUseError' means the connection is still usable and is the only+-- constructor 'Control.Monad.Except.catchError' on a 'Hasql.Session.Session'+-- can see. 'ConnectionUseError' means the connection is gone, and no handler+-- inside the session can intercept it - the split is structural, enforced by+-- the 'Session' 'Control.Monad.Monad' instance rather than by any check a+-- handler has to remember to make.+data UseError+  = -- | The session reported an ordinary failure and the connection is+    -- still usable.+    SessionUseError+      SessionError+  | -- | The connection is gone.     ---    -- This indicates either:+    -- This covers every way 'Hasql.Connection.use' can lose the connection:+    -- a dropped socket, a request @libpq@ refused to send outright (e.g.+    -- more than 65535 parameters in one statement), an unexpected response+    -- from the server, or a bug in Hasql. The reason text says which.     ---    -- * A bug in Hasql-    -- * The PostgreSQL server misbehaving-    -- * An unexpected response from the server+    -- 'Hasql.Connection.use' has finished the connection before returning+    -- this, so the 'Hasql.Connection.Connection' the session ran on is+    -- spent: further 'Hasql.Connection.use' on it fails with this same+    -- error, and 'Hasql.Connection.release' is a no-op. Pools must discard+    -- it rather than return it.     ---    -- If you encounter this error, please report it as a bug.-    DriverSessionError+    -- Whatever the cause, the driver cannot vouch for the protocol state of+    -- a connection a request failed to leave, and repairing one costs more+    -- than replacing it: the repair would have to push a Sync, which+    -- flushes and commits the very commands the failed session never got to+    -- complete. So this is reported uniformly rather than split by cause -+    -- retry policy belongs to the caller, informed by the reason text and,+    -- for server errors, 'Hasql.Errors.toSqlState'.+    ConnectionUseError       -- | Human-readable details about what went wrong.       Text   deriving stock (Show, Eq)@@ -308,66 +346,108 @@       Text   deriving stock (Show, Eq) -fromRoundtripError :: Hasql.Comms.Roundtrip.Error context -> SessionError+-- |+-- Whether a round trip error is a @Parse@ failing with SQLSTATE @42P05@+-- ("prepared statement \"...\" already exists").+--+-- Since prepared statement names are content-addressed (a SHA-256 digest of+-- the SQL text and the parameter OIDs), a collision on the name is - up to a+-- hash collision - a collision on the statement itself: whatever the server+-- already holds under that name is the very statement that was about to be+-- parsed. Callers that evict a cache entry on ordinary @Parse@ failures+-- should keep it in this one case, since the statement is in fact on the+-- server under the name they just tried to commit.+--+-- This is a fact about Hasql's own naming scheme, not something derivable+-- from the PostgreSQL error-code appendix: nothing about @42P05@ in general+-- says a collision is safe to treat as a cache hit, only Hasql's+-- content-addressing does.+isPrepareCollision :: Hasql.Comms.Roundtrip.Error tag -> Bool+isPrepareCollision = \case+  Hasql.Comms.Roundtrip.ServerError (Hasql.Comms.Recv.ResultError _ _ (Hasql.Comms.ResultDecoder.ServerError code _ _ _ _)) ->+    code == "42P05"+  _ -> False++-- | Turn a failed @libpq@ send into a 'UseError'.+--+-- A failed send always finishes the connection: either the socket is gone,+-- or @libpq@ refused the request with commands possibly queued behind it and+-- no way to tell what the server has seen. Neither is worth repairing - a+-- repair would have to push a Sync, which flushes and commits the very+-- commands the failed session never got to complete - so the connection is+-- finished instead.+fromSendError :: Text -> UseError+fromSendError = ConnectionUseError++fromRoundtripError :: Hasql.Comms.Roundtrip.Error tag -> UseError fromRoundtripError = \case-  Hasql.Comms.Roundtrip.ClientError _context details ->-    ConnectionSessionError (maybe "" decodeUtf8Lenient details)+  Hasql.Comms.Roundtrip.ClientError _tag details ->+    fromSendError details   Hasql.Comms.Roundtrip.ServerError recvError ->     fromRecvError (Nothing <$ recvError) -fromRecvError :: Hasql.Comms.Recv.Error (Maybe (Int, Int, ByteString, [Text], Bool)) -> SessionError+fromRecvError :: Hasql.Comms.Recv.Error (Maybe (Int, Int, ByteString, [Text], Bool)) -> UseError fromRecvError = \case-  Hasql.Comms.Recv.ResultError location _resultOffset resultError ->-    case location of+  Hasql.Comms.Recv.ResultError tag _resultOffset resultError ->+    case tag of       Nothing ->-        (DriverSessionError . TextBuilder.toText . mconcat)-          [ "Unexpected error outside of statement context. ",+        (ConnectionUseError . TextBuilder.toText . mconcat)+          [ "Unexpected error in an operation not associated with any statement. ",             "This indicates a bug in Hasql or the server misbehaving. ",             "Error: ",             TextBuilder.string (show resultError)           ]       Just (totalStatements, statementIndex, sql, parameters, prepared) ->-        StatementSessionError-          totalStatements-          statementIndex-          (decodeUtf8Lenient sql)-          parameters-          prepared-          (fromStatementResultError resultError)-  Hasql.Comms.Recv.NoResultsError location details ->-    case location of-      Nothing ->-        (DriverSessionError . TextBuilder.toText . mconcat)-          [ "Unexpectedly got no results outside of statement context. ",-            "This indicates a bug in Hasql or the server misbehaving. ",-            "Details: ",-            TextBuilder.string (show details)-          ]-      Just (totalStatements, statementIndex, sql, parameters, prepared) ->-        StatementSessionError-          totalStatements-          statementIndex-          (decodeUtf8Lenient sql)-          parameters-          prepared-          (UnexpectedRowCountStatementError 1 1 0)-  Hasql.Comms.Recv.TooManyResultsError location actual ->-    case location of+        SessionUseError+          $ StatementSessionError+            totalStatements+            statementIndex+            (decodeUtf8Lenient sql)+            parameters+            prepared+            (fromStatementResultError resultError)+  Hasql.Comms.Recv.NoResultsError tag connectionLost details ->+    if connectionLost+      then -- The results are not late, they are never coming: the socket is+      -- gone. Reporting this as a row-count mismatch would describe a+      -- dropped connection as a statement that returned nothing, and+      -- leave pools reusing a connection that no longer exists.+        ConnectionUseError (maybe "" decodeUtf8Lenient details)+      else case tag of+        Nothing ->+          (ConnectionUseError . TextBuilder.toText . mconcat)+            [ "Unexpectedly got no results in an operation not associated with any statement. ",+              "This indicates a bug in Hasql or the server misbehaving. ",+              "Details: ",+              TextBuilder.string (show details)+            ]+        Just (totalStatements, statementIndex, sql, parameters, prepared) ->+          SessionUseError+            $ StatementSessionError+              totalStatements+              statementIndex+              (decodeUtf8Lenient sql)+              parameters+              prepared+              (UnexpectedRowCountStatementError 1 1 0)+  Hasql.Comms.Recv.TooManyResultsError tag actual ->+    case tag of       Nothing ->-        (DriverSessionError . TextBuilder.toText . mconcat)-          [ "Unexpectedly got too many results outside of statement context. ",+        (ConnectionUseError . TextBuilder.toText . mconcat)+          [ "Unexpectedly got too many results in an operation not associated with any statement. ",             "This indicates a bug in Hasql or the server misbehaving. ",             "Amount: ",             TextBuilder.decimal actual           ]       Just (totalStatements, statementIndex, sql, parameters, prepared) ->-        StatementSessionError-          totalStatements-          statementIndex-          (decodeUtf8Lenient sql)-          parameters-          prepared-          (UnexpectedRowCountStatementError 1 1 actual)+        SessionUseError+          $ StatementSessionError+            totalStatements+            statementIndex+            (decodeUtf8Lenient sql)+            parameters+            prepared+            (UnexpectedRowCountStatementError 1 1 actual)  fromStatementResultError :: Hasql.Comms.ResultDecoder.Error -> StatementError fromStatementResultError = \case@@ -409,39 +489,40 @@           rowIndex           (RefinementRowError msg) -fromRecvErrorInScript :: ByteString -> Hasql.Comms.Recv.Error (Maybe ByteString) -> SessionError+fromRecvErrorInScript :: ByteString -> Hasql.Comms.Recv.Error (Maybe ByteString) -> UseError fromRecvErrorInScript scriptSql = \case   Hasql.Comms.Recv.ResultError _ _ resultError ->     case resultError of       Hasql.Comms.ResultDecoder.ServerError code message detail hint position ->-        ScriptSessionError-          (decodeUtf8Lenient scriptSql)-          ( ServerError-              (decodeUtf8Lenient code)-              (decodeUtf8Lenient message)-              (fmap decodeUtf8Lenient detail)-              (fmap decodeUtf8Lenient hint)-              position-          )+        SessionUseError+          $ ScriptSessionError+            (decodeUtf8Lenient scriptSql)+            ( ServerError+                (decodeUtf8Lenient code)+                (decodeUtf8Lenient message)+                (fmap decodeUtf8Lenient detail)+                (fmap decodeUtf8Lenient hint)+                position+            )       Hasql.Comms.ResultDecoder.UnexpectedResult msg ->-        (DriverSessionError . TextBuilder.toText . mconcat)+        (ConnectionUseError . TextBuilder.toText . mconcat)           [ "Unexpected result in script: ",             TextBuilder.text msg           ]       Hasql.Comms.ResultDecoder.UnexpectedRowCount actual ->-        (DriverSessionError . TextBuilder.toText . mconcat)+        (ConnectionUseError . TextBuilder.toText . mconcat)           [ "Unexpected amount of rows in script: ",             TextBuilder.decimal actual           ]       Hasql.Comms.ResultDecoder.UnexpectedColumnCount expected actual ->-        (DriverSessionError . TextBuilder.toText . mconcat)+        (ConnectionUseError . TextBuilder.toText . mconcat)           [ "Unexpected amount of columns in script: expected ",             TextBuilder.decimal expected,             ", got ",             TextBuilder.decimal actual           ]       Hasql.Comms.ResultDecoder.DecoderTypeMismatch colIdx expectedOid actualOid ->-        (DriverSessionError . TextBuilder.toText . mconcat)+        (ConnectionUseError . TextBuilder.toText . mconcat)           [ "Decoder type mismatch in script: expected OID ",             TextBuilder.string (show expectedOid),             " at column ",@@ -450,22 +531,25 @@             TextBuilder.string (show actualOid)           ]       Hasql.Comms.ResultDecoder.RowError rowIndex rowError ->-        (DriverSessionError . TextBuilder.toText . mconcat)+        (ConnectionUseError . TextBuilder.toText . mconcat)           [ "Row error in script at row ",             TextBuilder.decimal rowIndex,             ": ",             TextBuilder.string (show rowError)           ]-  Hasql.Comms.Recv.NoResultsError _ details ->-    (DriverSessionError . TextBuilder.toText . mconcat)-      [ "Got no results in script.",-        " This indicates a bug in Hasql or the server misbehaving.",-        details-          & filter (/= "")-          & foldMap (mappend " Details: " . TextBuilder.text . decodeUtf8Lenient)-      ]+  Hasql.Comms.Recv.NoResultsError _ connectionLost details ->+    if connectionLost+      then ConnectionUseError (maybe "" decodeUtf8Lenient details)+      else+        (ConnectionUseError . TextBuilder.toText . mconcat)+          [ "Got no results in script.",+            " This indicates a bug in Hasql or the server misbehaving.",+            details+              & filter (/= "")+              & foldMap (mappend " Details: " . TextBuilder.text . decodeUtf8Lenient)+          ]   Hasql.Comms.Recv.TooManyResultsError _ actual ->-    (DriverSessionError . TextBuilder.toText . mconcat)+    (ConnectionUseError . TextBuilder.toText . mconcat)       [ "Got too many results in script. ",         "This indicates a bug in Hasql or the server misbehaving. ",         "Amount: ",
src/library/Hasql/Engine/PqProcedures/SelectTypeInfo.hs view
@@ -1,6 +1,5 @@ module Hasql.Engine.PqProcedures.SelectTypeInfo   ( SelectTypeInfo (..),-    SelectTypeInfoResult,     run,   ) where@@ -28,7 +27,7 @@ type SelectTypeInfoResult =   HashMap CodecsVocab.QualifiedTypeName CodecsVocab.TypeInfo.TypeInfo -run :: Pq.Connection -> SelectTypeInfo -> IO (Either Errors.SessionError SelectTypeInfoResult)+run :: Pq.Connection -> SelectTypeInfo -> IO (Either Errors.UseError SelectTypeInfoResult) run connection (SelectTypeInfo keys) =   if HashSet.null keys     then pure (Right HashMap.empty)
src/library/Hasql/Errors.hs view
@@ -3,8 +3,9 @@ -- -- This module provides access to all error types used throughout Hasql: ----- * 'ConnectionError' - errors that occur when establishing a database connection--- * 'SessionError' - errors that occur during session execution+-- * 'AcquireError' - errors that occur when establishing a database connection+-- * 'UseError' - errors returned when using a connection+-- * 'SessionError' - recoverable errors that occur during session execution -- -- The module follows Hasql's philosophy of explicit error handling, -- where all errors are represented as values rather than exceptions.@@ -13,9 +14,12 @@     IsError (..),     toDetailedText, -    -- * Connection errors-    ConnectionError (..),+    -- * Acquire errors+    AcquireError (..), +    -- * Use errors+    UseError (..),+     -- * Session errors     SessionError (..),     StatementError (..),@@ -34,6 +38,15 @@ -- * Classes  -- | A class for types that can be treated as errors.+--+-- This is a rendering interface: it turns an error value into a+-- human-readable message, a list of dynamic details, and - where the error+-- carries one - the server's SQLSTATE. It deliberately does not offer a+-- retryability verdict. Whether an operation is worth retrying depends on+-- the caller's retry policy, the transaction it sits inside, and the+-- SQLSTATE where one is available - not on a boolean this class hands out.+-- Hasql declines to own that decision, so the omission here is not an+-- oversight. class IsError a where   -- | Convert the error to a human-readable message with no dynamic details.   toMessage :: a -> Text@@ -41,9 +54,6 @@   -- | Convert the error to a list of key-value pairs of dynamic details.   toDetails :: a -> [(Text, Text)] -  -- | Whether the error is transient and the operation causing it can be retried.-  isTransient :: a -> Bool-   -- | The SQLSTATE the server reported, if this error carries one at all.   --   -- Lets you branch on a PostgreSQL error code without knowing which@@ -86,32 +96,36 @@  -- * Instances -instance IsError ConnectionError where+instance IsError AcquireError where   toMessage = \case-    NetworkingConnectionError {} ->-      "Networking error while connecting to the database"-    AuthenticationConnectionError {} ->-      "Authentication error while connecting to the database"-    CompatibilityConnectionError {} ->-      "Compatibility error while connecting to the database"-    OtherConnectionError {} ->-      "Connection error while connecting to the database"+    ConnectionAcquireError {} ->+      "Failed to establish a connection to the database"+    ConnectionPasswordRequiredAcquireError {} ->+      "The server demanded a password and none was available"+    VersionTooOldAcquireError {} ->+      "Server version is too old"+    InitializationConnectionLossAcquireError {} ->+      "Connection lost while initializing the session"+    InitializationServerErrorAcquireError err ->+      toMessage err    toDetails = \case-    NetworkingConnectionError reason ->-      [("reason", reason)]-    AuthenticationConnectionError reason ->+    ConnectionAcquireError reason ->       [("reason", reason)]-    CompatibilityConnectionError reason ->+    ConnectionPasswordRequiredAcquireError reason ->       [("reason", reason)]-    OtherConnectionError reason ->+    VersionTooOldAcquireError major minor patch ->+      [ ("version", (TextBuilder.toText . mconcat) [TextBuilder.decimal major, ".", TextBuilder.decimal minor, ".", TextBuilder.decimal patch]),+        ("minimumVersion", "9.0.0")+      ]+    InitializationConnectionLossAcquireError reason ->       [("reason", reason)]+    InitializationServerErrorAcquireError err ->+      toDetails err -  isTransient = \case-    NetworkingConnectionError {} -> True-    AuthenticationConnectionError {} -> False-    CompatibilityConnectionError {} -> False-    OtherConnectionError {} -> False+  toSqlState = \case+    InitializationServerErrorAcquireError err -> toSqlState err+    _ -> Nothing  instance IsError ServerError where   toMessage _ =@@ -125,8 +139,6 @@         maybe [] (\p -> [("position", (TextBuilder.toText . TextBuilder.decimal) p)]) position       ] -  isTransient = const False-   toSqlState (ServerError code _ _ _ _) = Just code  instance IsError CellError where@@ -142,8 +154,6 @@     DeserializationCellError reason ->       [("reason", reason)] -  isTransient = const False- instance IsError StatementError where   toMessage = \case     ServerStatementError executionError ->@@ -181,8 +191,6 @@     UnexpectedResultStatementError reason ->       [("reason", reason)] -  isTransient = const False-   toSqlState = \case     ServerStatementError executionError -> toSqlState executionError     UnexpectedRowCountStatementError {} -> Nothing@@ -207,18 +215,12 @@     RefinementRowError reason ->       [("reason", reason)] -  isTransient = const False- instance IsError SessionError where   toMessage = \case     StatementSessionError _ _ _ _ _ statementError ->       toMessage statementError     ScriptSessionError _ execErr ->       toMessage execErr-    ConnectionSessionError {} ->-      "Connection error"-    DriverSessionError {} ->-      "Driver error"     MissingTypesSessionError {} ->       "Types not found in database" @@ -233,10 +235,6 @@         <> toDetails statementError     ScriptSessionError sql execErr ->       ("sql", sql) : toDetails execErr-    ConnectionSessionError reason ->-      [("reason", reason)]-    DriverSessionError reason ->-      [("reason", reason)]     MissingTypesSessionError missingTypes ->       [ ( "missingTypes",           (TextBuilder.toText . mconcat . intersperse ", " . fmap formatType . HashSet.toList) missingTypes@@ -245,16 +243,24 @@       where         formatType (schema, name) = maybe "" ((<> ".") . TextBuilder.text) schema <> TextBuilder.text name -  isTransient = \case-    ConnectionSessionError _ -> True-    StatementSessionError {} -> False-    ScriptSessionError {} -> False-    DriverSessionError {} -> False-    MissingTypesSessionError {} -> False-   toSqlState = \case     StatementSessionError _ _ _ _ _ statementError -> toSqlState statementError     ScriptSessionError _ serverError -> toSqlState serverError-    ConnectionSessionError {} -> Nothing-    DriverSessionError {} -> Nothing     MissingTypesSessionError {} -> Nothing++instance IsError UseError where+  toMessage = \case+    SessionUseError err ->+      toMessage err+    ConnectionUseError {} ->+      "Connection error"++  toDetails = \case+    SessionUseError err ->+      toDetails err+    ConnectionUseError reason ->+      [("reason", reason)]++  toSqlState = \case+    SessionUseError err -> toSqlState err+    ConnectionUseError {} -> Nothing
src/platform/Hasql/Platform/Prelude.hs view
@@ -1,6 +1,5 @@ module Hasql.Platform.Prelude   ( module Exports,-    LazyByteString,     forMToZero_,     forMFromZero_,     strictCons,@@ -32,7 +31,6 @@ import Data.Bits as Exports import Data.Bool as Exports import Data.ByteString as Exports (ByteString)-import Data.ByteString.Lazy qualified import Data.Char as Exports import Data.Coerce as Exports import Data.Complex as Exports@@ -104,9 +102,6 @@ import TextBuilder as Exports (TextBuilder) import Unsafe.Coerce as Exports import Witherable as Exports--type LazyByteString =-  Data.ByteString.Lazy.ByteString  {-# INLINE forMToZero_ #-} forMToZero_ :: (Applicative m) => Int -> (Int -> m a) -> m ()
src/to-be-resolved/Hasql/ToBeResolved.hs view
@@ -22,7 +22,14 @@  type role ToBeResolved _ _ representational -deriving stock instance Functor (ToBeResolved k v)+-- Written out rather than derived so that 'fmap' carries an @INLINE@. Every+-- row decoder is a chain of 'fmap's and '<*>'s over this type, and without the+-- unfolding the chain cannot collapse at its definition site -- which leaves a+-- closure allocation per column per row.+instance Functor (ToBeResolved k v) where+  {-# INLINE fmap #-}+  fmap fn (ToBeResolved keys use) =+    ToBeResolved keys (fn . use)  instance Applicative (ToBeResolved k v) where   {-# INLINE pure #-}