MIT licensed and maintained by Nikita Volkov
This version can be pinned in stack with:pqi-native-1.0.1.18@sha256:9aced4749a41f3e5444a48c721e46c6dc5e6834b94e2b90fb6911d982343d9b0,4349

Module documentation for 1.0.1.18

pqi-native

Hackage Continuous Haddock

Status: Alpha. pqi-native is an early implementation of a pure-Haskell transport for pqi. It exists alongside pqi-ffi, the established C-backed adapter, and the two are fully interchangeable: any code written against pqi runs unchanged on either one, so trying pqi-native carries no lock-in and no rewrite cost. Correctness is checked continuously against a conformance suite (see below), but the adapter hasn’t yet accumulated production mileage. If you need a production-proven transport today, use pqi-ffi. See Making libpq a choice for why this project exists and what tradeoffs that implies.

A pure-Haskell pqi adapter that speaks the PostgreSQL frontend/backend wire protocol directly - no dependency on the C libpq library.

pqi-native reimplements the wire protocol handled by the PostgreSQL C client library, libpq, from scratch in Haskell. The upstream libpq source is the direct reference for the implementation.

Fidelity goal

The goal is identical output to libpq for every protocol-derived value - error message strings, notice text, result status, field metadata, cell data, and all structured error fields. Fidelity is continuously enforced by pqi-conformance, which runs every operation on both this adapter and a direct postgresql-libpq reference connection against the same database and asserts exact equality.

Status

Alpha. The full Pqi.Connection capability record is implemented and verified against the postgresql-libpq reference via the conformance differential suite, but the library hasn’t yet accumulated real-world production mileage.

Because it implements the same pqi interface as pqi-ffi, switching between the two is a one-line change - pass a different Adapter value, nothing else in your code moves. That makes pqi-native low-risk to evaluate now and easy to fall back from: adopt it where you want to shed the libpq dependency, and drop back to pqi-ffi at any time without touching the rest of your codebase. Read Making libpq a choice for the motivation and the tradeoffs of adopting it at this stage.

Authentication: trust, MD5, and SCRAM-SHA-256 are implemented. SCRAM is verified against a password-auth PostgreSQL 17 container (which defaults to scram-sha-256).

Transport: plain TCP and Unix-domain sockets. A host value that’s an absolute path names a socket directory instead of a TCP host, and omitting host altogether defaults the way libpq itself does: PGHOST if set, otherwise a Unix-domain socket in /tmp on Unix-like systems, or localhost on Windows.

Changes

v1.0.1.18

Non-breaking

  • Relaxed the crypton upper bound to allow the 2.1 release series.

v1.0.1.17

Fixes

  • Fixed a query sent under uninterruptibleMask hanging forever on the non-threaded RTS (#17). Transport.awaitWritableOrReadable, the read-or-write readiness wait of the send loop, armed both waits with base’s threadWaitReadSTM/threadWaitWriteSTM. On the non-threaded RTS those fork a helper thread with a bare forkIO and cancel it with killThread, and a forked thread inherits the caller’s masking state: from under an uninterruptibleMask - such as a safe-exceptions bracket‘s release action - the cancellation of the readable wait could never be delivered while the socket stayed writable-but-not-readable, the steady state of an idle connection being sent a query, so the send, and with it the whole query, never reached the server. libpq’s send loop (pqSendSome in fe-misc.c) waits with a plain select and has no masking state to inherit. On the non-threaded RTS the wait helper is now forked with forkIOWithUnmask, whose body runs unmasked whatever the caller’s state (it is forkIO (io unsafeUnmask)), so the cancellation always delivers; on the threaded RTS the waits remain base’s event-manager registrations, which have no helper thread. Caught by the pqi-conformance spec Pqi.Conformance.Operation.Exec.UninterruptibleMask (pqi-conformance 1.0.18.0), run by the new native-test-nonthreaded test suite: the suite must be built without -threaded for the divergence to manifest.

v1.0.1.16

Fixes

  • Fixed reading a result’s cells being quadratic in its rows (#15). mkResult kept the rows, fields and parameter OIDs as lists, and getvalue, getvalue', getisnull and getlength reached the requested row with drop from the head of the list on every call, so scanning every row through them took time quadratic in the row count: 3.9 s for 40,000 rows, where libpq, which indexes an array, took 17 ms. The rows, fields and parameter OIDs are now indexed into vectors once per result, on first access, and shared by every accessor, so each lookup takes constant time. Out-of-range indexes still return the same values. Caught by the pqi-conformance spec Pqi.Conformance.Operation.Getvalue.ManyRows.

  • Fixed a synchronous call returning the results of an earlier query whose results were still unread (#16). exec, execParams, prepare, execPrepared, describePrepared and describePortal sent their query and read up to the next ReadyForQuery without recording that a query was in flight. When an asynchronous exception, such as one from timeout, interrupted one of them while it waited, the interrupted query’s messages stayed unread. The next call read them as its own and returned the interrupted query’s result, and every call after that returned the result of the one before it, with no error. A sendQuery or sendQueryParams whose results were never fetched had the same effect on the synchronous call that followed it. libpq’s PQexecParams is a blocking foreign call that cannot be interrupted, and PQexecStart reads and discards any leftover results before a synchronous call sends its query. The synchronous flows now do the same: they first discard any results still pending (outside pipeline mode), and they mark the connection busy from their send until their own ReadyForQuery, so an interrupted flow leaves its results to be discarded by the next one. If the connection is lost while discarding, the call returns Nothing, as PQexec does. Because the connection is now marked busy while a synchronous flow waits, a cancel from another thread reaches its query, where before it was skipped as if nothing were running. Caught by the pqi-conformance specs Pqi.Conformance.Operation.ExecParams.Interrupted and Pqi.Conformance.Operation.Exec.Interrupted.

v1.0.1.15

Fixes

  • Fixed receiving a large message allocating quadratically in its size (#13). Transport.fillTo appended every received chunk to a strict ByteString, copying the whole accumulated frame on each receive, and asked recv for a buffer as large as the rest of the frame, allocating that much again on each receive. A single 64 MiB bytea field allocated ~512 GiB over a Unix-domain socket. The read buffer is now a pinned storage that the socket is read straight into with recvBuf. It is replaced by a larger one only when a frame does not fit, sized exactly for a large frame and doubling otherwise, and frames are handed out as slices of it rather than copies. The same 64 MiB field now allocates 2.0 times its size on the Haskell heap: the receive and the copy getvalue returns. Caught by the pqi-conformance spec Pqi.Conformance.Operation.ExecParams.LargeField.

v1.0.1.14

Fixes

  • Fixed the hostaddr conninfo parameter being ignored (#11). With a hostaddr, libpq connects to that numeric address and never resolves host, which it keeps only for authentication and for naming the server in messages. pqi-native had no notion of it: it resolved host through DNS regardless, so a conninfo whose host does not resolve failed to connect, and the hostaddr key was forwarded to the server in the startup packet as if it were a run-time setting, which libpq never does. hostaddr is now parsed from both the key=value form and the URI’s query string, kept out of the startup parameters, and dialled over TCP in preference to host, also when host is a Unix-domain socket directory, and also by a later cancel and reset. host is still what Pqi.host reports. Caught by the pqi-conformance spec Pqi.Conformance.Operation.Connectdb.Hostaddr.

  • Fixed a lost connection being reported by throwing an IOException instead of the way libpq reports it. When the server closed the connection, or the socket failed, while a flow was waiting for results, Pqi.getResult (and, for a send that failed, the send itself) used to throw pqi-native: connection closed by server: end of file or a socket error such as Connection reset by peer; status stayed ConnectionOk; errorMessage stayed empty or lost the server’s own FATAL text; and a further send was accepted and threw again. libpq never throws here (hasql#341). Now, as in pqReadData, PQgetResult and pqDropConnection, the loss returns a FatalError result with no error fields (so no SQLSTATE) whose resultErrorMessage is libpq’s “server closed the connection unexpectedly” text, appended to the connection’s errorMessage after whatever was recorded before it. The connection becomes ConnectionBad, its socket is dropped (socket is Nothing, finish stays safe) and the next getResult returns Nothing. When the server announced the termination with a FATAL, that result is still returned first and unchanged, with status ConnectionOk, and the loss is reported by the read that follows. A pipeline that is lost ends the same way, without PipelineAbort results made up for the outstanding commands. A failed write (Broken pipe, Connection reset by peer) no longer throws either: as in libpq’s pqsecure_raw_write it is remembered, the send reports success, and the loss is reported by the following read. A send, or a synchronous exec family call, on a connection that is not usable returns False (Nothing) and sets errorMessage to “no connection to the server”, and transactionStatus is TransUnknown, as libpq’s are. putCopyData and putCopyEnd on such a connection return CopyInError instead of attempting the write. Also fixed in a pipeline: errorMessage was empty after a server error where libpq has the server’s text, and was not cleared when the next command’s results begin. Only IOException from the transport is caught, so asynchronous exceptions such as ThreadKilled and Timeout still propagate untouched. Caught by the pqi-conformance specs Pqi.Conformance.Operation.GetResult.LostConnection, Pqi.Conformance.Operation.Exec.LostConnection and Pqi.Conformance.Operation.ExecParams.LostConnection, whose scenario (pqi-conformance 1.0.14.0) also pins transactionStatus and socket after the loss.

v1.0.1.13

Non-breaking

  • Migrated the crypton dependency from the 0.34-1.x line to 2.0.1, which replaces its internal memory dependency with ram/base16. Pqi.Native.Auth’s MD5 and SCRAM-SHA-256 logic (Crypto.Hash, Crypto.KDF.PBKDF2, Crypto.MAC.HMAC, Crypto.Random) needed no source changes; verified hashWith, hmac, and fastPBKDF2_SHA256 still reproduce known MD5/SHA-256/HMAC-SHA256/PBKDF2 test vectors under crypton-2.0.1.

v1.0.1.12

Fixes

  • Fixed a pipeline flow-control deadlock: a pipelined burst of commands larger than the socket buffers along the path can absorb, submitted before any result is read, used to wedge both sides permanently. Pqi.Native.Transport.send was a bare blocking Network.Socket.ByteString.sendAll, which never reads while sending; once the server has filled its output path with unread results it blocks in ClientWrite and stops reading the client’s commands, so the client - still blocked in send with unsent bytes - can never finish, and neither side progresses again. libpq survives the same situation because its pqSendSome (fe-misc.c), on an incomplete send, calls pqReadData() to absorb incoming data and then pqWait(true, true, …) for read-or-write readiness, looping until its output is fully sent. send now mirrors that loop: whenever the socket is not writable, incoming bytes are drained into the transport’s read buffer and the wait is armed for read-or-write readiness (write-biased, so a streaming server cannot starve the send); a peer closing mid-send surfaces as the same classified EOF the read side reports. On Windows the plain sendAll remains, as GHC’s I/O manager cannot back the readiness wait there. Surfaced as hasql’s manyLargeResultsViaPipeline benchmark hanging from 1.0.1.4 onward, after the default host resolution moved to the Unix-domain socket whose 8KB buffers expose what TCP’s larger ones absorbed. Caught by the pqi-conformance spec Pqi.Conformance.Operation.SendQueryParams.PipelineFlowControl.

v1.0.1.11

Fixes

  • Fixed Pqi.connectionNeedsPassword and Pqi.connectionUsedPassword tracking the conninfo password= field instead of libpq’s password_needed auth-exchange state. connectionNeedsPassword was hardcoded pure False; connectionUsedPassword was not (ByteString.null password), so it reported True whenever a password string was merely present in the conninfo, trust auth or not, and connectionNeedsPassword never reported True even when SCRAM authentication was challenged for and no password was supplied. Pqi.Native.Connection.Connection now carries a passwordNeeded flag, set during the handshake only when the server actually sends AuthenticationCleartextPassword/MD5Password/SASL, and reset on reconnect; both functions now derive from that state, matching fe-auth.c’s password_needed semantics exactly. Caught by the pqi-conformance specs Pqi.Conformance.Operation.ConnectionNeedsPassword and Pqi.Conformance.Operation.ConnectionUsedPassword.

v1.0.1.10

Fixes

  • Fixed a socket death during a send (e.g. EPIPE/ECONNRESET) escaping Pqi.sendQuery/sendQueryParams/sendPrepare/sendQueryPrepared/sendDescribePrepared/sendDescribePortal as a raw, uncaught IOException instead of the False libpq’s PQsendQuery and friends always return for a fatal send (marking PQstatus CONNECTION_BAD and leaving PQerrorMessage with the same “server closed the connection unexpectedly” wording used for a connection lost while reading). Pqi.Native.Transport.send is Network.Socket.ByteString.sendAll, which throws rather than reporting failure through a return value, and sendAsync - the function every one of those six calls funnels through - called it with no exception handler at all. This is also the entry point hasql’s Session machinery actually exercises for every ordinary (non-pipelined) statement, so the escaped exception used to reach Hasql.Connection.use’s interruption handling and get treated as an async interruption instead of a classified send failure. sendAsync now catches an escaped IOException, marks the connection bad via the same markConnectionLost classification the read side already had, and returns False. The sibling direct sends in pipelineSync/sendFlushRequest (which bypass sendAsync entirely) get the same treatment. Caught by the pqi-conformance spec Pqi.Conformance.Operation.SendQuery.ConnectionLostBeforeSend.

v1.0.1.9

Fixes

  • Fixed a DNS resolution failure during connectdb reporting the raw Shown Network.Socket.getAddrInfo exception (e.g. could not connect to server: Network.Socket.getAddrInfo (called with preferred socket type/protocol: ...): does not exist (nodename nor servname provided, or not known)) instead of libpq’s own sentence for it (could not translate host name "..." to address: nodename nor servname provided, or not known). connectFailureMessage now recognizes a resolver failure by Network.Socket.getAddrInfo naming itself in the exception’s ioe_location, and reproduces libpq’s wording using the exception’s ioe_description. Caught by the pqi-conformance spec Pqi.Conformance.Operation.Connectdb.UnresolvableHost.

  • Fixed a handshake-time hard TCP reset (ECONNRESET, as opposed to a clean EOF) reporting the raw Shown IOException (e.g. Network.Socket.recvBuf: resource vanished (Connection reset by peer)) instead of libpq’s own “server closed the connection unexpectedly” sentence, which it uses for both a reset and a clean EOF alike. handshakeFailureMessage’s classification (isConnectionLost, factored out as connectionLostMessage) now also recognizes a reset - Network.Socket surfaces ECONNRESET as ioe_type == ResourceVanished rather than System.IO.Error.eofErrorType - not just a clean EOF. Caught by the pqi-conformance spec Pqi.Conformance.Operation.Connectdb.HandshakeReset.

  • Fixed a connection reset while a query response was in flight escaping Pqi.exec/execParams/prepare/execPrepared/describePrepared/describePortal as a raw, uncaught IOException instead of coming back as a classified FatalError result the way libpq’s PQexec does (a lost connection mid-query never throws there; it reports a result with FatalError status and the same “server closed the connection unexpectedly” wording used for a handshake-time loss). Each of those six flows now catches an IOException escaping its read loop and reports it through the same connectionLostMessage classification, also marking the connection ConnectionBad. Caught by the pqi-conformance spec Pqi.Conformance.Operation.Exec.ConnectionLostMidQuery. Found via hasql issue #329.

v1.0.1.8

Fixes

  • Fixed connectFailureMessage (used when the initial connect(2) fails, e.g. a missing Unix-socket directory) hand-rolling a TCP-shaped message - the raw Shown IOException prefixed with "could not connect to server: " and a (Unix domain socket '<path>') parenthetical appended - instead of reporting the failure the way libpq does. That hand-rolled text retained the literal prefix "could not connect to server: ", which is also the substring Hasql.Connection‘s error classifier matches to identify a transient networking failure - so a permanent misconfiguration (missing socket directory) was misclassified as transient. The Unix-socket branch now delegates to unixSocketFailureMessage, extracting the underlying IOException‘s ioe_description (the raw OS strerror text, e.g. "No such file or directory") instead of embedding its whole Shown form, and appending the same "Is the server running locally and accepting connections on that socket?" hint libpq appends for this failure - matching libpq’s message for this case exactly. Also fixed unixSocketFailureMessage itself quoting the socket path with single quotes ('<path>') instead of libpq’s double quotes ("<path>"), which affects every message it formats, including the handshake-rejection path this Unix-socket branch now shares. Caught by the pqi-conformance spec Pqi.Conformance.Operation.Connectdb.MissingUnixSocketDirectory. Found via hasql issue #329.

v1.0.1.7

Fixes

  • Fixed a postgresql:// URI conninfo with a percent-encoded Unix-socket host (e.g. %2ftmp%2f...) being passed through to host still percent-encoded instead of decoded. parseUri’s host/port splitter decoded every other URI component (user, password, dbname, query params) but forwarded the raw, undecoded host bytes. Caught by the pqi-conformance differential spec Pqi.Conformance.Operation.Connectdb.UnixSocketUri.

v1.0.1.6

Fixes

  • Fixed a mid-handshake server rejection (e.g. “sorry, too many clients already”) escaping as an uncaught IOException instead of coming back as a classified ConnectionBad (#8). establish only wrapped the initial TCP connect in an exception handler; the handshake read that follows it is now caught too and routed through the same tcpFailureMessage/unixSocketFailureMessage wrapper failWith uses, with libpq’s own wording for the EOF case. tcpFailureMessage also stopped adding a redundant “(ip)” parenthetical when the resolved peer IP is identical to the given host. Caught by the pqi-conformance spec added in nikita-volkov/pqi-conformance@92f5205.

  • Fixed a pipelined command’s result getting misattributed to a later, unrelated command after a prior pipeline aborted on a server error (#9). A pipelined command that sends a Parse (sendQueryParams/sendPrepare) records a FIFO entry so the eventual ParseComplete can be charged to the right command; that entry was only ever popped by a ParseComplete actually arriving. A command whose Parse itself fails - a syntax error, or being silently discarded by the server after a pipeline abort - never gets a ParseComplete, so its entry was leaked. A sendPrepare leaks a True entry, and once a later, unrelated command’s genuine ParseComplete popped that stale True instead of its own, that command terminated immediately as CommandOk instead of collecting its real result, observed as a SELECT returning CommandOk instead of TuplesOk. Every pipelined command now pops its FIFO entry exactly once, whether via its own ParseComplete or, failing that, at its own terminal message (including the synthetic result generated for a command discarded after an abort). Caught by the differential coverage added in pqi-conformance 1.0.5.1.

v1.0.1.5

Fixes

  • sendQueryParams, execParams, sendPrepare, prepare, sendQueryPrepared, and execPrepared now reject a parameter list (or, for prepare/sendPrepare, a parameter-type list) longer than 65535 locally, without writing anything to the socket, mirroring libpq’s PQ_QUERY_PARAM_MAX_LIMIT check. The Parse/Bind messages encode their parameter count as a 16-bit field; past the limit fromIntegral silently wrapped it (65536 became 0), producing a malformed message the server rejected with invalid message format and leaving the connection desynchronized - inside a pipeline, every command dispatched before the failing one was left with its results undrained. Caught by the differential coverage added in pqi-conformance 1.0.5.0. Found via hasql issue #326.

v1.0.1.4

Fixes

  • Fixed missing support for connecting over a Unix-domain socket (#6). A host value that looks like an absolute path (e.g. host=/var/run/postgresql) names a socket directory rather than a TCP host, and the connection is made to a .s.PGSQL.<port> unix-domain socket in that directory, mirroring libpq’s rule for the host conninfo parameter. A conninfo with no host (or an empty one) now defaults the way libpq itself does: the PGHOST environment variable if set and non-empty, otherwise a Unix-domain socket in /tmp on Unix-like systems (see Pqi.Native.Connection.defaultUnixSocketDir‘s Haddock for how a distribution that compiles its own libpq with a different default, e.g. Fedora’s /run/postgresql, can match it via cabal.project - no source patch needed), or localhost on Windows, unchanged. Connect-failure and handshake-failure messages now describe the socket path rather than a host/port pair when connecting this way.

    No privilege-elevation guard is applied to reading PGHOST (or the existing PGUSER lookup): libpq itself reads these with plain getenv(), with no secure_getenv/geteuid-vs-getuid check anywhere in fe-connect.c - responsibility for scrubbing the environment before opening a database connection is on any setuid/setgid caller, exactly as it is for libpq.

v1.0.1.3

Fixes

  • Fixed an async exception around an aborted pipeline leaving a connection permanently stuck, with no timer able to reclaim it. Two changes, which are only a fix together:

    • Query.getNextResult now runs mask_ed. The connection’s result bookkeeping - the pending-command counter, the separator flag, the ParseComplete origin FIFO - lives in separate IORefs that one logical transition updates in sequence. An interrupt landing between two of those updates left them inconsistent, and an inconsistent pair sends the next getNextResult off to wait for a message the backend has already decided not to send.

    • Transport.receiveFrame no longer runs uninterruptibleMask_ed. It buffers a whole frame before consuming any of it and takes it out of the buffer in one atomic step, so the framing 1.0.1.2 set out to protect stays intact - but the blocking wait is masked only across moving bytes off the socket, not across waiting for them. The 1.0.1.2 shape made every wait unabandonable, which is what turned the stall above into a deadlock System.Timeout.timeout could not break.

    Found via a hang in hasql’s Integration.Sharing.Connection.Use.PipelineAbortedInterruptionCleanup, which wedged only under concurrent load and only on this adapter.

v1.0.1.2

Fixes

  • Fixed an async exception (e.g. from System.Timeout.timeout) landing mid-read permanently desyncing a connection’s message framing. Transport.receiveFrame now runs uninterruptibleMask_ed, so a frame is either read to completion or not started, mirroring how pqi-ffi’s safe FFI call into libpq is structurally immune to the same hazard. Caught by the differential coverage in pqi-conformance 1.0.3.0 (#5).

v1.0.1.1

Fixes

  • Builds on Windows: socket I/O and signal handling now branch on the host OS, selecting Win32 in place of unix.

  • Fixed a pipelined sendPrepare stealing the preceding sendQueryParams’ ParseComplete, which produced a spurious CommandOk and shifted every later result by one. ParseComplete messages are now charged to the command that produced them via a per-command FIFO (#3).

v1.0.1.0

Non-breaking

  • Picked up pqi 1.1.0.0, which renamed Notify’s fields to notifyRelname/notifyBePid/notifyExtra to match postgresql-libpq

v1.0.0.1

Doc corrections.

v1.0.0.0

Non-breaking

  • Support for the resStatus field of Pqi.Adapter

v0.2.0.5

Fixes

  • Fixed the release process to actually result in publishing of the package.

v0.2.0.4

Fixes

  • Fixed the connection closing.

v0.2.0.3

Documentation corrections.

v0.2.0.2

Fixes

  • Connection startup now forwards extra conninfo params (e.g. application_name, options) instead of silently dropping everything but user and database, so they reach the server the way libpq’s do. Caught by the new differential coverage in pqi-conformance 0.1.1.0.

v0.2.0.1

Documentation corrections.

v0.2.0.0

Breaking

  • Hid the public sublibs.

v0.1.0.1

Fixes

  • Adapted to GHC 8.10: pruned unsupported default-extensions (ApplicativeDo, DuplicateRecordFields, NoFieldSelectors, OverloadedRecordDot, TemplateHaskell) and rewrote the source accordingly

v0.1.0.0

Breaking

  • Migrate to pqi 0.1’s record-of-functions redesign and switch to exporting the adapter value instead of the Connection type.