diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,257 @@
+# 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
+
+- `IsError` gained a `toSqlState` method, exposing the SQLSTATE the server reported for an error, or `Nothing` where the error carries no server code. It saves consumers from pattern-matching their way down to the nested `ServerError` — a dig that has to be rewritten every time the error types gain a constructor.
+
+  ```haskell
+  case Errors.toSqlState err of
+    Just "23505" -> handleUniqueViolation
+    _ -> rethrow err
+  ```
+
+  The method has a default implementation returning `Nothing`, so existing instances keep compiling. Instances for error types that *wrap* another error type must override it and delegate to the wrapped value, otherwise they silently report `Nothing` for codes they do carry.
+
+# v2.0.0.3
+
+## Fixes
+
+- Work around the bug in Cabal due to which documentation does not get generated for definitions reexported from sublibs.
+
+# v2.0.0.2
+
+Work around the bugs in Cabal/Haddock that cause missing documentation for two-hop reexported internal modules.
+
+# v2.0.0.1
+
+Support for `pqi-1.1`.
+
+# v2.0.0.0
+
+New era: the transport layer is now pluggable via [`pqi`](https://github.com/nikita-volkov/pqi), and an alpha pure-Haskell backend, [`pqi-native`](https://github.com/nikita-volkov/pqi-native), is available for early adopters. Goal: a reliable, performant, no-C-dependency replacement for libpq.
+
+## Breaking
+
+- `Hasql.Connection.acquire` now takes an explicit adapter as its first argument, ahead of `Settings`. To keep prior behaviour, depend on [`pqi-ffi`](https://hackage.haskell.org/package/pqi-ffi) and pass `Pqi.Ffi.adapter`. To try the native backend, depend on [`pqi-native`](https://hackage.haskell.org/package/pqi-native) and pass `Pqi.Native.adapter`.
+
+# 1.10
+
+Major revision happened.
+
+## New Features
+
+- **OID by name resolution**.
+
+  Encoders and decoders now support resolving PostgreSQL type OIDs by their names at runtime. This enables working with custom types (enums, composite types, domains) without hardcoding OID values. The system includes an OID cache to optimize repeated lookups and automatically queries `pg_type` and related system catalogs when needed. This change affects array, composite, and value encoders/decoders throughout the codec system.
+
+- **Decoder compatibility checks**.
+
+  Previously decoders were silently accepting values of different types, if binary decoding did not fail. Now decoders check if the actual type of the column matches the expected type of the decoder and report `UnexpectedColumnTypeStatementError` error if they do not match. They also match the amount of columns in the result with the amount of columns expected by the decoder and report an error if they do not match.
+
+- **No resets on errors**.
+
+  Previously when an async exception was raised during the execution of a session, the connection would get reestablished to recover from any possible half-finished states. That led to a loss of the connection-local state on the server side. Now the connection recovers without resetting.
+
+- **Redesigned connection configuration API**.
+
+  The connection settings API has been completely redesigned to be more composable and user-friendly. Settings are now represented as a monoid, allowing easy combination of multiple configuration options. The API now supports both URI and key-value connection string formats, with individual setters for common parameters like host, port, user, password, etc.
+
+- **Custom codec API**.
+
+  Added `Hasql.Encoders.custom` and `Hasql.Decoders.custom` functions providing a low-level API for defining custom value encoders and decoders. These functions offer fine-grained control over OID resolution, allowing you to:
+  - Specify static OIDs when known at compile time
+  - Automatically resolve OIDs at runtime by type name
+  - Declare dependencies on other types needed for serialization/deserialization (e.g., field types in composite types)
+  - Implement custom binary encoding/decoding logic with access to resolved OIDs
+
+  This is particularly useful for advanced use cases like custom composite types with field validation or specialized binary formats.
+
+## Breaking changes
+
+- Text instead of ByteString for textual data.
+  - The public API now uses `Text` instead of `ByteString` for SQL statements and error messages.
+
+- Custom type mappings (enums and composite types) now require specifying names for the types being mapped.
+  - This will automatically identify the types with the DB and do deep compatibility checks.
+
+- Decoder checks are now more strict and report `UnexpectedColumnTypeStatementError` when the actual type of a column does not match the expected type of the decoder. Previously such mismatches were silently ignored and could lead to either autocasts or runtime errors in later stages.
+  - E.g., `int4` column decoded with `int8` decoder will now report `UnexpectedColumnTypeStatementError` instead of silently accepting the value.
+
+- Session now has exclusive access to the connection for its entire duration. Previously it was releasing and reacquiring the lock on the connection between statements.
+  - If you need the old behaviour, you can use `ReaderT Connection (ExceptT SessionError IO)`.
+
+- Dropped `MonadReader Connection` instance for `Session`.
+
+- Dropped `Monad` and `MonadFail` instances for the `Row` decoder. `Applicative` is enough for all practical purposes.
+
+- Errors model completely overhauled.
+  - `ConnectionError` restructured and moved from the `Hasql.Connection` module to `Hasql.Errors`.
+  - `SessionError` restructured and moved from the `Hasql.Session` module to `Hasql.Errors`.
+
+- `usePreparedStatements` setting dropped. Use `disablePreparedStatements` instead.
+
+- `Hasql.Session.sql` renamed to `Hasql.Session.script` to better reflect its purpose.
+
+- Connection configuration API overhaul to improve UX.
+  - `Hasql.Connection.acquire` now takes a single `Settings` value instead of a list of `Setting` values.
+  - The `Hasql.Connection.Setting` module has been replaced with `Hasql.Connection.Settings`.
+  - Settings are now constructed using flat monoid composition instead of hierarchical lists requiring multiple imports.
+  - Removed `Hasql.Connection.Setting.Connection` and related submodules.
+
+- Custom value decoder signature changed.
+
+  The `Hasql.Decoders.custom` function signature has been extended to support more explicit control over type resolution. It now requires:
+  - Optional static OIDs parameter (previously implicit)
+  - List of additional type dependencies needed for decoding
+  - The decoder function now receives an OID lookup function as its first parameter
+
+  This change enables more robust custom type handling but requires updating existing custom decoder implementations.
+
+- Exception instances on error types removed. The error types here were never thrown as exceptions. Wrap them in your own exception type if you need to throw them.
+
+# 1.9
+
+- Revised the settings construction exposing a tree of modules
+- Added a global prepared statements setting
+
+## Why the changes?
+
+To introduce the new global prepared statements setting and to make the settings API ready for extension without backward compatibility breakage.
+
+## Instructions on upgrading the 1.8 code
+
+### When explicit connection string is used
+
+Replace
+
+```haskell
+Hasql.Connection.acquire connectionString
+```
+
+with
+
+```haskell
+Hasql.Connection.acquire 
+  [ Hasql.Connection.Setting.connection (Hasql.Connection.Setting.Connection.string connectionString)
+  ]
+```
+
+### When parameteric connection string is used
+
+Replace
+
+```haskell
+Hasql.Connection.acquire (Hasql.Connection.settings host port user password dbname)
+```
+
+with
+
+```haskell
+Hasql.Connection.acquire
+  [ Hasql.Connection.Setting.connection
+    ( Hasql.Connection.Setting.Connection.params
+      [ Hasql.Connection.Setting.Connection.Param.host host,
+        Hasql.Connection.Setting.Connection.Param.port port,
+        Hasql.Connection.Setting.Connection.Param.user user,
+        Hasql.Connection.Setting.Connection.Param.password password,
+        Hasql.Connection.Setting.Connection.Param.dbname dbname
+      ]
+    )
+  ]
+```
+
+# 1.8.1
+
+- In case of exceptions thrown by user from inside of Session, the connection status gets checked to be out of transaction and unless it is the connection gets reset.
+
+# 1.8
+
+- Move to "iproute" from "network-ip" for the "inet" datatype (#163).
+
+# 1.7
+
+- Decidable instance on `Encoders.Params` removed. It was useless and limited the design.
+- `QueryError` type renamed to `SessionError`.
+- `PipelineError` constructor added to the `SessionError` type.
+
+# 1.6.3.1
+
+- Moved to "postgresql-libpq-0.10"
+
+# 1.6.3
+
+- Added `unknownEnum` encoder
+
+# 1.6.2
+
+- Added composite encoder
+- Added `oid` and `name` encoders
+
+# 1.6.1
+
+- Added `jsonLazyBytes` and `jsonbLazyBytes`
+
+# 1.6
+
+- Added position to `ServerError` (breaking change).
+- Disabled failure on empty query.
+
+# 1.5
+
+- Added column number to `RowError` (breaking change).
+- Added `MonadReader Connection` instance for Session.
diff --git a/README.md b/README.md
new file mode 100644
--- /dev/null
+++ b/README.md
@@ -0,0 +1,196 @@
+# Hasql
+
+[![Hackage](https://img.shields.io/hackage/v/hasql.svg)](https://hackage.haskell.org/package/hasql)
+[![Continuous Haddock](https://img.shields.io/badge/haddock-master-blue)](https://nikita-volkov.github.io/hasql/)
+
+PostgreSQL driver for Haskell, that prioritizes:
+
+- **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`.
+
+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).
+
+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.
+
+## Getting started
+
+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:
+  hasql,
+  pqi-ffi,  -- or pqi-native
+```
+
+`Hasql.Connection.acquire` then takes the adapter explicitly, as its first argument:
+
+```haskell
+connection <- Hasql.Connection.acquire Pqi.Ffi.adapter settings
+```
+
+["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.
+
+## Example
+
+Following is a complete application, which sums three numbers in Postgres by running one statement twice on the same connection.
+
+```haskell
+{-# LANGUAGE OverloadedStrings #-}
+
+import Data.Functor.Contravariant
+import Data.Int
+import Hasql.Session (Session)
+import Prelude
+import qualified Hasql.Connection as Connection
+import qualified Hasql.Connection.Settings as Settings
+import qualified Hasql.Decoders as Decoders
+import qualified Hasql.Encoders as Encoders
+import qualified Hasql.Session as Session
+import qualified Hasql.Statement as Statement
+import qualified Pqi.Ffi
+
+main :: IO ()
+main = do
+  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
+    settings =
+      mconcat
+        [ Settings.hostAndPort "localhost" 5432,
+          Settings.user "postgres",
+          Settings.password "postgres",
+          Settings.dbname "postgres"
+          -- Prepared statements are enabled by default.
+          -- To disable them (e.g., for pgbouncer compatibility):
+          -- Settings.noPreparedStatements True
+        ]
+
+-- | 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
+
+-- | 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
+    sql =
+      "select $1 + $2"
+    encoder =
+      mconcat
+        [ fst >$< Encoders.param (Encoders.nonNullable Encoders.int8),
+          snd >$< Encoders.param (Encoders.nonNullable Encoders.int8)
+        ]
+    decoder =
+      Decoders.singleRow
+        (Decoders.column (Decoders.nonNullable Decoders.int8))
+```
+
+[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.
+
+## Errors
+
+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.
+
+`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) -> ...
+```
+
+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
+
+This policy is intended to balance stability for users with the ability to evolve the library.
+
+Each major release of Hasql is supported for at least **one year** from the date of its first release. During this period, fixes are backported to the latest minor version of that major release.
+
+After the support period ends, the release may continue to work but is no longer guaranteed to receive fixes.
+
+You're welcome to post requests to change the policy or issues if you believe something is not being addressed.
diff --git a/Setup.hs b/Setup.hs
deleted file mode 100644
--- a/Setup.hs
+++ /dev/null
@@ -1,2 +0,0 @@
-import Distribution.Simple
-main = defaultMain
diff --git a/benchmarks/Main.hs b/benchmarks/Main.hs
deleted file mode 100644
--- a/benchmarks/Main.hs
+++ /dev/null
@@ -1,107 +0,0 @@
-module Main where
-
-import Prelude
-import Bug
-import Criterion
-import Criterion.Main
-import qualified Hasql.Connection as A
-import qualified Hasql.Session as B
-import qualified Hasql.Query as C
-import qualified Hasql.Decoders as D
-import qualified Hasql.Encoders as E
-import qualified Data.Vector as F
-
-
-main =
-  do
-    Right connection <- acquireConnection
-    useConnection connection
-  where
-    acquireConnection =
-      A.acquire ""
-    useConnection connection =
-      defaultMain
-      [
-        sessionBench "largeResultInVector" sessionWithSingleLargeResultInVector
-        ,
-        sessionBench "largeResultInList" sessionWithSingleLargeResultInList
-        ,
-        sessionBench "manyLargeResults" sessionWithManyLargeResults
-        ,
-        sessionBench "manySmallResults" sessionWithManySmallResults
-      ]
-      where
-        sessionBench :: NFData a => String -> B.Session a -> Benchmark
-        sessionBench name session =
-          bench name (nfIO (fmap (either ($bug "") id) (B.run session connection)))
-
-
--- * Sessions
--------------------------
-
-sessionWithManySmallParameters :: Vector (Int64, Int64) -> B.Session ()
-sessionWithManySmallParameters =
-  $(todo "sessionWithManySmallParameters")
-
-sessionWithSingleLargeResultInVector :: B.Session (Vector (Int64, Int64))
-sessionWithSingleLargeResultInVector =
-  B.query () queryWithManyRowsInVector
-
-sessionWithManyLargeResults :: B.Session [Vector (Int64, Int64)]
-sessionWithManyLargeResults =
-  replicateM 1000 (B.query () queryWithManyRowsInVector)
-
-sessionWithSingleLargeResultInList :: B.Session (List (Int64, Int64))
-sessionWithSingleLargeResultInList =
-  B.query () queryWithManyRowsInList
-
-sessionWithManySmallResults :: B.Session [(Int64, Int64)]
-sessionWithManySmallResults =
-  replicateM 1000 (B.query () queryWithSingleRow)
-
-
--- * Statements
--------------------------
-
-queryWithManyParameters :: C.Query (Vector (Int64, Int64)) ()
-queryWithManyParameters =
-  $(todo "statementWithManyParameters")
-
-queryWithSingleRow :: C.Query () (Int64, Int64)
-queryWithSingleRow =
-  C.statement template encoder decoder True
-  where
-    template =
-      "SELECT 1, 2"
-    encoder =
-      conquer
-    decoder =
-      D.singleRow row
-      where
-        row =
-          tuple <$> D.value D.int8 <*> D.value D.int8
-          where
-            tuple !a !b =
-              (a, b)
-
-queryWithManyRows :: (D.Row (Int64, Int64) -> D.Result result) -> C.Query () result
-queryWithManyRows decoder =
-  C.statement template encoder (decoder rowDecoder) True
-  where
-    template =
-      "SELECT generate_series(0,1000) as a, generate_series(1000,2000) as b"
-    encoder =
-      conquer
-    rowDecoder =
-      tuple <$> D.value D.int8 <*> D.value D.int8
-      where
-        tuple !a !b =
-          (a, b)
-
-queryWithManyRowsInVector :: C.Query () (Vector (Int64, Int64))
-queryWithManyRowsInVector =
-  queryWithManyRows D.rowsVector
-
-queryWithManyRowsInList :: C.Query () (List (Int64, Int64))
-queryWithManyRowsInList =
-  queryWithManyRows D.rowsList
diff --git a/hasql.cabal b/hasql.cabal
--- a/hasql.cabal
+++ b/hasql.cabal
@@ -1,205 +1,393 @@
-name:
-  hasql
-version:
-  1.1.1
-category:
-  Hasql, Database, PostgreSQL
-synopsis:
-  An efficient PostgreSQL driver and a flexible mapping API
+cabal-version: 3.0
+name: hasql
+version: 2.1.0.0
+category: Hasql, Database, PostgreSQL
+synopsis: Fast PostgreSQL driver with a flexible mapping API
 description:
-  This package is the root of the \"hasql\" ecosystem.
-  .
-  The API is completely disinfected from exceptions. All error-reporting is explicit and is presented using the 'Either' type.
-  .
-  The version 1 is completely backward-compatible with 0.19.
-homepage:
-  https://github.com/nikita-volkov/hasql 
-bug-reports:
-  https://github.com/nikita-volkov/hasql/issues 
-author:
-  Nikita Volkov <nikita.y.volkov@mail.ru>
-maintainer:
-  Nikita Volkov <nikita.y.volkov@mail.ru>
-copyright:
-  (c) 2014, Nikita Volkov
-license:
-  MIT
-license-file:
-  LICENSE
-build-type:
-  Simple
-cabal-version:
-  >=1.10
+  Root of the \"hasql\" ecosystem.
+  This library provides connection management, execution of queries and mapping of parameters and results.
+  Extended functionality such as pooling, transactions and compile-time checking of SQL is provided by extension libraries.
+  For more details and tutorials see <https://github.com/nikita-volkov/hasql the readme>.
 
+  All error-reporting is explicit:
+  database, protocol and connection failures are reported via the 'Either' type
+  instead of being thrown as exceptions.
 
+  The transport layer is pluggable via <https://hackage.haskell.org/package/pqi pqi>,
+  so \"hasql\" itself carries no C dependency.
+  To compile an application you need to depend on \"hasql\" together with one adapter package
+  and pass that adapter to @Hasql.Connection.acquire@ as its first argument.
+  Two adapters are available:
+
+  * <https://hackage.haskell.org/package/pqi-ffi pqi-ffi> -
+    the stable, production-proven adapter, backed by the C \"libpq\" library.
+    It requires \"libpq\" of at least version 14 to be installed to compile.
+    \"libpq\" comes distributed with PostgreSQL,
+    so typically all you need is just to install the latest PostgreSQL distro.
+    Via this adapter \"hasql\" is thoroughly tested to be compatible
+    with a wide range of PostgreSQL servers starting from version 9.
+
+  * <https://hackage.haskell.org/package/pqi-native pqi-native> -
+    a pure-Haskell adapter, which speaks the PostgreSQL wire protocol directly
+    and thus requires no C dependency at all.
+    It is thoroughly tested:
+    <https://github.com/nikita-volkov/pqi-conformance 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\" and \"hasql-transaction\"
+    run against both adapters.
+    It is still labelled __alpha__, but is fully interchangeable with \"pqi-ffi\":
+    switching between the two is a one-line change.
+
+homepage: https://github.com/nikita-volkov/hasql
+bug-reports: https://github.com/nikita-volkov/hasql/issues
+author: Nikita Volkov <nikita.y.volkov@mail.ru>
+maintainer: Nikita Volkov <nikita.y.volkov@mail.ru>
+copyright: (c) 2014, Nikita Volkov
+license: MIT
+license-file: LICENSE
+extra-source-files:
+  README.md
+
+extra-doc-files:
+  CHANGELOG.md
+
 source-repository head
-  type:
-    git
-  location:
-    git://github.com/nikita-volkov/hasql.git
+  type: git
+  location: https://github.com/nikita-volkov/hasql
 
+common base
+  default-language: Haskell2010
+  default-extensions:
+    ApplicativeDo
+    Arrows
+    BangPatterns
+    BlockArguments
+    ConstraintKinds
+    DataKinds
+    DefaultSignatures
+    DeriveAnyClass
+    DeriveFoldable
+    DeriveFunctor
+    DeriveGeneric
+    DeriveTraversable
+    DerivingVia
+    DuplicateRecordFields
+    EmptyDataDecls
+    FlexibleContexts
+    FlexibleInstances
+    FunctionalDependencies
+    GADTs
+    GeneralizedNewtypeDeriving
+    ImportQualifiedPost
+    LambdaCase
+    LiberalTypeSynonyms
+    MultiParamTypeClasses
+    MultiWayIf
+    NamedFieldPuns
+    NoImplicitPrelude
+    NoMonomorphismRestriction
+    NumericUnderscores
+    OverloadedStrings
+    PatternGuards
+    QuasiQuotes
+    RankNTypes
+    RecordWildCards
+    RoleAnnotations
+    ScopedTypeVariables
+    StandaloneDeriving
+    StrictData
+    TupleSections
+    TypeApplications
+    TypeFamilies
+    TypeOperators
+    ViewPatterns
 
-library
-  hs-source-dirs:
-    library
+common executable
+  import: base
   ghc-options:
-  default-extensions:
-    Arrows, BangPatterns, ConstraintKinds, DataKinds, DefaultSignatures, DeriveDataTypeable, DeriveFoldable, DeriveFunctor, DeriveGeneric, DeriveTraversable, EmptyDataDecls, FlexibleContexts, FlexibleInstances, FunctionalDependencies, GADTs, GeneralizedNewtypeDeriving, LambdaCase, LiberalTypeSynonyms, MagicHash, MultiParamTypeClasses, MultiWayIf, NoImplicitPrelude, NoMonomorphismRestriction, OverloadedStrings, PatternGuards, ParallelListComp, QuasiQuotes, RankNTypes, RecordWildCards, ScopedTypeVariables, StandaloneDeriving, TemplateHaskell, TupleSections, TypeFamilies, TypeOperators, UnboxedTuples
-  default-language:
-    Haskell2010
-  other-modules:
-    Hasql.Private.Prelude
-    Hasql.Private.PTI
-    Hasql.Private.IO
-    Hasql.Private.Query
-    Hasql.Private.Session
-    Hasql.Private.Connection
-    Hasql.Private.PreparedStatementRegistry
-    Hasql.Private.Settings
-    Hasql.Private.Commands
-    Hasql.Private.Decoders.Array
-    Hasql.Private.Decoders.Composite
-    Hasql.Private.Decoders.Value
-    Hasql.Private.Decoders.Row
-    Hasql.Private.Decoders.Result
-    Hasql.Private.Decoders.Results
-    Hasql.Private.Encoders.Array
-    Hasql.Private.Encoders.Value
-    Hasql.Private.Encoders.Params
+    -O2
+    -threaded
+    -with-rtsopts=-N
+    -rtsopts
+    -funbox-strict-fields
+
+common test
+  import: base
+  ghc-options:
+    -threaded
+    -with-rtsopts=-N
+
+library
+  import: base
+  hs-source-dirs: src/library
   exposed-modules:
+    Hasql.Connection
+    Hasql.Connection.Settings
     Hasql.Decoders
     Hasql.Encoders
-    Hasql.Connection
-    Hasql.Query
+    Hasql.Errors
+    Hasql.Pipeline
     Hasql.Session
+    Hasql.Statement
+
+  other-modules:
+    Hasql.Codecs.Decoders
+    Hasql.Codecs.Decoders.Array
+    Hasql.Codecs.Decoders.Composite
+    Hasql.Codecs.Decoders.NullableOrNot
+    Hasql.Codecs.Decoders.Value
+    Hasql.Codecs.Encoders
+    Hasql.Codecs.Encoders.Array
+    Hasql.Codecs.Encoders.Composite
+    Hasql.Codecs.Encoders.NullableOrNot
+    Hasql.Codecs.Encoders.Params
+    Hasql.Codecs.Encoders.Value
+    Hasql.Connection.Config
+    Hasql.Connection.ServerVersion
+    Hasql.Engine.Contexts.Pipeline
+    Hasql.Engine.Contexts.Session
+    Hasql.Engine.Decoders.Result
+    Hasql.Engine.Decoders.Row
+    Hasql.Engine.Errors
+    Hasql.Engine.PqProcedures.SelectTypeInfo
+    Hasql.Engine.Statement
+
   build-depends:
-    -- parsing:
-    attoparsec >= 0.10 && < 0.14,
-    -- database:
-    postgresql-binary >= 0.12.1 && < 0.13,
-    postgresql-libpq == 0.9.*,
-    -- builders:
-    bytestring-strict-builder >= 0.4 && < 0.5,
-    -- data:
-    dlist >= 0.7 && < 0.9,
-    vector >= 0.10 && < 0.13,
-    hashtables >= 1.1 && < 2,
-    text >= 1 && < 2,
-    bytestring >= 0.10 && < 0.11,
-    hashable >= 1.2 && < 1.3,
-    -- control:
-    semigroups >= 0.18 && < 0.20,
-    data-default-class >= 0.0.1 && < 0.2,
-    profunctors >= 5.1 && < 6,
-    contravariant-extras == 0.3.*,
-    contravariant >= 1.3 && < 2,
-    mtl >= 2 && < 3,
-    transformers >= 0.3 && < 0.6,
-    -- errors:
-    loch-th == 0.2.*,
-    placeholders == 0.1.*,
-    -- general:
-    base-prelude >= 0.1.19 && < 2,
-    base >= 4.6 && < 5
+    aeson >=2 && <3,
+    bytestring >=0.10 && <0.13,
+    bytestring-strict-builder >=0.4.5.4 && <0.5,
+    hasql:codecs-vocab,
+    hasql:comms,
+    hasql:connection-state,
+    hasql:platform,
+    hasql:to-be-resolved,
+    iproute >=1.7 && <1.9,
+    postgresql-binary ^>=0.15,
+    postgresql-connection-string ^>=0.1,
+    pqi >=1.0 && <1.2,
+    text >=1 && <3,
+    text-builder >=1 && <1.1,
+    unordered-containers >=0.2 && <0.3,
+    vector >=0.10 && <0.14,
 
+library platform
+  import: base
+  hs-source-dirs: src/platform
+  exposed-modules:
+    Hasql.Platform.Prelude
 
-test-suite tasty
-  type:
-    exitcode-stdio-1.0
-  hs-source-dirs:
-    tasty
-  main-is:
-    Main.hs
   other-modules:
-    Main.DSL
-    Main.Connection
-    Main.Queries
-    Main.Prelude
-  default-extensions:
-    Arrows, BangPatterns, ConstraintKinds, DataKinds, DefaultSignatures, DeriveDataTypeable, DeriveFoldable, DeriveFunctor, DeriveGeneric, DeriveTraversable, EmptyDataDecls, FlexibleContexts, FlexibleInstances, FunctionalDependencies, GADTs, GeneralizedNewtypeDeriving, LambdaCase, LiberalTypeSynonyms, MagicHash, MultiParamTypeClasses, MultiWayIf, NoImplicitPrelude, NoMonomorphismRestriction, OverloadedStrings, PatternGuards, ParallelListComp, QuasiQuotes, RankNTypes, RecordWildCards, ScopedTypeVariables, StandaloneDeriving, TemplateHaskell, TupleSections, TypeFamilies, TypeOperators, UnboxedTuples
-  default-language:
-    Haskell2010
+    Hasql.Platform.Prelude.Text
+
   build-depends:
-    -- database:
-    hasql,
-    -- testing:
-    tasty >= 0.12 && < 0.13,
-    tasty-quickcheck >= 0.9 && < 0.10,
-    tasty-hunit >= 0.9 && < 0.10,
-    quickcheck-instances >= 0.3.11 && < 0.4,
-    QuickCheck >= 2.8.1 && < 3,
-    -- general:
-    data-default-class,
-    -- 
-    rerebase < 2
+    base >=4.14 && <5,
+    bytestring >=0.10 && <0.13,
+    comonad ^>=5,
+    contravariant >=1.3 && <2,
+    dlist >=0.8 && <0.9 || >=1 && <2,
+    hashable >=1.2 && <2,
+    mtl >=2 && <3,
+    profunctors >=5.1 && <6,
+    scientific >=0.3 && <0.4,
+    text >=1 && <3,
+    text-builder >=1 && <1.1,
+    time >=1.9 && <2,
+    transformers >=0.5 && <0.7,
+    unordered-containers >=0.2 && <0.3,
+    uuid >=1.3 && <2,
+    vector >=0.10 && <0.14,
+    witherable >=0.5 && <0.6,
 
+library to-be-resolved
+  import: base
+  hs-source-dirs: src/to-be-resolved
+  exposed-modules:
+    Hasql.ToBeResolved
 
-test-suite threads-test
-  type:
-    exitcode-stdio-1.0
-  hs-source-dirs:
-    threads-test
-  main-is:
-    Main.hs
-  other-modules:
-    Main.Queries
-  ghc-options:
-    -O2
-    -threaded
-    "-with-rtsopts=-N"
-  default-extensions:
-    Arrows, BangPatterns, ConstraintKinds, DataKinds, DefaultSignatures, DeriveDataTypeable, DeriveFoldable, DeriveFunctor, DeriveGeneric, DeriveTraversable, EmptyDataDecls, FlexibleContexts, FlexibleInstances, FunctionalDependencies, GADTs, GeneralizedNewtypeDeriving, LambdaCase, LiberalTypeSynonyms, MagicHash, MultiParamTypeClasses, MultiWayIf, NoImplicitPrelude, NoMonomorphismRestriction, OverloadedStrings, PatternGuards, ParallelListComp, QuasiQuotes, RankNTypes, RecordWildCards, ScopedTypeVariables, StandaloneDeriving, TemplateHaskell, TupleSections, TypeFamilies, TypeOperators, UnboxedTuples
-  default-language:
-    Haskell2010
   build-depends:
-    -- database:
-    hasql,
-    -- 
-    rebase
+    base >=4.14 && <5
 
+library codecs-vocab
+  import: base
+  hs-source-dirs: src/codecs-vocab
+  exposed-modules:
+    Hasql.CodecsVocab
+    Hasql.CodecsVocab.QualifiedTypeName
+    Hasql.CodecsVocab.TypeInfo
+    Hasql.CodecsVocab.TypeRef
+    Hasql.CodecsVocab.TypeShape
 
+  build-depends:
+    hasql:platform
+
+library connection-state
+  import: base
+  hs-source-dirs: src/connection-state
+  exposed-modules:
+    Hasql.ConnectionState
+    Hasql.ConnectionState.OidCache
+    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,
+    unordered-containers >=0.2 && <0.3,
+
+library comms
+  import: base
+  hs-source-dirs: src/comms
+  exposed-modules:
+    Hasql.Comms.Recv
+    Hasql.Comms.ResultDecoder
+    Hasql.Comms.Roundtrip
+    Hasql.Comms.RowDecoder
+    Hasql.Comms.RowReader
+    Hasql.Comms.Send
+
+  build-depends:
+    attoparsec >=0.10 && <0.15,
+    bytestring >=0.10 && <0.13,
+    hasql:platform,
+    pqi >=1.0 && <1.2,
+    vector >=0.10 && <0.14,
+
 benchmark benchmarks
-  type: 
-    exitcode-stdio-1.0
-  hs-source-dirs:
-    benchmarks
-  main-is:
-    Main.hs
-  ghc-options:
-    -O2
-    -threaded
-    "-with-rtsopts=-N"
-    -rtsopts
-    -funbox-strict-fields
-  default-extensions:
-    Arrows, BangPatterns, ConstraintKinds, DataKinds, DefaultSignatures, DeriveDataTypeable, DeriveFoldable, DeriveFunctor, DeriveGeneric, DeriveTraversable, EmptyDataDecls, FlexibleContexts, FlexibleInstances, FunctionalDependencies, GADTs, GeneralizedNewtypeDeriving, LambdaCase, LiberalTypeSynonyms, MagicHash, MultiParamTypeClasses, MultiWayIf, NoImplicitPrelude, NoMonomorphismRestriction, OverloadedStrings, PatternGuards, ParallelListComp, QuasiQuotes, RankNTypes, RecordWildCards, ScopedTypeVariables, StandaloneDeriving, TemplateHaskell, TupleSections, TypeFamilies, TypeOperators, UnboxedTuples
-  default-language:
-    Haskell2010
+  import: executable
+  type: exitcode-stdio-1.0
+  hs-source-dirs: src/benchmarks
+  main-is: Main.hs
   build-depends:
+    criterion >=1.6 && <2,
     hasql,
-    -- benchmarking:
-    criterion >= 1.1 && < 2,
-    -- general:
-    bug == 1.*,
-    rerebase < 2
-
+    pqi-ffi ^>=1.0,
+    pqi-native ^>=1.0.1.0,
+    rerebase <2,
 
 test-suite profiling
-  type:
-    exitcode-stdio-1.0
-  hs-source-dirs:
-    profiling
-  main-is:
-    Main.hs
+  import: base
+  type: exitcode-stdio-1.0
+  hs-source-dirs: src/profiling
+  main-is: Main.hs
   ghc-options:
     -O2
     -threaded
     -rtsopts
-  default-extensions:
-    Arrows, BangPatterns, ConstraintKinds, DataKinds, DefaultSignatures, DeriveDataTypeable, DeriveFoldable, DeriveFunctor, DeriveGeneric, DeriveTraversable, EmptyDataDecls, FlexibleContexts, FlexibleInstances, FunctionalDependencies, GADTs, GeneralizedNewtypeDeriving, LambdaCase, LiberalTypeSynonyms, MagicHash, MultiParamTypeClasses, MultiWayIf, NoImplicitPrelude, NoMonomorphismRestriction, OverloadedStrings, PatternGuards, ParallelListComp, QuasiQuotes, RankNTypes, RecordWildCards, ScopedTypeVariables, StandaloneDeriving, TemplateHaskell, TupleSections, TypeFamilies, TypeOperators, UnboxedTuples
-  default-language:
-    Haskell2010
+
   build-depends:
     hasql,
-    bug == 1.*,
-    rerebase == 1.*
+    pqi-ffi ^>=1.0,
+    rerebase >=1 && <2,
+    testcontainers-postgresql ^>=0.2,
+
+test-suite connection-state-tests
+  import: test
+  type: exitcode-stdio-1.0
+  hs-source-dirs: src/connection-state-tests
+  main-is: Main.hs
+  other-modules:
+    Hasql.ConnectionState.OidCacheSpec
+    Hasql.ConnectionState.StatementCacheSpec
+
+  build-tool-depends:
+    hspec-discover:hspec-discover ^>=2.11.12
+
+  build-depends:
+    base >=4.14 && <5,
+    bytestring >=0.10 && <0.13,
+    hasql:codecs-vocab,
+    hasql:connection-state,
+    hspec ^>=2.11.12,
+    unordered-containers >=0.2 && <0.3,
+
+test-suite library-tests
+  import: test
+  type: exitcode-stdio-1.0
+  hs-source-dirs: src/library-tests
+  main-is: Main.hs
+  other-modules:
+    Helpers.Adapters
+    Helpers.Dsls.Execution
+    Helpers.Dsls.Statement
+    Helpers.PostgresContainer
+    Helpers.Scripts
+    Helpers.Statements
+    Helpers.Statements.BrokenSyntax
+    Helpers.Statements.CountPreparedStatements
+    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.InterruptionSpec
+    Integration.Sharing.Connection.UseSpec
+    Integration.Sharing.Decoders.CitextSpec
+    Integration.Sharing.Decoders.Composite.OidMismatchSpec
+    Integration.Sharing.Decoders.CompositeSpec
+    Integration.Sharing.Decoders.CustomSpec
+    Integration.Sharing.Decoders.DomainSpec
+    Integration.Sharing.Decoders.EnumSpec
+    Integration.Sharing.Decoders.Float8Spec
+    Integration.Sharing.Decoders.HstoreSpec
+    Integration.Sharing.Decoders.InetSpec
+    Integration.Sharing.Decoders.IntervalSpec
+    Integration.Sharing.Decoders.JsonSpec
+    Integration.Sharing.Decoders.RecordSpec
+    Integration.Sharing.Decoders.UuidSpec
+    Integration.Sharing.Encoders.ArraySpec
+    Integration.Sharing.Encoders.CitextSpec
+    Integration.Sharing.Encoders.Composite.OidMismatchSpec
+    Integration.Sharing.Encoders.CompositeSpec
+    Integration.Sharing.Encoders.CustomSpec
+    Integration.Sharing.Encoders.DomainSpec
+    Integration.Sharing.Encoders.EnumSpec
+    Integration.Sharing.Encoders.HstoreSpec
+    Integration.Sharing.Encoders.InetSpec
+    Integration.Sharing.Encoders.IntervalSpec
+    Integration.Sharing.Encoders.JsonSpec
+    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:
+    hspec-discover:hspec-discover ^>=2.11.12
+
+  build-depends:
+    aeson,
+    hasql,
+    hspec ^>=2.11.12,
+    iproute,
+    pqi >=1.0 && <1.2,
+    pqi-ffi ^>=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,
diff --git a/library/Hasql/Connection.hs b/library/Hasql/Connection.hs
deleted file mode 100644
--- a/library/Hasql/Connection.hs
+++ /dev/null
@@ -1,16 +0,0 @@
--- |
--- This module provides a low-level effectful API dealing with the connections to the database.
-module Hasql.Connection
-(
-  Connection,
-  ConnectionError(..),
-  acquire,
-  release,
-  Settings,
-  settings,
-  withLibPQConnection
-)
-where
-
-import Hasql.Private.Connection
-import Hasql.Private.Settings
diff --git a/library/Hasql/Decoders.hs b/library/Hasql/Decoders.hs
deleted file mode 100644
--- a/library/Hasql/Decoders.hs
+++ /dev/null
@@ -1,713 +0,0 @@
--- |
--- A DSL for declaration of result decoders.
-module Hasql.Decoders
-(
-  -- * Result
-  Result,
-  unit,
-  rowsAffected,
-  singleRow,
-  -- ** Specialized multi-row results
-  maybeRow,
-  rowsVector,
-  rowsList,
-  -- ** Multi-row traversers
-  foldlRows,
-  foldrRows,
-  -- * Row
-  Row,
-  value,
-  nullableValue,
-  -- * Value
-  Value,
-  bool,
-  int2,
-  int4,
-  int8,
-  float4,
-  float8,
-  numeric,
-  char,
-  text,
-  bytea,
-  date,
-  timestamp,
-  timestamptz,
-  time,
-  timetz,
-  interval,
-  uuid,
-  inet,
-  json,
-  jsonBytes,
-  jsonb,
-  jsonbBytes,
-  array,
-  composite,
-  hstore,
-  enum,
-  custom,
-  -- * Array
-  Array,
-  arrayDimension,
-  arrayValue,
-  arrayNullableValue,
-  -- * Composite
-  Composite,
-  compositeValue,
-  compositeNullableValue,
-)
-where
-
-import Hasql.Private.Prelude hiding (maybe, bool)
-import qualified Data.Vector as Vector
-import qualified PostgreSQL.Binary.Decoding as A
-import qualified PostgreSQL.Binary.Data as B
-import qualified Hasql.Private.Decoders.Results as Results
-import qualified Hasql.Private.Decoders.Result as Result
-import qualified Hasql.Private.Decoders.Row as Row
-import qualified Hasql.Private.Decoders.Value as Value
-import qualified Hasql.Private.Decoders.Array as Array
-import qualified Hasql.Private.Decoders.Composite as Composite
-import qualified Hasql.Private.Prelude as Prelude
-
--- * Result
--------------------------
-
--- |
--- Decoder of a query result.
--- 
-newtype Result a =
-  Result (Results.Results a)
-  deriving (Functor)
-
--- |
--- Decode no value from the result.
--- 
--- Useful for statements like @INSERT@ or @CREATE@.
--- 
-{-# INLINABLE unit #-}
-unit :: Result ()
-unit =
-  Result (Results.single Result.unit)
-
--- |
--- Get the amount of rows affected by such statements as
--- @UPDATE@ or @DELETE@.
--- 
-{-# INLINABLE rowsAffected #-}
-rowsAffected :: Result Int64
-rowsAffected =
-  Result (Results.single Result.rowsAffected)
-
--- |
--- Exactly one row.
--- Will raise the 'Hasql.Query.UnexpectedAmountOfRows' error if it's any other.
--- 
-{-# INLINABLE singleRow #-}
-singleRow :: Row a -> Result a
-singleRow (Row row) =
-  Result (Results.single (Result.single row))
-
--- ** Multi-row traversers
--------------------------
-
--- |
--- Foldl multiple rows.
--- 
-{-# INLINABLE foldlRows #-}
-foldlRows :: (a -> b -> a) -> a -> Row b -> Result a
-foldlRows step init (Row row) =
-  Result (Results.single (Result.foldl step init row))
-
--- |
--- Foldr multiple rows.
--- 
-{-# INLINABLE foldrRows #-}
-foldrRows :: (b -> a -> a) -> a -> Row b -> Result a
-foldrRows step init (Row row) =
-  Result (Results.single (Result.foldr step init row))
-
--- ** Specialized multi-row results
--------------------------
-
--- |
--- Maybe one row or none.
--- 
-{-# INLINABLE maybeRow #-}
-maybeRow :: Row a -> Result (Maybe a)
-maybeRow (Row row) =
-  Result (Results.single (Result.maybe row))
-
--- |
--- Zero or more rows packed into the vector.
--- 
--- It's recommended to prefer this function to 'rowsList',
--- since it performs notably better.
--- 
-{-# INLINABLE rowsVector #-}
-rowsVector :: Row a -> Result (Vector a)
-rowsVector (Row row) =
-  Result (Results.single (Result.vector row))
-
--- |
--- Zero or more rows packed into the list.
--- 
-{-# INLINABLE rowsList #-}
-rowsList :: Row a -> Result [a]
-rowsList =
-  foldrRows strictCons []
-
-
--- ** Instances
--------------------------
-
--- | Maps to 'unit'.
-instance Default (Result ()) where
-  {-# INLINE def #-}
-  def =
-    unit
-
--- | Maps to 'rowsAffected'.
-instance Default (Result Int64) where
-  {-# INLINE def #-}
-  def =
-    rowsAffected
-
--- | Maps to @('maybeRow' def)@.
-instance Default (Row a) => Default (Result (Maybe a)) where
-  {-# INLINE def #-}
-  def =
-    maybeRow def
-
--- | Maps to @('rowsVector' def)@.
-instance Default (Row a) => Default (Result (Vector a)) where
-  {-# INLINE def #-}
-  def =
-    rowsVector def
-
--- | Maps to @('rowsList' def)@.
-instance Default (Row a) => Default (Result ([] a)) where
-  {-# INLINE def #-}
-  def =
-    rowsList def
-
--- | Maps to @(fmap Identity ('singleRow' def)@.
-instance Default (Row a) => Default (Result (Identity a)) where
-  {-# INLINE def #-}
-  def =
-    fmap Identity (singleRow def)
-
-
--- * Row
--------------------------
-
--- |
--- Decoder of an individual row,
--- which gets composed of column value decoders.
--- 
--- E.g.:
--- 
--- >x :: Row (Maybe Int64, Text, TimeOfDay)
--- >x =
--- >  (,,) <$> nullableValue int8 <*> value text <*> value time
--- 
-newtype Row a =
-  Row (Row.Row a)
-  deriving (Functor, Applicative, Monad)
-
--- |
--- Lift an individual non-nullable value decoder to a composable row decoder.
--- 
-{-# INLINABLE value #-}
-value :: Value a -> Row a
-value (Value imp) =
-  Row (Row.nonNullValue imp)
-
--- |
--- Lift an individual nullable value decoder to a composable row decoder.
--- 
-{-# INLINABLE nullableValue #-}
-nullableValue :: Value a -> Row (Maybe a)
-nullableValue (Value imp) =
-  Row (Row.value imp)
-
-
--- ** Instances
--------------------------
-
-instance Default (Value a) => Default (Row (Identity a)) where
-  {-# INLINE def #-}
-  def =
-    fmap Identity (value def)
-
-instance Default (Value a) => Default (Row (Maybe a)) where
-  {-# INLINE def #-}
-  def =
-    nullableValue def
-
-instance (Default (Value a1), Default (Value a2)) => Default (Row (a1, a2)) where
-  {-# INLINE def #-}
-  def =
-    ap (fmap (,) (value def)) (value def)
-
-
--- * Value
--------------------------
-
--- |
--- Decoder of an individual value.
--- 
-newtype Value a =
-  Value (Value.Value a)
-  deriving (Functor)
-
-
--- ** Plain value decoders
--------------------------
-
--- |
--- Decoder of the @BOOL@ values.
--- 
-{-# INLINABLE bool #-}
-bool :: Value Bool
-bool =
-  Value (Value.decoder (const A.bool))
-
--- |
--- Decoder of the @INT2@ values.
--- 
-{-# INLINABLE int2 #-}
-int2 :: Value Int16
-int2 =
-  Value (Value.decoder (const A.int))
-
--- |
--- Decoder of the @INT4@ values.
--- 
-{-# INLINABLE int4 #-}
-int4 :: Value Int32
-int4 =
-  Value (Value.decoder (const A.int))
-
--- |
--- Decoder of the @INT8@ values.
--- 
-{-# INLINABLE int8 #-}
-int8 :: Value Int64
-int8 =
-  {-# SCC "int8" #-} 
-  Value (Value.decoder (const ({-# SCC "int8.int" #-} A.int)))
-
--- |
--- Decoder of the @FLOAT4@ values.
--- 
-{-# INLINABLE float4 #-}
-float4 :: Value Float
-float4 =
-  Value (Value.decoder (const A.float4))
-
--- |
--- Decoder of the @FLOAT8@ values.
--- 
-{-# INLINABLE float8 #-}
-float8 :: Value Double
-float8 =
-  Value (Value.decoder (const A.float8))
-
--- |
--- Decoder of the @NUMERIC@ values.
--- 
-{-# INLINABLE numeric #-}
-numeric :: Value B.Scientific
-numeric =
-  Value (Value.decoder (const A.numeric))
-
--- |
--- Decoder of the @CHAR@ values.
--- Note that it supports UTF-8 values.
-{-# INLINABLE char #-}
-char :: Value Char
-char =
-  Value (Value.decoder (const A.char))
-
--- |
--- Decoder of the @TEXT@ values.
--- 
-{-# INLINABLE text #-}
-text :: Value Text
-text =
-  Value (Value.decoder (const A.text_strict))
-
--- |
--- Decoder of the @BYTEA@ values.
--- 
-{-# INLINABLE bytea #-}
-bytea :: Value ByteString
-bytea =
-  Value (Value.decoder (const A.bytea_strict))
-
--- |
--- Decoder of the @DATE@ values.
--- 
-{-# INLINABLE date #-}
-date :: Value B.Day
-date =
-  Value (Value.decoder (const A.date))
-
--- |
--- Decoder of the @TIMESTAMP@ values.
--- 
-{-# INLINABLE timestamp #-}
-timestamp :: Value B.LocalTime
-timestamp =
-  Value (Value.decoder (Prelude.bool A.timestamp_float A.timestamp_int))
-
--- |
--- Decoder of the @TIMESTAMPTZ@ values.
--- 
--- /NOTICE/
--- 
--- Postgres does not store the timezone information of @TIMESTAMPTZ@.
--- Instead it stores a UTC value and performs silent conversions
--- to the currently set timezone, when dealt with in the text format.
--- However this library bypasses the silent conversions
--- and communicates with Postgres using the UTC values directly.
-{-# INLINABLE timestamptz #-}
-timestamptz :: Value B.UTCTime
-timestamptz =
-  Value (Value.decoder (Prelude.bool A.timestamptz_float A.timestamptz_int))
-
--- |
--- Decoder of the @TIME@ values.
--- 
-{-# INLINABLE time #-}
-time :: Value B.TimeOfDay
-time =
-  Value (Value.decoder (Prelude.bool A.time_float A.time_int))
-
--- |
--- Decoder of the @TIMETZ@ values.
--- 
--- Unlike in case of @TIMESTAMPTZ@, 
--- Postgres does store the timezone information for @TIMETZ@.
--- However the Haskell's \"time\" library does not contain any composite type,
--- that fits the task, so we use a pair of 'TimeOfDay' and 'TimeZone'
--- to represent a value on the Haskell's side.
-{-# INLINABLE timetz #-}
-timetz :: Value (B.TimeOfDay, B.TimeZone)
-timetz =
-  Value (Value.decoder (Prelude.bool A.timetz_float A.timetz_int))
-
--- |
--- Decoder of the @INTERVAL@ values.
--- 
-{-# INLINABLE interval #-}
-interval :: Value B.DiffTime
-interval =
-  Value (Value.decoder (Prelude.bool A.interval_float A.interval_int))
-
--- |
--- Decoder of the @UUID@ values.
--- 
-{-# INLINABLE uuid #-}
-uuid :: Value B.UUID
-uuid =
-  Value (Value.decoder (const A.uuid))
-
--- |
--- Decoder of the @INET@ values.
---
-{-# INLINABLE inet #-}
-inet :: Value (B.NetAddr B.IP)
-inet =
-  Value (Value.decoder (const A.inet))
-
--- |
--- Decoder of the @JSON@ values into a JSON AST.
--- 
-{-# INLINABLE json #-}
-json :: Value B.Value
-json =
-  Value (Value.decoder (const A.json_ast))
-
--- |
--- Decoder of the @JSON@ values into a raw JSON 'ByteString'.
--- 
-{-# INLINABLE jsonBytes #-}
-jsonBytes :: (ByteString -> Either Text a) -> Value a
-jsonBytes fn =
-  Value (Value.decoder (const (A.json_bytes fn)))
-
--- |
--- Decoder of the @JSONB@ values into a JSON AST.
--- 
-{-# INLINABLE jsonb #-}
-jsonb :: Value B.Value
-jsonb =
-  Value (Value.decoder (const A.jsonb_ast))
-
--- |
--- Decoder of the @JSONB@ values into a raw JSON 'ByteString'.
--- 
-{-# INLINABLE jsonbBytes #-}
-jsonbBytes :: (ByteString -> Either Text a) -> Value a
-jsonbBytes fn =
-  Value (Value.decoder (const (A.jsonb_bytes fn)))
-
--- |
--- Lifts a custom value decoder function to a 'Value' decoder.
--- 
-{-# INLINABLE custom #-}
-custom :: (Bool -> ByteString -> Either Text a) -> Value a
-custom fn =
-  Value (Value.decoderFn fn)
-
-
--- ** Composite value decoders
--------------------------
-
--- |
--- Lifts the 'Array' decoder to the 'Value' decoder.
--- 
-{-# INLINABLE array #-}
-array :: Array a -> Value a
-array (Array imp) =
-  Value (Value.decoder (Array.run imp))
-
--- |
--- Lifts the 'Composite' decoder to the 'Value' decoder.
--- 
-{-# INLINABLE composite #-}
-composite :: Composite a -> Value a
-composite (Composite imp) =
-  Value (Value.decoder (Composite.run imp))
-
--- |
--- A generic decoder of @HSTORE@ values.
--- 
--- Here's how you can use it to construct a specific value:
--- 
--- @
--- x :: Value [(Text, Maybe Text)]
--- x =
---   hstore 'replicateM'
--- @
--- 
-{-# INLINABLE hstore #-}
-hstore :: (forall m. Monad m => Int -> m (Text, Maybe Text) -> m a) -> Value a
-hstore replicateM =
-  Value (Value.decoder (const (A.hstore replicateM A.text_strict A.text_strict)))
-
--- |
--- Given a partial mapping from text to value,
--- produces a decoder of that value.
-enum :: (Text -> Maybe a) -> Value a
-enum mapping =
-  Value (Value.decoder (const (A.enum mapping)))
-
-
--- ** Instances
--------------------------
-
--- |
--- Maps to 'bool'.
-instance Default (Value Bool) where
-  {-# INLINE def #-}
-  def =
-    bool
-
--- |
--- Maps to 'int2'.
-instance Default (Value Int16) where
-  {-# INLINE def #-}
-  def =
-    int2
-
--- |
--- Maps to 'int4'.
-instance Default (Value Int32) where
-  {-# INLINE def #-}
-  def =
-    int4
-
--- |
--- Maps to 'int8'.
-instance Default (Value Int64) where
-  {-# INLINE def #-}
-  def =
-    int8
-
--- |
--- Maps to 'float4'.
-instance Default (Value Float) where
-  {-# INLINE def #-}
-  def =
-    float4
-
--- |
--- Maps to 'float8'.
-instance Default (Value Double) where
-  {-# INLINE def #-}
-  def =
-    float8
-
--- |
--- Maps to 'numeric'.
-instance Default (Value B.Scientific) where
-  {-# INLINE def #-}
-  def =
-    numeric
-
--- |
--- Maps to 'char'.
-instance Default (Value Char) where
-  {-# INLINE def #-}
-  def =
-    char
-
--- |
--- Maps to 'text'.
-instance Default (Value Text) where
-  {-# INLINE def #-}
-  def =
-    text
-
--- |
--- Maps to 'bytea'.
-instance Default (Value ByteString) where
-  {-# INLINE def #-}
-  def =
-    bytea
-
--- |
--- Maps to 'date'.
-instance Default (Value B.Day) where
-  {-# INLINE def #-}
-  def =
-    date
-
--- |
--- Maps to 'timestamp'.
-instance Default (Value B.LocalTime) where
-  {-# INLINE def #-}
-  def =
-    timestamp
-
--- |
--- Maps to 'timestamptz'.
-instance Default (Value B.UTCTime) where
-  {-# INLINE def #-}
-  def =
-    timestamptz
-
--- |
--- Maps to 'time'.
-instance Default (Value B.TimeOfDay) where
-  {-# INLINE def #-}
-  def =
-    time
-
--- |
--- Maps to 'timetz'.
-instance Default (Value (B.TimeOfDay, B.TimeZone)) where
-  {-# INLINE def #-}
-  def =
-    timetz
-
--- |
--- Maps to 'interval'.
-instance Default (Value B.DiffTime) where
-  {-# INLINE def #-}
-  def =
-    interval
-
--- |
--- Maps to 'uuid'.
-instance Default (Value B.UUID) where
-  {-# INLINE def #-}
-  def =
-    uuid
-
--- |
--- Maps to 'json'.
-instance Default (Value B.Value) where
-  {-# INLINE def #-}
-  def =
-    json
-
-
--- * Array decoders
--------------------------
-
--- |
--- A generic array decoder.
--- 
--- Here's how you can use it to produce a specific array value decoder:
--- 
--- @
--- x :: Value [[Text]]
--- x =
---   array (arrayDimension 'replicateM' (arrayDimension 'replicateM' (arrayValue text)))
--- @
--- 
-newtype Array a =
-  Array (Array.Array a)
-  deriving (Functor)
-
--- |
--- A function for parsing a dimension of an array.
--- Provides support for multi-dimensional arrays.
--- 
--- Accepts:
--- 
--- * An implementation of the @replicateM@ function
--- (@Control.Monad.'Control.Monad.replicateM'@, @Data.Vector.'Data.Vector.replicateM'@),
--- which determines the output value.
--- 
--- * A decoder of its components, which can be either another 'arrayDimension',
--- 'arrayValue' or 'arrayNullableValue'.
--- 
-{-# INLINABLE arrayDimension #-}
-arrayDimension :: (forall m. Monad m => Int -> m a -> m b) -> Array a -> Array b
-arrayDimension replicateM (Array imp) =
-  Array (Array.dimension replicateM imp)
-
--- |
--- Lift a 'Value' decoder into an 'Array' decoder for parsing of non-nullable leaf values.
-{-# INLINABLE arrayValue #-}
-arrayValue :: Value a -> Array a
-arrayValue (Value imp) =
-  Array (Array.nonNullValue (Value.run imp))
-
--- |
--- Lift a 'Value' decoder into an 'Array' decoder for parsing of nullable leaf values.
-{-# INLINABLE arrayNullableValue #-}
-arrayNullableValue :: Value a -> Array (Maybe a)
-arrayNullableValue (Value imp) =
-  Array (Array.value (Value.run imp))
-
-
--- * Composite decoders
--------------------------
-
--- |
--- Composable decoder of composite values (rows, records).
-newtype Composite a =
-  Composite (Composite.Composite a)
-  deriving (Functor, Applicative, Monad)
-
--- |
--- Lift a 'Value' decoder into a 'Composite' decoder for parsing of non-nullable leaf values.
-{-# INLINABLE compositeValue #-}
-compositeValue :: Value a -> Composite a
-compositeValue (Value imp) =
-  Composite (Composite.nonNullValue (Value.run imp))
-
--- |
--- Lift a 'Value' decoder into a 'Composite' decoder for parsing of nullable leaf values.
-{-# INLINABLE compositeNullableValue #-}
-compositeNullableValue :: Value a -> Composite (Maybe a)
-compositeNullableValue (Value imp) =
-  Composite (Composite.value (Value.run imp))
-
diff --git a/library/Hasql/Encoders.hs b/library/Hasql/Encoders.hs
deleted file mode 100644
--- a/library/Hasql/Encoders.hs
+++ /dev/null
@@ -1,556 +0,0 @@
--- |
--- A DSL for declaration of query parameter encoders.
-module Hasql.Encoders
-(
-  -- * Params
-  Params,
-  unit,
-  value,
-  nullableValue,
-  -- * Value
-  Value,
-  bool,
-  int2,
-  int4,
-  int8,
-  float4,
-  float8,
-  numeric,
-  char,
-  text,
-  bytea,
-  date,
-  timestamp,
-  timestamptz,
-  time,
-  timetz,
-  interval,
-  uuid,
-  inet,
-  json,
-  jsonBytes,
-  jsonb,
-  jsonbBytes,
-  array,
-  enum,
-  unknown,
-  -- * Array
-  Array,
-  arrayValue,
-  arrayNullableValue,
-  arrayDimension,
-  -- ** Insert Many
-  -- $insertMany
-)
-where
-
-import Hasql.Private.Prelude hiding (bool)
-import qualified PostgreSQL.Binary.Encoding as A
-import qualified PostgreSQL.Binary.Data as B
-import qualified Hasql.Private.Encoders.Params as Params
-import qualified Hasql.Private.Encoders.Value as Value
-import qualified Hasql.Private.Encoders.Array as Array
-import qualified Hasql.Private.PTI as PTI
-import qualified Hasql.Private.Prelude as Prelude
-
--- * Parameters Product Encoder
--------------------------
-
--- |
--- Encoder of some representation of the parameters product.
--- 
--- Has instances of 'Contravariant', 'Divisible' and 'Monoid',
--- which you can use to compose multiple parameters together.
--- E.g.,
--- 
--- @
--- someParamsEncoder :: 'Params' (Int64, Maybe Text)
--- someParamsEncoder =
---   'contramap' 'fst' ('value' 'int8') '<>'
---   'contramap' 'snd' ('nullableValue' 'text')
--- @
--- 
--- As a general solution for tuples of any arity, instead of 'fst' and 'snd',
--- consider the functions of the @contrazip@ family
--- from the \"contravariant-extras\" package.
--- E.g., here's how you can achieve the same as the above:
--- 
--- @
--- someParamsEncoder :: 'Params' (Int64, Maybe Text)
--- someParamsEncoder =
---   'contrazip2' ('value' 'int8') ('nullableValue' 'text')
--- @
--- 
--- Here's how you can implement encoders for custom composite types:
--- 
--- @
--- data Person =
---   Person { name :: Text, gender :: Gender, age :: Int }
--- 
--- data Gender =
---   Male | Female
--- 
--- personParams :: 'Params' Person
--- personParams =
---   'contramap' name ('value' 'text') '<>'
---   'contramap' gender ('value' genderValue) '<>'
---   'contramap' (fromIntegral . age) ('value' 'int8')
--- 
--- genderValue :: 'Value' Gender
--- genderValue =
---   'contramap' genderText 'text'
---   where
---     genderText gender =
---       case gender of
---         Male -> "male"
---         Female -> "female"
--- @
--- 
-newtype Params a =
-  Params (Params.Params a)
-  deriving (Contravariant, Divisible, Decidable, Monoid, Semigroup)
-
--- |
--- Encode no parameters.
--- 
-{-# INLINABLE unit #-}
-unit :: Params ()
-unit =
-  Params mempty
-
--- |
--- Lift an individual value encoder to a parameters encoder.
--- 
-{-# INLINABLE value #-}
-value :: Value a -> Params a
-value (Value x) =
-  Params (Params.value x)
-
--- |
--- Lift an individual nullable value encoder to a parameters encoder.
--- 
-{-# INLINABLE nullableValue #-}
-nullableValue :: Value a -> Params (Maybe a)
-nullableValue (Value x) =
-  Params (Params.nullableValue x)
-
-
--- ** Instances
--------------------------
-
--- |
--- Maps to 'unit'.
-instance Default (Params ()) where
-  {-# INLINE def #-}
-  def =
-    unit
-
-instance Default (Value a) => Default (Params (Identity a)) where
-  {-# INLINE def #-}
-  def =
-    contramap runIdentity (value def)
-
-instance (Default (Value a1), Default (Value a2)) => Default (Params (a1, a2)) where
-  {-# INLINE def #-}
-  def =
-    contrazip2 (value def) (value def)
-
-instance (Default (Value a1), Default (Value a2), Default (Value a3)) => Default (Params (a1, a2, a3)) where
-  {-# INLINE def #-}
-  def =
-    contrazip3 (value def) (value def) (value def)
-
-instance (Default (Value a1), Default (Value a2), Default (Value a3), Default (Value a4)) => Default (Params (a1, a2, a3, a4)) where
-  {-# INLINE def #-}
-  def =
-    contrazip4 (value def) (value def) (value def) (value def)
-
-instance (Default (Value a1), Default (Value a2), Default (Value a3), Default (Value a4), Default (Value a5)) => Default (Params (a1, a2, a3, a4, a5)) where
-  {-# INLINE def #-}
-  def =
-    contrazip5 (value def) (value def) (value def) (value def) (value def)
-
-
--- * Value Encoder
--------------------------
-
--- |
--- An individual value encoder.
--- Will be mapped to a single placeholder in the query.
--- 
-newtype Value a =
-  Value (Value.Value a)
-  deriving (Contravariant)
-
--- |
--- Encoder of @BOOL@ values.
-{-# INLINABLE bool #-}
-bool :: Value Bool
-bool =
-  Value (Value.unsafePTI PTI.bool (const A.bool))
-
--- |
--- Encoder of @INT2@ values.
-{-# INLINABLE int2 #-}
-int2 :: Value Int16
-int2 =
-  Value (Value.unsafePTI PTI.int2 (const A.int2_int16))
-
--- |
--- Encoder of @INT4@ values.
-{-# INLINABLE int4 #-}
-int4 :: Value Int32
-int4 =
-  Value (Value.unsafePTI PTI.int4 (const A.int4_int32))
-
--- |
--- Encoder of @INT8@ values.
-{-# INLINABLE int8 #-}
-int8 :: Value Int64
-int8 =
-  Value (Value.unsafePTI PTI.int8 (const A.int8_int64))
-
--- |
--- Encoder of @FLOAT4@ values.
-{-# INLINABLE float4 #-}
-float4 :: Value Float
-float4 =
-  Value (Value.unsafePTI PTI.float4 (const A.float4))
-
--- |
--- Encoder of @FLOAT8@ values.
-{-# INLINABLE float8 #-}
-float8 :: Value Double
-float8 =
-  Value (Value.unsafePTI PTI.float8 (const A.float8))
-
--- |
--- Encoder of @NUMERIC@ values.
-{-# INLINABLE numeric #-}
-numeric :: Value B.Scientific
-numeric =
-  Value (Value.unsafePTI PTI.numeric (const A.numeric))
-
--- |
--- Encoder of @CHAR@ values.
--- Note that it supports UTF-8 values and
--- identifies itself under the @TEXT@ OID because of that.
-{-# INLINABLE char #-}
-char :: Value Char
-char =
-  Value (Value.unsafePTI PTI.text (const A.char_utf8))
-
--- |
--- Encoder of @TEXT@ values.
-{-# INLINABLE text #-}
-text :: Value Text
-text =
-  Value (Value.unsafePTI PTI.text (const A.text_strict))
-
--- |
--- Encoder of @BYTEA@ values.
-{-# INLINABLE bytea #-}
-bytea :: Value ByteString
-bytea =
-  Value (Value.unsafePTI PTI.bytea (const A.bytea_strict))
-
--- |
--- Encoder of @DATE@ values.
-{-# INLINABLE date #-}
-date :: Value B.Day
-date =
-  Value (Value.unsafePTI PTI.date (const A.date))
-
--- |
--- Encoder of @TIMESTAMP@ values.
-{-# INLINABLE timestamp #-}
-timestamp :: Value B.LocalTime
-timestamp =
-  Value (Value.unsafePTI PTI.timestamp (Prelude.bool A.timestamp_float A.timestamp_int))
-
--- |
--- Encoder of @TIMESTAMPTZ@ values.
-{-# INLINABLE timestamptz #-}
-timestamptz :: Value B.UTCTime
-timestamptz =
-  Value (Value.unsafePTI PTI.timestamptz (Prelude.bool A.timestamptz_float A.timestamptz_int))
-
--- |
--- Encoder of @TIME@ values.
-{-# INLINABLE time #-}
-time :: Value B.TimeOfDay
-time =
-  Value (Value.unsafePTI PTI.time (Prelude.bool A.time_float A.time_int))
-
--- |
--- Encoder of @TIMETZ@ values.
-{-# INLINABLE timetz #-}
-timetz :: Value (B.TimeOfDay, B.TimeZone)
-timetz =
-  Value (Value.unsafePTI PTI.timetz (Prelude.bool A.timetz_float A.timetz_int))
-
--- |
--- Encoder of @INTERVAL@ values.
-{-# INLINABLE interval #-}
-interval :: Value B.DiffTime
-interval =
-  Value (Value.unsafePTI PTI.interval (Prelude.bool A.interval_float A.interval_int))
-
--- |
--- Encoder of @UUID@ values.
-{-# INLINABLE uuid #-}
-uuid :: Value B.UUID
-uuid =
-  Value (Value.unsafePTI PTI.uuid (const A.uuid))
-
--- |
--- Encoder of @INET@ values.
-{-# INLINABLE inet #-}
-inet :: Value (B.NetAddr B.IP)
-inet =
-  Value (Value.unsafePTI PTI.inet (const A.inet))
-
--- |
--- Encoder of @JSON@ values from JSON AST.
-{-# INLINABLE json #-}
-json :: Value B.Value
-json =
-  Value (Value.unsafePTI PTI.json (const A.json_ast))
-
--- |
--- Encoder of @JSON@ values from raw JSON.
-{-# INLINABLE jsonBytes #-}
-jsonBytes :: Value ByteString
-jsonBytes =
-  Value (Value.unsafePTI PTI.json (const A.json_bytes))
-
--- |
--- Encoder of @JSONB@ values from JSON AST.
-{-# INLINABLE jsonb #-}
-jsonb :: Value B.Value
-jsonb =
-  Value (Value.unsafePTI PTI.jsonb (const A.jsonb_ast))
-
--- |
--- Encoder of @JSONB@ values from raw JSON.
-{-# INLINABLE jsonbBytes #-}
-jsonbBytes :: Value ByteString
-jsonbBytes =
-  Value (Value.unsafePTI PTI.jsonb (const A.jsonb_bytes))
-
--- |
--- Unlifts the 'Array' encoder to the plain 'Value' encoder.
-{-# INLINABLE array #-}
-array :: Array a -> Value a
-array (Array imp) =
-  Array.run imp & \(arrayOID, encoder') ->
-    Value (Value.Value arrayOID arrayOID encoder')
-
--- |
--- Given a function,
--- which maps the value into the textual enum label from the DB side,
--- produces a encoder of that value.
-{-# INLINABLE enum #-}
-enum :: (a -> Text) -> Value a
-enum mapping =
-  Value (Value.unsafePTI PTI.text (const (A.text_strict . mapping)))
-
--- |
--- Identifies the value with the PostgreSQL's \"unknown\" type,
--- thus leaving it up to Postgres to infer the actual type of the value.
--- 
--- The value transimitted is any value encoded in the Postgres' Text data format.
--- For reference, see the
--- <https://www.postgresql.org/docs/10/static/protocol-overview.html#protocol-format-codes Formats and Format Codes>
--- section of the Postgres' documentation.
-{-# INLINABLE unknown #-}
-unknown :: Value ByteString
-unknown =
-  Value (Value.unsafePTI PTI.unknown (const A.bytea_strict))
-
-
--- ** Instances
--------------------------
-
--- | Maps to 'bool'.
-instance Default (Value Bool) where
-  {-# INLINE def #-}
-  def =
-    bool
-
--- | Maps to 'int2'.
-instance Default (Value Int16) where
-  {-# INLINE def #-}
-  def =
-    int2
-
--- | Maps to 'int4'.
-instance Default (Value Int32) where
-  {-# INLINE def #-}
-  def =
-    int4
-
--- | Maps to 'int8'.
-instance Default (Value Int64) where
-  {-# INLINE def #-}
-  def =
-    int8
-
--- | Maps to 'float4'.
-instance Default (Value Float) where
-  {-# INLINE def #-}
-  def =
-    float4
-
--- | Maps to 'float8'.
-instance Default (Value Double) where
-  {-# INLINE def #-}
-  def =
-    float8
-
--- | Maps to 'numeric'.
-instance Default (Value B.Scientific) where
-  {-# INLINE def #-}
-  def =
-    numeric
-
--- | Maps to 'char'.
-instance Default (Value Char) where
-  {-# INLINE def #-}
-  def =
-    char
-
--- | Maps to 'text'.
-instance Default (Value Text) where
-  {-# INLINE def #-}
-  def =
-    text
-
--- | Maps to 'bytea'.
-instance Default (Value ByteString) where
-  {-# INLINE def #-}
-  def =
-    bytea
-
--- | Maps to 'date'.
-instance Default (Value B.Day) where
-  {-# INLINE def #-}
-  def =
-    date
-
--- | Maps to 'timestamp'.
-instance Default (Value B.LocalTime) where
-  {-# INLINE def #-}
-  def =
-    timestamp
-
--- | Maps to 'timestamptz'.
-instance Default (Value B.UTCTime) where
-  {-# INLINE def #-}
-  def =
-    timestamptz
-
--- | Maps to 'time'.
-instance Default (Value B.TimeOfDay) where
-  {-# INLINE def #-}
-  def =
-    time
-
--- | Maps to 'timetz'.
-instance Default (Value (B.TimeOfDay, B.TimeZone)) where
-  {-# INLINE def #-}
-  def =
-    timetz
-
--- | Maps to 'interval'.
-instance Default (Value B.DiffTime) where
-  {-# INLINE def #-}
-  def =
-    interval
-
--- | Maps to 'uuid'.
-instance Default (Value B.UUID) where
-  {-# INLINE def #-}
-  def =
-    uuid
-
--- | Maps to 'json'.
-instance Default (Value B.Value) where
-  {-# INLINE def #-}
-  def =
-    json
-
-
--- * Array
--------------------------
-
--- |
--- A generic array encoder.
--- 
--- Here's an example of its usage:
--- 
--- >x :: Value [[Int64]]
--- >x =
--- >  array (arrayDimension foldl' (arrayDimension foldl' (arrayValue int8)))
--- 
--- Please note that the PostgreSQL __IN__ keyword does not "accept" an array, but rather a syntactical list of
--- values, thus this encoder is not suited for that. Use a **field** = ANY($1) query instead.
---
-newtype Array a =
-  Array (Array.Array a)
-
--- |
--- Lifts the 'Value' encoder into the 'Array' encoder of a non-nullable value.
-{-# INLINABLE arrayValue #-}
-arrayValue :: Value a -> Array a
-arrayValue (Value (Value.Value elementOID arrayOID encoder')) =
-  Array (Array.value elementOID arrayOID encoder')
-
--- |
--- Lifts the 'Value' encoder into the 'Array' encoder of a nullable value.
-{-# INLINABLE arrayNullableValue #-}
-arrayNullableValue :: Value a -> Array (Maybe a)
-arrayNullableValue (Value (Value.Value elementOID arrayOID encoder')) =
-  Array (Array.nullableValue elementOID arrayOID encoder')
-
--- |
--- An encoder of an array dimension,
--- which thus provides support for multidimensional arrays.
--- 
--- Accepts:
--- 
--- * An implementation of the left-fold operation,
--- such as @Data.Foldable.'foldl''@,
--- which determines the input value.
--- 
--- * A component encoder, which can be either another 'arrayDimension',
--- 'arrayValue' or 'arrayNullableValue'.
--- 
-{-# INLINABLE arrayDimension #-}
-arrayDimension :: (forall a. (a -> b -> a) -> a -> c -> a) -> Array b -> Array c
-arrayDimension foldl (Array imp) =
-  Array (Array.dimension foldl imp)
-
--- $insertMany
--- It is not currently possible to pass in an array of encodable values
--- to use in an 'insert many' query using Hasql. Instead, PostgreSQL's
---  (9.4 or later) `unnest` function can be used to in an analogous way
--- to haskell's `zip` function by passing in multiple arrays of values
--- to be zipped into the rows we want to insert:
---
--- @
---   insertMultipleLocations :: Query (Vector (UUID, Double, Double)) ()
---   insertMultipleLocations =
---     statement sql encoder decoder True
---     where
---       sql =
---         "insert into location (id, x, y) select * from unnest ($1, $2, $3)"
---       encoder =
---         contramap Vector.unzip3 $
---         contrazip3 (vector Encoders.uuid) (vector Encoders.float8) (vector Encoders.float8)
---         where
---           vector value =
---             Encoders.value (Encoders.array (Encoders.arrayDimension foldl' (Encoders.arrayValue value)))
---       decoder =
---         Decoders.unit
--- @
diff --git a/library/Hasql/Private/Commands.hs b/library/Hasql/Private/Commands.hs
deleted file mode 100644
--- a/library/Hasql/Private/Commands.hs
+++ /dev/null
@@ -1,33 +0,0 @@
-module Hasql.Private.Commands
-(
-  Commands,
-  asBytes,
-  setEncodersToUTF8,
-  setMinClientMessagesToWarning,
-)
-where
-
-import Hasql.Private.Prelude
-import qualified Data.ByteString as B
-import qualified Data.ByteString.Lazy.Builder as BB
-import qualified Data.ByteString.Lazy.Builder.ASCII as BB
-import qualified Data.ByteString.Lazy as BL
-
-
-newtype Commands =
-  Commands (DList BB.Builder)
-  deriving (Monoid)
-
-instance Semigroup Commands
-
-asBytes :: Commands -> ByteString
-asBytes (Commands list) =
-  BL.toStrict $ BB.toLazyByteString $ foldMap (<> BB.char7 ';') $ list
-
-setEncodersToUTF8 :: Commands
-setEncodersToUTF8 =
-  Commands (pure "SET client_encoding = 'UTF8'")
-
-setMinClientMessagesToWarning :: Commands
-setMinClientMessagesToWarning =
-  Commands (pure "SET client_min_messages TO WARNING")
diff --git a/library/Hasql/Private/Connection.hs b/library/Hasql/Private/Connection.hs
deleted file mode 100644
--- a/library/Hasql/Private/Connection.hs
+++ /dev/null
@@ -1,52 +0,0 @@
--- |
--- This module provides a low-level effectful API dealing with the connections to the database.
-module Hasql.Private.Connection
-where
-
-import Hasql.Private.Prelude
-import qualified Database.PostgreSQL.LibPQ as LibPQ
-import qualified Hasql.Private.PreparedStatementRegistry as PreparedStatementRegistry
-import qualified Hasql.Private.IO as IO
-import qualified Hasql.Private.Settings as Settings
-
-
--- |
--- A single connection to the database.
-data Connection =
-  Connection !(MVar LibPQ.Connection) !Bool !PreparedStatementRegistry.PreparedStatementRegistry
-
--- |
--- Possible details of the connection acquistion error.
-type ConnectionError =
-  Maybe ByteString
-
--- |
--- Acquire a connection using the provided settings encoded according to the PostgreSQL format.
-acquire :: Settings.Settings -> IO (Either ConnectionError Connection)
-acquire settings =
-  {-# SCC "acquire" #-}
-  runExceptT $ do
-    pqConnection <- lift (IO.acquireConnection settings)
-    lift (IO.checkConnectionStatus pqConnection) >>= traverse throwError
-    lift (IO.initConnection pqConnection)
-    integerDatetimes <- lift (IO.getIntegerDatetimes pqConnection)
-    registry <- lift (IO.acquirePreparedStatementRegistry)
-    pqConnectionRef <- lift (newMVar pqConnection)
-    pure (Connection pqConnectionRef integerDatetimes registry)
-
--- |
--- Release the connection.
-release :: Connection -> IO ()
-release (Connection pqConnectionRef _ _) =
-  mask_ $ do
-    nullConnection <- LibPQ.newNullConnection
-    pqConnection <- swapMVar pqConnectionRef nullConnection
-    IO.releaseConnection pqConnection
-
--- |
--- Execute an operation on the raw @libpq@ 'LibPQ.Connection'.
---
--- The access to the connection is exclusive.
-withLibPQConnection :: Connection -> (LibPQ.Connection -> IO a) -> IO a
-withLibPQConnection (Connection pqConnectionRef _ _) =
-  withMVar pqConnectionRef
diff --git a/library/Hasql/Private/Decoders/Array.hs b/library/Hasql/Private/Decoders/Array.hs
deleted file mode 100644
--- a/library/Hasql/Private/Decoders/Array.hs
+++ /dev/null
@@ -1,30 +0,0 @@
-module Hasql.Private.Decoders.Array where
-
-import Hasql.Private.Prelude
-import qualified PostgreSQL.Binary.Decoding as A
-
-
-newtype Array a =
-  Array (ReaderT Bool A.Array a)
-  deriving (Functor)
-
-{-# INLINE run #-}
-run :: Array a -> Bool -> A.Value a
-run (Array imp) env =
-  A.array (runReaderT imp env)
-
-{-# INLINE dimension #-}
-dimension :: (forall m. Monad m => Int -> m a -> m b) -> Array a -> Array b
-dimension replicateM (Array imp) =
-  Array $ ReaderT $ \env -> A.dimensionArray replicateM (runReaderT imp env)
-
-{-# INLINE value #-}
-value :: (Bool -> A.Value a) -> Array (Maybe a)
-value decoder' =
-  Array $ ReaderT $ A.nullableValueArray . decoder'
-
-{-# INLINE nonNullValue #-}
-nonNullValue :: (Bool -> A.Value a) -> Array a
-nonNullValue decoder' =
-  Array $ ReaderT $ A.valueArray . decoder'
-
diff --git a/library/Hasql/Private/Decoders/Composite.hs b/library/Hasql/Private/Decoders/Composite.hs
deleted file mode 100644
--- a/library/Hasql/Private/Decoders/Composite.hs
+++ /dev/null
@@ -1,25 +0,0 @@
-module Hasql.Private.Decoders.Composite where
-
-import Hasql.Private.Prelude
-import qualified PostgreSQL.Binary.Decoding as A
-
-
-newtype Composite a =
-  Composite (ReaderT Bool A.Composite a)
-  deriving (Functor, Applicative, Monad)
-
-{-# INLINE run #-}
-run :: Composite a -> Bool -> A.Value a
-run (Composite imp) env =
-  A.composite (runReaderT imp env)
-
-{-# INLINE value #-}
-value :: (Bool -> A.Value a) -> Composite (Maybe a)
-value decoder' =
-  Composite $ ReaderT $ A.nullableValueComposite . decoder'
-
-{-# INLINE nonNullValue #-}
-nonNullValue :: (Bool -> A.Value a) -> Composite a
-nonNullValue decoder' =
-  Composite $ ReaderT $ A.valueComposite . decoder'
-
diff --git a/library/Hasql/Private/Decoders/Result.hs b/library/Hasql/Private/Decoders/Result.hs
deleted file mode 100644
--- a/library/Hasql/Private/Decoders/Result.hs
+++ /dev/null
@@ -1,232 +0,0 @@
-module Hasql.Private.Decoders.Result where
-
-import Hasql.Private.Prelude hiding (maybe, many)
-import qualified Database.PostgreSQL.LibPQ as LibPQ
-import qualified Hasql.Private.Decoders.Row as Row
-import qualified Data.Attoparsec.ByteString.Char8 as Attoparsec
-import qualified Data.ByteString as ByteString
-import qualified Hasql.Private.Prelude as Prelude
-import qualified Data.Vector as Vector
-import qualified Data.Vector.Mutable as MutableVector
-
-
-newtype Result a =
-  Result (ReaderT (Bool, LibPQ.Result) (ExceptT Error IO) a)
-  deriving (Functor, Applicative, Monad)
-
-data Error =
-  -- | 
-  -- An error reported by the DB. Code, message, details, hint.
-  -- 
-  -- * The SQLSTATE code for the error. The SQLSTATE code identifies the type of error that has occurred; 
-  -- it can be used by front-end applications to perform specific operations (such as error handling) 
-  -- in response to a particular database error. 
-  -- For a list of the possible SQLSTATE codes, see Appendix A.
-  -- This field is not localizable, and is always present.
-  -- 
-  -- * The primary human-readable error message (typically one line). Always present.
-  -- 
-  -- * Detail: an optional secondary error message carrying more detail about the problem. 
-  -- Might run to multiple lines.
-  -- 
-  -- * Hint: an optional suggestion what to do about the problem. 
-  -- This is intended to differ from detail in that it offers advice (potentially inappropriate) 
-  -- rather than hard facts. Might run to multiple lines.
-  ServerError !ByteString !ByteString !(Maybe ByteString) !(Maybe ByteString) |
-  -- |
-  -- The database returned an unexpected result.
-  -- Indicates an improper statement or a schema mismatch.
-  UnexpectedResult !Text |
-  -- |
-  -- An error of the row reader, preceded by the index of the row.
-  RowError !Int !Row.Error |
-  -- |
-  -- An unexpected amount of rows.
-  UnexpectedAmountOfRows !Int
-  deriving (Show)
-
-{-# INLINE run #-}
-run :: Result a -> (Bool, LibPQ.Result) -> IO (Either Error a)
-run (Result reader) env =
-  runExceptT (runReaderT reader env)
-
-{-# INLINE unit #-}
-unit :: Result ()
-unit =
-  checkExecStatus $ \case
-    LibPQ.CommandOk -> True
-    LibPQ.TuplesOk -> True
-    _ -> False
-
-{-# INLINE rowsAffected #-}
-rowsAffected :: Result Int64
-rowsAffected =
-  do
-    checkExecStatus $ \case
-      LibPQ.CommandOk -> True
-      _ -> False
-    Result $ ReaderT $ \(_, result) -> ExceptT $
-      LibPQ.cmdTuples result & fmap cmdTuplesReader
-  where
-    cmdTuplesReader =
-      notNothing >=> notEmpty >=> decimal
-      where
-        notNothing =
-          Prelude.maybe (Left (UnexpectedResult "No bytes")) Right
-        notEmpty bytes =
-          if ByteString.null bytes
-            then Left (UnexpectedResult "Empty bytes")
-            else Right bytes
-        decimal bytes =
-          mapLeft (\m -> UnexpectedResult ("Decimal parsing failure: " <> fromString m)) $
-          Attoparsec.parseOnly (Attoparsec.decimal <* Attoparsec.endOfInput) bytes
-
-{-# INLINE checkExecStatus #-}
-checkExecStatus :: (LibPQ.ExecStatus -> Bool) -> Result ()
-checkExecStatus predicate =
-  {-# SCC "checkExecStatus" #-} 
-  do
-    status <- Result $ ReaderT $ \(_, result) -> lift $ LibPQ.resultStatus result
-    unless (predicate status) $ do
-      case status of
-        LibPQ.BadResponse   -> serverError
-        LibPQ.NonfatalError -> serverError
-        LibPQ.FatalError    -> serverError
-        _ -> Result $ lift $ ExceptT $ pure $ Left $ UnexpectedResult $ "Unexpected result status: " <> (fromString $ show status)
-
-{-# INLINE serverError #-}
-serverError :: Result ()
-serverError =
-  Result $ ReaderT $ \(_, result) -> ExceptT $ do
-    code <- 
-      fmap (fromMaybe ($bug "No code")) $
-      LibPQ.resultErrorField result LibPQ.DiagSqlstate
-    message <- 
-      fmap (fromMaybe ($bug "No message")) $
-      LibPQ.resultErrorField result LibPQ.DiagMessagePrimary
-    detail <- 
-      LibPQ.resultErrorField result LibPQ.DiagMessageDetail
-    hint <- 
-      LibPQ.resultErrorField result LibPQ.DiagMessageHint
-    pure $ Left $ ServerError code message detail hint
-
-{-# INLINE maybe #-}
-maybe :: Row.Row a -> Result (Maybe a)
-maybe rowDec =
-  do
-    checkExecStatus $ \case
-      LibPQ.TuplesOk -> True
-      _ -> False
-    Result $ ReaderT $ \(integerDatetimes, result) -> ExceptT $ do
-      maxRows <- LibPQ.ntuples result
-      case maxRows of
-        0 -> return (Right Nothing)
-        1 -> do
-          maxCols <- LibPQ.nfields result
-          fmap (fmap Just . mapLeft (RowError 0)) $ Row.run rowDec (result, 0, maxCols, integerDatetimes)
-        _ -> return (Left (UnexpectedAmountOfRows (rowToInt maxRows)))
-  where
-    rowToInt (LibPQ.Row n) =
-      fromIntegral n
-    intToRow =
-      LibPQ.Row . fromIntegral
-
-{-# INLINE single #-}
-single :: Row.Row a -> Result a
-single rowDec =
-  do
-    checkExecStatus $ \case
-      LibPQ.TuplesOk -> True
-      _ -> False
-    Result $ ReaderT $ \(integerDatetimes, result) -> ExceptT $ do
-      maxRows <- LibPQ.ntuples result
-      case maxRows of
-        1 -> do
-          maxCols <- LibPQ.nfields result
-          fmap (mapLeft (RowError 0)) $ Row.run rowDec (result, 0, maxCols, integerDatetimes)
-        _ -> return (Left (UnexpectedAmountOfRows (rowToInt maxRows)))
-  where
-    rowToInt (LibPQ.Row n) =
-      fromIntegral n
-    intToRow =
-      LibPQ.Row . fromIntegral
-
-{-# INLINE vector #-}
-vector :: Row.Row a -> Result (Vector a)
-vector rowDec =
-  do
-    checkExecStatus $ \case
-      LibPQ.TuplesOk -> True
-      _ -> False
-    Result $ ReaderT $ \(integerDatetimes, result) -> ExceptT $ do
-      maxRows <- LibPQ.ntuples result
-      maxCols <- LibPQ.nfields result
-      mvector <- MutableVector.unsafeNew (rowToInt maxRows)
-      failureRef <- newIORef Nothing
-      forMFromZero_ (rowToInt maxRows) $ \rowIndex -> do
-        rowResult <- Row.run rowDec (result, intToRow rowIndex, maxCols, integerDatetimes)
-        case rowResult of
-          Left !x -> writeIORef failureRef (Just (RowError rowIndex x))
-          Right !x -> MutableVector.unsafeWrite mvector rowIndex x
-      readIORef failureRef >>= \case
-        Nothing -> Right <$> Vector.unsafeFreeze mvector
-        Just x -> pure (Left x)
-  where
-    rowToInt (LibPQ.Row n) =
-      fromIntegral n
-    intToRow =
-      LibPQ.Row . fromIntegral
-
-{-# INLINE foldl #-}
-foldl :: (a -> b -> a) -> a -> Row.Row b -> Result a
-foldl step init rowDec =
-  {-# SCC "foldl" #-} 
-  do
-    checkExecStatus $ \case
-      LibPQ.TuplesOk -> True
-      _ -> False
-    Result $ ReaderT $ \(integerDatetimes, result) -> ExceptT $ {-# SCC "traversal" #-} do
-      maxRows <- LibPQ.ntuples result
-      maxCols <- LibPQ.nfields result
-      accRef <- newIORef init
-      failureRef <- newIORef Nothing
-      forMFromZero_ (rowToInt maxRows) $ \rowIndex -> do
-        rowResult <- Row.run rowDec (result, intToRow rowIndex, maxCols, integerDatetimes)
-        case rowResult of
-          Left !x -> writeIORef failureRef (Just (RowError rowIndex x))
-          Right !x -> modifyIORef accRef (\acc -> step acc x)
-      readIORef failureRef >>= \case
-        Nothing -> Right <$> readIORef accRef
-        Just x -> pure (Left x)
-  where
-    rowToInt (LibPQ.Row n) =
-      fromIntegral n
-    intToRow =
-      LibPQ.Row . fromIntegral
-
-{-# INLINE foldr #-}
-foldr :: (b -> a -> a) -> a -> Row.Row b -> Result a
-foldr step init rowDec =
-  {-# SCC "foldr" #-} 
-  do
-    checkExecStatus $ \case
-      LibPQ.TuplesOk -> True
-      _ -> False
-    Result $ ReaderT $ \(integerDatetimes, result) -> ExceptT $ do
-      maxRows <- LibPQ.ntuples result
-      maxCols <- LibPQ.nfields result
-      accRef <- newIORef init
-      failureRef <- newIORef Nothing
-      forMToZero_ (rowToInt maxRows) $ \rowIndex -> do
-        rowResult <- Row.run rowDec (result, intToRow rowIndex, maxCols, integerDatetimes)
-        case rowResult of
-          Left !x -> writeIORef failureRef (Just (RowError rowIndex x))
-          Right !x -> modifyIORef accRef (\acc -> step x acc)
-      readIORef failureRef >>= \case
-        Nothing -> Right <$> readIORef accRef
-        Just x -> pure (Left x)
-  where
-    rowToInt (LibPQ.Row n) =
-      fromIntegral n
-    intToRow =
-      LibPQ.Row . fromIntegral
diff --git a/library/Hasql/Private/Decoders/Results.hs b/library/Hasql/Private/Decoders/Results.hs
deleted file mode 100644
--- a/library/Hasql/Private/Decoders/Results.hs
+++ /dev/null
@@ -1,91 +0,0 @@
--- |
--- An API for retrieval of multiple results.
--- Can be used to handle:
--- 
--- * A single result,
--- 
--- * Individual results of a multi-statement query
--- with the help of "Applicative" and "Monad",
--- 
--- * Row-by-row fetching.
--- 
-module Hasql.Private.Decoders.Results where
-
-import Hasql.Private.Prelude hiding (maybe, many)
-import qualified Database.PostgreSQL.LibPQ as LibPQ
-import qualified Hasql.Private.Prelude as Prelude
-import qualified Hasql.Private.Decoders.Result as Result
-import qualified Hasql.Private.Decoders.Row as Row
-
-
-newtype Results a =
-  Results (ReaderT (Bool, LibPQ.Connection) (ExceptT Error IO) a)
-  deriving (Functor, Applicative, Monad)
-
-data Error =
-  -- |
-  -- An error on the client-side,
-  -- with a message generated by the \"libpq\" library.
-  -- Usually indicates problems with the connection.
-  ClientError !(Maybe ByteString) |
-  ResultError !Result.Error
-  deriving (Show)
-
-{-# INLINE run #-}
-run :: Results a -> (Bool, LibPQ.Connection) -> IO (Either Error a)
-run (Results stack) env =
-  runExceptT (runReaderT stack env)
-
-{-# INLINE clientError #-}
-clientError :: Results a
-clientError =
-  Results $ ReaderT $ \(_, connection) -> ExceptT $
-  fmap (Left . ClientError) (LibPQ.errorMessage connection)
-
--- |
--- Parse a single result.
-{-# INLINE single #-}
-single :: Result.Result a -> Results a
-single resultDec =
-  Results $ ReaderT $ \(integerDatetimes, connection) -> ExceptT $ do
-    resultMaybe <- LibPQ.getResult connection
-    case resultMaybe of
-      Just result ->
-        mapLeft ResultError <$> Result.run resultDec (integerDatetimes, result) 
-      Nothing ->
-        fmap (Left . ClientError) (LibPQ.errorMessage connection)
-
--- |
--- Fetch a single result.
-{-# INLINE getResult #-}
-getResult :: Results LibPQ.Result
-getResult =
-  Results $ ReaderT $ \(_, connection) -> ExceptT $ do
-    resultMaybe <- LibPQ.getResult connection
-    case resultMaybe of
-      Just result -> pure (Right result)
-      Nothing -> fmap (Left . ClientError) (LibPQ.errorMessage connection)
-
--- |
--- Fetch a single result.
-{-# INLINE getResultMaybe #-}
-getResultMaybe :: Results (Maybe LibPQ.Result)
-getResultMaybe =
-  Results $ ReaderT $ \(_, connection) -> lift $ LibPQ.getResult connection
-
-{-# INLINE dropRemainders #-}
-dropRemainders :: Results ()
-dropRemainders =
-  {-# SCC "dropRemainders" #-} 
-  Results $ ReaderT $ \(integerDatetimes, connection) -> loop integerDatetimes connection
-  where
-    loop integerDatetimes connection =
-      getResultMaybe >>= Prelude.maybe (pure ()) onResult
-      where
-        getResultMaybe =
-          lift $ LibPQ.getResult connection
-        onResult result =
-          loop integerDatetimes connection <* checkErrors
-          where
-            checkErrors =
-              ExceptT $ fmap (mapLeft ResultError) $ Result.run Result.unit (integerDatetimes, result)
diff --git a/library/Hasql/Private/Decoders/Row.hs b/library/Hasql/Private/Decoders/Row.hs
deleted file mode 100644
--- a/library/Hasql/Private/Decoders/Row.hs
+++ /dev/null
@@ -1,65 +0,0 @@
-module Hasql.Private.Decoders.Row where
-
-import Hasql.Private.Prelude
-import qualified Database.PostgreSQL.LibPQ as LibPQ
-import qualified PostgreSQL.Binary.Decoding as A
-import qualified Hasql.Private.Decoders.Value as Value
-
-
-newtype Row a =
-  Row (ReaderT Env (ExceptT Error IO) a)
-  deriving (Functor, Applicative, Monad)
-
-data Env =
-  Env !LibPQ.Result !LibPQ.Row !LibPQ.Column !Bool !(IORef LibPQ.Column)
-
-data Error =
-  EndOfInput |
-  UnexpectedNull |
-  ValueError !Text
-  deriving (Show)
-
-
--- * Functions
--------------------------
-
-{-# INLINE run #-}
-run :: Row a -> (LibPQ.Result, LibPQ.Row, LibPQ.Column, Bool) -> IO (Either Error a)
-run (Row impl) (result, row, columnsAmount, integerDatetimes) =
-  do
-    columnRef <- newIORef 0
-    runExceptT (runReaderT impl (Env result row columnsAmount integerDatetimes columnRef))
-
-{-# INLINE error #-}
-error :: Error -> Row a
-error x =
-  Row (ReaderT (const (ExceptT (pure (Left x)))))
-
--- |
--- Next value, decoded using the provided value decoder.
-{-# INLINE value #-}
-value :: Value.Value a -> Row (Maybe a)
-value valueDec =
-  {-# SCC "value" #-} 
-  Row $ ReaderT $ \(Env result row columnsAmount integerDatetimes columnRef) -> ExceptT $ do
-    col <- readIORef columnRef
-    writeIORef columnRef (succ col)
-    if col < columnsAmount
-      then do
-        valueMaybe <- {-# SCC "getvalue'" #-} LibPQ.getvalue' result row col
-        pure $ 
-          case valueMaybe of
-            Nothing ->
-              Right Nothing
-            Just value ->
-              fmap Just $ mapLeft ValueError $
-              {-# SCC "decode" #-} A.valueParser (Value.run valueDec integerDatetimes) value
-      else pure (Left EndOfInput)
-
--- |
--- Next value, decoded using the provided value decoder.
-{-# INLINE nonNullValue #-}
-nonNullValue :: Value.Value a -> Row a
-nonNullValue valueDec =
-  {-# SCC "nonNullValue" #-} 
-  value valueDec >>= maybe (error UnexpectedNull) pure
diff --git a/library/Hasql/Private/Decoders/Value.hs b/library/Hasql/Private/Decoders/Value.hs
deleted file mode 100644
--- a/library/Hasql/Private/Decoders/Value.hs
+++ /dev/null
@@ -1,27 +0,0 @@
-module Hasql.Private.Decoders.Value where
-
-import Hasql.Private.Prelude
-import qualified PostgreSQL.Binary.Decoding as A
-
-
-newtype Value a =
-  Value (ReaderT Bool A.Value a)
-  deriving (Functor)
-
-
-{-# INLINE run #-}
-run :: Value a -> Bool -> A.Value a
-run (Value imp) integerDatetimes =
-  runReaderT imp integerDatetimes
-
-{-# INLINE decoder #-}
-decoder :: (Bool -> A.Value a) -> Value a
-decoder =
-  {-# SCC "decoder" #-} 
-  Value . ReaderT
-
-{-# INLINE decoderFn #-}
-decoderFn :: (Bool -> ByteString -> Either Text a) -> Value a
-decoderFn fn =
-  Value $ ReaderT $ \integerDatetimes -> A.fn $ fn integerDatetimes
-
diff --git a/library/Hasql/Private/Encoders/Array.hs b/library/Hasql/Private/Encoders/Array.hs
deleted file mode 100644
--- a/library/Hasql/Private/Encoders/Array.hs
+++ /dev/null
@@ -1,30 +0,0 @@
-module Hasql.Private.Encoders.Array where
-
-import Hasql.Private.Prelude
-import qualified PostgreSQL.Binary.Encoding as A
-import qualified Hasql.Private.PTI as B
-
-
-data Array a =
-  Array B.OID B.OID (Bool -> a -> A.Array)
-
-{-# INLINE run #-}
-run :: Array a -> (B.OID, Bool -> a -> A.Encoding)
-run (Array valueOID arrayOID encoder) =
-  (arrayOID, \env input -> A.array (B.oidWord32 valueOID) (encoder env input))
-
-{-# INLINE value #-}
-value :: B.OID -> B.OID -> (Bool -> a -> A.Encoding) -> Array a
-value valueOID arrayOID encoder =
-  Array valueOID arrayOID (\params -> A.encodingArray . encoder params)
-
-{-# INLINE nullableValue #-}
-nullableValue :: B.OID -> B.OID -> (Bool -> a -> A.Encoding) -> Array (Maybe a)
-nullableValue valueOID arrayOID encoder =
-  Array valueOID arrayOID (\params -> maybe A.nullArray (A.encodingArray . encoder params))
-
-{-# INLINE dimension #-}
-dimension :: (forall a. (a -> b -> a) -> a -> c -> a) -> Array b -> Array c
-dimension fold (Array valueOID arrayOID encoder) =
-  Array valueOID arrayOID (\params -> A.dimensionArray fold (encoder params))
-
diff --git a/library/Hasql/Private/Encoders/Params.hs b/library/Hasql/Private/Encoders/Params.hs
deleted file mode 100644
--- a/library/Hasql/Private/Encoders/Params.hs
+++ /dev/null
@@ -1,56 +0,0 @@
-module Hasql.Private.Encoders.Params where
-
-import Hasql.Private.Prelude
-import qualified Database.PostgreSQL.LibPQ as A
-import qualified PostgreSQL.Binary.Encoding as B
-import qualified Hasql.Private.Encoders.Value as C
-import qualified Hasql.Private.PTI as D
-
-
--- |
--- Encoder of some representation of a parameters product.
-newtype Params a =
-  Params (Op (DList (A.Oid, Bool -> Maybe ByteString)) a)
-  deriving (Contravariant, Divisible, Decidable, Monoid)
-
-instance Semigroup (Params a)
-
-run :: Params a -> a -> DList (A.Oid, Bool -> Maybe ByteString)
-run (Params (Op op)) params =
-  {-# SCC "run" #-} 
-  op params
-
-run' :: Params a -> a -> Bool -> ([A.Oid], [Maybe (ByteString, A.Format)])
-run' (Params (Op op)) params integerDatetimes =
-  {-# SCC "run'" #-} 
-  foldr step ([], []) (op params)
-  where
-    step (oid, bytesGetter) ~(oidList, bytesAndFormatList) =
-      (,)
-        (oid : oidList)
-        (fmap (\bytes -> (bytes, format oid)) (bytesGetter integerDatetimes) : bytesAndFormatList)
-
-run'' :: Params a -> a -> Bool -> [Maybe (A.Oid, ByteString, A.Format)]
-run'' (Params (Op op)) params integerDatetimes =
-  {-# SCC "run''" #-} 
-  foldr step [] (op params)
-  where
-    step a b =
-      mapping a : b
-      where
-        mapping (oid, bytesGetter) =
-          (,,) <$> pure oid <*> bytesGetter integerDatetimes <*> pure (format oid)
-
-format :: A.Oid -> A.Format
-format oid = case oid of
-  A.Oid 705 -> A.Text -- is unknown
-  _         -> A.Binary
-
-value :: C.Value a -> Params a
-value =
-  contramap Just . nullableValue
-
-nullableValue :: C.Value a -> Params (Maybe a)
-nullableValue (C.Value valueOID arrayOID encoder) =
-  Params $ Op $ \input -> 
-    pure (D.oidPQ valueOID, \env -> fmap (B.encodingBytes . encoder env) input)
diff --git a/library/Hasql/Private/Encoders/Value.hs b/library/Hasql/Private/Encoders/Value.hs
deleted file mode 100644
--- a/library/Hasql/Private/Encoders/Value.hs
+++ /dev/null
@@ -1,26 +0,0 @@
-module Hasql.Private.Encoders.Value where
-
-import Hasql.Private.Prelude
-import qualified PostgreSQL.Binary.Encoding as B
-import qualified Hasql.Private.PTI as PTI
-
-
-data Value a =
-  Value PTI.OID PTI.OID (Bool -> a -> B.Encoding)
-
-instance Contravariant Value where
-  {-# INLINE contramap #-}
-  contramap f (Value valueOID arrayOID encoder) =
-    Value valueOID arrayOID (\integerDatetimes input -> encoder integerDatetimes (f input))
-
-{-# INLINE run #-}
-run :: Value a -> (PTI.OID, PTI.OID, Bool -> a -> B.Encoding)
-run (Value valueOID arrayOID encoder') =
-  (valueOID, arrayOID, encoder')
-
-{-# INLINE unsafePTI #-}
-unsafePTI :: PTI.PTI -> (Bool -> a -> B.Encoding) -> Value a
-unsafePTI pti encoder' =
-  Value (PTI.ptiOID pti) (fromMaybe ($bug "No array OID") (PTI.ptiArrayOID pti)) encoder'
-
-
diff --git a/library/Hasql/Private/IO.hs b/library/Hasql/Private/IO.hs
deleted file mode 100644
--- a/library/Hasql/Private/IO.hs
+++ /dev/null
@@ -1,159 +0,0 @@
--- |
--- An API of low-level IO operations.
-module Hasql.Private.IO
-where
-
-import Hasql.Private.Prelude
-import qualified Database.PostgreSQL.LibPQ as LibPQ
-import qualified Hasql.Private.Commands as Commands
-import qualified Hasql.Private.PreparedStatementRegistry as PreparedStatementRegistry
-import qualified Hasql.Private.Decoders.Result as ResultDecoders
-import qualified Hasql.Private.Decoders.Results as ResultsDecoders
-import qualified Hasql.Private.Encoders.Params as ParamsEncoders
-import qualified Data.DList as DList
-
-
-{-# INLINE acquireConnection #-}
-acquireConnection :: ByteString -> IO LibPQ.Connection
-acquireConnection =
-  LibPQ.connectdb
-
-{-# INLINE acquirePreparedStatementRegistry #-}
-acquirePreparedStatementRegistry :: IO PreparedStatementRegistry.PreparedStatementRegistry
-acquirePreparedStatementRegistry =
-  PreparedStatementRegistry.new
-
-{-# INLINE releaseConnection #-}
-releaseConnection :: LibPQ.Connection -> IO ()
-releaseConnection connection =
-  LibPQ.finish connection
-
-{-# INLINE checkConnectionStatus #-}
-checkConnectionStatus :: LibPQ.Connection -> IO (Maybe (Maybe ByteString))
-checkConnectionStatus c =
-  do
-    s <- LibPQ.status c
-    case s of
-      LibPQ.ConnectionOk -> return Nothing
-      _ -> fmap Just (LibPQ.errorMessage c)
-
-{-# INLINE checkServerVersion #-}
-checkServerVersion :: LibPQ.Connection -> IO (Maybe Int)
-checkServerVersion c =
-  fmap (mfilter (< 80200) . Just) (LibPQ.serverVersion c)
-
-{-# INLINE getIntegerDatetimes #-}
-getIntegerDatetimes :: LibPQ.Connection -> IO Bool
-getIntegerDatetimes c =
-  fmap decodeValue $ LibPQ.parameterStatus c "integer_datetimes"
-  where
-    decodeValue = 
-      \case
-        Just "on" -> True
-        _ -> False
-
-{-# INLINE initConnection #-}
-initConnection :: LibPQ.Connection -> IO ()
-initConnection c =
-  void $ LibPQ.exec c (Commands.asBytes (Commands.setEncodersToUTF8 <> Commands.setMinClientMessagesToWarning))
-
-{-# INLINE getResults #-}
-getResults :: LibPQ.Connection -> Bool -> ResultsDecoders.Results a -> IO (Either ResultsDecoders.Error a)
-getResults connection integerDatetimes decoder =
-  {-# SCC "getResults" #-} 
-  (<*) <$> get <*> dropRemainders
-  where
-    get =
-      ResultsDecoders.run decoder (integerDatetimes, connection)
-    dropRemainders =
-      ResultsDecoders.run ResultsDecoders.dropRemainders (integerDatetimes, connection)
-
-{-# INLINE getPreparedStatementKey #-}
-getPreparedStatementKey ::
-  LibPQ.Connection -> PreparedStatementRegistry.PreparedStatementRegistry ->
-  ByteString -> [LibPQ.Oid] ->
-  IO (Either ResultsDecoders.Error ByteString)
-getPreparedStatementKey connection registry template oidList =
-  {-# SCC "getPreparedStatementKey" #-} 
-  PreparedStatementRegistry.update localKey onNewRemoteKey onOldRemoteKey registry
-  where
-    localKey =
-      PreparedStatementRegistry.LocalKey template wordOIDList
-      where
-        wordOIDList =
-          map (\(LibPQ.Oid x) -> fromIntegral x) oidList
-    onNewRemoteKey key =
-      do
-        sent <- LibPQ.sendPrepare connection key template (mfilter (not . null) (Just oidList))
-        let resultsDecoder = 
-              if sent
-                then ResultsDecoders.single ResultDecoders.unit
-                else ResultsDecoders.clientError
-        fmap resultsMapping $ getResults connection undefined resultsDecoder
-      where
-        resultsMapping =
-          \case
-            Left x -> (False, Left x)
-            Right _ -> (True, Right key)
-    onOldRemoteKey key =
-      pure (pure key)
-
-{-# INLINE checkedSend #-}
-checkedSend :: LibPQ.Connection -> IO Bool -> IO (Either ResultsDecoders.Error ())
-checkedSend connection send =
-  send >>= \case
-    False -> fmap (Left . ResultsDecoders.ClientError) $ LibPQ.errorMessage connection
-    True -> pure (Right ())
-
-{-# INLINE sendPreparedParametricQuery #-}
-sendPreparedParametricQuery ::
-  LibPQ.Connection ->
-  PreparedStatementRegistry.PreparedStatementRegistry ->
-  ByteString ->
-  [LibPQ.Oid] ->
-  [Maybe (ByteString, LibPQ.Format)] ->
-  IO (Either ResultsDecoders.Error ())
-sendPreparedParametricQuery connection registry template oidList valueAndFormatList =
-  runExceptT $ do
-    key <- ExceptT $ getPreparedStatementKey connection registry template oidList
-    ExceptT $ checkedSend connection $ LibPQ.sendQueryPrepared connection key valueAndFormatList LibPQ.Binary
-
-{-# INLINE sendUnpreparedParametricQuery #-}
-sendUnpreparedParametricQuery ::
-  LibPQ.Connection ->
-  ByteString ->
-  [Maybe (LibPQ.Oid, ByteString, LibPQ.Format)] ->
-  IO (Either ResultsDecoders.Error ())
-sendUnpreparedParametricQuery connection template paramList =
-  checkedSend connection $ LibPQ.sendQueryParams connection template paramList LibPQ.Binary
-
-{-# INLINE sendParametricQuery #-}
-sendParametricQuery ::
-  LibPQ.Connection ->
-  Bool -> 
-  PreparedStatementRegistry.PreparedStatementRegistry ->
-  ByteString ->
-  ParamsEncoders.Params a ->
-  Bool ->
-  a ->
-  IO (Either ResultsDecoders.Error ())
-sendParametricQuery connection integerDatetimes registry template encoder prepared params =
-  {-# SCC "sendParametricQuery" #-} 
-  if prepared
-    then
-      let
-        (oidList, valueAndFormatList) =
-          ParamsEncoders.run' encoder params integerDatetimes
-        in
-          sendPreparedParametricQuery connection registry template oidList valueAndFormatList
-    else
-      let
-        paramList =
-          ParamsEncoders.run'' encoder params integerDatetimes
-        in
-          sendUnpreparedParametricQuery connection template paramList
-
-{-# INLINE sendNonparametricQuery #-}
-sendNonparametricQuery :: LibPQ.Connection -> ByteString -> IO (Either ResultsDecoders.Error ())
-sendNonparametricQuery connection sql =
-  checkedSend connection $ LibPQ.sendQuery connection sql
diff --git a/library/Hasql/Private/PTI.hs b/library/Hasql/Private/PTI.hs
deleted file mode 100644
--- a/library/Hasql/Private/PTI.hs
+++ /dev/null
@@ -1,94 +0,0 @@
-module Hasql.Private.PTI where
-
-import Hasql.Private.Prelude hiding (bool)
-import qualified Database.PostgreSQL.LibPQ as LibPQ
-
-
--- | A Postgresql type info
-data PTI = PTI { ptiOID :: !OID, ptiArrayOID :: !(Maybe OID) }
-
--- | A Word32 and a LibPQ representation of an OID
-data OID = OID { oidWord32 :: !Word32, oidPQ :: !LibPQ.Oid }
-
-mkOID :: Word32 -> OID
-mkOID x =
-  OID x ((LibPQ.Oid . fromIntegral) x)
-
-mkPTI :: Word32 -> Maybe Word32 -> PTI
-mkPTI oid arrayOID =
-  PTI (mkOID oid) (fmap mkOID arrayOID)
-
-
--- * Constants
--------------------------
-
-abstime         = mkPTI 702  (Just 1023)
-aclitem         = mkPTI 1033 (Just 1034)
-bit             = mkPTI 1560 (Just 1561)
-bool            = mkPTI 16   (Just 1000)
-box             = mkPTI 603  (Just 1020)
-bpchar          = mkPTI 1042 (Just 1014)
-bytea           = mkPTI 17   (Just 1001)
-char            = mkPTI 18   (Just 1002)
-cid             = mkPTI 29   (Just 1012)
-cidr            = mkPTI 650  (Just 651)
-circle          = mkPTI 718  (Just 719)
-cstring         = mkPTI 2275 (Just 1263)
-date            = mkPTI 1082 (Just 1182)
-daterange       = mkPTI 3912 (Just 3913)
-float4          = mkPTI 700  (Just 1021)
-float8          = mkPTI 701  (Just 1022)
-gtsvector       = mkPTI 3642 (Just 3644)
-inet            = mkPTI 869  (Just 1041)
-int2            = mkPTI 21   (Just 1005)
-int2vector      = mkPTI 22   (Just 1006)
-int4            = mkPTI 23   (Just 1007)
-int4range       = mkPTI 3904 (Just 3905)
-int8            = mkPTI 20   (Just 1016)
-int8range       = mkPTI 3926 (Just 3927)
-interval        = mkPTI 1186 (Just 1187)
-json            = mkPTI 114  (Just 199)
-jsonb           = mkPTI 3802 (Just 3807)
-line            = mkPTI 628  (Just 629)
-lseg            = mkPTI 601  (Just 1018)
-macaddr         = mkPTI 829  (Just 1040)
-money           = mkPTI 790  (Just 791)
-name            = mkPTI 19   (Just 1003)
-numeric         = mkPTI 1700 (Just 1231)
-numrange        = mkPTI 3906 (Just 3907)
-oid             = mkPTI 26   (Just 1028)
-oidvector       = mkPTI 30   (Just 1013)
-path            = mkPTI 602  (Just 1019)
-point           = mkPTI 600  (Just 1017)
-polygon         = mkPTI 604  (Just 1027)
-record          = mkPTI 2249 (Just 2287)
-refcursor       = mkPTI 1790 (Just 2201)
-regclass        = mkPTI 2205 (Just 2210)
-regconfig       = mkPTI 3734 (Just 3735)
-regdictionary   = mkPTI 3769 (Just 3770)
-regoper         = mkPTI 2203 (Just 2208)
-regoperator     = mkPTI 2204 (Just 2209)
-regproc         = mkPTI 24   (Just 1008)
-regprocedure    = mkPTI 2202 (Just 2207)
-regtype         = mkPTI 2206 (Just 2211)
-reltime         = mkPTI 703  (Just 1024)
-text            = mkPTI 25   (Just 1009)
-tid             = mkPTI 27   (Just 1010)
-time            = mkPTI 1083 (Just 1183)
-timestamp       = mkPTI 1114 (Just 1115)
-timestamptz     = mkPTI 1184 (Just 1185)
-timetz          = mkPTI 1266 (Just 1270)
-tinterval       = mkPTI 704  (Just 1025)
-tsquery         = mkPTI 3615 (Just 3645)
-tsrange         = mkPTI 3908 (Just 3909)
-tstzrange       = mkPTI 3910 (Just 3911)
-tsvector        = mkPTI 3614 (Just 3643)
-txid_snapshot   = mkPTI 2970 (Just 2949)
-unknown         = mkPTI 705  (Just 705)
-uuid            = mkPTI 2950 (Just 2951)
-varbit          = mkPTI 1562 (Just 1563)
-varchar         = mkPTI 1043 (Just 1015)
-void            = mkPTI 2278 Nothing
-xid             = mkPTI 28   (Just 1011)
-xml             = mkPTI 142  (Just 143)
-
diff --git a/library/Hasql/Private/Prelude.hs b/library/Hasql/Private/Prelude.hs
deleted file mode 100644
--- a/library/Hasql/Private/Prelude.hs
+++ /dev/null
@@ -1,135 +0,0 @@
-module Hasql.Private.Prelude
-(
-  module Exports,
-  LazyByteString,
-  ByteStringBuilder,
-  LazyText,
-  TextBuilder,
-  bug,
-  bottom,
-  forMToZero_,
-  forMFromZero_,
-  strictCons,
-  mapLeft,
-)
-where
-
-
--- base-prelude
--------------------------
-import BasePrelude as Exports hiding (assert, left, right, isLeft, isRight, fromLeft, fromRight, error, (<>), First(..), Last(..), new)
-
--- transformers
--------------------------
-import Control.Monad.IO.Class as Exports
-import Control.Monad.Trans.Class as Exports
-import Control.Monad.Trans.Cont as Exports hiding (shift, callCC)
-import Control.Monad.Trans.Except as Exports (ExceptT(ExceptT), Except, except, runExcept, runExceptT, mapExcept, mapExceptT, withExcept, withExceptT, throwE, catchE)
-import Control.Monad.Trans.Maybe as Exports
-import Control.Monad.Trans.Reader as Exports (Reader, runReader, mapReader, withReader, ReaderT(ReaderT), runReaderT, mapReaderT, withReaderT)
-import Control.Monad.Trans.State.Strict as Exports (State, runState, evalState, execState, mapState, withState, StateT(StateT), runStateT, evalStateT, execStateT, mapStateT, withStateT)
-import Control.Monad.Trans.Writer.Strict as Exports (Writer, runWriter, execWriter, mapWriter, WriterT(..), execWriterT, mapWriterT)
-import Data.Functor.Compose as Exports
-import Data.Functor.Identity as Exports
-
--- mtl
--------------------------
-import Control.Monad.Error.Class as Exports (MonadError (..))
-
--- data-default-class
--------------------------
-import Data.Default.Class as Exports
-
--- profunctors
--------------------------
-import Data.Profunctor.Unsafe as Exports
-
--- contravariant
--------------------------
-import Data.Functor.Contravariant as Exports
-import Data.Functor.Contravariant.Divisible as Exports
-
--- contravariant-extras
--------------------------
-import Contravariant.Extras as Exports
-
--- semigroups
--------------------------
-import Data.Semigroup as Exports
-
--- hashable
--------------------------
-import Data.Hashable as Exports (Hashable(..))
-
--- text
--------------------------
-import Data.Text as Exports (Text)
-
--- bytestring
--------------------------
-import Data.ByteString as Exports (ByteString)
-
--- vector
--------------------------
-import Data.Vector as Exports (Vector)
-
--- dlist
--------------------------
-import Data.DList as Exports (DList)
-
--- placeholders
--------------------------
-import Development.Placeholders as Exports
-
--- loch-th
--------------------------
-import Debug.Trace.LocationTH as Exports
-
--- custom
--------------------------
-import qualified Debug.Trace.LocationTH
-import qualified Data.Text.Lazy
-import qualified Data.Text.Lazy.Builder
-import qualified Data.ByteString.Lazy
-import qualified Data.ByteString.Builder
-
-
-type LazyByteString =
-  Data.ByteString.Lazy.ByteString
-
-type ByteStringBuilder =
-  Data.ByteString.Builder.Builder
-
-type LazyText =
-  Data.Text.Lazy.Text
-
-type TextBuilder =
-  Data.Text.Lazy.Builder.Builder
-
-bug =
-  [e| $(Debug.Trace.LocationTH.failure) . (msg <>) |]
-  where
-    msg = "A \"hasql\" package bug: " :: String
-
-bottom =
-  [e| $bug "Bottom evaluated" |]
-
-{-# INLINE forMToZero_ #-}
-forMToZero_ :: Applicative m => Int -> (Int -> m a) -> m ()
-forMToZero_ !startN f =
-  ($ pred startN) $ fix $ \loop !n -> if n >= 0 then f n *> loop (pred n) else pure ()
-
-{-# INLINE forMFromZero_ #-}
-forMFromZero_ :: Applicative m => Int -> (Int -> m a) -> m ()
-forMFromZero_ !endN f =
-  ($ 0) $ fix $ \loop !n -> if n < endN then f n *> loop (succ n) else pure ()
-
-{-# INLINE strictCons #-}
-strictCons :: a -> [a] -> [a]
-strictCons !a b =
-  let !c = a : b in c
-
-{-# INLINE mapLeft #-}
-mapLeft :: (a -> c) -> Either a b -> Either c b
-mapLeft f =
-  either (Left . f) Right
diff --git a/library/Hasql/Private/PreparedStatementRegistry.hs b/library/Hasql/Private/PreparedStatementRegistry.hs
deleted file mode 100644
--- a/library/Hasql/Private/PreparedStatementRegistry.hs
+++ /dev/null
@@ -1,56 +0,0 @@
-module Hasql.Private.PreparedStatementRegistry
-(
-  PreparedStatementRegistry,
-  new,
-  update,
-  LocalKey(..),
-)
-where
-
-import Hasql.Private.Prelude hiding (lookup)
-import qualified Data.HashTable.IO as A
-import qualified ByteString.StrictBuilder as B
-
-
-data PreparedStatementRegistry =
-  PreparedStatementRegistry !(A.BasicHashTable LocalKey ByteString) !(IORef Word)
-
-{-# INLINABLE new #-}
-new :: IO PreparedStatementRegistry
-new =
-  PreparedStatementRegistry <$> A.new <*> newIORef 0
-
-{-# INLINABLE update #-}
-update :: LocalKey -> (ByteString -> IO (Bool, a)) -> (ByteString -> IO a) -> PreparedStatementRegistry -> IO a
-update localKey onNewRemoteKey onOldRemoteKey (PreparedStatementRegistry table counter) =
-  lookup >>= maybe new old
-  where
-    lookup =
-      A.lookup table localKey
-    new =
-      readIORef counter >>= onN
-      where
-        onN n =
-          do
-            (save, result) <- onNewRemoteKey remoteKey
-            when save $ do
-              A.insert table localKey remoteKey
-              writeIORef counter (succ n)
-            return result
-          where
-            remoteKey =
-              B.builderBytes . B.asciiIntegral $ n
-    old =
-      onOldRemoteKey
-
-
--- |
--- Local statement key.
-data LocalKey =
-  LocalKey !ByteString ![Word32]
-  deriving (Show, Eq)
-
-instance Hashable LocalKey where
-  {-# INLINE hashWithSalt #-}
-  hashWithSalt salt (LocalKey template types) =
-    hashWithSalt salt template
diff --git a/library/Hasql/Private/Query.hs b/library/Hasql/Private/Query.hs
deleted file mode 100644
--- a/library/Hasql/Private/Query.hs
+++ /dev/null
@@ -1,61 +0,0 @@
-module Hasql.Private.Query
-where
-
-import Hasql.Private.Prelude
-import qualified Database.PostgreSQL.LibPQ as LibPQ
-import qualified Hasql.Private.IO as IO
-import qualified Hasql.Private.Connection as Connection
-import qualified Hasql.Private.Decoders.Results as Decoders.Results
-import qualified Hasql.Private.Encoders.Params as Encoders.Params
-
-
--- |
--- An abstraction over parametric queries.
--- 
--- It is composable using
--- the standard interfaces of the category theory,
--- which it has instances of.
--- E.g., here's how you can compose queries
--- using the Arrow notation:
--- 
--- @
--- -- |
--- -- Given an Update query,
--- -- which uses the \@fmap (> 0) 'Decoders.Results.rowsAffected'\@ decoder
--- -- to detect, whether it had any effect,
--- -- and an Insert query,
--- -- produces a query which performs Upsert.
--- composeUpsert :: Query a Bool -> Query a () -> Query a ()
--- composeUpsert update insert =
---   proc params -> do
---     updated <- update -< params
---     if updated
---       then 'returnA' -< ()
---       else insert -< params
--- @
-newtype Query a b =
-  Query (Kleisli (ReaderT Connection.Connection (ExceptT Decoders.Results.Error IO)) a b)
-  deriving (Category, Arrow, ArrowChoice, ArrowLoop, ArrowApply)
-
-instance Functor (Query a) where
-  {-# INLINE fmap #-}
-  fmap =
-    (^<<)
-
-instance Profunctor Query where
-  {-# INLINE lmap #-}
-  lmap =
-    (^>>)
-  {-# INLINE rmap #-}
-  rmap =
-    (^<<)
-
-statement :: ByteString -> Encoders.Params.Params a -> Decoders.Results.Results b -> Bool -> Query a b
-statement template encoder decoder preparable =
-  Query $ Kleisli $ \params -> 
-    ReaderT $ \(Connection.Connection pqConnectionRef integerDatetimes registry) -> 
-      ExceptT $ withMVar pqConnectionRef $ \pqConnection -> do
-        r1 <- IO.sendParametricQuery pqConnection integerDatetimes registry template encoder preparable params
-        r2 <- IO.getResults pqConnection integerDatetimes decoder
-        return $ r1 *> r2
-
diff --git a/library/Hasql/Private/Session.hs b/library/Hasql/Private/Session.hs
deleted file mode 100644
--- a/library/Hasql/Private/Session.hs
+++ /dev/null
@@ -1,117 +0,0 @@
-module Hasql.Private.Session
-where
-
-import Hasql.Private.Prelude
-import qualified Database.PostgreSQL.LibPQ as LibPQ
-import qualified Hasql.Private.Decoders.Results as Decoders.Results
-import qualified Hasql.Private.Decoders.Result as Decoders.Result
-import qualified Hasql.Private.Settings as Settings
-import qualified Hasql.Private.IO as IO
-import qualified Hasql.Private.Query as Query
-import qualified Hasql.Private.Connection as Connection
-
-
--- |
--- A batch of actions to be executed in the context of a database connection.
-newtype Session a =
-  Session (ReaderT Connection.Connection (ExceptT Error IO) a)
-  deriving (Functor, Applicative, Monad, MonadError Error, MonadIO)
-
--- |
--- Executes a bunch of commands on the provided connection.
-run :: Session a -> Connection.Connection -> IO (Either Error a)
-run (Session impl) connection =
-  runExceptT $
-  runReaderT impl connection
-
--- |
--- Possibly a multi-statement query,
--- which however cannot be parameterized or prepared,
--- nor can any results of it be collected.
-sql :: ByteString -> Session ()
-sql sql =
-  Session $ ReaderT $ \(Connection.Connection pqConnectionRef integerDatetimes registry) ->
-    ExceptT $ fmap (mapLeft unsafeCoerce) $ withMVar pqConnectionRef $ \pqConnection -> do
-      r1 <- IO.sendNonparametricQuery pqConnection sql
-      r2 <- IO.getResults pqConnection integerDatetimes decoder
-      return $ r1 *> r2
-  where
-    decoder =
-      Decoders.Results.single $
-      Decoders.Result.unit
-
--- |
--- Parameters and a specification of the parametric query to apply them to.
-query :: a -> Query.Query a b -> Session b
-query input (Query.Query (Kleisli impl)) =
-  Session $ unsafeCoerce $ impl input
-
-
--- * Error
--------------------------
-
--- |
--- An error of some command in the session.
-data Error =
-  -- |
-  -- An error on the client-side,
-  -- with a message generated by the \"libpq\" library.
-  -- Usually indicates problems with connection.
-  ClientError !(Maybe ByteString) |
-  -- |
-  -- Some error with a command result.
-  ResultError !ResultError
-  deriving (Show, Eq)
-
--- |
--- An error with a command result.
-data ResultError =
-  -- | 
-  -- An error reported by the DB.
-  -- Consists of the following: Code, message, details, hint.
-  -- 
-  -- * __Code__.
-  -- The SQLSTATE code for the error.
-  -- It's recommended to use
-  -- <http://hackage.haskell.org/package/postgresql-error-codes the "postgresql-error-codes" package>
-  -- to work with those.
-  -- 
-  -- * __Message__.
-  -- The primary human-readable error message (typically one line). Always present.
-  -- 
-  -- * __Details__.
-  -- An optional secondary error message carrying more detail about the problem. 
-  -- Might run to multiple lines.
-  -- 
-  -- * __Hint__.
-  -- An optional suggestion on what to do about the problem. 
-  -- This is intended to differ from detail in that it offers advice (potentially inappropriate) 
-  -- rather than hard facts.
-  -- Might run to multiple lines.
-  ServerError !ByteString !ByteString !(Maybe ByteString) !(Maybe ByteString) |
-  -- |
-  -- The database returned an unexpected result.
-  -- Indicates an improper statement or a schema mismatch.
-  UnexpectedResult !Text |
-  -- |
-  -- An error of the row reader, preceded by the index of the row.
-  RowError !Int !RowError |
-  -- |
-  -- An unexpected amount of rows.
-  UnexpectedAmountOfRows !Int
-  deriving (Show, Eq)
-
--- |
--- An error during the decoding of a specific row.
-data RowError =
-  -- |
-  -- Appears on the attempt to parse more columns than there are in the result.
-  EndOfInput |
-  -- |
-  -- Appears on the attempt to parse a @NULL@ as some value.
-  UnexpectedNull |
-  -- |
-  -- Appears when a wrong value parser is used.
-  -- Comes with the error details.
-  ValueError !Text
-  deriving (Show, Eq)
diff --git a/library/Hasql/Private/Settings.hs b/library/Hasql/Private/Settings.hs
deleted file mode 100644
--- a/library/Hasql/Private/Settings.hs
+++ /dev/null
@@ -1,39 +0,0 @@
-module Hasql.Private.Settings where
-
-import Hasql.Private.Prelude
-import qualified Data.ByteString as B
-import qualified Data.ByteString.Lazy.Builder as BB
-import qualified Data.ByteString.Lazy.Builder.ASCII as BB
-import qualified Data.ByteString.Lazy as BL
-
-
-
--- | 
--- All settings encoded in a single byte-string according to 
--- <http://www.postgresql.org/docs/9.4/static/libpq-connect.html#LIBPQ-CONNSTRING the PostgreSQL format>.
-type Settings =
-  ByteString
-
--- |
--- Encode a host, a port, a user, a password and a database into the PostgreSQL settings byte-string.
-{-# INLINE settings #-}
-settings :: ByteString -> Word16 -> ByteString -> ByteString -> ByteString -> Settings
-settings host port user password database =
-  BL.toStrict $ BB.toLazyByteString $ mconcat $ intersperse (BB.char7 ' ') $ catMaybes $
-  [
-    mappend (BB.string7 "host=") . BB.byteString <$> 
-    mfilter (not . B.null) (pure host)
-    ,
-    mappend (BB.string7 "port=") . BB.word16Dec <$> 
-    mfilter (/= 0) (pure port)
-    ,
-    mappend (BB.string7 "user=") . BB.byteString <$> 
-    mfilter (not . B.null) (pure user)
-    ,
-    mappend (BB.string7 "password=") . BB.byteString <$> 
-    mfilter (not . B.null) (pure password)
-    ,
-    mappend (BB.string7 "dbname=") . BB.byteString <$> 
-    mfilter (not . B.null) (pure database)
-  ]
-
diff --git a/library/Hasql/Query.hs b/library/Hasql/Query.hs
deleted file mode 100644
--- a/library/Hasql/Query.hs
+++ /dev/null
@@ -1,57 +0,0 @@
-module Hasql.Query
-(
-  Query.Query,
-  statement,
-)
-where
-
-import Hasql.Private.Prelude
-import qualified Hasql.Private.Query as Query
-import qualified Hasql.Private.Decoders.Results as Decoders.Results
-import qualified Hasql.Decoders as Decoders
-import qualified Hasql.Private.Encoders.Params as Encoders.Params
-import qualified Hasql.Encoders as Encoders
-
-
-
--- |
--- A specification of a strictly single-statement query, which can be parameterized and prepared.
--- 
--- Consists of the following:
--- 
--- * SQL template,
--- * params encoder,
--- * result decoder,
--- * a flag, determining whether it should be prepared.
--- 
--- The SQL template must be formatted according to Postgres' standard,
--- with any non-ASCII characters of the template encoded using UTF-8.
--- According to the format,
--- parameters must be referred to using the positional notation, as in the following:
--- @$1@, @$2@, @$3@ and etc.
--- Those references must be used to refer to the values of the 'Encoders.Params' encoder.
--- 
--- Following is an example of the declaration of a prepared statement with its associated codecs.
--- 
--- @
--- selectSum :: Hasql.Query.'Query.Query' (Int64, Int64) Int64
--- selectSum =
---   Hasql.Query.'statement' sql encoder decoder True
---   where
---     sql =
---       "select ($1 + $2)"
---     encoder =
---       'contramap' 'fst' (Hasql.Encoders.'Hasql.Encoders.value' Hasql.Encoders.'Hasql.Encoders.int8') '<>'
---       'contramap' 'snd' (Hasql.Encoders.'Hasql.Encoders.value' Hasql.Encoders.'Hasql.Encoders.int8')
---     decoder =
---       Hasql.Decoders.'Hasql.Decoders.singleRow' (Hasql.Decoders.'Hasql.Decoders.value' Hasql.Decoders.'Hasql.Decoders.int8')
--- @
--- 
--- The statement above accepts a product of two parameters of type 'Int64'
--- and produces a single result of type 'Int64'.
--- 
-{-# INLINE statement #-}
-statement :: ByteString -> Encoders.Params a -> Decoders.Result b -> Bool -> Query.Query a b
-statement =
-  unsafeCoerce Query.statement
-
diff --git a/library/Hasql/Session.hs b/library/Hasql/Session.hs
deleted file mode 100644
--- a/library/Hasql/Session.hs
+++ /dev/null
@@ -1,15 +0,0 @@
-module Hasql.Session
-(
-  Session.Session,
-  Session.sql,
-  Session.query,
-  -- * Execution
-  Session.Error(..),
-  Session.ResultError(..),
-  Session.RowError(..),
-  Session.run,
-)
-where
-
-import qualified Hasql.Private.Session as Session
-
diff --git a/profiling/Main.hs b/profiling/Main.hs
deleted file mode 100644
--- a/profiling/Main.hs
+++ /dev/null
@@ -1,98 +0,0 @@
-module Main where
-
-import Prelude
-import Bug
-import qualified Hasql.Connection as A
-import qualified Hasql.Session as B
-import qualified Hasql.Query as C
-import qualified Hasql.Decoders as D
-import qualified Hasql.Encoders as E
-import qualified Data.Vector as F
-
-
-main =
-  do
-    Right connection <- acquireConnection
-    traceEventIO "START Session"
-    Right result <- B.run sessionWithManySmallResults connection
-    traceEventIO "STOP Session"
-    return ()
-  where
-    acquireConnection =
-      A.acquire settings
-      where
-        settings =
-          A.settings host port user password database
-          where
-            host = "localhost"
-            port = 5432
-            user = "postgres"
-            password = ""
-            database = "postgres"
-
-
--- * Sessions
--------------------------
-
-sessionWithManySmallParameters :: Vector (Int64, Int64) -> B.Session ()
-sessionWithManySmallParameters =
-  $(todo "sessionWithManySmallParameters")
-
-sessionWithSingleLargeResultInVector :: B.Session (Vector (Int64, Int64))
-sessionWithSingleLargeResultInVector =
-  B.query () queryWithManyRowsInVector
-
-sessionWithSingleLargeResultInList :: B.Session (List (Int64, Int64))
-sessionWithSingleLargeResultInList =
-  B.query () queryWithManyRowsInList
-
-sessionWithManySmallResults :: B.Session (Vector (Int64, Int64))
-sessionWithManySmallResults =
-  F.replicateM 1000 (B.query () queryWithSingleRow)
-
-
--- * Statements
--------------------------
-
-queryWithManyParameters :: C.Query (Vector (Int64, Int64)) ()
-queryWithManyParameters =
-  $(todo "statementWithManyParameters")
-
-queryWithSingleRow :: C.Query () (Int64, Int64)
-queryWithSingleRow =
-  C.statement template encoder decoder True
-  where
-    template =
-      "SELECT 1, 2"
-    encoder =
-      conquer
-    decoder =
-      D.singleRow row
-      where
-        row =
-          tuple <$> D.value D.int8 <*> D.value D.int8
-          where
-            tuple !a !b =
-              (a, b)
-
-queryWithManyRows :: (D.Row (Int64, Int64) -> D.Result result) -> C.Query () result
-queryWithManyRows decoder =
-  C.statement template encoder (decoder rowDecoder) True
-  where
-    template =
-      "SELECT generate_series(0,1000) as a, generate_series(1000,2000) as b"
-    encoder =
-      conquer
-    rowDecoder =
-      tuple <$> D.value D.int8 <*> D.value D.int8
-      where
-        tuple !a !b =
-          (a, b)
-
-queryWithManyRowsInVector :: C.Query () (Vector (Int64, Int64))
-queryWithManyRowsInVector =
-  queryWithManyRows D.rowsVector
-
-queryWithManyRowsInList :: C.Query () (List (Int64, Int64))
-queryWithManyRowsInList =
-  queryWithManyRows D.rowsList
diff --git a/src/benchmarks/Main.hs b/src/benchmarks/Main.hs
new file mode 100644
--- /dev/null
+++ b/src/benchmarks/Main.hs
@@ -0,0 +1,107 @@
+module Main (main) where
+
+import Criterion
+import Criterion.Main
+import Hasql.Connection qualified as A
+import Hasql.Decoders qualified as D
+import Hasql.Pipeline qualified as E
+import Hasql.Session qualified as B
+import Hasql.Statement qualified as C
+import Pqi.Ffi qualified
+import Pqi.Native qualified
+import Prelude
+
+main :: IO ()
+main =
+  do
+    ffiConnection <- acquireConnection Pqi.Ffi.adapter
+    nativeConnection <- acquireConnection Pqi.Native.adapter
+    defaultMain
+      [ adapterGroup "ffi" ffiConnection,
+        adapterGroup "native" nativeConnection
+      ]
+  where
+    acquireConnection adapter =
+      A.acquire adapter mempty >>= either (fail . show) pure
+    adapterGroup :: String -> A.Connection -> Benchmark
+    adapterGroup groupName connection =
+      bgroup
+        groupName
+        [ sessionBench "largeResultInVector" sessionWithSingleLargeResultInVector,
+          sessionBench "largeResultInList" sessionWithSingleLargeResultInList,
+          sessionBench "manyLargeResults" sessionWithManyLargeResults,
+          sessionBench "manyLargeResultsViaPipeline" sessionWithManyLargeResultsViaPipeline,
+          sessionBench "manySmallResults" sessionWithManySmallResults,
+          sessionBench "manySmallResultsViaPipeline" sessionWithManySmallResultsViaPipeline
+        ]
+      where
+        sessionBench :: (NFData a) => String -> B.Session a -> Benchmark
+        sessionBench name session =
+          bench name (nfIO (A.use connection session >>= either (fail . show) pure))
+
+-- * Sessions
+
+sessionWithSingleLargeResultInVector :: B.Session (Vector (Int32, Int32))
+sessionWithSingleLargeResultInVector =
+  B.statement () statementWithManyRowsInVector
+
+sessionWithSingleLargeResultInList :: B.Session [(Int32, Int32)]
+sessionWithSingleLargeResultInList =
+  B.statement () statementWithManyRowsInList
+
+sessionWithManyLargeResults :: B.Session [Vector (Int32, Int32)]
+sessionWithManyLargeResults =
+  replicateM 100 (B.statement () statementWithManyRowsInVector)
+
+sessionWithManySmallResults :: B.Session [(Int32, Int32)]
+sessionWithManySmallResults =
+  replicateM 100 (B.statement () statementWithSingleRow)
+
+sessionWithManyLargeResultsViaPipeline :: B.Session [Vector (Int32, Int32)]
+sessionWithManyLargeResultsViaPipeline =
+  B.pipeline (replicateM 100 (E.statement () statementWithManyRowsInVector))
+
+sessionWithManySmallResultsViaPipeline :: B.Session [(Int32, Int32)]
+sessionWithManySmallResultsViaPipeline =
+  B.pipeline (replicateM 100 (E.statement () statementWithSingleRow))
+
+-- * Statements
+
+statementWithSingleRow :: C.Statement () (Int32, Int32)
+statementWithSingleRow =
+  C.preparable template encoder decoder
+  where
+    template =
+      "SELECT 1, 2"
+    encoder =
+      conquer
+    decoder =
+      D.singleRow row
+      where
+        row =
+          tuple <$> (D.column . D.nonNullable) D.int4 <*> (D.column . D.nonNullable) D.int4
+          where
+            tuple !a !b =
+              (a, b)
+
+statementWithManyRows :: (D.Row (Int32, Int32) -> D.Result result) -> C.Statement () result
+statementWithManyRows decoder =
+  C.preparable template encoder (decoder rowDecoder)
+  where
+    template =
+      "SELECT generate_series(0,1000) as a, generate_series(1000,2000) as b"
+    encoder =
+      conquer
+    rowDecoder =
+      tuple <$> (D.column . D.nonNullable) D.int4 <*> (D.column . D.nonNullable) D.int4
+      where
+        tuple !a !b =
+          (a, b)
+
+statementWithManyRowsInVector :: C.Statement () (Vector (Int32, Int32))
+statementWithManyRowsInVector =
+  statementWithManyRows D.rowVector
+
+statementWithManyRowsInList :: C.Statement () [(Int32, Int32)]
+statementWithManyRowsInList =
+  statementWithManyRows D.rowList
diff --git a/src/codecs-vocab/Hasql/CodecsVocab.hs b/src/codecs-vocab/Hasql/CodecsVocab.hs
new file mode 100644
--- /dev/null
+++ b/src/codecs-vocab/Hasql/CodecsVocab.hs
@@ -0,0 +1,12 @@
+module Hasql.CodecsVocab
+  ( QualifiedTypeName (QualifiedTypeName),
+    TypeInfo (TypeInfo),
+    TypeRef (..),
+    TypeShape (TypeShape),
+  )
+where
+
+import Hasql.CodecsVocab.QualifiedTypeName
+import Hasql.CodecsVocab.TypeInfo
+import Hasql.CodecsVocab.TypeRef
+import Hasql.CodecsVocab.TypeShape
diff --git a/src/codecs-vocab/Hasql/CodecsVocab/QualifiedTypeName.hs b/src/codecs-vocab/Hasql/CodecsVocab/QualifiedTypeName.hs
new file mode 100644
--- /dev/null
+++ b/src/codecs-vocab/Hasql/CodecsVocab/QualifiedTypeName.hs
@@ -0,0 +1,43 @@
+module Hasql.CodecsVocab.QualifiedTypeName
+  ( QualifiedTypeName (..),
+    fromNameTuple,
+    toNameTuple,
+  )
+where
+
+import Hasql.Platform.Prelude
+
+-- |
+-- A Postgres type identified by name: an optional schema together with a
+-- required type name.
+--
+-- A 'Nothing' schema means the name is unqualified and is resolved via the
+-- server's search path.
+--
+-- Used as the key under which a type's OIDs are resolved and cached.
+data QualifiedTypeName = QualifiedTypeName
+  { schema :: Maybe Text,
+    name :: Text
+  }
+  deriving stock (Eq, Ord, Show, Generic)
+
+instance Hashable QualifiedTypeName
+
+-- | An unqualified name constructor for convenience.
+instance IsString QualifiedTypeName where
+  fromString = QualifiedTypeName Nothing . fromString
+
+-- |
+-- Convert from the legacy @(schema, name)@ tuple representation.
+--
+-- Used at public-API boundaries (e.g. the @custom@ codecs and error types)
+-- where the tuple is still exposed but internals operate on 'QualifiedTypeName'.
+fromNameTuple :: (Maybe Text, Text) -> QualifiedTypeName
+fromNameTuple (schema, name) = QualifiedTypeName schema name
+
+-- |
+-- Convert to the legacy @(schema, name)@ tuple representation.
+--
+-- See 'fromNameTuple'.
+toNameTuple :: QualifiedTypeName -> (Maybe Text, Text)
+toNameTuple (QualifiedTypeName schema name) = (schema, name)
diff --git a/src/codecs-vocab/Hasql/CodecsVocab/TypeInfo.hs b/src/codecs-vocab/Hasql/CodecsVocab/TypeInfo.hs
new file mode 100644
--- /dev/null
+++ b/src/codecs-vocab/Hasql/CodecsVocab/TypeInfo.hs
@@ -0,0 +1,235 @@
+module Hasql.CodecsVocab.TypeInfo where
+
+import Hasql.Platform.Prelude hiding (bool)
+
+-- | A Postgresql type info
+data TypeInfo
+  = TypeInfo {toBaseOid :: Word32, toArrayOid :: Word32}
+  deriving (Eq, Ord, Show)
+
+abstime :: TypeInfo
+abstime = TypeInfo 702 1023
+
+aclitem :: TypeInfo
+aclitem = TypeInfo 1033 1034
+
+bit :: TypeInfo
+bit = TypeInfo 1560 1561
+
+bool :: TypeInfo
+bool = TypeInfo 16 1000
+
+box :: TypeInfo
+box = TypeInfo 603 1020
+
+bpchar :: TypeInfo
+bpchar = TypeInfo 1042 1014
+
+bytea :: TypeInfo
+bytea = TypeInfo 17 1001
+
+char :: TypeInfo
+char = TypeInfo 18 1002
+
+cid :: TypeInfo
+cid = TypeInfo 29 1012
+
+cidr :: TypeInfo
+cidr = TypeInfo 650 651
+
+circle :: TypeInfo
+circle = TypeInfo 718 719
+
+cstring :: TypeInfo
+cstring = TypeInfo 2275 1263
+
+date :: TypeInfo
+date = TypeInfo 1082 1182
+
+daterange :: TypeInfo
+daterange = TypeInfo 3912 3913
+
+datemultirange :: TypeInfo
+datemultirange = TypeInfo 4535 6155
+
+float4 :: TypeInfo
+float4 = TypeInfo 700 1021
+
+float8 :: TypeInfo
+float8 = TypeInfo 701 1022
+
+gtsvector :: TypeInfo
+gtsvector = TypeInfo 3642 3644
+
+inet :: TypeInfo
+inet = TypeInfo 869 1041
+
+int2 :: TypeInfo
+int2 = TypeInfo 21 1005
+
+int2vector :: TypeInfo
+int2vector = TypeInfo 22 1006
+
+int4 :: TypeInfo
+int4 = TypeInfo 23 1007
+
+int4range :: TypeInfo
+int4range = TypeInfo 3904 3905
+
+int4multirange :: TypeInfo
+int4multirange = TypeInfo 4451 6150
+
+int8 :: TypeInfo
+int8 = TypeInfo 20 1016
+
+int8range :: TypeInfo
+int8range = TypeInfo 3926 3927
+
+int8multirange :: TypeInfo
+int8multirange = TypeInfo 4536 6157
+
+interval :: TypeInfo
+interval = TypeInfo 1186 1187
+
+json :: TypeInfo
+json = TypeInfo 114 199
+
+jsonb :: TypeInfo
+jsonb = TypeInfo 3802 3807
+
+line :: TypeInfo
+line = TypeInfo 628 629
+
+lseg :: TypeInfo
+lseg = TypeInfo 601 1018
+
+macaddr :: TypeInfo
+macaddr = TypeInfo 829 1040
+
+money :: TypeInfo
+money = TypeInfo 790 791
+
+name :: TypeInfo
+name = TypeInfo 19 1003
+
+numeric :: TypeInfo
+numeric = TypeInfo 1700 1231
+
+numrange :: TypeInfo
+numrange = TypeInfo 3906 3907
+
+nummultirange :: TypeInfo
+nummultirange = TypeInfo 4532 6151
+
+oid :: TypeInfo
+oid = TypeInfo 26 1028
+
+oidvector :: TypeInfo
+oidvector = TypeInfo 30 1013
+
+path :: TypeInfo
+path = TypeInfo 602 1019
+
+point :: TypeInfo
+point = TypeInfo 600 1017
+
+polygon :: TypeInfo
+polygon = TypeInfo 604 1027
+
+record :: TypeInfo
+record = TypeInfo 2249 2287
+
+refcursor :: TypeInfo
+refcursor = TypeInfo 1790 2201
+
+regclass :: TypeInfo
+regclass = TypeInfo 2205 2210
+
+regconfig :: TypeInfo
+regconfig = TypeInfo 3734 3735
+
+regdictionary :: TypeInfo
+regdictionary = TypeInfo 3769 3770
+
+regoper :: TypeInfo
+regoper = TypeInfo 2203 2208
+
+regoperator :: TypeInfo
+regoperator = TypeInfo 2204 2209
+
+regproc :: TypeInfo
+regproc = TypeInfo 24 1008
+
+regprocedure :: TypeInfo
+regprocedure = TypeInfo 2202 2207
+
+regtype :: TypeInfo
+regtype = TypeInfo 2206 2211
+
+reltime :: TypeInfo
+reltime = TypeInfo 703 1024
+
+text :: TypeInfo
+text = TypeInfo 25 1009
+
+tid :: TypeInfo
+tid = TypeInfo 27 1010
+
+time :: TypeInfo
+time = TypeInfo 1083 1183
+
+timestamp :: TypeInfo
+timestamp = TypeInfo 1114 1115
+
+timestamptz :: TypeInfo
+timestamptz = TypeInfo 1184 1185
+
+timetz :: TypeInfo
+timetz = TypeInfo 1266 1270
+
+tinterval :: TypeInfo
+tinterval = TypeInfo 704 1025
+
+tsquery :: TypeInfo
+tsquery = TypeInfo 3615 3645
+
+tsrange :: TypeInfo
+tsrange = TypeInfo 3908 3909
+
+tsmultirange :: TypeInfo
+tsmultirange = TypeInfo 4533 6152
+
+tstzrange :: TypeInfo
+tstzrange = TypeInfo 3910 3911
+
+tstzmultirange :: TypeInfo
+tstzmultirange = TypeInfo 4534 6153
+
+tsvector :: TypeInfo
+tsvector = TypeInfo 3614 3643
+
+txid_snapshot :: TypeInfo
+txid_snapshot = TypeInfo 2970 2949
+
+-- | Postgres's actual @unknown@ type, assigned to untyped literals. Not to be confused with 'invalid'.
+unknown :: TypeInfo
+unknown = TypeInfo 705 705
+
+-- | Sentinel for a type name that failed to resolve to a real OID. Not to be confused with 'unknown', which is a real Postgres type.
+invalid :: TypeInfo
+invalid = TypeInfo 0 0
+
+uuid :: TypeInfo
+uuid = TypeInfo 2950 2951
+
+varbit :: TypeInfo
+varbit = TypeInfo 1562 1563
+
+varchar :: TypeInfo
+varchar = TypeInfo 1043 1015
+
+xid :: TypeInfo
+xid = TypeInfo 28 1011
+
+xml :: TypeInfo
+xml = TypeInfo 142 143
diff --git a/src/codecs-vocab/Hasql/CodecsVocab/TypeRef.hs b/src/codecs-vocab/Hasql/CodecsVocab/TypeRef.hs
new file mode 100644
--- /dev/null
+++ b/src/codecs-vocab/Hasql/CodecsVocab/TypeRef.hs
@@ -0,0 +1,20 @@
+module Hasql.CodecsVocab.TypeRef
+  ( TypeRef (..),
+  )
+where
+
+import Hasql.CodecsVocab.QualifiedTypeName (QualifiedTypeName)
+import Hasql.Platform.Prelude
+
+-- |
+-- How a parameter's Postgres type is identified within parameter metadata:
+-- either an already-known OID, or a 'QualifiedTypeName' still pending OID
+-- resolution against the server.
+data TypeRef
+  = -- | The type's OID is statically known.
+    KnownOid Word32
+  | -- | The type is named and its OID must be resolved before execution.
+    NamedType QualifiedTypeName
+  deriving stock (Eq, Ord, Show, Generic)
+
+instance Hashable TypeRef
diff --git a/src/codecs-vocab/Hasql/CodecsVocab/TypeShape.hs b/src/codecs-vocab/Hasql/CodecsVocab/TypeShape.hs
new file mode 100644
--- /dev/null
+++ b/src/codecs-vocab/Hasql/CodecsVocab/TypeShape.hs
@@ -0,0 +1,13 @@
+module Hasql.CodecsVocab.TypeShape
+  ( TypeShape (..),
+  )
+where
+
+import Hasql.CodecsVocab.TypeRef (TypeRef)
+import Hasql.Platform.Prelude
+
+-- | A value's type shape: type reference, array dimensionality, text-format flag.
+data TypeShape = TypeShape TypeRef Word Bool
+  deriving stock (Eq, Ord, Show, Generic)
+
+instance Hashable TypeShape
diff --git a/src/comms/Hasql/Comms/Recv.hs b/src/comms/Hasql/Comms/Recv.hs
new file mode 100644
--- /dev/null
+++ b/src/comms/Hasql/Comms/Recv.hs
@@ -0,0 +1,150 @@
+module Hasql.Comms.Recv
+  ( Recv,
+    singleResult,
+    allResults,
+    toHandler,
+    Error (..),
+  )
+where
+
+import Hasql.Comms.ResultDecoder qualified as ResultDecoder
+import Hasql.Platform.Prelude
+import Pqi qualified as Pq
+
+-- | 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 tag) where
+  {-# INLINE pure #-}
+  pure x = Recv \_ -> pure (Right x)
+  {-# INLINE (<*>) #-}
+  Recv recv1 <*> Recv recv2 =
+    Recv \cs -> do
+      ef <- recv1 cs
+      eg <- recv2 cs
+      pure (ef <*> eg)
+
+instance Bifunctor Recv where
+  {-# INLINE bimap #-}
+  bimap f g (Recv recv) = Recv (fmap (bimap (fmap f) g) . recv)
+
+toHandler :: Recv tag a -> Pq.Connection -> IO (Either (Error tag) a)
+toHandler (Recv recv) = recv
+
+-- | Exactly one result.
+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
+        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 -> 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 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.
+-- This is useful for scripts that may contain multiple statements,
+-- 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 :: 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 -> 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 tag resultIndex err))
+              Right _ ->
+                loop (resultIndex + 1) maybeError
+  errorOrUnit <- loop 0 Nothing
+  pure (maybe (Right ()) Left errorOrUnit)
+
+-- * Errors
+
+-- | Error of receiving results, carrying the tag of the action that caused it.
+data Error tag
+  = ResultError
+      tag
+      -- | Offset of the result in the series.
+      Int
+      -- | Underlying error.
+      ResultDecoder.Error
+  | NoResultsError
+      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
+      tag
+      -- | Expected count.
+      Int
+  deriving stock (Show, Eq, Functor)
+
+instance Comonad Error where
+  {-# INLINE extract #-}
+  extract = \case
+    ResultError tag _ _ -> tag
+    NoResultsError tag _ _ -> tag
+    TooManyResultsError tag _ -> tag
+
+  {-# INLINE duplicate #-}
+  duplicate e = case e of
+    ResultError _ resultIndex resultError -> ResultError e resultIndex resultError
+    NoResultsError _ connectionLost details -> NoResultsError e connectionLost details
+    TooManyResultsError _ expectedCount -> TooManyResultsError e expectedCount
diff --git a/src/comms/Hasql/Comms/ResultDecoder.hs b/src/comms/Hasql/Comms/ResultDecoder.hs
new file mode 100644
--- /dev/null
+++ b/src/comms/Hasql/Comms/ResultDecoder.hs
@@ -0,0 +1,344 @@
+module Hasql.Comms.ResultDecoder
+  ( ResultDecoder,
+
+    -- * Relations
+    Handler,
+    toHandler,
+    fromHandler,
+
+    -- * Extractors
+    columnOids,
+
+    -- * Constructors
+
+    -- ** Basic
+    ok,
+    pipelineSync,
+    rowsAffected,
+    checkExecStatus,
+
+    -- ** Higher-level decoders
+    maybe,
+    single,
+    vector,
+    foldl,
+    foldr,
+
+    -- ** Refinement
+    refine,
+
+    -- * Errors
+    Error (..),
+  )
+where
+
+import Data.Attoparsec.ByteString.Char8 qualified as Attoparsec
+import Data.ByteString qualified as ByteString
+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
+import Pqi qualified as Pq
+
+-- | Result consumption context, for consuming a single result from a sequence of results returned by the server.
+newtype ResultDecoder a
+  = ResultDecoder (Pq.Result -> IO (Either Error a))
+  deriving
+    (Functor, Applicative, Monad, MonadError Error, MonadReader Pq.Result)
+    via (ReaderT Pq.Result (ExceptT Error IO))
+
+instance Filterable ResultDecoder where
+  {-# INLINE mapMaybe #-}
+  mapMaybe fn =
+    refine (Prelude.maybe (Left "Invalid result") Right . fn)
+
+-- * Relations
+
+-- ** Handler
+
+type Handler a = Pq.Result -> IO (Either Error a)
+
+toHandler :: ResultDecoder a -> Handler a
+toHandler (ResultDecoder handler) =
+  handler
+
+fromHandler :: Handler a -> ResultDecoder a
+fromHandler handler =
+  ResultDecoder handler
+
+-- * Construction
+
+{-# INLINE ok #-}
+ok :: ResultDecoder ()
+ok = checkExecStatus [Pq.CommandOk, Pq.TuplesOk]
+
+{-# INLINE pipelineSync #-}
+pipelineSync :: ResultDecoder ()
+pipelineSync = checkExecStatus [Pq.PipelineSync]
+
+{-# INLINE rowsAffected #-}
+rowsAffected :: ResultDecoder Int64
+rowsAffected = do
+  checkExecStatus [Pq.CommandOk]
+  ResultDecoder \result -> do
+    cmdTuplesReader <$> Pq.cmdTuples result
+  where
+    cmdTuplesReader =
+      notNothing >=> notEmpty >=> decimal
+      where
+        notNothing =
+          Prelude.maybe (Left (UnexpectedResult "No bytes")) Right
+        notEmpty bytes =
+          if ByteString.null bytes
+            then Left (UnexpectedResult "Empty bytes")
+            else Right bytes
+        decimal bytes =
+          first
+            ( \m ->
+                UnexpectedResult
+                  ("Decimal parsing failure: " <> fromString m)
+            )
+            ( Attoparsec.parseOnly
+                (Attoparsec.decimal <* Attoparsec.endOfInput)
+                bytes
+            )
+
+{-# INLINE checkExecStatus #-}
+checkExecStatus :: [Pq.ExecStatus] -> ResultDecoder ()
+checkExecStatus expectedList = do
+  status <- ResultDecoder \result -> Right <$> Pq.resultStatus result
+  unless (elem status expectedList) $ do
+    case status of
+      Pq.BadResponse -> serverError
+      Pq.NonfatalError -> serverError
+      Pq.FatalError -> serverError
+      Pq.EmptyQuery -> return ()
+      _ ->
+        throwError
+          ( UnexpectedResult
+              ("Unexpected result status: " <> fromString (show status) <> ". Expecting one of the following: " <> fromString (show expectedList))
+          )
+
+{-# INLINE serverError #-}
+serverError :: ResultDecoder ()
+serverError =
+  ResultDecoder \result -> do
+    code <-
+      fold <$> Pq.resultErrorField result Pq.DiagSqlstate
+    message <-
+      fold <$> Pq.resultErrorField result Pq.DiagMessagePrimary
+    detail <-
+      Pq.resultErrorField result Pq.DiagMessageDetail
+    hint <-
+      Pq.resultErrorField result Pq.DiagMessageHint
+    position <-
+      parsePosition <$> Pq.resultErrorField result Pq.DiagStatementPosition
+    pure $ Left $ ServerError code message detail hint position
+  where
+    parsePosition = \case
+      Nothing -> Nothing
+      Just pos ->
+        case Attoparsec.parseOnly (Attoparsec.decimal <* Attoparsec.endOfInput) pos of
+          Right pos -> Just pos
+          _ -> Nothing
+
+-- | Get the OIDs of all columns in the current result.
+{-# INLINE columnOids #-}
+columnOids :: ResultDecoder [Word32]
+columnOids = ResultDecoder \result -> do
+  count <- Pq.nfields result
+  oids <- forM [0 .. count - 1] $ \colIndex ->
+    Pq.ftype result colIndex
+  pure (Right oids)
+
+-- * Higher-level decoders
+
+{-# INLINE checkCompatibility #-}
+checkCompatibility :: RowDecoder.RowDecoder a -> ResultDecoder ()
+checkCompatibility rowDec =
+  let oids = RowDecoder.toExpectedOids rowDec
+      oidsLength = length oids
+   in ResultDecoder \result -> do
+        maxCols <- Pq.nfields result
+        if oidsLength == fromIntegral maxCols
+          then
+            let go [] _ = pure (Right ())
+                go (Nothing : rest) colIndex = go rest (succ colIndex)
+                go (Just expectedOid : rest) colIndex = do
+                  actualOid <- Pq.ftype result (fromIntegral colIndex)
+                  if actualOid == expectedOid
+                    then go rest (succ colIndex)
+                    else
+                      pure
+                        ( Left
+                            ( DecoderTypeMismatch
+                                colIndex
+                                expectedOid
+                                actualOid
+                            )
+                        )
+             in go oids 0
+          else pure (Left (UnexpectedColumnCount oidsLength (fromIntegral maxCols)))
+
+{-# INLINE maybe #-}
+maybe :: RowDecoder.RowDecoder a -> ResultDecoder (Maybe a)
+maybe rowDec =
+  do
+    checkExecStatus [Pq.TuplesOk]
+    checkCompatibility rowDec
+    ResultDecoder
+      $ \result -> do
+        maxRows <- Pq.ntuples result
+        case maxRows of
+          0 -> return (Right Nothing)
+          1 -> do
+            result <-
+              RowDecoder.toDecoder rowDec result 0
+                <&> first (RowError 0)
+            pure (fmap Just result)
+          _ -> return (Left (UnexpectedRowCount (fromIntegral maxRows)))
+
+{-# INLINE single #-}
+single :: RowDecoder.RowDecoder a -> ResultDecoder a
+single rowDec =
+  do
+    checkExecStatus [Pq.TuplesOk]
+    checkCompatibility rowDec
+    ResultDecoder
+      $ \result -> do
+        maxRows <- Pq.ntuples result
+        case maxRows of
+          1 -> do
+            RowDecoder.toDecoder rowDec result 0
+              <&> first (RowError 0)
+          _ -> return (Left (UnexpectedRowCount (fromIntegral maxRows)))
+
+{-# INLINE vector #-}
+vector :: (GenericVector.Vector vector a) => RowDecoder.RowDecoder a -> ResultDecoder (vector a)
+vector rowDec =
+  do
+    checkExecStatus [Pq.TuplesOk]
+    checkCompatibility rowDec
+    ResultDecoder
+      $ \result -> do
+        maxRows <- Pq.ntuples result
+        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 -> GenericMutableVector.unsafeWrite mvector rowIndex x
+        readIORef failureRef >>= \case
+          Nothing -> Right <$> GenericVector.unsafeFreeze mvector
+          Just x -> pure (Left x)
+
+{-# INLINE foldl #-}
+foldl :: (a -> b -> a) -> a -> RowDecoder.RowDecoder b -> ResultDecoder a
+foldl step init rowDec =
+  {-# SCC "foldl" #-}
+  do
+    checkExecStatus [Pq.TuplesOk]
+    checkCompatibility rowDec
+    ResultDecoder
+      $ \result ->
+        {-# SCC "traversal" #-}
+        do
+          maxRows <- Pq.ntuples result
+          accRef <- newIORef init
+          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 -> modifyIORef' accRef (\acc -> step acc x)
+          readIORef failureRef >>= \case
+            Nothing -> Right <$> readIORef accRef
+            Just x -> pure (Left x)
+
+{-# INLINE foldr #-}
+foldr :: (b -> a -> a) -> a -> RowDecoder.RowDecoder b -> ResultDecoder a
+foldr step init rowDec =
+  {-# SCC "foldr" #-}
+  do
+    checkExecStatus [Pq.TuplesOk]
+    checkCompatibility rowDec
+    ResultDecoder
+      $ \result -> do
+        maxRows <- Pq.ntuples result
+        accRef <- newIORef init
+        failureRef <- newIORef Nothing
+        forMToZero_ (fromIntegral maxRows) $ \rowIndex -> do
+          rowResult <- RowDecoder.toDecoder rowDec result (fromIntegral rowIndex)
+          case rowResult of
+            Left !err -> writeIORef failureRef (Just (RowError rowIndex err))
+            Right !x -> modifyIORef accRef (\acc -> step x acc)
+        readIORef failureRef >>= \case
+          Nothing -> Right <$> readIORef accRef
+          Just x -> pure (Left x)
+
+-- * Refinement
+
+refine :: (a -> Either Text b) -> ResultDecoder a -> ResultDecoder b
+refine refiner (ResultDecoder reader) = ResultDecoder
+  $ \result -> do
+    resultEither <- reader result
+    return $ resultEither >>= first UnexpectedResult . refiner
+
+-- * Errors
+
+-- |
+-- An error with a command result.
+data Error
+  = -- | An error reported by the DB.
+    ServerError
+      -- | __Code__. The SQLSTATE code for the error. It's recommended to use
+      -- <http://hackage.haskell.org/package/postgresql-error-codes
+      -- the "postgresql-error-codes" package> to work with those.
+      ByteString
+      -- | __Message__. The primary human-readable error message(typically one
+      -- line). Always present.
+      ByteString
+      -- | __Details__. An optional secondary error message carrying more
+      -- detail about the problem. Might run to multiple lines.
+      (Maybe ByteString)
+      -- | __Hint__. An optional suggestion on what to do about the problem.
+      -- This is intended to differ from detail in that it offers advice
+      -- (potentially inappropriate) rather than hard facts. Might run to
+      -- multiple lines.
+      (Maybe ByteString)
+      -- | __Position__. Error cursor position as an index into the original
+      -- statement string. Positions are measured in characters not bytes.
+      (Maybe Int)
+  | -- |
+    -- The database returned an unexpected result.
+    -- Indicates an improper statement or a schema mismatch.
+    UnexpectedResult Text
+  | -- |
+    -- An unexpected amount of rows.
+    UnexpectedRowCount Int
+  | -- |
+    -- An unexpected amount of columns in the result.
+    UnexpectedColumnCount
+      -- | Expected amount of columns.
+      Int
+      -- | Actual amount of columns.
+      Int
+  | -- |
+    -- Appears when the decoder's expected type doesn't match the actual column type.
+    -- Reports the expected OID and the actual OID from the result.
+    DecoderTypeMismatch
+      -- | Column index.
+      Int
+      -- | Expected OID.
+      Word32
+      -- | Actual OID.
+      Word32
+  | -- | An error in a specific row, reported by a row decoder.
+    RowError
+      -- | Row index.
+      Int
+      -- | Underlying error.
+      RowDecoder.Error
+  deriving (Show, Eq)
diff --git a/src/comms/Hasql/Comms/Roundtrip.hs b/src/comms/Hasql/Comms/Roundtrip.hs
new file mode 100644
--- /dev/null
+++ b/src/comms/Hasql/Comms/Roundtrip.hs
@@ -0,0 +1,179 @@
+module Hasql.Comms.Roundtrip
+  ( Roundtrip,
+
+    -- * Constructors
+    prepare,
+    queryPrepared,
+    queryParams,
+    script,
+
+    -- * Errors
+    Error (..),
+
+    -- * Execution
+    toPipelineIO,
+    toSerialIO,
+  )
+where
+
+import Hasql.Comms.Recv qualified as Recv
+import Hasql.Comms.ResultDecoder qualified as ResultDecoder
+import Hasql.Comms.Send qualified as Send
+import Hasql.Platform.Prelude
+import Pqi qualified as Pq
+
+-- | 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 tag) where
+  {-# INLINE pure #-}
+  pure x = Roundtrip mempty (pure x)
+  {-# INLINE (<*>) #-}
+  Roundtrip send1 recv1 <*> Roundtrip send2 recv2 =
+    Roundtrip (send1 <> send2) (recv1 <*> recv2)
+
+instance Bifunctor Roundtrip where
+  {-# INLINE bimap #-}
+  bimap f g (Roundtrip send recv) =
+    Roundtrip
+      (fmap f send)
+      (bimap f g recv)
+
+prepare :: tag -> ByteString -> ByteString -> [Word32] -> Roundtrip tag ()
+prepare tag statementName sql oidList =
+  Roundtrip
+    (Send.prepare tag statementName sql (Just oidList))
+    (Recv.singleResult tag ResultDecoder.ok)
+
+queryPrepared ::
+  tag ->
+  -- | Prepared statement name.
+  ByteString ->
+  -- | Parameters.
+  [Maybe (ByteString, Pq.Format)] ->
+  -- | Result format.
+  Pq.Format ->
+  -- | Result decoder.
+  ResultDecoder.ResultDecoder a ->
+  Roundtrip tag a
+queryPrepared tag statementName params resultFormat resultDecoder =
+  Roundtrip
+    (Send.queryPrepared tag statementName params resultFormat)
+    (Recv.singleResult tag resultDecoder)
+
+queryParams ::
+  tag ->
+  -- | SQL.
+  ByteString ->
+  -- | Parameters.
+  [Maybe (Word32, ByteString, Pq.Format)] ->
+  -- | Result format.
+  Pq.Format ->
+  -- | Result decoder.
+  ResultDecoder.ResultDecoder a ->
+  Roundtrip tag a
+queryParams tag sql params resultFormat resultDecoder =
+  Roundtrip
+    (Send.queryParams tag sql params resultFormat)
+    (Recv.singleResult tag resultDecoder)
+
+-- | Execute a script (multi-statement SQL).
+-- It consumes all results from the execution,
+-- which is necessary for scripts containing multiple statements.
+script :: tag -> ByteString -> Roundtrip tag ()
+script tag sql =
+  Roundtrip
+    (Send.query tag sql)
+    (Recv.allResults tag ResultDecoder.ok)
+
+-- | 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 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))
diff --git a/src/comms/Hasql/Comms/RowDecoder.hs b/src/comms/Hasql/Comms/RowDecoder.hs
new file mode 100644
--- /dev/null
+++ b/src/comms/Hasql/Comms/RowDecoder.hs
@@ -0,0 +1,79 @@
+module Hasql.Comms.RowDecoder
+  ( RowDecoder,
+    nullableColumn,
+    nonNullableColumn,
+
+    -- * Relations
+
+    -- ** Expected OIDs
+    toExpectedOids,
+
+    -- ** Decoder
+    Decoder,
+    toDecoder,
+
+    -- * Errors
+    Error,
+  )
+where
+
+import Hasql.Comms.RowReader qualified as RowReader
+import Hasql.Platform.Prelude
+import Pqi qualified as Pq
+
+-- * RowDecoder
+
+data RowDecoder a
+  = RowDecoder
+      [Maybe Word32]
+      (RowReader.RowReader a)
+  deriving stock (Functor)
+
+instance Applicative RowDecoder where
+  pure a = RowDecoder [] (pure a)
+  RowDecoder lOids lDec <*> RowDecoder rOids rDec =
+    RowDecoder (lOids <> rOids) (lDec <*> rDec)
+
+instance Filterable RowDecoder where
+  mapMaybe fn (RowDecoder oids dec) =
+    RowDecoder oids (mapMaybe fn dec)
+
+-- * Functions
+
+-- |
+-- Next value, decoded using the provided value decoder.
+{-# INLINE nullableColumn #-}
+nullableColumn :: Maybe Word32 -> (ByteString -> Either Text a) -> RowDecoder (Maybe a)
+nullableColumn oid decoder =
+  RowDecoder
+    [oid]
+    (RowReader.nullableColumn decoder)
+
+-- |
+-- Next value, decoded using the provided value decoder.
+{-# INLINE nonNullableColumn #-}
+nonNullableColumn :: Maybe Word32 -> (ByteString -> Either Text a) -> RowDecoder a
+nonNullableColumn oid decoder =
+  RowDecoder
+    [oid]
+    (RowReader.nonNullableColumn decoder)
+
+-- * Relations
+
+-- ** Expected OIDs
+
+toExpectedOids :: RowDecoder a -> [Maybe Word32]
+toExpectedOids (RowDecoder oids _) = oids
+
+-- ** Decoder
+
+type Decoder a = Pq.Result -> Int32 -> IO (Either Error a)
+
+{-# INLINE toDecoder #-}
+toDecoder :: RowDecoder a -> Decoder a
+toDecoder (RowDecoder _ dec) result row =
+  RowReader.toHandler dec result row
+
+-- * Errors
+
+type Error = RowReader.Error
diff --git a/src/comms/Hasql/Comms/RowReader.hs b/src/comms/Hasql/Comms/RowReader.hs
new file mode 100644
--- /dev/null
+++ b/src/comms/Hasql/Comms/RowReader.hs
@@ -0,0 +1,150 @@
+-- | 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,
+    nonNullableColumn,
+
+    -- * Errors
+    Error (..),
+    CellError (..),
+
+    -- * Relations
+    toHandler,
+  )
+where
+
+import Hasql.Platform.Prelude
+import Pqi qualified as Pq
+
+data Error
+  = CellError
+      -- | Column index, 0-based.
+      Int
+      -- | OID of the column type as reported by Postgres.
+      Word32
+      -- | Underlying error.
+      CellError
+  | RefinementError Text
+  deriving stock (Eq, Show)
+
+data CellError
+  = DecodingCellError Text
+  | 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
+      ( 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 \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 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 \result row col onError onSuccess ->
+    let colInt = fromIntegral col
+        col' = succ col
+
+        unexpectedNull = do
+          oid <- Pq.ftype result col
+          onError (CellError colInt oid UnexpectedNullCellError)
+
+        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.
+{-# INLINE nullableColumn #-}
+nullableColumn :: (ByteString -> Either Text a) -> RowReader (Maybe a)
+nullableColumn = column Just
+
+-- |
+-- Next value, decoded using the provided value decoder.
+{-# INLINE nonNullableColumn #-}
+nonNullableColumn :: (ByteString -> Either Text a) -> RowReader a
+nonNullableColumn = column id
diff --git a/src/comms/Hasql/Comms/Send.hs b/src/comms/Hasql/Comms/Send.hs
new file mode 100644
--- /dev/null
+++ b/src/comms/Hasql/Comms/Send.hs
@@ -0,0 +1,78 @@
+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
+
+-- | 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 ()))
+
+instance Functor Send where
+  {-# INLINE fmap #-}
+  fmap f (Send send) = Send \connection -> first f <$> send connection
+
+instance Semigroup (Send err) where
+  {-# INLINE (<>) #-}
+  Send send1 <> Send send2 = Send \cs -> do
+    result <- send1 cs
+    case result of
+      Left err -> pure (Left err)
+      Right () -> send2 cs
+
+instance Monoid (Send err) where
+  {-# INLINE mempty #-}
+  mempty = Send \_ -> pure (Right ())
+
+toHandler :: Send err -> Pq.Connection -> IO (Either err ())
+toHandler (Send send) = send
+
+liftPqSend :: err -> (Pq.Connection -> IO Bool) -> Send err
+liftPqSend err pqSend = Send \connection -> do
+  success <- pqSend connection
+  pure (if success then Right () else Left err)
+
+prepare :: err -> ByteString -> ByteString -> Maybe [Word32] -> Send err
+prepare err statementName sql oidList =
+  liftPqSend err \connection -> Pq.sendPrepare connection statementName sql oidList
+
+query :: err -> ByteString -> Send err
+query err sql =
+  liftPqSend err \connection -> Pq.sendQuery connection sql
+
+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 :: 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 :: err -> Send err
+pipelineSync err =
+  liftPqSend err \connection -> Pq.pipelineSync connection
+
+enterPipelineMode :: err -> Send err
+enterPipelineMode err =
+  liftPqSend err \connection -> Pq.enterPipelineMode connection
+
+exitPipelineMode :: err -> Send err
+exitPipelineMode err =
+  liftPqSend err \connection -> Pq.exitPipelineMode connection
diff --git a/src/connection-state-tests/Hasql/ConnectionState/OidCacheSpec.hs b/src/connection-state-tests/Hasql/ConnectionState/OidCacheSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/connection-state-tests/Hasql/ConnectionState/OidCacheSpec.hs
@@ -0,0 +1,114 @@
+module Hasql.ConnectionState.OidCacheSpec (spec) where
+
+import Data.HashMap.Strict qualified as HashMap
+import Data.HashSet qualified as HashSet
+import Hasql.CodecsVocab.QualifiedTypeName qualified as CodecsVocab.QualifiedTypeName
+import Hasql.CodecsVocab.TypeInfo qualified as CodecsVocab.TypeInfo
+import Hasql.ConnectionState.OidCache qualified as OidCache
+import Prelude
+import Test.Hspec
+
+int4Key :: CodecsVocab.QualifiedTypeName.QualifiedTypeName
+int4Key = CodecsVocab.QualifiedTypeName.QualifiedTypeName Nothing "int4"
+
+int8Key :: CodecsVocab.QualifiedTypeName.QualifiedTypeName
+int8Key = CodecsVocab.QualifiedTypeName.QualifiedTypeName Nothing "int8"
+
+spec :: Spec
+spec = do
+  describe "empty" do
+    it "returns Nothing on lookup" do
+      OidCache.lookupTypeInfo int4Key OidCache.empty
+        `shouldBe` Nothing
+
+  describe "fromHashMap and lookupTypeInfo" do
+    it "can look up an inserted type" do
+      let cache = OidCache.fromHashMap (HashMap.singleton int4Key (CodecsVocab.TypeInfo.TypeInfo 23 1007))
+      OidCache.lookupTypeInfo int4Key cache
+        `shouldBe` Just (CodecsVocab.TypeInfo.TypeInfo 23 1007)
+
+    it "returns Nothing for a non-inserted type" do
+      let cache = OidCache.fromHashMap (HashMap.singleton int4Key (CodecsVocab.TypeInfo.TypeInfo 23 1007))
+      OidCache.lookupTypeInfo int8Key cache
+        `shouldBe` Nothing
+
+    it "handles schema-qualified names" do
+      let key = CodecsVocab.QualifiedTypeName.QualifiedTypeName (Just "public") "my_type"
+          cache = OidCache.fromHashMap (HashMap.singleton key (CodecsVocab.TypeInfo.TypeInfo 100 200))
+      OidCache.lookupTypeInfo key cache
+        `shouldBe` Just (CodecsVocab.TypeInfo.TypeInfo 100 200)
+      OidCache.lookupTypeInfo (CodecsVocab.QualifiedTypeName.QualifiedTypeName Nothing "my_type") cache
+        `shouldBe` Nothing
+
+    it "distinguishes same type name in different schemas" do
+      let keyA = CodecsVocab.QualifiedTypeName.QualifiedTypeName (Just "schema_a") "my_type"
+          keyB = CodecsVocab.QualifiedTypeName.QualifiedTypeName (Just "schema_b") "my_type"
+          cache = OidCache.fromHashMap (HashMap.fromList [(keyA, CodecsVocab.TypeInfo.TypeInfo 100 200), (keyB, CodecsVocab.TypeInfo.TypeInfo 300 400)])
+      OidCache.lookupTypeInfo keyA cache
+        `shouldBe` Just (CodecsVocab.TypeInfo.TypeInfo 100 200)
+      OidCache.lookupTypeInfo keyB cache
+        `shouldBe` Just (CodecsVocab.TypeInfo.TypeInfo 300 400)
+
+  describe "selectUnknownNames" do
+    it "returns all names when cache is empty" do
+      let names = HashSet.fromList [int4Key, int8Key]
+      OidCache.selectUnknownNames names OidCache.empty
+        `shouldBe` names
+
+    it "returns empty when all names are known" do
+      let cache = OidCache.fromHashMap (HashMap.fromList [(int4Key, CodecsVocab.TypeInfo.TypeInfo 23 1007), (int8Key, CodecsVocab.TypeInfo.TypeInfo 20 1016)])
+          names = HashSet.fromList [int4Key, int8Key]
+      OidCache.selectUnknownNames names cache
+        `shouldBe` HashSet.empty
+
+    it "returns only unknown names" do
+      let cache = OidCache.fromHashMap (HashMap.singleton int4Key (CodecsVocab.TypeInfo.TypeInfo 23 1007))
+          names = HashSet.fromList [int4Key, int8Key]
+      OidCache.selectUnknownNames names cache
+        `shouldBe` HashSet.fromList [int8Key]
+
+  describe "toResolver" do
+    it "resolves a known type" do
+      let cache = OidCache.fromHashMap (HashMap.singleton int4Key (CodecsVocab.TypeInfo.TypeInfo 23 1007))
+      OidCache.toResolver cache int4Key
+        `shouldBe` CodecsVocab.TypeInfo.TypeInfo 23 1007
+
+    it "falls back to invalid for an unknown type" do
+      OidCache.toResolver OidCache.empty int4Key
+        `shouldBe` CodecsVocab.TypeInfo.invalid
+
+  describe "Semigroup" do
+    it "right operand takes precedence for duplicate keys" do
+      let cacheA = OidCache.fromHashMap (HashMap.singleton int4Key (CodecsVocab.TypeInfo.TypeInfo 23 1007))
+          cacheB = OidCache.fromHashMap (HashMap.singleton int4Key (CodecsVocab.TypeInfo.TypeInfo 99 999))
+          merged = cacheA <> cacheB
+      OidCache.lookupTypeInfo int4Key merged
+        `shouldBe` Just (CodecsVocab.TypeInfo.TypeInfo 99 999)
+
+    it "preserves entries from both sides when no conflict" do
+      let cacheA = OidCache.fromHashMap (HashMap.singleton int4Key (CodecsVocab.TypeInfo.TypeInfo 23 1007))
+          cacheB = OidCache.fromHashMap (HashMap.singleton int8Key (CodecsVocab.TypeInfo.TypeInfo 20 1016))
+          merged = cacheA <> cacheB
+      OidCache.lookupTypeInfo int4Key merged
+        `shouldBe` Just (CodecsVocab.TypeInfo.TypeInfo 23 1007)
+      OidCache.lookupTypeInfo int8Key merged
+        `shouldBe` Just (CodecsVocab.TypeInfo.TypeInfo 20 1016)
+
+    it "is associative" do
+      let a = OidCache.fromHashMap (HashMap.singleton "t1" (CodecsVocab.TypeInfo.TypeInfo 1 2))
+          b = OidCache.fromHashMap (HashMap.fromList [("t1", CodecsVocab.TypeInfo.TypeInfo 3 4), ("t2", CodecsVocab.TypeInfo.TypeInfo 5 6)])
+          c = OidCache.fromHashMap (HashMap.fromList [("t2", CodecsVocab.TypeInfo.TypeInfo 7 8), ("t3", CodecsVocab.TypeInfo.TypeInfo 9 10)])
+      (a <> b) <> c
+        `shouldBe` a <> (b <> c)
+
+  describe "Monoid" do
+    it "mempty is identity for Semigroup" do
+      let cache = OidCache.fromHashMap (HashMap.singleton int4Key (CodecsVocab.TypeInfo.TypeInfo 23 1007))
+      cache <> mempty
+        `shouldBe` cache
+      mempty <> cache
+        `shouldBe` cache
+
+    it "empty equals mempty" do
+      OidCache.empty
+        `shouldBe` mempty
diff --git a/src/connection-state-tests/Hasql/ConnectionState/StatementCacheSpec.hs b/src/connection-state-tests/Hasql/ConnectionState/StatementCacheSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/connection-state-tests/Hasql/ConnectionState/StatementCacheSpec.hs
@@ -0,0 +1,143 @@
+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
+        `shouldBe` Nothing
+
+  describe "insert and lookup" do
+    it "can insert and retrieve a statement" do
+      let (remoteKey, cache) = StatementCache.insert "SELECT 1" [] StatementCache.empty
+      StatementCache.lookup "SELECT 1" [] cache
+        `shouldBe` Just remoteKey
+
+    it "generates unique remote keys for different SQL" do
+      let (key1, cache1) = StatementCache.insert "SELECT 1" [] StatementCache.empty
+          (key2, _cache2) = StatementCache.insert "SELECT 2" [] cache1
+      key1 `shouldNotBe` key2
+
+    it "generates unique remote keys for same SQL with different OIDs" do
+      let oid23 = 23
+          oid25 = 25
+          (key1, cache1) = StatementCache.insert "SELECT $1" [oid23] StatementCache.empty
+          (key2, _cache2) = StatementCache.insert "SELECT $1" [oid25] cache1
+      key1 `shouldNotBe` key2
+
+    it "distinguishes statements with same SQL but different OIDs" do
+      let oid23 = 23
+          oid25 = 25
+          (_key1, cache1) = StatementCache.insert "SELECT $1" [oid23] StatementCache.empty
+          (_key2, cache2) = StatementCache.insert "SELECT $1" [oid25] cache1
+      -- Both should be findable
+      StatementCache.lookup "SELECT $1" [oid23] cache2
+        `shouldSatisfy` isJust
+      StatementCache.lookup "SELECT $1" [oid25] cache2
+        `shouldSatisfy` isJust
+      -- And should have different remote keys
+      let rk1 = StatementCache.lookup "SELECT $1" [oid23] cache2
+          rk2 = StatementCache.lookup "SELECT $1" [oid25] cache2
+      rk1 `shouldNotBe` rk2
+
+    it "returns Nothing for a non-inserted SQL" do
+      let (_key, cache) = StatementCache.insert "SELECT 1" [] StatementCache.empty
+      StatementCache.lookup "SELECT 2" [] cache
+        `shouldBe` Nothing
+
+    it "returns Nothing for matching SQL but different OIDs" do
+      let oid23 = 23
+          oid25 = 25
+          (_key, cache) = StatementCache.insert "SELECT $1" [oid23] StatementCache.empty
+      StatementCache.lookup "SELECT $1" [oid25] cache
+        `shouldBe` Nothing
+
+    it "handles empty OID list" do
+      let (key, cache) = StatementCache.insert "SELECT 1" [] StatementCache.empty
+      StatementCache.lookup "SELECT 1" [] cache
+        `shouldBe` Just key
+
+    it "handles multiple OIDs" do
+      let oids = [23, 25, 1043]
+          (key, cache) = StatementCache.insert "SELECT $1, $2, $3" oids StatementCache.empty
+      StatementCache.lookup "SELECT $1, $2, $3" oids cache
+        `shouldBe` Just key
+
+    it "distinguishes different OID ordering" do
+      let oidsA = [23, 25]
+          oidsB = [25, 23]
+          (_keyA, cache1) = StatementCache.insert "SELECT $1, $2" oidsA StatementCache.empty
+          (_keyB, cache2) = StatementCache.insert "SELECT $1, $2" oidsB cache1
+      StatementCache.lookup "SELECT $1, $2" oidsA cache2
+        `shouldSatisfy` isJust
+      StatementCache.lookup "SELECT $1, $2" oidsB cache2
+        `shouldSatisfy` isJust
+      let rkA = StatementCache.lookup "SELECT $1, $2" oidsA cache2
+          rkB = StatementCache.lookup "SELECT $1, $2" oidsB cache2
+      rkA `shouldNotBe` rkB
+
+  describe "reset" do
+    it "clears all cached statements" do
+      let (_key, cache) = StatementCache.insert "SELECT 1" [] StatementCache.empty
+          resetCache = StatementCache.reset cache
+      StatementCache.lookup "SELECT 1" [] resetCache
+        `shouldBe` Nothing
+
+    it "results in a cache equal to empty" do
+      let (_key, cache) = StatementCache.insert "SELECT 1" [] StatementCache.empty
+      StatementCache.reset cache
+        `shouldBe` StatementCache.empty
diff --git a/src/connection-state-tests/Main.hs b/src/connection-state-tests/Main.hs
new file mode 100644
--- /dev/null
+++ b/src/connection-state-tests/Main.hs
@@ -0,0 +1,1 @@
+{-# OPTIONS_GHC -F -pgmF hspec-discover #-}
diff --git a/src/connection-state/Hasql/ConnectionState.hs b/src/connection-state/Hasql/ConnectionState.hs
new file mode 100644
--- /dev/null
+++ b/src/connection-state/Hasql/ConnectionState.hs
@@ -0,0 +1,93 @@
+-- |
+-- This module defines the internal state of a database connection.
+module Hasql.ConnectionState
+  ( ConnectionState (..),
+    toStatementCache,
+    fromConnection,
+    setPreparedStatements,
+    setStatementCache,
+    setConnection,
+    setOidCache,
+    mapStatementCache,
+    mapOidCache,
+    traverseStatementCache,
+  )
+where
+
+import Hasql.ConnectionState.OidCache qualified as OidCache
+import Hasql.ConnectionState.StatementCache qualified as StatementCache
+import Hasql.Platform.Prelude
+import Pqi qualified as Pq
+
+-- |
+-- The internal state of a database connection.
+data ConnectionState = ConnectionState
+  { -- | Whether prepared statements are enabled.
+    preparedStatements :: Bool,
+    -- | The statement cache for prepared statements.
+    statementCache :: StatementCache.StatementCache,
+    -- | The OID cache for type name to OID mapping.
+    oidCache :: OidCache.OidCache,
+    -- | The underlying database connection.
+    connection :: Pq.Connection
+  }
+
+toStatementCache :: ConnectionState -> StatementCache.StatementCache
+toStatementCache ConnectionState {..} = statementCache
+
+fromConnection :: Pq.Connection -> ConnectionState
+fromConnection connection =
+  ConnectionState
+    { preparedStatements = False,
+      statementCache = StatementCache.empty,
+      oidCache = OidCache.empty,
+      connection = connection
+    }
+
+setPreparedStatements :: Bool -> ConnectionState -> ConnectionState
+setPreparedStatements preparedStatements connectionState =
+  connectionState {preparedStatements = preparedStatements}
+
+setStatementCache :: StatementCache.StatementCache -> ConnectionState -> ConnectionState
+setStatementCache statementCache connectionState =
+  connectionState {statementCache = statementCache}
+
+setConnection :: Pq.Connection -> ConnectionState -> ConnectionState
+setConnection connection connectionState =
+  connectionState {connection = connection}
+
+setOidCache :: OidCache.OidCache -> ConnectionState -> ConnectionState
+setOidCache oidCache connectionState =
+  connectionState {oidCache}
+
+mapStatementCache ::
+  (StatementCache.StatementCache -> StatementCache.StatementCache) ->
+  (ConnectionState -> ConnectionState)
+mapStatementCache f ConnectionState {..} =
+  ConnectionState
+    { statementCache = f statementCache,
+      ..
+    }
+
+mapOidCache ::
+  (OidCache.OidCache -> OidCache.OidCache) ->
+  (ConnectionState -> ConnectionState)
+mapOidCache f ConnectionState {..} =
+  ConnectionState
+    { oidCache = f oidCache,
+      ..
+    }
+
+traverseStatementCache ::
+  (Functor f) =>
+  (StatementCache.StatementCache -> f StatementCache.StatementCache) ->
+  (ConnectionState -> f ConnectionState)
+traverseStatementCache f ConnectionState {..} =
+  fmap
+    ( \newStatementCache ->
+        ConnectionState
+          { statementCache = newStatementCache,
+            ..
+          }
+    )
+    (f statementCache)
diff --git a/src/connection-state/Hasql/ConnectionState/OidCache.hs b/src/connection-state/Hasql/ConnectionState/OidCache.hs
new file mode 100644
--- /dev/null
+++ b/src/connection-state/Hasql/ConnectionState/OidCache.hs
@@ -0,0 +1,63 @@
+module Hasql.ConnectionState.OidCache
+  ( OidCache,
+
+    -- * Accessors
+    lookupTypeInfo,
+    toResolver,
+
+    -- * Constructors
+    fromHashMap,
+    empty,
+    selectUnknownNames,
+  )
+where
+
+import Data.HashMap.Strict qualified as HashMap
+import Data.HashSet qualified as HashSet
+import Hasql.CodecsVocab qualified as CodecsVocab
+import Hasql.CodecsVocab.TypeInfo qualified as CodecsVocab.TypeInfo
+import Hasql.Platform.Prelude hiding (empty, insert, lookup, reset)
+
+-- | Pure registry state containing the hash map and counter
+newtype OidCache
+  = OidCache
+      -- | By name of the type.
+      --
+      -- > scalar name -> TypeInfo (scalar OID, array OID)
+      (HashMap CodecsVocab.QualifiedTypeName CodecsVocab.TypeInfo)
+  deriving stock (Show, Eq)
+
+instance Semigroup OidCache where
+  OidCache byNameL <> OidCache byNameR =
+    OidCache (HashMap.union byNameR byNameL)
+
+instance Monoid OidCache where
+  mempty = OidCache mempty
+
+{-# INLINEABLE empty #-}
+empty :: OidCache
+empty =
+  OidCache HashMap.empty
+
+-- | Having a set of required type names, select those that are not present in the cache.
+{-# INLINE selectUnknownNames #-}
+selectUnknownNames :: HashSet CodecsVocab.QualifiedTypeName -> OidCache -> HashSet CodecsVocab.QualifiedTypeName
+selectUnknownNames keys (OidCache byName) =
+  HashSet.filter (\key -> not (HashMap.member key byName)) keys
+
+{-# INLINE fromHashMap #-}
+fromHashMap :: HashMap CodecsVocab.QualifiedTypeName CodecsVocab.TypeInfo -> OidCache
+fromHashMap byName = OidCache byName
+
+-- * Accessors
+
+{-# INLINE lookupTypeInfo #-}
+lookupTypeInfo :: CodecsVocab.QualifiedTypeName -> OidCache -> Maybe CodecsVocab.TypeInfo
+lookupTypeInfo name (OidCache byName) =
+  HashMap.lookup name byName
+
+-- | Resolution function for a name against the cache, falling back to 'TypeInfo.invalid' on a miss.
+{-# INLINE toResolver #-}
+toResolver :: OidCache -> CodecsVocab.QualifiedTypeName -> CodecsVocab.TypeInfo
+toResolver oidCache name =
+  lookupTypeInfo name oidCache & fromMaybe CodecsVocab.TypeInfo.invalid
diff --git a/src/connection-state/Hasql/ConnectionState/StatementCache.hs b/src/connection-state/Hasql/ConnectionState/StatementCache.hs
new file mode 100644
--- /dev/null
+++ b/src/connection-state/Hasql/ConnectionState/StatementCache.hs
@@ -0,0 +1,65 @@
+module Hasql.ConnectionState.StatementCache
+  ( StatementCache,
+    empty,
+    lookup,
+    insert,
+    reset,
+  )
+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 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
+
+-- | Pure lookup operation
+{-# INLINEABLE lookup #-}
+lookup :: ByteString -> [Word32] -> StatementCache -> Maybe ByteString
+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) = (remoteKey, newState)
+  where
+    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
+
+-- |
+-- Local statement key.
+data LocalKey
+  = LocalKey ByteString [Word32]
+  deriving (Show, Eq)
+
+instance Hashable LocalKey where
+  {-# INLINE hashWithSalt #-}
+  hashWithSalt salt (LocalKey template oids) =
+    hashWithSalt (hashWithSalt salt template) oids
diff --git a/src/library-tests/Helpers/Adapters.hs b/src/library-tests/Helpers/Adapters.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Helpers/Adapters.hs
@@ -0,0 +1,29 @@
+module Helpers.Adapters
+  ( hook,
+  )
+where
+
+import Pqi qualified
+import Pqi.Ffi qualified
+import Pqi.Native qualified
+import Prelude
+import Test.Hspec
+
+adapters :: [Pqi.Adapter]
+adapters =
+  [ Pqi.Ffi.adapter,
+    Pqi.Native.adapter
+  ]
+
+-- | Run the given spec-building function once per available Pqi adapter,
+-- nesting each run under a @describe@ named after the adapter.
+byAdapter :: (Pqi.Adapter -> Spec) -> Spec
+byAdapter f =
+  for_ adapters \adapter ->
+    describe (toList (Pqi.name adapter)) do
+      f adapter
+
+hook :: SpecWith Pqi.Adapter -> Spec
+hook hookedSpec =
+  byAdapter \adapter ->
+    mapSubject (const adapter) hookedSpec
diff --git a/src/library-tests/Helpers/Dsls/Execution.hs b/src/library-tests/Helpers/Dsls/Execution.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Helpers/Dsls/Execution.hs
@@ -0,0 +1,40 @@
+module Helpers.Dsls.Execution
+  ( Session,
+    sessionByParams,
+    Pipeline,
+    pipelineByParams,
+    generateVarname,
+  )
+where
+
+import Hasql.Pipeline (Pipeline)
+import Hasql.Pipeline qualified as Pipeline
+import Hasql.Session (Session)
+import Hasql.Session qualified as Session
+import Helpers.Dsls.Statement qualified as StatementDsl
+import Prelude
+import System.Random.Stateful qualified as Random
+import TextBuilder qualified
+
+sessionByParams ::
+  (StatementDsl.StatementModule params result) =>
+  params -> Session result
+sessionByParams = Session.pipeline . pipelineByParams
+
+pipelineByParams ::
+  (StatementDsl.StatementModule params result) =>
+  params -> Pipeline result
+pipelineByParams params = Pipeline.statement params StatementDsl.statement
+
+generateVarname :: IO Text
+generateVarname = do
+  uniqueNum1 <- Random.uniformWord64 Random.globalStdGen
+  uniqueNum2 <- Random.uniformWord64 Random.globalStdGen
+  pure
+    $ TextBuilder.toText
+    $ mconcat
+    $ [ "testing.v",
+        TextBuilder.decimal uniqueNum1,
+        "v",
+        TextBuilder.decimal uniqueNum2
+      ]
diff --git a/src/library-tests/Helpers/Dsls/Statement.hs b/src/library-tests/Helpers/Dsls/Statement.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Helpers/Dsls/Statement.hs
@@ -0,0 +1,6 @@
+module Helpers.Dsls.Statement where
+
+import Hasql.Statement qualified as Statement
+
+class StatementModule params result | params -> result where
+  statement :: Statement.Statement params result
diff --git a/src/library-tests/Helpers/PostgresContainer.hs b/src/library-tests/Helpers/PostgresContainer.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Helpers/PostgresContainer.hs
@@ -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
diff --git a/src/library-tests/Helpers/Scripts.hs b/src/library-tests/Helpers/Scripts.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Helpers/Scripts.hs
@@ -0,0 +1,63 @@
+module Helpers.Scripts where
+
+import Hasql.Connection qualified as Connection
+import Hasql.Connection.Settings qualified as Settings
+import Pqi qualified
+import Prelude
+import System.Random.Stateful qualified as Random
+import TextBuilder qualified
+
+-- |
+-- Parameters provided by the scope.
+-- Adapter, host and port of a running isolated postgres server.
+type ScopeParams = (Pqi.Adapter, Text, Word16)
+
+onPreparableConnection :: ScopeParams -> (Connection.Connection -> IO a) -> IO a
+onPreparableConnection = onConnection False
+
+onUnpreparableConnection :: ScopeParams -> (Connection.Connection -> IO a) -> IO a
+onUnpreparableConnection = onConnection True
+
+onConnection :: Bool -> ScopeParams -> (Connection.Connection -> IO a) -> IO a
+onConnection unpreparable (adapter, host, port) =
+  bracket
+    ( do
+        let settings =
+              mconcat
+                [ Settings.hostAndPort host (fromIntegral port),
+                  Settings.user "postgres",
+                  Settings.password "postgres",
+                  Settings.dbname "postgres",
+                  Settings.noPreparedStatements unpreparable
+                ]
+        res <- Connection.acquire adapter settings
+        case res of
+          Left err -> fail ("Connection failed: " <> show err)
+          Right conn -> pure conn
+    )
+    Connection.release
+
+-- | Generate a unique name of the following pattern:
+--
+-- > <prefix><uniqueNum1><infix><uniqueNum2><suffix>
+generateName :: Text -> Text -> Text -> IO Text
+generateName prefix infix_ suffix = do
+  uniqueNum1 <- Random.uniformWord64 Random.globalStdGen
+  uniqueNum2 <- Random.uniformWord64 Random.globalStdGen
+  pure
+    $ TextBuilder.toText
+    $ mconcat
+    $ [ TextBuilder.text prefix,
+        TextBuilder.decimal uniqueNum1,
+        TextBuilder.text infix_,
+        TextBuilder.decimal uniqueNum2,
+        TextBuilder.text suffix
+      ]
+
+generateVarname :: IO Text
+generateVarname = do
+  generateName "testing.v" "v" ""
+
+generateSymname :: IO Text
+generateSymname =
+  generateName "test_" "_" ""
diff --git a/src/library-tests/Helpers/Statements.hs b/src/library-tests/Helpers/Statements.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Helpers/Statements.hs
@@ -0,0 +1,26 @@
+module Helpers.Statements
+  ( module Helpers.Statements.BrokenSyntax,
+    module Helpers.Statements.CountPreparedStatements,
+    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
+
+import Helpers.Statements.BrokenSyntax
+import Helpers.Statements.CountPreparedStatements
+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
diff --git a/src/library-tests/Helpers/Statements/BrokenSyntax.hs b/src/library-tests/Helpers/Statements/BrokenSyntax.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Helpers/Statements/BrokenSyntax.hs
@@ -0,0 +1,28 @@
+module Helpers.Statements.BrokenSyntax where
+
+import Data.Int
+import Hasql.Decoders qualified as Decoders
+import Hasql.Encoders qualified as Encoders
+import Hasql.Statement qualified as Statement
+import Helpers.Dsls.Statement
+import Prelude
+
+data BrokenSyntax = BrokenSyntax
+  { start :: Int64,
+    end :: Int64
+  }
+
+type BrokenSyntaxResult = [Int64]
+
+instance StatementModule BrokenSyntax BrokenSyntaxResult where
+  statement =
+    Statement.preparable
+      "S"
+      ( mconcat
+          [ start >$< Encoders.param (Encoders.nonNullable Encoders.int8),
+            end >$< Encoders.param (Encoders.nonNullable Encoders.int8)
+          ]
+      )
+      ( Decoders.rowList
+          (Decoders.column (Decoders.nonNullable Decoders.int8))
+      )
diff --git a/src/library-tests/Helpers/Statements/CountPreparedStatements.hs b/src/library-tests/Helpers/Statements/CountPreparedStatements.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Helpers/Statements/CountPreparedStatements.hs
@@ -0,0 +1,17 @@
+module Helpers.Statements.CountPreparedStatements where
+
+import Hasql.Decoders qualified as Decoders
+import Hasql.Statement qualified as Statement
+import Helpers.Dsls.Statement
+import Prelude
+
+data CountPreparedStatements = CountPreparedStatements
+
+type CountPreparedStatementsResult = Int32
+
+instance StatementModule CountPreparedStatements CountPreparedStatementsResult where
+  statement =
+    Statement.unpreparable
+      "select count(*)::int4 from pg_prepared_statements"
+      mempty
+      (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int4)))
diff --git a/src/library-tests/Helpers/Statements/CurrentSetting.hs b/src/library-tests/Helpers/Statements/CurrentSetting.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Helpers/Statements/CurrentSetting.hs
@@ -0,0 +1,31 @@
+module Helpers.Statements.CurrentSetting 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
+
+data CurrentSetting = CurrentSetting
+  { name :: Text,
+    missingOk :: Bool
+  }
+
+type CurrentSettingResult = Maybe Text
+
+instance StatementModule CurrentSetting CurrentSettingResult where
+  statement =
+    Statement.preparable sql encoder decoder
+    where
+      sql =
+        "SELECT current_setting($1, $2)"
+
+      encoder =
+        mconcat
+          [ name >$< Encoders.param (Encoders.nonNullable Encoders.text),
+            missingOk >$< Encoders.param (Encoders.nonNullable Encoders.bool)
+          ]
+
+      decoder =
+        Decoders.singleRow
+          (Decoders.column (Decoders.nullable Decoders.text))
diff --git a/src/library-tests/Helpers/Statements/GenerateSeries.hs b/src/library-tests/Helpers/Statements/GenerateSeries.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Helpers/Statements/GenerateSeries.hs
@@ -0,0 +1,26 @@
+module Helpers.Statements.GenerateSeries where
+
+import Data.Int
+import Hasql.Decoders qualified as Decoders
+import Hasql.Encoders qualified as Encoders
+import Hasql.Statement qualified as Statement
+import Helpers.Dsls.Statement
+import Prelude
+
+data GenerateSeries = GenerateSeries
+  { start :: Int64,
+    end :: Int64
+  }
+
+type GenerateSeriesResult = [Int64]
+
+instance StatementModule GenerateSeries GenerateSeriesResult where
+  statement =
+    Statement.preparable
+      "SELECT generate_series($1, $2)"
+      ( (contramap start (Encoders.param (Encoders.nonNullable Encoders.int8)))
+          <> (contramap end (Encoders.param (Encoders.nonNullable Encoders.int8)))
+      )
+      ( Decoders.rowList
+          (Decoders.column (Decoders.nonNullable Decoders.int8))
+      )
diff --git a/src/library-tests/Helpers/Statements/SelectOne.hs b/src/library-tests/Helpers/Statements/SelectOne.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Helpers/Statements/SelectOne.hs
@@ -0,0 +1,17 @@
+module Helpers.Statements.SelectOne where
+
+import Hasql.Decoders qualified as Decoders
+import Hasql.Statement qualified as Statement
+import Helpers.Dsls.Statement
+import Prelude
+
+data SelectOne = SelectOne
+
+type SelectOneResult = Int32
+
+instance StatementModule SelectOne SelectOneResult where
+  statement =
+    Statement.preparable
+      "select 1"
+      mempty
+      (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int4)))
diff --git a/src/library-tests/Helpers/Statements/SelectPreparedStatementNames.hs b/src/library-tests/Helpers/Statements/SelectPreparedStatementNames.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Helpers/Statements/SelectPreparedStatementNames.hs
@@ -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)))
diff --git a/src/library-tests/Helpers/Statements/SelectProvidedInt8.hs b/src/library-tests/Helpers/Statements/SelectProvidedInt8.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Helpers/Statements/SelectProvidedInt8.hs
@@ -0,0 +1,20 @@
+module Helpers.Statements.SelectProvidedInt8 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
+
+data SelectProvidedInt8 = SelectProvidedInt8
+  { value :: Int64
+  }
+
+type SelectProvidedInt8Result = Int64
+
+instance StatementModule SelectProvidedInt8 SelectProvidedInt8Result where
+  statement =
+    Statement.preparable
+      "select $1"
+      (value >$< Encoders.param (Encoders.nonNullable Encoders.int8))
+      (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int8)))
diff --git a/src/library-tests/Helpers/Statements/SetConfig.hs b/src/library-tests/Helpers/Statements/SetConfig.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Helpers/Statements/SetConfig.hs
@@ -0,0 +1,32 @@
+module Helpers.Statements.SetConfig 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 hiding (local)
+
+data SetConfig = SetConfig
+  { name :: Text,
+    value :: Text,
+    local :: Bool
+  }
+
+type SetConfigResult = ()
+
+instance StatementModule SetConfig SetConfigResult where
+  statement =
+    Statement.preparable sql encoder decoder
+    where
+      sql =
+        "SELECT set_config($1, $2, $3)"
+
+      encoder =
+        mconcat
+          [ name >$< Encoders.param (Encoders.nonNullable Encoders.text),
+            value >$< Encoders.param (Encoders.nonNullable Encoders.text),
+            local >$< Encoders.param (Encoders.nonNullable Encoders.bool)
+          ]
+
+      decoder =
+        Decoders.noResult
diff --git a/src/library-tests/Helpers/Statements/Sleep.hs b/src/library-tests/Helpers/Statements/Sleep.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Helpers/Statements/Sleep.hs
@@ -0,0 +1,20 @@
+module Helpers.Statements.Sleep 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 hiding (local)
+
+data Sleep = Sleep
+  { seconds :: Double
+  }
+
+type SleepResult = ()
+
+instance StatementModule Sleep SleepResult where
+  statement =
+    Statement.preparable
+      "select pg_sleep($1)"
+      (seconds >$< Encoders.param (Encoders.nonNullable Encoders.float8))
+      Decoders.noResult
diff --git a/src/library-tests/Helpers/Statements/TooManyParams.hs b/src/library-tests/Helpers/Statements/TooManyParams.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Helpers/Statements/TooManyParams.hs
@@ -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))
diff --git a/src/library-tests/Helpers/Statements/WrongDecoder.hs b/src/library-tests/Helpers/Statements/WrongDecoder.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Helpers/Statements/WrongDecoder.hs
@@ -0,0 +1,29 @@
+module Helpers.Statements.WrongDecoder where
+
+import Data.Int
+import Data.UUID qualified
+import Hasql.Decoders qualified as Decoders
+import Hasql.Encoders qualified as Encoders
+import Hasql.Statement qualified as Statement
+import Helpers.Dsls.Statement
+import Prelude
+
+data WrongDecoder = WrongDecoder
+  { start :: Int64,
+    end :: Int64
+  }
+
+type WrongDecoderResult = [Data.UUID.UUID]
+
+instance StatementModule WrongDecoder WrongDecoderResult where
+  statement =
+    Statement.preparable
+      "SELECT generate_series($1, $2)"
+      ( mconcat
+          [ start >$< Encoders.param (Encoders.nonNullable Encoders.int8),
+            end >$< Encoders.param (Encoders.nonNullable Encoders.int8)
+          ]
+      )
+      ( Decoders.rowList
+          (Decoders.column (Decoders.nonNullable Decoders.uuid))
+      )
diff --git a/src/library-tests/Integration/Isolated/Connection/AcquireSpec.hs b/src/library-tests/Integration/Isolated/Connection/AcquireSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Isolated/Connection/AcquireSpec.hs
@@ -0,0 +1,243 @@
+module Integration.Isolated.Connection.AcquireSpec (spec) where
+
+import Hasql.Connection qualified
+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
+import TestcontainersPostgresql qualified
+
+spec :: SpecWith Pqi.Adapter
+spec = do
+  describe "By result" do
+    describe "Left" do
+      describe "Networking" do
+        it "Fails on server missing" \adapter -> do
+          let settings =
+                Settings.hostAndPort "nopostgresql.net" 5432
+          result <- Connection.acquire adapter settings
+          case result of
+            Right conn -> do
+              Connection.release conn
+              expectationFailure "Expected connection to fail with ConnectionAcquireError, but it succeeded"
+            Left (Errors.ConnectionAcquireError _) ->
+              pure ()
+            Left err ->
+              expectationFailure ("Expected ConnectionAcquireError, but got: " <> show err)
+
+  describe "postgres:9" do
+    it "Succeeds" \adapter -> do
+      PostgresContainer.run
+        TestcontainersPostgresql.Config
+          { tagName = "postgres:9",
+            auth = TestcontainersPostgresql.CredentialsAuth "postgres" "postgres",
+            forwardLogs = False
+          }
+        \(host, port) -> do
+          let settings =
+                mconcat
+                  [ Settings.hostAndPort host port,
+                    Settings.user "postgres",
+                    Settings.password "postgres",
+                    Settings.dbname "postgres"
+                  ]
+          result <- Connection.acquire adapter settings
+          case result of
+            Right conn -> do
+              Connection.release conn
+            Left err -> do
+              expectationFailure ("Expected connection to succeed, but it failed with error: " <> show err)
+
+  describe "postgres:18" do
+    it "Succeeds" \adapter -> do
+      PostgresContainer.run
+        TestcontainersPostgresql.Config
+          { tagName = "postgres:18",
+            auth = TestcontainersPostgresql.CredentialsAuth "postgres" "postgres",
+            forwardLogs = False
+          }
+        \(host, port) -> do
+          let settings =
+                mconcat
+                  [ Settings.hostAndPort host port,
+                    Settings.user "postgres",
+                    Settings.password "postgres",
+                    Settings.dbname "postgres"
+                  ]
+          result <- Connection.acquire adapter settings
+          case result of
+            Right conn -> do
+              Connection.release conn
+            Left err -> do
+              expectationFailure ("Expected connection to succeed, but it failed with error: " <> show err)
+
+    it "Reports ConnectionPasswordRequiredAcquireError when no password is supplied" \adapter -> do
+      PostgresContainer.run
+        TestcontainersPostgresql.Config
+          { tagName = "postgres:18",
+            auth = TestcontainersPostgresql.CredentialsAuth "postgres" "postgres",
+            forwardLogs = False
+          }
+        \(host, port) -> do
+          let settings =
+                mconcat
+                  [ Settings.hostAndPort host port,
+                    Settings.user "postgres",
+                    Settings.password "",
+                    Settings.dbname "postgres1"
+                  ]
+          result <- Connection.acquire adapter settings
+          case result of
+            Right conn -> do
+              Connection.release conn
+              expectationFailure "Expected connection to fail with ConnectionPasswordRequiredAcquireError, but it succeeded"
+            Left (Errors.ConnectionPasswordRequiredAcquireError _) ->
+              pure ()
+            Left err ->
+              expectationFailure ("Expected ConnectionPasswordRequiredAcquireError, but got: " <> show err)
+
+    it "Reports ConnectionAcquireError on a wrong password" \adapter -> do
+      PostgresContainer.run
+        TestcontainersPostgresql.Config
+          { tagName = "postgres:18",
+            auth = TestcontainersPostgresql.CredentialsAuth "postgres" "postgres",
+            forwardLogs = False
+          }
+        \(host, port) -> do
+          let settings =
+                mconcat
+                  [ Settings.hostAndPort host port,
+                    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 ConnectionAcquireError, but it succeeded"
+            Left (Errors.ConnectionAcquireError _) ->
+              pure ()
+            Left err ->
+              expectationFailure ("Expected ConnectionAcquireError, but got: " <> show err)
+
+  describe "postgres:9" do
+    byDistro "postgres:9"
+
+  describe "postgres:18" do
+    byDistro "postgres:18"
+
+byDistro :: Text -> SpecWith Pqi.Adapter
+byDistro tagName = do
+  let itConnects :: Text -> Text -> SpecWith Pqi.Adapter
+      itConnects username password =
+        describe ("username: " <> toList username) do
+          describe ("password: " <> toList password) do
+            it "connects" \adapter -> do
+              PostgresContainer.run
+                TestcontainersPostgresql.Config
+                  { tagName,
+                    auth = TestcontainersPostgresql.CredentialsAuth username password,
+                    forwardLogs = False
+                  }
+                ( \(host, port) -> do
+                    result <-
+                      Hasql.Connection.acquire
+                        adapter
+                        ( mconcat
+                            [ Settings.hostAndPort host port,
+                              Settings.user username,
+                              Settings.password password
+                            ]
+                        )
+                    case result of
+                      Left err -> expectationFailure ("Connection failed: " <> show err <> ". Host: " <> show host <> ", port: " <> show port)
+                      Right connection -> do
+                        Hasql.Connection.release connection
+                        pure ()
+                )
+   in do
+        itConnects "user" "new password"
+        itConnects "user" "new\\password"
+        itConnects "user" "new'password"
+        itConnects "new user" "password"
+
+  describe "Connection errors" do
+    describe "ConnectionAcquireError" do
+      it "is reported for invalid host" \adapter -> do
+        result <-
+          Hasql.Connection.acquire
+            adapter
+            ( mconcat
+                [ Settings.hostAndPort "nonexistent.invalid.host" 5432,
+                  Settings.user "postgres",
+                  Settings.password ""
+                ]
+            )
+        case result of
+          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
+        result <-
+          Hasql.Connection.acquire
+            adapter
+            ( mconcat
+                [ Settings.hostAndPort "127.0.0.1" 1,
+                  Settings.user "postgres",
+                  Settings.password ""
+                ]
+            )
+        case result of
+          Left (Errors.ConnectionAcquireError _) -> pure ()
+          Left err -> expectationFailure ("Expected ConnectionAcquireError, got: " <> show err)
+          Right _conn -> expectationFailure "Expected connection to fail"
+
+      it "is reported for a wrong password" \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 "incorrectpassword"
+                    ]
+                )
+            case result of
+              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"
diff --git a/src/library-tests/Integration/Sharing/Connection/Use/InterruptionSpec.hs b/src/library-tests/Integration/Sharing/Connection/Use/InterruptionSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/Connection/Use/InterruptionSpec.hs
@@ -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
diff --git a/src/library-tests/Integration/Sharing/Connection/UseSpec.hs b/src/library-tests/Integration/Sharing/Connection/UseSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/Connection/UseSpec.hs
@@ -0,0 +1,171 @@
+module Integration.Sharing.Connection.UseSpec (spec) where
+
+import Control.Concurrent
+import Control.Exception
+import Data.Either
+import Data.IORef
+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.SelectProvidedInt8 qualified as Statements.SelectProvidedInt8
+import Prelude
+import Test.Hspec
+
+spec :: SpecWith Scripts.ScopeParams
+spec = do
+  describe "Transactions" do
+    it "Do not cause \"in progress after error\"" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        let sumStatement =
+              Statement.preparable
+                "select ($1 + $2)"
+                ( mconcat
+                    [ fst >$< Encoders.param (Encoders.nonNullable Encoders.int8),
+                      snd >$< Encoders.param (Encoders.nonNullable Encoders.int8)
+                    ]
+                )
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int8)))
+
+        result <-
+          Connection.use connection do
+            Session.script "."
+
+        result `shouldSatisfy` isLeft
+
+        result <-
+          Connection.use connection do
+            Session.script "begin;"
+            s <- Session.statement (1 :: Int64, 2 :: Int64) sumStatement
+            Session.script "end;"
+            return s
+
+        result `shouldBe` Right (3 :: Int64)
+
+  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
+        _ <- Connection.use connection (Session.script "select 1")
+        Connection.release connection
+        Connection.release connection
+
+    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
+
+        result <- Connection.use connection (Session.script "select 1")
+        case result of
+          Left (Errors.ConnectionUseError _) -> pure ()
+          _ -> expectationFailure ("Unexpected result: " <> show result)
+
+        -- Releasing an already-spent connection remains a no-op.
+        Connection.release connection
+
+  describe "Concurrency" do
+    it "handles concurrent connections properly" \config -> do
+      Scripts.onPreparableConnection config \connection1 -> do
+        Scripts.onPreparableConnection config \connection2 -> do
+          let selectSleep =
+                Statement.preparable
+                  "select pg_sleep($1)"
+                  (Encoders.param (Encoders.nonNullable Encoders.float8))
+                  Decoders.noResult
+
+          beginVar <- newEmptyMVar
+          finishVar <- newEmptyMVar
+
+          _ <- forkIO do
+            putMVar beginVar ()
+            _ <- Connection.use connection1 (Session.statement (0.2 :: Double) selectSleep)
+            void (tryPutMVar finishVar False)
+
+          _ <- forkIO do
+            takeMVar beginVar
+            _ <- Connection.use connection2 (Session.statement (0.1 :: Double) selectSleep)
+            void (tryPutMVar finishVar True)
+
+          -- The second connection should finish first (True)
+          result <- takeMVar finishVar
+          result `shouldBe` True
+
+    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.
+
+      -- Results collected by the thread using the connection alongside the
+      -- one that interrupts it.
+      resultsRef <- newIORef []
+
+      startBarrier <- newEmptyMVar
+      doneBarrier <- newEmptyMVar
+
+      -- 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
+          _ <- try @SomeException do
+            Connection.use connection do
+              Session.script "BEGIN"
+              liftIO (throwIO (userError "Intentional exception"))
+          threadDelay 1000
+        putMVar doneBarrier ()
+
+      -- Thread B: keeps using the connection throughout.
+      _ <- forkIO do
+        takeMVar startBarrier
+        replicateM_ 20 do
+          result <- Connection.use connection (Execution.sessionByParams (Statements.SelectProvidedInt8.SelectProvidedInt8 42))
+          atomicModifyIORef' resultsRef (\results -> (result : results, ()))
+          threadDelay 500
+        putMVar doneBarrier ()
+
+      putMVar startBarrier ()
+      putMVar startBarrier ()
+
+      completion <- timeout (5 * 1000000) do
+        takeMVar doneBarrier
+        takeMVar doneBarrier
+
+      case completion of
+        Nothing ->
+          expectationFailure "Timed out waiting for the threads to complete, which means the connection deadlocked."
+        Just () -> do
+          results <- readIORef resultsRef
+          let unexpected =
+                filter
+                  ( \case
+                      Right 42 -> False
+                      Left (Errors.ConnectionUseError _) -> False
+                      _ -> True
+                  )
+                  results
+          unexpected `shouldBe` []
+
+          -- Once gone, gone: the handle does not come back to life.
+          finalResult <- Connection.use connection (Execution.sessionByParams (Statements.SelectProvidedInt8.SelectProvidedInt8 99))
+          case finalResult of
+            Left (Errors.ConnectionUseError _) -> pure ()
+            _ -> expectationFailure ("Unexpected final result: " <> show finalResult)
diff --git a/src/library-tests/Integration/Sharing/Decoders/CitextSpec.hs b/src/library-tests/Integration/Sharing/Decoders/CitextSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/Decoders/CitextSpec.hs
@@ -0,0 +1,85 @@
+module Integration.Sharing.Decoders.CitextSpec (spec) where
+
+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.Scripts qualified as Scripts
+import Prelude
+import Test.Hspec
+
+spec :: SpecWith Scripts.ScopeParams
+spec = do
+  describe "Citext Decoders" do
+    it "decodes a citext value" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          catchError
+            ( Session.statement ()
+                $ Statement.unpreparable
+                  "CREATE EXTENSION IF NOT EXISTS citext"
+                  Encoders.noParams
+                  Decoders.noResult
+            )
+            (const (pure ()))
+          Session.statement ()
+            $ Statement.preparable
+              "select 'Hello World'::citext"
+              mempty
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.citext)))
+        result `shouldBe` Right "Hello World"
+
+    it "decodes a citext value preserving case" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          catchError
+            ( Session.statement ()
+                $ Statement.unpreparable
+                  "CREATE EXTENSION IF NOT EXISTS citext"
+                  Encoders.noParams
+                  Decoders.noResult
+            )
+            (const (pure ()))
+          Session.statement ()
+            $ Statement.preparable
+              "select 'HeLLo WoRLd'::citext"
+              mempty
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.citext)))
+        result `shouldBe` Right "HeLLo WoRLd"
+
+    it "decodes a nullable citext value" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          catchError
+            ( Session.statement ()
+                $ Statement.unpreparable
+                  "CREATE EXTENSION IF NOT EXISTS citext"
+                  Encoders.noParams
+                  Decoders.noResult
+            )
+            (const (pure ()))
+          Session.statement ()
+            $ Statement.preparable
+              "select null::citext"
+              mempty
+              (Decoders.singleRow (Decoders.column (Decoders.nullable Decoders.citext)))
+        result `shouldBe` Right (Nothing :: Maybe Text)
+
+    it "decodes citext case-insensitive comparison in SQL" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          catchError
+            ( Session.statement ()
+                $ Statement.unpreparable
+                  "CREATE EXTENSION IF NOT EXISTS citext"
+                  Encoders.noParams
+                  Decoders.noResult
+            )
+            (const (pure ()))
+          Session.statement ()
+            $ Statement.preparable
+              "select 'hello'::citext = 'HELLO'::citext"
+              mempty
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.bool)))
+        result `shouldBe` Right True
diff --git a/src/library-tests/Integration/Sharing/Decoders/Composite/OidMismatchSpec.hs b/src/library-tests/Integration/Sharing/Decoders/Composite/OidMismatchSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/Decoders/Composite/OidMismatchSpec.hs
@@ -0,0 +1,165 @@
+module Integration.Sharing.Decoders.Composite.OidMismatchSpec (spec) where
+
+import Hasql.Connection qualified as Connection
+import Hasql.Decoders qualified as Decoders
+import Hasql.Errors qualified as Errors
+import Hasql.Session qualified as Session
+import Hasql.Statement qualified as Statement
+import Helpers.Scripts qualified as Scripts
+import Prelude
+import Test.Hspec
+
+spec :: SpecWith Scripts.ScopeParams
+spec = do
+  describe "Composite field OID mismatch detection" do
+    describe "Decoder field type mismatch" do
+      it "detects when decoder expects int4 but actual field is int8" \config -> do
+        typeName <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            -- Create composite type with int8 field
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create type ", typeName, " as (x int8)"])
+                mempty
+                Decoders.noResult
+            -- Try to decode with int4 decoder
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["select row(42) :: ", typeName])
+                mempty
+                ( Decoders.singleRow
+                    ( Decoders.column
+                        ( Decoders.nonNullable
+                            ( Decoders.composite
+                                Nothing
+                                typeName
+                                -- Using int4 decoder for int8 field - should fail
+                                (Decoders.field (Decoders.nonNullable Decoders.int4))
+                            )
+                        )
+                    )
+                )
+          -- The error should indicate a decoding failure due to type mismatch
+          case result of
+            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 ->
+              expectationFailure ("Unexpected type of error: " <> show err)
+            Right _ ->
+              expectationFailure "Expected an error but got success"
+
+      it "detects when decoder expects int8 but actual field is int4" \config -> do
+        typeName <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            -- Create composite type with int4 field
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create type ", typeName, " as (x int4)"])
+                mempty
+                Decoders.noResult
+            -- Try to decode with int8 decoder
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["select row(42) :: ", typeName])
+                mempty
+                ( Decoders.singleRow
+                    ( Decoders.column
+                        ( Decoders.nonNullable
+                            ( Decoders.composite
+                                Nothing
+                                typeName
+                                -- Using int8 decoder for int4 field - should fail
+                                (Decoders.field (Decoders.nonNullable Decoders.int8))
+                            )
+                        )
+                    )
+                )
+          -- The error should indicate a decoding failure due to type mismatch
+          case result of
+            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 ->
+              expectationFailure ("Unexpected type of error: " <> show err)
+            Right _ ->
+              expectationFailure "Expected an error but got success"
+
+      it "detects when decoder expects text but actual field is int8" \config -> do
+        typeName <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            -- Create composite type with int8 field
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create type ", typeName, " as (x int8)"])
+                mempty
+                Decoders.noResult
+            -- Try to decode with text decoder
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["select row(42) :: ", typeName])
+                mempty
+                ( Decoders.singleRow
+                    ( Decoders.column
+                        ( Decoders.nonNullable
+                            ( Decoders.composite
+                                Nothing
+                                typeName
+                                -- Using text decoder for int8 field - should fail
+                                (Decoders.field (Decoders.nonNullable Decoders.text))
+                            )
+                        )
+                    )
+                )
+          -- The error should indicate a decoding failure due to type mismatch
+          case result of
+            Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.RowStatementError _ (Errors.CellRowError _ _ (Errors.DeserializationCellError _msg))))) -> do
+              -- PostgreSQL binary decoder should detect the type mismatch
+              pure ()
+            Left err ->
+              expectationFailure ("Unexpected type of error: " <> show err)
+            Right _ ->
+              expectationFailure "Expected an error but got success"
+
+    describe "Multiple fields with mismatches" do
+      it "detects mismatch in second field" \config -> do
+        typeName <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            -- Create composite type with int8, int4 fields
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create type ", typeName, " as (a int8, b int4)"])
+                mempty
+                Decoders.noResult
+            -- Try to decode with correct first field but wrong second field
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["select row(1, 2) :: ", typeName])
+                mempty
+                ( Decoders.singleRow
+                    ( Decoders.column
+                        ( Decoders.nonNullable
+                            ( Decoders.composite
+                                Nothing
+                                typeName
+                                ( (,)
+                                    <$> Decoders.field (Decoders.nonNullable Decoders.int8)
+                                    -- Using int8 decoder for int4 field - should fail
+                                    <*> Decoders.field (Decoders.nonNullable Decoders.int8)
+                                )
+                            )
+                        )
+                    )
+                )
+          -- The error should indicate a decoding failure
+          case result of
+            Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.RowStatementError _ (Errors.CellRowError _ _ (Errors.DeserializationCellError _msg))))) -> do
+              pure ()
+            Left err ->
+              expectationFailure ("Unexpected type of error: " <> show err)
+            Right _ ->
+              expectationFailure "Expected an error but got success"
diff --git a/src/library-tests/Integration/Sharing/Decoders/CompositeSpec.hs b/src/library-tests/Integration/Sharing/Decoders/CompositeSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/Decoders/CompositeSpec.hs
@@ -0,0 +1,777 @@
+module Integration.Sharing.Decoders.CompositeSpec (spec) where
+
+import Data.HashSet qualified as HashSet
+import Hasql.Connection qualified as Connection
+import Hasql.Decoders qualified as Decoders
+import Hasql.Errors qualified as Errors
+import Hasql.Session qualified as Session
+import Hasql.Statement qualified as Statement
+import Helpers.Scripts qualified as Scripts
+import Prelude
+import Test.Hspec
+
+spec :: SpecWith Scripts.ScopeParams
+spec = do
+  describe "Named Composite Decoders" do
+    describe "Simple composites" do
+      it "decodes a simple named composite from static SQL" \config -> do
+        typeName <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            -- Create composite type
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create type ", typeName, " as (x int8, y bool)"])
+                mempty
+                Decoders.noResult
+            -- Test decoding from static value
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["select (42, true) :: ", typeName])
+                mempty
+                ( Decoders.singleRow
+                    ( Decoders.column
+                        ( Decoders.nonNullable
+                            ( Decoders.composite
+                                Nothing
+                                typeName
+                                ( (,)
+                                    <$> Decoders.field (Decoders.nonNullable Decoders.int8)
+                                    <*> Decoders.field (Decoders.nonNullable Decoders.bool)
+                                )
+                            )
+                        )
+                    )
+                )
+          result `shouldBe` Right (42 :: Int64, True)
+
+      it "decodes a simple named composite with different values" \config -> do
+        typeName <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            -- Create composite type
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create type ", typeName, " as (a text, b int4)"])
+                mempty
+                Decoders.noResult
+            -- Test decoding
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["select ('hello', 123) :: ", typeName])
+                mempty
+                ( Decoders.singleRow
+                    ( Decoders.column
+                        ( Decoders.nonNullable
+                            ( Decoders.composite
+                                Nothing
+                                typeName
+                                ( (,)
+                                    <$> Decoders.field (Decoders.nonNullable Decoders.text)
+                                    <*> Decoders.field (Decoders.nonNullable Decoders.int4)
+                                )
+                            )
+                        )
+                    )
+                )
+          result `shouldBe` Right ("hello", 123 :: Int32)
+
+    describe "Nested composites" do
+      it "decodes nested named composites from static SQL" \config -> do
+        innerType <- Scripts.generateSymname
+        outerType <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            -- Create inner composite type
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create type ", innerType, " as (x int8, y bool)"])
+                mempty
+                Decoders.noResult
+            -- Create outer composite type
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create type ", outerType, " as (\"inner\" ", innerType, ", z text)"])
+                mempty
+                Decoders.noResult
+            -- Test nested decoding
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["select ((42, true), 'world') :: ", outerType])
+                mempty
+                ( Decoders.singleRow
+                    ( Decoders.column
+                        ( Decoders.nonNullable
+                            ( Decoders.composite
+                                Nothing
+                                outerType
+                                ( (,)
+                                    <$> Decoders.field
+                                      ( Decoders.nonNullable
+                                          ( Decoders.composite
+                                              Nothing
+                                              innerType
+                                              ( (,)
+                                                  <$> Decoders.field (Decoders.nonNullable Decoders.int8)
+                                                  <*> Decoders.field (Decoders.nonNullable Decoders.bool)
+                                              )
+                                          )
+                                      )
+                                    <*> Decoders.field (Decoders.nonNullable Decoders.text)
+                                )
+                            )
+                        )
+                    )
+                )
+          result `shouldBe` Right ((42 :: Int64, True), "world")
+
+      it "decodes deeply nested named composites" \config -> do
+        type1 <- Scripts.generateSymname
+        type2 <- Scripts.generateSymname
+        type3 <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            -- Create level 1 composite
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create type ", type1, " as (val int8)"])
+                mempty
+                Decoders.noResult
+            -- Create level 2 composite
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create type ", type2, " as (\"inner\" ", type1, ", flag bool)"])
+                mempty
+                Decoders.noResult
+            -- Create level 3 composite
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create type ", type3, " as (\"nested\" ", type2, ", name text)"])
+                mempty
+                Decoders.noResult
+            -- Test deeply nested decoding
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["select row (row (row (99), true), 'deep') :: ", type3])
+                mempty
+                ( Decoders.singleRow
+                    ( Decoders.column
+                        ( Decoders.nonNullable
+                            ( Decoders.composite
+                                Nothing
+                                type3
+                                ( (,)
+                                    <$> Decoders.field
+                                      ( Decoders.nonNullable
+                                          ( Decoders.composite
+                                              Nothing
+                                              type2
+                                              ( (,)
+                                                  <$> Decoders.field
+                                                    ( Decoders.nonNullable
+                                                        ( Decoders.composite
+                                                            Nothing
+                                                            type1
+                                                            (Decoders.field (Decoders.nonNullable Decoders.int8))
+                                                        )
+                                                    )
+                                                  <*> Decoders.field (Decoders.nonNullable Decoders.bool)
+                                              )
+                                          )
+                                      )
+                                    <*> Decoders.field (Decoders.nonNullable Decoders.text)
+                                )
+                            )
+                        )
+                    )
+                )
+          result `shouldBe` Right ((99 :: Int64, True), "deep")
+
+    describe "Arrays of composites" do
+      it "decodes arrays of primitives" \config -> do
+        typeName <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create type ", typeName, " as (x int4[])"])
+                mempty
+                Decoders.noResult
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["select row(array[1,2,3])", " :: ", typeName])
+                mempty
+                ( Decoders.singleRow
+                    ( Decoders.column
+                        ( Decoders.nonNullable
+                            ( Decoders.composite
+                                Nothing
+                                typeName
+                                ( Decoders.field
+                                    ( Decoders.nonNullable
+                                        ( Decoders.array
+                                            ( Decoders.dimension
+                                                replicateM
+                                                ( Decoders.element
+                                                    (Decoders.nonNullable Decoders.int4)
+                                                )
+                                            )
+                                        )
+                                    )
+                                )
+                            )
+                        )
+                    )
+                )
+          result `shouldBe` Right [1, 2, 3]
+
+      it "decodes arrays of named composites from static SQL" \config -> do
+        typeName <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            -- Create composite type
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create type ", typeName, " as (x int8, y bool)"])
+                mempty
+                Decoders.noResult
+            -- Test array decoding
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["select array[(1, true), (2, false), (3, true)] :: ", typeName, "[]"])
+                mempty
+                ( Decoders.singleRow
+                    ( Decoders.column
+                        ( Decoders.nonNullable
+                            ( Decoders.array
+                                ( Decoders.dimension
+                                    replicateM
+                                    ( Decoders.element
+                                        ( Decoders.nonNullable
+                                            ( Decoders.composite
+                                                Nothing
+                                                typeName
+                                                ( (,)
+                                                    <$> Decoders.field (Decoders.nonNullable Decoders.int8)
+                                                    <*> Decoders.field (Decoders.nonNullable Decoders.bool)
+                                                )
+                                            )
+                                        )
+                                    )
+                                )
+                            )
+                        )
+                    )
+                )
+          result `shouldBe` Right [(1 :: Int64, True), (2, False), (3, True)]
+
+      it "decodes 2D arrays of named composites" \config -> do
+        typeName <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            -- Create composite type
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create type ", typeName, " as (val int4)"])
+                mempty
+                Decoders.noResult
+            -- Test 2D array decoding
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["select array[array[row (1), row (2)], array[row (3), row (4)]] :: ", typeName, "[][]"])
+                mempty
+                ( Decoders.singleRow
+                    ( Decoders.column
+                        ( Decoders.nonNullable
+                            ( Decoders.array
+                                ( Decoders.dimension
+                                    replicateM
+                                    ( Decoders.dimension
+                                        replicateM
+                                        ( Decoders.element
+                                            ( Decoders.nonNullable
+                                                ( Decoders.composite
+                                                    Nothing
+                                                    typeName
+                                                    (Decoders.field (Decoders.nonNullable Decoders.int4))
+                                                )
+                                            )
+                                        )
+                                    )
+                                )
+                            )
+                        )
+                    )
+                )
+          result `shouldBe` Right [[1 :: Int32, 2], [3, 4]]
+
+    describe "Composites with array fields" do
+      it "decodes a composite with an enum array field" \config -> do
+        enumType <- Scripts.generateSymname
+        compositeType <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            -- Create enum type
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create type ", enumType, " as enum ('red', 'green', 'blue')"])
+                mempty
+                Decoders.noResult
+            -- Create composite type with enum array field
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create type ", compositeType, " as (id int8, colors ", enumType, "[])"])
+                mempty
+                Decoders.noResult
+            -- Test decoding composite with enum array field
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["select (42, array['red', 'green', 'blue'] :: ", enumType, "[]) :: ", compositeType])
+                mempty
+                ( Decoders.singleRow
+                    ( Decoders.column
+                        ( Decoders.nonNullable
+                            ( Decoders.composite
+                                Nothing
+                                compositeType
+                                ( (,)
+                                    <$> Decoders.field (Decoders.nonNullable Decoders.int8)
+                                    <*> Decoders.field
+                                      ( Decoders.nonNullable
+                                          ( Decoders.array
+                                              ( Decoders.dimension
+                                                  replicateM
+                                                  ( Decoders.element
+                                                      ( Decoders.nonNullable
+                                                          ( Decoders.enum
+                                                              Nothing
+                                                              enumType
+                                                              Just
+                                                          )
+                                                      )
+                                                  )
+                                              )
+                                          )
+                                      )
+                                )
+                            )
+                        )
+                    )
+                )
+          result `shouldBe` Right (42 :: Int64, ["red", "green", "blue"])
+
+      it "decodes a composite with multiple enum array fields" \config -> do
+        enum1 <- Scripts.generateSymname
+        enum2 <- Scripts.generateSymname
+        compositeType <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            -- Create first enum type
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create type ", enum1, " as enum ('small', 'medium', 'large')"])
+                mempty
+                Decoders.noResult
+            -- Create second enum type
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create type ", enum2, " as enum ('low', 'high')"])
+                mempty
+                Decoders.noResult
+            -- Create composite type with multiple enum array fields
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create type ", compositeType, " as (sizes ", enum1, "[], priorities ", enum2, "[])"])
+                mempty
+                Decoders.noResult
+            -- Test decoding composite with multiple enum array fields
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["select (array['small', 'large'] :: ", enum1, "[], array['high', 'low'] :: ", enum2, "[]) :: ", compositeType])
+                mempty
+                ( Decoders.singleRow
+                    ( Decoders.column
+                        ( Decoders.nonNullable
+                            ( Decoders.composite
+                                Nothing
+                                compositeType
+                                ( (,)
+                                    <$> Decoders.field
+                                      ( Decoders.nonNullable
+                                          ( Decoders.array
+                                              ( Decoders.dimension
+                                                  replicateM
+                                                  ( Decoders.element
+                                                      ( Decoders.nonNullable
+                                                          ( Decoders.enum
+                                                              Nothing
+                                                              enum1
+                                                              Just
+                                                          )
+                                                      )
+                                                  )
+                                              )
+                                          )
+                                      )
+                                    <*> Decoders.field
+                                      ( Decoders.nonNullable
+                                          ( Decoders.array
+                                              ( Decoders.dimension
+                                                  replicateM
+                                                  ( Decoders.element
+                                                      ( Decoders.nonNullable
+                                                          ( Decoders.enum
+                                                              Nothing
+                                                              enum2
+                                                              Just
+                                                          )
+                                                      )
+                                                  )
+                                              )
+                                          )
+                                      )
+                                )
+                            )
+                        )
+                    )
+                )
+          result `shouldBe` Right (["small", "large"], ["high", "low"])
+
+      it "decodes a composite with mixed scalar and enum array fields" \config -> do
+        enumType <- Scripts.generateSymname
+        compositeType <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            -- Create enum type
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create type ", enumType, " as enum ('A', 'B', 'C')"])
+                mempty
+                Decoders.noResult
+            -- Create composite type with mixed fields
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create type ", compositeType, " as (name text, age int4, grades ", enumType, "[])"])
+                mempty
+                Decoders.noResult
+            -- Test decoding composite with mixed fields
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["select ('Alice', 25, array['A', 'B', 'A'] :: ", enumType, "[]) :: ", compositeType])
+                mempty
+                ( Decoders.singleRow
+                    ( Decoders.column
+                        ( Decoders.nonNullable
+                            ( Decoders.composite
+                                Nothing
+                                compositeType
+                                ( do
+                                    name <- Decoders.field (Decoders.nonNullable Decoders.text)
+                                    age <- Decoders.field (Decoders.nonNullable Decoders.int4)
+                                    grades <-
+                                      Decoders.field
+                                        ( Decoders.nonNullable
+                                            ( Decoders.array
+                                                ( Decoders.dimension
+                                                    replicateM
+                                                    ( Decoders.element
+                                                        ( Decoders.nonNullable
+                                                            ( Decoders.enum
+                                                                Nothing
+                                                                enumType
+                                                                ( \case
+                                                                    "A" -> Just 'A'
+                                                                    "B" -> Just 'B'
+                                                                    "C" -> Just 'C'
+                                                                    _ -> Nothing
+                                                                )
+                                                            )
+                                                        )
+                                                    )
+                                                )
+                                            )
+                                        )
+                                    pure (name, age, grades)
+                                )
+                            )
+                        )
+                    )
+                )
+          result `shouldBe` Right ("Alice", 25 :: Int32, ['A', 'B', 'A'])
+
+      it "decodes nested composite with enum array field" \config -> do
+        enumType <- Scripts.generateSymname
+        innerType <- Scripts.generateSymname
+        outerType <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            -- Create enum type
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create type ", enumType, " as enum ('x', 'y', 'z')"])
+                mempty
+                Decoders.noResult
+            -- Create inner composite type with enum array field
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create type ", innerType, " as (values ", enumType, "[])"])
+                mempty
+                Decoders.noResult
+            -- Create outer composite type containing the inner type
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create type ", outerType, " as (id int4, data ", innerType, ")"])
+                mempty
+                Decoders.noResult
+            -- Test nested decoding
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["select (100, row(array['x', 'y', 'z'] :: ", enumType, "[]) :: ", innerType, ") :: ", outerType])
+                mempty
+                ( Decoders.singleRow
+                    ( Decoders.column
+                        ( Decoders.nonNullable
+                            ( Decoders.composite
+                                Nothing
+                                outerType
+                                ( (,)
+                                    <$> Decoders.field (Decoders.nonNullable Decoders.int4)
+                                    <*> Decoders.field
+                                      ( Decoders.nonNullable
+                                          ( Decoders.composite
+                                              Nothing
+                                              innerType
+                                              ( Decoders.field
+                                                  ( Decoders.nonNullable
+                                                      ( Decoders.array
+                                                          ( Decoders.dimension
+                                                              replicateM
+                                                              ( Decoders.element
+                                                                  ( Decoders.nonNullable
+                                                                      ( Decoders.enum
+                                                                          Nothing
+                                                                          enumType
+                                                                          ( \case
+                                                                              "x" -> Just 'x'
+                                                                              "y" -> Just 'y'
+                                                                              "z" -> Just 'z'
+                                                                              _ -> Nothing
+                                                                          )
+                                                                      )
+                                                                  )
+                                                              )
+                                                          )
+                                                      )
+                                                  )
+                                              )
+                                          )
+                                      )
+                                )
+                            )
+                        )
+                    )
+                )
+          result `shouldBe` Right (100 :: Int32, ['x', 'y', 'z'])
+
+      it "decodes a composite with 2D enum array field" \config -> do
+        enumType <- Scripts.generateSymname
+        compositeType <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            -- Create enum type
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create type ", enumType, " as enum ('0', '1')"])
+                mempty
+                Decoders.noResult
+            -- Create composite type with 2D enum array field
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create type ", compositeType, " as (matrix ", enumType, "[][])"])
+                mempty
+                Decoders.noResult
+            -- Test decoding composite with 2D enum array field
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["select row(array[array['0', '1'], array['1', '0']] :: ", enumType, "[][]) :: ", compositeType])
+                mempty
+                ( Decoders.singleRow
+                    ( Decoders.column
+                        ( Decoders.nonNullable
+                            ( Decoders.composite
+                                Nothing
+                                compositeType
+                                ( Decoders.field
+                                    ( Decoders.nonNullable
+                                        ( Decoders.array
+                                            ( Decoders.dimension
+                                                replicateM
+                                                ( Decoders.dimension
+                                                    replicateM
+                                                    ( Decoders.element
+                                                        ( Decoders.nonNullable
+                                                            ( Decoders.enum
+                                                                Nothing
+                                                                enumType
+                                                                ( \case
+                                                                    "0" -> Just (0 :: Int)
+                                                                    "1" -> Just 1
+                                                                    _ -> Nothing
+                                                                )
+                                                            )
+                                                        )
+                                                    )
+                                                )
+                                            )
+                                        )
+                                    )
+                                )
+                            )
+                        )
+                    )
+                )
+          result `shouldBe` Right [[0, 1], [1, 0]]
+
+    describe "OID compatibility checking" do
+      it "fails when decoder expects a composite but gets a different type" \config -> do
+        typeName <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            -- Create composite type
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create type ", typeName, " as (x int8, y bool)"])
+                mempty
+                Decoders.noResult
+            -- Try to decode text as the composite type (should fail during deserialization)
+            Session.statement ()
+              $ Statement.preparable
+                "select 'some text'::text"
+                mempty
+                ( Decoders.singleRow
+                    ( Decoders.column
+                        ( Decoders.nonNullable
+                            ( Decoders.composite
+                                Nothing
+                                typeName
+                                ( (,)
+                                    <$> Decoders.field (Decoders.nonNullable Decoders.int8)
+                                    <*> Decoders.field (Decoders.nonNullable Decoders.bool)
+                                )
+                            )
+                        )
+                    )
+                )
+          -- Should fail with a cell error because text cannot be decoded as a composite
+          case result of
+            Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.UnexpectedColumnTypeStatementError 0 _ _))) ->
+              pure ()
+            Left err ->
+              expectationFailure ("Unexpected type of error: " <> show err)
+            Right _ ->
+              expectationFailure "Expected an error but got success"
+
+      it "fails when decoder expects one composite type but gets another" \config -> do
+        type1 <- Scripts.generateSymname
+        type2 <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            -- Create first composite type with two fields
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create type ", type1, " as (x int8, y text)"])
+                mempty
+                Decoders.noResult
+            -- Create second composite type with different structure
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create type ", type2, " as (a bool)"])
+                mempty
+                Decoders.noResult
+            -- Try to decode type2 value as type1 (should fail during deserialization)
+            -- type2 has 1 field, type1 decoder expects 2 fields
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["select row (true) :: ", type2])
+                mempty
+                ( Decoders.singleRow
+                    ( Decoders.column
+                        ( Decoders.nonNullable
+                            ( Decoders.composite
+                                Nothing
+                                type1
+                                ( (,)
+                                    <$> Decoders.field (Decoders.nonNullable Decoders.int8)
+                                    <*> Decoders.field (Decoders.nonNullable Decoders.text)
+                                )
+                            )
+                        )
+                    )
+                )
+          -- Should fail with a cell error because the field count doesn't match
+          case result of
+            Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.UnexpectedColumnTypeStatementError 0 _ _))) ->
+              pure ()
+            Left err ->
+              expectationFailure ("Unexpected type of error: " <> show err)
+            Right _ ->
+              expectationFailure "Expected an error but got success"
+
+      it "correctly validates matching composite type OIDs" \config -> do
+        typeName <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            -- Create composite type
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create type ", typeName, " as (x int8, y bool)"])
+                mempty
+                Decoders.noResult
+            -- Decode with correct type - should succeed
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["select row (42, true) :: ", typeName])
+                mempty
+                ( Decoders.singleRow
+                    ( Decoders.column
+                        ( Decoders.nonNullable
+                            ( Decoders.composite
+                                Nothing
+                                typeName
+                                ( (,)
+                                    <$> Decoders.field (Decoders.nonNullable Decoders.int8)
+                                    <*> Decoders.field (Decoders.nonNullable Decoders.bool)
+                                )
+                            )
+                        )
+                    )
+                )
+          result `shouldBe` Right (42 :: Int64, True)
+
+  it "detects attempts to decode non-existent composite types" \config -> do
+    Scripts.onPreparableConnection config \connection -> do
+      result <- Connection.use connection do
+        Session.statement ()
+          $ Statement.preparable
+            "select row(42, text 'test')"
+            mempty
+            ( Decoders.singleRow
+                ( Decoders.column
+                    ( Decoders.nonNullable
+                        ( Decoders.composite
+                            Nothing
+                            "nonexistent_composite_type"
+                            ( (,)
+                                <$> Decoders.field (Decoders.nonNullable Decoders.int4)
+                                <*> Decoders.field (Decoders.nonNullable Decoders.text)
+                            )
+                        )
+                    )
+                )
+            )
+
+      case result of
+        Left (Errors.SessionUseError (Errors.MissingTypesSessionError missingTypes)) ->
+          missingTypes `shouldBe` HashSet.fromList [(Nothing, "nonexistent_composite_type")]
+        _ ->
+          expectationFailure ("Unexpected result: " <> show result)
diff --git a/src/library-tests/Integration/Sharing/Decoders/CustomSpec.hs b/src/library-tests/Integration/Sharing/Decoders/CustomSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/Decoders/CustomSpec.hs
@@ -0,0 +1,286 @@
+module Integration.Sharing.Decoders.CustomSpec (spec) where
+
+import Data.ByteString qualified as ByteString
+import Data.HashSet qualified as HashSet
+import Data.Text.Encoding (encodeUtf8)
+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.Scripts qualified as Scripts
+import Prelude
+import Test.Hspec
+
+spec :: SpecWith Scripts.ScopeParams
+spec = do
+  describe "Basic custom decoders" do
+    it "decodes a custom type with runtime OID lookup" \config -> do
+      enumName <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create enum type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", enumName, " as enum ('alpha', 'beta', 'gamma')"])
+              mempty
+              Decoders.noResult
+          -- Test custom decoder with runtime OID lookup
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["select 'beta' :: ", enumName])
+              mempty
+              ( Decoders.singleRow
+                  ( Decoders.column
+                      ( Decoders.nonNullable
+                          ( Decoders.custom
+                              Nothing
+                              enumName
+                              Nothing
+                              []
+                              (\_ bytes -> Right (ByteString.length bytes, bytes))
+                          )
+                      )
+                  )
+              )
+        -- Should successfully decode with length and bytes
+        case result of
+          Right (len, bytes) -> do
+            len `shouldBe` 4
+            bytes `shouldBe` "beta"
+          Left err ->
+            expectationFailure ("Unexpected error: " <> show err)
+
+    it "decodes a custom type with static OIDs" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Test custom decoder with static OIDs for int4 (type OID 23, array OID 1007)
+          Session.statement ()
+            $ Statement.preparable
+              "select 42::int4"
+              mempty
+              ( Decoders.singleRow
+                  ( Decoders.column
+                      ( Decoders.nonNullable
+                          ( Decoders.custom
+                              Nothing
+                              "int4"
+                              (Just (23, 1007))
+                              []
+                              (\_ bytes -> Right (ByteString.length bytes))
+                          )
+                      )
+                  )
+              )
+        -- int4 is encoded in 4 bytes
+        result `shouldBe` Right 4
+
+    it "decodes with dependent type OID requests" \config -> do
+      enumName <- Scripts.generateSymname
+      compositeName <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create enum type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", enumName, " as enum ('small', 'large')"])
+              mempty
+              Decoders.noResult
+          -- Create composite type with the enum
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", compositeName, " as (size ", enumName, ", count int4)"])
+              mempty
+              Decoders.noResult
+          -- Test custom decoder requesting OIDs of dependent types
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["select ('large', 5) :: ", compositeName])
+              mempty
+              ( Decoders.singleRow
+                  ( Decoders.column
+                      ( Decoders.nonNullable
+                          ( Decoders.custom
+                              Nothing
+                              compositeName
+                              Nothing
+                              [(Nothing, enumName), (Nothing, "int4")]
+                              ( \lookupOid bytes -> do
+                                  let (enumOidScalar, _enumOidArray) = lookupOid (Nothing, enumName)
+                                      (int4OidScalar, _int4OidArray) = lookupOid (Nothing, "int4")
+                                  -- Verify we got valid OIDs
+                                  if enumOidScalar > 0 && int4OidScalar > 0
+                                    then Right (enumOidScalar, int4OidScalar, ByteString.length bytes)
+                                    else Left "Failed to resolve OIDs"
+                              )
+                          )
+                      )
+                  )
+              )
+        -- Should successfully get OIDs and byte length
+        case result of
+          Right (enumOid, int4Oid, len) -> do
+            enumOid `shouldSatisfy` (> 0)
+            int4Oid `shouldBe` 23
+            len `shouldSatisfy` (> 0)
+          Left err ->
+            expectationFailure ("Unexpected error: " <> show err)
+
+  describe "Error handling" do
+    it "detects missing types in custom decoders" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          Session.statement ()
+            $ Statement.preparable
+              "select 'test'::text"
+              mempty
+              ( Decoders.singleRow
+                  ( Decoders.column
+                      ( Decoders.nonNullable
+                          ( Decoders.custom
+                              Nothing
+                              "nonexistent_custom_type"
+                              Nothing
+                              []
+                              (\_ bytes -> Right bytes)
+                          )
+                      )
+                  )
+              )
+
+        case result of
+          Left (Errors.SessionUseError (Errors.MissingTypesSessionError missingTypes)) ->
+            missingTypes `shouldBe` HashSet.fromList [(Nothing, "nonexistent_custom_type")]
+          _ ->
+            expectationFailure ("Unexpected result: " <> show result)
+
+    it "detects missing dependent types in custom decoders" \config -> do
+      customTypeName <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create a custom type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", customTypeName, " as (id int4)"])
+              mempty
+              Decoders.noResult
+          -- Try to decode it but request a non-existent dependent type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["select (42) :: ", customTypeName])
+              mempty
+              ( Decoders.singleRow
+                  ( Decoders.column
+                      ( Decoders.nonNullable
+                          ( Decoders.custom
+                              Nothing
+                              customTypeName
+                              Nothing
+                              [(Nothing, "nonexistent_dependency")]
+                              (\_ bytes -> Right bytes)
+                          )
+                      )
+                  )
+              )
+
+        case result of
+          Left (Errors.SessionUseError (Errors.MissingTypesSessionError missingTypes)) ->
+            missingTypes `shouldBe` HashSet.fromList [(Nothing, "nonexistent_dependency")]
+          _ ->
+            expectationFailure ("Unexpected result: " <> show result)
+
+    it "handles decoding errors in custom decoders" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          Session.statement ()
+            $ Statement.preparable
+              "select 42::int4"
+              mempty
+              ( Decoders.singleRow
+                  ( Decoders.column
+                      ( Decoders.nonNullable
+                          ( Decoders.custom
+                              Nothing
+                              "int4"
+                              (Just (23, 1007))
+                              []
+                              (\_ _ -> Left "Custom decoding error")
+                          )
+                      )
+                  )
+              )
+
+        case result of
+          Left (Errors.SessionUseError (Errors.StatementSessionError {})) -> pure ()
+          _ ->
+            expectationFailure "Expected statement error"
+
+  describe "Roundtrip tests" do
+    it "roundtrips custom encoded and decoded values" \config -> do
+      enumName <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create enum type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", enumName, " as enum ('one', 'two', 'three')"])
+              mempty
+              Decoders.noResult
+          -- Test roundtrip using custom encoder and decoder
+          Session.statement "two"
+            $ Statement.preparable
+              (mconcat ["select $1 :: ", enumName])
+              (Encoders.param (Encoders.nonNullable (Encoders.custom Nothing enumName Nothing [] (\_ val -> encodeUtf8 val) id)))
+              ( Decoders.singleRow
+                  ( Decoders.column
+                      ( Decoders.nonNullable
+                          ( Decoders.custom
+                              Nothing
+                              enumName
+                              Nothing
+                              []
+                              (\_ bytes -> Right bytes)
+                          )
+                      )
+                  )
+              )
+        result `shouldBe` Right "two"
+
+  describe "Schema-qualified types" do
+    it "decodes custom types from specific schemas" \config -> do
+      schemaName <- Scripts.generateSymname
+      typeName <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create schema
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create schema ", schemaName])
+              mempty
+              Decoders.noResult
+          -- Create enum type in that schema
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", schemaName, ".", typeName, " as enum ('x', 'y')"])
+              mempty
+              Decoders.noResult
+          -- Test custom decoder with schema qualification
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["select 'y' :: ", schemaName, ".", typeName])
+              mempty
+              ( Decoders.singleRow
+                  ( Decoders.column
+                      ( Decoders.nonNullable
+                          ( Decoders.custom
+                              (Just schemaName)
+                              typeName
+                              Nothing
+                              []
+                              (\_ bytes -> Right bytes)
+                          )
+                      )
+                  )
+              )
+        result `shouldBe` Right "y"
diff --git a/src/library-tests/Integration/Sharing/Decoders/DomainSpec.hs b/src/library-tests/Integration/Sharing/Decoders/DomainSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/Decoders/DomainSpec.hs
@@ -0,0 +1,194 @@
+module Integration.Sharing.Decoders.DomainSpec (spec) where
+
+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.Scripts qualified as Scripts
+import Prelude
+import Test.Hspec
+
+spec :: SpecWith Scripts.ScopeParams
+spec = do
+  describe "Domain type decoding" do
+    describe "Simple scalar domains" do
+      it "decodes a domain based on int8 using int8 codec" \config -> do
+        domainName <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            -- Create domain type
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create domain ", domainName, " as int8"])
+                mempty
+                Decoders.noResult
+            -- Test decoding from static value
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["select 42 :: ", domainName])
+                mempty
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int8)))
+          result `shouldBe` Right (42 :: Int64)
+
+      it "decodes a domain based on text using text codec" \config -> do
+        domainName <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            -- Create domain type
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create domain ", domainName, " as text"])
+                mempty
+                Decoders.noResult
+            -- Test decoding from static value
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["select 'hello' :: ", domainName])
+                mempty
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.text)))
+          result `shouldBe` Right "hello"
+
+      it "decodes a domain based on bool using bool codec" \config -> do
+        domainName <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            -- Create domain type
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create domain ", domainName, " as bool"])
+                mempty
+                Decoders.noResult
+            -- Test decoding from static value
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["select true :: ", domainName])
+                mempty
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.bool)))
+          result `shouldBe` Right True
+
+      it "roundtrips a domain based on numeric" \config -> do
+        domainName <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            -- Create domain type
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create domain ", domainName, " as numeric"])
+                mempty
+                Decoders.noResult
+            -- Test roundtrip
+            Session.statement (123.456 :: Scientific)
+              $ Statement.preparable
+                (mconcat ["select $1 :: ", domainName])
+                (Encoders.param (Encoders.nonNullable Encoders.numeric))
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.numeric)))
+          result `shouldBe` Right (123.456 :: Scientific)
+
+    describe "Domain with constraints" do
+      it "decodes domain values that satisfy constraints" \config -> do
+        domainName <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            -- Create domain type with constraint
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create domain ", domainName, " as int8 check (value > 0)"])
+                mempty
+                Decoders.noResult
+            -- Decode value that satisfies constraint
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["select 42 :: ", domainName])
+                mempty
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int8)))
+          result `shouldBe` Right (42 :: Int64)
+
+    describe "Domain type cast compatibility for composite usage" do
+      it "decodes domain value cast to base type from composite field" \config -> do
+        domainName <- Scripts.generateSymname
+        compositeName <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            -- Create domain type
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create domain ", domainName, " as int8"])
+                mempty
+                Decoders.noResult
+            -- Create composite type with domain field
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create type ", compositeName, " as (x ", domainName, ", y bool)"])
+                mempty
+                Decoders.noResult
+            -- Extract and cast domain field to base type for decoding
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["select ((42 :: ", domainName, ") :: int8)"])
+                mempty
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int8)))
+          result `shouldBe` Right (42 :: Int64)
+
+    describe "Domain type cast compatibility for array usage" do
+      it "decodes array cast from domain array to base type array" \config -> do
+        domainName <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            -- Create domain type
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create domain ", domainName, " as int8"])
+                mempty
+                Decoders.noResult
+            -- Decode base type array
+            Session.statement ()
+              $ Statement.preparable
+                "select ARRAY[1,2,3] :: int8[]"
+                mempty
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable (Decoders.listArray (Decoders.nonNullable Decoders.int8)))))
+          result `shouldBe` Right ([1, 2, 3] :: [Int64])
+
+      it "roundtrips array using base type codec" \config -> do
+        domainName <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            -- Create domain type
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create domain ", domainName, " as text"])
+                mempty
+                Decoders.noResult
+            -- Test roundtrip using base type codec
+            Session.statement (["a", "b", "c"] :: [Text])
+              $ Statement.preparable
+                "select $1 :: text[]"
+                ( Encoders.param
+                    ( Encoders.nonNullable
+                        (Encoders.foldableArray (Encoders.nonNullable Encoders.text))
+                    )
+                )
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable (Decoders.listArray (Decoders.nonNullable Decoders.text)))))
+          result `shouldBe` Right (["a", "b", "c"] :: [Text])
+
+      it "decodes base type array that can work with domain arrays via cast" \config -> do
+        domainName <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            -- Create domain type
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create domain ", domainName, " as int8"])
+                mempty
+                Decoders.noResult
+            -- Demonstrate that base codec works for arrays
+            Session.statement ([10, 20, 30] :: [Int64])
+              $ Statement.preparable
+                "select $1 :: int8[]"
+                ( Encoders.param
+                    ( Encoders.nonNullable
+                        (Encoders.foldableArray (Encoders.nonNullable Encoders.int8))
+                    )
+                )
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable (Decoders.listArray (Decoders.nonNullable Decoders.int8)))))
+          result `shouldBe` Right ([10, 20, 30] :: [Int64])
diff --git a/src/library-tests/Integration/Sharing/Decoders/EnumSpec.hs b/src/library-tests/Integration/Sharing/Decoders/EnumSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/Decoders/EnumSpec.hs
@@ -0,0 +1,302 @@
+module Integration.Sharing.Decoders.EnumSpec (spec) where
+
+import Data.HashSet qualified as HashSet
+import Hasql.Connection qualified as Connection
+import Hasql.Decoders qualified as Decoders
+import Hasql.Errors qualified as Errors
+import Hasql.Session qualified as Session
+import Hasql.Statement qualified as Statement
+import Helpers.Scripts qualified as Scripts
+import Prelude
+import Test.Hspec
+
+spec :: SpecWith Scripts.ScopeParams
+spec = do
+  describe "Simple enums" do
+    it "decodes a simple named enum from static SQL" \config -> do
+      enumName <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create enum type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", enumName, " as enum ('sad', 'ok', 'happy')"])
+              mempty
+              Decoders.noResult
+          -- Test decoding from static value
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["select 'happy' :: ", enumName])
+              mempty
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable (Decoders.enum Nothing enumName (Just . id)))))
+        result `shouldBe` Right "happy"
+
+    it "decodes different enum values" \config -> do
+      enumName <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create enum type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", enumName, " as enum ('alpha', 'beta', 'gamma')"])
+              mempty
+              Decoders.noResult
+          -- Test decoding multiple values
+          r1 <-
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["select 'alpha' :: ", enumName])
+                mempty
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable (Decoders.enum Nothing enumName (Just . id)))))
+          r2 <-
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["select 'gamma' :: ", enumName])
+                mempty
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable (Decoders.enum Nothing enumName (Just . id)))))
+          return (r1, r2)
+        result `shouldBe` Right ("alpha", "gamma")
+
+  describe "Enums in composites" do
+    it "decodes enums nested in named composites from static SQL" \config -> do
+      enumName <- Scripts.generateSymname
+      compositeName <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create enum type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", enumName, " as enum ('red', 'green', 'blue')"])
+              mempty
+              Decoders.noResult
+          -- Create composite type with enum
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", compositeName, " as (id int8, color ", enumName, ")"])
+              mempty
+              Decoders.noResult
+          -- Test decoding
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["select (42, 'green') :: ", compositeName])
+              mempty
+              ( Decoders.singleRow
+                  ( Decoders.column
+                      ( Decoders.nonNullable
+                          ( Decoders.composite
+                              Nothing
+                              compositeName
+                              ( (,)
+                                  <$> Decoders.field (Decoders.nonNullable Decoders.int8)
+                                  <*> Decoders.field (Decoders.nonNullable (Decoders.enum Nothing enumName (Just . id)))
+                              )
+                          )
+                      )
+                  )
+              )
+        result `shouldBe` Right (42 :: Int64, "green")
+
+    it "decodes multiple levels of nesting with enums" \config -> do
+      enumName <- Scripts.generateSymname
+      innerType <- Scripts.generateSymname
+      outerType <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create enum type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", enumName, " as enum ('small', 'medium', 'large')"])
+              mempty
+              Decoders.noResult
+          -- Create inner composite with enum
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", innerType, " as (size ", enumName, ", count int4)"])
+              mempty
+              Decoders.noResult
+          -- Create outer composite
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", outerType, " as (\"inner\" ", innerType, ", name text)"])
+              mempty
+              Decoders.noResult
+          -- Test decoding
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["select (('large', 5), 'test') :: ", outerType])
+              mempty
+              ( Decoders.singleRow
+                  ( Decoders.column
+                      ( Decoders.nonNullable
+                          ( Decoders.composite
+                              Nothing
+                              outerType
+                              ( (,)
+                                  <$> Decoders.field
+                                    ( Decoders.nonNullable
+                                        ( Decoders.composite
+                                            Nothing
+                                            innerType
+                                            ( (,)
+                                                <$> Decoders.field (Decoders.nonNullable (Decoders.enum Nothing enumName (Just . id)))
+                                                <*> Decoders.field (Decoders.nonNullable Decoders.int4)
+                                            )
+                                        )
+                                    )
+                                  <*> Decoders.field (Decoders.nonNullable Decoders.text)
+                              )
+                          )
+                      )
+                  )
+              )
+        result `shouldBe` Right (("large", 5 :: Int32), "test")
+
+  describe "Arrays of enums" do
+    it "decodes arrays of named enums from static SQL" \config -> do
+      enumName <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create enum type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", enumName, " as enum ('first', 'second', 'third')"])
+              mempty
+              Decoders.noResult
+          -- Test array decoding
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["select array['first', 'third', 'second'] :: ", enumName, "[]"])
+              mempty
+              ( Decoders.singleRow
+                  ( Decoders.column
+                      ( Decoders.nonNullable
+                          ( Decoders.array
+                              ( Decoders.dimension
+                                  replicateM
+                                  (Decoders.element (Decoders.nonNullable (Decoders.enum Nothing enumName (Just . id))))
+                              )
+                          )
+                      )
+                  )
+              )
+        result `shouldBe` Right ["first", "third", "second"]
+
+    it "decodes 2D arrays of named enums" \config -> do
+      enumName <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create enum type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", enumName, " as enum ('a', 'b', 'c')"])
+              mempty
+              Decoders.noResult
+          -- Test 2D array decoding
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["select array[array['a', 'b'], array['c', 'a']] :: ", enumName, "[][]"])
+              mempty
+              ( Decoders.singleRow
+                  ( Decoders.column
+                      ( Decoders.nonNullable
+                          ( Decoders.array
+                              ( Decoders.dimension
+                                  replicateM
+                                  ( Decoders.dimension
+                                      replicateM
+                                      (Decoders.element (Decoders.nonNullable (Decoders.enum Nothing enumName (Just . id))))
+                                  )
+                              )
+                          )
+                      )
+                  )
+              )
+        result `shouldBe` Right [["a", "b"], ["c", "a"]]
+
+    it "decodes arrays of composites containing enums" \config -> do
+      enumName <- Scripts.generateSymname
+      compositeName <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create enum type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", enumName, " as enum ('low', 'high')"])
+              mempty
+              Decoders.noResult
+          -- Create composite type with enum
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", compositeName, " as (priority ", enumName, ", id int4)"])
+              mempty
+              Decoders.noResult
+          -- Test decoding array of composites with enums
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["select array[('high', 1), ('low', 2)] :: ", compositeName, "[]"])
+              mempty
+              ( Decoders.singleRow
+                  ( Decoders.column
+                      ( Decoders.nonNullable
+                          ( Decoders.array
+                              ( Decoders.dimension
+                                  replicateM
+                                  ( Decoders.element
+                                      ( Decoders.nonNullable
+                                          ( Decoders.composite
+                                              Nothing
+                                              compositeName
+                                              ( (,)
+                                                  <$> Decoders.field (Decoders.nonNullable (Decoders.enum Nothing enumName (Just . id)))
+                                                  <*> Decoders.field (Decoders.nonNullable Decoders.int4)
+                                              )
+                                          )
+                                      )
+                                  )
+                              )
+                          )
+                      )
+                  )
+              )
+        result `shouldBe` Right [("high", 1 :: Int32), ("low", 2)]
+
+  it "detects attempts to decode non-existent enum types" \config -> do
+    Scripts.onPreparableConnection config \connection -> do
+      result <- Connection.use connection do
+        Session.statement ()
+          $ Statement.preparable
+            "select 'value'::text"
+            mempty
+            (Decoders.singleRow (Decoders.column (Decoders.nonNullable (Decoders.enum Nothing "nonexistent_enum_type" (Just . id)))))
+
+      case result of
+        Left (Errors.SessionUseError (Errors.MissingTypesSessionError missingTypes)) ->
+          missingTypes `shouldBe` HashSet.fromList [(Nothing, "nonexistent_enum_type")]
+        _ ->
+          expectationFailure ("Unexpected result: " <> show result)
+
+  it "detects attempts to decode arrays of non-existent enum types" \config -> do
+    Scripts.onPreparableConnection config \connection -> do
+      result <- Connection.use connection do
+        Session.statement ()
+          $ Statement.preparable
+            "select array['a', 'b']::text[]"
+            mempty
+            ( Decoders.singleRow
+                ( Decoders.column
+                    ( Decoders.nonNullable
+                        ( Decoders.array
+                            ( Decoders.dimension
+                                replicateM
+                                (Decoders.element (Decoders.nonNullable (Decoders.enum Nothing "nonexistent_array_enum" (Just . id))))
+                            )
+                        )
+                    )
+                )
+            )
+
+      case result of
+        Left (Errors.SessionUseError (Errors.MissingTypesSessionError missingTypes)) ->
+          missingTypes `shouldBe` HashSet.fromList [(Nothing, "nonexistent_array_enum")]
+        _ ->
+          expectationFailure ("Unexpected result: " <> show result)
diff --git a/src/library-tests/Integration/Sharing/Decoders/Float8Spec.hs b/src/library-tests/Integration/Sharing/Decoders/Float8Spec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/Decoders/Float8Spec.hs
@@ -0,0 +1,27 @@
+module Integration.Sharing.Decoders.Float8Spec (spec) where
+
+import Hasql.Connection qualified as Connection
+import Hasql.Decoders qualified as Decoders
+import Hasql.Session qualified as Session
+import Hasql.Statement qualified as Statement
+import Helpers.Scripts qualified as Scripts
+import Prelude
+import Test.Hspec
+
+spec :: SpecWith Scripts.ScopeParams
+spec = do
+  it "decodes static value properly" \config -> do
+    Scripts.onPreparableConnection config \connection -> do
+      let statement =
+            Statement.preparable
+              "select 3.14 :: float8"
+              mempty
+              ( Decoders.singleRow
+                  ( Decoders.column
+                      ( Decoders.nonNullable
+                          Decoders.float8
+                      )
+                  )
+              )
+      result <- Connection.use connection (Session.statement () statement)
+      result `shouldBe` Right 3.14
diff --git a/src/library-tests/Integration/Sharing/Decoders/HstoreSpec.hs b/src/library-tests/Integration/Sharing/Decoders/HstoreSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/Decoders/HstoreSpec.hs
@@ -0,0 +1,114 @@
+module Integration.Sharing.Decoders.HstoreSpec (spec) where
+
+import Data.HashMap.Strict qualified as HashMap
+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.Scripts qualified as Scripts
+import Prelude
+import Test.Hspec
+
+spec :: SpecWith Scripts.ScopeParams
+spec = do
+  describe "Hstore Decoders" do
+    it "decodes empty hstore" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Enable hstore extension (unprepared), ignore if already exists
+          catchError
+            ( Session.statement ()
+                $ Statement.unpreparable
+                  "CREATE EXTENSION IF NOT EXISTS hstore"
+                  Encoders.noParams
+                  Decoders.noResult
+            )
+            (const (pure ()))
+          -- Test decoding empty hstore
+          Session.statement ()
+            $ Statement.preparable
+              "select ''::hstore"
+              Encoders.noParams
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable (Decoders.hstore (\n f -> replicateM n f >>= pure . HashMap.fromList)))))
+        result `shouldBe` Right (HashMap.empty :: HashMap.HashMap Text (Maybe Text))
+
+    it "decodes hstore with single key-value pair" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Enable hstore extension (unprepared), ignore if already exists
+          catchError
+            ( Session.statement ()
+                $ Statement.unpreparable
+                  "CREATE EXTENSION IF NOT EXISTS hstore"
+                  Encoders.noParams
+                  Decoders.noResult
+            )
+            (const (pure ()))
+          -- Test decoding single key-value pair
+          Session.statement ()
+            $ Statement.preparable
+              "select 'key => value'::hstore"
+              Encoders.noParams
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable (Decoders.hstore (\n f -> replicateM n f >>= pure . HashMap.fromList)))))
+        result `shouldBe` Right (HashMap.fromList [("key", Just "value")] :: HashMap.HashMap Text (Maybe Text))
+
+    it "decodes hstore with multiple key-value pairs" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Enable hstore extension (unprepared), ignore if already exists
+          catchError
+            ( Session.statement ()
+                $ Statement.unpreparable
+                  "CREATE EXTENSION IF NOT EXISTS hstore"
+                  Encoders.noParams
+                  Decoders.noResult
+            )
+            (const (pure ()))
+          -- Test decoding multiple key-value pairs
+          Session.statement ()
+            $ Statement.preparable
+              "select 'a => 1, b => 2, c => 3'::hstore"
+              Encoders.noParams
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable (Decoders.hstore (\n f -> replicateM n f >>= pure . HashMap.fromList)))))
+        result `shouldBe` Right (HashMap.fromList [("a", Just "1"), ("b", Just "2"), ("c", Just "3")] :: HashMap.HashMap Text (Maybe Text))
+
+    it "decodes hstore with null values" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Enable hstore extension (unprepared), ignore if already exists
+          catchError
+            ( Session.statement ()
+                $ Statement.unpreparable
+                  "CREATE EXTENSION IF NOT EXISTS hstore"
+                  Encoders.noParams
+                  Decoders.noResult
+            )
+            (const (pure ()))
+          -- Test decoding hstore with null values
+          Session.statement ()
+            $ Statement.preparable
+              "select 'key1 => value1, key2 => NULL, key3 => value3'::hstore"
+              Encoders.noParams
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable (Decoders.hstore (\n f -> replicateM n f >>= pure . HashMap.fromList)))))
+        result `shouldBe` Right (HashMap.fromList [("key1", Just "value1"), ("key2", Nothing), ("key3", Just "value3")] :: HashMap.HashMap Text (Maybe Text))
+
+    it "decodes hstore with special characters" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Enable hstore extension (unprepared), ignore if already exists
+          catchError
+            ( Session.statement ()
+                $ Statement.unpreparable
+                  "CREATE EXTENSION IF NOT EXISTS hstore"
+                  Encoders.noParams
+                  Decoders.noResult
+            )
+            (const (pure ()))
+          -- Test decoding hstore with special characters
+          Session.statement ()
+            $ Statement.preparable
+              "select '\"key with spaces\" => \"value with quotes\"'::hstore"
+              Encoders.noParams
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable (Decoders.hstore (\n f -> replicateM n f >>= pure . HashMap.fromList)))))
+        result `shouldBe` Right (HashMap.fromList [("key with spaces", Just "value with quotes")] :: HashMap.HashMap Text (Maybe Text))
diff --git a/src/library-tests/Integration/Sharing/Decoders/InetSpec.hs b/src/library-tests/Integration/Sharing/Decoders/InetSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/Decoders/InetSpec.hs
@@ -0,0 +1,72 @@
+module Integration.Sharing.Decoders.InetSpec (spec) where
+
+import Data.IP (IPv4, IPv6)
+import Data.IP qualified as IP
+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.Scripts qualified as Scripts
+import Prelude
+import Test.Hspec
+
+spec :: SpecWith Scripts.ScopeParams
+spec = do
+  describe "INET Decoders" do
+    it "decodes IPv4 address" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        let statement =
+              Statement.preparable
+                "select '192.168.1.1/32'::inet"
+                Encoders.noParams
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.inet)))
+        result <- Connection.use connection (Session.statement () statement)
+        let expectedAddr = read "192.168.1.1" :: IPv4
+            expectedRange = IP.makeAddrRange expectedAddr 32
+        result `shouldBe` Right (IP.IPv4Range expectedRange)
+
+    it "decodes IPv4 CIDR" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        let statement =
+              Statement.preparable
+                "select '10.0.0.0/8'::inet"
+                Encoders.noParams
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.inet)))
+        result <- Connection.use connection (Session.statement () statement)
+        let expectedAddr = read "10.0.0.0" :: IPv4
+            expectedRange = IP.makeAddrRange expectedAddr 8
+        result `shouldBe` Right (IP.IPv4Range expectedRange)
+
+    it "decodes IPv6 address" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        let statement =
+              Statement.preparable
+                "select '::1/128'::inet"
+                Encoders.noParams
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.inet)))
+        result <- Connection.use connection (Session.statement () statement)
+        let expectedAddr = read "::1" :: IPv6
+            expectedRange = IP.makeAddrRange expectedAddr 128
+        result `shouldBe` Right (IP.IPv6Range expectedRange)
+
+  describe "MACADDR Decoders" do
+    it "decodes MAC address" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        let statement =
+              Statement.preparable
+                "select '08:00:2b:01:02:03'::macaddr"
+                Encoders.noParams
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.macaddr)))
+        result <- Connection.use connection (Session.statement () statement)
+        result `shouldBe` Right (0x08, 0x00, 0x2b, 0x01, 0x02, 0x03)
+
+    it "decodes another MAC address format" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        let statement =
+              Statement.preparable
+                "select 'ff:ff:ff:ff:ff:ff'::macaddr"
+                Encoders.noParams
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.macaddr)))
+        result <- Connection.use connection (Session.statement () statement)
+        result `shouldBe` Right (0xff, 0xff, 0xff, 0xff, 0xff, 0xff)
diff --git a/src/library-tests/Integration/Sharing/Decoders/IntervalSpec.hs b/src/library-tests/Integration/Sharing/Decoders/IntervalSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/Decoders/IntervalSpec.hs
@@ -0,0 +1,23 @@
+module Integration.Sharing.Decoders.IntervalSpec (spec) where
+
+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.Scripts qualified as Scripts
+import Prelude
+import Test.Hspec
+
+spec :: SpecWith Scripts.ScopeParams
+spec = do
+  describe "Interval Decoders" do
+    it "decodes intervals correctly" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        let statement =
+              Statement.preparable
+                "select interval '10 seconds'"
+                Encoders.noParams
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.interval)))
+        result <- Connection.use connection (Session.statement () statement)
+        result `shouldBe` Right (10 :: DiffTime)
diff --git a/src/library-tests/Integration/Sharing/Decoders/JsonSpec.hs b/src/library-tests/Integration/Sharing/Decoders/JsonSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/Decoders/JsonSpec.hs
@@ -0,0 +1,85 @@
+module Integration.Sharing.Decoders.JsonSpec (spec) where
+
+import Data.Aeson qualified as Aeson
+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.Scripts qualified as Scripts
+import Prelude
+import Test.Hspec
+
+spec :: SpecWith Scripts.ScopeParams
+spec = do
+  describe "JSON Decoders" do
+    it "decodes JSON null" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        let statement =
+              Statement.preparable
+                "select 'null'::json"
+                Encoders.noParams
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.json)))
+        result <- Connection.use connection (Session.statement () statement)
+        result `shouldBe` Right Aeson.Null
+
+    it "decodes JSON number" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        let statement =
+              Statement.preparable
+                "select '42'::json"
+                Encoders.noParams
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.json)))
+        result <- Connection.use connection (Session.statement () statement)
+        result `shouldBe` Right (Aeson.Number 42)
+
+    it "decodes JSON string" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        let statement =
+              Statement.preparable
+                "select '\"hello\"'::json"
+                Encoders.noParams
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.json)))
+        result <- Connection.use connection (Session.statement () statement)
+        result `shouldBe` Right (Aeson.String "hello")
+
+    it "decodes JSON array" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        let statement =
+              Statement.preparable
+                "select '[1,2,3]'::json"
+                Encoders.noParams
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.json)))
+        result <- Connection.use connection (Session.statement () statement)
+        result `shouldBe` Right (Aeson.Array (fromList [Aeson.Number 1, Aeson.Number 2, Aeson.Number 3]))
+
+    it "decodes JSON object" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        let statement =
+              Statement.preparable
+                "select '{\"name\":\"John\",\"age\":30}'::json"
+                Encoders.noParams
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.json)))
+        result <- Connection.use connection (Session.statement () statement)
+        result `shouldBe` Right (Aeson.object [("name", Aeson.String "John"), ("age", Aeson.Number 30)])
+
+  describe "JSONB Decoders" do
+    it "decodes JSONB object" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        let statement =
+              Statement.preparable
+                "select '{\"key\":\"value\"}'::jsonb"
+                Encoders.noParams
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.jsonb)))
+        result <- Connection.use connection (Session.statement () statement)
+        result `shouldBe` Right (Aeson.object [("key", Aeson.String "value")])
+
+    it "decodes JSONB array" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        let statement =
+              Statement.preparable
+                "select '[true, false]'::jsonb"
+                Encoders.noParams
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.jsonb)))
+        result <- Connection.use connection (Session.statement () statement)
+        result `shouldBe` Right (Aeson.Array (fromList [Aeson.Bool True, Aeson.Bool False]))
diff --git a/src/library-tests/Integration/Sharing/Decoders/RecordSpec.hs b/src/library-tests/Integration/Sharing/Decoders/RecordSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/Decoders/RecordSpec.hs
@@ -0,0 +1,259 @@
+module Integration.Sharing.Decoders.RecordSpec (spec) where
+
+import Hasql.Connection qualified as Connection
+import Hasql.Decoders qualified as Decoders
+import Hasql.Session qualified as Session
+import Hasql.Statement qualified as Statement
+import Helpers.Scripts qualified as Scripts
+import Prelude
+import Test.Hspec
+
+spec :: SpecWith Scripts.ScopeParams
+spec = do
+  describe "Unnamed Composite Decoders" do
+    describe "Simple composites" do
+      it "decodes a simple unnamed composite from static SQL" \config -> do
+        Scripts.onPreparableConnection config \connection -> do
+          let statement =
+                Statement.preparable
+                  "select (1, true)"
+                  mempty
+                  ( Decoders.singleRow
+                      ( Decoders.column
+                          ( Decoders.nonNullable
+                              ( Decoders.record
+                                  ( (,)
+                                      <$> Decoders.field (Decoders.nonNullable Decoders.int4)
+                                      <*> Decoders.field (Decoders.nonNullable Decoders.bool)
+                                  )
+                              )
+                          )
+                      )
+                  )
+          result <- Connection.use connection (Session.statement () statement)
+          result `shouldBe` Right (1, True)
+
+      it "decodes unnamed composites with different types" \config -> do
+        Scripts.onPreparableConnection config \connection -> do
+          let statement =
+                Statement.preparable
+                  "select (text 'hello', 123)"
+                  mempty
+                  ( Decoders.singleRow
+                      ( Decoders.column
+                          ( Decoders.nonNullable
+                              ( Decoders.record
+                                  ( (,)
+                                      <$> Decoders.field (Decoders.nonNullable Decoders.text)
+                                      <*> Decoders.field (Decoders.nonNullable Decoders.int4)
+                                  )
+                              )
+                          )
+                      )
+                  )
+          result <- Connection.use connection (Session.statement () statement)
+          result `shouldBe` Right ("hello", 123 :: Int32)
+
+      it "decodes unnamed composites with three fields" \config -> do
+        Scripts.onPreparableConnection config \connection -> do
+          let statement =
+                Statement.preparable
+                  "select (42, text 'test', 3.14 :: float8)"
+                  mempty
+                  ( Decoders.singleRow
+                      ( Decoders.column
+                          ( Decoders.nonNullable
+                              ( Decoders.record
+                                  ( (,,)
+                                      <$> Decoders.field (Decoders.nonNullable Decoders.int4)
+                                      <*> Decoders.field (Decoders.nonNullable Decoders.text)
+                                      <*> Decoders.field (Decoders.nonNullable Decoders.float8)
+                                  )
+                              )
+                          )
+                      )
+                  )
+          result <- Connection.use connection (Session.statement () statement)
+          result `shouldBe` Right (42, "test", 3.14 :: Double)
+
+    describe "Nested composites" do
+      it "decodes nested unnamed composites from static SQL" \config -> do
+        Scripts.onPreparableConnection config \connection -> do
+          let statement =
+                Statement.preparable
+                  "select ((1, true), (text 'hello', 3))"
+                  mempty
+                  ( Decoders.singleRow
+                      ( Decoders.column
+                          ( Decoders.nonNullable
+                              ( Decoders.record
+                                  ( (,)
+                                      <$> Decoders.field
+                                        ( Decoders.nonNullable
+                                            ( Decoders.record
+                                                ( (,)
+                                                    <$> Decoders.field (Decoders.nonNullable Decoders.int4)
+                                                    <*> Decoders.field (Decoders.nonNullable Decoders.bool)
+                                                )
+                                            )
+                                        )
+                                      <*> Decoders.field
+                                        ( Decoders.nonNullable
+                                            ( Decoders.record
+                                                ( (,)
+                                                    <$> Decoders.field (Decoders.nonNullable Decoders.text)
+                                                    <*> Decoders.field (Decoders.nonNullable Decoders.int4)
+                                                )
+                                            )
+                                        )
+                                  )
+                              )
+                          )
+                      )
+                  )
+          result <- Connection.use connection (Session.statement () statement)
+          result `shouldBe` Right ((1, True), ("hello", 3))
+
+      it "decodes deeply nested unnamed composites" \config -> do
+        Scripts.onPreparableConnection config \connection -> do
+          let statement =
+                Statement.preparable
+                  "select ((row (99), (true, text 'test')), text 'outer')"
+                  mempty
+                  ( Decoders.singleRow
+                      ( Decoders.column
+                          ( Decoders.nonNullable
+                              ( Decoders.record
+                                  ( (,)
+                                      <$> Decoders.field
+                                        ( Decoders.nonNullable
+                                            ( Decoders.record
+                                                ( (,)
+                                                    <$> Decoders.field
+                                                      ( Decoders.nonNullable
+                                                          ( Decoders.record
+                                                              (Decoders.field (Decoders.nonNullable Decoders.int4))
+                                                          )
+                                                      )
+                                                    <*> Decoders.field
+                                                      ( Decoders.nonNullable
+                                                          ( Decoders.record
+                                                              ( (,)
+                                                                  <$> Decoders.field (Decoders.nonNullable Decoders.bool)
+                                                                  <*> Decoders.field (Decoders.nonNullable Decoders.text)
+                                                              )
+                                                          )
+                                                      )
+                                                )
+                                            )
+                                        )
+                                      <*> Decoders.field (Decoders.nonNullable Decoders.text)
+                                  )
+                              )
+                          )
+                      )
+                  )
+          result <- Connection.use connection (Session.statement () statement)
+          result `shouldBe` Right ((99, (True, "test")), "outer")
+
+    describe "Arrays of composites" do
+      it "decodes arrays of unnamed composites from static SQL" \config -> do
+        Scripts.onPreparableConnection config \connection -> do
+          let statement =
+                Statement.preparable
+                  "select array[(1, true), (2, false), (3, true)]"
+                  mempty
+                  ( Decoders.singleRow
+                      ( Decoders.column
+                          ( Decoders.nonNullable
+                              ( Decoders.array
+                                  ( Decoders.dimension
+                                      replicateM
+                                      ( Decoders.element
+                                          ( Decoders.nonNullable
+                                              ( Decoders.record
+                                                  ( (,)
+                                                      <$> Decoders.field (Decoders.nonNullable Decoders.int4)
+                                                      <*> Decoders.field (Decoders.nonNullable Decoders.bool)
+                                                  )
+                                              )
+                                          )
+                                      )
+                                  )
+                              )
+                          )
+                      )
+                  )
+          result <- Connection.use connection (Session.statement () statement)
+          result `shouldBe` Right [(1, True), (2, False), (3, True)]
+
+      it "decodes 2D arrays of unnamed composites" \config -> do
+        Scripts.onPreparableConnection config \connection -> do
+          let statement =
+                Statement.preparable
+                  "select array[array[(1, text 'a'), (2, text 'b')], array[(3, text 'c'), (4, text 'd')]]"
+                  mempty
+                  ( Decoders.singleRow
+                      ( Decoders.column
+                          ( Decoders.nonNullable
+                              ( Decoders.array
+                                  ( Decoders.dimension
+                                      replicateM
+                                      ( Decoders.dimension
+                                          replicateM
+                                          ( Decoders.element
+                                              ( Decoders.nonNullable
+                                                  ( Decoders.record
+                                                      ( (,)
+                                                          <$> Decoders.field (Decoders.nonNullable Decoders.int4)
+                                                          <*> Decoders.field (Decoders.nonNullable Decoders.text)
+                                                      )
+                                                  )
+                                              )
+                                          )
+                                      )
+                                  )
+                              )
+                          )
+                      )
+                  )
+          result <- Connection.use connection (Session.statement () statement)
+          result `shouldBe` Right [[(1 :: Int32, "a"), (2, "b")], [(3, "c"), (4, "d")]]
+
+      it "decodes arrays of nested unnamed composites" \config -> do
+        Scripts.onPreparableConnection config \connection -> do
+          let statement =
+                Statement.preparable
+                  "select array[((1, true), text 'x'), ((2, false), text 'y')]"
+                  mempty
+                  ( Decoders.singleRow
+                      ( Decoders.column
+                          ( Decoders.nonNullable
+                              ( Decoders.array
+                                  ( Decoders.dimension
+                                      replicateM
+                                      ( Decoders.element
+                                          ( Decoders.nonNullable
+                                              ( Decoders.record
+                                                  ( (,)
+                                                      <$> Decoders.field
+                                                        ( Decoders.nonNullable
+                                                            ( Decoders.record
+                                                                ( (,)
+                                                                    <$> Decoders.field (Decoders.nonNullable Decoders.int4)
+                                                                    <*> Decoders.field (Decoders.nonNullable Decoders.bool)
+                                                                )
+                                                            )
+                                                        )
+                                                      <*> Decoders.field (Decoders.nonNullable Decoders.text)
+                                                  )
+                                              )
+                                          )
+                                      )
+                                  )
+                              )
+                          )
+                      )
+                  )
+          result <- Connection.use connection (Session.statement () statement)
+          result `shouldBe` Right [((1, True), "x"), ((2, False), "y")]
diff --git a/src/library-tests/Integration/Sharing/Decoders/UuidSpec.hs b/src/library-tests/Integration/Sharing/Decoders/UuidSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/Decoders/UuidSpec.hs
@@ -0,0 +1,36 @@
+module Integration.Sharing.Decoders.UuidSpec (spec) where
+
+import Data.UUID qualified as UUID
+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.Scripts qualified as Scripts
+import Prelude
+import Test.Hspec
+
+spec :: SpecWith Scripts.ScopeParams
+spec = do
+  describe "UUID Decoders" do
+    it "decodes UUID from static value" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        let statement =
+              Statement.preparable
+                "select '550e8400-e29b-41d4-a716-446655440000'::uuid"
+                Encoders.noParams
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.uuid)))
+        result <- Connection.use connection (Session.statement () statement)
+        case UUID.fromString "550e8400-e29b-41d4-a716-446655440000" of
+          Just expectedUuid -> result `shouldBe` Right expectedUuid
+          Nothing -> expectationFailure "Failed to parse expected UUID"
+
+    it "decodes nil UUID" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        let statement =
+              Statement.preparable
+                "select '00000000-0000-0000-0000-000000000000'::uuid"
+                Encoders.noParams
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.uuid)))
+        result <- Connection.use connection (Session.statement () statement)
+        result `shouldBe` Right UUID.nil
diff --git a/src/library-tests/Integration/Sharing/Encoders/ArraySpec.hs b/src/library-tests/Integration/Sharing/Encoders/ArraySpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/Encoders/ArraySpec.hs
@@ -0,0 +1,40 @@
+module Integration.Sharing.Encoders.ArraySpec (spec) where
+
+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.Scripts qualified as Scripts
+import Prelude hiding (assert)
+import Test.Hspec
+import Test.QuickCheck
+import Test.QuickCheck.Instances ()
+import Test.QuickCheck.Monadic (assert, monadicIO, pre, run)
+
+spec :: SpecWith Scripts.ScopeParams
+spec = do
+  describe "Array Encoders" do
+    describe "1D arrays" do
+      it "roundtrips 1D arrays" \config -> property $ \(values :: [Int64]) -> monadicIO $ do
+        let statement =
+              Statement.preparable
+                "select $1"
+                (Encoders.param (Encoders.nonNullable (Encoders.array (Encoders.dimension foldl' (Encoders.element (Encoders.nonNullable Encoders.int8))))))
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable (Decoders.array (Decoders.dimension replicateM (Decoders.element (Decoders.nonNullable Decoders.int8)))))))
+        result <- run $ Scripts.onPreparableConnection config \connection ->
+          Connection.use connection (Session.statement values statement)
+        assert $ result == Right values
+
+    describe "2D arrays" do
+      it "roundtrips 2D arrays" \config -> property $ \(values :: [Int64]) -> monadicIO $ do
+        pre (not (null values))
+        let input = replicate 3 values
+        let statement =
+              Statement.preparable
+                "select $1"
+                (Encoders.param (Encoders.nonNullable (Encoders.array (Encoders.dimension foldl' (Encoders.dimension foldl' (Encoders.element (Encoders.nonNullable Encoders.int8)))))))
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable (Decoders.array (Decoders.dimension replicateM (Decoders.dimension replicateM (Decoders.element (Decoders.nonNullable Decoders.int8))))))))
+        result <- run $ Scripts.onPreparableConnection config \connection ->
+          Connection.use connection (Session.statement input statement)
+        assert $ result == Right input
diff --git a/src/library-tests/Integration/Sharing/Encoders/CitextSpec.hs b/src/library-tests/Integration/Sharing/Encoders/CitextSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/Encoders/CitextSpec.hs
@@ -0,0 +1,67 @@
+module Integration.Sharing.Encoders.CitextSpec (spec) where
+
+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.Scripts qualified as Scripts
+import Prelude
+import Test.Hspec
+
+spec :: SpecWith Scripts.ScopeParams
+spec = do
+  describe "Citext Encoders" do
+    it "encodes a citext value and compares with static value" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          catchError
+            ( Session.statement ()
+                $ Statement.unpreparable
+                  "CREATE EXTENSION IF NOT EXISTS citext"
+                  Encoders.noParams
+                  Decoders.noResult
+            )
+            (const (pure ()))
+          Session.statement "hello"
+            $ Statement.preparable
+              "select $1 = 'hello'"
+              (Encoders.param (Encoders.nonNullable Encoders.citext))
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.bool)))
+        result `shouldBe` Right True
+
+    it "encodes a citext value with case-insensitive comparison" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          catchError
+            ( Session.statement ()
+                $ Statement.unpreparable
+                  "CREATE EXTENSION IF NOT EXISTS citext"
+                  Encoders.noParams
+                  Decoders.noResult
+            )
+            (const (pure ()))
+          Session.statement "Hello"
+            $ Statement.preparable
+              "select $1 = 'hello'"
+              (Encoders.param (Encoders.nonNullable Encoders.citext))
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.bool)))
+        result `shouldBe` Right True
+
+    it "roundtrips a citext value" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          catchError
+            ( Session.statement ()
+                $ Statement.unpreparable
+                  "CREATE EXTENSION IF NOT EXISTS citext"
+                  Encoders.noParams
+                  Decoders.noResult
+            )
+            (const (pure ()))
+          Session.statement "Hello World"
+            $ Statement.preparable
+              "select $1"
+              (Encoders.param (Encoders.nonNullable Encoders.citext))
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.citext)))
+        result `shouldBe` Right "Hello World"
diff --git a/src/library-tests/Integration/Sharing/Encoders/Composite/OidMismatchSpec.hs b/src/library-tests/Integration/Sharing/Encoders/Composite/OidMismatchSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/Encoders/Composite/OidMismatchSpec.hs
@@ -0,0 +1,193 @@
+module Integration.Sharing.Encoders.Composite.OidMismatchSpec (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.Scripts qualified as Scripts
+import Prelude
+import Test.Hspec
+
+spec :: SpecWith Scripts.ScopeParams
+spec = do
+  describe "Composite field OID mismatch detection" do
+    describe "Encoder field type mismatch" do
+      it "detects when encoder uses int4 but actual field is int8" \config -> do
+        typeName <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            -- Create composite type with int8 field
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create type ", typeName, " as (x int8)"])
+                mempty
+                Decoders.noResult
+            -- Try to encode with int4 encoder to int8 field
+            Session.statement (42 :: Int32)
+              $ Statement.preparable
+                (mconcat ["select $1 :: ", typeName])
+                ( Encoders.param
+                    ( Encoders.nonNullable
+                        ( Encoders.composite
+                            Nothing
+                            typeName
+                            -- Using int4 encoder for int8 field - should fail
+                            (Encoders.field (Encoders.nonNullable Encoders.int4))
+                        )
+                    )
+                )
+                ( Decoders.singleRow
+                    ( Decoders.column
+                        ( Decoders.nonNullable
+                            (Decoders.composite Nothing typeName (Decoders.field (Decoders.nonNullable Decoders.int8)))
+                        )
+                    )
+                )
+          -- The error should indicate a type mismatch from the server
+          case result of
+            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")
+            Left err ->
+              expectationFailure ("Unexpected type of error: " <> show err)
+            Right _ ->
+              expectationFailure "Expected an error but got success"
+
+      it "detects when encoder uses int8 but actual field is int4" \config -> do
+        typeName <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            -- Create composite type with int4 field
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create type ", typeName, " as (x int4)"])
+                mempty
+                Decoders.noResult
+            -- Try to encode with int8 encoder to int4 field
+            Session.statement (42 :: Int64)
+              $ Statement.preparable
+                (mconcat ["select $1 :: ", typeName])
+                ( Encoders.param
+                    ( Encoders.nonNullable
+                        ( Encoders.composite
+                            Nothing
+                            typeName
+                            -- Using int8 encoder for int4 field - should fail
+                            (Encoders.field (Encoders.nonNullable Encoders.int8))
+                        )
+                    )
+                )
+                ( Decoders.singleRow
+                    ( Decoders.column
+                        ( Decoders.nonNullable
+                            (Decoders.composite Nothing typeName (Decoders.field (Decoders.nonNullable Decoders.int4)))
+                        )
+                    )
+                )
+          -- The error should indicate a type mismatch from the server
+          case result of
+            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")
+            Left err ->
+              expectationFailure ("Unexpected type of error: " <> show err)
+            Right _ ->
+              expectationFailure "Expected an error but got success"
+
+      it "detects when encoder uses text but actual field is int8" \config -> do
+        typeName <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            -- Create composite type with int8 field
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create type ", typeName, " as (x int8)"])
+                mempty
+                Decoders.noResult
+            -- Try to encode with text encoder to int8 field
+            Session.statement ("hello" :: Text)
+              $ Statement.preparable
+                (mconcat ["select $1 :: ", typeName])
+                ( Encoders.param
+                    ( Encoders.nonNullable
+                        ( Encoders.composite
+                            Nothing
+                            typeName
+                            -- Using text encoder for int8 field - should fail
+                            (Encoders.field (Encoders.nonNullable Encoders.text))
+                        )
+                    )
+                )
+                ( Decoders.singleRow
+                    ( Decoders.column
+                        ( Decoders.nonNullable
+                            (Decoders.composite Nothing typeName (Decoders.field (Decoders.nonNullable Decoders.int8)))
+                        )
+                    )
+                )
+          -- The error should indicate a type mismatch from the server
+          case result of
+            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 ->
+              expectationFailure ("Unexpected type of error: " <> show err)
+            Right _ ->
+              expectationFailure "Expected an error but got success"
+
+    describe "Multiple fields with mismatches" do
+      it "detects mismatch in second field" \config -> do
+        typeName <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            -- Create composite type with int8, int4 fields
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create type ", typeName, " as (a int8, b int4)"])
+                mempty
+                Decoders.noResult
+            -- Try to encode with correct first field but wrong second field
+            Session.statement (1 :: Int64, 2 :: Int64)
+              $ Statement.preparable
+                (mconcat ["select $1 :: ", typeName])
+                ( Encoders.param
+                    ( Encoders.nonNullable
+                        ( Encoders.composite
+                            Nothing
+                            typeName
+                            ( divide
+                                (\(a, b) -> (a, b))
+                                (Encoders.field (Encoders.nonNullable Encoders.int8))
+                                -- Using int8 encoder for int4 field - should fail
+                                (Encoders.field (Encoders.nonNullable Encoders.int8))
+                            )
+                        )
+                    )
+                )
+                ( Decoders.singleRow
+                    ( Decoders.column
+                        ( Decoders.nonNullable
+                            ( Decoders.composite
+                                Nothing
+                                typeName
+                                ( (,)
+                                    <$> Decoders.field (Decoders.nonNullable Decoders.int8)
+                                    <*> Decoders.field (Decoders.nonNullable Decoders.int4)
+                                )
+                            )
+                        )
+                    )
+                )
+          -- The error should indicate a type mismatch from the server
+          case result of
+            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 ->
+              expectationFailure ("Unexpected type of error: " <> show err)
+            Right _ ->
+              expectationFailure "Expected an error but got success"
diff --git a/src/library-tests/Integration/Sharing/Encoders/CompositeSpec.hs b/src/library-tests/Integration/Sharing/Encoders/CompositeSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/Encoders/CompositeSpec.hs
@@ -0,0 +1,807 @@
+module Integration.Sharing.Encoders.CompositeSpec (spec) where
+
+import Data.HashSet qualified as HashSet
+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.Scripts qualified as Scripts
+import Prelude
+import Test.Hspec
+
+spec :: SpecWith Scripts.ScopeParams
+spec = do
+  describe "Simple composites" do
+    it "encodes a simple named composite and compares with static value" \config -> do
+      typeName <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create composite type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", typeName, " as (x int8, y bool)"])
+              mempty
+              Decoders.noResult
+          -- Test encoding by comparing with static value
+          Session.statement (42 :: Int64, True)
+            $ Statement.preparable
+              (mconcat ["select ($1 :: ", typeName, ") = (42, true) :: ", typeName])
+              ( Encoders.param
+                  ( Encoders.nonNullable
+                      ( Encoders.composite
+                          Nothing
+                          typeName
+                          ( divide
+                              (\(a, b) -> (a, b))
+                              (Encoders.field (Encoders.nonNullable Encoders.int8))
+                              (Encoders.field (Encoders.nonNullable Encoders.bool))
+                          )
+                      )
+                  )
+              )
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.bool)))
+        result `shouldBe` Right True
+
+    it "encodes and roundtrips a simple named composite" \config -> do
+      typeName <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create composite type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", typeName, " as (x int8, y bool)"])
+              mempty
+              Decoders.noResult
+          -- Test roundtrip
+          Session.statement (42 :: Int64, True)
+            $ Statement.preparable
+              (mconcat ["select $1 :: ", typeName])
+              ( Encoders.param
+                  ( Encoders.nonNullable
+                      ( Encoders.composite
+                          Nothing
+                          typeName
+                          ( divide
+                              (\(a, b) -> (a, b))
+                              (Encoders.field (Encoders.nonNullable Encoders.int8))
+                              (Encoders.field (Encoders.nonNullable Encoders.bool))
+                          )
+                      )
+                  )
+              )
+              ( Decoders.singleRow
+                  ( Decoders.column
+                      ( Decoders.nonNullable
+                          ( Decoders.composite
+                              Nothing
+                              typeName
+                              ( (,)
+                                  <$> Decoders.field (Decoders.nonNullable Decoders.int8)
+                                  <*> Decoders.field (Decoders.nonNullable Decoders.bool)
+                              )
+                          )
+                      )
+                  )
+              )
+        result `shouldBe` Right (42 :: Int64, True)
+
+  describe "Nested composites" do
+    it "encodes nested named composites" \config -> do
+      innerType <- Scripts.generateSymname
+      outerType <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create inner composite type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", innerType, " as (x int8, y bool)"])
+              mempty
+              Decoders.noResult
+          -- Create outer composite type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", outerType, " as (\"inner\" ", innerType, ", z text)"])
+              mempty
+              Decoders.noResult
+          -- Test nested encoding
+          Session.statement ((42 :: Int64, True), "hello")
+            $ Statement.preparable
+              (mconcat ["select ($1 :: ", outerType, ") = ((42, true), 'hello') :: ", outerType])
+              ( Encoders.param
+                  ( Encoders.nonNullable
+                      ( Encoders.composite
+                          Nothing
+                          outerType
+                          ( divide
+                              (\(inner, z) -> (inner, z))
+                              ( Encoders.field
+                                  ( Encoders.nonNullable
+                                      ( Encoders.composite
+                                          Nothing
+                                          innerType
+                                          ( divide
+                                              (\(a, b) -> (a, b))
+                                              (Encoders.field (Encoders.nonNullable Encoders.int8))
+                                              (Encoders.field (Encoders.nonNullable Encoders.bool))
+                                          )
+                                      )
+                                  )
+                              )
+                              (Encoders.field (Encoders.nonNullable Encoders.text))
+                          )
+                      )
+                  )
+              )
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.bool)))
+        result `shouldBe` Right True
+
+    it "roundtrips nested named composites" \config -> do
+      innerType <- Scripts.generateSymname
+      outerType <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create inner composite type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", innerType, " as (x int8, y bool)"])
+              mempty
+              Decoders.noResult
+          -- Create outer composite type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", outerType, " as (\"inner\" ", innerType, ", z text)"])
+              mempty
+              Decoders.noResult
+          -- Test roundtrip
+          Session.statement ((42 :: Int64, True), "hello")
+            $ Statement.preparable
+              (mconcat ["select $1 :: ", outerType])
+              ( Encoders.param
+                  ( Encoders.nonNullable
+                      ( Encoders.composite
+                          Nothing
+                          outerType
+                          ( divide
+                              (\(inner, z) -> (inner, z))
+                              ( Encoders.field
+                                  ( Encoders.nonNullable
+                                      ( Encoders.composite
+                                          Nothing
+                                          innerType
+                                          ( divide
+                                              (\(a, b) -> (a, b))
+                                              (Encoders.field (Encoders.nonNullable Encoders.int8))
+                                              (Encoders.field (Encoders.nonNullable Encoders.bool))
+                                          )
+                                      )
+                                  )
+                              )
+                              (Encoders.field (Encoders.nonNullable Encoders.text))
+                          )
+                      )
+                  )
+              )
+              ( Decoders.singleRow
+                  ( Decoders.column
+                      ( Decoders.nonNullable
+                          ( Decoders.composite
+                              Nothing
+                              outerType
+                              ( (,)
+                                  <$> Decoders.field
+                                    ( Decoders.nonNullable
+                                        ( Decoders.composite
+                                            Nothing
+                                            innerType
+                                            ( (,)
+                                                <$> Decoders.field (Decoders.nonNullable Decoders.int8)
+                                                <*> Decoders.field (Decoders.nonNullable Decoders.bool)
+                                            )
+                                        )
+                                    )
+                                  <*> Decoders.field (Decoders.nonNullable Decoders.text)
+                              )
+                          )
+                      )
+                  )
+              )
+        result `shouldBe` Right ((42 :: Int64, True), "hello")
+
+  describe "Arrays of composites" do
+    it "encodes arrays of named composites" \config -> do
+      typeName <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create composite type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", typeName, " as (x int8, y bool)"])
+              mempty
+              Decoders.noResult
+          -- Test array encoding
+          Session.statement [(1 :: Int64, True), (2, False), (3, True)]
+            $ Statement.preparable
+              (mconcat ["select $1 = array[(1, true), (2, false), (3, true)] :: ", typeName, "[]"])
+              ( Encoders.param
+                  ( Encoders.nonNullable
+                      ( Encoders.array
+                          ( Encoders.dimension
+                              foldl'
+                              ( Encoders.element
+                                  ( Encoders.nonNullable
+                                      ( Encoders.composite
+                                          Nothing
+                                          typeName
+                                          ( divide
+                                              (\(a, b) -> (a, b))
+                                              (Encoders.field (Encoders.nonNullable Encoders.int8))
+                                              (Encoders.field (Encoders.nonNullable Encoders.bool))
+                                          )
+                                      )
+                                  )
+                              )
+                          )
+                      )
+                  )
+              )
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.bool)))
+        result `shouldBe` Right True
+
+    it "roundtrips arrays of named composites" \config -> do
+      typeName <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create composite type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", typeName, " as (x int8, y bool)"])
+              mempty
+              Decoders.noResult
+          -- Test roundtrip
+          Session.statement [(1 :: Int64, True), (2, False), (3, True)]
+            $ Statement.preparable
+              (mconcat ["select $1 :: ", typeName, "[]"])
+              ( Encoders.param
+                  ( Encoders.nonNullable
+                      ( Encoders.array
+                          ( Encoders.dimension
+                              foldl'
+                              ( Encoders.element
+                                  ( Encoders.nonNullable
+                                      ( Encoders.composite
+                                          Nothing
+                                          typeName
+                                          ( divide
+                                              (\(a, b) -> (a, b))
+                                              (Encoders.field (Encoders.nonNullable Encoders.int8))
+                                              (Encoders.field (Encoders.nonNullable Encoders.bool))
+                                          )
+                                      )
+                                  )
+                              )
+                          )
+                      )
+                  )
+              )
+              ( Decoders.singleRow
+                  ( Decoders.column
+                      ( Decoders.nonNullable
+                          ( Decoders.array
+                              ( Decoders.dimension
+                                  replicateM
+                                  ( Decoders.element
+                                      ( Decoders.nonNullable
+                                          ( Decoders.composite
+                                              Nothing
+                                              typeName
+                                              ( (,)
+                                                  <$> Decoders.field (Decoders.nonNullable Decoders.int8)
+                                                  <*> Decoders.field (Decoders.nonNullable Decoders.bool)
+                                              )
+                                          )
+                                      )
+                                  )
+                              )
+                          )
+                      )
+                  )
+              )
+        result `shouldBe` Right [(1 :: Int64, True), (2, False), (3, True)]
+
+  describe "OID lookup verification" do
+    it "requests OID for named composites (verified by successful execution)" \config -> do
+      -- This test verifies that OID lookup happens by ensuring a named composite
+      -- type works correctly - if OID lookup didn't happen, the statement would fail
+      typeName <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create composite type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", typeName, " as (value int8)"])
+              mempty
+              Decoders.noResult
+          -- Use named composite - this requires OID lookup to succeed
+          Session.statement (100 :: Int64)
+            $ Statement.preparable
+              (mconcat ["select $1 :: ", typeName])
+              ( Encoders.param
+                  ( Encoders.nonNullable
+                      ( Encoders.composite
+                          Nothing
+                          typeName
+                          (Encoders.field (Encoders.nonNullable Encoders.int8))
+                      )
+                  )
+              )
+              ( Decoders.singleRow
+                  ( Decoders.column
+                      ( Decoders.nonNullable
+                          (Decoders.composite Nothing typeName (Decoders.field (Decoders.nonNullable Decoders.int8)))
+                      )
+                  )
+              )
+        result `shouldBe` Right (100 :: Int64)
+
+    it "correctly tracks unknown types for nested composites with built-in field types" \config -> do
+      -- This test reproduces the bug where unknownTypes were incorrectly tracked.
+      -- The bug: when a field had a known elementOid (like int8), it was incorrectly
+      -- added to unknownTypes. When elementOid was Nothing (custom types), it wasn't added.
+      -- This caused nested composites with built-in types to fail OID lookup.
+      --
+      -- Specifically: When using a named composite as a field in another composite,
+      -- the inner composite type needs OID lookup (it's custom), but its int8 field doesn't.
+      -- The bug would cause int8 to be requested for OID lookup (wasteful but harmless)
+      -- and fail to request OID lookup for the inner composite type (causing failure).
+      innerType <- Scripts.generateSymname
+      outerType <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create inner composite with a built-in type field
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", innerType, " as (value int8)"])
+              mempty
+              Decoders.noResult
+          -- Create outer composite containing the inner composite
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", outerType, " as (\"inner\" ", innerType, ")"])
+              mempty
+              Decoders.noResult
+          -- With the bug: innerType wouldn't be in the OID cache because
+          -- field (with Nothing elementOid) didn't add it to unknownTypes.
+          -- Instead, int8 (with Just elementOid) was being added (incorrectly).
+          -- This would cause the encoder to use OID 0 for innerType, causing an error.
+          Session.statement (42 :: Int64)
+            $ Statement.preparable
+              (mconcat ["select ($1 :: ", outerType, ").inner.value"])
+              ( Encoders.param
+                  ( Encoders.nonNullable
+                      ( Encoders.composite
+                          Nothing
+                          outerType
+                          ( Encoders.field
+                              ( Encoders.nonNullable
+                                  ( Encoders.composite
+                                      Nothing
+                                      innerType
+                                      (Encoders.field (Encoders.nonNullable Encoders.int8))
+                                  )
+                              )
+                          )
+                      )
+                  )
+              )
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int8)))
+        result `shouldBe` Right (42 :: Int64)
+
+  describe "OID compatibility checking" do
+    it "validates that encoder uses correct composite type OID" \config -> do
+      -- This test ensures that when encoding a composite type, the correct OID is used.
+      -- If the OID lookup fails or returns wrong OID, the statement should fail.
+      typeName <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create composite type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", typeName, " as (x int8, y bool)"])
+              mempty
+              Decoders.noResult
+          -- Encode and verify - the DB will validate the OID is correct
+          Session.statement (42 :: Int64, True)
+            $ Statement.preparable
+              (mconcat ["select ($1 :: ", typeName, ") = row (42, true) :: ", typeName])
+              ( Encoders.param
+                  ( Encoders.nonNullable
+                      ( Encoders.composite
+                          Nothing
+                          typeName
+                          ( divide
+                              (\(a, b) -> (a, b))
+                              (Encoders.field (Encoders.nonNullable Encoders.int8))
+                              (Encoders.field (Encoders.nonNullable Encoders.bool))
+                          )
+                      )
+                  )
+              )
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.bool)))
+        result `shouldBe` Right True
+
+    it "validates OID lookup for nested composite types during encoding" \config -> do
+      -- This test ensures OID lookup works correctly for nested composites
+      innerType <- Scripts.generateSymname
+      outerType <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create inner composite type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", innerType, " as (value int8)"])
+              mempty
+              Decoders.noResult
+          -- Create outer composite type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", outerType, " as (\"nested\" ", innerType, ", flag bool)"])
+              mempty
+              Decoders.noResult
+          -- Encode nested composite - both type OIDs must be looked up correctly
+          Session.statement (99 :: Int64, True)
+            $ Statement.preparable
+              (mconcat ["select ($1 :: ", outerType, ") = row (row (99), true) :: ", outerType])
+              ( Encoders.param
+                  ( Encoders.nonNullable
+                      ( Encoders.composite
+                          Nothing
+                          outerType
+                          ( divide
+                              (\(val, flag) -> (val, flag))
+                              ( Encoders.field
+                                  ( Encoders.nonNullable
+                                      ( Encoders.composite
+                                          Nothing
+                                          innerType
+                                          (Encoders.field (Encoders.nonNullable Encoders.int8))
+                                      )
+                                  )
+                              )
+                              (Encoders.field (Encoders.nonNullable Encoders.bool))
+                          )
+                      )
+                  )
+              )
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.bool)))
+        result `shouldBe` Right True
+
+  describe "Composite with array fields" do
+    it "encodes composite types containing array fields" \config -> do
+      typeName <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create composite type with an array field
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", typeName, " as (id int8, values int8[])"])
+              mempty
+              Decoders.noResult
+          -- Test encoding composite with array field
+          Session.statement (42 :: Int64, [1, 2, 3] :: [Int64])
+            $ Statement.preparable
+              (mconcat ["select ($1 :: ", typeName, ") = (42, '{1, 2, 3}') :: ", typeName])
+              ( Encoders.param
+                  ( Encoders.nonNullable
+                      ( Encoders.composite
+                          Nothing
+                          typeName
+                          ( divide
+                              (\(i, vs) -> (i, vs))
+                              (Encoders.field (Encoders.nonNullable Encoders.int8))
+                              ( Encoders.field
+                                  ( Encoders.nonNullable
+                                      (Encoders.array (Encoders.dimension foldl' (Encoders.element (Encoders.nonNullable Encoders.int8))))
+                                  )
+                              )
+                          )
+                      )
+                  )
+              )
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.bool)))
+        result `shouldBe` Right True
+
+    it "roundtrips composite types containing array fields" \config -> do
+      typeName <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create composite type with an array field
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", typeName, " as (id int8, values int8[])"])
+              mempty
+              Decoders.noResult
+          -- Test roundtrip
+          Session.statement (42 :: Int64, [1, 2, 3] :: [Int64])
+            $ Statement.preparable
+              (mconcat ["select $1 :: ", typeName])
+              ( Encoders.param
+                  ( Encoders.nonNullable
+                      ( Encoders.composite
+                          Nothing
+                          typeName
+                          ( divide
+                              (\(i, vs) -> (i, vs))
+                              (Encoders.field (Encoders.nonNullable Encoders.int8))
+                              ( Encoders.field
+                                  ( Encoders.nonNullable
+                                      (Encoders.array (Encoders.dimension foldl' (Encoders.element (Encoders.nonNullable Encoders.int8))))
+                                  )
+                              )
+                          )
+                      )
+                  )
+              )
+              ( Decoders.singleRow
+                  ( Decoders.column
+                      ( Decoders.nonNullable
+                          ( Decoders.composite
+                              Nothing
+                              typeName
+                              ( (,)
+                                  <$> Decoders.field (Decoders.nonNullable Decoders.int8)
+                                  <*> Decoders.field
+                                    ( Decoders.nonNullable
+                                        (Decoders.array (Decoders.dimension replicateM (Decoders.element (Decoders.nonNullable Decoders.int8))))
+                                    )
+                              )
+                          )
+                      )
+                  )
+              )
+        result `shouldBe` Right (42 :: Int64, [1, 2, 3] :: [Int64])
+
+    it "encodes composite types containing arrays of named composite types" \config -> do
+      innerType <- Scripts.generateSymname
+      outerType <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create inner composite type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", innerType, " as (x int8, y bool)"])
+              mempty
+              Decoders.noResult
+          -- Create outer composite type with array of inner composite
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", outerType, " as (id int8, items ", innerType, "[])"])
+              mempty
+              Decoders.noResult
+          -- Test encoding composite with array of composite field by checking a field value
+          Session.statement (99 :: Int64, [(1 :: Int64, True), (2, False), (3, True)])
+            $ Statement.preparable
+              (mconcat ["select ($1 :: ", outerType, ").id"])
+              ( Encoders.param
+                  ( Encoders.nonNullable
+                      ( Encoders.composite
+                          Nothing
+                          outerType
+                          ( divide
+                              (\(i, items) -> (i, items))
+                              (Encoders.field (Encoders.nonNullable Encoders.int8))
+                              ( Encoders.field
+                                  ( Encoders.nonNullable
+                                      ( Encoders.array
+                                          ( Encoders.dimension
+                                              foldl'
+                                              ( Encoders.element
+                                                  ( Encoders.nonNullable
+                                                      ( Encoders.composite
+                                                          Nothing
+                                                          innerType
+                                                          ( divide
+                                                              (\(x, y) -> (x, y))
+                                                              (Encoders.field (Encoders.nonNullable Encoders.int8))
+                                                              (Encoders.field (Encoders.nonNullable Encoders.bool))
+                                                          )
+                                                      )
+                                                  )
+                                              )
+                                          )
+                                      )
+                                  )
+                              )
+                          )
+                      )
+                  )
+              )
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int8)))
+        result `shouldBe` Right (99 :: Int64)
+
+    it "roundtrips composite types containing arrays of named composite types" \config -> do
+      innerType <- Scripts.generateSymname
+      outerType <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create inner composite type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", innerType, " as (x int8, y bool)"])
+              mempty
+              Decoders.noResult
+          -- Create outer composite type with array of inner composite
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", outerType, " as (id int8, items ", innerType, "[])"])
+              mempty
+              Decoders.noResult
+          -- Test roundtrip
+          Session.statement (99 :: Int64, [(1 :: Int64, True), (2, False), (3, True)])
+            $ Statement.preparable
+              (mconcat ["select $1 :: ", outerType])
+              ( Encoders.param
+                  ( Encoders.nonNullable
+                      ( Encoders.composite
+                          Nothing
+                          outerType
+                          ( divide
+                              (\(i, items) -> (i, items))
+                              (Encoders.field (Encoders.nonNullable Encoders.int8))
+                              ( Encoders.field
+                                  ( Encoders.nonNullable
+                                      ( Encoders.array
+                                          ( Encoders.dimension
+                                              foldl'
+                                              ( Encoders.element
+                                                  ( Encoders.nonNullable
+                                                      ( Encoders.composite
+                                                          Nothing
+                                                          innerType
+                                                          ( divide
+                                                              (\(x, y) -> (x, y))
+                                                              (Encoders.field (Encoders.nonNullable Encoders.int8))
+                                                              (Encoders.field (Encoders.nonNullable Encoders.bool))
+                                                          )
+                                                      )
+                                                  )
+                                              )
+                                          )
+                                      )
+                                  )
+                              )
+                          )
+                      )
+                  )
+              )
+              ( Decoders.singleRow
+                  ( Decoders.column
+                      ( Decoders.nonNullable
+                          ( Decoders.composite
+                              Nothing
+                              outerType
+                              ( (,)
+                                  <$> Decoders.field (Decoders.nonNullable Decoders.int8)
+                                  <*> Decoders.field
+                                    ( Decoders.nonNullable
+                                        ( Decoders.array
+                                            ( Decoders.dimension
+                                                replicateM
+                                                ( Decoders.element
+                                                    ( Decoders.nonNullable
+                                                        ( Decoders.composite
+                                                            Nothing
+                                                            innerType
+                                                            ( (,)
+                                                                <$> Decoders.field (Decoders.nonNullable Decoders.int8)
+                                                                <*> Decoders.field (Decoders.nonNullable Decoders.bool)
+                                                            )
+                                                        )
+                                                    )
+                                                )
+                                            )
+                                        )
+                                    )
+                              )
+                          )
+                      )
+                  )
+              )
+        result `shouldBe` Right (99 :: Int64, [(1 :: Int64, True), (2, False), (3, True)])
+
+    it "encodes composite types with multiple levels of nesting: composite -> array -> composite" \config -> do
+      deepType <- Scripts.generateSymname
+      midType <- Scripts.generateSymname
+      topType <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create deepest composite type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", deepType, " as (value int8)"])
+              mempty
+              Decoders.noResult
+          -- Create middle composite type with array of deep composite
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", midType, " as (data ", deepType, "[])"])
+              mempty
+              Decoders.noResult
+          -- Create top composite type containing middle composite
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", topType, " as (name text, \"nested\" ", midType, ")"])
+              mempty
+              Decoders.noResult
+          -- Test encoding deeply nested structure by extracting a value
+          Session.statement ("test", [1 :: Int64, 2, 3])
+            $ Statement.preparable
+              (mconcat ["select ($1 :: ", topType, ").name"])
+              ( Encoders.param
+                  ( Encoders.nonNullable
+                      ( Encoders.composite
+                          Nothing
+                          topType
+                          ( divide
+                              (\(name, nested) -> (name, nested))
+                              (Encoders.field (Encoders.nonNullable Encoders.text))
+                              ( Encoders.field
+                                  ( Encoders.nonNullable
+                                      ( Encoders.composite
+                                          Nothing
+                                          midType
+                                          ( Encoders.field
+                                              ( Encoders.nonNullable
+                                                  ( Encoders.array
+                                                      ( Encoders.dimension
+                                                          foldl'
+                                                          ( Encoders.element
+                                                              ( Encoders.nonNullable
+                                                                  ( Encoders.composite
+                                                                      Nothing
+                                                                      deepType
+                                                                      (Encoders.field (Encoders.nonNullable Encoders.int8))
+                                                                  )
+                                                              )
+                                                          )
+                                                      )
+                                                  )
+                                              )
+                                          )
+                                      )
+                                  )
+                              )
+                          )
+                      )
+                  )
+              )
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.text)))
+        result `shouldBe` Right "test"
+
+  it "detects attempts to encode non-existent composite types" \config -> do
+    Scripts.onPreparableConnection config \connection -> do
+      result <- Connection.use connection do
+        Session.statement (42 :: Int64, "test")
+          $ Statement.preparable
+            "select $1::nonexistent_composite_type"
+            ( Encoders.param
+                ( Encoders.nonNullable
+                    ( Encoders.composite
+                        Nothing
+                        "nonexistent_composite_type"
+                        ( divide
+                            (\(a, b) -> (a, b))
+                            (Encoders.field (Encoders.nonNullable Encoders.int8))
+                            (Encoders.field (Encoders.nonNullable Encoders.text))
+                        )
+                    )
+                )
+            )
+            (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.text)))
+
+      case result of
+        Left (Errors.SessionUseError (Errors.MissingTypesSessionError missingTypes)) ->
+          missingTypes `shouldBe` HashSet.fromList [(Nothing, "nonexistent_composite_type")]
+        _ ->
+          expectationFailure ("Unexpected result: " <> show result)
diff --git a/src/library-tests/Integration/Sharing/Encoders/CustomSpec.hs b/src/library-tests/Integration/Sharing/Encoders/CustomSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/Encoders/CustomSpec.hs
@@ -0,0 +1,341 @@
+module Integration.Sharing.Encoders.CustomSpec (spec) where
+
+import Data.HashSet qualified as HashSet
+import Data.Text.Encoding (encodeUtf8)
+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.Scripts qualified as Scripts
+import Prelude
+import Test.Hspec
+import TextBuilder qualified
+
+spec :: SpecWith Scripts.ScopeParams
+spec = do
+  describe "Basic custom encoders" do
+    it "encodes a custom type with runtime OID lookup" \config -> do
+      enumName <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create enum type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", enumName, " as enum ('alpha', 'beta', 'gamma')"])
+              mempty
+              Decoders.noResult
+          -- Test custom encoder with runtime OID lookup
+          Session.statement "beta"
+            $ Statement.preparable
+              (mconcat ["select ($1 :: ", enumName, ") = 'beta' :: ", enumName])
+              ( Encoders.param
+                  ( Encoders.nonNullable
+                      ( Encoders.custom
+                          Nothing
+                          enumName
+                          Nothing
+                          []
+                          (\_ val -> encodeUtf8 val)
+                          id
+                      )
+                  )
+              )
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.bool)))
+        result `shouldBe` Right True
+
+    it "encodes a custom type with static OIDs" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Test custom encoder with static OIDs for text (type OID 25, array OID 1009)
+          Session.statement "hello"
+            $ Statement.preparable
+              "select $1::text = 'hello'::text"
+              ( Encoders.param
+                  ( Encoders.nonNullable
+                      ( Encoders.custom
+                          Nothing
+                          "text"
+                          (Just (25, 1009))
+                          []
+                          (\_ val -> encodeUtf8 val)
+                          id
+                      )
+                  )
+              )
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.bool)))
+        result `shouldBe` Right True
+
+    it "encodes with dependent type OID requests" \config -> do
+      enumName <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create enum type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", enumName, " as enum ('small', 'large')"])
+              mempty
+              Decoders.noResult
+          -- Test custom encoder that requests OID of the enum type itself
+          Session.statement "large"
+            $ Statement.preparable
+              (mconcat ["select ($1 :: ", enumName, ") = 'large' :: ", enumName])
+              ( Encoders.param
+                  ( Encoders.nonNullable
+                      ( Encoders.custom
+                          Nothing
+                          enumName
+                          Nothing
+                          [(Nothing, enumName)]
+                          ( \lookupOid val -> do
+                              let (enumOidScalar, _enumOidArray) = lookupOid (Nothing, enumName)
+                              -- Verify we got a valid OID (non-zero)
+                              if enumOidScalar > 0
+                                then encodeUtf8 val
+                                else error "Failed to resolve enum OID"
+                          )
+                          id
+                      )
+                  )
+              )
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.bool)))
+        result `shouldBe` Right True
+
+  describe "Error handling" do
+    it "detects missing types in custom encoders" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          Session.statement "test_value"
+            $ Statement.preparable
+              "select $1"
+              ( Encoders.param
+                  ( Encoders.nonNullable
+                      ( Encoders.custom
+                          Nothing
+                          "nonexistent_custom_type"
+                          Nothing
+                          []
+                          (\_ val -> encodeUtf8 val)
+                          id
+                      )
+                  )
+              )
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.text)))
+
+        case result of
+          Left (Errors.SessionUseError (Errors.MissingTypesSessionError missingTypes)) ->
+            missingTypes `shouldBe` HashSet.fromList [(Nothing, "nonexistent_custom_type")]
+          _ ->
+            expectationFailure ("Unexpected result: " <> show result)
+
+    it "detects missing dependent types in custom encoders" \config -> do
+      customTypeName <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create a custom type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", customTypeName, " as (id int4)"])
+              mempty
+              Decoders.noResult
+          -- Try to encode it but request a non-existent dependent type
+          Session.statement (42 :: Int32)
+            $ Statement.preparable
+              (mconcat ["select $1 :: ", customTypeName])
+              ( Encoders.param
+                  ( Encoders.nonNullable
+                      ( Encoders.custom
+                          Nothing
+                          customTypeName
+                          Nothing
+                          [(Nothing, "nonexistent_dependency")]
+                          (\_ val -> encodeUtf8 (TextBuilder.toText (TextBuilder.decimal val)))
+                          (TextBuilder.toText . TextBuilder.decimal)
+                      )
+                  )
+              )
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.text)))
+
+        case result of
+          Left (Errors.SessionUseError (Errors.MissingTypesSessionError missingTypes)) ->
+            missingTypes `shouldBe` HashSet.fromList [(Nothing, "nonexistent_dependency")]
+          _ ->
+            expectationFailure ("Unexpected result: " <> show result)
+
+  describe "Roundtrip tests" do
+    it "roundtrips custom encoded and decoded values" \config -> do
+      enumName <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create enum type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", enumName, " as enum ('one', 'two', 'three')"])
+              mempty
+              Decoders.noResult
+          -- Test roundtrip using custom encoder and decoder
+          Session.statement "three"
+            $ Statement.preparable
+              (mconcat ["select $1 :: ", enumName])
+              ( Encoders.param
+                  ( Encoders.nonNullable
+                      ( Encoders.custom
+                          Nothing
+                          enumName
+                          Nothing
+                          []
+                          (\_ val -> encodeUtf8 val)
+                          id
+                      )
+                  )
+              )
+              ( Decoders.singleRow
+                  ( Decoders.column
+                      ( Decoders.nonNullable
+                          ( Decoders.custom
+                              Nothing
+                              enumName
+                              Nothing
+                              []
+                              (\_ bytes -> Right bytes)
+                          )
+                      )
+                  )
+              )
+        result `shouldBe` Right "three"
+
+    it "roundtrips multiple values" \config -> do
+      enumName <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create enum type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", enumName, " as enum ('first', 'second', 'third')"])
+              mempty
+              Decoders.noResult
+          -- Test roundtrip for multiple values
+          r1 <-
+            Session.statement "first"
+              $ Statement.preparable
+                (mconcat ["select $1 :: ", enumName])
+                ( Encoders.param
+                    ( Encoders.nonNullable
+                        ( Encoders.custom
+                            Nothing
+                            enumName
+                            Nothing
+                            []
+                            (\_ val -> encodeUtf8 val)
+                            id
+                        )
+                    )
+                )
+                ( Decoders.singleRow
+                    ( Decoders.column
+                        ( Decoders.nonNullable
+                            ( Decoders.custom
+                                Nothing
+                                enumName
+                                Nothing
+                                []
+                                (\_ bytes -> Right bytes)
+                            )
+                        )
+                    )
+                )
+          r2 <-
+            Session.statement "third"
+              $ Statement.preparable
+                (mconcat ["select $1 :: ", enumName])
+                ( Encoders.param
+                    ( Encoders.nonNullable
+                        ( Encoders.custom
+                            Nothing
+                            enumName
+                            Nothing
+                            []
+                            (\_ val -> encodeUtf8 val)
+                            id
+                        )
+                    )
+                )
+                ( Decoders.singleRow
+                    ( Decoders.column
+                        ( Decoders.nonNullable
+                            ( Decoders.custom
+                                Nothing
+                                enumName
+                                Nothing
+                                []
+                                (\_ bytes -> Right bytes)
+                            )
+                        )
+                    )
+                )
+          return (r1, r2)
+        result `shouldBe` Right ("first", "third")
+
+  describe "Schema-qualified types" do
+    it "encodes custom types from specific schemas" \config -> do
+      schemaName <- Scripts.generateSymname
+      typeName <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create schema
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create schema ", schemaName])
+              mempty
+              Decoders.noResult
+          -- Create enum type in that schema
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", schemaName, ".", typeName, " as enum ('x', 'y', 'z')"])
+              mempty
+              Decoders.noResult
+          -- Test custom encoder with schema qualification
+          Session.statement "z"
+            $ Statement.preparable
+              (mconcat ["select ($1 :: ", schemaName, ".", typeName, ") = 'z' :: ", schemaName, ".", typeName])
+              ( Encoders.param
+                  ( Encoders.nonNullable
+                      ( Encoders.custom
+                          (Just schemaName)
+                          typeName
+                          Nothing
+                          []
+                          (\_ val -> encodeUtf8 val)
+                          id
+                      )
+                  )
+              )
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.bool)))
+        result `shouldBe` Right True
+
+    it "detects missing types in non-existent schemas" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          Session.statement "test"
+            $ Statement.preparable
+              "select $1"
+              ( Encoders.param
+                  ( Encoders.nonNullable
+                      ( Encoders.custom
+                          (Just "nonexistent_schema")
+                          "nonexistent_type"
+                          Nothing
+                          []
+                          (\_ val -> encodeUtf8 val)
+                          id
+                      )
+                  )
+              )
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.text)))
+
+        case result of
+          Left (Errors.SessionUseError (Errors.MissingTypesSessionError missingTypes)) ->
+            missingTypes `shouldBe` HashSet.fromList [(Just "nonexistent_schema", "nonexistent_type")]
+          _ ->
+            expectationFailure ("Unexpected result: " <> show result)
diff --git a/src/library-tests/Integration/Sharing/Encoders/DomainSpec.hs b/src/library-tests/Integration/Sharing/Encoders/DomainSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/Encoders/DomainSpec.hs
@@ -0,0 +1,151 @@
+module Integration.Sharing.Encoders.DomainSpec (spec) where
+
+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.Scripts qualified as Scripts
+import Prelude
+import Test.Hspec
+
+spec :: SpecWith Scripts.ScopeParams
+spec = do
+  describe "Domain type encoding" do
+    describe "Simple scalar domains" do
+      it "encodes a domain based on int8 using int8 codec" \config -> do
+        domainName <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            -- Create domain type
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create domain ", domainName, " as int8"])
+                mempty
+                Decoders.noResult
+            -- Test encoding by comparing with static value
+            Session.statement (42 :: Int64)
+              $ Statement.preparable
+                (mconcat ["select ($1 :: ", domainName, ") = 42"])
+                (Encoders.param (Encoders.nonNullable Encoders.int8))
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.bool)))
+          result `shouldBe` Right True
+
+      it "encodes a domain based on text using text codec" \config -> do
+        domainName <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            -- Create domain type
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create domain ", domainName, " as text"])
+                mempty
+                Decoders.noResult
+            -- Test encoding by comparing with static value
+            Session.statement ("hello" :: Text)
+              $ Statement.preparable
+                (mconcat ["select ($1 :: ", domainName, ") = 'hello'"])
+                (Encoders.param (Encoders.nonNullable Encoders.text))
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.bool)))
+          result `shouldBe` Right True
+
+      it "encodes a domain based on bool using bool codec" \config -> do
+        domainName <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            -- Create domain type
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create domain ", domainName, " as bool"])
+                mempty
+                Decoders.noResult
+            -- Test encoding by comparing with static value
+            Session.statement True
+              $ Statement.preparable
+                (mconcat ["select ($1 :: ", domainName, ") = true"])
+                (Encoders.param (Encoders.nonNullable Encoders.bool))
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.bool)))
+          result `shouldBe` Right True
+
+    describe "Domains with constraints" do
+      it "encodes values that satisfy domain constraints" \config -> do
+        domainName <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            -- Create domain type with constraint
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create domain ", domainName, " as int8 check (value > 0)"])
+                mempty
+                Decoders.noResult
+            -- Test encoding a value that satisfies the constraint
+            Session.statement (42 :: Int64)
+              $ Statement.preparable
+                (mconcat ["select ($1 :: ", domainName, ") = 42"])
+                (Encoders.param (Encoders.nonNullable Encoders.int8))
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.bool)))
+          result `shouldBe` Right True
+
+    describe "Domain type cast compatibility for composite usage" do
+      it "encodes base type value that can be used in composite with domain field via explicit cast" \config -> do
+        domainName <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            -- Create domain type
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create domain ", domainName, " as int8"])
+                mempty
+                Decoders.noResult
+            -- Encode int8, cast it to domain, and use in ROW constructor
+            Session.statement (42 :: Int64)
+              $ Statement.preparable
+                (mconcat ["select ($1 :: ", domainName, ") = 42"])
+                (Encoders.param (Encoders.nonNullable Encoders.int8))
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.bool)))
+          result `shouldBe` Right True
+
+    describe "Domain type cast compatibility for array usage" do
+      it "encodes base type array that can be cast to domain array" \config -> do
+        domainName <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            -- Create domain type
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create domain ", domainName, " as int8"])
+                mempty
+                Decoders.noResult
+            -- Encode int8 array using base codec and verify it works
+            Session.statement ([1, 2, 3] :: [Int64])
+              $ Statement.preparable
+                "select $1 = ARRAY[1,2,3] :: int8[]"
+                ( Encoders.param
+                    ( Encoders.nonNullable
+                        (Encoders.foldableArray (Encoders.nonNullable Encoders.int8))
+                    )
+                )
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.bool)))
+          result `shouldBe` Right True
+
+      it "encodes text array that can be used with text domain" \config -> do
+        domainName <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          result <- Connection.use connection do
+            -- Create domain type
+            Session.statement ()
+              $ Statement.preparable
+                (mconcat ["create domain ", domainName, " as text"])
+                mempty
+                Decoders.noResult
+            -- Encode text array using base codec
+            Session.statement (["a", "b", "c"] :: [Text])
+              $ Statement.preparable
+                "select $1 = ARRAY['a','b','c'] :: text[]"
+                ( Encoders.param
+                    ( Encoders.nonNullable
+                        (Encoders.foldableArray (Encoders.nonNullable Encoders.text))
+                    )
+                )
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.bool)))
+          result `shouldBe` Right True
diff --git a/src/library-tests/Integration/Sharing/Encoders/EnumSpec.hs b/src/library-tests/Integration/Sharing/Encoders/EnumSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/Encoders/EnumSpec.hs
@@ -0,0 +1,315 @@
+module Integration.Sharing.Encoders.EnumSpec (spec) where
+
+import Data.HashSet qualified as HashSet
+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.Scripts qualified as Scripts
+import Prelude
+import Test.Hspec
+
+spec :: SpecWith Scripts.ScopeParams
+spec = do
+  describe "Simple enums" do
+    it "encodes a simple named enum and compares with static value" \config -> do
+      enumName <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create enum type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", enumName, " as enum ('sad', 'ok', 'happy')"])
+              mempty
+              Decoders.noResult
+          -- Test encoding by comparing with static value
+          Session.statement "ok"
+            $ Statement.preparable
+              (mconcat ["select ($1 :: ", enumName, ") = 'ok' :: ", enumName])
+              (Encoders.param (Encoders.nonNullable (Encoders.enum Nothing enumName id)))
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.bool)))
+        result `shouldBe` Right True
+
+    it "encodes and roundtrips a simple named enum" \config -> do
+      enumName <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create enum type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", enumName, " as enum ('sad', 'ok', 'happy')"])
+              mempty
+              Decoders.noResult
+          -- Test roundtrip
+          Session.statement "happy"
+            $ Statement.preparable
+              (mconcat ["select $1 :: ", enumName])
+              (Encoders.param (Encoders.nonNullable (Encoders.enum Nothing enumName id)))
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable (Decoders.enum Nothing enumName (Just . id)))))
+        result `shouldBe` Right "happy"
+
+  describe "Enums in composites" do
+    it "encodes enums nested in named composites" \config -> do
+      enumName <- Scripts.generateSymname
+      compositeName <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create enum type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", enumName, " as enum ('red', 'green', 'blue')"])
+              mempty
+              Decoders.noResult
+          -- Create composite type with enum
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", compositeName, " as (id int8, color ", enumName, ")"])
+              mempty
+              Decoders.noResult
+          -- Test encoding
+          Session.statement (42 :: Int64, "green")
+            $ Statement.preparable
+              (mconcat ["select ($1 :: ", compositeName, ") = (42, 'green') :: ", compositeName])
+              ( Encoders.param
+                  ( Encoders.nonNullable
+                      ( Encoders.composite
+                          Nothing
+                          compositeName
+                          ( divide
+                              (\(a, b) -> (a, b))
+                              (Encoders.field (Encoders.nonNullable Encoders.int8))
+                              (Encoders.field (Encoders.nonNullable (Encoders.enum Nothing enumName id)))
+                          )
+                      )
+                  )
+              )
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.bool)))
+        result `shouldBe` Right True
+
+    it "roundtrips enums nested in named composites" \config -> do
+      enumName <- Scripts.generateSymname
+      compositeName <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create enum type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", enumName, " as enum ('red', 'green', 'blue')"])
+              mempty
+              Decoders.noResult
+          -- Create composite type with enum
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", compositeName, " as (id int8, color ", enumName, ")"])
+              mempty
+              Decoders.noResult
+          -- Test roundtrip
+          Session.statement (42 :: Int64, "blue")
+            $ Statement.preparable
+              (mconcat ["select $1 :: ", compositeName])
+              ( Encoders.param
+                  ( Encoders.nonNullable
+                      ( Encoders.composite
+                          Nothing
+                          compositeName
+                          ( divide
+                              (\(a, b) -> (a, b))
+                              (Encoders.field (Encoders.nonNullable Encoders.int8))
+                              (Encoders.field (Encoders.nonNullable (Encoders.enum Nothing enumName id)))
+                          )
+                      )
+                  )
+              )
+              ( Decoders.singleRow
+                  ( Decoders.column
+                      ( Decoders.nonNullable
+                          ( Decoders.composite
+                              Nothing
+                              compositeName
+                              ( (,)
+                                  <$> Decoders.field (Decoders.nonNullable Decoders.int8)
+                                  <*> Decoders.field (Decoders.nonNullable (Decoders.enum Nothing enumName (Just . id)))
+                              )
+                          )
+                      )
+                  )
+              )
+        result `shouldBe` Right (42 :: Int64, "blue")
+
+  describe "Arrays of enums" do
+    it "encodes arrays of named enums" \config -> do
+      enumName <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create enum type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", enumName, " as enum ('small', 'medium', 'large')"])
+              mempty
+              Decoders.noResult
+          -- Test array encoding
+          Session.statement ["small", "large", "medium"]
+            $ Statement.preparable
+              (mconcat ["select ($1 :: ", enumName, "[]) = array['small', 'large', 'medium'] :: ", enumName, "[]"])
+              ( Encoders.param
+                  ( Encoders.nonNullable
+                      ( Encoders.array
+                          ( Encoders.dimension
+                              foldl'
+                              (Encoders.element (Encoders.nonNullable (Encoders.enum Nothing enumName id)))
+                          )
+                      )
+                  )
+              )
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.bool)))
+        result `shouldBe` Right True
+
+    it "roundtrips arrays of named enums" \config -> do
+      enumName <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create enum type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", enumName, " as enum ('alpha', 'beta', 'gamma')"])
+              mempty
+              Decoders.noResult
+          -- Test roundtrip
+          Session.statement ["beta", "alpha", "gamma"]
+            $ Statement.preparable
+              (mconcat ["select $1 :: ", enumName, "[]"])
+              ( Encoders.param
+                  ( Encoders.nonNullable
+                      ( Encoders.array
+                          ( Encoders.dimension
+                              foldl'
+                              (Encoders.element (Encoders.nonNullable (Encoders.enum Nothing enumName id)))
+                          )
+                      )
+                  )
+              )
+              ( Decoders.singleRow
+                  ( Decoders.column
+                      ( Decoders.nonNullable
+                          ( Decoders.array
+                              ( Decoders.dimension
+                                  replicateM
+                                  (Decoders.element (Decoders.nonNullable (Decoders.enum Nothing enumName (Just . id))))
+                              )
+                          )
+                      )
+                  )
+              )
+        result `shouldBe` Right ["beta", "alpha", "gamma"]
+
+  describe "OID lookup verification" do
+    it "requests OID for named enums (verified by successful execution)" \config -> do
+      -- This test verifies that OID lookup happens by ensuring a named enum
+      -- type works correctly - if OID lookup didn't happen, the statement would fail
+      enumName <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Create enum type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", enumName, " as enum ('first', 'second')"])
+              mempty
+              Decoders.noResult
+          -- Use named enum - this requires OID lookup to succeed
+          Session.statement "second"
+            $ Statement.preparable
+              (mconcat ["select $1 :: ", enumName])
+              (Encoders.param (Encoders.nonNullable (Encoders.enum Nothing enumName id)))
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable (Decoders.enum Nothing enumName (Just . id)))))
+        result `shouldBe` Right "second"
+
+  it "handles enum encoding and decoding" \config -> do
+    name <- Scripts.generateSymname
+    Scripts.onPreparableConnection config \connection -> do
+      result <- Connection.use connection do
+        -- First create the enum type
+        Session.statement ()
+          $ Statement.preparable
+            (mconcat ["create type ", name, " as enum ('sad', 'ok', 'happy')"])
+            mempty
+            Decoders.noResult
+        -- Then test encoding and decoding
+        Session.statement "ok"
+          $ Statement.preparable
+            (mconcat ["select ($1 :: ", name, ")"])
+            (Encoders.param (Encoders.nonNullable (Encoders.enum Nothing name id)))
+            (Decoders.singleRow (Decoders.column (Decoders.nonNullable (Decoders.enum Nothing name (Just . id)))))
+      result `shouldBe` Right "ok"
+
+  it "detects attempts to encode non-existent enum types" \config -> do
+    Scripts.onPreparableConnection config \connection -> do
+      result <- Connection.use connection do
+        Session.statement "test_value"
+          $ Statement.preparable
+            "select $1"
+            (Encoders.param (Encoders.nonNullable (Encoders.enum Nothing "this_enum_does_not_exist_in_db" id)))
+            (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.text)))
+
+      case result of
+        Left (Errors.SessionUseError (Errors.MissingTypesSessionError missingTypes)) ->
+          missingTypes `shouldBe` HashSet.fromList [(Nothing, "this_enum_does_not_exist_in_db")]
+        _ ->
+          expectationFailure ("Unexpected result: " <> show result)
+
+  describe "Namespaced" do
+    it "detects attempts to use non-existent type in non-existent schema" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          Session.statement "test"
+            $ Statement.preparable
+              "select $1::nonexistent_schema.nonexistent_type"
+              (Encoders.param (Encoders.nonNullable (Encoders.enum (Just "nonexistent_schema") "nonexistent_type" id)))
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.text)))
+
+        case result of
+          Left (Errors.SessionUseError (Errors.MissingTypesSessionError missingTypes)) ->
+            missingTypes `shouldBe` HashSet.fromList [(Just "nonexistent_schema", "nonexistent_type")]
+          _ ->
+            expectationFailure ("Unexpected result: " <> show result)
+
+    it "detects attempts to use non-existent type in existing schema" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          Session.statement "test"
+            $ Statement.preparable
+              "select $1::public.this_type_does_not_exist"
+              (Encoders.param (Encoders.nonNullable (Encoders.enum (Just "public") "this_type_does_not_exist" id)))
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.text)))
+
+        -- The statement should fail when trying to use a non-existent type in existing schema
+        case result of
+          Left (Errors.SessionUseError (Errors.MissingTypesSessionError missingTypes)) -> do
+            missingTypes `shouldBe` HashSet.fromList [(Just "public", "this_type_does_not_exist")]
+          _ ->
+            expectationFailure ("Unexpected result: " <> show result)
+
+  it "detects attempts to encode arrays of non-existent enum types" \config -> do
+    Scripts.onPreparableConnection config \connection -> do
+      result <- Connection.use connection do
+        Session.statement ["val1", "val2"]
+          $ Statement.preparable
+            "select $1::nonexistent_array_enum[]"
+            ( Encoders.param
+                ( Encoders.nonNullable
+                    ( Encoders.array
+                        ( Encoders.dimension
+                            foldl'
+                            (Encoders.element (Encoders.nonNullable (Encoders.enum Nothing "nonexistent_array_enum" id)))
+                        )
+                    )
+                )
+            )
+            (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.text)))
+
+      case result of
+        Left (Errors.SessionUseError (Errors.MissingTypesSessionError missingTypes)) ->
+          missingTypes `shouldBe` HashSet.fromList [(Nothing, "nonexistent_array_enum")]
+        _ ->
+          expectationFailure ("Unexpected result: " <> show result)
diff --git a/src/library-tests/Integration/Sharing/Encoders/HstoreSpec.hs b/src/library-tests/Integration/Sharing/Encoders/HstoreSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/Encoders/HstoreSpec.hs
@@ -0,0 +1,141 @@
+module Integration.Sharing.Encoders.HstoreSpec (spec) where
+
+import Data.HashMap.Strict qualified as HashMap
+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.Scripts qualified as Scripts
+import Prelude
+import Test.Hspec
+
+spec :: SpecWith Scripts.ScopeParams
+spec = do
+  describe "Hstore Encoders" do
+    it "encodes empty hstore" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Enable hstore extension (unprepared), ignore if already exists
+          catchError
+            ( Session.statement ()
+                $ Statement.unpreparable
+                  "CREATE EXTENSION IF NOT EXISTS hstore"
+                  Encoders.noParams
+                  Decoders.noResult
+            )
+            (const (pure ()))
+          -- Test encoding empty hstore
+          Session.statement
+            ([] :: [(Text, Maybe Text)])
+            $ Statement.preparable
+              "select $1::hstore = ''::hstore"
+              (Encoders.param (Encoders.nonNullable Encoders.hstore))
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.bool)))
+        result `shouldBe` Right True
+
+    it "encodes hstore with single key-value pair" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Enable hstore extension (unprepared), ignore if already exists
+          catchError
+            ( Session.statement ()
+                $ Statement.unpreparable
+                  "CREATE EXTENSION IF NOT EXISTS hstore"
+                  Encoders.noParams
+                  Decoders.noResult
+            )
+            (const (pure ()))
+          -- Test encoding single key-value pair
+          Session.statement
+            [("key", Just "value")]
+            $ Statement.preparable
+              "select $1::hstore = 'key => value'::hstore"
+              (Encoders.param (Encoders.nonNullable Encoders.hstore))
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.bool)))
+        result `shouldBe` Right True
+
+    it "encodes hstore with multiple key-value pairs" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Enable hstore extension (unprepared), ignore if already exists
+          catchError
+            ( Session.statement ()
+                $ Statement.unpreparable
+                  "CREATE EXTENSION IF NOT EXISTS hstore"
+                  Encoders.noParams
+                  Decoders.noResult
+            )
+            (const (pure ()))
+          -- Test encoding multiple key-value pairs
+          Session.statement
+            [("a", Just "1"), ("b", Just "2"), ("c", Just "3")]
+            $ Statement.preparable
+              "select $1::hstore @> 'a => 1'::hstore AND $1::hstore @> 'b => 2'::hstore AND $1::hstore @> 'c => 3'::hstore"
+              (Encoders.param (Encoders.nonNullable Encoders.hstore))
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.bool)))
+        result `shouldBe` Right True
+
+    it "encodes hstore with null values" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Enable hstore extension (unprepared), ignore if already exists
+          catchError
+            ( Session.statement ()
+                $ Statement.unpreparable
+                  "CREATE EXTENSION IF NOT EXISTS hstore"
+                  Encoders.noParams
+                  Decoders.noResult
+            )
+            (const (pure ()))
+          -- Test encoding hstore with null values
+          Session.statement
+            [("key1", Just "value1"), ("key2", Nothing), ("key3", Just "value3")]
+            $ Statement.preparable
+              "select $1::hstore = 'key1 => value1, key2 => NULL, key3 => value3'::hstore"
+              (Encoders.param (Encoders.nonNullable Encoders.hstore))
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.bool)))
+        result `shouldBe` Right True
+
+    it "roundtrips hstore correctly" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        let testData = HashMap.fromList [("key1", Just "value1"), ("key2", Nothing), ("key3", Just "value3")]
+        result <- Connection.use connection do
+          -- Enable hstore extension (unprepared), ignore if already exists
+          catchError
+            ( Session.statement ()
+                $ Statement.unpreparable
+                  "CREATE EXTENSION IF NOT EXISTS hstore"
+                  Encoders.noParams
+                  Decoders.noResult
+            )
+            (const (pure ()))
+          -- Test roundtrip
+          Session.statement
+            (HashMap.toList testData)
+            $ Statement.preparable
+              "select $1"
+              (Encoders.param (Encoders.nonNullable Encoders.hstore))
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable (Decoders.hstore (\n f -> replicateM n f >>= pure . HashMap.fromList)))))
+        result `shouldBe` Right testData
+
+    it "encodes hstore with special characters" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- Enable hstore extension (unprepared), ignore if already exists
+          catchError
+            ( Session.statement ()
+                $ Statement.unpreparable
+                  "CREATE EXTENSION IF NOT EXISTS hstore"
+                  Encoders.noParams
+                  Decoders.noResult
+            )
+            (const (pure ()))
+          -- Test encoding hstore with special characters
+          Session.statement
+            [("key with spaces", Just "value with quotes")]
+            $ Statement.preparable
+              "select $1::hstore = '\"key with spaces\" => \"value with quotes\"'::hstore"
+              (Encoders.param (Encoders.nonNullable Encoders.hstore))
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.bool)))
+        result `shouldBe` Right True
diff --git a/src/library-tests/Integration/Sharing/Encoders/InetSpec.hs b/src/library-tests/Integration/Sharing/Encoders/InetSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/Encoders/InetSpec.hs
@@ -0,0 +1,74 @@
+module Integration.Sharing.Encoders.InetSpec (spec) where
+
+import Data.IP (IPv4, IPv6)
+import Data.IP qualified as IP
+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.Scripts qualified as Scripts
+import Prelude
+import Test.Hspec
+
+spec :: SpecWith Scripts.ScopeParams
+spec = do
+  describe "INET Encoders" do
+    it "encodes IPv4 address correctly" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        let statement =
+              Statement.preparable
+                "select $1 = '192.168.1.1/32'::inet"
+                (Encoders.param (Encoders.nonNullable Encoders.inet))
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.bool)))
+            testAddr = read "192.168.1.1" :: IPv4
+            testRange = IP.makeAddrRange testAddr 32
+        result <- Connection.use connection (Session.statement (IP.IPv4Range testRange) statement)
+        result `shouldBe` Right True
+
+    it "roundtrips IPv4 CIDR" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        let statement =
+              Statement.preparable
+                "select $1"
+                (Encoders.param (Encoders.nonNullable Encoders.inet))
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.inet)))
+            testAddr = read "10.0.0.0" :: IPv4
+            testRange = IP.makeAddrRange testAddr 8
+        result <- Connection.use connection (Session.statement (IP.IPv4Range testRange) statement)
+        result `shouldBe` Right (IP.IPv4Range testRange)
+
+    it "roundtrips IPv6 address" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        let statement =
+              Statement.preparable
+                "select $1"
+                (Encoders.param (Encoders.nonNullable Encoders.inet))
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.inet)))
+            testAddr = read "2001:db8::1" :: IPv6
+            testRange = IP.makeAddrRange testAddr 128
+        result <- Connection.use connection (Session.statement (IP.IPv6Range testRange) statement)
+        result `shouldBe` Right (IP.IPv6Range testRange)
+
+  describe "MACADDR Encoders" do
+    it "encodes MAC address correctly" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        let statement =
+              Statement.preparable
+                "select $1 = '08:00:2b:01:02:03'::macaddr"
+                (Encoders.param (Encoders.nonNullable Encoders.macaddr))
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.bool)))
+            testMac = (0x08, 0x00, 0x2b, 0x01, 0x02, 0x03)
+        result <- Connection.use connection (Session.statement testMac statement)
+        result `shouldBe` Right True
+
+    it "roundtrips MAC address" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        let statement =
+              Statement.preparable
+                "select $1"
+                (Encoders.param (Encoders.nonNullable Encoders.macaddr))
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.macaddr)))
+            testMac = (0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff)
+        result <- Connection.use connection (Session.statement testMac statement)
+        result `shouldBe` Right testMac
diff --git a/src/library-tests/Integration/Sharing/Encoders/IntervalSpec.hs b/src/library-tests/Integration/Sharing/Encoders/IntervalSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/Encoders/IntervalSpec.hs
@@ -0,0 +1,33 @@
+module Integration.Sharing.Encoders.IntervalSpec (spec) where
+
+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.Scripts qualified as Scripts
+import Prelude
+import Test.Hspec
+
+spec :: SpecWith Scripts.ScopeParams
+spec = do
+  describe "Interval Encoders" do
+    it "encodes intervals correctly" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        let statement =
+              Statement.preparable
+                "select $1 = interval '10 seconds'"
+                (Encoders.param (Encoders.nonNullable Encoders.interval))
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.bool)))
+        result <- Connection.use connection (Session.statement (10 :: DiffTime) statement)
+        result `shouldBe` Right True
+
+    it "roundtrips intervals correctly" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        let statement =
+              Statement.preparable
+                "select $1"
+                (Encoders.param (Encoders.nonNullable Encoders.interval))
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.interval)))
+        result <- Connection.use connection (Session.statement (10 :: DiffTime) statement)
+        result `shouldBe` Right (10 :: DiffTime)
diff --git a/src/library-tests/Integration/Sharing/Encoders/JsonSpec.hs b/src/library-tests/Integration/Sharing/Encoders/JsonSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/Encoders/JsonSpec.hs
@@ -0,0 +1,63 @@
+module Integration.Sharing.Encoders.JsonSpec (spec) where
+
+import Data.Aeson qualified as Aeson
+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.Scripts qualified as Scripts
+import Prelude
+import Test.Hspec
+
+spec :: SpecWith Scripts.ScopeParams
+spec = do
+  describe "JSON Encoders" do
+    it "encodes JSON object correctly" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        let statement =
+              Statement.preparable
+                "select $1::json"
+                (Encoders.param (Encoders.nonNullable Encoders.json))
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.json)))
+            testValue = Aeson.object [("key", Aeson.String "value")]
+        result <- Connection.use connection (Session.statement testValue statement)
+        result `shouldBe` Right testValue
+
+    it "roundtrips JSON array" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        let statement =
+              Statement.preparable
+                "select $1"
+                (Encoders.param (Encoders.nonNullable Encoders.json))
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.json)))
+            testValue = Aeson.Array (fromList [Aeson.Number 1, Aeson.Number 2])
+        result <- Connection.use connection (Session.statement testValue statement)
+        result `shouldBe` Right testValue
+
+  describe "JSONB Encoders" do
+    it "encodes JSONB object correctly" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        let statement =
+              Statement.preparable
+                "select $1::jsonb"
+                (Encoders.param (Encoders.nonNullable Encoders.jsonb))
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.jsonb)))
+            testValue = Aeson.object [("name", Aeson.String "test"), ("value", Aeson.Number 123)]
+        result <- Connection.use connection (Session.statement testValue statement)
+        result `shouldBe` Right testValue
+
+    it "roundtrips JSONB with nested structure" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        let statement =
+              Statement.preparable
+                "select $1"
+                (Encoders.param (Encoders.nonNullable Encoders.jsonb))
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.jsonb)))
+            testValue =
+              Aeson.object
+                [ ("array", Aeson.Array (fromList [Aeson.Number 1, Aeson.Number 2])),
+                  ("nested", Aeson.object [("inner", Aeson.String "value")])
+                ]
+        result <- Connection.use connection (Session.statement testValue statement)
+        result `shouldBe` Right testValue
diff --git a/src/library-tests/Integration/Sharing/Encoders/UnknownSpec.hs b/src/library-tests/Integration/Sharing/Encoders/UnknownSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/Encoders/UnknownSpec.hs
@@ -0,0 +1,33 @@
+{-# OPTIONS_GHC -Wno-deprecations #-}
+
+module Integration.Sharing.Encoders.UnknownSpec (spec) where
+
+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.Scripts qualified as Scripts
+import Prelude
+import Test.Hspec
+
+spec :: SpecWith Scripts.ScopeParams
+spec = do
+  describe "Unknown Type Encoders" do
+    it "handles unknown type encoding" \config -> do
+      name <- Scripts.generateSymname
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection do
+          -- First create the enum type
+          Session.statement ()
+            $ Statement.preparable
+              (mconcat ["create type ", name, " as enum ('sad', 'ok', 'happy')"])
+              mempty
+              Decoders.noResult
+          -- Then test encoding
+          Session.statement "ok"
+            $ Statement.preparable
+              (mconcat ["select $1 = ('ok' :: ", name, ")"])
+              (Encoders.param (Encoders.nonNullable Encoders.unknown))
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.bool)))
+        result `shouldBe` Right True
diff --git a/src/library-tests/Integration/Sharing/Encoders/UuidSpec.hs b/src/library-tests/Integration/Sharing/Encoders/UuidSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/Encoders/UuidSpec.hs
@@ -0,0 +1,50 @@
+module Integration.Sharing.Encoders.UuidSpec (spec) where
+
+import Data.UUID qualified as UUID
+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.Scripts qualified as Scripts
+import Prelude
+import Test.Hspec
+
+spec :: SpecWith Scripts.ScopeParams
+spec = do
+  describe "UUID Encoders" do
+    it "encodes UUID correctly" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        let statement =
+              Statement.preparable
+                "select $1 = '550e8400-e29b-41d4-a716-446655440000'::uuid"
+                (Encoders.param (Encoders.nonNullable Encoders.uuid))
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.bool)))
+        case UUID.fromString "550e8400-e29b-41d4-a716-446655440000" of
+          Just testUuid -> do
+            result <- Connection.use connection (Session.statement testUuid statement)
+            result `shouldBe` Right True
+          Nothing -> expectationFailure "Failed to parse test UUID"
+
+    it "roundtrips UUID correctly" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        let statement =
+              Statement.preparable
+                "select $1"
+                (Encoders.param (Encoders.nonNullable Encoders.uuid))
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.uuid)))
+        case UUID.fromString "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11" of
+          Just testUuid -> do
+            result <- Connection.use connection (Session.statement testUuid statement)
+            result `shouldBe` Right testUuid
+          Nothing -> expectationFailure "Failed to parse test UUID"
+
+    it "encodes nil UUID correctly" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        let statement =
+              Statement.preparable
+                "select $1"
+                (Encoders.param (Encoders.nonNullable Encoders.uuid))
+                (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.uuid)))
+        result <- Connection.use connection (Session.statement UUID.nil statement)
+        result `shouldBe` Right UUID.nil
diff --git a/src/library-tests/Integration/Sharing/ErrorsSpec.hs b/src/library-tests/Integration/Sharing/ErrorsSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/ErrorsSpec.hs
@@ -0,0 +1,262 @@
+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
+import Hasql.Statement qualified as Statement
+import Helpers.Scripts qualified as Scripts
+import Prelude
+import Test.Hspec
+
+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
+        forM_ [False, True] \preparable -> do
+          describe (if preparable then "Preparable" else "Unpreparable") do
+            it "gets reported properly" \config -> do
+              Scripts.onPreparableConnection config \connection -> do
+                result <- Connection.use connection do
+                  let statement =
+                        if preparable
+                          then Statement.preparable "-" mempty Decoders.noResult
+                          else Statement.unpreparable "-" mempty Decoders.noResult
+                  if inPipeline
+                    then Session.pipeline (Pipeline.statement () statement)
+                    else Session.statement () statement
+
+                shouldBe
+                  result
+                  ( Left
+                      ( Errors.SessionUseError
+                          $ (Errors.StatementSessionError 1 0 "-" [] preparable)
+                            ( Errors.ServerStatementError
+                                ( Errors.ServerError
+                                    "42601"
+                                    "syntax error at or near \"-\""
+                                    Nothing
+                                    Nothing
+                                    (Just 1)
+                                )
+                            )
+                      )
+                  )
+
+  describe "Decoder mismatches" $ parallel do
+    decoderMismatchByPreparedStatusAndExecutor True "Session" (Session.statement ())
+    decoderMismatchByPreparedStatusAndExecutor False "Session" (Session.statement ())
+    decoderMismatchByPreparedStatusAndExecutor True "Pipeline" (Session.pipeline . Pipeline.statement ())
+    decoderMismatchByPreparedStatusAndExecutor False "Pipeline" (Session.pipeline . Pipeline.statement ())
+
+decoderMismatchByPreparedStatusAndExecutor ::
+  Bool ->
+  Text ->
+  (forall a. (Show a) => Statement.Statement () a -> Session.Session a) ->
+  SpecWith Scripts.ScopeParams
+decoderMismatchByPreparedStatusAndExecutor preparable executorName executor = do
+  describe (if preparable then "Preparable" else "Unpreparable") do
+    describe (toList executorName) do
+      describe "UnexpectedColumnCount" do
+        it "gets reported when result has more columns" \config -> do
+          Scripts.onPreparableConnection config \connection -> do
+            let statement =
+                  (if preparable then Statement.preparable else Statement.unpreparable)
+                    "select 1, 2"
+                    mempty
+                    (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int8)))
+            result <- Connection.use connection (executor statement)
+            case result of
+              Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.UnexpectedColumnCountStatementError expected actual))) -> do
+                shouldBe expected 1
+                shouldBe actual 2
+              Left err ->
+                expectationFailure ("Unexpected type of error: " <> show err)
+              result ->
+                expectationFailure ("Not an error: " <> show result)
+
+        it "gets reported when result has fewer columns" \config -> do
+          Scripts.onPreparableConnection config \connection -> do
+            let statement =
+                  (if preparable then Statement.preparable else Statement.unpreparable)
+                    "select 1"
+                    mempty
+                    ( Decoders.singleRow
+                        ( (,)
+                            <$> Decoders.column (Decoders.nonNullable Decoders.int8)
+                            <*> Decoders.column (Decoders.nonNullable Decoders.int8)
+                        )
+                    )
+            result <- Connection.use connection (executor statement)
+            case result of
+              Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.UnexpectedColumnCountStatementError expected actual))) -> do
+                shouldBe expected 2
+                shouldBe actual 1
+              Left err ->
+                expectationFailure ("Unexpected type of error: " <> show err)
+              result ->
+                expectationFailure ("Not an error: " <> show result)
+
+      describe "DecoderTypeMismatch" do
+        describe "singleRow" do
+          it "gets reported when column type mismatches decoder" \config -> do
+            Scripts.onPreparableConnection config \connection -> do
+              let statement =
+                    (if preparable then Statement.preparable else Statement.unpreparable)
+                      "select 1::int8, 'text'::text"
+                      mempty
+                      ( Decoders.singleRow
+                          ( (,)
+                              <$> Decoders.column (Decoders.nonNullable Decoders.int8)
+                              <*> Decoders.column (Decoders.nonNullable Decoders.int8)
+                          )
+                      )
+              result <- Connection.use connection (executor statement)
+              case result of
+                Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.UnexpectedColumnTypeStatementError column expected actual))) -> do
+                  shouldBe column 1
+                  shouldBe expected 20
+                  shouldBe actual 25
+                Left err ->
+                  expectationFailure ("Unexpected type of error: " <> show err)
+                result ->
+                  expectationFailure ("Not an error: " <> show result)
+
+        describe "rowMaybe" do
+          it "gets reported when column type mismatches decoder" \config -> do
+            Scripts.onPreparableConnection config \connection -> do
+              let statement =
+                    (if preparable then Statement.preparable else Statement.unpreparable)
+                      "select 1::int8, 'text'::text"
+                      mempty
+                      ( Decoders.rowMaybe
+                          ( (,)
+                              <$> Decoders.column (Decoders.nonNullable Decoders.int8)
+                              <*> Decoders.column (Decoders.nonNullable Decoders.int8)
+                          )
+                      )
+              result <- Connection.use connection (executor statement)
+              case result of
+                Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.UnexpectedColumnTypeStatementError column expected actual))) -> do
+                  shouldBe column 1
+                  (expected, actual) `shouldBe` (20, 25)
+                Left err ->
+                  expectationFailure ("Unexpected type of error: " <> show err)
+                result ->
+                  expectationFailure ("Not an error: " <> show result)
+
+        describe "rowVector" do
+          it "gets reported when column type mismatches decoder" \config -> do
+            Scripts.onPreparableConnection config \connection -> do
+              let statement :: Statement.Statement () (Vector.Vector (Int64, Int64))
+                  statement =
+                    (if preparable then Statement.preparable else Statement.unpreparable)
+                      "select int8 '1', text 'text'"
+                      mempty
+                      ( Decoders.rowVector
+                          ( (,)
+                              <$> Decoders.column (Decoders.nonNullable Decoders.int8)
+                              <*> Decoders.column (Decoders.nonNullable Decoders.int8)
+                          )
+                      )
+              result <- Connection.use connection (executor statement)
+              case result of
+                Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.UnexpectedColumnTypeStatementError column expected actual))) -> do
+                  shouldBe column 1
+                  (expected, actual) `shouldBe` (20, 25)
+                Left err ->
+                  expectationFailure ("Unexpected type of error: " <> show err)
+                result ->
+                  expectationFailure ("Not an error: " <> show result)
+
+        describe "array" do
+          describe "decoder:int8[]" do
+            describe "column:int8" do
+              it "reports properly" \config -> do
+                Scripts.onPreparableConnection config \connection -> do
+                  let statement =
+                        (if preparable then Statement.preparable else Statement.unpreparable)
+                          "select 1::int8"
+                          mempty
+                          ( Decoders.singleRow
+                              (Decoders.column (Decoders.nonNullable (Decoders.vectorArray @Vector (Decoders.nonNullable Decoders.int8))))
+                          )
+                  result <- Connection.use connection (executor statement)
+                  case result of
+                    Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.UnexpectedColumnTypeStatementError column expected actual))) -> do
+                      shouldBe column 0
+                      (expected, actual) `shouldBe` (1016, 20)
+                    Left err ->
+                      expectationFailure ("Unexpected type of error: " <> show err)
+                    result ->
+                      expectationFailure ("Not an error: " <> show result)
+
+          describe "decoder:int8[]" do
+            describe "column:int8[]" do
+              it "decodes properly" \config -> do
+                Scripts.onPreparableConnection config \connection -> do
+                  let statement =
+                        (if preparable then Statement.preparable else Statement.unpreparable)
+                          "select ARRAY[1::int8, 2::int8]"
+                          mempty
+                          ( Decoders.singleRow
+                              (Decoders.column (Decoders.nonNullable (Decoders.vectorArray @Vector (Decoders.nonNullable Decoders.int8))))
+                          )
+                  result <- Connection.use connection (executor statement)
+                  shouldBe result (Right (Vector.fromList [1, 2]))
+
+          describe "decoder:int8" do
+            describe "column:int8[]" do
+              it "reports properly" \config -> do
+                Scripts.onPreparableConnection config \connection -> do
+                  let statement =
+                        (if preparable then Statement.preparable else Statement.unpreparable)
+                          "select ARRAY[1::int8, 2::int8]"
+                          mempty
+                          ( Decoders.singleRow
+                              (Decoders.column (Decoders.nonNullable Decoders.int8))
+                          )
+                  result <- Connection.use connection (executor statement)
+                  case result of
+                    Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.UnexpectedColumnTypeStatementError column expected actual))) -> do
+                      shouldBe column 0
+                      (expected, actual) `shouldBe` (20, 1016)
+                    Left err ->
+                      expectationFailure ("Unexpected type of error: " <> show err)
+                    result ->
+                      expectationFailure ("Not an error: " <> show result)
diff --git a/src/library-tests/Integration/Sharing/Pipeline/Statement/SendFailureSpec.hs b/src/library-tests/Integration/Sharing/Pipeline/Statement/SendFailureSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/Pipeline/Statement/SendFailureSpec.hs
@@ -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)
diff --git a/src/library-tests/Integration/Sharing/PipelineSpec.hs b/src/library-tests/Integration/Sharing/PipelineSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/PipelineSpec.hs
@@ -0,0 +1,219 @@
+module Integration.Sharing.PipelineSpec (spec) where
+
+import Data.Either
+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
+
+spec :: SpecWith Scripts.ScopeParams
+spec = do
+  describe "Single-statement" do
+    describe "Unprepared" do
+      it "Collects results and sends params" \config -> do
+        Scripts.onUnpreparableConnection config \connection -> do
+          result <-
+            (Connection.use connection . Session.pipeline)
+              $ Execution.pipelineByParams Statements.GenerateSeries {start = 0, end = 2}
+          shouldBe result (Right [0 .. 2])
+
+    describe "Prepared" do
+      it "Collects results and sends params" \config -> do
+        Scripts.onPreparableConnection config \connection -> do
+          result <-
+            (Connection.use connection . Session.pipeline)
+              $ Execution.pipelineByParams Statements.GenerateSeries {start = 0, end = 2}
+          shouldBe result (Right [0 .. 2])
+
+  describe "Multi-statement" do
+    describe "On unprepared statements" do
+      it "Collects results and sends params" \config -> do
+        Scripts.onUnpreparableConnection config \connection -> do
+          result <-
+            (Connection.use connection . Session.pipeline)
+              $ replicateM 2
+              $ Execution.pipelineByParams Statements.GenerateSeries {start = 0, end = 2}
+          shouldBe result (Right [[0 .. 2], [0 .. 2]])
+
+    describe "On prepared statements" do
+      it "Collects results and sends params" \config -> do
+        Scripts.onPreparableConnection config \connection -> do
+          result <-
+            (Connection.use connection . Session.pipeline)
+              $ replicateM 2
+              $ Execution.pipelineByParams Statements.GenerateSeries {start = 0, end = 2}
+          shouldBe result (Right [[0 .. 2], [0 .. 2]])
+
+    describe "When a part in the middle fails" do
+      describe "With query error" do
+        it "Captures the error" \config -> do
+          Scripts.onPreparableConnection config \connection -> do
+            result <-
+              (Connection.use connection . Session.pipeline)
+                $ (,,)
+                <$> Execution.pipelineByParams Statements.GenerateSeries {start = 0, end = 2}
+                <*> Execution.pipelineByParams Statements.BrokenSyntax {start = 0, end = 2}
+                <*> Execution.pipelineByParams Statements.GenerateSeries {start = 0, end = 2}
+            case result of
+              Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.ServerStatementError _))) -> pure ()
+              _ -> expectationFailure $ "Unexpected result: " <> show result
+
+        it "Leaves the connection usable" \config -> do
+          Scripts.onPreparableConnection config \connection -> do
+            result <-
+              Connection.use connection do
+                _ <-
+                  catchError
+                    ( Just
+                        <$> Session.pipeline
+                          ( (,,)
+                              <$> Execution.pipelineByParams Statements.GenerateSeries {start = 0, end = 2}
+                              <*> Execution.pipelineByParams Statements.BrokenSyntax {start = 0, end = 2}
+                              <*> Execution.pipelineByParams Statements.GenerateSeries {start = 0, end = 2}
+                          )
+                    )
+                    (const (pure Nothing))
+                Execution.sessionByParams Statements.GenerateSeries {start = 0, end = 0}
+            shouldBe result (Right [0])
+
+      describe "With decoding error" do
+        it "Captures the error" \config -> do
+          Scripts.onPreparableConnection config \connection -> do
+            result <-
+              (Connection.use connection . Session.pipeline)
+                $ (,,)
+                <$> Execution.pipelineByParams Statements.GenerateSeries {start = 0, end = 2}
+                <*> Execution.pipelineByParams Statements.WrongDecoder {start = 0, end = 2}
+                <*> Execution.pipelineByParams Statements.GenerateSeries {start = 0, end = 2}
+            case result of
+              Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.UnexpectedColumnTypeStatementError {}))) -> pure ()
+              _ -> expectationFailure $ "Unexpected result: " <> show result
+
+        it "Leaves the connection usable" \config -> do
+          Scripts.onPreparableConnection config \connection -> do
+            result <-
+              Connection.use connection do
+                _ <-
+                  catchError
+                    ( Just
+                        <$> Session.pipeline
+                          ( (,,)
+                              <$> Execution.pipelineByParams Statements.GenerateSeries {start = 0, end = 2}
+                              <*> Execution.pipelineByParams Statements.WrongDecoder {start = 0, end = 2}
+                              <*> Execution.pipelineByParams Statements.GenerateSeries {start = 0, end = 2}
+                          )
+                    )
+                    (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
+      Scripts.onPreparableConnection config \connection -> do
+        -- Run an intentionally failing prepared statement in a pipeline to set the condition of the bug.
+        result <- Connection.use connection do
+          Session.pipeline do
+            Pipeline.statement
+              ()
+              ( Statement.preparable
+                  "select null :: int4"
+                  mempty
+                  (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int4)))
+              )
+        case result of
+          Right val ->
+            expectationFailure ("First statement succeeded unexpectedly: " <> show val)
+          Left _ ->
+            pure ()
+
+        -- Run a succeeding prepared statement in a pipeline to see if the cache is still in a good state.
+        result <- Connection.use connection do
+          Session.pipeline do
+            Pipeline.statement
+              ()
+              ( Statement.preparable
+                  "select 1"
+                  mempty
+                  (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int4)))
+              )
+        -- If there is an error the cache got corrupted.
+        case result of
+          Right _ ->
+            pure ()
+          Left result ->
+            expectationFailure ("Unexpected error: " <> show result)
+
+    it "Handles failures within the same pipeline gracefully" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        -- Run an intentionally failing prepared statement in a pipeline to set the condition of the bug.
+        result <- Connection.use connection do
+          Session.pipeline do
+            Pipeline.statement
+              ()
+              ( Statement.preparable
+                  "select null :: int4"
+                  mempty
+                  (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int4)))
+              )
+              <* Pipeline.statement
+                ()
+                ( Statement.preparable
+                    "select 1"
+                    mempty
+                    (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int4)))
+                )
+        case result of
+          Right val ->
+            expectationFailure ("First statement succeeded unexpectedly: " <> show val)
+          Left _ ->
+            pure ()
diff --git a/src/library-tests/Integration/Sharing/Session/CatchErrorSpec.hs b/src/library-tests/Integration/Sharing/Session/CatchErrorSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/Session/CatchErrorSpec.hs
@@ -0,0 +1,33 @@
+module Integration.Sharing.Session.CatchErrorSpec (spec) where
+
+import Data.Either
+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.Scripts qualified as Scripts
+import Prelude
+import Test.Hspec
+
+spec :: SpecWith Scripts.ScopeParams
+spec = do
+  it "Leaves the session usable" \config -> do
+    Scripts.onPreparableConnection config \connection -> do
+      let tryStatement =
+            Statement.preparable
+              "select $1 :: int8"
+              (Encoders.param (Encoders.nonNullable Encoders.int8))
+              (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int8)))
+
+      result <-
+        Connection.use connection do
+          -- First successful query
+          a <- Session.statement (1 :: Int64) tryStatement
+          -- This should fail but connection should remain usable
+          () <- catchError (Session.script "absurd") (const (pure ()))
+          -- Second successful query
+          b <- Session.statement (2 :: Int64) tryStatement
+          pure (a, b)
+
+      result `shouldBe` Right (1, 2)
diff --git a/src/library-tests/Integration/Sharing/Session/OnLibpqConnection/DirtyReturnCleanupSpec.hs b/src/library-tests/Integration/Sharing/Session/OnLibpqConnection/DirtyReturnCleanupSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/Session/OnLibpqConnection/DirtyReturnCleanupSpec.hs
@@ -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)
diff --git a/src/library-tests/Integration/Sharing/Session/RecoveredPipelineFailureSpec.hs b/src/library-tests/Integration/Sharing/Session/RecoveredPipelineFailureSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/Session/RecoveredPipelineFailureSpec.hs
@@ -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)
diff --git a/src/library-tests/Integration/Sharing/Session/ScriptSpec.hs b/src/library-tests/Integration/Sharing/Session/ScriptSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/Session/ScriptSpec.hs
@@ -0,0 +1,59 @@
+module Integration.Sharing.Session.ScriptSpec (spec) where
+
+import Data.Either
+import Hasql.Connection qualified as Connection
+import Hasql.Errors qualified as Errors
+import Hasql.Session qualified as Session
+import Helpers.Scripts qualified as Scripts
+import Prelude
+import Test.Hspec
+
+spec :: SpecWith Scripts.ScopeParams
+spec = do
+  it "returns ServerSessionError on syntax errors" \config -> do
+    Scripts.onPreparableConnection config \connection -> do
+      result <- Connection.use connection (Session.script "THIS IS INVALID SQL")
+      case result of
+        Left (Errors.SessionUseError (Errors.ScriptSessionError _ _)) -> pure ()
+        _ -> expectationFailure $ "Expected ScriptSessionError with ExecutionScriptError, got: " <> show result
+
+  it "handles multi-statement DDL scripts with comments" \config -> do
+    Scripts.onPreparableConnection config \connection -> do
+      tableName <- Scripts.generateSymname
+      let sql =
+            (mconcat . map (<> "\n"))
+              [ "create table \"" <> tableName <> "_genre\" (",
+                "  \"id\" int4 not null primary key,",
+                "  \"name\" text not null unique",
+                ");",
+                "",
+                "create table \"" <> tableName <> "_artist\" (",
+                "  \"id\" int4 not null primary key,",
+                "  \"name\" text not null",
+                ");",
+                "",
+                "create table \"" <> tableName <> "_album\" (",
+                "  \"id\" int4 not null primary key,",
+                "  -- Album name.",
+                "  \"name\" text not null,",
+                "  -- The date the album was first released.",
+                "  \"released\" date null",
+                ");",
+                "",
+                "create table \"" <> tableName <> "_album_genre\" (",
+                "  \"album\" int4 not null references \"" <> tableName <> "_album\",",
+                "  \"genre\" int4 not null references \"" <> tableName <> "_genre\"",
+                ");",
+                "",
+                "create table \"" <> tableName <> "_album_artist\" (",
+                "  \"album\" int4 not null references \"" <> tableName <> "_album\",",
+                "  \"artist\" int4 not null references \"" <> tableName <> "_artist\",",
+                "  -- Whether it is the primary artist",
+                "  \"primary\" bool not null,",
+                "  primary key (\"album\", \"artist\")",
+                ");"
+              ]
+      result <- Connection.use connection (Session.script sql)
+      case result of
+        Right () -> pure ()
+        Left err -> expectationFailure $ "Expected success, got: " <> show err
diff --git a/src/library-tests/Integration/Sharing/Session/StatementSpec.hs b/src/library-tests/Integration/Sharing/Session/StatementSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/Session/StatementSpec.hs
@@ -0,0 +1,109 @@
+module Integration.Sharing.Session.StatementSpec (spec) where
+
+import Data.Either
+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.Scripts qualified as Scripts
+import Prelude
+import Test.Hspec
+
+spec :: SpecWith Scripts.ScopeParams
+spec = do
+  describe "Roundtrips" do
+    it "handles simple values correctly" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        result <- Connection.use connection (Session.statement (42 :: Int64) echoStatement)
+        result `shouldBe` Right 42
+
+    it "reuses a prepared statement across executions in one session" \config -> do
+      -- The first execution is a cache miss (separate PARSE roundtrip),
+      -- the second a cache hit (single roundtrip). Both must succeed.
+      Scripts.onPreparableConnection config \connection -> do
+        result <-
+          Connection.use connection do
+            a <- Session.statement (1 :: Int64) echoStatement
+            b <- Session.statement (2 :: Int64) echoStatement
+            pure (a, b)
+        result `shouldBe` Right (1, 2)
+
+    it "keeps a prepared statement usable after an EXECUTE error" \config -> do
+      -- Regression: PARSE succeeds, EXECUTE fails (division by zero). The
+      -- statement is on the server under its cached name, so a later use on the
+      -- same connection must hit the cache rather than re-issuing PARSE for an
+      -- already-existing name ("prepared statement ... already exists").
+      Scripts.onPreparableConnection config \connection -> do
+        failure <- Connection.use connection (Session.statement 0 divStatement)
+        failure `shouldSatisfy` isLeft
+        success <- Connection.use connection (Session.statement 1 divStatement)
+        success `shouldBe` Right 1
+
+    it "works on an unpreparable connection" \config -> do
+      Scripts.onUnpreparableConnection config \connection -> do
+        result <- Connection.use connection (Session.statement (42 :: Int64) echoStatement)
+        result `shouldBe` Right 42
+
+  describe "Error Handling" do
+    it "captures query errors correctly" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        let statement =
+              Statement.preparable
+                "select true where 1 = any ($1) and $2"
+                ( mconcat
+                    [ fst >$< (Encoders.param (Encoders.nonNullable (Encoders.array (Encoders.dimension foldl' (Encoders.element (Encoders.nonNullable Encoders.int8)))))),
+                      snd >$< (Encoders.param (Encoders.nonNullable Encoders.text))
+                    ]
+                )
+                (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.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
+    "select $1"
+    (Encoders.param (Encoders.nonNullable Encoders.int8))
+    (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int8)))
+
+-- | Parses fine, but fails at execution time when given 0 (division by zero).
+divStatement :: Statement.Statement Int64 Int64
+divStatement =
+  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)))
diff --git a/src/library-tests/Integration/Sharing/SessionSpec.hs b/src/library-tests/Integration/Sharing/SessionSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/SessionSpec.hs
@@ -0,0 +1,26 @@
+module Integration.Sharing.SessionSpec (spec) where
+
+import Data.Either
+import Hasql.Connection qualified as Connection
+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 = do
+  -- 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
+
+      result <- Connection.use connection do
+        Execution.sessionByParams (Statements.SetConfig varname "1" False)
+      result `shouldSatisfy` isRight
+
+      result <- Connection.use connection do
+        Execution.sessionByParams (Statements.CurrentSetting varname True)
+      result `shouldBe` Right (Just "1")
diff --git a/src/library-tests/Integration/Sharing/SpecHook.hs b/src/library-tests/Integration/Sharing/SpecHook.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/SpecHook.hs
@@ -0,0 +1,30 @@
+-- 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
+import Test.Hspec
+import TestcontainersPostgresql qualified
+
+type HookedSpec = SpecWith Scripts.ScopeParams
+
+hook :: HookedSpec -> SpecWith Pqi.Adapter
+hook hookedSpec = do
+  byDistro "postgres:9"
+  byDistro "postgres:18"
+  where
+    byDistro tagName =
+      describe (toList tagName)
+        $ aroundAllWith
+          ( \action adapter ->
+              PostgresContainer.run
+                TestcontainersPostgresql.Config
+                  { tagName,
+                    auth = TestcontainersPostgresql.CredentialsAuth "postgres" "postgres",
+                    forwardLogs = False
+                  }
+                (\(host, port) -> action (adapter, host, port))
+          )
+          (parallel hookedSpec)
diff --git a/src/library-tests/Integration/Sharing/Statement/PreparedStatementNamingSpec.hs b/src/library-tests/Integration/Sharing/Statement/PreparedStatementNamingSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/Statement/PreparedStatementNamingSpec.hs
@@ -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)))
diff --git a/src/library-tests/Integration/Sharing/StatementSpec.hs b/src/library-tests/Integration/Sharing/StatementSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/Sharing/StatementSpec.hs
@@ -0,0 +1,586 @@
+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
+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.CountPreparedStatements qualified as CountPreparedStatements
+import Prelude
+import Test.Hspec
+
+spec :: SpecWith Scripts.ScopeParams
+spec = do
+  describe "Statement Functionality" do
+    describe "Prepared statements" do
+      it "allows reuse of the same prepared statement on different types" \config -> do
+        Scripts.onPreparableConnection config \connection -> do
+          let statement1 =
+                Statement.preparable
+                  "select $1"
+                  (Encoders.param (Encoders.nonNullable Encoders.text))
+                  (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.text)))
+          let statement2 =
+                Statement.preparable
+                  "select $1"
+                  (Encoders.param (Encoders.nonNullable Encoders.int8))
+                  (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int8)))
+
+          result <-
+            Connection.use connection do
+              result1 <- Session.statement "ok" statement1
+              result2 <- Session.statement (1 :: Int64) statement2
+              return (result1, result2)
+          result `shouldBe` Right ("ok", 1 :: Int64)
+
+    describe "Row counting" do
+      it "counts affected rows correctly" \config -> do
+        tableName <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          let dropTable = Statement.preparable ("drop table if exists " <> tableName) mempty Decoders.noResult
+          let createTable = Statement.preparable ("create table " <> tableName <> " (id bigserial not null, name varchar not null, primary key (id))") mempty Decoders.noResult
+          let insertRow = Statement.unpreparable ("insert into " <> tableName <> " (name) values ('a')") mempty Decoders.noResult
+          let deleteRows = Statement.unpreparable ("delete from " <> tableName) mempty Decoders.rowsAffected
+
+          result <-
+            Connection.use connection do
+              Session.statement () dropTable
+              Session.statement () createTable
+              replicateM_ 100 (Session.statement () insertRow)
+              affectedRows <- Session.statement () deleteRows
+              Session.statement () dropTable
+              return affectedRows
+          result `shouldBe` Right 100
+
+    describe "Auto-incremented columns" do
+      it "returns auto-incremented column results" \config -> do
+        tableName <- Scripts.generateSymname
+        Scripts.onPreparableConnection config \connection -> do
+          let dropTable = Statement.preparable ("drop table if exists " <> tableName) mempty Decoders.noResult
+          let createTable = Statement.preparable ("create table " <> tableName <> " (id bigserial not null, name varchar not null, primary key (id))") mempty Decoders.noResult
+          let insertRow = Statement.unpreparable ("insert into " <> tableName <> " (name) values ('a') returning id") mempty (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int8)))
+          let insertRow2 = Statement.unpreparable ("insert into " <> tableName <> " (name) values ('b') returning id") mempty (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int8)))
+
+          result <-
+            Connection.use connection do
+              Session.statement () dropTable
+              Session.statement () createTable
+              id1 <- Session.statement () insertRow
+              id2 <- Session.statement () insertRow2
+              Session.statement () dropTable
+              return (id1, id2)
+          result `shouldBe` Right (1 :: Int64, 2 :: Int64)
+
+    describe "List decoding" do
+      it "decodes lists correctly" \config -> do
+        Scripts.onPreparableConnection config \connection -> do
+          let statement =
+                Statement.preparable
+                  "values (1 :: int8, 2 :: int8), (3,4), (5,6)"
+                  mempty
+                  (Decoders.rowList ((,) <$> (Decoders.column (Decoders.nonNullable Decoders.int8)) <*> (Decoders.column (Decoders.nonNullable Decoders.int8))))
+          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
+          let statement =
+                Statement.preparable
+                  "select true where 1 = any ($1)"
+                  (Encoders.param (Encoders.nonNullable (Encoders.array (Encoders.dimension foldl' (Encoders.element (Encoders.nonNullable Encoders.int8))))))
+                  (fmap (maybe False (const True)) (Decoders.rowMaybe (Decoders.column (Decoders.nonNullable Decoders.bool))))
+          result <- Connection.use connection do
+            result1 <- Session.statement ([1, 2] :: [Int64]) statement
+            result2 <- Session.statement ([2, 3] :: [Int64]) statement
+            return (result1, result2)
+          result `shouldBe` Right (True, False)
+
+    describe "NOT IN simulation" do
+      it "works with arrays" \config -> do
+        Scripts.onPreparableConnection config \connection -> do
+          let statement =
+                Statement.preparable
+                  "select true where 3 <> all ($1)"
+                  (Encoders.param (Encoders.nonNullable (Encoders.array (Encoders.dimension foldl' (Encoders.element (Encoders.nonNullable Encoders.int8))))))
+                  (fmap (maybe False (const True)) (Decoders.rowMaybe (Decoders.column (Decoders.nonNullable Decoders.bool))))
+          result <- Connection.use connection do
+            result1 <- Session.statement ([1, 2] :: [Int64]) statement
+            result2 <- Session.statement ([2, 3] :: [Int64]) statement
+            return (result1, result2)
+          result `shouldBe` Right (True, False)
+
+    describe "Preparation" do
+      it "Do get prepared when configuration allows" \config -> do
+        Scripts.onPreparableConnection config \connection -> do
+          -- Execute a preparable statement
+          result <-
+            Connection.use connection do
+              Session.statement
+                ()
+                ( Statement.preparable
+                    "select 1 + 1"
+                    mempty
+                    (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int4)))
+                )
+          result `shouldBe` Right 2
+
+          -- Query pg_prepared_statements to verify it was prepared
+          preparedCount <-
+            Connection.use connection do
+              Execution.sessionByParams CountPreparedStatements.CountPreparedStatements
+
+          preparedCount `shouldSatisfy` \case
+            Right count -> count > 0
+            Left _ -> False
+
+      it "Do not get prepared when configuration forbids it" \config -> do
+        Scripts.onUnpreparableConnection config \connection -> do
+          -- Execute a statement marked as preparable
+          result <-
+            Connection.use connection do
+              Session.statement
+                ()
+                ( Statement.preparable
+                    "select 2 + 2"
+                    mempty
+                    (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int4)))
+                )
+          result `shouldBe` Right 4
+
+          -- Query pg_prepared_statements to verify it was NOT prepared
+          preparedCount <-
+            Connection.use connection do
+              Execution.sessionByParams CountPreparedStatements.CountPreparedStatements
+
+          preparedCount `shouldBe` Right 0
+
+    describe "Cache resilience after a failing prepared statement" do
+      describe "Session" do
+        it "Failing statements don't cause misses in updates of the prepared statement cache" \config -> do
+          Scripts.onPreparableConnection config \connection -> do
+            -- Run an intentionally failing prepared statement to set the condition of the bug.
+            result <- Connection.use connection do
+              Session.statement
+                ()
+                ( Statement.preparable
+                    "select null"
+                    mempty
+                    (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int4)))
+                )
+            shouldBe (isLeft result) True
+            -- Run a succeeding prepared statement to see if the cache is still in a good state.
+            result <- Connection.use connection do
+              Session.statement
+                ()
+                ( Statement.preparable
+                    "select 1"
+                    mempty
+                    (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int4)))
+                )
+            -- If there is an error the cache got corrupted.
+            case result of
+              Right _ ->
+                pure ()
+              Left result ->
+                expectationFailure ("Unexpected error: " <> show result)
+
+        it "Syntax errors in prepared statements don't corrupt the cache for subsequent uses of the same statement" \config -> do
+          Scripts.onPreparableConnection config \connection -> do
+            let brokenStatement =
+                  Statement.preparable
+                    "S"
+                    mempty
+                    Decoders.noResult
+            -- First run: syntax error.
+            result1 <- Connection.use connection do
+              Session.statement () brokenStatement
+            error1 <- case result1 of
+              Left error1 -> pure error1
+              Right _ -> fail "First run unexpectedly succeeded"
+
+            -- Second run of the same statement: should also produce a syntax error,
+            -- not "prepared statement does not exist".
+            result2 <- Connection.use connection do
+              Session.statement () brokenStatement
+            error2 <- case result2 of
+              Left error2 -> pure error2
+              Right _ -> fail "Second run unexpectedly succeeded"
+            shouldBe error2 error1
+
+      describe "Pipeline" do
+        it "Failing pipeline statements don't cause misses in updates of the prepared statement cache" \config -> do
+          Scripts.onPreparableConnection config \connection -> do
+            -- Run an intentionally failing prepared statement in a pipeline to set the condition of the bug.
+            result <- Connection.use connection do
+              Session.pipeline do
+                Pipeline.statement
+                  ()
+                  ( Statement.preparable
+                      "select null :: int4"
+                      mempty
+                      (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int4)))
+                  )
+            case result of
+              Right val ->
+                expectationFailure ("First statement succeeded unexpectedly: " <> show val)
+              Left _ ->
+                pure ()
+
+            -- Run a succeeding prepared statement in a pipeline to see if the cache is still in a good state.
+            result <- Connection.use connection do
+              Session.pipeline do
+                Pipeline.statement
+                  ()
+                  ( Statement.preparable
+                      "select 1"
+                      mempty
+                      (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int4)))
+                  )
+            -- If there is an error the cache got corrupted.
+            case result of
+              Right _ ->
+                pure ()
+              Left result ->
+                expectationFailure ("Unexpected error: " <> show result)
+
+        it "Syntax errors in pipeline prepared statements don't corrupt the cache for subsequent uses of the same statement" \config -> do
+          Scripts.onPreparableConnection config \connection -> do
+            let brokenStatement =
+                  Statement.preparable
+                    "S"
+                    mempty
+                    Decoders.noResult
+            -- First run: syntax error.
+            result1 <- Connection.use connection do
+              Session.pipeline (Pipeline.statement () brokenStatement)
+            shouldBe (isLeft result1) True
+            -- Second run of the same statement: should also produce a syntax error,
+            -- not "prepared statement does not exist".
+            result2 <- Connection.use connection do
+              Session.pipeline (Pipeline.statement () brokenStatement)
+            case result2 of
+              Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.ServerStatementError (Errors.ServerError "42601" _ _ _ _)))) ->
+                pure ()
+              Left other ->
+                expectationFailure ("Unexpected error on second run: " <> show other)
+              Right _ ->
+                expectationFailure "Second run unexpectedly succeeded"
+
+        it "A pipeline with a broken statement first and a valid one after it can be retried with the same syntax error" \config -> do
+          Scripts.onPreparableConnection config \connection -> do
+            let broken = Statement.preparable "S" mempty Decoders.noResult
+                ok = Statement.preparable "select 1" mempty (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int4)))
+            result1 <- Connection.use connection do
+              Session.pipeline do
+                (,)
+                  <$> Pipeline.statement () broken
+                  <*> Pipeline.statement () ok
+            error1 <- case result1 of
+              Left error1 -> pure error1
+              Right _ -> fail "First run unexpectedly succeeded"
+
+            result2 <- Connection.use connection do
+              Session.pipeline do
+                (,)
+                  <$> Pipeline.statement () broken
+                  <*> Pipeline.statement () ok
+            error2 <- case result2 of
+              Left error2 -> pure error2
+              Right _ -> fail "Second run unexpectedly succeeded"
+            shouldBe error2 error1
+
+        it "A valid statement after a broken pipeline statement still prepares in a later pipeline" \config -> do
+          Scripts.onPreparableConnection config \connection -> do
+            let broken = Statement.preparable "S" mempty Decoders.noResult
+                trailing = Statement.preparable "select 1" mempty (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int4)))
+            result1 <- Connection.use connection do
+              Session.pipeline do
+                (,)
+                  <$> Pipeline.statement () broken
+                  <*> Pipeline.statement () trailing
+            shouldBe (isLeft result1) True
+
+            result2 <- Connection.use connection do
+              Session.pipeline do
+                Pipeline.statement () trailing
+            case result2 of
+              Right val -> val `shouldBe` 1
+              Left err -> expectationFailure ("Unexpected error on follow-up pipeline: " <> show err)
+
+        it "A pipeline with successful statements followed by a broken one can be retried without 'already exists' errors" \config -> do
+          Scripts.onPreparableConnection config \connection -> do
+            let ok1 = Statement.preparable "select 1" mempty (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int4)))
+                ok2 = Statement.preparable "select 2" mempty (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int4)))
+                broken = Statement.preparable "S" mempty Decoders.noResult
+            -- First run: pipeline with two OK statements and a broken one at the end.
+            result1 <- Connection.use connection do
+              Session.pipeline do
+                (,,)
+                  <$> Pipeline.statement () ok1
+                  <*> Pipeline.statement () ok2
+                  <*> Pipeline.statement () broken
+            error1 <- case result1 of
+              Left error1 -> pure error1
+              Right _ -> fail "First run unexpectedly succeeded"
+
+            -- Second run of the same pipeline: must fail with the SAME syntax error,
+            -- not "prepared statement already exists".
+            result2 <- Connection.use connection do
+              Session.pipeline do
+                (,,)
+                  <$> Pipeline.statement () ok1
+                  <*> Pipeline.statement () ok2
+                  <*> Pipeline.statement () broken
+            error2 <- case result2 of
+              Left error2 -> pure error2
+              Right _ -> fail "Second run unexpectedly succeeded"
+            shouldBe error2 error1
+
+            -- Also, a standalone valid statement should still work afterwards.
+            result3 <- Connection.use connection do
+              Session.statement () ok1
+            case result3 of
+              Right val -> val `shouldBe` 1
+              Left err -> expectationFailure ("Unexpected error on standalone statement: " <> show err)
+
+        it "A pipeline with a broken statement in the middle can be retried without 'already exists' errors" \config -> do
+          Scripts.onPreparableConnection config \connection -> do
+            let ok1 = Statement.preparable "select 1" mempty (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int4)))
+                broken = Statement.preparable "S" mempty Decoders.noResult
+                ok2 = Statement.preparable "select 2" mempty (Decoders.singleRow (Decoders.column (Decoders.nonNullable Decoders.int4)))
+            -- First run: pipeline with broken statement in the middle.
+            result1 <- Connection.use connection do
+              Session.pipeline do
+                (,,)
+                  <$> Pipeline.statement () ok1
+                  <*> Pipeline.statement () broken
+                  <*> Pipeline.statement () ok2
+            shouldBe (isLeft result1) True
+
+            -- Second run of the same pipeline: must fail with the same syntax error.
+            result2 <- Connection.use connection do
+              Session.pipeline do
+                (,,)
+                  <$> Pipeline.statement () ok1
+                  <*> Pipeline.statement () broken
+                  <*> Pipeline.statement () ok2
+            case result2 of
+              Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.ServerStatementError (Errors.ServerError "42601" _ _ _ _)))) ->
+                pure ()
+              Left other ->
+                expectationFailure ("Unexpected error on second run: " <> show other)
+              Right _ ->
+                expectationFailure "Second run unexpectedly succeeded"
+
+            -- Standalone valid statements should still work afterwards.
+            result3 <- Connection.use connection do
+              Session.statement () ok1
+            case result3 of
+              Right val -> val `shouldBe` 1
+              Left err -> expectationFailure ("Unexpected error on standalone ok1: " <> show err)
+            result4 <- Connection.use connection do
+              Session.statement () ok2
+            case result4 of
+              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) ->
+  SpecWith Scripts.ScopeParams
+decoderCompatibilityCacheByExecutor executorName executor = do
+  describe (toList executorName) do
+    it "does not hide decoder mismatches from a previously verified statement" \config -> do
+      Scripts.onPreparableConnection config \connection -> do
+        let sql = "select 1::int8, 'text'::text"
+            correctStatement =
+              Statement.preparable
+                sql
+                mempty
+                ( Decoders.singleRow
+                    ( (,)
+                        <$> Decoders.column (Decoders.nonNullable Decoders.int8)
+                        <*> Decoders.column (Decoders.nonNullable Decoders.text)
+                    )
+                )
+            mismatchingStatement =
+              Statement.preparable
+                sql
+                mempty
+                ( Decoders.singleRow
+                    ( (,)
+                        <$> Decoders.column (Decoders.nonNullable Decoders.int8)
+                        <*> Decoders.column (Decoders.nonNullable Decoders.int8)
+                    )
+                )
+        firstResult <- Connection.use connection (executor correctStatement)
+        shouldBe firstResult (Right (1, "text"))
+        secondResult <- Connection.use connection (executor mismatchingStatement)
+        case secondResult of
+          Left (Errors.SessionUseError (Errors.StatementSessionError _ _ _ _ _ (Errors.UnexpectedColumnTypeStatementError column expected actual))) -> do
+            shouldBe column 1
+            (expected, actual) `shouldBe` (20, 25)
+          Left err ->
+            expectationFailure ("Unexpected type of error: " <> show err)
+          result ->
+            expectationFailure ("Not an error: " <> show result)
diff --git a/src/library-tests/Integration/SpecHook.hs b/src/library-tests/Integration/SpecHook.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Integration/SpecHook.hs
@@ -0,0 +1,8 @@
+module Integration.SpecHook (hook) where
+
+import Helpers.Adapters qualified as Adapters
+import Pqi qualified
+import Test.Hspec
+
+hook :: SpecWith Pqi.Adapter -> Spec
+hook = Adapters.hook
diff --git a/src/library-tests/Main.hs b/src/library-tests/Main.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Main.hs
@@ -0,0 +1,1 @@
+{-# OPTIONS_GHC -F -pgmF hspec-discover #-}
diff --git a/src/library-tests/Pure/Connection/AcquireSpec.hs b/src/library-tests/Pure/Connection/AcquireSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Pure/Connection/AcquireSpec.hs
@@ -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)
diff --git a/src/library-tests/Pure/ErrorsSpec.hs b/src/library-tests/Pure/ErrorsSpec.hs
new file mode 100644
--- /dev/null
+++ b/src/library-tests/Pure/ErrorsSpec.hs
@@ -0,0 +1,325 @@
+module Pure.ErrorsSpec (spec) where
+
+import Data.HashSet qualified as HashSet
+import Hasql.Errors qualified as Errors
+import Prelude
+import Test.Hspec
+
+spec :: Spec
+spec = do
+  describe "AcquireError" do
+    describe "toMessage" do
+      it "renders ConnectionAcquireError" do
+        (Errors.toMessage (Errors.ConnectionAcquireError "timeout"))
+          `shouldBe` "Failed to establish a connection 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 ConnectionAcquireError" do
+        (Errors.toDetails (Errors.ConnectionAcquireError "connection timeout"))
+          `shouldBe` [("reason", "connection timeout")]
+
+      it "includes reason for ConnectionPasswordRequiredAcquireError" do
+        (Errors.toDetails (Errors.ConnectionPasswordRequiredAcquireError "no password supplied"))
+          `shouldBe` [("reason", "no password supplied")]
+
+      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 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 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
+    describe "toMessage" do
+      it "renders ServerError" do
+        (Errors.toMessage (Errors.ServerError "42P01" "relation does not exist" Nothing Nothing Nothing))
+          `shouldBe` "Server error"
+
+    describe "toDetails" do
+      it "includes all fields when provided" do
+        (Errors.toDetails (Errors.ServerError "42P01" "relation \"users\" does not exist" (Just "The relation users does not exist.") (Just "Check your table name.") (Just 15)))
+          `shouldBe` [ ("code", "42P01"),
+                       ("message", "relation \"users\" does not exist"),
+                       ("detail", "The relation users does not exist."),
+                       ("hint", "Check your table name."),
+                       ("position", "15")
+                     ]
+
+      it "excludes optional fields when not provided" do
+        (Errors.toDetails (Errors.ServerError "42601" "syntax error" Nothing Nothing Nothing))
+          `shouldBe` [ ("code", "42601"),
+                       ("message", "syntax error")
+                     ]
+
+    describe "toSqlState" do
+      it "is the code the server reported" do
+        (Errors.toSqlState (Errors.ServerError "23505" "duplicate key value violates unique constraint" Nothing Nothing Nothing))
+          `shouldBe` Just "23505"
+
+    describe "toDetailedText" do
+      it "renders ServerError with all details" do
+        (Errors.toDetailedText (Errors.ServerError "42P01" "relation \"users\" does not exist" (Just "The relation users does not exist.") (Just "Check your table name.") (Just 15)))
+          `shouldBe` "Server error\n\
+                     \  code: 42P01\n\
+                     \  message: relation \"users\" does not exist\n\
+                     \  detail: The relation users does not exist.\n\
+                     \  hint: Check your table name.\n\
+                     \  position: 15"
+
+  describe "CellError" do
+    describe "toMessage" do
+      it "renders UnexpectedNullCellError" do
+        (Errors.toMessage Errors.UnexpectedNullCellError)
+          `shouldBe` "Unexpected null value"
+
+      it "renders DeserializationCellError" do
+        (Errors.toMessage (Errors.DeserializationCellError "invalid integer format"))
+          `shouldBe` "Failed to deserialize cell"
+
+    describe "toDetails" do
+      it "includes no details for UnexpectedNullCellError" do
+        (Errors.toDetails Errors.UnexpectedNullCellError)
+          `shouldBe` []
+
+      it "includes reason for DeserializationCellError" do
+        (Errors.toDetails (Errors.DeserializationCellError "expected integer, got text"))
+          `shouldBe` [("reason", "expected integer, got text")]
+
+    describe "toDetailedText" do
+      it "renders DeserializationCellError with details" do
+        (Errors.toDetailedText (Errors.DeserializationCellError "invalid timestamp format"))
+          `shouldBe` "Failed to deserialize cell\n\
+                     \  reason: invalid timestamp format"
+
+  describe "RowError" do
+    describe "toMessage" do
+      it "renders CellRowError with nested message" do
+        (Errors.toMessage (Errors.CellRowError 2 23 Errors.UnexpectedNullCellError))
+          `shouldBe` "Unexpected null value"
+
+      it "renders RefinementRowError" do
+        (Errors.toMessage (Errors.RefinementRowError "age must be positive"))
+          `shouldBe` "Refinement error"
+
+    describe "toDetails" do
+      it "includes column index, oid, and nested cell error details" do
+        (Errors.toDetails (Errors.CellRowError 3 1043 (Errors.DeserializationCellError "invalid format")))
+          `shouldBe` [ ("columnIndex", "3"),
+                       ("oid", "1043"),
+                       ("reason", "invalid format")
+                     ]
+
+    describe "toDetailedText" do
+      it "renders CellRowError with all details" do
+        (Errors.toDetailedText (Errors.CellRowError 2 1043 (Errors.DeserializationCellError "invalid text encoding")))
+          `shouldBe` "Failed to deserialize cell\n  columnIndex: 2\n  oid: 1043\n  reason: invalid text encoding"
+
+  describe "StatementError" do
+    describe "toMessage" do
+      it "renders ServerStatementError with nested message" do
+        (Errors.toMessage (Errors.ServerStatementError (Errors.ServerError "42P01" "relation does not exist" Nothing Nothing Nothing)))
+          `shouldBe` "Server error"
+
+      it "renders UnexpectedRowCountStatementError" do
+        (Errors.toMessage (Errors.UnexpectedRowCountStatementError 1 1 0))
+          `shouldBe` "Unexpected number of rows"
+
+      it "renders UnexpectedColumnTypeStatementError" do
+        (Errors.toMessage (Errors.UnexpectedColumnTypeStatementError 1 23 1043))
+          `shouldBe` "Unexpected column type"
+
+    describe "toDetails" do
+      it "includes expected and actual for UnexpectedRowCountStatementError" do
+        (Errors.toDetails (Errors.UnexpectedRowCountStatementError 1 1 5))
+          `shouldBe` [("expectedMin", "1"), ("expectedMax", "1"), ("actual", "5")]
+
+      it "includes column index and oids for UnexpectedColumnTypeStatementError" do
+        (Errors.toDetails (Errors.UnexpectedColumnTypeStatementError 2 23 1043))
+          `shouldBe` [("columnIndex", "2"), ("expectedOid", "23"), ("actualOid", "1043")]
+
+    describe "toSqlState" do
+      it "digs the code out of ServerStatementError" do
+        (Errors.toSqlState (Errors.ServerStatementError (Errors.ServerError "23505" "duplicate key" Nothing Nothing Nothing)))
+          `shouldBe` Just "23505"
+
+      it "is Nothing for a decoding failure" do
+        (Errors.toSqlState (Errors.RowStatementError 3 (Errors.CellRowError 1 23 Errors.UnexpectedNullCellError)))
+          `shouldBe` Nothing
+
+      it "is Nothing for a row count mismatch" do
+        (Errors.toSqlState (Errors.UnexpectedRowCountStatementError 1 1 0))
+          `shouldBe` Nothing
+
+    describe "toDetailedText" do
+      it "renders UnexpectedRowCountStatementError with details" do
+        (Errors.toDetailedText (Errors.UnexpectedRowCountStatementError 1 1 0))
+          `shouldBe` "Unexpected number of rows\n  expectedMin: 1\n  expectedMax: 1\n  actual: 0"
+
+      it "renders RowStatementError with nested details" do
+        (Errors.toDetailedText (Errors.RowStatementError 3 (Errors.CellRowError 1 23 Errors.UnexpectedNullCellError)))
+          `shouldBe` "Unexpected null value\n  rowIndex: 3\n  columnIndex: 1\n  oid: 23"
+
+  describe "SessionError" do
+    describe "toMessage" do
+      it "renders StatementSessionError with nested message" do
+        (Errors.toMessage (Errors.StatementSessionError 1 0 "SELECT 1" [] True (Errors.UnexpectedRowCountStatementError 1 1 0)))
+          `shouldBe` "Unexpected number of rows"
+
+      it "renders MissingTypesSessionError" do
+        (Errors.toMessage (Errors.MissingTypesSessionError (HashSet.fromList [(Just "public", "custom_type"), (Nothing, "enum_type")])))
+          `shouldBe` "Types not found in database"
+
+    describe "toDetails" do
+      it "includes statement context and nested error details" do
+        (Errors.toDetails (Errors.StatementSessionError 3 1 "SELECT * FROM users WHERE id = $1" ["42"] True (Errors.ServerStatementError (Errors.ServerError "42P01" "relation does not exist" Nothing Nothing Nothing))))
+          `shouldBe` [ ("totalStatements", "3"),
+                       ("statementIndex", "1"),
+                       ("sql", "SELECT * FROM users WHERE id = $1"),
+                       ("parameters", "42"),
+                       ("prepared", "true"),
+                       ("code", "42P01"),
+                       ("message", "relation does not exist")
+                     ]
+
+      it "includes multiple parameters" do
+        (Errors.toDetails (Errors.StatementSessionError 1 0 "INSERT INTO users (name, age) VALUES ($1, $2)" ["Alice", "30"] False (Errors.UnexpectedRowCountStatementError 1 1 0)))
+          `shouldBe` [ ("totalStatements", "1"),
+                       ("statementIndex", "0"),
+                       ("sql", "INSERT INTO users (name, age) VALUES ($1, $2)"),
+                       ("parameters", "Alice, 30"),
+                       ("prepared", "false"),
+                       ("expectedMin", "1"),
+                       ("expectedMax", "1"),
+                       ("actual", "0")
+                     ]
+
+    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))))
+          `shouldBe` Just "23505"
+
+      it "digs the code out of ScriptSessionError" do
+        (Errors.toSqlState (Errors.ScriptSessionError "DROP TABLE users" (Errors.ServerError "42P01" "relation does not exist" Nothing Nothing Nothing)))
+          `shouldBe` Just "42P01"
+
+      it "is Nothing for StatementSessionError wrapping a non-server error" do
+        (Errors.toSqlState (Errors.StatementSessionError 1 0 "SELECT 1" [] True (Errors.UnexpectedRowCountStatementError 1 1 0)))
+          `shouldBe` Nothing
+
+      it "is Nothing for MissingTypesSessionError" do
+        (Errors.toSqlState (Errors.MissingTypesSessionError (HashSet.fromList [(Just "public", "custom_type")])))
+          `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)))
+          `shouldBe` "Unexpected number of rows\n\
+                     \  totalStatements: 1\n\
+                     \  statementIndex: 0\n\
+                     \  sql: SELECT * FROM users\n\
+                     \  parameters:\n\
+                     \  prepared: true\n\
+                     \  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
+      (Errors.toDetailedText (Errors.ServerError "42601" "syntax error" (Just "Line 1: syntax error\nLine 2: near unexpected token\nLine 3: suggestion here") Nothing Nothing))
+        `shouldBe` "Server error\n\
+                   \  code: 42601\n\
+                   \  message: syntax error\n\
+                   \  detail:\n\
+                   \    Line 1: syntax error\n\
+                   \    Line 2: near unexpected token\n\
+                   \    Line 3: suggestion here"
+
+    it "indents multiline hint values correctly" do
+      (Errors.toDetailedText (Errors.ServerError "42P01" "relation not found" Nothing (Just "Perhaps you meant:\n  users\n  user_accounts\n  user_profiles") Nothing))
+        `shouldBe` "Server error\n\
+                   \  code: 42P01\n\
+                   \  message: relation not found\n\
+                   \  hint:\n\
+                   \    Perhaps you meant:\n\
+                   \      users\n\
+                   \      user_accounts\n\
+                   \      user_profiles"
+
+    it "handles multiline SQL in StatementSessionError" do
+      (Errors.toDetailedText (Errors.StatementSessionError 1 0 "SELECT *\nFROM users\nWHERE id = $1" ["1"] False (Errors.UnexpectedRowCountStatementError 1 1 0)))
+        `shouldBe` "Unexpected number of rows\n\
+                   \  totalStatements: 1\n\
+                   \  statementIndex: 0\n\
+                   \  sql:\n\
+                   \    SELECT *\n\
+                   \    FROM users\n\
+                   \    WHERE id = $1\n\
+                   \  parameters: 1\n\
+                   \  prepared: false\n\
+                   \  expectedMin: 1\n\
+                   \  expectedMax: 1\n\
+                   \  actual: 0"
diff --git a/src/library/Hasql/Codecs/Decoders.hs b/src/library/Hasql/Codecs/Decoders.hs
new file mode 100644
--- /dev/null
+++ b/src/library/Hasql/Codecs/Decoders.hs
@@ -0,0 +1,147 @@
+module Hasql.Codecs.Decoders
+  ( -- * Nullability
+    NullableOrNot.NullableOrNot (..),
+    NullableOrNot.nonNullable,
+    NullableOrNot.nullable,
+
+    -- * Value
+    Value.Value (..),
+    Value.bool,
+    Value.int2,
+    Value.int4,
+    Value.int8,
+    Value.float4,
+    Value.float8,
+    Value.numeric,
+    Value.char,
+    Value.text,
+    Value.varchar,
+    Value.bpchar,
+    Value.bytea,
+    Value.date,
+    Value.timestamp,
+    Value.timestamptz,
+    Value.time,
+    Value.timetz,
+    Value.interval,
+    Value.uuid,
+    Value.inet,
+    Value.macaddr,
+    Value.json,
+    Value.jsonBytes,
+    Value.jsonb,
+    Value.jsonbBytes,
+    Value.int4range,
+    Value.int8range,
+    Value.numrange,
+    Value.tsrange,
+    Value.tstzrange,
+    Value.daterange,
+    Value.int4multirange,
+    Value.int8multirange,
+    Value.nummultirange,
+    Value.tsmultirange,
+    Value.tstzmultirange,
+    Value.datemultirange,
+    Value.citext,
+    array,
+    listArray,
+    vectorArray,
+    composite,
+    record,
+    Value.hstore,
+    Value.enum,
+    Value.custom,
+    Value.refine,
+
+    -- * Array
+    Array.Array,
+    Array.dimension,
+    Array.element,
+
+    -- * Composite
+    Composite.Composite (..),
+    Composite.field,
+  )
+where
+
+import Data.Vector.Generic qualified as GenericVector
+import Hasql.Codecs.Decoders.Array qualified as Array
+import Hasql.Codecs.Decoders.Composite qualified as Composite
+import Hasql.Codecs.Decoders.NullableOrNot qualified as NullableOrNot
+import Hasql.Codecs.Decoders.Value qualified as Value
+import Hasql.CodecsVocab.TypeInfo qualified as CodecsVocab.TypeInfo
+import Hasql.Platform.Prelude
+
+-- * Value
+
+-- |
+-- Lift an 'Array.Array' decoder to a 'Value.Value' decoder.
+{-# INLINEABLE array #-}
+array :: Array.Array a -> Value.Value a
+array decoder = Value.Value (Array.toSchema decoder) (Array.toTypeName decoder) (Array.toBaseOid decoder) (Array.toArrayOid decoder) (Array.toDimensionality decoder) (Array.toValueDecoder decoder)
+
+-- |
+-- Lift a value decoder of element into a unidimensional array decoder producing a list.
+--
+-- This function is merely a shortcut to the following expression:
+--
+-- @
+-- ('array' . 'dimension' Control.Monad.'replicateM' . 'element')
+-- @
+--
+-- Please notice that in case of multidimensional arrays nesting 'listArray' decoder
+-- won't work. You have to explicitly construct the array decoder using 'array'.
+{-# INLINE listArray #-}
+listArray :: NullableOrNot.NullableOrNot Value.Value element -> Value.Value [element]
+listArray = array . Array.dimension replicateM . Array.element
+
+-- |
+-- Lift a value decoder of element into a unidimensional array decoder producing a generic vector.
+--
+-- This function is merely a shortcut to the following expression:
+--
+-- @
+-- ('array' . 'dimension' Data.Vector.Generic.'GenericVector.replicateM' . 'element')
+-- @
+--
+-- Please notice that in case of multidimensional arrays nesting 'vectorArray' decoder
+-- won't work. You have to explicitly construct the array decoder using 'array'.
+{-# INLINE vectorArray #-}
+vectorArray :: (GenericVector.Vector vector element) => NullableOrNot.NullableOrNot Value.Value element -> Value.Value (vector element)
+vectorArray = array . Array.dimension GenericVector.replicateM . Array.element
+
+-- |
+-- Lift a 'Composite.Composite' decoder to a 'Value.Value' decoder for named composite types.
+--
+-- This function is for named composite types where the type name is known.
+-- For anonymous composite types (like those created with ROW constructor),
+-- use 'record' instead.
+{-# INLINEABLE composite #-}
+composite :: Maybe Text -> Text -> Composite.Composite a -> Value.Value a
+composite schema typeName composite =
+  Value.Value
+    schema
+    typeName
+    Nothing
+    Nothing
+    0
+    (Composite.toValueDecoder composite)
+
+-- |
+-- Lift a 'Composite.Composite' decoder to a 'Value.Value' decoder for unnamed composite types.
+--
+-- This is useful for decoding anonymous composites (like those created with ROW constructor)
+-- where no type name is required. Postgres will handle the type automatically.
+{-# INLINEABLE record #-}
+record :: Composite.Composite a -> Value.Value a
+record composite =
+  Value.Value
+    Nothing
+    "record"
+    (Just (CodecsVocab.TypeInfo.toBaseOid typeInfo))
+    (Just (CodecsVocab.TypeInfo.toArrayOid typeInfo))
+    0
+    (Composite.toValueDecoder composite)
+  where
+    typeInfo = CodecsVocab.TypeInfo.record
diff --git a/src/library/Hasql/Codecs/Decoders/Array.hs b/src/library/Hasql/Codecs/Decoders/Array.hs
new file mode 100644
--- /dev/null
+++ b/src/library/Hasql/Codecs/Decoders/Array.hs
@@ -0,0 +1,141 @@
+module Hasql.Codecs.Decoders.Array
+  ( Array,
+    toValueDecoder,
+    toTypeSig,
+    toSchema,
+    toTypeName,
+    toBaseOid,
+    toArrayOid,
+    toDimensionality,
+    dimension,
+    element,
+  )
+where
+
+import Hasql.Codecs.Decoders.NullableOrNot qualified as NullableOrNot
+import Hasql.Codecs.Decoders.Value qualified as Value
+import Hasql.CodecsVocab.QualifiedTypeName qualified as CodecsVocab.QualifiedTypeName
+import Hasql.CodecsVocab.TypeInfo qualified as CodecsVocab.TypeInfo
+import Hasql.Platform.Prelude
+import Hasql.ToBeResolved qualified as ToBeResolved
+import PostgreSQL.Binary.Decoding qualified as Binary
+import TextBuilder qualified
+
+-- |
+-- Binary generic array decoder.
+--
+-- Here's how you can use it to produce a specific array value decoder:
+--
+-- @
+-- x :: 'Value.Value' [[Text]]
+-- x = 'array' ('dimension' 'replicateM' ('dimension' 'replicateM' ('element' ('nonNullable' 'text'))))
+-- @
+data Array a
+  = Array
+      -- | Schema name.
+      (Maybe Text)
+      -- | Type name for the array element.
+      Text
+      -- | Statically known OID for the base (element) type.
+      (Maybe Word32)
+      -- | Statically known OID for the array type.
+      (Maybe Word32)
+      -- | Number of dimensions.
+      Word
+      -- | Decoding function
+      (ToBeResolved.ToBeResolved CodecsVocab.QualifiedTypeName.QualifiedTypeName CodecsVocab.TypeInfo.TypeInfo (Binary.Array a))
+  deriving (Functor)
+
+{-# INLINE toValueDecoder #-}
+toValueDecoder :: Array a -> ToBeResolved.ToBeResolved CodecsVocab.QualifiedTypeName.QualifiedTypeName CodecsVocab.TypeInfo.TypeInfo (Binary.Value a)
+toValueDecoder (Array _ _ _ _ _ decoder) =
+  fmap Binary.array decoder
+
+-- | Get the type signature for the array based on element type name
+{-# INLINE toTypeSig #-}
+toTypeSig :: Array a -> Text
+toTypeSig (Array schemaName elementTypeName _ _ ndims _) =
+  TextBuilder.toText
+    ( mconcat
+        ( mconcat
+            [ foldMap
+                (\s -> [TextBuilder.text s, TextBuilder.char '.'])
+                schemaName,
+              [ TextBuilder.text elementTypeName
+              ],
+              replicate
+                (fromIntegral ndims)
+                (TextBuilder.text "[]")
+            ]
+        )
+    )
+
+toSchema :: Array a -> Maybe Text
+toSchema (Array schema _ _ _ _ _) = schema
+
+-- | Get the type name for the array based on element type name
+{-# INLINE toTypeName #-}
+toTypeName :: Array a -> Text
+toTypeName (Array _ elementTypeName _ _ _ _) =
+  elementTypeName
+
+-- | Get the base OID if statically known
+{-# INLINE toBaseOid #-}
+toBaseOid :: Array a -> Maybe Word32
+toBaseOid (Array _ _ baseOid _ _ _) = baseOid
+
+-- | Get the array OID if statically known
+{-# INLINE toArrayOid #-}
+toArrayOid :: Array a -> Maybe Word32
+toArrayOid (Array _ _ _ arrayOid _ _) = arrayOid
+
+-- | Get the dimensionality of the array
+{-# INLINE toDimensionality #-}
+toDimensionality :: Array a -> Word
+toDimensionality (Array _ _ _ _ ndims _) = ndims
+
+-- * Public API
+
+-- |
+-- Binary function for parsing a dimension of an array.
+-- Provides support for multi-dimensional arrays.
+--
+-- Accepts:
+--
+-- * An implementation of the @replicateM@ function
+-- (@Control.Monad.'Control.Monad.replicateM'@, @Data.Vector.'Data.Vector.replicateM'@),
+-- which determines the output value.
+--
+-- * Binary decoder of its components, which can be either another 'dimension' or 'element'.
+{-# INLINEABLE dimension #-}
+dimension :: (forall m. (Monad m) => Int -> m a -> m b) -> Array a -> Array b
+dimension replicateM (Array schema typeName baseOid arrayOid ndims decoder) =
+  Array
+    schema
+    typeName
+    baseOid
+    arrayOid
+    (succ ndims)
+    (fmap (Binary.dimensionArray replicateM) decoder)
+
+-- |
+-- Lift a 'Value.Value' decoder into an 'Array' decoder for parsing of leaf values.
+{-# INLINEABLE element #-}
+element :: NullableOrNot.NullableOrNot Value.Value a -> Array a
+element = \case
+  NullableOrNot.NonNullable imp ->
+    Array
+      (Value.toSchema imp)
+      (Value.toTypeName imp)
+      (Value.toBaseOid imp)
+      (Value.toArrayOid imp)
+      1
+      (fmap Binary.valueArray (Value.toDecoder imp))
+  NullableOrNot.Nullable imp ->
+    Array
+      (Value.toSchema imp)
+      (Value.toTypeName imp)
+      (Value.toBaseOid imp)
+      (Value.toArrayOid imp)
+      1
+      (fmap Binary.nullableValueArray (Value.toDecoder imp))
diff --git a/src/library/Hasql/Codecs/Decoders/Composite.hs b/src/library/Hasql/Codecs/Decoders/Composite.hs
new file mode 100644
--- /dev/null
+++ b/src/library/Hasql/Codecs/Decoders/Composite.hs
@@ -0,0 +1,50 @@
+module Hasql.Codecs.Decoders.Composite where
+
+import Hasql.Codecs.Decoders.NullableOrNot qualified as NullableOrNot
+import Hasql.Codecs.Decoders.Value qualified as Value
+import Hasql.CodecsVocab.QualifiedTypeName qualified as CodecsVocab.QualifiedTypeName
+import Hasql.CodecsVocab.TypeInfo qualified as CodecsVocab.TypeInfo
+import Hasql.Platform.Prelude
+import Hasql.ToBeResolved qualified as ToBeResolved
+import PostgreSQL.Binary.Decoding qualified as Binary
+
+-- |
+-- Composable decoder of composite values (rows, records).
+newtype Composite a
+  = Composite (ToBeResolved.ToBeResolved CodecsVocab.QualifiedTypeName.QualifiedTypeName CodecsVocab.TypeInfo.TypeInfo (Binary.Composite a))
+  deriving
+    (Functor, Applicative)
+    via (Compose (ToBeResolved.ToBeResolved CodecsVocab.QualifiedTypeName.QualifiedTypeName CodecsVocab.TypeInfo.TypeInfo) Binary.Composite)
+
+toValueDecoder :: Composite a -> ToBeResolved.ToBeResolved CodecsVocab.QualifiedTypeName.QualifiedTypeName CodecsVocab.TypeInfo.TypeInfo (Binary.Value a)
+toValueDecoder (Composite imp) =
+  fmap Binary.composite imp
+
+-- |
+-- Lift a 'Value.Value' decoder into a 'Composite' decoder for parsing of component values.
+field :: NullableOrNot.NullableOrNot Value.Value a -> Composite a
+field = \case
+  NullableOrNot.NonNullable imp ->
+    let dimensionality = Value.toDimensionality imp
+        staticOid = if dimensionality == 0 then Value.toBaseOid imp else Value.toArrayOid imp
+     in case staticOid of
+          Just oid ->
+            Composite (fmap (Binary.typedValueComposite oid) (Value.toDecoder imp))
+          Nothing ->
+            Composite
+              ( (\typeInfo decoder -> Binary.typedValueComposite (if dimensionality == 0 then CodecsVocab.TypeInfo.toBaseOid typeInfo else CodecsVocab.TypeInfo.toArrayOid typeInfo) decoder)
+                  <$> ToBeResolved.lookup (CodecsVocab.QualifiedTypeName.QualifiedTypeName (Value.toSchema imp) (Value.toTypeName imp))
+                  <*> Value.toDecoder imp
+              )
+  NullableOrNot.Nullable imp ->
+    let dimensionality = Value.toDimensionality imp
+        staticOid = if dimensionality == 0 then Value.toBaseOid imp else Value.toArrayOid imp
+     in case staticOid of
+          Just oid ->
+            Composite (fmap (Binary.typedNullableValueComposite oid) (Value.toDecoder imp))
+          Nothing ->
+            Composite
+              ( (\typeInfo decoder -> Binary.typedNullableValueComposite (if dimensionality == 0 then CodecsVocab.TypeInfo.toBaseOid typeInfo else CodecsVocab.TypeInfo.toArrayOid typeInfo) decoder)
+                  <$> ToBeResolved.lookup (CodecsVocab.QualifiedTypeName.QualifiedTypeName (Value.toSchema imp) (Value.toTypeName imp))
+                  <*> Value.toDecoder imp
+              )
diff --git a/src/library/Hasql/Codecs/Decoders/NullableOrNot.hs b/src/library/Hasql/Codecs/Decoders/NullableOrNot.hs
new file mode 100644
--- /dev/null
+++ b/src/library/Hasql/Codecs/Decoders/NullableOrNot.hs
@@ -0,0 +1,27 @@
+module Hasql.Codecs.Decoders.NullableOrNot
+  ( -- * Nullability
+    NullableOrNot (..),
+    nonNullable,
+    nullable,
+  )
+where
+
+import Hasql.Platform.Prelude
+
+-- * Nullability
+
+-- |
+-- Extensional specification of nullability over a generic decoder.
+data NullableOrNot decoder a where
+  NonNullable :: decoder a -> NullableOrNot decoder a
+  Nullable :: decoder a -> NullableOrNot decoder (Maybe a)
+
+-- |
+-- Specify that a decoder produces a non-nullable value.
+nonNullable :: decoder a -> NullableOrNot decoder a
+nonNullable = NonNullable
+
+-- |
+-- Specify that a decoder produces a nullable value.
+nullable :: decoder a -> NullableOrNot decoder (Maybe a)
+nullable = Nullable
diff --git a/src/library/Hasql/Codecs/Decoders/Value.hs b/src/library/Hasql/Codecs/Decoders/Value.hs
new file mode 100644
--- /dev/null
+++ b/src/library/Hasql/Codecs/Decoders/Value.hs
@@ -0,0 +1,450 @@
+module Hasql.Codecs.Decoders.Value
+  ( Value (..),
+    bool,
+    int2,
+    int4,
+    int8,
+    float4,
+    float8,
+    numeric,
+    char,
+    text,
+    varchar,
+    bpchar,
+    bytea,
+    date,
+    timestamp,
+    timestamptz,
+    time,
+    timetz,
+    interval,
+    uuid,
+    inet,
+    macaddr,
+    json,
+    jsonBytes,
+    jsonb,
+    jsonbBytes,
+    int4range,
+    int8range,
+    numrange,
+    tsrange,
+    tstzrange,
+    daterange,
+    int4multirange,
+    int8multirange,
+    nummultirange,
+    tsmultirange,
+    tstzmultirange,
+    datemultirange,
+    citext,
+    custom,
+    refine,
+    hstore,
+    enum,
+    toDimensionality,
+    toDecoder,
+    toSchema,
+    toTypeName,
+    toOid,
+    toBaseOid,
+    toArrayOid,
+    isArray,
+  )
+where
+
+import Data.Aeson qualified as Aeson
+import Data.IP qualified as Iproute
+import Hasql.CodecsVocab.QualifiedTypeName qualified as CodecsVocab.QualifiedTypeName
+import Hasql.CodecsVocab.TypeInfo qualified as CodecsVocab.TypeInfo
+import Hasql.Platform.Prelude hiding (bool)
+import Hasql.ToBeResolved qualified as ToBeResolved
+import PostgreSQL.Binary.Decoding qualified as Binary
+import PostgreSQL.Binary.Range qualified as R
+
+-- |
+-- Value decoder.
+data Value a
+  = Value
+      -- | Schema name.
+      (Maybe Text)
+      -- | Type name.
+      Text
+      -- | Statically known OID for the type.
+      (Maybe Word32)
+      -- | Statically known OID for the array-type with this type as the element.
+      (Maybe Word32)
+      -- | Dimensionality. If 0 then it is a scalar value, otherwise it is an array with that many dimensions.
+      Word
+      -- | Decoding function on a registry of OIDs by type name.
+      (ToBeResolved.ToBeResolved CodecsVocab.QualifiedTypeName.QualifiedTypeName CodecsVocab.TypeInfo.TypeInfo (Binary.Value a))
+  deriving (Functor)
+
+type role Value representational
+
+instance Filterable Value where
+  {-# INLINE mapMaybe #-}
+  mapMaybe fn =
+    refine (maybe (Left "Invalid value") Right . fn)
+
+-- |
+-- Create a decoder from TypeInfo metadata and a decoding function.
+{-# INLINE primitive #-}
+primitive :: Text -> CodecsVocab.TypeInfo.TypeInfo -> Binary.Value a -> Value a
+primitive typeName pti decoder =
+  Value Nothing typeName (Just (CodecsVocab.TypeInfo.toBaseOid pti)) (Just (CodecsVocab.TypeInfo.toArrayOid pti)) 0 (pure decoder)
+
+-- * Static types
+
+-- |
+-- Decoder of the @BOOL@ values.
+{-# INLINEABLE bool #-}
+bool :: Value Bool
+bool = primitive "bool" CodecsVocab.TypeInfo.bool Binary.bool
+
+-- |
+-- Decoder of the @INT2@ values.
+{-# INLINEABLE int2 #-}
+int2 :: Value Int16
+int2 = primitive "int2" CodecsVocab.TypeInfo.int2 Binary.int
+
+-- |
+-- Decoder of the @INT4@ values.
+{-# INLINEABLE int4 #-}
+int4 :: Value Int32
+int4 = primitive "int4" CodecsVocab.TypeInfo.int4 Binary.int
+
+-- |
+-- Decoder of the @INT8@ values.
+{-# INLINEABLE int8 #-}
+int8 :: Value Int64
+int8 =
+  {-# SCC "int8" #-}
+  primitive "int8" CodecsVocab.TypeInfo.int8 ({-# SCC "int8.int" #-} Binary.int)
+
+-- |
+-- Decoder of the @FLOAT4@ values.
+{-# INLINEABLE float4 #-}
+float4 :: Value Float
+float4 = primitive "float4" CodecsVocab.TypeInfo.float4 Binary.float4
+
+-- |
+-- Decoder of the @FLOAT8@ values.
+{-# INLINEABLE float8 #-}
+float8 :: Value Double
+float8 = primitive "float8" CodecsVocab.TypeInfo.float8 Binary.float8
+
+-- |
+-- Decoder of the @NUMERIC@ values.
+{-# INLINEABLE numeric #-}
+numeric :: Value Scientific
+numeric = primitive "numeric" CodecsVocab.TypeInfo.numeric Binary.numeric
+
+-- |
+-- Decoder of the @CHAR@ values.
+-- Note that it supports Unicode values.
+{-# INLINEABLE char #-}
+char :: Value Char
+char = primitive "char" CodecsVocab.TypeInfo.char Binary.char
+
+-- |
+-- Decoder of the @TEXT@ values.
+{-# INLINEABLE text #-}
+text :: Value Text
+text = primitive "text" CodecsVocab.TypeInfo.text Binary.text_strict
+
+-- |
+-- Decoder of the @VARCHAR@ values.
+{-# INLINEABLE varchar #-}
+varchar :: Value Text
+varchar = primitive "varchar" CodecsVocab.TypeInfo.varchar Binary.text_strict
+
+-- |
+-- Decoder of @BPCHAR@ or @CHAR(n)@, @CHARACTER(n)@ values.
+{-# INLINEABLE bpchar #-}
+bpchar :: Value Text
+bpchar = primitive "bpchar" CodecsVocab.TypeInfo.bpchar Binary.text_strict
+
+-- |
+-- Decoder of the @BYTEA@ values.
+{-# INLINEABLE bytea #-}
+bytea :: Value ByteString
+bytea = primitive "bytea" CodecsVocab.TypeInfo.bytea Binary.bytea_strict
+
+-- |
+-- Decoder of the @DATE@ values.
+{-# INLINEABLE date #-}
+date :: Value Day
+date = primitive "date" CodecsVocab.TypeInfo.date Binary.date
+
+-- |
+-- Decoder of the @TIMESTAMP@ values.
+{-# INLINEABLE timestamp #-}
+timestamp :: Value LocalTime
+timestamp = primitive "timestamp" CodecsVocab.TypeInfo.timestamp Binary.timestamp_int
+
+-- |
+-- Decoder of the @TIMESTAMPTZ@ values.
+--
+-- /NOTICE/
+--
+-- Postgres does not store the timezone information of @TIMESTAMPTZ@.
+-- Instead it stores a UTC value and performs silent conversions
+-- to the currently set timezone, when dealt with in the text format.
+-- However this library bypasses the silent conversions
+-- and communicates with Postgres using the UTC values directly.
+{-# INLINEABLE timestamptz #-}
+timestamptz :: Value UTCTime
+timestamptz = primitive "timestamptz" CodecsVocab.TypeInfo.timestamptz Binary.timestamptz_int
+
+-- |
+-- Decoder of the @TIME@ values.
+{-# INLINEABLE time #-}
+time :: Value TimeOfDay
+time = primitive "time" CodecsVocab.TypeInfo.time Binary.time_int
+
+-- |
+-- Decoder of the @TIMETZ@ values.
+--
+-- Unlike in case of @TIMESTAMPTZ@,
+-- Postgres does store the timezone information for @TIMETZ@.
+-- However the Haskell's \"time\" library does not contain any composite type,
+-- that fits the task, so we use a pair of 'TimeOfDay' and 'TimeZone'
+-- to represent a value on the Haskell's side.
+{-# INLINEABLE timetz #-}
+timetz :: Value (TimeOfDay, TimeZone)
+timetz = primitive "timetz" CodecsVocab.TypeInfo.timetz Binary.timetz_int
+
+-- |
+-- Decoder of the @INTERVAL@ values.
+{-# INLINEABLE interval #-}
+interval :: Value DiffTime
+interval = primitive "interval" CodecsVocab.TypeInfo.interval Binary.interval_int
+
+-- |
+-- Decoder of the @UUID@ values.
+{-# INLINEABLE uuid #-}
+uuid :: Value UUID
+uuid = primitive "uuid" CodecsVocab.TypeInfo.uuid Binary.uuid
+
+-- |
+-- Decoder of the @INET@ values.
+{-# INLINEABLE inet #-}
+inet :: Value Iproute.IPRange
+inet = primitive "inet" CodecsVocab.TypeInfo.inet Binary.inet
+
+-- |
+-- Decoder of the @MACADDR@ values.
+--
+-- Represented as a 6-tuple of Word8 values in big endian order. If
+-- you use `ip` library consider using it with `fromOctets`.
+--
+-- > (\(a,b,c,d,e,f) -> fromOctets a b c d e f) <$> macaddr
+{-# INLINEABLE macaddr #-}
+macaddr :: Value (Word8, Word8, Word8, Word8, Word8, Word8)
+macaddr = primitive "macaddr" CodecsVocab.TypeInfo.macaddr Binary.macaddr
+
+-- |
+-- Decoder of the @JSON@ values into a JSON AST.
+{-# INLINEABLE json #-}
+json :: Value Aeson.Value
+json = primitive "json" CodecsVocab.TypeInfo.json Binary.json_ast
+
+-- |
+-- Decoder of the @JSON@ values into a raw JSON 'ByteString'.
+{-# INLINEABLE jsonBytes #-}
+jsonBytes :: (ByteString -> Either Text a) -> Value a
+jsonBytes fn = primitive "json" CodecsVocab.TypeInfo.json (Binary.json_bytes fn)
+
+-- |
+-- Decoder of the @JSONB@ values into a JSON AST.
+{-# INLINEABLE jsonb #-}
+jsonb :: Value Aeson.Value
+jsonb = primitive "jsonb" CodecsVocab.TypeInfo.jsonb Binary.jsonb_ast
+
+-- |
+-- Decoder of the @JSONB@ values into a raw JSON 'ByteString'.
+{-# INLINEABLE jsonbBytes #-}
+jsonbBytes :: (ByteString -> Either Text a) -> Value a
+jsonbBytes fn = primitive "jsonb" CodecsVocab.TypeInfo.jsonb (Binary.jsonb_bytes fn)
+
+-- |
+-- Decoder of the @INT4RANGE@ values.
+{-# INLINEABLE int4range #-}
+int4range :: Value (R.Range Int32)
+int4range = primitive "int4range" CodecsVocab.TypeInfo.int4range Binary.int4range
+
+-- |
+-- Decoder of the @INT8RANGE@ values.
+{-# INLINEABLE int8range #-}
+int8range :: Value (R.Range Int64)
+int8range = primitive "int8range" CodecsVocab.TypeInfo.int8range Binary.int8range
+
+-- |
+-- Decoder of the @NUMRANGE@ values.
+{-# INLINEABLE numrange #-}
+numrange :: Value (R.Range Scientific)
+numrange = primitive "numrange" CodecsVocab.TypeInfo.numrange Binary.numrange
+
+-- |
+-- Decoder of the @TSRANGE@ values.
+{-# INLINEABLE tsrange #-}
+tsrange :: Value (R.Range LocalTime)
+tsrange = primitive "tsrange" CodecsVocab.TypeInfo.tsrange Binary.tsrange_int
+
+-- |
+-- Decoder of the @TSTZRANGE@ values.
+{-# INLINEABLE tstzrange #-}
+tstzrange :: Value (R.Range UTCTime)
+tstzrange = primitive "tstzrange" CodecsVocab.TypeInfo.tstzrange Binary.tstzrange_int
+
+-- |
+-- Decoder of the @DATERANGE@ values.
+{-# INLINEABLE daterange #-}
+daterange :: Value (R.Range Day)
+daterange = primitive "daterange" CodecsVocab.TypeInfo.daterange Binary.daterange
+
+-- |
+-- Decoder of the @INT4MULTIRANGE@ values.
+{-# INLINEABLE int4multirange #-}
+int4multirange :: Value (R.Multirange Int32)
+int4multirange = primitive "int4multirange" CodecsVocab.TypeInfo.int4multirange Binary.int4multirange
+
+-- |
+-- Decoder of the @INT8MULTIRANGE@ values.
+{-# INLINEABLE int8multirange #-}
+int8multirange :: Value (R.Multirange Int64)
+int8multirange = primitive "int8multirange" CodecsVocab.TypeInfo.int8multirange Binary.int8multirange
+
+-- |
+-- Decoder of the @NUMMULTIRANGE@ values.
+{-# INLINEABLE nummultirange #-}
+nummultirange :: Value (R.Multirange Scientific)
+nummultirange = primitive "nummultirange" CodecsVocab.TypeInfo.nummultirange Binary.nummultirange
+
+-- |
+-- Decoder of the @TSMULTIRANGE@ values.
+{-# INLINEABLE tsmultirange #-}
+tsmultirange :: Value (R.Multirange LocalTime)
+tsmultirange = primitive "tsmultirange" CodecsVocab.TypeInfo.tsmultirange Binary.tsmultirange_int
+
+-- |
+-- Decoder of the @TSTZMULTIRANGE@ values.
+{-# INLINEABLE tstzmultirange #-}
+tstzmultirange :: Value (R.Multirange UTCTime)
+tstzmultirange = primitive "tstzmultirange" CodecsVocab.TypeInfo.tstzmultirange Binary.tstzmultirange_int
+
+-- |
+-- Decoder of the @DATEMULTIRANGE@ values.
+{-# INLINEABLE datemultirange #-}
+datemultirange :: Value (R.Multirange Day)
+datemultirange = primitive "datemultirange" CodecsVocab.TypeInfo.datemultirange Binary.datemultirange
+
+-- |
+-- Decoder of the @CITEXT@ values.
+--
+-- Requires the @citext@ extension to be installed in the database.
+{-# INLINEABLE citext #-}
+citext :: Value Text
+citext = Value Nothing "citext" Nothing Nothing 0 (pure Binary.text_strict)
+
+-- |
+-- Low level API for defining custom value decoders.
+{-# INLINEABLE custom #-}
+custom ::
+  -- | Schema name.
+  Maybe Text ->
+  -- | Type name.
+  Text ->
+  -- | Possible static OIDs for the type. The first is for scalar values the second is for arrays.
+  --
+  -- When unspecified, the OIDs will be automatically determined at runtime by looking up by name.
+  Maybe (Word32, Word32) ->
+  -- | Other named types whose OIDs are needed for deserializing.
+  --
+  -- E.g., when decoding composite types you can check the OIDs of its fields against the ones specified by Postgres.
+  --
+  -- When any of the requested types is missing in the database an error will be raised upon the statement execution.
+  [(Maybe Text, Text)] ->
+  -- | Deserialization function in the context of resolved OIDs of the types requested in the previous parameter.
+  --
+  -- It's safe to assume that all of the requested types will be present.
+  -- In case you run the provided lookup function with unmentioned type names it will produce OID of 0 for them, standing for unknown type in Postgres.
+  ( ((Maybe Text, Text) -> (Word32, Word32)) ->
+    ByteString ->
+    Either Text a
+  ) ->
+  Value a
+custom schema typeName staticOids requestedTypes fn =
+  Value
+    schema
+    typeName
+    (fmap fst staticOids)
+    (fmap snd staticOids)
+    0
+    (ToBeResolved.ToBeResolved (fmap CodecsVocab.QualifiedTypeName.fromNameTuple requestedTypes) (\lookup -> Binary.fn (fn (toTuple . lookup . CodecsVocab.QualifiedTypeName.fromNameTuple))))
+  where
+    toTuple typeInfo = (CodecsVocab.TypeInfo.toBaseOid typeInfo, CodecsVocab.TypeInfo.toArrayOid typeInfo)
+
+-- |
+-- Refine a value decoder, lifting the possible error to the session level.
+{-# INLINE refine #-}
+refine :: (a -> Either Text b) -> Value a -> Value b
+refine fn (Value schema typeName typeOid arrayOid dimensionality decoder) =
+  Value schema typeName typeOid arrayOid dimensionality (fmap (Binary.refine fn) decoder)
+
+-- |
+-- Binary generic decoder of @HSTORE@ values.
+--
+-- Here's how you can use it to construct a specific value:
+--
+-- @
+-- x :: Value [(Text, Maybe Text)]
+-- x = hstore 'replicateM'
+-- @
+{-# INLINEABLE hstore #-}
+hstore :: (forall m. (Monad m) => Int -> m (Text, Maybe Text) -> m a) -> Value a
+hstore replicateM =
+  Value Nothing "hstore" Nothing Nothing 0 (pure (Binary.hstore replicateM Binary.text_strict Binary.text_strict))
+
+-- |
+-- Given a partial mapping from text to value, produces a decoder of that value for a named enum type.
+enum ::
+  -- | Schema name.
+  Maybe Text ->
+  -- | Type name.
+  Text ->
+  -- | Mapping from text to value.
+  (Text -> Maybe a) ->
+  Value a
+enum schema typeName mapping =
+  Value schema typeName Nothing Nothing 0 (pure (Binary.enum mapping))
+
+-- * Relations
+
+toDimensionality :: Value a -> Word
+toDimensionality (Value _ _ _ _ dimensionality _) = dimensionality
+
+toSchema :: Value a -> Maybe Text
+toSchema (Value schema _ _ _ _ _) = schema
+
+toTypeName :: Value a -> Text
+toTypeName (Value _ typeName _ _ _ _) = typeName
+
+toOid :: Value a -> Maybe Word32
+toOid (Value _ _ baseOid arrayOid dimensionality _) =
+  if dimensionality > 0
+    then arrayOid
+    else baseOid
+
+toBaseOid :: Value a -> Maybe Word32
+toBaseOid (Value _ _ baseOid _ _ _) = baseOid
+
+toArrayOid :: Value a -> Maybe Word32
+toArrayOid (Value _ _ _ oid _ _) = oid
+
+toDecoder :: Value a -> ToBeResolved.ToBeResolved CodecsVocab.QualifiedTypeName.QualifiedTypeName CodecsVocab.TypeInfo.TypeInfo (Binary.Value a)
+toDecoder (Value _ _ _ _ _ decoder) = decoder
+
+isArray :: Value a -> Bool
+isArray (Value _ _ _ _ dimensionality _) = dimensionality > 0
diff --git a/src/library/Hasql/Codecs/Encoders.hs b/src/library/Hasql/Codecs/Encoders.hs
new file mode 100644
--- /dev/null
+++ b/src/library/Hasql/Codecs/Encoders.hs
@@ -0,0 +1,147 @@
+-- |
+-- A DSL for declaration of statement parameter encoders.
+--
+-- For compactness of names all the types defined here imply being an encoder.
+-- E.g., the `Array` type is an __encoder__ of arrays, not the data-structure itself.
+module Hasql.Codecs.Encoders
+  ( -- * Parameters product
+    Params.Params,
+    Params.noParams,
+    Params.param,
+
+    -- * Nullability
+    NullableOrNot.NullableOrNot,
+    NullableOrNot.nonNullable,
+    NullableOrNot.nullable,
+
+    -- * Value
+    Value.Value,
+    Value.bool,
+    Value.int2,
+    Value.int4,
+    Value.int8,
+    Value.float4,
+    Value.float8,
+    Value.numeric,
+    Value.char,
+    Value.text,
+    Value.varchar,
+    Value.bpchar,
+    Value.bytea,
+    Value.date,
+    Value.timestamp,
+    Value.timestamptz,
+    Value.time,
+    Value.timetz,
+    Value.interval,
+    Value.uuid,
+    Value.inet,
+    Value.macaddr,
+    Value.json,
+    Value.jsonBytes,
+    Value.jsonLazyBytes,
+    Value.jsonb,
+    Value.jsonbBytes,
+    Value.jsonbLazyBytes,
+    Value.int4range,
+    Value.int8range,
+    Value.numrange,
+    Value.tsrange,
+    Value.tstzrange,
+    Value.daterange,
+    Value.int4multirange,
+    Value.int8multirange,
+    Value.nummultirange,
+    Value.tsmultirange,
+    Value.tstzmultirange,
+    Value.datemultirange,
+    Value.citext,
+    Value.name,
+    Value.oid,
+    foldableArray,
+    array,
+    Value.hstore,
+    Value.enum,
+    composite,
+    Value.unknown,
+    Value.custom,
+
+    -- * Array
+    Array.Array,
+    Array.element,
+    Array.dimension,
+
+    -- * Composite
+    Composite.Composite,
+    Composite.field,
+  )
+where
+
+import Hasql.Codecs.Encoders.Array qualified as Array
+import Hasql.Codecs.Encoders.Composite qualified as Composite
+import Hasql.Codecs.Encoders.NullableOrNot qualified as NullableOrNot
+import Hasql.Codecs.Encoders.Params qualified as Params
+import Hasql.Codecs.Encoders.Value qualified as Value
+import Hasql.CodecsVocab.QualifiedTypeName qualified as CodecsVocab.QualifiedTypeName
+import Hasql.CodecsVocab.TypeInfo qualified as CodecsVocab.TypeInfo
+import Hasql.Platform.Prelude hiding (bool)
+import Hasql.ToBeResolved qualified as ToBeResolved
+import PostgreSQL.Binary.Encoding qualified as Binary
+import TextBuilder qualified
+
+-- * Recursive definitions
+
+-- |
+-- Lift a value encoder of element into a unidimensional array encoder of a foldable value.
+--
+-- This function is merely a shortcut to the following expression:
+--
+-- @
+-- ('array' . 'Array.dimension' 'foldl'' . 'Array.element')
+-- @
+--
+-- You can use it like this:
+--
+-- @
+-- vectorOfInts :: Value (Vector Int64)
+-- vectorOfInts = 'foldableArray' ('nonNullable' 'int8')
+-- @
+--
+-- Please notice that in case of multidimensional arrays nesting 'foldableArray' encoder
+-- won't work. You have to explicitly construct the array encoder using 'array'.
+{-# INLINE foldableArray #-}
+foldableArray :: (Foldable foldable) => NullableOrNot.NullableOrNot Value.Value element -> Value.Value (foldable element)
+foldableArray = array . Array.dimension foldl' . Array.element
+
+-- |
+-- Lift an array encoder into a value encoder.
+array :: Array.Array a -> Value.Value a
+array (Array.Array baseTypeSchema baseTypeName _isText dimensionality scalarOidIfKnown arrayOidIfKnown arrayEncoder renderer) =
+  let toEncoder baseOid encode = \input -> Binary.array baseOid (encode input)
+      encoder = case scalarOidIfKnown of
+        Just oid -> fmap (toEncoder oid) arrayEncoder
+        Nothing ->
+          (\typeInfo -> toEncoder (CodecsVocab.TypeInfo.toBaseOid typeInfo))
+            <$> ToBeResolved.lookup (CodecsVocab.QualifiedTypeName.QualifiedTypeName baseTypeSchema baseTypeName)
+            <*> arrayEncoder
+   in Value.Value baseTypeSchema baseTypeName scalarOidIfKnown arrayOidIfKnown dimensionality False encoder renderer
+
+-- |
+-- Lift a composite encoder into a value encoder for named composite types.
+--
+-- This function is for named composite types where the type name is known.
+-- If you need to encode an anonymous composite type (like those created with the ROW constructor),
+-- PostgreSQL itself does not support that.
+composite ::
+  -- | Schema name where the composite type is defined.
+  Maybe Text ->
+  -- | Composite type name.
+  Text ->
+  Composite.Composite a ->
+  Value.Value a
+composite schema name (Composite.Composite request print) =
+  Value.Value schema name Nothing Nothing 0 False encoder printValue
+  where
+    encoder = fmap (Binary.composite .) request
+    printValue val =
+      "ROW (" <> TextBuilder.intercalate ", " (print val) <> ")"
diff --git a/src/library/Hasql/Codecs/Encoders/Array.hs b/src/library/Hasql/Codecs/Encoders/Array.hs
new file mode 100644
--- /dev/null
+++ b/src/library/Hasql/Codecs/Encoders/Array.hs
@@ -0,0 +1,102 @@
+module Hasql.Codecs.Encoders.Array where
+
+import Hasql.Codecs.Encoders.NullableOrNot qualified as NullableOrNot
+import Hasql.Codecs.Encoders.Value qualified as Value
+import Hasql.CodecsVocab.QualifiedTypeName qualified as CodecsVocab.QualifiedTypeName
+import Hasql.CodecsVocab.TypeInfo qualified as CodecsVocab.TypeInfo
+import Hasql.Platform.Prelude
+import Hasql.ToBeResolved qualified as ToBeResolved
+import PostgreSQL.Binary.Encoding qualified as Binary
+import TextBuilder qualified as TextBuilder
+
+-- |
+-- Generic array encoder.
+--
+-- Here's an example of its usage:
+--
+-- @
+-- someParamsEncoder :: 'Params' [[Int64]]
+-- someParamsEncoder = 'param' ('nonNullable' ('array' ('dimension' 'foldl'' ('dimension' 'foldl'' ('element' ('nonNullable' 'int8'))))))
+-- @
+--
+-- Please note that the PostgreSQL @IN@ keyword does not accept an array, but rather a syntactical list of
+-- values, thus this encoder is not suited for that. Use a @value = ANY($1)@ condition instead.
+data Array a
+  = Array
+      -- | Schema name, if any.
+      (Maybe Text)
+      -- | Type name.
+      Text
+      -- | Text format?
+      Bool
+      -- | Dimensionality. If 0 then it is not an array, but a scalar value.
+      Word
+      -- | OID of the element type.
+      (Maybe Word32)
+      -- | OID of the array type.
+      (Maybe Word32)
+      -- | Serialization function, deferring the names of types that must be looked up at runtime.
+      (ToBeResolved.ToBeResolved CodecsVocab.QualifiedTypeName.QualifiedTypeName CodecsVocab.TypeInfo.TypeInfo (a -> Binary.Array))
+      -- | Render function for error messages.
+      (a -> TextBuilder.TextBuilder)
+
+instance Contravariant Array where
+  contramap fn (Array schemaName typeName textFormat dimensionality valueOid arrayOid elEncoder elRenderer) =
+    Array schemaName typeName textFormat dimensionality valueOid arrayOid (fmap (\encode -> encode . fn) elEncoder) (elRenderer . fn)
+
+-- |
+-- Lifts a 'Value.Value' encoder into an 'Array' encoder.
+element :: NullableOrNot.NullableOrNot Value.Value a -> Array a
+element = \case
+  NullableOrNot.NonNullable (Value.Value schemaName typeName scalarOid arrayOid dimensionality textFormat serialize print) ->
+    Array
+      schemaName
+      typeName
+      textFormat
+      dimensionality
+      scalarOid
+      arrayOid
+      (fmap (Binary.encodingArray .) serialize)
+      print
+  NullableOrNot.Nullable (Value.Value schemaName typeName scalarOid arrayOid dimensionality textFormat serialize print) ->
+    let maybeSerialize encode =
+          maybe Binary.nullArray (Binary.encodingArray . encode)
+        maybePrint =
+          maybe (TextBuilder.string "null") print
+     in Array
+          schemaName
+          typeName
+          textFormat
+          dimensionality
+          scalarOid
+          arrayOid
+          (fmap maybeSerialize serialize)
+          maybePrint
+
+-- |
+-- Encoder of an array dimension,
+-- which thus provides support for multidimensional arrays.
+--
+-- Accepts:
+--
+-- * An implementation of the left-fold operation,
+-- such as @Data.Foldable.'foldl''@,
+-- which determines the input value.
+--
+-- * A component encoder, which can be either another 'dimension' or 'element'.
+{-# INLINE dimension #-}
+dimension :: (forall a. (a -> b -> a) -> a -> c -> a) -> Array b -> Array c
+dimension fold (Array schemaName typeName textFormat dimensionality valueOid arrayOid elEncoder elRenderer) =
+  let encoder =
+        Binary.dimensionArray fold
+      renderer els =
+        let folded =
+              let step builder el =
+                    if TextBuilder.isEmpty builder
+                      then TextBuilder.char '[' <> elRenderer el
+                      else builder <> TextBuilder.string ", " <> elRenderer el
+               in fold step mempty els
+         in if TextBuilder.isEmpty folded
+              then TextBuilder.string "[]"
+              else folded <> TextBuilder.char ']'
+   in Array schemaName typeName textFormat (succ dimensionality) valueOid arrayOid (fmap encoder elEncoder) renderer
diff --git a/src/library/Hasql/Codecs/Encoders/Composite.hs b/src/library/Hasql/Codecs/Encoders/Composite.hs
new file mode 100644
--- /dev/null
+++ b/src/library/Hasql/Codecs/Encoders/Composite.hs
@@ -0,0 +1,73 @@
+module Hasql.Codecs.Encoders.Composite where
+
+import Hasql.Codecs.Encoders.NullableOrNot qualified as NullableOrNot
+import Hasql.Codecs.Encoders.Value qualified as Value
+import Hasql.CodecsVocab.QualifiedTypeName qualified as CodecsVocab.QualifiedTypeName
+import Hasql.CodecsVocab.TypeInfo qualified as CodecsVocab.TypeInfo
+import Hasql.Platform.Prelude hiding (bool)
+import Hasql.ToBeResolved qualified as ToBeResolved
+import PostgreSQL.Binary.Encoding qualified as Binary
+import TextBuilder qualified
+
+-- |
+-- Composite or row-types encoder.
+data Composite a
+  = Composite
+      -- | Serialization function, deferring the names of types that must be looked up at runtime.
+      (ToBeResolved.ToBeResolved CodecsVocab.QualifiedTypeName.QualifiedTypeName CodecsVocab.TypeInfo.TypeInfo (a -> Binary.Composite))
+      -- | Render function for error messages.
+      (a -> [TextBuilder.TextBuilder])
+
+instance Contravariant Composite where
+  contramap f (Composite request print) =
+    Composite (fmap (. f) request) (print . f)
+
+instance Divisible Composite where
+  divide f (Composite requestL printL) (Composite requestR printR) =
+    Composite
+      ( liftA2
+          (\encodeL encodeR val -> case f val of (lVal, rVal) -> encodeL lVal <> encodeR rVal)
+          requestL
+          requestR
+      )
+      (\val -> case f val of (lVal, rVal) -> printL lVal <> printR rVal)
+  conquer = mempty
+
+instance Semigroup (Composite a) where
+  Composite requestL printL <> Composite requestR printR =
+    Composite
+      (liftA2 (\encodeL encodeR val -> encodeL val <> encodeR val) requestL requestR)
+      (\val -> printL val <> printR val)
+
+instance Monoid (Composite a) where
+  mempty = Composite (pure mempty) mempty
+
+-- | Single field of a row-type.
+field :: NullableOrNot.NullableOrNot Value.Value a -> Composite a
+field = \case
+  NullableOrNot.NonNullable (Value.Value schemaName typeName scalarOid arrayOid dimensionality _ serialize print) ->
+    let staticOid = if dimensionality == 0 then scalarOid else arrayOid
+        toField oid encode = \val -> Binary.field oid (encode val)
+     in case staticOid of
+          Just oid ->
+            Composite (fmap (toField oid) serialize) (\val -> [print val])
+          Nothing ->
+            Composite
+              ( (\typeInfo -> toField (if dimensionality == 0 then CodecsVocab.TypeInfo.toBaseOid typeInfo else CodecsVocab.TypeInfo.toArrayOid typeInfo))
+                  <$> ToBeResolved.lookup (CodecsVocab.QualifiedTypeName.QualifiedTypeName schemaName typeName)
+                  <*> serialize
+              )
+              (\val -> [print val])
+  NullableOrNot.Nullable (Value.Value schemaName typeName scalarOid arrayOid dimensionality _ serialize print) ->
+    let staticOid = if dimensionality == 0 then scalarOid else arrayOid
+        toField oid encode = maybe (Binary.nullField oid) (Binary.field oid . encode)
+     in case staticOid of
+          Just oid ->
+            Composite (fmap (toField oid) serialize) (maybe ["NULL"] (\val -> [print val]))
+          Nothing ->
+            Composite
+              ( (\typeInfo -> toField (if dimensionality == 0 then CodecsVocab.TypeInfo.toBaseOid typeInfo else CodecsVocab.TypeInfo.toArrayOid typeInfo))
+                  <$> ToBeResolved.lookup (CodecsVocab.QualifiedTypeName.QualifiedTypeName schemaName typeName)
+                  <*> serialize
+              )
+              (maybe ["NULL"] (\val -> [print val]))
diff --git a/src/library/Hasql/Codecs/Encoders/NullableOrNot.hs b/src/library/Hasql/Codecs/Encoders/NullableOrNot.hs
new file mode 100644
--- /dev/null
+++ b/src/library/Hasql/Codecs/Encoders/NullableOrNot.hs
@@ -0,0 +1,19 @@
+module Hasql.Codecs.Encoders.NullableOrNot where
+
+import Hasql.Platform.Prelude
+
+-- |
+-- Extensional specification of nullability over a generic encoder.
+data NullableOrNot encoder a where
+  NonNullable :: encoder a -> NullableOrNot encoder a
+  Nullable :: encoder a -> NullableOrNot encoder (Maybe a)
+
+-- |
+-- Specify that an encoder produces a non-nullable value.
+nonNullable :: encoder a -> NullableOrNot encoder a
+nonNullable = NonNullable
+
+-- |
+-- Specify that an encoder produces a nullable value.
+nullable :: encoder a -> NullableOrNot encoder (Maybe a)
+nullable = Nullable
diff --git a/src/library/Hasql/Codecs/Encoders/Params.hs b/src/library/Hasql/Codecs/Encoders/Params.hs
new file mode 100644
--- /dev/null
+++ b/src/library/Hasql/Codecs/Encoders/Params.hs
@@ -0,0 +1,195 @@
+module Hasql.Codecs.Encoders.Params
+  ( Params,
+    noParams,
+    param,
+    toColumnsMetadata,
+    toUnknownTypes,
+    toSerializer,
+    toPrinter,
+  )
+where
+
+import Data.Vector qualified as Vector
+import Hasql.Codecs.Encoders.NullableOrNot qualified as NullableOrNot
+import Hasql.Codecs.Encoders.Value qualified as Value
+import Hasql.CodecsVocab qualified as CodecsVocab
+import Hasql.CodecsVocab.QualifiedTypeName qualified as CodecsVocab.QualifiedTypeName
+import Hasql.CodecsVocab.TypeRef qualified as CodecsVocab.TypeRef
+import Hasql.CodecsVocab.TypeShape (TypeShape (..))
+import Hasql.Platform.Prelude
+import Hasql.ToBeResolved qualified as ToBeResolved
+import PostgreSQL.Binary.Encoding qualified as Binary
+import TextBuilder qualified
+
+-- | Frozen per-parameter type shapes: type reference, dimensionality, text-format flag.
+toColumnsMetadata :: Params a -> Vector TypeShape
+toColumnsMetadata (Params _ _ columnsMetadata _) = freezeColumnsMetadata columnsMetadata
+  where
+    freezeColumnsMetadata =
+      Vector.fromList . toList
+
+toUnknownTypes :: Params a -> HashSet CodecsVocab.QualifiedTypeName
+toUnknownTypes (Params _ (ToBeResolved.ToBeResolved unknownTypes _) _ _) =
+  fromList unknownTypes
+
+-- | Serialise params to encoded wire values given a resolver of type names to their OIDs.
+toSerializer :: Params a -> (CodecsVocab.QualifiedTypeName -> CodecsVocab.TypeInfo) -> a -> [Maybe ByteString]
+toSerializer (Params _ (ToBeResolved.ToBeResolved _ serializer) _ _) resolve = serializer resolve
+
+-- | Render params in human-readable form (for error reporting).
+toPrinter :: Params a -> a -> [Text]
+toPrinter (Params _ _ _ printer) = toList . printer
+
+-- |
+-- Encoder of some representation of a parameters product.
+--
+-- Has instances of 'Contravariant', 'Divisible' and 'Monoid',
+-- which you can use to compose multiple parameters together.
+-- E.g.,
+--
+-- @
+-- someParamsEncoder :: 'Params' (Int64, Maybe Text)
+-- someParamsEncoder =
+--   ('fst' '>$<' 'param' ('nonNullable' 'int8')) '<>'
+--   ('snd' '>$<' 'param' ('nullable' 'text'))
+-- @
+--
+-- As a general solution for tuples of any arity, instead of 'fst' and 'snd',
+-- consider the functions of the @contrazip@ family
+-- from the "contravariant-extras" package.
+-- E.g., here's how you can achieve the same as the above:
+--
+-- @
+-- someParamsEncoder :: 'Params' (Int64, Maybe Text)
+-- someParamsEncoder =
+--   'contrazip2' ('param' ('nonNullable' 'int8')) ('param' ('nullable' 'text'))
+-- @
+--
+-- Here's how you can implement encoders for custom composite types:
+--
+-- @
+-- data Person = Person { name :: Text, gender :: Gender, age :: Int }
+--
+-- data Gender = Male | Female
+--
+-- personParams :: 'Params' Person
+-- personParams =
+--   (name '>$<' 'param' ('nonNullable' 'text')) '<>'
+--   (gender '>$<' 'param' ('nonNullable' genderValue)) '<>'
+--   ('fromIntegral' . age '>$<' 'param' ('nonNullable' 'int8'))
+--
+-- genderValue :: 'Value.Value' Gender
+-- genderValue = 'enum' Nothing (Just "gender") genderText where
+--   genderText gender = case gender of
+--     Male -> "male"
+--     Female -> "female"
+-- @
+data Params a = Params
+  { size :: Int,
+    -- | Serialization function, deferring the names of types that must be looked up at runtime.
+    request :: ToBeResolved.ToBeResolved CodecsVocab.QualifiedTypeName CodecsVocab.TypeInfo (a -> [Maybe ByteString]),
+    -- | Type shape for each parameter.
+    columnsMetadata :: DList TypeShape,
+    printer :: a -> DList Text
+  }
+
+instance Contravariant Params where
+  contramap fn (Params size request columnsMetadata printer) =
+    Params size (fmap (. fn) request) columnsMetadata (printer . fn)
+
+instance Divisible Params where
+  divide
+    divisor
+    (Params leftSize leftRequest leftColumnsMetadata leftPrinter)
+    (Params rightSize rightRequest rightColumnsMetadata rightPrinter) =
+      Params
+        { size = leftSize + rightSize,
+          request =
+            liftA2
+              ( \leftSerializer rightSerializer input -> case divisor input of
+                  (leftInput, rightInput) -> leftSerializer leftInput <> rightSerializer rightInput
+              )
+              leftRequest
+              rightRequest,
+          columnsMetadata = leftColumnsMetadata <> rightColumnsMetadata,
+          printer = \input -> case divisor input of
+            (leftInput, rightInput) -> leftPrinter leftInput <> rightPrinter rightInput
+        }
+  conquer =
+    Params
+      { size = 0,
+        request = pure mempty,
+        columnsMetadata = mempty,
+        printer = mempty
+      }
+
+instance Semigroup (Params a) where
+  Params leftSize leftRequest leftColumnsMetadata leftPrinter <> Params rightSize rightRequest rightColumnsMetadata rightPrinter =
+    Params
+      { size = leftSize + rightSize,
+        request = liftA2 (\leftSerializer rightSerializer input -> leftSerializer input <> rightSerializer input) leftRequest rightRequest,
+        columnsMetadata = leftColumnsMetadata <> rightColumnsMetadata,
+        printer = \input -> leftPrinter input <> rightPrinter input
+      }
+
+instance Monoid (Params a) where
+  mempty = conquer
+
+value :: Value.Value a -> Params a
+value (Value.Value schemaName typeName scalarOid arrayOid dimensionality textFormat serialize print) =
+  let staticOid = if dimensionality == 0 then scalarOid else arrayOid
+      toRequest = fmap (\encode -> pure . Just . Binary.encodingBytes . encode)
+      printer = pure . TextBuilder.toText . print
+      size = 1
+   in case staticOid of
+        Just oid ->
+          Params
+            { size,
+              request = toRequest serialize,
+              columnsMetadata = pure (TypeShape (CodecsVocab.TypeRef.KnownOid oid) dimensionality textFormat),
+              printer
+            }
+        Nothing ->
+          let key = CodecsVocab.QualifiedTypeName.QualifiedTypeName schemaName typeName
+           in Params
+                { size,
+                  request = toRequest (ToBeResolved.lookup key *> serialize),
+                  columnsMetadata = pure (TypeShape (CodecsVocab.TypeRef.NamedType key) dimensionality textFormat),
+                  printer
+                }
+
+nullableValue :: Value.Value a -> Params (Maybe a)
+nullableValue (Value.Value schemaName typeName scalarOid arrayOid dimensionality textFormat serialize print) =
+  let staticOid = if dimensionality == 0 then scalarOid else arrayOid
+      toRequest = fmap (\encode -> pure . fmap (Binary.encodingBytes . encode))
+      printer = pure . maybe "null" (TextBuilder.toText . print)
+      size = 1
+   in case staticOid of
+        Just oid ->
+          Params
+            { size,
+              request = toRequest serialize,
+              columnsMetadata = pure (TypeShape (CodecsVocab.TypeRef.KnownOid oid) dimensionality textFormat),
+              printer
+            }
+        Nothing ->
+          let key = CodecsVocab.QualifiedTypeName.QualifiedTypeName schemaName typeName
+           in Params
+                { size,
+                  request = toRequest (ToBeResolved.lookup key *> serialize),
+                  columnsMetadata = pure (TypeShape (CodecsVocab.TypeRef.NamedType key) dimensionality textFormat),
+                  printer
+                }
+
+-- |
+-- No parameters. Same as `mempty` and `conquered`.
+noParams :: Params ()
+noParams = mempty
+
+-- |
+-- Lift a single parameter encoder, with its nullability specified,
+-- associating it with a single placeholder.
+param :: NullableOrNot.NullableOrNot Value.Value a -> Params a
+param = \case
+  NullableOrNot.NonNullable valueEnc -> value valueEnc
+  NullableOrNot.Nullable valueEnc -> nullableValue valueEnc
diff --git a/src/library/Hasql/Codecs/Encoders/Value.hs b/src/library/Hasql/Codecs/Encoders/Value.hs
new file mode 100644
--- /dev/null
+++ b/src/library/Hasql/Codecs/Encoders/Value.hs
@@ -0,0 +1,450 @@
+module Hasql.Codecs.Encoders.Value where
+
+import ByteString.StrictBuilder qualified
+import Data.Aeson qualified as Aeson
+import Data.ByteString.Lazy qualified as LazyByteString
+import Data.IP qualified as Iproute
+import Hasql.CodecsVocab qualified as CodecsVocab
+import Hasql.CodecsVocab.QualifiedTypeName qualified as CodecsVocab.QualifiedTypeName
+import Hasql.CodecsVocab.TypeInfo qualified as CodecsVocab.TypeInfo
+import Hasql.Platform.Prelude
+import Hasql.ToBeResolved qualified as ToBeResolved
+import PostgreSQL.Binary.Encoding qualified as Binary
+import PostgreSQL.Binary.Range qualified as Range
+import TextBuilder qualified as TextBuilder
+
+-- |
+-- Value encoder.
+data Value a
+  = Value
+      -- | Schema name, if any.
+      (Maybe Text)
+      -- | Type name.
+      Text
+      -- | Statically known OID for the type.
+      -- When unspecified, the OID may be determined at runtime by looking up by name.
+      (Maybe Word32)
+      -- | Statically known OID for the array-type with this type as the element.
+      -- When unspecified, the OID may be determined at runtime by looking up by name.
+      -- It may also mean that there may be no array type containing this type, which is the case in attempts to double-nest arrays.
+      (Maybe Word32)
+      -- | Dimensionality. If 0 then it is not an array, but a scalar value.
+      Word
+      -- | Text format?
+      Bool
+      -- | Serialization function, deferring the names of types that must be looked up at runtime.
+      (ToBeResolved.ToBeResolved CodecsVocab.QualifiedTypeName CodecsVocab.TypeInfo (a -> Binary.Encoding))
+      -- | Render function for error messages.
+      (a -> TextBuilder.TextBuilder)
+
+instance Contravariant Value where
+  {-# INLINE contramap #-}
+  contramap f (Value schemaName typeName valueOid arrayOid dimensionality textFormat serialize render) =
+    Value schemaName typeName valueOid arrayOid dimensionality textFormat (fmap (\encode -> encode . f) serialize) (render . f)
+
+{-# INLINE primitive #-}
+primitive :: Text -> Bool -> CodecsVocab.TypeInfo -> (a -> Binary.Encoding) -> (a -> TextBuilder.TextBuilder) -> Value a
+primitive typeName isText typeInfo encode render =
+  Value
+    Nothing
+    typeName
+    (Just (CodecsVocab.TypeInfo.toBaseOid typeInfo))
+    (Just (CodecsVocab.TypeInfo.toArrayOid typeInfo))
+    0
+    isText
+    (pure encode)
+    render
+
+-- |
+-- Encoder of @BOOL@ values.
+{-# INLINEABLE bool #-}
+bool :: Value Bool
+bool = primitive "bool" False CodecsVocab.TypeInfo.bool Binary.bool (TextBuilder.string . show)
+
+-- |
+-- Encoder of @INT2@ values.
+{-# INLINEABLE int2 #-}
+int2 :: Value Int16
+int2 = primitive "int2" False CodecsVocab.TypeInfo.int2 Binary.int2_int16 (TextBuilder.string . show)
+
+-- |
+-- Encoder of @INT4@ values.
+{-# INLINEABLE int4 #-}
+int4 :: Value Int32
+int4 = primitive "int4" False CodecsVocab.TypeInfo.int4 Binary.int4_int32 (TextBuilder.string . show)
+
+-- |
+-- Encoder of @INT8@ values.
+{-# INLINEABLE int8 #-}
+int8 :: Value Int64
+int8 = primitive "int8" False CodecsVocab.TypeInfo.int8 Binary.int8_int64 (TextBuilder.string . show)
+
+-- |
+-- Encoder of @FLOAT4@ values.
+{-# INLINEABLE float4 #-}
+float4 :: Value Float
+float4 = primitive "float4" False CodecsVocab.TypeInfo.float4 Binary.float4 (TextBuilder.string . show)
+
+-- |
+-- Encoder of @FLOAT8@ values.
+{-# INLINEABLE float8 #-}
+float8 :: Value Double
+float8 = primitive "float8" False CodecsVocab.TypeInfo.float8 Binary.float8 (TextBuilder.string . show)
+
+-- |
+-- Encoder of @NUMERIC@ values.
+{-# INLINEABLE numeric #-}
+numeric :: Value Scientific
+numeric = primitive "numeric" False CodecsVocab.TypeInfo.numeric Binary.numeric (TextBuilder.string . show)
+
+-- |
+-- Encoder of @CHAR@ values.
+--
+-- Note that it supports Unicode values and
+-- identifies itself under the @TEXT@ OID because of that.
+{-# INLINEABLE char #-}
+char :: Value Char
+char = primitive "char" False CodecsVocab.TypeInfo.text Binary.char_utf8 (TextBuilder.string . show)
+
+-- |
+-- Encoder of @TEXT@ values.
+{-# INLINEABLE text #-}
+text :: Value Text
+text = primitive "text" False CodecsVocab.TypeInfo.text Binary.text_strict (TextBuilder.string . show)
+
+-- |
+-- Encoder of @VARCHAR@ values.
+{-# INLINEABLE varchar #-}
+varchar :: Value Text
+varchar = primitive "varchar" False CodecsVocab.TypeInfo.varchar Binary.text_strict (TextBuilder.string . show)
+
+-- |
+-- Encoder of @BPCHAR@ or @CHAR(n)@, @CHARACTER(n)@ values.
+{-# INLINEABLE bpchar #-}
+bpchar :: Value Text
+bpchar = primitive "bpchar" False CodecsVocab.TypeInfo.bpchar Binary.text_strict (TextBuilder.string . show)
+
+-- |
+-- Encoder of @BYTEA@ values.
+{-# INLINEABLE bytea #-}
+bytea :: Value ByteString
+bytea = primitive "bytea" False CodecsVocab.TypeInfo.bytea Binary.bytea_strict (TextBuilder.string . show)
+
+-- |
+-- Encoder of @DATE@ values.
+{-# INLINEABLE date #-}
+date :: Value Day
+date = primitive "date" False CodecsVocab.TypeInfo.date Binary.date (TextBuilder.string . show)
+
+-- |
+-- Encoder of @TIMESTAMP@ values.
+{-# INLINEABLE timestamp #-}
+timestamp :: Value LocalTime
+timestamp = primitive "timestamp" False CodecsVocab.TypeInfo.timestamp Binary.timestamp_int (TextBuilder.string . show)
+
+-- |
+-- Encoder of @TIMESTAMPTZ@ values.
+{-# INLINEABLE timestamptz #-}
+timestamptz :: Value UTCTime
+timestamptz = primitive "timestamptz" False CodecsVocab.TypeInfo.timestamptz Binary.timestamptz_int (TextBuilder.string . show)
+
+-- |
+-- Encoder of @TIME@ values.
+{-# INLINEABLE time #-}
+time :: Value TimeOfDay
+time = primitive "time" False CodecsVocab.TypeInfo.time Binary.time_int (TextBuilder.string . show)
+
+-- |
+-- Encoder of @TIMETZ@ values.
+{-# INLINEABLE timetz #-}
+timetz :: Value (TimeOfDay, TimeZone)
+timetz = primitive "timetz" False CodecsVocab.TypeInfo.timetz Binary.timetz_int (TextBuilder.string . show)
+
+-- |
+-- Encoder of @INTERVAL@ values.
+{-# INLINEABLE interval #-}
+interval :: Value DiffTime
+interval = primitive "interval" False CodecsVocab.TypeInfo.interval Binary.interval_int (TextBuilder.string . show)
+
+-- |
+-- Encoder of @UUID@ values.
+{-# INLINEABLE uuid #-}
+uuid :: Value UUID
+uuid = primitive "uuid" False CodecsVocab.TypeInfo.uuid Binary.uuid (TextBuilder.string . show)
+
+-- |
+-- Encoder of @INET@ values.
+{-# INLINEABLE inet #-}
+inet :: Value Iproute.IPRange
+inet = primitive "inet" False CodecsVocab.TypeInfo.inet Binary.inet (TextBuilder.string . show)
+
+-- |
+-- Encoder of @MACADDR@ values.
+--
+-- Represented as a 6-tuple of Word8 values in big endian order. If
+-- you use `ip` library you can convert using its `toOctets`.
+--
+-- > toOctets >$< macaddr
+{-# INLINEABLE macaddr #-}
+macaddr :: Value (Word8, Word8, Word8, Word8, Word8, Word8)
+macaddr = primitive "macaddr" False CodecsVocab.TypeInfo.macaddr Binary.macaddr (TextBuilder.string . show)
+
+-- |
+-- Encoder of @JSON@ values from JSON AST.
+{-# INLINEABLE json #-}
+json :: Value Aeson.Value
+json = primitive "json" False CodecsVocab.TypeInfo.json Binary.json_ast (TextBuilder.string . show)
+
+-- |
+-- Encoder of @JSON@ values from raw JSON.
+{-# INLINEABLE jsonBytes #-}
+jsonBytes :: Value ByteString
+jsonBytes = primitive "json" False CodecsVocab.TypeInfo.json Binary.json_bytes (TextBuilder.string . show)
+
+-- |
+-- Encoder of @JSON@ values from raw JSON as lazy ByteString.
+{-# INLINEABLE jsonLazyBytes #-}
+jsonLazyBytes :: Value LazyByteString.ByteString
+jsonLazyBytes = primitive "json" False CodecsVocab.TypeInfo.json Binary.json_bytes_lazy (TextBuilder.string . show)
+
+-- |
+-- Encoder of @JSONB@ values from JSON AST.
+{-# INLINEABLE jsonb #-}
+jsonb :: Value Aeson.Value
+jsonb = primitive "jsonb" False CodecsVocab.TypeInfo.jsonb Binary.jsonb_ast (TextBuilder.string . show)
+
+-- |
+-- Encoder of @JSONB@ values from raw JSON.
+{-# INLINEABLE jsonbBytes #-}
+jsonbBytes :: Value ByteString
+jsonbBytes = primitive "jsonb" False CodecsVocab.TypeInfo.jsonb Binary.jsonb_bytes (TextBuilder.string . show)
+
+-- |
+-- Encoder of @JSONB@ values from raw JSON as lazy ByteString.
+{-# INLINEABLE jsonbLazyBytes #-}
+jsonbLazyBytes :: Value LazyByteString.ByteString
+jsonbLazyBytes = primitive "jsonb" False CodecsVocab.TypeInfo.jsonb Binary.jsonb_bytes_lazy (TextBuilder.string . show)
+
+-- |
+-- Encoder of @OID@ values.
+{-# INLINEABLE oid #-}
+oid :: Value Int32
+oid = primitive "oid" False CodecsVocab.TypeInfo.oid Binary.int4_int32 (TextBuilder.string . show)
+
+-- |
+-- Encoder of @NAME@ values.
+{-# INLINEABLE name #-}
+name :: Value Text
+name = primitive "name" False CodecsVocab.TypeInfo.name Binary.text_strict (TextBuilder.string . show)
+
+-- |
+-- Encoder of @INT4RANGE@ values.
+{-# INLINEABLE int4range #-}
+int4range :: Value (Range.Range Int32)
+int4range = primitive "int4range" False CodecsVocab.TypeInfo.int4range Binary.int4range (TextBuilder.string . show)
+
+-- |
+-- Encoder of @INT8RANGE@ values.
+{-# INLINEABLE int8range #-}
+int8range :: Value (Range.Range Int64)
+int8range = primitive "int8range" False CodecsVocab.TypeInfo.int8range Binary.int8range (TextBuilder.string . show)
+
+-- |
+-- Encoder of @NUMRANGE@ values.
+{-# INLINEABLE numrange #-}
+numrange :: Value (Range.Range Scientific)
+numrange = primitive "numrange" False CodecsVocab.TypeInfo.numrange Binary.numrange (TextBuilder.string . show)
+
+-- |
+-- Encoder of @TSRANGE@ values.
+{-# INLINEABLE tsrange #-}
+tsrange :: Value (Range.Range LocalTime)
+tsrange = primitive "tsrange" False CodecsVocab.TypeInfo.tsrange Binary.tsrange_int (TextBuilder.string . show)
+
+-- |
+-- Encoder of @TSTZRANGE@ values.
+{-# INLINEABLE tstzrange #-}
+tstzrange :: Value (Range.Range UTCTime)
+tstzrange = primitive "tstzrange" False CodecsVocab.TypeInfo.tstzrange Binary.tstzrange_int (TextBuilder.string . show)
+
+-- |
+-- Encoder of @DATERANGE@ values.
+{-# INLINEABLE daterange #-}
+daterange :: Value (Range.Range Day)
+daterange = primitive "daterange" False CodecsVocab.TypeInfo.daterange Binary.daterange (TextBuilder.string . show)
+
+-- |
+-- Encoder of @INT4MULTIRANGE@ values.
+{-# INLINEABLE int4multirange #-}
+int4multirange :: Value (Range.Multirange Int32)
+int4multirange = primitive "int4multirange" False CodecsVocab.TypeInfo.int4multirange Binary.int4multirange (TextBuilder.string . show)
+
+-- |
+-- Encoder of @INT8MULTIRANGE@ values.
+{-# INLINEABLE int8multirange #-}
+int8multirange :: Value (Range.Multirange Int64)
+int8multirange = primitive "int8multirange" False CodecsVocab.TypeInfo.int8multirange Binary.int8multirange (TextBuilder.string . show)
+
+-- |
+-- Encoder of @NUMMULTIRANGE@ values.
+{-# INLINEABLE nummultirange #-}
+nummultirange :: Value (Range.Multirange Scientific)
+nummultirange = primitive "nummultirange" False CodecsVocab.TypeInfo.nummultirange Binary.nummultirange (TextBuilder.string . show)
+
+-- |
+-- Encoder of @TSMULTIRANGE@ values.
+{-# INLINEABLE tsmultirange #-}
+tsmultirange :: Value (Range.Multirange LocalTime)
+tsmultirange = primitive "tsmultirange" False CodecsVocab.TypeInfo.tsmultirange Binary.tsmultirange_int (TextBuilder.string . show)
+
+-- |
+-- Encoder of @TSTZMULTIRANGE@ values.
+{-# INLINEABLE tstzmultirange #-}
+tstzmultirange :: Value (Range.Multirange UTCTime)
+tstzmultirange = primitive "tstzmultirange" False CodecsVocab.TypeInfo.tstzmultirange Binary.tstzmultirange_int (TextBuilder.string . show)
+
+-- |
+-- Encoder of @DATEMULTIRANGE@ values.
+{-# INLINEABLE datemultirange #-}
+datemultirange :: Value (Range.Multirange Day)
+datemultirange = primitive "datemultirange" False CodecsVocab.TypeInfo.datemultirange Binary.datemultirange (TextBuilder.string . show)
+
+-- |
+-- Encoder of @CITEXT@ values.
+--
+-- Requires the @citext@ extension to be installed in the database.
+{-# INLINEABLE citext #-}
+citext :: Value Text
+citext =
+  Value
+    Nothing
+    "citext"
+    Nothing
+    Nothing
+    0
+    False
+    (pure Binary.text_strict)
+    (TextBuilder.string . show)
+
+-- |
+-- Given a function which maps a value into a textual enum label used on the DB side,
+-- produces an encoder of that value for a named enum type.
+{-# INLINEABLE enum #-}
+enum ::
+  -- | Schema name where the enum type is defined.
+  Maybe Text ->
+  -- | Enum type name.
+  Text ->
+  -- | Mapping function from value to enum label.
+  (a -> Text) ->
+  Value a
+enum schemaName typeName mapping =
+  Value
+    schemaName
+    typeName
+    Nothing
+    Nothing
+    0
+    False
+    (fmap (\_typeInfo -> Binary.text_strict . mapping) (ToBeResolved.lookup (CodecsVocab.QualifiedTypeName schemaName typeName)))
+    (TextBuilder.text . mapping)
+
+-- |
+-- Identifies the value with the PostgreSQL's \"unknown\" type,
+-- thus leaving it up to Postgres to infer the actual type of the value.
+--
+-- The value transmitted is any value encoded in the Postgres' Text data format.
+-- For reference, see the
+-- <https://www.postgresql.org/docs/10/static/protocol-overview.html#PROTOCOL-FORMAT-CODES Formats and Format Codes>
+-- section of the Postgres' documentation.
+--
+-- __Warning:__ Do not use this as part of composite encoders like 'array' since
+-- it is the only encoder that doesn't use the binary format.
+{-# DEPRECATED unknown "Use 'custom' instead." #-}
+{-# INLINEABLE unknown #-}
+unknown :: Value ByteString
+unknown = primitive "unknown" True CodecsVocab.TypeInfo.unknown Binary.bytea_strict (TextBuilder.string . show)
+
+-- |
+-- Low level API for defining custom value encoders.
+{-# INLINEABLE custom #-}
+custom ::
+  -- | Schema name where the type is defined.
+  Maybe Text ->
+  -- | Type name.
+  Text ->
+  -- | Possible static OIDs for the type. The first is for scalar values the second is for arrays.
+  --
+  -- When unspecified, the OIDs will be automatically determined at runtime by looking up by name.
+  Maybe (Word32, Word32) ->
+  -- | Other named types whose OIDs are needed for serializing.
+  --
+  -- E.g., when encoding composite types Postgres requires specifying OIDs of all of its fields.
+  --
+  -- When any of the requested types is missing in the database an error will be raised upon the statement execution.
+  [(Maybe Text, Text)] ->
+  -- | Serialization function in the context of resolved OIDs of the types requested in the previous parameter.
+  --
+  -- It's safe to assume that all of the requested types will be present.
+  -- In case you run the provided lookup function with unmentioned type names it will produce OID of 0 for them, standing for unknown type in Postgres.
+  ( ((Maybe Text, Text) -> (Word32, Word32)) ->
+    a ->
+    ByteString
+  ) ->
+  -- | Render function for error messages.
+  (a -> Text) ->
+  Value a
+custom schemaName typeName staticOids requiredTypes encode render =
+  Value
+    schemaName
+    typeName
+    (fmap fst staticOids)
+    (fmap snd staticOids)
+    0
+    False
+    ( ToBeResolved.ToBeResolved
+        (fmap CodecsVocab.QualifiedTypeName.fromNameTuple requiredTypes)
+        ( \resolve ->
+            ByteString.StrictBuilder.bytes
+              . encode
+                ( \name ->
+                    let typeInfo = resolve (CodecsVocab.QualifiedTypeName.fromNameTuple name)
+                     in (CodecsVocab.TypeInfo.toBaseOid typeInfo, CodecsVocab.TypeInfo.toArrayOid typeInfo)
+                )
+        )
+    )
+    (TextBuilder.text . render)
+
+-- |
+-- Encoder of @HSTORE@ values from a foldable container of key-value pairs.
+--
+-- The value part can be @Nothing@ to represent a NULL value in the hstore.
+{-# INLINEABLE hstore #-}
+hstore :: (Foldable foldable) => Value (foldable (Text, Maybe Text))
+hstore =
+  Value
+    Nothing
+    "hstore"
+    Nothing
+    Nothing
+    0
+    False
+    (pure Binary.hStore_foldable)
+    renderHstore
+  where
+    renderHstore items =
+      mconcat
+        [ TextBuilder.text "hstore(",
+          TextBuilder.intercalate ", " (foldMap (\pair -> [renderPair pair]) items),
+          TextBuilder.text ")"
+        ]
+    renderPair (key, maybeValue) =
+      mconcat
+        [ TextBuilder.text "(",
+          TextBuilder.string (show key),
+          TextBuilder.text ", ",
+          case maybeValue of
+            Nothing -> TextBuilder.text "NULL"
+            Just value -> TextBuilder.string (show value),
+          TextBuilder.text ")"
+        ]
diff --git a/src/library/Hasql/Connection.hs b/src/library/Hasql/Connection.hs
new file mode 100644
--- /dev/null
+++ b/src/library/Hasql/Connection.hs
@@ -0,0 +1,222 @@
+-- |
+-- This module provides a low-level effectful API dealing with the connections to the database.
+module Hasql.Connection
+  ( Connection,
+    acquire,
+    release,
+    use,
+  )
+where
+
+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
+import Hasql.ConnectionState qualified as ConnectionState
+import Hasql.ConnectionState.StatementCache qualified as StatementCache
+import Hasql.Engine.Contexts.Session qualified as Session
+import Hasql.Engine.Errors
+import Hasql.Platform.Prelude
+import Pqi (Adapter)
+import Pqi qualified as Pq
+
+-- |
+-- A single connection to the database.
+newtype Connection
+  = 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.
+--
+-- The first argument is an 'Pqi.Adapter', which defines the backend
+-- implementation used to talk to PostgreSQL (for example, libpq via the
+-- <https://hackage.haskell.org/package/pqi-ffi pqi-ffi> package, or a pure
+-- Haskell implementation via the
+-- <https://hackage.haskell.org/package/pqi-native pqi-native> package).
+-- This is the only place in the library where users choose the adapter.
+--
+-- This function:
+--
+-- - Opens a PostgreSQL connection using the constructed connection string.
+-- - Validates that the connection is healthy.
+-- - Checks the server version for compatibility.
+-- - Initializes session-level settings (encoding and message verbosity).
+--
+-- On success, returns a 'Connection' wrapped in 'Right'.
+-- On failure, returns a classified 'AcquireError' in 'Left'.
+acquire ::
+  Adapter ->
+  Settings.Settings ->
+  IO (Either AcquireError Connection)
+acquire adapter settings =
+  {-# SCC "acquire" #-}
+  runExceptT do
+    let config = Config.construct settings
+
+    -- Connect:
+    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 version:
+            version <- lift (ServerVersion.load pqConnection)
+            when (version < ServerVersion.minimum) do
+              case version of
+                ServerVersion.ServerVersion major minor patch ->
+                  throwError (VersionTooOldAcquireError major minor patch)
+
+            -- 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))
+
+            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)
+
+          -- 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
+    -- 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)
+
+    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 var) =
+  mask_ do
+    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.
+--
+-- 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 \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 (ConnectionUseError _) -> finish
+          _ -> putMVar var (Just newState)
+
+        pure result
diff --git a/src/library/Hasql/Connection/Config.hs b/src/library/Hasql/Connection/Config.hs
new file mode 100644
--- /dev/null
+++ b/src/library/Hasql/Connection/Config.hs
@@ -0,0 +1,15 @@
+module Hasql.Connection.Config where
+
+import Hasql.Platform.Prelude
+
+data Config
+  = Config
+  { -- | Pre-rendered connection string.
+    connectionString :: ByteString,
+    noPreparedStatements :: Bool
+  }
+  deriving stock (Eq)
+
+-- | For values that can be compiled to 'Config'.
+class Constructs a where
+  construct :: a -> Config
diff --git a/src/library/Hasql/Connection/ServerVersion.hs b/src/library/Hasql/Connection/ServerVersion.hs
new file mode 100644
--- /dev/null
+++ b/src/library/Hasql/Connection/ServerVersion.hs
@@ -0,0 +1,71 @@
+module Hasql.Connection.ServerVersion
+  ( ServerVersion (..),
+    toText,
+    fromInt,
+    minimum,
+
+    -- * PQ operations
+    load,
+  )
+where
+
+import Hasql.Platform.Prelude hiding (minimum)
+import Pqi qualified as Pq
+import TextBuilder qualified
+
+data ServerVersion = ServerVersion Int Int Int
+  deriving stock (Eq, Ord, Show)
+
+-- |
+-- >>> fromInt 10000
+-- ServerVersion 1 0 0
+--
+-- >>> fromInt 100001
+-- ServerVersion 10 1 0
+--
+-- >>> fromInt 110000
+-- ServerVersion 11 0 0
+--
+-- >>> fromInt 90105
+-- ServerVersion 9 1 5
+--
+-- >>> fromInt 90200
+-- ServerVersion 9 2 0
+--
+-- Ref: https://www.postgresql.org/docs/18/libpq-status.html#LIBPQ-PQSERVERVERSION
+fromInt :: Int -> ServerVersion
+fromInt x =
+  if x < 100_000
+    then fromPre10Int x
+    else fromPost10Int x
+
+fromPost10Int :: Int -> ServerVersion
+fromPost10Int x =
+  let (major, minor) = divMod x 10_000
+   in ServerVersion major minor 0
+
+fromPre10Int :: Int -> ServerVersion
+fromPre10Int = evalState do
+  patch <- state (swap . flip divMod 100)
+  minor <- state (swap . flip divMod 100)
+  major <- get
+  pure (ServerVersion major minor patch)
+
+toText :: ServerVersion -> Text
+toText (ServerVersion major minor patch) =
+  (TextBuilder.toText . mconcat)
+    [ TextBuilder.decimal major,
+      ".",
+      TextBuilder.decimal minor,
+      ".",
+      TextBuilder.decimal patch
+    ]
+
+-- | Minimum supported version.
+minimum :: ServerVersion
+minimum = ServerVersion 9 0 0
+
+-- | Load from PQ connection.
+load :: Pq.Connection -> IO ServerVersion
+load connection =
+  fromInt <$> Pq.serverVersion connection
diff --git a/src/library/Hasql/Connection/Settings.hs b/src/library/Hasql/Connection/Settings.hs
new file mode 100644
--- /dev/null
+++ b/src/library/Hasql/Connection/Settings.hs
@@ -0,0 +1,136 @@
+module Hasql.Connection.Settings
+  ( -- * Settings
+    Settings,
+
+    -- * Constructors
+    host,
+    hostAndPort,
+    user,
+    password,
+    dbname,
+    applicationName,
+    other,
+    noPreparedStatements,
+    connectionString,
+  )
+where
+
+import Data.Text qualified as Text
+import Hasql.Connection.Config qualified as Config
+import Hasql.Platform.Prelude
+import PostgresqlConnectionString qualified as ConnectionString
+
+-- | Connection settings.
+--
+-- This is a monoid, so you can combine multiple settings using 'mappend' ('<>').
+-- The rightmost setting takes precedence in case of conflicts.
+--
+-- With OverloadedStrings, you can declare settings using connection strings directly.
+--
+-- For example, using a key-value format:
+--
+-- >>> "host=localhost port=5432 user=myuser dbname=mydb" :: Settings
+-- "postgresql://myuser@localhost:5432/mydb"
+--
+-- Or using a URI format:
+--
+-- >>> "postgresql://myuser@localhost:5432/mydb" :: Settings
+-- "postgresql://myuser@localhost:5432/mydb"
+--
+-- You can achieve the same effect by constructing from a 'Text' value:
+--
+-- >>> connectionString "host=localhost port=5432 user=myuser dbname=mydb"
+-- "postgresql://myuser@localhost:5432/mydb"
+--
+-- Or use the provided constructors for better type safety and clarity:
+--
+-- >>> hostAndPort "localhost" 5432 <> user "myuser" <> dbname "mydb"
+-- "postgresql://myuser@localhost:5432/mydb"
+newtype Settings
+  = Settings ConnectionString.ConnectionString
+  deriving newtype (Eq, IsString, Show, Semigroup, Monoid)
+
+-- | This instance allows interfacing with the internal Config.Config type without affecting the public API or requiring complex module hierarchies.
+instance Config.Constructs Settings where
+  construct (Settings connectionString) =
+    case ConnectionString.interceptParam "no_prepared_statements" connectionString of
+      Just (value, connectionString) ->
+        let noPreparedStatements = interpretTextAsBool value
+         in pack connectionString noPreparedStatements
+      Nothing -> pack connectionString False
+    where
+      interpretTextAsBool value = case Text.toLower value of
+        "1" -> True
+        "true" -> True
+        "t" -> True
+        "yes" -> True
+        "y" -> True
+        "on" -> True
+        _ -> False
+
+      pack connectionString noPreparedStatements =
+        Config.Config
+          { connectionString =
+              let textUrl = ConnectionString.toUrl connectionString
+               in encodeUtf8 textUrl,
+            noPreparedStatements
+          }
+
+-- * Constructors
+
+-- | Whether prepared statements are disabled.
+--
+-- 'False' by default.
+--
+-- When 'True', even the statements marked as preparable will be executed without preparation at the cost of reduced performance.
+--
+-- This is useful when dealing with proxying applications like @pgbouncer@, which may be incompatible with prepared statements.
+-- Consult their docs or just provide this setting to stay on the safe side.
+-- It should be noted that starting from version @1.21.0@ @pgbouncer@ now does provide support for prepared statements.
+noPreparedStatements :: Bool -> Settings
+noPreparedStatements =
+  Settings . ConnectionString.param "no_prepared_statements" . bool "false" "true"
+
+-- | Host domain name or IP-address.
+--
+-- To specify multiple alternate hosts, combine the produced settings via 'Monoid'.
+host :: Text -> Settings
+host host =
+  Settings (ConnectionString.host host)
+
+-- | Host domain name or IP-address and port.
+--
+-- Specifying a port without a host is not allowed due to how PostgreSQL handles connection strings.
+--
+-- This function creates a single host-port pair. To specify multiple alternate hosts, combine the results of multiple 'hostAndPort' calls using the 'Monoid' instance.
+hostAndPort :: Text -> Word16 -> Settings
+hostAndPort host port =
+  Settings (ConnectionString.hostAndPort host port)
+
+-- | User name.
+user :: Text -> Settings
+user = Settings . ConnectionString.user
+
+-- | Password.
+password :: Text -> Settings
+password = Settings . ConnectionString.password
+
+-- | Database name.
+dbname :: Text -> Settings
+dbname = Settings . ConnectionString.dbname
+
+-- | Application name.
+applicationName :: Text -> Settings
+applicationName = Settings . ConnectionString.param "application_name"
+
+-- | Other param.
+other :: Text -> Text -> Settings
+other key = Settings . ConnectionString.param key
+
+-- | Construct from a connection string in either URI or key-value format.
+--
+-- See the [PostgreSQL documentation](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING) for details on the format.
+--
+-- If the connection string is invalid, it will be treated as empty.
+connectionString :: Text -> Settings
+connectionString = Settings . either (const mempty) id . ConnectionString.parse
diff --git a/src/library/Hasql/Decoders.hs b/src/library/Hasql/Decoders.hs
new file mode 100644
--- /dev/null
+++ b/src/library/Hasql/Decoders.hs
@@ -0,0 +1,91 @@
+-- |
+-- A DSL for declaration of result decoders.
+module Hasql.Decoders
+  ( -- * Result
+    Result,
+    noResult,
+    rowsAffected,
+    singleRow,
+
+    -- ** Specialized multi-row results
+    rowMaybe,
+    rowVector,
+    rowList,
+
+    -- ** Multi-row traversers
+    foldlRows,
+    foldrRows,
+
+    -- * Row
+    Row,
+    column,
+
+    -- * Nullability
+    NullableOrNot,
+    nonNullable,
+    nullable,
+
+    -- * Value
+    Value,
+    bool,
+    int2,
+    int4,
+    int8,
+    float4,
+    float8,
+    numeric,
+    char,
+    text,
+    varchar,
+    bpchar,
+    bytea,
+    date,
+    timestamp,
+    timestamptz,
+    time,
+    timetz,
+    interval,
+    uuid,
+    inet,
+    macaddr,
+    json,
+    jsonBytes,
+    jsonb,
+    jsonbBytes,
+    int4range,
+    int8range,
+    numrange,
+    tsrange,
+    tstzrange,
+    daterange,
+    int4multirange,
+    int8multirange,
+    nummultirange,
+    tsmultirange,
+    tstzmultirange,
+    datemultirange,
+    citext,
+    array,
+    listArray,
+    vectorArray,
+    composite,
+    record,
+    hstore,
+    enum,
+    custom,
+    refine,
+
+    -- * Array
+    Array,
+    dimension,
+    element,
+
+    -- * Composite
+    Composite,
+    field,
+  )
+where
+
+import Hasql.Codecs.Decoders
+import Hasql.Engine.Decoders.Result
+import Hasql.Engine.Decoders.Row
diff --git a/src/library/Hasql/Encoders.hs b/src/library/Hasql/Encoders.hs
new file mode 100644
--- /dev/null
+++ b/src/library/Hasql/Encoders.hs
@@ -0,0 +1,80 @@
+-- |
+-- A DSL for declaration of statement parameter encoders.
+--
+-- For compactness of names all the types defined here imply being an encoder.
+-- E.g., the `Array` type is an __encoder__ of arrays, not the data-structure itself.
+module Hasql.Encoders
+  ( -- * Parameters product
+    Params,
+    noParams,
+    param,
+
+    -- * Nullability
+    NullableOrNot,
+    nonNullable,
+    nullable,
+
+    -- * Value
+    Value,
+    bool,
+    int2,
+    int4,
+    int8,
+    float4,
+    float8,
+    numeric,
+    char,
+    text,
+    varchar,
+    bpchar,
+    bytea,
+    date,
+    timestamp,
+    timestamptz,
+    time,
+    timetz,
+    interval,
+    uuid,
+    inet,
+    macaddr,
+    json,
+    jsonBytes,
+    jsonLazyBytes,
+    jsonb,
+    jsonbBytes,
+    jsonbLazyBytes,
+    int4range,
+    int8range,
+    numrange,
+    tsrange,
+    tstzrange,
+    daterange,
+    int4multirange,
+    int8multirange,
+    nummultirange,
+    tsmultirange,
+    tstzmultirange,
+    datemultirange,
+    citext,
+    name,
+    oid,
+    foldableArray,
+    array,
+    hstore,
+    enum,
+    composite,
+    custom,
+    unknown,
+
+    -- * Array
+    Array,
+    element,
+    dimension,
+
+    -- * Composite
+    Composite,
+    field,
+  )
+where
+
+import Hasql.Codecs.Encoders
diff --git a/src/library/Hasql/Engine/Contexts/Pipeline.hs b/src/library/Hasql/Engine/Contexts/Pipeline.hs
new file mode 100644
--- /dev/null
+++ b/src/library/Hasql/Engine/Contexts/Pipeline.hs
@@ -0,0 +1,282 @@
+module Hasql.Engine.Contexts.Pipeline
+  ( Pipeline,
+    run,
+    statement,
+  )
+where
+
+import Data.HashMap.Strict qualified as HashMap
+import Data.HashSet qualified as HashSet
+import Hasql.CodecsVocab qualified as CodecsVocab
+import Hasql.CodecsVocab.QualifiedTypeName qualified as CodecsVocab.QualifiedTypeName
+import Hasql.Comms.Roundtrip qualified as Comms.Roundtrip
+import Hasql.ConnectionState qualified as ConnectionState
+import Hasql.ConnectionState.OidCache qualified as OidCache
+import Hasql.ConnectionState.StatementCache qualified as StatementCache
+import Hasql.Engine.Errors qualified as Errors
+import Hasql.Engine.PqProcedures.SelectTypeInfo qualified as PqProcedures.SelectTypeInfo
+import Hasql.Engine.Statement qualified as Statement
+import Hasql.Platform.Prelude
+import Pqi qualified as Pq
+
+run ::
+  Pipeline a ->
+  ConnectionState.ConnectionState ->
+  IO (Either Errors.UseError a, ConnectionState.ConnectionState)
+run (Pipeline totalStatements unknownTypes runPipeline) connectionState@ConnectionState.ConnectionState {..} = do
+  let missingTypes = OidCache.selectUnknownNames unknownTypes oidCache
+  resolvedOidCache <-
+    if HashSet.null missingTypes
+      then pure (Right oidCache)
+      else do
+        oidCacheUpdates <-
+          PqProcedures.SelectTypeInfo.run connection (PqProcedures.SelectTypeInfo.SelectTypeInfo missingTypes)
+        pure $ case oidCacheUpdates of
+          Left err -> Left err
+          Right oidCacheUpdates ->
+            let foundTypes = HashMap.keysSet oidCacheUpdates
+                notFoundTypes = HashSet.difference missingTypes foundTypes
+             in if not (HashSet.null 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)
+    Right newOidCache -> do
+      let (roundtrip, newStatementCache) =
+            runPipeline 0 preparedStatements newOidCache statementCache
+
+      -- 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 _tag details ->
+                    Errors.fromSendError details
+                  Comms.Roundtrip.ServerError 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 ->
+                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,
+          connectionState
+            { ConnectionState.oidCache = newOidCache,
+              ConnectionState.statementCache = finalStatementCache
+            }
+        )
+
+-- |
+-- Composable abstraction over the execution of queries in [the pipeline mode](https://www.postgresql.org/docs/current/libpq-pipeline-mode.html).
+--
+-- It allows you to issue multiple queries to the server in much fewer network transactions.
+-- If the amounts of sent and received data do not surpass the buffer sizes in the driver and on the server it will be just a single roundtrip.
+-- Typically the buffer size is 8KB.
+--
+-- This execution mode is much more efficient than running queries directly from 'Hasql.Session.Session', because in session every statement execution involves a dedicated network roundtrip.
+--
+-- An obvious question rises then: why not execute all queries like that?
+-- In situations where the parameters depend on the result of another query it is impossible to execute them in parallel, because the client needs to receive the results of one query before sending the request to execute the next.
+-- This reasoning is essentially the same as the one for the difference between 'Applicative' and 'Monad'.
+-- That's why 'Pipeline' does not have the 'Monad' instance.
+--
+-- To execute 'Pipeline' lift it into 'Hasql.Session.Session' via 'Hasql.Session.pipeline'.
+--
+-- == Examples
+--
+-- === Insert-Many or Batch-Insert
+--
+-- You can use pipeline to turn a single-row insert query into an efficient multi-row insertion session.
+-- In effect this should be comparable in performance to issuing a single multi-row insert statement.
+--
+-- Given the following definition in a Statements module:
+--
+-- @
+-- insertOrder :: 'Hasql.Statement.Statement' OrderDetails OrderId
+-- @
+--
+-- You can lift it into the following session
+--
+-- @
+-- insertOrders :: [OrderDetails] -> 'Hasql.Session.Session' [OrderId]
+-- insertOrders orders =
+--   'Hasql.Session.pipeline' $
+--     for orders $ \order ->
+--       'Hasql.Pipeline.statement' order Statements.insertOrder
+-- @
+--
+-- === Combining Queries
+--
+-- Given the following definitions in a Statements module:
+--
+-- @
+-- selectOrderDetails :: 'Hasql.Statement.Statement' OrderId (Maybe OrderDetails)
+-- selectOrderProducts :: 'Hasql.Statement.Statement' OrderId [OrderProduct]
+-- selectOrderFinancialTransactions :: 'Hasql.Statement.Statement' OrderId [FinancialTransaction]
+-- @
+--
+-- You can combine them into a session using the `ApplicativeDo` extension as follows:
+--
+-- @
+-- selectEverythingAboutOrder :: OrderId -> 'Hasql.Session.Session' (Maybe OrderDetails, [OrderProduct], [FinancialTransaction])
+-- selectEverythingAboutOrder orderId =
+--   'Hasql.Session.pipeline' $ do
+--     details <- 'Hasql.Pipeline.statement' orderId Statements.selectOrderDetails
+--     products <- 'Hasql.Pipeline.statement' orderId Statements.selectOrderProducts
+--     transactions <- 'Hasql.Pipeline.statement' orderId Statements.selectOrderFinancialTransactions
+--     pure (details, products, transactions)
+-- @
+data Pipeline a
+  = Pipeline
+      -- | Amount of statements in this pipeline.
+      Int
+      -- | Names of types that are used in this pipeline.
+      --
+      -- They will be used to pre-resolve type OIDs before running the pipeline providing them in OidCache.
+      -- It can be assumed in the execution function that these types are always present in the cache.
+      -- To achieve that property we will be validating the presence of all requested types in the database or failing before running the pipeline.
+      -- In the execution function we will be defaulting to OID 0 for unknown types as a fallback in case of bugs.
+      (HashSet CodecsVocab.QualifiedTypeName)
+      -- | Function that runs the pipeline.
+      --
+      -- The integer parameter indicates the current offset of the statement in the pipeline (0-based).
+      --
+      -- The boolean parameter indicates whether preparable statements should be prepared.
+      --
+      -- OidCache is provided in which the names of types used in this pipeline are already resolved.
+      --
+      -- The function takes the current statement cache and returns a tuple of:
+      -- 1. The actual roundtrip action to be executed in the pipeline.
+      -- 2. The updated statement cache after composing this part of the pipeline.
+      --
+      -- The resulting cache is optimistic: on failure we recover the last known
+      -- committed cache from statement tag carried by roundtrip errors.
+      ( Int ->
+        Bool ->
+        OidCache.OidCache ->
+        StatementCache.StatementCache ->
+        (Comms.Roundtrip.Roundtrip StatementTag a, StatementCache.StatementCache)
+      )
+
+-- | Tag of a statement execution in a pipeline,
+-- carried by roundtrip errors to identify the statement and recover the cache.
+data StatementTag
+  = StatementTag
+      -- | Offset of the statement in the pipeline (0-based).
+      Int
+      -- | SQL.
+      ByteString
+      -- | Parameters in a human-readable form.
+      [Text]
+      -- | Whether the statement is prepared.
+      Bool
+      -- | The cache to recover to on an ordinary failure.
+      StatementCache.StatementCache
+      -- | The cache to recover to when the failure is a @Parse@ hitting a
+      -- 42P05 name collision, i.e., with this statement's own mapping
+      -- committed. Since 42P05 can only ever be reported in response to our
+      -- own @Parse@, this is only consulted for the tag attached to the
+      -- @Parse@ step; elsewhere it's the same as the ordinary recovery
+      -- cache.
+      StatementCache.StatementCache
+  deriving stock (Show, Eq)
+
+-- * Instances
+
+instance Functor Pipeline where
+  fmap f (Pipeline count unknownTypes run) = Pipeline count unknownTypes \offset usePreparedStatements oidCache cache ->
+    let (roundtrip, newStatementCache) = run offset usePreparedStatements oidCache cache
+     in (fmap f roundtrip, newStatementCache)
+
+instance Applicative Pipeline where
+  pure a =
+    Pipeline 0 mempty (\_ _ _ cache -> (pure a, cache))
+
+  Pipeline lCount leftUnknownTypes lRun <*> Pipeline rCount rightUnknownTypes rRun =
+    let unknownTypes = leftUnknownTypes <> rightUnknownTypes
+     in Pipeline (lCount + rCount) unknownTypes \offset usePreparedStatements oidCache statementCache ->
+          let (lRoundtrip, statementCache1) = lRun offset usePreparedStatements oidCache statementCache
+              offset1 = offset + lCount
+              (rRoundtrip, statementCache2) = rRun offset1 usePreparedStatements oidCache statementCache1
+           in (lRoundtrip <*> rRoundtrip, statementCache2)
+
+-- * Construction
+
+-- |
+-- Execute a statement in pipelining mode.
+statement ::
+  Statement.Statement params result ->
+  params ->
+  Pipeline result
+statement stmt params =
+  Pipeline 1 (Statement.unknownTypes stmt) run
+  where
+    sql = Statement.sql stmt
+    run offset usePreparedStatements oidCache =
+      if prepare
+        then runPrepared
+        else runUnprepared
+      where
+        resolve = OidCache.toResolver oidCache
+
+        (oidList, valueAndFormatList) =
+          Statement.compilePreparedStatementData stmt resolve params
+
+        prepare =
+          usePreparedStatements && Statement.isPrepared stmt
+
+        tag soFarStatementCache collisionStatementCache =
+          StatementTag
+            offset
+            sql
+            (Statement.printer stmt params)
+            prepare
+            soFarStatementCache
+            collisionStatementCache
+
+        runPrepared statementCache =
+          (roundtrip, newStatementCache)
+          where
+            (isNew, remoteKey, newStatementCache) =
+              case StatementCache.lookup sql oidList statementCache of
+                Just remoteKey -> (False, remoteKey, statementCache)
+                Nothing ->
+                  let (remoteKey, newStatementCache) = StatementCache.insert sql oidList statementCache
+                   in (True, remoteKey, newStatementCache)
+
+            roundtrip =
+              when
+                isNew
+                (Comms.Roundtrip.prepare (tag statementCache newStatementCache) remoteKey sql oidList)
+                *> Comms.Roundtrip.queryPrepared (tag newStatementCache newStatementCache) remoteKey encodedParams Pq.Binary decoder'
+              where
+                encodedParams =
+                  valueAndFormatList
+                    & fmap (fmap (\(bytes, format) -> (bytes, bool Pq.Binary Pq.Text format)))
+
+        runUnprepared statementCache =
+          (roundtrip, statementCache)
+          where
+            roundtrip =
+              Comms.Roundtrip.queryParams (tag statementCache statementCache) sql encodedParams Pq.Binary decoder'
+              where
+                encodedParams =
+                  Statement.compileUnpreparedStatementData stmt resolve params
+                    & fmap (fmap (\(oid, bytes, format) -> (oid, bytes, bool Pq.Binary Pq.Text format)))
+
+        decoder' =
+          Statement.decoder stmt resolve
diff --git a/src/library/Hasql/Engine/Contexts/Session.hs b/src/library/Hasql/Engine/Contexts/Session.hs
new file mode 100644
--- /dev/null
+++ b/src/library/Hasql/Engine/Contexts/Session.hs
@@ -0,0 +1,281 @@
+module Hasql.Engine.Contexts.Session where
+
+import Data.HashMap.Strict qualified as HashMap
+import Data.HashSet qualified as HashSet
+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.Contexts.Pipeline qualified as Pipeline
+import Hasql.Engine.Errors qualified as Errors
+import Hasql.Engine.PqProcedures.SelectTypeInfo qualified as PqProcedures.SelectTypeInfo
+import Hasql.Engine.Statement qualified as Statement
+import Hasql.Platform.Prelude
+import Pqi qualified as Pq
+
+-- |
+-- A sequence of operations to be executed in the context of a single database connection with exclusive access to it.
+--
+-- Construct sessions using helpers in this module such as
+-- 'statement', 'pipeline' and 'script', or use 'onLibpqConnection' for a low-level
+-- escape hatch.
+--
+-- To actually execute a 'Session' use 'Hasql.Connection.use', which manages
+-- concurrent access to the shared connection state and returns either a
+-- '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, 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.UseError 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,
+-- nor can any results of it be collected.
+script :: ByteString -> Session ()
+script sql =
+  Session \connectionState -> do
+    let connection = ConnectionState.connection connectionState
+    result <- Comms.Roundtrip.toSerialIO (Comms.Roundtrip.script (Just sql) sql) connection
+    case result of
+      Left err -> case err of
+        Comms.Roundtrip.ClientError _ details -> do
+          pure
+            ( Left (Errors.fromSendError details),
+              connectionState
+            )
+        Comms.Roundtrip.ServerError recvError ->
+          pure
+            ( Left (Errors.fromRecvErrorInScript sql recvError),
+              connectionState
+            )
+      Right () ->
+        pure
+          ( Right (),
+            connectionState
+          )
+
+-- |
+-- Execute a single statement by providing parameters to it,
+-- running it directly in serial mode.
+--
+-- Each execution is a dedicated network roundtrip. The first execution of a
+-- preparable statement costs an extra roundtrip (a separate @PARSE@), after
+-- which steady-state execution is a single roundtrip.
+--
+-- To batch multiple statements into fewer roundtrips, use 'pipeline' instead.
+statement ::
+  Statement.Statement params result ->
+  params ->
+  Session result
+statement stmt params =
+  Session \connectionState -> do
+    let usePreparedStatements = ConnectionState.preparedStatements connectionState
+        statementCache = ConnectionState.statementCache connectionState
+        oidCache = ConnectionState.oidCache connectionState
+        connection = ConnectionState.connection connectionState
+        sql = Statement.sql stmt
+        missingTypes = OidCache.selectUnknownNames (Statement.unknownTypes stmt) oidCache
+    resolvedOidCache <-
+      if HashSet.null missingTypes
+        then pure (Right oidCache)
+        else do
+          oidCacheUpdates <-
+            PqProcedures.SelectTypeInfo.run connection (PqProcedures.SelectTypeInfo.SelectTypeInfo missingTypes)
+          pure $ case oidCacheUpdates of
+            Left err -> Left err
+            Right oidCacheUpdates ->
+              let foundTypes = HashMap.keysSet oidCacheUpdates
+                  notFoundTypes = HashSet.difference missingTypes foundTypes
+               in if not (HashSet.null 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)
+      Right newOidCache -> do
+        let resolve = OidCache.toResolver newOidCache
+            decoder' = Statement.decoder stmt resolve
+            prepared = usePreparedStatements && Statement.isPrepared stmt
+            -- Single-statement tag for error reporting:
+            -- total statements 1, index 0.
+            tag = Just (1, 0, sql, Statement.printer stmt params, prepared)
+            mapError = \case
+              Comms.Roundtrip.ClientError _ details ->
+                Errors.fromSendError details
+              Comms.Roundtrip.ServerError recvError ->
+                Errors.fromRecvError recvError
+            withState (result, newStatementCache) =
+              ( first mapError result,
+                connectionState
+                  { ConnectionState.oidCache = newOidCache,
+                    ConnectionState.statementCache = newStatementCache
+                  }
+              )
+        fmap withState
+          $ if prepared
+            then do
+              let (oidList, valueAndFormatList) =
+                    Statement.compilePreparedStatementData stmt resolve params
+                  encodedParams =
+                    valueAndFormatList
+                      & fmap (fmap (\(bytes, format) -> (bytes, bool Pq.Binary Pq.Text format)))
+                  execute remoteKey =
+                    Comms.Roundtrip.toSerialIO
+                      (Comms.Roundtrip.queryPrepared tag remoteKey encodedParams Pq.Binary decoder')
+                      connection
+              case StatementCache.lookup sql oidList statementCache of
+                Just remoteKey -> do
+                  result <- execute remoteKey
+                  pure (result, statementCache)
+                Nothing -> do
+                  let (remoteKey, newStatementCache) = StatementCache.insert sql oidList statementCache
+                  -- In non-pipeline mode PARSE and EXECUTE cannot be sent
+                  -- back-to-back, so prepare in a dedicated roundtrip first.
+                  prepareResult <-
+                    Comms.Roundtrip.toSerialIO
+                      (Comms.Roundtrip.prepare tag remoteKey sql oidList)
+                      connection
+                  case prepareResult of
+                    -- 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
+                      -- fails. Commit the cache so a later use hits it instead
+                      -- of re-issuing PARSE for an already-existing name.
+                      result <- execute remoteKey
+                      pure (result, newStatementCache)
+            else do
+              let encodedParams =
+                    Statement.compileUnpreparedStatementData stmt resolve params
+                      & fmap (fmap (\(oid, bytes, format) -> (oid, bytes, bool Pq.Binary Pq.Text format)))
+              result <-
+                Comms.Roundtrip.toSerialIO
+                  (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 (Pipeline.run pipeline)
+
+-- |
+-- Execute an operation on the raw libpq connection possibly producing an error and updating the connection.
+-- This is a low-level escape hatch for custom integrations.
+--
+-- You can supply a new connection in the result to replace it in the running Hasql connection.
+-- The responsibility to close the old libpq connection is on you.
+-- Otherwise, just return the same connection you've received.
+--
+-- 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, 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.UseError a, Pq.Connection)) ->
+  Session a
+onLibpqConnection f = Session \connectionState -> do
+  let pqConnection = ConnectionState.connection connectionState
+  (result, newConnection) <- f pqConnection
+  let newState = ConnectionState.setConnection newConnection connectionState
+  pure (result, newState)
diff --git a/src/library/Hasql/Engine/Decoders/Result.hs b/src/library/Hasql/Engine/Decoders/Result.hs
new file mode 100644
--- /dev/null
+++ b/src/library/Hasql/Engine/Decoders/Result.hs
@@ -0,0 +1,103 @@
+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
+import Hasql.Engine.Decoders.Row (Row (..))
+import Hasql.Engine.Decoders.Row qualified as Row
+import Hasql.Platform.Prelude
+import Hasql.ToBeResolved qualified as ToBeResolved
+
+-- |
+-- Decoder of a query result.
+newtype Result a
+  = Result (ToBeResolved.ToBeResolved CodecsVocab.QualifiedTypeName.QualifiedTypeName CodecsVocab.TypeInfo.TypeInfo (ResultDecoder.ResultDecoder a))
+  deriving
+    (Functor, Applicative, Filterable)
+    via (Compose (ToBeResolved.ToBeResolved CodecsVocab.QualifiedTypeName.QualifiedTypeName CodecsVocab.TypeInfo.TypeInfo) ResultDecoder.ResultDecoder)
+
+-- | Names of types that must be looked up at runtime before the decoder can run.
+toUnknownTypes :: Result a -> HashSet CodecsVocab.QualifiedTypeName.QualifiedTypeName
+toUnknownTypes (Result (ToBeResolved.ToBeResolved unknownTypes _)) = fromList unknownTypes
+
+-- | Resolve the decoder given a resolver of type names to their OIDs.
+toBase :: Result a -> (CodecsVocab.QualifiedTypeName.QualifiedTypeName -> CodecsVocab.TypeInfo.TypeInfo) -> ResultDecoder.ResultDecoder a
+toBase (Result (ToBeResolved.ToBeResolved _ decoder)) = decoder
+
+-- * Construction
+
+-- |
+-- Decode no value from the result.
+--
+-- Useful for statements like @INSERT@ or @CREATE@.
+{-# INLINE noResult #-}
+noResult :: Result ()
+noResult =
+  Result (pure ResultDecoder.ok)
+
+-- |
+-- Get the amount of rows affected by such statements as
+-- @UPDATE@ or @DELETE@.
+{-# INLINE rowsAffected #-}
+rowsAffected :: Result Int64
+rowsAffected =
+  Result (pure ResultDecoder.rowsAffected)
+
+-- |
+-- Exactly one row.
+-- Will raise the 'Hasql.Errors.UnexpectedRowCountStatementError' error if it's any other.
+{-# INLINE singleRow #-}
+singleRow :: Row a -> Result a
+singleRow decoder =
+  Result (fmap ResultDecoder.single (Row.toDecoder decoder))
+
+refineResult :: (a -> Either Text b) -> Result a -> Result b
+refineResult refiner (Result decoder) =
+  Result (fmap (ResultDecoder.refine refiner) decoder)
+
+-- ** Multi-row traversers
+
+-- |
+-- Foldl multiple rows.
+{-# INLINE foldlRows #-}
+foldlRows :: (a -> b -> a) -> a -> Row b -> Result a
+foldlRows step init decoder =
+  Result
+    (fmap (ResultDecoder.foldl step init) (Row.toDecoder decoder))
+
+-- |
+-- Foldr multiple rows.
+{-# INLINE foldrRows #-}
+foldrRows :: (b -> a -> a) -> a -> Row b -> Result a
+foldrRows step init decoder =
+  Result
+    (fmap (ResultDecoder.foldr step init) (Row.toDecoder decoder))
+
+-- ** Specialized multi-row results
+
+-- |
+-- Maybe one row or none.
+{-# INLINE rowMaybe #-}
+rowMaybe :: Row a -> Result (Maybe a)
+rowMaybe decoder =
+  Result
+    (fmap ResultDecoder.maybe (Row.toDecoder decoder))
+
+-- |
+-- Zero or more rows packed into the vector.
+--
+-- It's recommended to prefer this function to 'rowList',
+-- since it performs notably better.
+{-# INLINE rowVector #-}
+rowVector :: (Vector.Vector vector a) => Row a -> Result (vector a)
+rowVector decoder =
+  Result
+    (fmap ResultDecoder.vector (Row.toDecoder decoder))
+
+-- |
+-- Zero or more rows packed into the list.
+{-# INLINE rowList #-}
+rowList :: Row a -> Result [a]
+rowList =
+  foldrRows strictCons []
diff --git a/src/library/Hasql/Engine/Decoders/Row.hs b/src/library/Hasql/Engine/Decoders/Row.hs
new file mode 100644
--- /dev/null
+++ b/src/library/Hasql/Engine/Decoders/Row.hs
@@ -0,0 +1,82 @@
+module Hasql.Engine.Decoders.Row where
+
+import Hasql.Codecs.Decoders
+import Hasql.Codecs.Decoders.Value qualified as Value
+import Hasql.CodecsVocab.QualifiedTypeName qualified as CodecsVocab.QualifiedTypeName
+import Hasql.CodecsVocab.TypeInfo qualified as CodecsVocab.TypeInfo
+import Hasql.Comms.RowDecoder qualified
+import Hasql.Platform.Prelude
+import Hasql.ToBeResolved qualified as ToBeResolved
+import PostgreSQL.Binary.Decoding qualified as Binary
+
+-- |
+-- Decoder of an individual row,
+-- which gets composed of column value decoders.
+-- E.g.:
+--
+-- @
+-- x :: 'Row' (Maybe Int64, Text, TimeOfDay)
+-- x = (,,) '<$>' ('column' . 'nullable') 'int8' '<*>' ('column' . 'nonNullable') 'text' '<*>' ('column' . 'nonNullable') 'time'
+-- @
+newtype Row a
+  = Row (ToBeResolved.ToBeResolved CodecsVocab.QualifiedTypeName.QualifiedTypeName CodecsVocab.TypeInfo.TypeInfo (Hasql.Comms.RowDecoder.RowDecoder a))
+
+-- 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 ->
+  ToBeResolved.ToBeResolved CodecsVocab.QualifiedTypeName.QualifiedTypeName CodecsVocab.TypeInfo.TypeInfo (Hasql.Comms.RowDecoder.RowDecoder a)
+toDecoder (Row f) = f
+
+-- |
+-- Lift an individual value decoder to a composable row decoder.
+{-# INLINE column #-}
+column :: NullableOrNot Value a -> Row a
+column = \case
+  Nullable valueDecoder ->
+    Row case Value.toOid valueDecoder of
+      Just oid ->
+        fmap
+          (Hasql.Comms.RowDecoder.nullableColumn (Just oid) . Binary.valueParser)
+          (Value.toDecoder valueDecoder)
+      Nothing ->
+        ( \lookupResult decoder ->
+            Hasql.Comms.RowDecoder.nullableColumn (Just (chooseLookedUpOid valueDecoder lookupResult)) (Binary.valueParser decoder)
+        )
+          <$> ToBeResolved.lookup (CodecsVocab.QualifiedTypeName.QualifiedTypeName (Value.toSchema valueDecoder) (Value.toTypeName valueDecoder))
+          <*> Value.toDecoder valueDecoder
+  NonNullable valueDecoder ->
+    Row case Value.toOid valueDecoder of
+      Just oid ->
+        fmap
+          (Hasql.Comms.RowDecoder.nonNullableColumn (Just oid) . Binary.valueParser)
+          (Value.toDecoder valueDecoder)
+      Nothing ->
+        (\lookupResult decoder -> Hasql.Comms.RowDecoder.nonNullableColumn (Just (chooseLookedUpOid valueDecoder lookupResult)) (Binary.valueParser decoder))
+          <$> ToBeResolved.lookup (CodecsVocab.QualifiedTypeName.QualifiedTypeName (Value.toSchema valueDecoder) (Value.toTypeName valueDecoder))
+          <*> Value.toDecoder valueDecoder
+  where
+    chooseLookedUpOid valueDecoder typeInfo =
+      if Value.toDimensionality valueDecoder > 0
+        then CodecsVocab.TypeInfo.toArrayOid typeInfo
+        else CodecsVocab.TypeInfo.toBaseOid typeInfo
diff --git a/src/library/Hasql/Engine/Errors.hs b/src/library/Hasql/Engine/Errors.hs
new file mode 100644
--- /dev/null
+++ b/src/library/Hasql/Engine/Errors.hs
@@ -0,0 +1,557 @@
+module Hasql.Engine.Errors where
+
+import Hasql.Comms.Recv qualified
+import Hasql.Comms.ResultDecoder qualified
+import Hasql.Comms.Roundtrip qualified
+import Hasql.Comms.RowReader qualified
+import Hasql.Platform.Prelude
+import TextBuilder qualified
+
+-- * Error types
+
+-- |
+-- Error that occurs when attempting to establish a database connection.
+--
+-- 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.
+    --
+    -- 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
+  | -- | The server demanded a password and none was available.
+    --
+    -- 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
+  | -- | The server's version is below the minimum this driver supports.
+    --
+    -- 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.
+    --
+    -- 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
+  | -- | Session initialization failed and the server said why.
+    --
+    -- 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 and leaves the connection
+-- usable.
+--
+-- A session is a batch of actions executed in a database connection context.
+-- 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
+-- a pipeline of statements.
+data SessionError
+  = -- | An error occurred while executing a statement in the session.
+    --
+    -- This wraps statement-level errors and provides additional context about:
+    --
+    -- * Which statement in the pipeline failed (when multiple statements are batched)
+    -- * The SQL text and parameters of the failing statement
+    -- * Whether the statement was prepared or unprepared
+    --
+    -- The error message includes formatted output showing all this context,
+    -- making it easier to diagnose issues in production.
+    StatementSessionError
+      -- | Total number of statements in the running pipeline. 1 if it's executed alone.
+      Int
+      -- | 0-based index of the statement that failed. 0 if it's executed alone.
+      Int
+      -- | SQL template of the failing statement.
+      Text
+      -- | Parameter values as text (for logging purposes).
+      [Text]
+      -- | Whether the statement was executed as a prepared one.
+      Bool
+      -- | The underlying statement error.
+      StatementError
+  | -- | An error occurred while executing a script.
+    --
+    -- Scripts are multi-statement SQL texts executed via 'Hasql.Session.script'.
+    -- Unlike regular statements, scripts don't support parameters or result decoding,
+    -- and errors are limited to server-reported issues.
+    ScriptSessionError
+      -- | The SQL text of the script.
+      Text
+      -- | The server error that occurred.
+      ServerError
+  | -- | 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
+    -- are resolved by name at runtime, but the types don't exist in the database.
+    --
+    -- To fix this error:
+    --
+    -- * Ensure the types are defined in the database
+    -- * Check that schema search paths are configured correctly
+    -- * Verify that the type names in your code match those in the database
+    MissingTypesSessionError
+      -- | Set of (schema name, type name) pairs that could not be found.
+      --
+      -- Schema name is 'Nothing' when the type was looked up without a schema qualifier.
+      (HashSet (Maybe Text, Text))
+  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 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.
+    --
+    -- '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.
+    --
+    -- 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)
+
+-- |
+-- Error that occurs when executing a single statement.
+--
+-- Statement errors can be caused by server-side issues (SQL errors, constraint violations)
+-- or by mismatches between the decoder specification and the actual result structure
+-- (wrong number of rows/columns, type mismatches, or cell-level decoding failures).
+data StatementError
+  = -- | The server rejected the statement and returned an error.
+    --
+    -- This includes SQL syntax errors, constraint violations, permission errors,
+    -- and any other error reported by PostgreSQL during statement execution.
+    ServerStatementError ServerError
+  | -- | The statement returned a different number of rows than expected.
+    --
+    -- This occurs when using result decoders like @Decoders.singleRow@ or
+    -- @Decoders.rowsAffectedAtLeast@ that have specific row count expectations.
+    UnexpectedRowCountStatementError
+      -- | Expected minimum number of rows.
+      Int
+      -- | Expected maximum number of rows.
+      Int
+      -- | Actual number of rows returned.
+      Int
+  | -- | The statement returned a different number of columns than expected.
+    --
+    -- This indicates a mismatch between the decoder specification and the
+    -- actual result structure, possibly due to:
+    --
+    -- * Schema changes (columns added or removed)
+    -- * Wrong query (selecting different columns than expected)
+    -- * Decoder configuration error
+    UnexpectedColumnCountStatementError
+      -- | Expected number of columns.
+      Int
+      -- | Actual number of columns returned.
+      Int
+  | -- | A column has a different type than expected.
+    --
+    -- This occurs when the decoder expects a specific PostgreSQL type (by OID)
+    -- but the actual column has a different type. This can happen due to:
+    --
+    -- * Schema changes (column type changed)
+    -- * Wrong query (selecting wrong column or using a cast)
+    -- * Decoder configuration error
+    --
+    -- Note: As of version 1.10, Hasql performs strict type checking and will
+    -- report this error instead of attempting automatic type coercion.
+    UnexpectedColumnTypeStatementError
+      -- | 0-based column index where the type mismatch occurred.
+      Int
+      -- | Expected PostgreSQL type OID.
+      Word32
+      -- | Actual PostgreSQL type OID of the column.
+      Word32
+  | -- | An error occurred while decoding a specific row.
+    --
+    -- This wraps errors that occur at the row or cell level, providing
+    -- context about which row failed.
+    RowStatementError
+      -- | 0-based index of the row that failed to decode.
+      Int
+      -- | The underlying row-level error.
+      RowError
+  | -- | The database returned an unexpected result structure.
+    --
+    -- This is a catch-all error that indicates either:
+    --
+    -- * An improper statement (e.g., executing a query that doesn't match expectations)
+    -- * A schema mismatch between the code and database
+    -- * A bug in Hasql or server misbehavior
+    UnexpectedResultStatementError
+      -- | Human-readable details about what went wrong.
+      Text
+  deriving stock (Show, Eq)
+
+-- |
+-- Error reported by the PostgreSQL server when executing a statement.
+--
+-- The server provides structured error information including error codes
+-- (SQL state), messages, and optional context like hints and position information.
+--
+-- For a complete list of PostgreSQL error codes, see:
+-- <https://www.postgresql.org/docs/current/errcodes-appendix.html>
+data ServerError
+  = ServerError
+      -- | SQL State Code (SQLSTATE).
+      --
+      -- A five-character code that identifies the error class and condition.
+      -- Examples: @\"23505\"@ (unique violation), @\"42P01\"@ (undefined table).
+      Text
+      -- | Primary error message.
+      --
+      -- A human-readable description of the error.
+      Text
+      -- | Optional detailed error information.
+      --
+      -- Additional context about the error, if available.
+      (Maybe Text)
+      -- | Optional hint for resolving the error.
+      --
+      -- A suggestion for how to fix the problem, if available.
+      (Maybe Text)
+      -- | Optional position in the SQL string where the error occurred.
+      --
+      -- A 1-based character index into the SQL string, if the error
+      -- relates to a specific location in the query.
+      (Maybe Int)
+  deriving stock (Show, Eq)
+
+-- |
+-- Error that occurs when decoding a result row.
+--
+-- Row errors indicate problems when processing an individual row from the result set,
+-- either at the cell level or during row refinement/validation.
+data RowError
+  = -- | An error occurred while decoding a specific cell in the row.
+    --
+    -- This wraps cell-level errors (null handling, deserialization failures)
+    -- and provides context about which column failed and its type.
+    CellRowError
+      -- | 0-based index of the column where the error occurred.
+      Int
+      -- | PostgreSQL type OID of the column, as reported by the server.
+      Word32
+      -- | The underlying cell-level error.
+      CellError
+  | -- | A refinement or validation error when processing the row.
+    --
+    -- This occurs when using refinement functions in row decoders
+    -- (e.g., with 'Decoders.refineRow') to validate or transform
+    -- decoded values. The refinement function rejected the row data.
+    RefinementRowError
+      -- | Human-readable details about why the refinement failed.
+      Text
+  deriving stock (Show, Eq)
+
+-- |
+-- Error that occurs when decoding a single cell (column value) in a result row.
+--
+-- Cell errors indicate problems with individual values returned by the database,
+-- such as unexpected nulls or failures in binary deserialization.
+data CellError
+  = -- | A NULL value was encountered when a non-NULL value was expected.
+    --
+    -- This occurs when using non-nullable decoders (e.g., @Decoders.nonNullable@)
+    -- on a column that contains a NULL value.
+    UnexpectedNullCellError
+  | -- | Failed to deserialize the cell value from its binary representation.
+    --
+    -- This can occur when:
+    --
+    -- * The binary data is corrupted
+    -- * The decoder doesn't match the actual data type
+    -- * The data format is invalid for the expected type
+    DeserializationCellError
+      -- | Human-readable error message describing what went wrong.
+      Text
+  deriving stock (Show, Eq)
+
+-- |
+-- 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 _tag details ->
+    fromSendError details
+  Hasql.Comms.Roundtrip.ServerError recvError ->
+    fromRecvError (Nothing <$ recvError)
+
+fromRecvError :: Hasql.Comms.Recv.Error (Maybe (Int, Int, ByteString, [Text], Bool)) -> UseError
+fromRecvError = \case
+  Hasql.Comms.Recv.ResultError tag _resultOffset resultError ->
+    case tag of
+      Nothing ->
+        (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) ->
+        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 ->
+        (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) ->
+        SessionUseError
+          $ StatementSessionError
+            totalStatements
+            statementIndex
+            (decodeUtf8Lenient sql)
+            parameters
+            prepared
+            (UnexpectedRowCountStatementError 1 1 actual)
+
+fromStatementResultError :: Hasql.Comms.ResultDecoder.Error -> StatementError
+fromStatementResultError = \case
+  Hasql.Comms.ResultDecoder.ServerError code message detail hint position ->
+    ServerStatementError
+      ( ServerError
+          (decodeUtf8Lenient code)
+          (decodeUtf8Lenient message)
+          (fmap decodeUtf8Lenient detail)
+          (fmap decodeUtf8Lenient hint)
+          position
+      )
+  Hasql.Comms.ResultDecoder.UnexpectedResult msg ->
+    UnexpectedResultStatementError msg
+  Hasql.Comms.ResultDecoder.UnexpectedRowCount actual ->
+    UnexpectedRowCountStatementError 1 1 actual
+  Hasql.Comms.ResultDecoder.UnexpectedColumnCount expected actual ->
+    UnexpectedColumnCountStatementError expected actual
+  Hasql.Comms.ResultDecoder.DecoderTypeMismatch colIdx expectedOid actualOid ->
+    UnexpectedColumnTypeStatementError
+      colIdx
+      expectedOid
+      actualOid
+  Hasql.Comms.ResultDecoder.RowError rowIndex rowError ->
+    case rowError of
+      Hasql.Comms.RowReader.CellError column oid cellErr ->
+        RowStatementError
+          rowIndex
+          ( CellRowError
+              column
+              oid
+              ( case cellErr of
+                  Hasql.Comms.RowReader.DecodingCellError msg -> DeserializationCellError msg
+                  Hasql.Comms.RowReader.UnexpectedNullCellError -> UnexpectedNullCellError
+              )
+          )
+      Hasql.Comms.RowReader.RefinementError msg ->
+        RowStatementError
+          rowIndex
+          (RefinementRowError msg)
+
+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 ->
+        SessionUseError
+          $ ScriptSessionError
+            (decodeUtf8Lenient scriptSql)
+            ( ServerError
+                (decodeUtf8Lenient code)
+                (decodeUtf8Lenient message)
+                (fmap decodeUtf8Lenient detail)
+                (fmap decodeUtf8Lenient hint)
+                position
+            )
+      Hasql.Comms.ResultDecoder.UnexpectedResult msg ->
+        (ConnectionUseError . TextBuilder.toText . mconcat)
+          [ "Unexpected result in script: ",
+            TextBuilder.text msg
+          ]
+      Hasql.Comms.ResultDecoder.UnexpectedRowCount actual ->
+        (ConnectionUseError . TextBuilder.toText . mconcat)
+          [ "Unexpected amount of rows in script: ",
+            TextBuilder.decimal actual
+          ]
+      Hasql.Comms.ResultDecoder.UnexpectedColumnCount expected actual ->
+        (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 ->
+        (ConnectionUseError . TextBuilder.toText . mconcat)
+          [ "Decoder type mismatch in script: expected OID ",
+            TextBuilder.string (show expectedOid),
+            " at column ",
+            TextBuilder.decimal colIdx,
+            ", got ",
+            TextBuilder.string (show actualOid)
+          ]
+      Hasql.Comms.ResultDecoder.RowError rowIndex rowError ->
+        (ConnectionUseError . TextBuilder.toText . mconcat)
+          [ "Row error in script at row ",
+            TextBuilder.decimal rowIndex,
+            ": ",
+            TextBuilder.string (show rowError)
+          ]
+  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 ->
+    (ConnectionUseError . TextBuilder.toText . mconcat)
+      [ "Got too many results in script. ",
+        "This indicates a bug in Hasql or the server misbehaving. ",
+        "Amount: ",
+        TextBuilder.decimal actual
+      ]
diff --git a/src/library/Hasql/Engine/PqProcedures/SelectTypeInfo.hs b/src/library/Hasql/Engine/PqProcedures/SelectTypeInfo.hs
new file mode 100644
--- /dev/null
+++ b/src/library/Hasql/Engine/PqProcedures/SelectTypeInfo.hs
@@ -0,0 +1,123 @@
+module Hasql.Engine.PqProcedures.SelectTypeInfo
+  ( SelectTypeInfo (..),
+    run,
+  )
+where
+
+import Data.HashMap.Strict qualified as HashMap
+import Data.HashSet qualified as HashSet
+import Hasql.CodecsVocab qualified as CodecsVocab
+import Hasql.CodecsVocab.QualifiedTypeName qualified as CodecsVocab.QualifiedTypeName
+import Hasql.CodecsVocab.TypeInfo qualified as CodecsVocab.TypeInfo
+import Hasql.Comms.ResultDecoder qualified
+import Hasql.Comms.Roundtrip qualified
+import Hasql.Comms.RowDecoder qualified
+import Hasql.Engine.Errors qualified as Errors
+import Hasql.Platform.Prelude
+import PostgreSQL.Binary.Decoding qualified as BinaryDecoding
+import PostgreSQL.Binary.Encoding qualified as Binary
+import Pqi qualified as Pq
+
+newtype SelectTypeInfo = SelectTypeInfo
+  { -- | Set of (schema name, type name) pairs to look up.
+    keys :: HashSet CodecsVocab.QualifiedTypeName
+  }
+
+-- | Result maps (schema name, type name) pairs to TypeInfo (scalar OID, array OID).
+type SelectTypeInfoResult =
+  HashMap CodecsVocab.QualifiedTypeName CodecsVocab.TypeInfo.TypeInfo
+
+run :: Pq.Connection -> SelectTypeInfo -> IO (Either Errors.UseError SelectTypeInfoResult)
+run connection (SelectTypeInfo keys) =
+  if HashSet.null keys
+    then pure (Right HashMap.empty)
+    else
+      first Errors.fromRoundtripError
+        <$> Hasql.Comms.Roundtrip.toSerialIO (roundtrip (SelectTypeInfo keys)) connection
+
+sql :: ByteString
+sql =
+  "with\n\
+  \  inputs as (\n\
+  \    select *\n\
+  \    from unnest($1, $2) as x(schema_name, type_name)\n\
+  \  ),\n\
+  \  unnamespaced_results as (\n\
+  \    select\n\
+  \      null :: text as schema_name,\n\
+  \      pg_type.typname :: text as type_name,\n\
+  \      pg_type.oid :: int4 as type_oid,\n\
+  \      pg_type.typarray :: int4 as array_oid\n\
+  \    from inputs\n\
+  \    join pg_type on pg_type.oid = to_regtype(inputs.type_name)\n\
+  \    where inputs.schema_name is null\n\
+  \  ),\n\
+  \  namespaced_results as (\n\
+  \    select\n\
+  \      pg_namespace.nspname :: text as schema_name,\n\
+  \      pg_type.typname :: text as type_name,\n\
+  \      pg_type.oid :: int4 as type_oid,\n\
+  \      pg_type.typarray :: int4 as array_oid\n\
+  \    from inputs\n\
+  \    join pg_namespace on pg_namespace.nspname = inputs.schema_name\n\
+  \    join pg_type\n\
+  \      on pg_type.typname = inputs.type_name\n\
+  \      and pg_type.typnamespace = pg_namespace.oid\n\
+  \    where inputs.schema_name is not null\n\
+  \  )\n\
+  \select * from unnamespaced_results\n\
+  \union\n\
+  \select * from namespaced_results"
+
+roundtrip :: SelectTypeInfo -> Hasql.Comms.Roundtrip.Roundtrip () SelectTypeInfoResult
+roundtrip params =
+  Hasql.Comms.Roundtrip.queryParams () sql (encodeParams params) Pq.Binary decoder
+
+-- | Encode the two text-array parameters directly.
+-- Text OID is 25; text-array OID is 1009.
+encodeParams :: SelectTypeInfo -> [Maybe (Word32, ByteString, Pq.Format)]
+encodeParams (SelectTypeInfo keys) =
+  let (schemaNames, typeNames) = unzip (fmap CodecsVocab.QualifiedTypeName.toNameTuple (HashSet.toList keys))
+      schemaArray = Binary.encodingBytes (Binary.array 25 (encodeTextArray (encodeMaybeText schemaNames)))
+      typeArray = Binary.encodingBytes (Binary.array 25 (encodeTextArray (fmap (Binary.encodingArray . Binary.text_strict) typeNames)))
+   in [ Just (1009, schemaArray, Pq.Binary),
+        Just (1009, typeArray, Pq.Binary)
+      ]
+  where
+    encodeTextArray elements =
+      Binary.dimensionArray foldl' id elements
+    encodeMaybeText =
+      fmap \case
+        Nothing -> Binary.nullArray
+        Just text -> Binary.encodingArray (Binary.text_strict text)
+
+decoder :: Hasql.Comms.ResultDecoder.ResultDecoder SelectTypeInfoResult
+decoder =
+  Hasql.Comms.ResultDecoder.foldl step HashMap.empty rowDecoder
+  where
+    step acc (schemaName, typeName, typeOid, arrayOid) =
+      HashMap.insert (CodecsVocab.QualifiedTypeName.QualifiedTypeName schemaName typeName) (CodecsVocab.TypeInfo.TypeInfo typeOid arrayOid) acc
+
+-- | These four columns have permanently fixed, well-known Postgres OIDs
+-- (text = 25, int4 = 23), so they're decoded directly against
+-- "postgresql-binary" rather than through the dynamic codec framework.
+rowDecoder :: Hasql.Comms.RowDecoder.RowDecoder (Maybe Text, Text, Word32, Word32)
+rowDecoder =
+  (,,,)
+    <$> nullableColumn textOid BinaryDecoding.text_strict
+    <*> nonNullableColumn textOid BinaryDecoding.text_strict
+    <*> nonNullableColumn int4Oid BinaryDecoding.int
+    <*> nonNullableColumn int4Oid BinaryDecoding.int
+  where
+    textOid = 25
+    int4Oid = 23
+
+    nullableColumn oid valueDecoder =
+      Hasql.Comms.RowDecoder.nullableColumn
+        (Just oid)
+        (BinaryDecoding.valueParser valueDecoder)
+
+    nonNullableColumn oid valueDecoder =
+      Hasql.Comms.RowDecoder.nonNullableColumn
+        (Just oid)
+        (BinaryDecoding.valueParser valueDecoder)
diff --git a/src/library/Hasql/Engine/Statement.hs b/src/library/Hasql/Engine/Statement.hs
new file mode 100644
--- /dev/null
+++ b/src/library/Hasql/Engine/Statement.hs
@@ -0,0 +1,177 @@
+module Hasql.Engine.Statement
+  ( Statement (..),
+    preparable,
+    unpreparable,
+    refineResult,
+    toSql,
+    compilePreparedStatementData,
+    compileUnpreparedStatementData,
+  )
+where
+
+import Data.Text.Encoding qualified as TextEncoding
+import Data.Vector qualified as Vector
+import Hasql.Codecs.Encoders qualified as Encoders
+import Hasql.Codecs.Encoders.Params qualified as Params
+import Hasql.CodecsVocab qualified as CodecsVocab
+import Hasql.CodecsVocab.TypeInfo qualified as CodecsVocab.TypeInfo
+import Hasql.CodecsVocab.TypeRef qualified as CodecsVocab.TypeRef
+import Hasql.CodecsVocab.TypeShape (TypeShape (..))
+import Hasql.Comms.ResultDecoder qualified as ResultDecoder
+import Hasql.Engine.Decoders.Result qualified as Decoders
+import Hasql.Engine.Decoders.Result qualified as Decoders.Result
+import Hasql.Platform.Prelude
+
+-- |
+-- Specification of a strictly single-statement query, which can be parameterized and prepared.
+-- It encapsulates the mapping of parameters and results in association with an SQL template.
+--
+-- Following is an example of a declaration of a prepared statement with its associated codecs.
+--
+-- @
+-- selectSum :: 'Statement' (Int64, Int64) Int64
+-- selectSum =
+--   'preparable' sql encoder decoder
+--   where
+--     sql =
+--       \"select ($1 + $2)\"
+--     encoder =
+--       ('fst' '>$<' Encoders.'Hasql.Encoders.param' (Encoders.'Hasql.Encoders.nonNullable' Encoders.'Hasql.Encoders.int8')) '<>'
+--       ('snd' '>$<' Encoders.'Hasql.Encoders.param' (Encoders.'Hasql.Encoders.nonNullable' Encoders.'Hasql.Encoders.int8'))
+--     decoder =
+--       Decoders.'Hasql.Decoders.singleRow' (Decoders.'Hasql.Decoders.column' (Decoders.'Hasql.Decoders.nonNullable' Decoders.'Hasql.Decoders.int8'))
+-- @
+--
+-- The statement above accepts a product of two parameters of type 'Int64'
+-- and produces a single result of type 'Int64'.
+data Statement params result
+  = Statement
+  { -- | SQL template pre-encoded as UTF-8 for execution.
+    sql :: ByteString,
+    -- | Frozen per-parameter type shapes.
+    -- Produced once at construction from the Params DList and reused across executions.
+    columnsMetadata :: Vector TypeShape,
+    -- | Serialise params to encoded wire values given a resolver of type names to their OIDs.
+    serializer :: (CodecsVocab.QualifiedTypeName -> CodecsVocab.TypeInfo) -> params -> [Maybe ByteString],
+    -- | Render params in human-readable form (for error reporting).
+    printer :: params -> [Text],
+    -- | Union of encoder and decoder unknown types, resolved once at construction.
+    unknownTypes :: HashSet CodecsVocab.QualifiedTypeName,
+    -- | Result decoder, given a resolver of type names to their OIDs.
+    decoder :: (CodecsVocab.QualifiedTypeName -> CodecsVocab.TypeInfo) -> ResultDecoder.ResultDecoder result,
+    -- | Whether this statement may be prepared on the server.
+    isPrepared :: Bool
+  }
+
+-- |
+-- Construct a preparable statement.
+--
+-- Use this for statements that will be executed multiple times with different parameters.
+-- Preparable statements are cached by PostgreSQL, which avoids reconstructing the execution plan each time.
+--
+-- Suitable for applications with a limited amount of queries that don't generate SQL dynamically.
+preparable ::
+  -- | SQL template with parameters in positional notation (@$1@, @$2@, etc.)
+  Text ->
+  -- | Parameters encoder
+  Encoders.Params params ->
+  -- | Result decoder
+  Decoders.Result result ->
+  Statement params result
+preparable sqlText encoder resultDecoder =
+  Statement
+    { sql = TextEncoding.encodeUtf8 sqlText,
+      columnsMetadata = Params.toColumnsMetadata encoder,
+      serializer = Params.toSerializer encoder,
+      printer = Params.toPrinter encoder,
+      unknownTypes = Params.toUnknownTypes encoder <> Decoders.Result.toUnknownTypes resultDecoder,
+      decoder = Decoders.Result.toBase resultDecoder,
+      isPrepared = True
+    }
+
+-- |
+-- Construct an unpreparable statement.
+--
+-- Use this for statements that are dynamically generated or executed only once.
+-- Unpreparable statements are not cached by PostgreSQL.
+--
+-- Suitable for dynamic SQL or one-off queries.
+unpreparable ::
+  -- | SQL template with parameters in positional notation (@$1@, @$2@, etc.)
+  Text ->
+  -- | Parameters encoder
+  Encoders.Params params ->
+  -- | Result decoder
+  Decoders.Result result ->
+  Statement params result
+unpreparable sqlText encoder resultDecoder =
+  Statement
+    { sql = TextEncoding.encodeUtf8 sqlText,
+      columnsMetadata = Params.toColumnsMetadata encoder,
+      serializer = Params.toSerializer encoder,
+      printer = Params.toPrinter encoder,
+      unknownTypes = Params.toUnknownTypes encoder <> Decoders.Result.toUnknownTypes resultDecoder,
+      decoder = Decoders.Result.toBase resultDecoder,
+      isPrepared = False
+    }
+
+instance Functor (Statement params) where
+  {-# INLINE fmap #-}
+  fmap f stmt = stmt {decoder = fmap (fmap f) (decoder stmt)}
+
+instance Filterable (Statement params) where
+  {-# INLINE mapMaybe #-}
+  mapMaybe filtrator stmt = stmt {decoder = fmap (mapMaybe filtrator) (decoder stmt)}
+
+instance Profunctor Statement where
+  {-# INLINE dimap #-}
+  dimap f1 f2 stmt =
+    stmt
+      { serializer = \resolve -> serializer stmt resolve . f1,
+        printer = printer stmt . f1,
+        decoder = fmap (fmap f2) (decoder stmt)
+      }
+
+-- |
+-- Refine the result of a statement,
+-- causing the running session to fail with the 'Hasql.Errors.UnexpectedResultStatementError' error in case of a refinement failure.
+--
+-- This function is especially useful for refining the results of statements produced with
+-- <http://hackage.haskell.org/package/hasql-th the \"hasql-th\" library>.
+refineResult :: (a -> Either Text b) -> Statement params a -> Statement params b
+refineResult refiner stmt = stmt {decoder = fmap (ResultDecoder.refine refiner) (decoder stmt)}
+
+-- | Extract the SQL template from a statement.
+toSql :: Statement params result -> Text
+toSql stmt = decodeUtf8Lenient (sql stmt)
+
+-- | Compile prepared-statement data: resolve OIDs and pair encoded values with their format flags.
+compilePreparedStatementData ::
+  Statement params result ->
+  (CodecsVocab.QualifiedTypeName -> CodecsVocab.TypeInfo) ->
+  params ->
+  ([Word32], [Maybe (ByteString, Bool)])
+compilePreparedStatementData stmt resolve params =
+  unzip
+    $ zipWith
+      (\(TypeShape typeRef dim fmt) encoding -> (resolveOid resolve typeRef dim, fmap (,fmt) encoding))
+      (Vector.toList (columnsMetadata stmt))
+      (serializer stmt resolve params)
+
+-- | Compile unprepared-statement data: resolve OIDs inline with encoded values.
+compileUnpreparedStatementData ::
+  Statement params result ->
+  (CodecsVocab.QualifiedTypeName -> CodecsVocab.TypeInfo) ->
+  params ->
+  [Maybe (Word32, ByteString, Bool)]
+compileUnpreparedStatementData stmt resolve params =
+  zipWith
+    (\(TypeShape typeRef dim fmt) encoding -> (,,) <$> Just (resolveOid resolve typeRef dim) <*> encoding <*> Just fmt)
+    (Vector.toList (columnsMetadata stmt))
+    (serializer stmt resolve params)
+
+-- | Resolve a param's wire OID given the dictionary of resolved type names.
+resolveOid :: (CodecsVocab.QualifiedTypeName -> CodecsVocab.TypeInfo) -> CodecsVocab.TypeRef.TypeRef -> Word -> Word32
+resolveOid resolve (CodecsVocab.TypeRef.NamedType name) dim =
+  (if dim == 0 then CodecsVocab.TypeInfo.toBaseOid else CodecsVocab.TypeInfo.toArrayOid) (resolve name)
+resolveOid _ (CodecsVocab.TypeRef.KnownOid oid) _ = oid
diff --git a/src/library/Hasql/Errors.hs b/src/library/Hasql/Errors.hs
new file mode 100644
--- /dev/null
+++ b/src/library/Hasql/Errors.hs
@@ -0,0 +1,266 @@
+-- |
+-- Explicit error types for all Hasql operations.
+--
+-- This module provides access to all error types used throughout Hasql:
+--
+-- * '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.
+module Hasql.Errors
+  ( -- * Error class
+    IsError (..),
+    toDetailedText,
+
+    -- * Acquire errors
+    AcquireError (..),
+
+    -- * Use errors
+    UseError (..),
+
+    -- * Session errors
+    SessionError (..),
+    StatementError (..),
+    RowError (..),
+    CellError (..),
+    ServerError (..),
+  )
+where
+
+import Data.HashSet qualified as HashSet
+import Data.Text qualified as Text
+import Hasql.Engine.Errors
+import Hasql.Platform.Prelude
+import TextBuilder qualified
+
+-- * 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
+
+  -- | Convert the error to a list of key-value pairs of dynamic details.
+  toDetails :: a -> [(Text, Text)]
+
+  -- | The SQLSTATE the server reported, if this error carries one at all.
+  --
+  -- Lets you branch on a PostgreSQL error code without knowing which
+  -- constructors of which error type the server error is nested under. For the
+  -- code vocabulary see
+  -- <https://www.postgresql.org/docs/current/errcodes-appendix.html>.
+  --
+  -- 'Nothing' means the error carries no server code: a connection failure, a
+  -- decoding failure, a driver bug. It never means "the operation succeeded".
+  --
+  -- The default implementation returns 'Nothing', which is correct only for
+  -- error types that can never carry a server error. A type that wraps another
+  -- error type MUST override it and delegate to the wrapped value, otherwise it
+  -- silently reports 'Nothing' for codes it does in fact carry.
+  toSqlState :: a -> Maybe Text
+  toSqlState _ = Nothing
+
+-- | Convert the error to a multiline detailed human-readable text representation containing all details.
+toDetailedText :: (IsError e) => e -> Text
+toDetailedText = TextBuilder.toText . toDetailedTextBuilder
+
+-- | Convert the error to a multiline detailed human-readable text representation containing all details.
+toDetailedTextBuilder :: (IsError e) => e -> TextBuilder
+toDetailedTextBuilder err =
+  TextBuilder.text (toMessage err)
+    <> foldMap
+      ( \(key, value) ->
+          mconcat
+            [ "\n  ",
+              TextBuilder.text key,
+              case Text.lines value of
+                [] -> ":"
+                [singleLine] ->
+                  ": " <> TextBuilder.text singleLine
+                multipleLines ->
+                  ":" <> foldMap (mappend "\n    " . TextBuilder.text) multipleLines
+            ]
+      )
+      (toDetails err)
+
+-- * Instances
+
+instance IsError AcquireError where
+  toMessage = \case
+    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
+    ConnectionAcquireError reason ->
+      [("reason", reason)]
+    ConnectionPasswordRequiredAcquireError reason ->
+      [("reason", 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
+
+  toSqlState = \case
+    InitializationServerErrorAcquireError err -> toSqlState err
+    _ -> Nothing
+
+instance IsError ServerError where
+  toMessage _ =
+    "Server error"
+
+  toDetails (ServerError code message detail hint position) =
+    mconcat
+      [ [("code", code), ("message", message)],
+        maybe [] (\d -> [("detail", d)]) detail,
+        maybe [] (\h -> [("hint", h)]) hint,
+        maybe [] (\p -> [("position", (TextBuilder.toText . TextBuilder.decimal) p)]) position
+      ]
+
+  toSqlState (ServerError code _ _ _ _) = Just code
+
+instance IsError CellError where
+  toMessage = \case
+    UnexpectedNullCellError ->
+      "Unexpected null value"
+    DeserializationCellError {} ->
+      "Failed to deserialize cell"
+
+  toDetails = \case
+    UnexpectedNullCellError ->
+      []
+    DeserializationCellError reason ->
+      [("reason", reason)]
+
+instance IsError StatementError where
+  toMessage = \case
+    ServerStatementError executionError ->
+      toMessage executionError
+    UnexpectedRowCountStatementError {} ->
+      "Unexpected number of rows"
+    UnexpectedColumnCountStatementError {} ->
+      "Unexpected number of columns"
+    UnexpectedColumnTypeStatementError {} ->
+      "Unexpected column type"
+    RowStatementError _ rowError ->
+      toMessage rowError
+    UnexpectedResultStatementError {} ->
+      "Driver error"
+
+  toDetails = \case
+    ServerStatementError executionError ->
+      toDetails executionError
+    UnexpectedRowCountStatementError min max actual ->
+      [ ("expectedMin", (TextBuilder.toText . TextBuilder.decimal) min),
+        ("expectedMax", (TextBuilder.toText . TextBuilder.decimal) max),
+        ("actual", (TextBuilder.toText . TextBuilder.decimal) actual)
+      ]
+    UnexpectedColumnCountStatementError expected actual ->
+      [ ("expected", (TextBuilder.toText . TextBuilder.decimal) expected),
+        ("actual", (TextBuilder.toText . TextBuilder.decimal) actual)
+      ]
+    UnexpectedColumnTypeStatementError colIdx expected actual ->
+      [ ("columnIndex", (TextBuilder.toText . TextBuilder.decimal) colIdx),
+        ("expectedOid", (TextBuilder.toText . TextBuilder.decimal) expected),
+        ("actualOid", (TextBuilder.toText . TextBuilder.decimal) actual)
+      ]
+    RowStatementError rowIdx rowError ->
+      ("rowIndex", (TextBuilder.toText . TextBuilder.decimal) rowIdx) : toDetails rowError
+    UnexpectedResultStatementError reason ->
+      [("reason", reason)]
+
+  toSqlState = \case
+    ServerStatementError executionError -> toSqlState executionError
+    UnexpectedRowCountStatementError {} -> Nothing
+    UnexpectedColumnCountStatementError {} -> Nothing
+    UnexpectedColumnTypeStatementError {} -> Nothing
+    RowStatementError _ rowError -> toSqlState rowError
+    UnexpectedResultStatementError {} -> Nothing
+
+instance IsError RowError where
+  toMessage = \case
+    CellRowError _ _ cellErr ->
+      toMessage cellErr
+    RefinementRowError {} ->
+      "Refinement error"
+
+  toDetails = \case
+    CellRowError colIdx oid cellErr ->
+      [ ("columnIndex", (TextBuilder.toText . TextBuilder.decimal) colIdx),
+        ("oid", (TextBuilder.toText . TextBuilder.decimal) oid)
+      ]
+        <> toDetails cellErr
+    RefinementRowError reason ->
+      [("reason", reason)]
+
+instance IsError SessionError where
+  toMessage = \case
+    StatementSessionError _ _ _ _ _ statementError ->
+      toMessage statementError
+    ScriptSessionError _ execErr ->
+      toMessage execErr
+    MissingTypesSessionError {} ->
+      "Types not found in database"
+
+  toDetails = \case
+    StatementSessionError totalStatements statementIndex sql parameters prepared statementError ->
+      [ ("totalStatements", (TextBuilder.toText . TextBuilder.decimal) totalStatements),
+        ("statementIndex", (TextBuilder.toText . TextBuilder.decimal) statementIndex),
+        ("sql", sql),
+        ("parameters", Text.intercalate ", " parameters),
+        ("prepared", if prepared then "true" else "false")
+      ]
+        <> toDetails statementError
+    ScriptSessionError sql execErr ->
+      ("sql", sql) : toDetails execErr
+    MissingTypesSessionError missingTypes ->
+      [ ( "missingTypes",
+          (TextBuilder.toText . mconcat . intersperse ", " . fmap formatType . HashSet.toList) missingTypes
+        )
+      ]
+      where
+        formatType (schema, name) = maybe "" ((<> ".") . TextBuilder.text) schema <> TextBuilder.text name
+
+  toSqlState = \case
+    StatementSessionError _ _ _ _ _ statementError -> toSqlState statementError
+    ScriptSessionError _ serverError -> toSqlState serverError
+    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
diff --git a/src/library/Hasql/Pipeline.hs b/src/library/Hasql/Pipeline.hs
new file mode 100644
--- /dev/null
+++ b/src/library/Hasql/Pipeline.hs
@@ -0,0 +1,13 @@
+module Hasql.Pipeline
+  ( Pipeline.Pipeline,
+    statement,
+  )
+where
+
+import Hasql.Engine.Contexts.Pipeline qualified as Pipeline
+import Hasql.Engine.Statement qualified as Statement
+
+-- |
+-- Execute a statement by providing parameters to it.
+statement :: params -> Statement.Statement params result -> Pipeline.Pipeline result
+statement params stmt = Pipeline.statement stmt params
diff --git a/src/library/Hasql/Session.hs b/src/library/Hasql/Session.hs
new file mode 100644
--- /dev/null
+++ b/src/library/Hasql/Session.hs
@@ -0,0 +1,24 @@
+module Hasql.Session
+  ( Session.Session,
+    Session.pipeline,
+    script,
+    statement,
+    Session.onLibpqConnection,
+  )
+where
+
+import Hasql.Engine.Contexts.Session qualified as Session
+import Hasql.Engine.Statement qualified as Statement
+import Hasql.Platform.Prelude
+
+-- |
+-- Possibly a multi-statement query,
+-- which however cannot be parameterized or prepared,
+-- nor can any results of it be collected.
+script :: Text -> Session.Session ()
+script sql = Session.script (encodeUtf8 sql)
+
+-- |
+-- Execute a statement by providing parameters to it.
+statement :: params -> Statement.Statement params result -> Session.Session result
+statement params stmt = Session.statement stmt params
diff --git a/src/library/Hasql/Statement.hs b/src/library/Hasql/Statement.hs
new file mode 100644
--- /dev/null
+++ b/src/library/Hasql/Statement.hs
@@ -0,0 +1,55 @@
+module Hasql.Statement
+  ( Statement,
+    preparable,
+    unpreparable,
+    refineResult,
+    toSql,
+
+    -- * Recipes
+
+    -- ** Insert many
+
+    -- |
+    -- Starting from PostgreSQL 9.4 there is an @unnest@ function which we can use in an analogous way
+    -- to haskell's `zip` to pass in multiple arrays of values
+    -- to be zipped into the rows to insert as in the following example:
+    --
+    -- @
+    -- insertMultipleLocations :: 'Statement' (Vector (UUID, Double, Double)) ()
+    -- insertMultipleLocations =
+    --   'preparable' sql encoder decoder
+    --   where
+    --     sql =
+    --       "insert into location (id, x, y) select * from unnest ($1, $2, $3)"
+    --     encoder =
+    --       Data.Vector.'Data.Vector.unzip3' '>$<'
+    --         Contravariant.Extras.contrazip3
+    --           (Encoders.'Encoders.param' $ Encoders.'Encoders.nonNullable' $ Encoders.'Encoders.foldableArray' $ Encoders.'Encoders.nonNullable' Encoders.'Encoders.uuid')
+    --           (Encoders.'Encoders.param' $ Encoders.'Encoders.nonNullable' $ Encoders.'Encoders.foldableArray' $ Encoders.'Encoders.nonNullable' Encoders.'Encoders.float8')
+    --           (Encoders.'Encoders.param' $ Encoders.'Encoders.nonNullable' $ Encoders.'Encoders.foldableArray' $ Encoders.'Encoders.nonNullable' Encoders.'Encoders.float8')
+    --     decoder =
+    --       Decoders.'Decoders.noResult'
+    -- @
+    --
+    -- While this approach is much more efficient than executing a single-row insert-statement multiple times from within 'Session', a comparable performance can also be achieved by executing a single-insert statement from within a 'Pipeline'.
+
+    -- ** IN and NOT IN
+
+    -- |
+    -- There is a common misconception that PostgreSQL supports array
+    -- as the parameter for the @IN@ operator.
+    -- However Postgres only supports a syntactical list of values with it,
+    -- i.e., you have to specify each option as an individual parameter.
+    -- E.g., @some_expression IN ($1, $2, $3)@.
+    --
+    -- Fortunately, Postgres does provide the expected functionality for arrays with other operators:
+    --
+    -- * Use @some_expression = ANY($1)@ instead of @some_expression IN ($1)@
+    -- * Use @some_expression <> ALL($1)@ instead of @some_expression NOT IN ($1)@
+    --
+    -- For details refer to
+    -- <https://www.postgresql.org/docs/9.6/static/functions-comparisons.html#AEN20944 the PostgreSQL docs>.
+  )
+where
+
+import Hasql.Engine.Statement
diff --git a/src/platform/Hasql/Platform/Prelude.hs b/src/platform/Hasql/Platform/Prelude.hs
new file mode 100644
--- /dev/null
+++ b/src/platform/Hasql/Platform/Prelude.hs
@@ -0,0 +1,119 @@
+module Hasql.Platform.Prelude
+  ( module Exports,
+    forMToZero_,
+    forMFromZero_,
+    strictCons,
+  )
+where
+
+import Control.Applicative as Exports hiding (WrappedArrow (..))
+import Control.Arrow as Exports hiding (first, second)
+import Control.Category as Exports
+import Control.Comonad as Exports (Comonad (..))
+import Control.Concurrent as Exports
+import Control.Exception as Exports hiding (Handler)
+import Control.Monad as Exports hiding (fail, forM, forM_, mapM, mapM_, msum, sequence, sequence_)
+import Control.Monad.Error.Class as Exports (MonadError (..))
+import Control.Monad.Fail as Exports
+import Control.Monad.Fix as Exports hiding (fix)
+import Control.Monad.IO.Class as Exports
+import Control.Monad.Reader.Class as Exports
+import Control.Monad.ST as Exports
+import Control.Monad.State.Class as Exports
+import Control.Monad.Trans.Class as Exports
+import Control.Monad.Trans.Cont as Exports hiding (callCC, shift)
+import Control.Monad.Trans.Except as Exports (Except, ExceptT (ExceptT), except, mapExcept, mapExceptT, runExcept, runExceptT, withExcept, withExceptT)
+import Control.Monad.Trans.Maybe as Exports
+import Control.Monad.Trans.Reader as Exports (Reader, ReaderT (ReaderT), mapReader, mapReaderT, runReader, runReaderT, withReader, withReaderT)
+import Control.Monad.Trans.State.Strict as Exports (State, StateT (StateT), evalState, evalStateT, execState, execStateT, mapState, mapStateT, runState, runStateT, withState, withStateT)
+import Control.Monad.Trans.Writer.Strict as Exports (Writer, WriterT (..), execWriter, execWriterT, mapWriter, mapWriterT, runWriter)
+import Data.Bifunctor as Exports
+import Data.Bits as Exports
+import Data.Bool as Exports
+import Data.ByteString as Exports (ByteString)
+import Data.Char as Exports
+import Data.Coerce as Exports
+import Data.Complex as Exports
+import Data.DList as Exports (DList)
+import Data.Data as Exports
+import Data.Dynamic as Exports
+import Data.Either as Exports
+import Data.Fixed as Exports
+import Data.Foldable as Exports hiding (toList)
+import Data.Function as Exports hiding (id, (.))
+import Data.Functor as Exports hiding (unzip)
+import Data.Functor.Compose as Exports
+import Data.Functor.Contravariant as Exports
+import Data.Functor.Contravariant.Divisible as Exports
+import Data.Functor.Identity as Exports
+import Data.HashMap.Strict as Exports (HashMap)
+import Data.HashSet as Exports (HashSet)
+import Data.Hashable as Exports (Hashable (..))
+import Data.IORef as Exports
+import Data.Int as Exports
+import Data.Ix as Exports
+import Data.List as Exports hiding (all, and, any, concat, concatMap, elem, filter, find, foldl, foldl', foldl1, foldr, foldr1, isSubsequenceOf, mapAccumL, mapAccumR, maximum, maximumBy, minimum, minimumBy, notElem, or, product, sortOn, sum, uncons)
+import Data.List.NonEmpty as Exports (NonEmpty (..))
+import Data.Maybe as Exports hiding (catMaybes, mapMaybe)
+import Data.Monoid as Exports hiding (Alt, (<>))
+import Data.Ord as Exports
+import Data.Profunctor.Unsafe as Exports
+import Data.Proxy as Exports
+import Data.Ratio as Exports
+import Data.STRef as Exports
+import Data.Scientific as Exports (Scientific)
+import Data.Semigroup as Exports hiding (First (..), Last (..))
+import Data.String as Exports
+import Data.Text as Exports (Text)
+import Data.Text.Encoding as Exports (encodeUtf8)
+import Data.Time as Exports
+import Data.Traversable as Exports
+import Data.Tuple as Exports
+import Data.UUID as Exports (UUID)
+import Data.Unique as Exports
+import Data.Vector as Exports (Vector)
+import Data.Version as Exports
+import Data.Void as Exports
+import Data.Word as Exports
+import Debug.Trace as Exports
+import Foreign.ForeignPtr as Exports
+import Foreign.Ptr as Exports
+import Foreign.StablePtr as Exports
+import Foreign.Storable as Exports
+import GHC.Conc as Exports hiding (orElse, threadWaitRead, threadWaitReadSTM, threadWaitWrite, threadWaitWriteSTM, withMVar)
+import GHC.Exts as Exports (IsList (..), groupWith, inline, lazy, sortWith)
+import GHC.Generics as Exports (Generic)
+import GHC.IO.Exception as Exports
+import GHC.OverloadedLabels as Exports
+import Hasql.Platform.Prelude.Text as Exports
+import Numeric as Exports
+import Prelude as Exports hiding (Read, all, and, any, concat, concatMap, elem, fail, filter, foldl, foldl1, foldr, foldr1, id, mapM, mapM_, maximum, minimum, notElem, or, product, sequence, sequence_, sum, (.))
+import System.Environment as Exports
+import System.Exit as Exports
+import System.IO as Exports (Handle, hClose)
+import System.IO.Error as Exports
+import System.IO.Unsafe as Exports
+import System.Mem as Exports
+import System.Mem.StableName as Exports
+import System.Timeout as Exports
+import Text.ParserCombinators.ReadP as Exports (ReadP, readP_to_S, readS_to_P)
+import Text.ParserCombinators.ReadPrec as Exports (ReadPrec, readP_to_Prec, readPrec_to_P, readPrec_to_S, readS_to_Prec)
+import Text.Printf as Exports (hPrintf, printf)
+import TextBuilder as Exports (TextBuilder)
+import Unsafe.Coerce as Exports
+import Witherable as Exports
+
+{-# INLINE forMToZero_ #-}
+forMToZero_ :: (Applicative m) => Int -> (Int -> m a) -> m ()
+forMToZero_ !startN f =
+  ($ pred startN) $ fix $ \loop !n -> if n >= 0 then f n *> loop (pred n) else pure ()
+
+{-# INLINE forMFromZero_ #-}
+forMFromZero_ :: (Applicative m) => Int -> (Int -> m a) -> m ()
+forMFromZero_ !endN f =
+  ($ 0) $ fix $ \loop !n -> if n < endN then f n *> loop (succ n) else pure ()
+
+{-# INLINE strictCons #-}
+strictCons :: a -> [a] -> [a]
+strictCons !a b =
+  let !c = a : b in c
diff --git a/src/platform/Hasql/Platform/Prelude/Text.hs b/src/platform/Hasql/Platform/Prelude/Text.hs
new file mode 100644
--- /dev/null
+++ b/src/platform/Hasql/Platform/Prelude/Text.hs
@@ -0,0 +1,14 @@
+module Hasql.Platform.Prelude.Text where
+
+import Data.ByteString qualified
+import Data.Text qualified
+import Data.Text.Encoding qualified
+import Data.Text.Encoding.Error qualified
+import Data.Text.Lazy qualified
+
+type LazyText =
+  Data.Text.Lazy.Text
+
+decodeUtf8Lenient :: Data.ByteString.ByteString -> Data.Text.Text
+decodeUtf8Lenient =
+  Data.Text.Encoding.decodeUtf8With Data.Text.Encoding.Error.lenientDecode
diff --git a/src/profiling/Main.hs b/src/profiling/Main.hs
new file mode 100644
--- /dev/null
+++ b/src/profiling/Main.hs
@@ -0,0 +1,118 @@
+module Main where
+
+import Control.Exception
+import Data.Vector qualified as F
+import Hasql.Connection qualified as Connection
+import Hasql.Connection.Settings qualified as Settings
+import Hasql.Decoders qualified as D
+import Hasql.Session qualified as B
+import Hasql.Statement qualified as Statement
+import Pqi.Ffi qualified
+import Prelude
+import TestcontainersPostgresql qualified
+
+main :: IO ()
+main =
+  withConnection \connection -> do
+    traceEventIO "START Session"
+    result <- Connection.use connection sessionWithManySmallResults
+    traceEventIO "STOP Session"
+    case result of
+      Left err ->
+        putStrLn ("Error: " <> show err)
+      Right vector -> do
+        putStrLn ("Received " <> show (F.length vector) <> " rows")
+    return ()
+
+-- * Sessions
+
+sessionWithManySmallParameters :: Vector (Int64, Int64) -> B.Session ()
+sessionWithManySmallParameters =
+  error "TODO: sessionWithManySmallParameters"
+
+sessionWithSingleLargeResultInVector :: B.Session (Vector (Int64, Int64))
+sessionWithSingleLargeResultInVector =
+  B.statement () statementWithManyRowsInVector
+
+sessionWithSingleLargeResultInList :: B.Session [(Int64, Int64)]
+sessionWithSingleLargeResultInList =
+  B.statement () statementWithManyRowsInList
+
+sessionWithManySmallResults :: B.Session (Vector (Int64, Int64))
+sessionWithManySmallResults =
+  F.replicateM 1000 (B.statement () statementWithSingleRow)
+
+-- * Statements
+
+statementWithManyParameters :: Statement.Statement (Vector (Int64, Int64)) ()
+statementWithManyParameters =
+  error "TODO: statementWithManyParameters"
+
+statementWithSingleRow :: Statement.Statement () (Int64, Int64)
+statementWithSingleRow =
+  Statement.preparable template encoder decoder
+  where
+    template =
+      "SELECT 1 :: int8, 2 :: int8"
+    encoder =
+      conquer
+    decoder =
+      D.singleRow row
+      where
+        row =
+          tuple <$> (D.column . D.nonNullable) D.int8 <*> (D.column . D.nonNullable) D.int8
+          where
+            tuple !a !b =
+              (a, b)
+
+statementWithManyRows :: (D.Row (Int64, Int64) -> D.Result result) -> Statement.Statement () result
+statementWithManyRows decoder =
+  Statement.preparable template encoder (decoder rowDecoder)
+  where
+    template =
+      "SELECT generate_series(0,1000) as a, generate_series(1000,2000) as b"
+    encoder =
+      conquer
+    rowDecoder =
+      tuple <$> (D.column . D.nonNullable) D.int8 <*> (D.column . D.nonNullable) D.int8
+      where
+        tuple !a !b =
+          (a, b)
+
+statementWithManyRowsInVector :: Statement.Statement () (Vector (Int64, Int64))
+statementWithManyRowsInVector =
+  statementWithManyRows D.rowVector
+
+statementWithManyRowsInList :: Statement.Statement () [(Int64, Int64)]
+statementWithManyRowsInList =
+  statementWithManyRows D.rowList
+
+-- * Testcontainers
+
+withConnection :: (Connection.Connection -> IO ()) -> IO ()
+withConnection = withConnectionByTagName "postgres:18"
+
+withConnectionByTagName :: Text -> (Connection.Connection -> IO ()) -> IO ()
+withConnectionByTagName tagName action = withConnectionSettings tagName \settings -> do
+  connection <- Connection.acquire Pqi.Ffi.adapter settings
+  case connection of
+    Left err -> fail ("Connection failed: " <> show err)
+    Right conn -> finally (action conn) (Connection.release conn)
+
+withConnectionSettings :: Text -> (Settings.Settings -> IO ()) -> IO ()
+withConnectionSettings tagName action = do
+  TestcontainersPostgresql.run
+    TestcontainersPostgresql.Config
+      { tagName,
+        auth = TestcontainersPostgresql.CredentialsAuth "postgres" "postgres",
+        forwardLogs = False
+      }
+    \(host, port) -> do
+      let settings =
+            mconcat
+              [ Settings.hostAndPort host port,
+                Settings.user "postgres",
+                Settings.password "postgres",
+                Settings.dbname "postgres"
+              ]
+      action settings
diff --git a/src/to-be-resolved/Hasql/ToBeResolved.hs b/src/to-be-resolved/Hasql/ToBeResolved.hs
new file mode 100644
--- /dev/null
+++ b/src/to-be-resolved/Hasql/ToBeResolved.hs
@@ -0,0 +1,47 @@
+module Hasql.ToBeResolved
+  ( ToBeResolved (..),
+    lookup,
+  )
+where
+
+import Control.Applicative
+import Prelude hiding (lookup)
+
+-- |
+-- A computation that first declares the keys it needs resolved and then,
+-- once a resolver @k -> v@ is provided, produces its result.
+--
+-- The defining trait is the upfront collection of keys prior to resolution,
+-- hence the name.
+data ToBeResolved k v a
+  = ToBeResolved
+      -- | Keys requested to be available for lookup.
+      [k]
+      -- | Continuation that looks up values by keys.
+      ((k -> v) -> a)
+
+type role ToBeResolved _ _ representational
+
+-- 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 #-}
+  pure a =
+    ToBeResolved [] (\_ -> a)
+  {-# INLINE (<*>) #-}
+  ToBeResolved lKeys lUse <*> ToBeResolved rKeys rUse =
+    ToBeResolved
+      (lKeys <> rKeys)
+      (\lookup -> lUse lookup (rUse lookup))
+
+{-# INLINE lookup #-}
+lookup :: k -> ToBeResolved k v v
+lookup key =
+  ToBeResolved [key] (\lookupFn -> lookupFn key)
diff --git a/tasty/Main.hs b/tasty/Main.hs
deleted file mode 100644
--- a/tasty/Main.hs
+++ /dev/null
@@ -1,448 +0,0 @@
-module Main where
-
-import Main.Prelude hiding (assert)
-import Test.QuickCheck.Instances
-import Test.Tasty
-import Test.Tasty.Runners
-import Test.Tasty.HUnit
-import Test.Tasty.QuickCheck
-import qualified Test.QuickCheck as QuickCheck
-import qualified Main.Queries as Queries
-import qualified Main.DSL as DSL
-import qualified Main.Connection as Connection
-import qualified Hasql.Query as Query
-import qualified Hasql.Encoders as Encoders
-import qualified Hasql.Decoders as Decoders
-import qualified Hasql.Session as Session
-
-main =
-  defaultMain tree
-
-tree =
-  localOption (NumThreads 1) $
-  testGroup "All tests"
-  [
-    testCase "IN simulation" $
-    let
-      query =
-        Query.statement "select true where 1 = any ($1)" encoder decoder True
-        where
-          encoder =
-            Encoders.value (Encoders.array (Encoders.arrayDimension foldl' (Encoders.arrayValue Encoders.int8)))
-          decoder =
-            fmap (maybe False (const True)) (Decoders.maybeRow (Decoders.value Decoders.bool))
-      session =
-        do
-          result1 <- Session.query [1, 2] query
-          result2 <- Session.query [2, 3] query
-          return (result1, result2)
-      in do
-        x <- Connection.with (Session.run session)
-        assertEqual (show x) (Right (Right (True, False))) x
-    ,
-    testCase "NOT IN simulation" $
-    let
-      query =
-        Query.statement "select true where 3 <> all ($1)" encoder decoder True
-        where
-          encoder =
-            Encoders.value (Encoders.array (Encoders.arrayDimension foldl' (Encoders.arrayValue Encoders.int8)))
-          decoder =
-            fmap (maybe False (const True)) (Decoders.maybeRow (Decoders.value Decoders.bool))
-      session =
-        do
-          result1 <- Session.query [1, 2] query
-          result2 <- Session.query [2, 3] query
-          return (result1, result2)
-      in do
-        x <- Connection.with (Session.run session)
-        assertEqual (show x) (Right (Right (True, False))) x
-    ,
-    testCase "Composite decoding" $
-    let
-      query =
-        Query.statement sql encoder decoder True
-        where
-          sql =
-            "select (1, true)"
-          encoder = 
-            Encoders.unit
-          decoder =
-            Decoders.singleRow (Decoders.value (Decoders.composite ((,) <$> Decoders.compositeValue Decoders.int8 <*> Decoders.compositeValue Decoders.bool)))
-      session =
-        Session.query () query
-      in do
-        x <- Connection.with (Session.run session)
-        assertEqual (show x) (Right (Right (1, True))) x
-    ,
-    testCase "Complex composite decoding" $
-    let
-      query =
-        Query.statement sql encoder decoder True
-        where
-          sql =
-            "select (1, true) as entity1, ('hello', 3) as entity2"
-          encoder =
-            Encoders.unit
-          decoder =
-            Decoders.singleRow $
-            (,) <$> Decoders.value entity1 <*> Decoders.value entity2
-            where
-              entity1 =
-                Decoders.composite $
-                (,) <$> Decoders.compositeValue Decoders.int8 <*> Decoders.compositeValue Decoders.bool
-              entity2 =
-                Decoders.composite $
-                (,) <$> Decoders.compositeValue Decoders.text <*> Decoders.compositeValue Decoders.int8
-      session =
-        Session.query () query
-      in do
-        x <- Connection.with (Session.run session)
-        assertEqual (show x) (Right (Right ((1, True), ("hello", 3)))) x
-    ,
-    testCase "Empty array" $
-    let
-      io =
-        do
-          x <- Connection.with (Session.run session)
-          assertEqual (show x) (Right (Right [])) x
-        where
-          session =
-            Session.query () query
-            where
-              query =
-                Query.statement sql encoder decoder True
-                where
-                  sql =
-                    "select array[]::int8[]"
-                  encoder =
-                    Encoders.unit
-                  decoder =
-                    Decoders.singleRow (Decoders.value (Decoders.array (Decoders.arrayDimension replicateM (Decoders.arrayValue Decoders.int8))))
-      in io
-    ,
-    testCase "Failing prepared statements" $
-    let
-      io =
-        Connection.with (Session.run session) >>=
-        (assertBool <$> show <*> resultTest)
-        where
-          resultTest =
-            \case
-              Right (Left (Session.ResultError (Session.ServerError "26000" _ _ _))) -> False
-              _ -> True
-          session =
-            catchError session (const (pure ())) *> session
-            where
-              session =
-                Session.query () query
-                where
-                  query =
-                    Query.statement sql encoder decoder True
-                    where
-                      sql =
-                        "absurd"
-                      encoder =
-                        Encoders.unit
-                      decoder =
-                        Decoders.unit
-      in io
-    ,
-    testCase "Prepared statements after error" $
-    let
-      io =
-        Connection.with (Session.run session) >>=
-        \x -> assertBool (show x) (either (const False) isRight x)
-        where
-          session =
-            try *> fail *> try
-            where
-              try =
-                Session.query 1 query
-                where
-                  query =
-                    Query.statement sql encoder decoder True
-                    where
-                      sql =
-                        "select $1 :: int8"
-                      encoder =
-                        Encoders.value Encoders.int8
-                      decoder =
-                        Decoders.singleRow $ Decoders.value Decoders.int8
-              fail =
-                catchError (Session.sql "absurd") (const (pure ()))
-      in io
-    ,
-    testCase "\"in progress after error\" bugfix" $
-    let
-      sumQuery :: Query.Query (Int64, Int64) Int64
-      sumQuery =
-        Query.statement sql encoder decoder True
-        where
-          sql =
-            "select ($1 + $2)"
-          encoder =
-            contramap fst (Encoders.value Encoders.int8) <>
-            contramap snd (Encoders.value Encoders.int8)
-          decoder =
-            Decoders.singleRow (Decoders.value Decoders.int8)
-      sumSession :: Session.Session Int64
-      sumSession =
-        Session.sql "begin" *> Session.query (1, 1) sumQuery <* Session.sql "end"
-      errorSession :: Session.Session ()
-      errorSession =
-        Session.sql "asldfjsldk"
-      io =
-        Connection.with $ \c -> do
-          Session.run errorSession c
-          Session.run sumSession c
-      in io >>= \x -> assertBool (show x) (either (const False) isRight x)
-    ,
-    testCase "\"another command is already in progress\" bugfix" $
-    let
-      sumQuery :: Query.Query (Int64, Int64) Int64
-      sumQuery =
-        Query.statement sql encoder decoder True
-        where
-          sql =
-            "select ($1 + $2)"
-          encoder =
-            contramap fst (Encoders.value Encoders.int8) <>
-            contramap snd (Encoders.value Encoders.int8)
-          decoder =
-            Decoders.singleRow (Decoders.value Decoders.int8)
-      session :: Session.Session Int64
-      session =
-        do
-          Session.sql "begin;"
-          s <- Session.query (1,1) sumQuery
-          Session.sql "end;"
-          return s
-      in DSL.session session >>= \x -> assertEqual (show x) (Right 2) x
-    ,
-    testCase "Executing the same query twice" $
-    pure ()
-    ,
-    testCase "Interval Encoding" $
-    let
-      actualIO =
-        DSL.session $ do
-          let
-            query =
-              Query.statement sql encoder decoder True
-              where
-                sql =
-                  "select $1 = interval '10 seconds'"
-                decoder =
-                  (Decoders.singleRow (Decoders.value (Decoders.bool)))
-                encoder =
-                  Encoders.value (Encoders.interval)
-            in DSL.query (10 :: DiffTime) query
-      in actualIO >>= \x -> assertEqual (show x) (Right True) x
-    ,
-    testCase "Interval Decoding" $
-    let
-      actualIO =
-        DSL.session $ do
-          let
-            query =
-              Query.statement sql encoder decoder True
-              where
-                sql =
-                  "select interval '10 seconds'"
-                decoder =
-                  (Decoders.singleRow (Decoders.value (Decoders.interval)))
-                encoder =
-                  Encoders.unit
-            in DSL.query () query
-      in actualIO >>= \x -> assertEqual (show x) (Right (10 :: DiffTime)) x
-    ,
-    testCase "Interval Encoding/Decoding" $
-    let
-      actualIO =
-        DSL.session $ do
-          let
-            query =
-              Query.statement sql encoder decoder True
-              where
-                sql =
-                  "select $1"
-                decoder =
-                  (Decoders.singleRow (Decoders.value (Decoders.interval)))
-                encoder =
-                  Encoders.value (Encoders.interval)
-            in DSL.query (10 :: DiffTime) query
-      in actualIO >>= \x -> assertEqual (show x) (Right (10 :: DiffTime)) x
-    ,
-    testCase "Unknown" $
-    let
-      actualIO =
-        DSL.session $ do
-          let
-            query =
-              Query.statement sql mempty Decoders.unit True
-              where
-                sql =
-                  "drop type if exists mood"
-            in DSL.query () query
-          let
-            query =
-              Query.statement sql mempty Decoders.unit True
-              where
-                sql =
-                  "create type mood as enum ('sad', 'ok', 'happy')"
-            in DSL.query () query
-          let
-            query =
-              Query.statement sql encoder decoder True
-              where
-                sql =
-                  "select $1 = ('ok' :: mood)"
-                decoder =
-                  (Decoders.singleRow (Decoders.value (Decoders.bool)))
-                encoder =
-                  Encoders.value (Encoders.unknown)
-            in DSL.query "ok" query
-      in actualIO >>= assertEqual "" (Right True)
-    ,
-    testCase "Textual Unknown" $
-    let
-      actualIO =
-        DSL.session $ do
-          let
-            query =
-              Query.statement sql mempty Decoders.unit True
-              where
-                sql =
-                  "create or replace function overloaded(a int, b int) returns int as $$ select a + b $$ language sql;"
-            in DSL.query () query
-          let
-            query =
-              Query.statement sql mempty Decoders.unit True
-              where
-                sql =
-                  "create or replace function overloaded(a text, b text, c text) returns text as $$ select a || b || c $$ language sql;"
-            in DSL.query () query
-          let
-            query =
-              Query.statement sql encoder decoder True
-              where
-                sql =
-                  "select overloaded($1, $2) || overloaded($3, $4, $5)"
-                decoder =
-                  (Decoders.singleRow (Decoders.value (Decoders.text)))
-                encoder =
-                  contramany (Encoders.value Encoders.unknown)
-            in DSL.query ["1", "2", "4", "5", "6"] query
-      in actualIO >>= assertEqual "" (Right "3456")
-    ,
-    testCase "Enum" $
-    let
-      actualIO =
-        DSL.session $ do
-          let
-            query =
-              Query.statement sql mempty Decoders.unit True
-              where
-                sql =
-                  "drop type if exists mood"
-            in DSL.query () query
-          let
-            query =
-              Query.statement sql mempty Decoders.unit True
-              where
-                sql =
-                  "create type mood as enum ('sad', 'ok', 'happy')"
-            in DSL.query () query
-          let
-            query =
-              Query.statement sql encoder decoder True
-              where
-                sql =
-                  "select ($1 :: mood)"
-                decoder =
-                  (Decoders.singleRow (Decoders.value (Decoders.enum (Just . id))))
-                encoder =
-                  Encoders.value (Encoders.enum id)
-            in DSL.query "ok" query
-      in actualIO >>= assertEqual "" (Right "ok")
-    ,
-    testCase "The same prepared statement used on different types" $ 
-    let
-      actualIO =
-        DSL.session $ do
-          let
-            effect1 =
-              DSL.query "ok" query
-              where
-                query =
-                  Query.statement sql encoder decoder True
-                  where
-                    sql =
-                      "select $1"
-                    encoder =
-                      Encoders.value Encoders.text
-                    decoder =
-                      (Decoders.singleRow (Decoders.value (Decoders.text)))
-            effect2 =
-              DSL.query 1 query
-              where
-                query =
-                  Query.statement sql encoder decoder True
-                  where
-                    sql =
-                      "select $1"
-                    encoder =
-                      Encoders.value Encoders.int8
-                    decoder =
-                      (Decoders.singleRow (Decoders.value Decoders.int8))
-            in (,) <$> effect1 <*> effect2
-      in actualIO >>= assertEqual "" (Right ("ok", 1))
-    ,
-    testCase "Affected rows counting" $
-    replicateM_ 13 $
-    let
-      actualIO =
-        DSL.session $ do
-          dropTable
-          createTable
-          replicateM_ 100 insertRow
-          deleteRows <* dropTable
-        where
-          dropTable =
-            DSL.query () $ Queries.plain $ 
-            "drop table if exists a"
-          createTable =
-            DSL.query () $ Queries.plain $
-            "create table a (id bigserial not null, name varchar not null, primary key (id))"
-          insertRow =
-            DSL.query () $ Queries.plain $
-            "insert into a (name) values ('a')"  
-          deleteRows =
-            DSL.query () $ Query.statement sql def decoder False
-            where
-              sql =
-                "delete from a"
-              decoder =
-                Decoders.rowsAffected
-      in actualIO >>= assertEqual "" (Right 100)
-    ,
-    testCase "Result of an auto-incremented column" $
-    let
-      actualIO =
-        DSL.session $ do
-          DSL.query () $ Queries.plain $ "drop table if exists a"
-          DSL.query () $ Queries.plain $ "create table a (id serial not null, v char not null, primary key (id))"
-          id1 <- DSL.query () $ Query.statement "insert into a (v) values ('a') returning id" def (Decoders.singleRow (Decoders.value Decoders.int4)) False
-          id2 <- DSL.query () $ Query.statement "insert into a (v) values ('b') returning id" def (Decoders.singleRow (Decoders.value Decoders.int4)) False
-          DSL.query () $ Queries.plain $ "drop table if exists a"
-          pure (id1, id2)
-      in assertEqual "" (Right (1, 2)) =<< actualIO
-    ,
-    testCase "List decoding" $
-    let
-      actualIO =
-        DSL.session $ DSL.query () $ Queries.selectList
-      in assertEqual "" (Right [(1, 2), (3, 4), (5, 6)]) =<< actualIO 
-  ]
-
diff --git a/tasty/Main/Connection.hs b/tasty/Main/Connection.hs
deleted file mode 100644
--- a/tasty/Main/Connection.hs
+++ /dev/null
@@ -1,28 +0,0 @@
-module Main.Connection
-where
-
-import Main.Prelude
-import qualified Hasql.Connection as HC
-import qualified Hasql.Query as HQ
-import qualified Hasql.Session
-
-
-with :: (HC.Connection -> IO a) -> IO (Either HC.ConnectionError a)
-with handler =
-  runExceptT $ acquire >>= \connection -> use connection <* release connection
-  where
-    acquire =
-      ExceptT $ HC.acquire settings
-      where
-        settings =
-          HC.settings host port user password database
-          where
-            host = "localhost"
-            port = 5432
-            user = "postgres"
-            password = ""
-            database = "postgres"
-    use connection =
-      lift $ handler connection
-    release connection =
-      lift $ HC.release connection
diff --git a/tasty/Main/DSL.hs b/tasty/Main/DSL.hs
deleted file mode 100644
--- a/tasty/Main/DSL.hs
+++ /dev/null
@@ -1,47 +0,0 @@
-module Main.DSL
-(
-  Session,
-  SessionError(..),
-  session,
-  Hasql.Session.query,
-  Hasql.Session.sql,
-)
-where
-
-import Main.Prelude
-import qualified Hasql.Connection as HC
-import qualified Hasql.Query as HQ
-import qualified Hasql.Encoders as HE
-import qualified Hasql.Decoders as HD
-import qualified Hasql.Session
-
-
-type Session =
-  Hasql.Session.Session
-
-data SessionError =
-  ConnectionError (HC.ConnectionError) |
-  SessionError (Hasql.Session.Error)
-  deriving (Show, Eq)
-
-session :: Session a -> IO (Either SessionError a)
-session session =
-  runExceptT $ acquire >>= \connection -> use connection <* release connection
-  where
-    acquire =
-      ExceptT $ fmap (mapLeft ConnectionError) $ HC.acquire settings
-      where
-        settings =
-          HC.settings host port user password database
-          where
-            host = "localhost"
-            port = 5432
-            user = "postgres"
-            password = ""
-            database = "postgres"
-    use connection =
-      ExceptT $
-      fmap (mapLeft SessionError) $
-      Hasql.Session.run session connection
-    release connection =
-      lift $ HC.release connection
diff --git a/tasty/Main/Prelude.hs b/tasty/Main/Prelude.hs
deleted file mode 100644
--- a/tasty/Main/Prelude.hs
+++ /dev/null
@@ -1,14 +0,0 @@
-module Main.Prelude
-(
-  module Exports,
-)
-where
-
-
--- rerebase
--------------------------
-import Prelude as Exports
-
--- data-default-class
--------------------------
-import Data.Default.Class as Exports
diff --git a/tasty/Main/Queries.hs b/tasty/Main/Queries.hs
deleted file mode 100644
--- a/tasty/Main/Queries.hs
+++ /dev/null
@@ -1,36 +0,0 @@
-module Main.Queries where
-
-import Main.Prelude hiding (def)
-import qualified Hasql.Query as HQ
-import qualified Hasql.Encoders as HE
-import qualified Hasql.Decoders as HD
-import qualified Main.Prelude as Prelude
-
-
-def :: ByteString -> HQ.Query () ()
-def sql =
-  HQ.statement sql Prelude.def Prelude.def False
-
-plain :: ByteString -> HQ.Query () ()
-plain sql =
-  HQ.statement sql mempty HD.unit False
-
-dropType :: ByteString -> HQ.Query () ()
-dropType name =
-  plain $
-    "drop type if exists " <> name
-
-createEnum :: ByteString -> [ByteString] -> HQ.Query () ()
-createEnum name values =
-  plain $
-    "create type " <> name <> " as enum (" <> 
-    mconcat (intersperse ", " (map (\x -> "'" <> x <> "'") values)) <> ")"
-
-selectList :: HQ.Query () ([] (Int64, Int64))
-selectList =
-  HQ.statement sql mempty decoder True
-  where
-    sql =
-      "values (1,2), (3,4), (5,6)"
-    decoder =
-      HD.rowsList ((,) <$> HD.value HD.int8 <*> HD.value HD.int8)
diff --git a/threads-test/Main.hs b/threads-test/Main.hs
deleted file mode 100644
--- a/threads-test/Main.hs
+++ /dev/null
@@ -1,45 +0,0 @@
-module Main where
-
-import Rebase.Prelude
-import qualified Hasql.Connection
-import qualified Hasql.Query
-import qualified Hasql.Encoders
-import qualified Hasql.Decoders
-import qualified Hasql.Session
-import qualified Main.Queries as Queries
-
-
-main =
-  acquire >>= use
-  where
-    acquire =
-      (,) <$> acquire <*> acquire
-      where
-        acquire =
-          join $
-          fmap (either (fail . show) return) $
-          Hasql.Connection.acquire connectionSettings
-          where
-            connectionSettings =
-              Hasql.Connection.settings "localhost" 5432 "postgres" "" "postgres"
-    use (connection1, connection2) =
-      do
-        beginVar <- newEmptyMVar
-        finishVar <- newEmptyMVar
-        forkIO $ do
-          traceM "1: in"
-          putMVar beginVar ()
-          session connection1 (Hasql.Session.query 0.2 Queries.selectSleep)
-          traceM "1: out"
-          void (tryPutMVar finishVar False)
-        forkIO $ do
-          takeMVar beginVar
-          traceM "2: in"
-          session connection2 (Hasql.Session.query 0.1 Queries.selectSleep)
-          traceM "2: out"
-          void (tryPutMVar finishVar True)
-        bool exitFailure exitSuccess . traceShowId =<< takeMVar finishVar
-      where
-        session connection session =
-          Hasql.Session.run session connection >>=
-          either (fail . show) return
diff --git a/threads-test/Main/Queries.hs b/threads-test/Main/Queries.hs
deleted file mode 100644
--- a/threads-test/Main/Queries.hs
+++ /dev/null
@@ -1,20 +0,0 @@
-module Main.Queries where
-
-import Rebase.Prelude
-import Hasql.Query
-import qualified Hasql.Encoders as E
-import qualified Hasql.Decoders as D
-
-
-selectSleep :: Query Double ()
-selectSleep =
-  statement sql encoder decoder True
-  where
-    sql =
-      "select pg_sleep($1)"
-    encoder =
-      E.value E.float8
-    decoder =
-      D.unit
-
-
