async_postgres/pg_connection/types

Search:
Group by:

Shared building blocks for pg_connection submodules (PgConnection, ConnConfig, tracing) and the state operations that keep its private fields consistent (see the sections below).

Internal module: not part of the public API. Import the pg_connection hub instead.

Types

AuthMethod = enum
  amNone,                   ## AuthenticationOk with no challenge (trust/peer/ident)
  amPassword,               ## cleartext password (libpq: "password")
  amMd5,                    ## MD5 challenge (libpq: "md5")
  amScramSha256, ## SASL SCRAM-SHA-256, with or without channel binding (libpq:
                  ## "scram-sha-256")
  amScramSha256Plus          ## SASL SCRAM-SHA-256-PLUS alone ("scram-sha-256-plus", not in libpq)
Individual authentication methods for ConnConfig.requireAuth allowlisting (libpq require_auth parity).
CachedStmt = ref object
  name*: string              ## Server-side name (``_sc_*``)
  fields*: seq[FieldDescription] ## Describe result
  noData*: bool              ## Describe answered ``NoData``: no rows, unlike a zero-column result.
  paramOids*: seq[int32]     ## Parse-time param OIDs; mismatch → re-parse (empty = no params)
  resultFormats*: seq[int16] ## Cached buildResultFormats() output
  colFmts*: seq[int16]       ## Per-column format codes for RowData
  colOids*: seq[int32]       ## Per-column type OIDs for RowData
  lruNode*: DoublyLinkedNode[string] ## Embedded LRU list node
Cached prepared statement (LRU).
ChannelBindingMode = enum
  cbPrefer,                 ## Use SCRAM-SHA-256-PLUS when SSL and server support it (default).
  cbDisable,                ## Never use SCRAM-SHA-256-PLUS; only SCRAM-SHA-256.
  cbRequire                  ## Require SCRAM-SHA-256-PLUS; fail if unavailable.
SCRAM channel binding policy (libpq-compatible).
CleanupKind = enum
  ckTxRollback,             ## Outer ``ROLLBACK``
  ckSavepointRollback        ## ``ROLLBACK TO SAVEPOINT``
Cleanup operation kind.
CleanupSkipReason = enum
  csrConnInvalidated,       ## Already ``csClosed`` — not dispatched (``err=nil``)
  csrCleanupFailed           ## Dispatched but raised (``err`` carries failure)
Why cleanup didn't complete.
ConnConfig = object
  host*: string
  port*: int
  hostaddr*: string ## Address dialed instead of resolving `host` (libpq `hostaddr`).
                    ## `host` is still the name used for SSL certificate verification,
                    ## except `127.0.0.1` (see `effectiveHost`).
  user*: string
  password*: string ## Cleartext password (libpq ``password``), held in plaintext in memory.
                    ## DSN parse/validation errors never echo parameter values, but callers
                    ## must not log it either.
  database*: string
  sslMode*: SslMode ## SSL/TLS negotiation mode. `parseDsn` and `initConnConfig` default this
                    ## to `sslPrefer` (libpq parity); a raw zero-initialized `ConnConfig` has
                    ## `sslDisable`.
  sslNegotiation*: SslNegotiation ## SSL negotiation method (default: `sslnPostgres`). A raw zero-initialized
                                  ## `ConnConfig` matches because `sslnPostgres` is the enum's zero value,
                                  ## which is locked in by a `static:` assertion on `SslNegotiation`.
  sslRootCert*: string       ## PEM-encoded CA certificate(s) for sslVerifyCa/sslVerifyFull
  sslCert*: string ## PEM-encoded client certificate (and any intermediates) for mutual TLS.
                   ## Must be paired with ``sslKey``; ``sslMode`` must also be ``sslPrefer``
                   ## or stronger, otherwise TLS would not be negotiated and the credential
                   ## would be silently unused — config validation rejects that.
  sslKey*: string ## PEM-encoded client private key for mutual TLS. The key must be
                  ## **unencrypted** on both backends (no passphrase callback is wired up).
                  ## PKCS#8, PKCS#1 (``RSA PRIVATE KEY``) and SEC1 (``EC PRIVATE KEY``) PEM
                  ## are accepted. Must be paired with ``sslCert``.
  sslSni*: bool ## Send TLS SNI (default true; suppressed for IP/empty host). chronos
                ## ignores it: it sends SNI only under `sslVerifyFull`, where BearSSL
                ## checks the same name.
  channelBinding*: ChannelBindingMode ## SCRAM channel binding policy (default cbPrefer). `cbRequire` fails the
                                      ## connection if SCRAM-SHA-256-PLUS cannot actually be used (libpq parity).
  requireAuth*: set[AuthMethod] ## Allowed auth methods; empty = any (libpq ``require_auth`` parity).
                                ## Cleartext password and MD5 are allowed by default; set this (e.g. to
                                ## ``{amScramSha256}``) to reject them.
  applicationName*: string
  connectTimeout*: Duration ## Timeout per address a host resolves to, dial to ready (libpq
                            ## ``connect_timeout``); ``ZeroDuration`` (default, or negative) = none.
  keepAlive*: bool ## Enable TCP keepalive (default true via parseDsn). POSIX only: Windows
                   ## has no keepalive path, so this and the timing options below are ignored there.
  keepAliveIdle*: int ## Seconds before first probe (0 = OS default; at most 32767 on Linux).
                      ## POSIX only.
  keepAliveInterval*: int    ## Seconds between probes (0 = OS default; at most 32767 on Linux). POSIX only.
  keepAliveCount*: int ## Number of probes before giving up (0 = OS default; at most 127 on Linux).
                       ## POSIX only.
  hosts*: seq[HostEntry]     ## Multiple hosts for failover (empty = use host/port)
  targetSessionAttrs*: TargetSessionAttrs ## Target server type (default tsaAny)
  loadBalanceHosts*: LoadBalanceHosts ## Host ordering for multi-host connections (libpq `load_balance_hosts`);
                                      ## see `LoadBalanceHosts`. `lbhDisable` (default) preserves the configured
                                      ## order.
  extraParams*: seq[(string, string)] ## Additional StartupMessage parameters (unknown DSN keys land here).
                                      ## Forwarded verbatim; treat as trusted config — typos are not rejected.
                                      ## Exception: ``client_encoding`` is always sent as UTF8, and another
                                      ## value (also via ``-c`` in ``options``) raises ``PgConfigError``.
                                      ## Likewise ``DateStyle`` is always sent with the ISO output style, so it
                                      ## overrides a role or database one, field order included (the order from
                                      ## the server's configuration or a ``-c`` in ``options`` stays). One here
                                      ## may set only the field order (``DMY``, ...); another output style
                                      ## raises ``PgConfigError`` the same way. As startup values, both survive
                                      ## ``RESET`` and ``DISCARD ALL``; a later ``SET`` of either to a value the
                                      ## decoders cannot read closes the connection with ``PgProtocolError``.
                                      ## ``TimeZone`` is sent as UTC unless set here or via ``-c`` in
                                      ## ``options``; ``DEFAULT`` sends none, keeping the server's, database's
                                      ## or role's zone. A session asked for UTC that reports another zone (a
                                      ## proxy dropped the startup value) fails ``connect`` with
                                      ## ``PgConnectionError``. In another zone, the ``DateTime`` encoders that
                                      ## send ``timestamp`` (``toPgParam``, ``toPgBinaryParam``,
                                      ## ``toPgTimestampArrayParam``) shift by its offset when bound to
                                      ## ``timestamptz``; the ``TimestampTz`` ones do not. The ``DateTime``
                                      ## range and multirange encoders shift the same way when a ``tsrange`` or
                                      ## ``tsmultirange`` value is bound to its ``tstz`` counterpart.
  maxMessageSize*: int       ## Max backend message size (0 = 1 GiB default); larger → ``PgProtocolError``.
  maxScramIterations*: int ## Upper bound on the server-requested SCRAM iteration count
                           ## (PostgreSQL 16+ `scram_iterations`), capping CPU spent in PBKDF2.
                           ## ``0`` (default) selects `DefaultMaxScramIterations` (10,000,000).
  tracer*: PgTracer          ## Optional tracer for connection-level hooks
Connection configuration. Construct via parseDsn or set fields directly.
CopyInCallback = proc (): Future[seq[byte]] {....gcsafe.}
Callback supplying data chunks during streaming COPY IN. Return empty seq to finish.
CopyInInfo = object
  format*: CopyFormat
  columnFormats*: seq[int16]
  commandTag*: string
Metadata returned when a streaming COPY IN begins.
CopyOutCallback = proc (data: sink seq[byte]): Future[void] {....gcsafe.}
Callback receiving each chunk during streaming COPY OUT. data is sink so the receive buffer moves in without a copy.
CopyOutInfo = object
  format*: CopyFormat
  columnFormats*: seq[int16]
  commandTag*: string
Metadata returned when a streaming COPY OUT begins.
CopyResult = object
  format*: CopyFormat
  columnFormats*: seq[int16]
  data*: seq[seq[byte]]
  commandTag*: string
Result of a buffered COPY OUT operation: all rows collected in memory.
DialTarget = tuple[domain: Domain, address: string, port: Port,
                   sa: Sockaddr_storage, saLen: SockLen]
One address to dial: an IP and port, or for AF_UNIX a socket path. address is for display (zone kept); sa is what is dialed.
HostEntry = object
  host*: string ## Host name (or Unix socket dir); used for SSL verification, except
                ## `127.0.0.1` alongside a `hostaddr` (see `effectiveHost`).
  hostaddr*: string ## Address dialed instead of resolving `host` (libpq `hostaddr`).
                    ## Empty = resolve `host`.
  port*: int
A single host:port entry for multi-host connection.
ListenErrorCallback = proc (err: ref PgListenError) {....gcsafe, raises: [].}
Callback invoked when the listen pump dies permanently.
LoadBalanceHosts = enum
  lbhDisable,               ## Configured order (default)
  lbhRandom                  ## Shuffle host list per connection (replica spread)
Host ordering (libpq load_balance_hosts).
Notice = object
  fields*: seq[ErrorField]
A notice or warning message from the server (not an error).
NoticeCallback = proc (notice: Notice) {....gcsafe, raises: [].}
Callback invoked when a notice/warning message arrives.
Notification = object
  pid*: int32
  channel*: string
  payload*: string
A NOTIFY message received from PostgreSQL.
NotifyCallback = proc (notification: Notification) {....gcsafe, raises: [].}
Callback invoked when a NOTIFY message arrives.
NotifyOverflowCallback = proc (dropped: int) {....gcsafe, raises: [].}
Callback invoked when the pull-API queue overflows. dropped counts what this one arrival discarded; notifyDropped is the running count since the last overflow waitNotification reported.
PgClosedReason = enum
  crOpen,                   ## Not closed.
  crClosedByUser,           ## `close()` was called by the application.
  crClosed                   ## The connection died on its own.
Why a connection is unusable (see closedReason).
PgConnection = ref object
  when hasChronos:
  elif hasAsyncDispatch:
  when defined(pgStateChecks):
A single PostgreSQL connection with buffered I/O and statement caching.
PgConnState = enum
  csConnecting, csAuthentication, csReady, csBusy, csListening, csReplicating,
  csClosed
Connection lifecycle state.
PgPoolOwner = ref object of RootObj
Opaque base for pool-ownership back-references on PgConnection. The concrete type is PgPool (defined in pg_pool); this base lives here to avoid a circular import. Consumers should not subclass this.
PgTracer = ref object
  onConnectStart*: proc (data: TraceConnectStartData): TraceContext {....gcsafe,
      raises: [].}
  onConnectEnd*: proc (ctx: TraceContext; data: TraceConnectEndData) {....gcsafe,
      raises: [].}
  onQueryStart*: proc (conn: PgConnection; data: TraceQueryStartData): TraceContext {.
      ...gcsafe, raises: [].}
  onQueryEnd*: proc (ctx: TraceContext; conn: PgConnection;
                     data: TraceQueryEndData) {....gcsafe, raises: [].}
  onPrepareStart*: proc (conn: PgConnection; data: TracePrepareStartData): TraceContext {.
      ...gcsafe, raises: [].}
  onPrepareEnd*: proc (ctx: TraceContext; conn: PgConnection;
                       data: TracePrepareEndData) {....gcsafe, raises: [].}
  onPipelineStart*: proc (conn: PgConnection; data: TracePipelineStartData): TraceContext {.
      ...gcsafe, raises: [].}
  onPipelineEnd*: proc (ctx: TraceContext; conn: PgConnection;
                        data: TracePipelineEndData) {....gcsafe, raises: [].}
  onCopyStart*: proc (conn: PgConnection; data: TraceCopyStartData): TraceContext {.
      ...gcsafe, raises: [].}
  onCopyEnd*: proc (ctx: TraceContext; conn: PgConnection;
                    data: TraceCopyEndData) {....gcsafe, raises: [].}
  onPoolAcquireStart*: proc (data: TracePoolAcquireStartData): TraceContext {.
      ...gcsafe, raises: [].}
  onPoolAcquireEnd*: proc (ctx: TraceContext; data: TracePoolAcquireEndData) {.
      ...gcsafe, raises: [].}
  onPoolReleaseStart*: proc (data: TracePoolReleaseStartData): TraceContext {.
      ...gcsafe, raises: [].}
  onPoolReleaseEnd*: proc (ctx: TraceContext; data: TracePoolReleaseEndData) {.
      ...gcsafe, raises: [].}
  onPoolDoubleRelease*: proc (data: TracePoolDoubleReleaseData) {....gcsafe,
      raises: [].}           ## Duplicate release (no-op).
  onPoolCloseError*: proc (data: TracePoolCloseErrorData) {....gcsafe, raises: [].}
  onTransportCloseError*: proc (data: TraceTransportCloseErrorData) {....gcsafe,
      raises: [].}           ## Swallowed ``closeWait`` error.
  onLeakedSessionLocks*: proc (data: TraceLeakedSessionLocksData) {....gcsafe,
      raises: [].}           ## Leaked advisory locks on pool return.
  onCleanupSkipped*: proc (data: TraceCleanupSkippedData) {....gcsafe, raises: [].} ## Skipped/failed ROLLBACK (may fire twice when nested).
  onInsecureAuth*: proc (data: TraceInsecureAuthData) {....gcsafe, raises: [].} ## Cleartext password sent over plaintext. Fires only for a request the
                                                                             ## client answers, after the order and require_auth checks.
  onDeprecatedAuth*: proc (data: TraceDeprecatedAuthData) {....gcsafe, raises: [].} ## MD5 password sent. Fires only for a request the client answers, after
                                                                                 ## the order and require_auth checks.
  onAdvisoryUnlockFailed*: proc (data: TraceAdvisoryUnlockFailedData) {....gcsafe,
      raises: [].}           ## Swallowed unlock failure.
Tracing hooks (nil = skipped; Start → TraceContext → End).
QueryResult = object
  fields*: seq[FieldDescription]
  data*: RowData
  rowCount*: int32
  commandTag*: string
Result of a query: field descriptions, row data, and command tag. data is nil only when the statement returned no rows, so rowCount > 0 implies data != nil.
ReconnectCallback = proc () {....gcsafe, raises: [].}
Callback invoked after the listen pump reconnects and re-subscribes.
ReplWrite = ref object
  frame*: seq[byte]          ## Encoded frame; empty for the library's status.
  waiters*: seq[Future[void]] ## Completed once written, failed if not.
  state*: ReplWriteState
A queued replication write (internal; see pg_replication).
ReplWriteState = enum
  rwQueued,                 ## Waiting in the queue.
  rwWriting,                ## Taken off the queue; a library status is encoded by then.
  rwWritten, rwFailed        ## Not written, whether it had started or not.
Lifecycle of a queued replication write (internal).
RowCallback = proc (row: Row) {....raises: [CatchableError], gcsafe.}
Callback invoked once per row during queryEach. The Row is only valid inside the callback — its backing buffer is reused for the next row.
SslMode = enum
  sslDisable,               ## Disable SSL
  sslAllow,                 ## Try plaintext; fall back to SSL if refused
  sslPrefer,                ## Try SSL; fall back to plaintext if refused (libpq default)
  sslRequire,               ## Require SSL (no certificate verification)
  sslVerifyCa,              ## Require SSL + verify CA chain (no hostname verification)
  sslVerifyFull              ## Require SSL + verify CA chain and hostname
SSL mode. Zero value is sslDisable (raw ConnConfig); parseDsn/ initConnConfig default to sslPrefer (libpq parity). Backend divergence: chronos/BearSSL also rejects expired certificates when sslAllow/sslPrefer/sslRequire negotiate TLS, and refuses IP-literal hosts under sslVerifyFull; full list in the async_postgres module doc ("Async Backend").
SslNegotiation = enum
  sslnPostgres,             ## Traditional SSLRequest negotiation (default)
  sslnDirect                 ## Direct SSL: start TLS immediately without SSLRequest (PostgreSQL 17+)
SSL negotiation method for the connection.
TargetSessionAttrs = enum
  tsaAny,                   ## Connect to any server (default)
  tsaReadWrite,             ## Read-write server (primary)
  tsaReadOnly,              ## Read-only server (standby)
  tsaPrimary,               ## Primary server
  tsaStandby,               ## Standby server
  tsaPreferStandby           ## Prefer standby, fall back to any
Target server type for multi-host failover (libpq compatible).
TraceAdvisoryUnlockFailedData = object
  conn*: PgConnection
  key*: int64                ## Single-key id (0 if ``twoKey``)
  key1*: int32               ## First key (two-key only)
  key2*: int32               ## Second key (two-key only)
  shared*: bool              ## Shared lock?
  twoKey*: bool              ## Two-key variant?
  err*: ref CatchableError ## Nil = unlock returned false (not held). An unlock `Defect` arrives
                           ## wrapped in `PgError` (`parent` = the Defect).
Swallowed unlock-failure advisory.
TraceCleanupSkippedData = object
  conn*: PgConnection
  kind*: CleanupKind
  reason*: CleanupSkipReason
  err*: ref CatchableError
ROLLBACK skipped/failed advisory (advisory only).
TraceConnectEndData = object
  conn*: PgConnection
  err*: ref CatchableError
Data passed to the connect end hook.
TraceConnectStartData = object
  hosts*: seq[HostEntry]
Data passed to the connect start hook.
TraceContext = RootRef
Opaque correlation token returned by trace Start hooks and passed to End hooks. Users subtype RootObj (e.g. type Span = ref object of RootObj) and return it from Start hooks; End hooks downcast via Span(ctx).
TraceCopyDirection = enum
  tcdIn, tcdOut
TraceCopyEndData = object
  commandTag*: string
  err*: ref CatchableError
Data passed to the copy end hook.
TraceCopyStartData = object
  sql*: string
  direction*: TraceCopyDirection
Data passed to the copy start hook.
TraceDeprecatedAuthData = object
  conn*: PgConnection
  authMethod*: AuthMethod    ## The method the server requested
Advisory notification that a server-requested auth method is considered cryptographically weak / deprecated regardless of transport. Currently fires for MD5 (PostgreSQL recommends SCRAM-SHA-256 since v10). The connection is NOT aborted — use ConnConfig.requireAuth for actual enforcement.
TraceInsecureAuthData = object
  conn*: PgConnection
  authMethod*: AuthMethod    ## The method the server requested
  sslEnabled*: bool          ## Transport state at the time of the auth step
Advisory notification that a server-requested auth method is considered insecure in the current transport context. Currently fires for cleartext password over a non-SSL connection. The connection is NOT aborted — use ConnConfig.requireAuth for actual enforcement.
TraceLeakedSessionLocksData = object
  conn*: PgConnection
  count*: int                ## ``heldSessionLocks`` at detection (0 = counter unreliable).
Leaked advisory-lock advisory (fires on sessionLockDirty).
TracePipelineEndData = object
  err*: ref CatchableError
Data passed to the pipeline end hook.
TracePipelineStartData = object
  opCount*: int
Data passed to the pipeline start hook.
TracePoolAcquireEndData = object
  conn*: PgConnection
  err*: ref CatchableError
  wasCreated*: bool          ## true if a new connection was created
Data passed to the pool acquire end hook.
TracePoolAcquireStartData = object
  idleCount*: int            ## `PgPool.idleCount()` as this acquire starts
  activeCount*: int ## `PgPool.activeCount()` as this acquire starts, so not counting it:
                    ## slots in use, not only borrowers
  maxSize*: int              ## `PoolConfig.maxSize`
Data passed to the pool acquire start hook.
TracePoolCloseErrorData = object
  conn*: PgConnection
  err*: ref CatchableError
Data passed to the pool close-error hook. Fired when a pool-initiated conn.close() raises — these errors are otherwise swallowed because close runs from non-async cleanup paths and fire-and-forget tasks, making leaks hard to observe without tracing.
TracePoolDoubleReleaseData = object
  conn*: PgConnection
Double-release hook data (no-op release).
TracePoolReleaseEndData = object
  wasClosed*: bool           ## true if connection was closed instead of returned to pool
  handedToWaiter*: bool      ## true if connection was given directly to a waiting acquirer
Data passed to the pool release end hook.
TracePoolReleaseStartData = object
  conn*: PgConnection
Data passed to the pool release start hook.
TracePrepareEndData = object
  err*: ref CatchableError
Data passed to the prepare end hook.
TracePrepareStartData = object
  name*: string
  sql*: string
Data passed to the prepare start hook.
TraceQueryEndData = object
  commandTag*: string
  rowCount*: int64
  err*: ref CatchableError
Data passed to the query/exec end hook.
TraceQueryStartData = object
  sql*: string
  params*: seq[PgParam] ## Populated when the caller used a `seq[PgParam]` overload. Mutually
                        ## exclusive with `paramsInline`: exactly one of the two is non-empty
                        ## per call (or both are empty if the query has no bound parameters).
  paramsInline*: seq[PgParamInline] ## Populated when the caller used a `PgParamInline` overload. Mutually
                                    ## exclusive with `params` (see above). Tracers that want a single view
                                    ## should branch on whichever field is non-empty.
  isExec*: bool              ## true for exec, false for query
Data passed to the query/exec start hook.
TraceTransportCloseErrorData = object
  conn*: PgConnection
  stage*: TransportCloseStage
  err*: ref CatchableError
Transport close-error hook data.
TransportCloseStage = enum
  tcsTlsReader, tcsTlsWriter, tcsBaseReader, tcsBaseWriter, tcsTransport
Which transport resource raised during connection teardown.

Vars

listenBackoffUnitMs = 1000
One listen-reconnect backoff step (ms), the unit listenReconnectMaxBackoff counts in. Tests shrink it; not re-exported through pg_connection.
listenReconnectStopWaitMs = 10000
Max wait (ms) for a listen pump stuck in a blocking connect(); it is orphaned on timeout. Not re-exported through pg_connection, so call sites cannot set it to 0 via the aggregate import and disable orphan safety.
TCP_KEEPCNT {.importc, header: "<netinet/tcp.h>".}: cint
TCP_KEEPIDLE {.importc, header: "<netinet/tcp.h>".}: cint
TCP_KEEPINTVL {.importc, header: "<netinet/tcp.h>".}: cint

Consts

ClientCertPairingErrorMsg = "sslcert and sslkey must be provided together for client certificate auth"
Shared so the wording can't drift between the config-time and connect-time checks.
closedByUserMsg = "Connection closed by the application"
Shared by failNotifyWaiter and checkListenAlive so a deliberate close() reports the same thing whether a waiter was parked or not.
DefaultHost = "127.0.0.1"
Target when neither host nor hostaddr is given.
DefaultNotifyMaxQueue = 1024
Connect-time pull-API count cap.
DefaultNotifyMaxQueueBytes = 16777216
Connect-time pull-API byte cap. 1024 × (channel + ≤8000-byte payload) fits with headroom.
ForkFailureText = "could not fork new process for connection: "
Start of the postmaster's error when it cannot fork a backend (untranslated).
RecvBufSize = 131072
Size of the temporary read buffer for recv operations
ServerCertUnavailable = "server certificate is unavailable"
Reason given when TLS setup recorded no cause for a missing certificate.
stmtNamePrefix = "_sc_"
Reserved for the cache's names: prepare rejects a name that starts with it.

Procs

proc addBind(conn: PgConnection; portalName: string; stmtName: string;
             paramFormats: openArray[int16];
             paramValues: openArray[Option[seq[byte]]];
             resultFormats: openArray[int16] = []) {.inline,
    ...raises: [PgTypeError, PgProtocolError], tags: [], forbids: [].}
Append a Bind message to the send buffer.
proc addBind(conn: PgConnection; portalName: string; stmtName: string;
             params: openArray[PgParam]; resultFormats: openArray[int16] = []) {.
    inline, ...raises: [PgTypeError, PgProtocolError], tags: [], forbids: [].}
Append a Bind message to the send buffer, writing straight out of params instead of flattening them into values and formats.
proc addBindRaw(conn: PgConnection; portalName: string; stmtName: string;
                paramFormats: openArray[int16]; paramData: openArray[byte];
                paramRanges: openArray[tuple[off: int32, len: int32]];
                resultFormats: openArray[int16] = []) {.inline,
    ...raises: [PgTypeError, PgProtocolError], tags: [], forbids: [].}
Append a Bind message built from raw parameter bytes and ranges.
proc addClose(conn: PgConnection; kind: DescribeKind; name: string) {.inline,
    ...raises: [PgTypeError, PgProtocolError], tags: [], forbids: [].}
Append a Close message to the send buffer.
proc addDescribe(conn: PgConnection; kind: DescribeKind; name: string) {.inline,
    ...raises: [PgTypeError, PgProtocolError], tags: [], forbids: [].}
Append a Describe message to the send buffer.
proc addExecute(conn: PgConnection; portalName: string; maxRows: int32 = 0) {.
    inline, ...raises: [PgTypeError, PgProtocolError], tags: [], forbids: [].}
Append an Execute message to the send buffer.
proc addFlush(conn: PgConnection) {.inline, ...raises: [PgProtocolError], tags: [],
                                    forbids: [].}
Append a Flush message to the send buffer.
proc addParse(conn: PgConnection; stmtName: string; sql: string;
              params: openArray[PgParam]) {.inline,
    ...raises: [PgTypeError, PgProtocolError], tags: [], forbids: [].}
Append a Parse message to the send buffer, taking the parameter OIDs from params without reshaping them into a seq[int32].
proc addParse(conn: PgConnection; stmtName: string; sql: string;
              paramTypeOids: openArray[int32] = []) {.inline,
    ...raises: [PgTypeError, PgProtocolError], tags: [], forbids: [].}
Append a Parse message to the send buffer.
proc addStmtCache(conn: PgConnection; sql: string; cached: CachedStmt) {.
    ...raises: [], tags: [], forbids: [].}

Add a prepared statement to the cache with auto-computed result formats. Single-statement callers pre-evict (evictForInsert) so the Close rides along. A pipeline would have to Close mid-batch, where a failing op gets it skipped, so it leaves eviction to the loop below, which queues the names for the next Extended Query send.

Every name handed in ends up cached or queued for Close: a statement the cache cannot keep (caching turned off while it was in flight) or an entry it replaces is closed, not forgotten.

proc addSync(conn: PgConnection) {.inline, ...raises: [PgProtocolError], tags: [],
                                   forbids: [].}
Append a Sync message to the send buffer.
proc adoptRecvBuf(conn, other: PgConnection) {....raises: [], tags: [], forbids: [].}
Take over other's buffered bytes and read pointer. For an in-place reconnect, which grafts the fresh connection's wire state onto the old record; the two fields must move as a pair or the pointer describes the wrong buffer.
proc appendCopyData(conn: PgConnection; data: openArray[byte]) {.inline,
    ...raises: [PgTypeError, PgProtocolError], tags: [], forbids: [].}
Append one CopyData frame to the send buffer.
proc appendCopyDone(conn: PgConnection) {.inline, ...raises: [PgProtocolError],
    tags: [], forbids: [].}
proc attachTransport(conn: PgConnection; s: AsyncSocket; target: DialTarget;
                     sslHost: string) {.inline, ...raises: [], tags: [],
                                        forbids: [].}
Attach a freshly dialled socket with what cancel needs to reach the same server: its address and TLS name.
proc beginSendBuf(conn: PgConnection) {....raises: [PgTypeError, PgProtocolError],
                                        tags: [], forbids: [].}
Start a new operation's send buffer: empty it, then stage the queued Close messages into it. The order matters: staging first would be truncated by the emptying.
proc borrowed(conn: PgConnection): var bool {.inline, ...raises: [], tags: [],
    forbids: [].}
proc borrowedByUser(conn: PgConnection): var bool {.inline, ...raises: [],
    tags: [], forbids: [].}
func cancelTarget(conn: PgConnection): lent seq[DialTarget] {.inline,
    ...raises: [], tags: [], forbids: [].}
proc checkNotClosed(conn: PgConnection) {.inline,
    ...raises: [PgStateError, PgConnectionError], tags: [], forbids: [].}
Reject if closed: PgStateError for deliberate close(), else PgConnectionError.
proc clearListenStop(conn: PgConnection) {.inline, ...raises: [], tags: [],
    forbids: [].}
proc clearListenTask(conn: PgConnection) {.inline, ...raises: [], tags: [],
    forbids: [].}
Forget the pump task without touching the stop flag.
proc clearSendBuf(conn: PgConnection) {.inline, ...raises: [], tags: [],
                                        forbids: [].}
Empty the send buffer without touching staged statement Closes.
proc clearSessionLocks(conn: PgConnection) {.inline, ...raises: [], tags: [],
    forbids: [].}
Forget session-lock tracking for a fresh or reset session.
proc clearStaged(conn: PgConnection) {.inline, ...raises: [], tags: [], forbids: [].}

The staged bytes went out and their names have been forgotten.

Only the drop disarms; abandoning the queue (clearStmtCache) leaves it armed, so a later drop still finds an empty staged list rather than tripping this guard.

proc clearStmtCache(conn: PgConnection) {....raises: [], tags: [], forbids: [].}
Forget every cached statement and owed Close: the session no longer holds them. A miss Parsed before this settles as gone (stmtCacheResetGen).
proc clearWireDebt(conn: PgConnection) {.inline, ...raises: [], tags: [],
    forbids: [].}
Forget which replies the previous frame was waiting for, without touching the buffers. For a frame that takes over a half-read wire — it is the reply count a CancelRequest must abort, and only the first frame to claim it may dial.
proc closedByUser(conn: PgConnection): var bool {.inline, ...raises: [], tags: [],
    forbids: [].}
func closedReason(conn: PgConnection): PgClosedReason {.inline, ...raises: [],
    tags: [], forbids: [].}
Why unusable (crClosedByUser outranks crClosed).
proc closeReplWrites(conn: PgConnection) {....raises: [Exception],
    tags: [RootEffect], forbids: [].}
The stream is ending: accept no more writes and fail those not started.
proc compactRecvBuf(conn: PgConnection) {....raises: [], tags: [], forbids: [].}
Move the unparsed bytes to the front, freeing the space already parsed. Only safe before reading new data from the socket: it moves bytes an in-flight read still points at.
func config(conn: PgConnection): lent ConnConfig {.inline, ...raises: [], tags: [],
    forbids: [].}
proc confirmReplFlushed(conn: PgConnection; lsn: uint64): bool {....raises: [],
    tags: [], forbids: [].}
Clamp to max-received and advance flush monotonically (raw helper).
proc confirmReplReportable(conn: PgConnection; lsn: uint64): bool {....raises: [],
    tags: [], forbids: [].}
confirmReplFlushed while the position can still reach the server.
func connectTimeZone(conn: PgConnection): string {.inline, ...raises: [], tags: [],
    forbids: [].}
proc consumeRecv(conn: PgConnection; count: int) {.inline, ...raises: [], tags: [],
    forbids: [].}
Mark count unparsed bytes parsed. Callers pass what one parse consumed; nothing may be skipped without being parsed.
proc copyServerError(se: ref PgQueryError): ref PgQueryError {....raises: [],
    tags: [], forbids: [].}
se's own copy for one error, nil for nil. A ref shared between errors would pile every raise's stack trace onto each of them.
func createdAt(conn: PgConnection): Moment {.inline, ...raises: [], tags: [],
    forbids: [].}
When the connection was established.
proc createdAt=(conn: PgConnection; value: Moment) {.inline, ...raises: [],
    tags: [], forbids: [].}
proc detachTransport(conn: PgConnection): AsyncSocket {.inline, ...raises: [],
    tags: [], forbids: [].}
Detach the socket for the caller to close.
func dialAddr(entry: HostEntry): string {.inline, ...raises: [], tags: [],
    forbids: [].}
The address actually dialed: hostaddr when given, otherwise host. Unlike libpq, a name in hostaddr is resolved rather than rejected.
proc dispatchNotice(conn: PgConnection; msg: BackendMessage) {....raises: [],
    tags: [RootEffect], forbids: [].}
proc dispatchNotification(conn: PgConnection; msg: BackendMessage) {....raises: [],
    tags: [RootEffect], forbids: [].}
func displayHost(entry: HostEntry): string {.inline, ...raises: [], tags: [],
    forbids: [].}
Host name for display and back-compat scalars: host, falling back to hostaddr (mirrors libpq's PQhost()).
proc dropStagedStmtCloses(conn: PgConnection) {....raises: [], tags: [],
    forbids: [].}
Forget the names whose Close is now on the wire. Names queued since the staging are in pendingStmtCloses and untouched by this.
func effectiveHost(entry: HostEntry): string {.inline, ...raises: [], tags: [],
    forbids: [].}
host as the name to verify. With a hostaddr, 127.0.0.1 is dropped: it may be the default left behind when hostaddr is set later, and an explicit one looks the same.
func effectiveMaxMessageSize(conn: PgConnection): int {.inline, ...raises: [],
    tags: [], forbids: [].}
Effective per-message recv cap for this connection. Resolves the ConnConfig.maxMessageSize default (0) to DefaultMaxBackendMessageLen.
func effectiveMaxScramIterations(config: ConnConfig): int {.inline, ...raises: [],
    tags: [], forbids: [].}
Resolves the ConnConfig.maxScramIterations default (0) to DefaultMaxScramIterations.
proc enqueueNotification(conn: PgConnection; notif: Notification) {....raises: [],
    tags: [RootEffect], forbids: [].}
Enqueue under notifyMaxQueue and notifyMaxQueueBytes (either <=0 = unbounded). Overflow drops oldest; oversize is not queued. Push onNotify still sees every arrival.
func errorSeverity(fields: seq[ErrorField]): string {....raises: [], tags: [],
    forbids: [].}
Severity of an ErrorResponse: 'V' (PG 9.6+) is never localized; 'S' may be.
proc evictForInsert(conn: PgConnection) {.inline,
    ...raises: [PgTypeError, PgProtocolError], tags: [], forbids: [].}
Make room for one more cache entry, staging the evicted Close into the connection's own send buffer.
proc evictForInsert(conn: PgConnection; buf: var seq[byte]) {.
    ...raises: [PgTypeError, PgProtocolError], tags: [], forbids: [].}
Make room for one more cache entry, staging the evicted Close into buf (the buffer this operation assembles).
proc evictStmtCache(conn: PgConnection): CachedStmt {....raises: [], tags: [],
    forbids: [].}
Evict the least recently used entry from the cache. Returns the evicted entry, or nil once the LRU list runs out.
proc failNotifyWaiter(conn: PgConnection; err: ref PgError = nil) {....raises: [],
    tags: [RootEffect], forbids: [].}
Fail parked waiter: closedByUser→PgStateError, else err/csClosed/stopped. Pass fresh err.
proc failQueuedReplWrites(conn: PgConnection) {....raises: [Exception],
    tags: [RootEffect], forbids: [].}
Fail every write not yet started. The one being written settles itself.
proc fatalServerError(conn: PgConnection): var ref PgQueryError {.inline,
    ...raises: [], tags: [], forbids: [].}
proc fillRecvBuf(conn: PgConnection; timeout: Duration = ZeroDuration): Future[
    void] {....stackTrace: false, raises: [Exception, PgStateError,
                                        PgConnectionError, AsyncTimeoutError,
                                        CancelledError, CatchableError],
            tags: [RootEffect, TimeEffect], forbids: [].}
Read into recvBuf. AsyncTimeoutError: caller handles state; other errors → csClosed + raiseTransportFailure.
proc fireAdvisoryUnlockFailed(conn: PgConnection; key: int64; key1, key2: int32;
                              shared, twoKey: bool; err: ref CatchableError) {.
    ...raises: [], tags: [RootEffect], forbids: [].}
Route a swallowed withAdvisoryLock* / withAdvisoryLockShared* unlock failure to the tracer. Reads from conn.config.tracer so the event fires regardless of the runtime conn.tracer alias. Nil hook is a no-op.
proc fireCleanupDefect(conn: PgConnection; kind: CleanupKind; d: ref Defect) {.
    ...raises: [], tags: [RootEffect], forbids: [].}
Swallow a same-frame Defect from a ROLLBACK cleanup so it can't replace the error being re-raised. The wire state is unknown, so the connection is retired; the Defect is reported as the parent of a PgError.
proc fireCleanupSkipped(conn: PgConnection; kind: CleanupKind;
                        reason: CleanupSkipReason; err: ref CatchableError = nil) {.
    ...raises: [], tags: [RootEffect], forbids: [].}
Route a withTransaction* / withSavepoint* ROLLBACK skip-or-swallow event to the tracer. Reads from conn.config.tracer so events fire regardless of the runtime conn.tracer alias. Nil hook is a no-op.
proc fireDeprecatedAuth(conn: PgConnection; authMethod: AuthMethod) {.
    ...raises: [], tags: [RootEffect], forbids: [].}
proc fireInsecureAuth(conn: PgConnection; authMethod: AuthMethod) {....raises: [],
    tags: [RootEffect], forbids: [].}
proc graftReconnectedSession(conn, src: PgConnection) {....raises: [], tags: [],
    forbids: [].}
Move a fresh connection's wire and session identity onto conn for an in-place reconnect. The caller owns state, the statement cache, session locks and the fatal error around it.
proc graftTransportFrom(conn, src: PgConnection) {.inline, ...raises: [], tags: [],
    forbids: [].}
Move the socket and its channel-binding certificate.
func hasNotification(conn: PgConnection): bool {.inline, ...raises: [], tags: [],
    forbids: [].}
Whether the pull-API queue holds a notification (handoff slot excluded).
func hasNotifyWaiter(conn: PgConnection): bool {.inline, ...raises: [], tags: [],
    forbids: [].}
Whether a waitNotification is parked.
func heldSessionLocks(conn: PgConnection): int {.inline, ...raises: [], tags: [],
    forbids: [].}
func host(conn: PgConnection): lent string {.inline, ...raises: [], tags: [],
    forbids: [].}
proc host=(conn: PgConnection; value: string) {.inline, ...raises: [], tags: [],
    forbids: [].}
proc initReplLsnTracking(conn: PgConnection; startLsn: uint64) {....raises: [],
    tags: [], forbids: [].}
Reset per-stream LSN tracking to startLsn.
proc invalidateAllStmtCache(conn: PgConnection; sql, stmtName: string) {.
    ...raises: [], tags: [], forbids: [].}
Drop every entry and queue its Close: a hit's statement vanished with no reset tag seen, so the rest likely went with it. A Close for a name already gone is a backend no-op. A no-op once sql no longer maps to stmtName, as in invalidateStmtCache.
proc invalidateStmtCache(conn: PgConnection; sql, stmtName: string) {.
    ...raises: [], tags: [], forbids: [].}
Drop a cache entry the server invalidated and queue its Close together. A no-op once sql no longer maps to stmtName: whatever dropped that entry already queued its Close.
proc isGucName(key, name: string): bool {....raises: [], tags: [], forbids: [].}
GUC names are case-insensitive.
proc isUtcZoneName(val: string): bool {....raises: [], tags: [], forbids: [].}
Whether val names a zone fixed at UTC+0, in any case and under the spellings the server accepts and reports: the tzdata links (UTC, Etc/UTC, GMT0, Greenwich, ...), POSIX forms of those with a zero offset (UTC0, GMT+00:00, ...), a bare zero offset (0, +00, 0.0) and the synthetic bracketed name of a numeric zone (<+00>-00). Any non-zero offset fails, so Etc/GMT+1, GMT+00:01 and <+09>-09 are not UTC.
proc isUtf8EncodingName(val: string): bool {....raises: [], tags: [], forbids: [].}
Whether val is one of the server's spellings of UTF8 (pg_char_to_encoding ignores case and punctuation).
proc listenChannels(conn: PgConnection): var HashSet[string] {.inline,
    ...raises: [], tags: [], forbids: [].}
func listenError(conn: PgConnection): ref PgListenError {.inline, ...raises: [],
    tags: [], forbids: [].}
Why the listen pump died permanently, or nil while it is alive.
proc listenError=(conn: PgConnection; value: ref PgListenError) {.inline,
    ...raises: [], tags: [], forbids: [].}
proc listenErrorCallback(conn: PgConnection): var ListenErrorCallback {.inline,
    ...raises: [], tags: [], forbids: [].}
func listenReconnecting(conn: PgConnection): bool {.inline, ...raises: [],
    tags: [], forbids: [].}
func listenReconnectMaxAttempts(conn: PgConnection): int {.inline, ...raises: [],
    tags: [], forbids: [].}
Reconnect attempt budget; see listenReconnectMaxAttempts=.
proc listenReconnectMaxAttempts=(conn: PgConnection; value: int) {.inline,
    ...raises: [], tags: [], forbids: [].}
Max reconnect attempts on listen-pump failure (10 default; <=0 = retry until close). A refusal — a wrong password, say — or a config fault ends the pump at once, whatever the budget left.
func listenReconnectMaxBackoff(conn: PgConnection): int {.inline, ...raises: [],
    tags: [], forbids: [].}
Backoff cap in seconds; see listenReconnectMaxBackoff=.
proc listenReconnectMaxBackoff=(conn: PgConnection; value: int) {.inline,
    ...raises: [], tags: [], forbids: [].}
Cap the seconds between listen-pump reconnect attempts (30 default).
func listenStopRequested(conn: PgConnection): bool {.inline, ...raises: [],
    tags: [], forbids: [].}
func listenTask(conn: PgConnection): Future[void] {.inline, ...raises: [],
    tags: [], forbids: [].}
proc lookupStmtCache(conn: PgConnection; sql: string): CachedStmt {....raises: [],
    tags: [], forbids: [].}
Look up a cached prepared statement by SQL text, updating LRU order on hit. Returns nil on miss. The returned ref stays valid across later mutations.
proc markBusy(conn: PgConnection) {.inline, ...raises: [], tags: [], forbids: [].}
Take the wire for one operation. Held until that operation reads its last reply (markReady) or dies on the wire (markClosed).
proc markClosed(conn: PgConnection) {.inline, ...raises: [], tags: [], forbids: [].}
Retire the connection: the wire is unusable, whether the transport is torn down yet or not.
proc markReady(conn: PgConnection) {.inline, ...raises: [], tags: [], forbids: [].}
Give the connection back: no operation owns the wire any more. See checkBorrowable for what the next borrower assumes.
proc markStaged(conn: PgConnection) {.inline, ...raises: [], tags: [], forbids: [].}
A build staged its queued Close messages into the bytes about to go out.
proc markState(conn: PgConnection; next: PgConnState) {.inline, ...raises: [],
    tags: [], forbids: [].}
Sole writer of state, the field every reuse decision reads. Use markReady / markBusy / markClosed for the query path; this one is for the states a single owner drives (csConnecting, csAuthentication, csListening, csReplicating).
proc namesNonIsoDateStyle(val: string): bool {....raises: [], tags: [], forbids: [].}
Whether a DateStyle value picks an output style other than ISO. DEFAULT counts: it is the server's, possibly non-ISO. The server takes any token starting with postgres as that style.
proc newClosedError(conn: PgConnection; msg: string; parent: ref Exception = nil): ref PgConnectionError {.
    ...raises: [], tags: [], forbids: [].}
proc newPgConnection(host: string; port: int; config: ConnConfig): PgConnection {.
    ...raises: [], tags: [], forbids: [].}
A csConnecting record with the default tunables, before the caller attaches its transport.
proc newPgQueryError(fields: seq[ErrorField]): ref PgQueryError {....raises: [],
    tags: [], forbids: [].}
Create a PgQueryError from server ErrorResponse fields.
proc nextPortalName(conn: PgConnection; prefix: string): string {....raises: [],
    tags: [], forbids: [].}
Fresh portal/savepoint name; owns counter so macro scope stays sealed.
proc nextReplWrite(conn: PgConnection): ReplWrite {....raises: [], tags: [],
    forbids: [].}
The queue in order, then the stop's final status and CopyDone, so nothing queued before the final status is encoded can land after CopyDone. Taking the library's status off the queue retires its pending mark, so the next one queued is a fresh entry.
proc nextStmtName(conn: PgConnection): string {....raises: [], tags: [],
    forbids: [].}
Generate the next unique prepared statement name for the statement cache.
proc noteBackendKeyData(conn: PgConnection; pid, secret: int32) {.inline,
    ...raises: [], tags: [], forbids: [].}
Record BackendKeyData: the pid and secret move together for cancel.
proc noteCommandTag(conn: PgConnection; tag: string) {....raises: [], tags: [],
    forbids: [].}
Drop the cache once the session's prepared statements are gone. A run inside a function sends no such tag; the next cache hit's 26000 catches that (see retryStmtCacheInvalidation).
proc noteConnectTimeZone(conn: PgConnection; followsServer: bool) {.inline,
    ...raises: [], tags: [], forbids: [].}
Take the reported TimeZone as the one the pool restores, and how.
proc noteListenPumpStarted(conn: PgConnection; task: Future[void]) {.inline,
    ...raises: [], tags: [], forbids: [].}
Adopt task as the pump and clear any previous stop/reconnect state.
proc noteNegotiatedProtocol(conn: PgConnection; minor: int32; opts: seq[string]) {.
    inline, ...raises: [], tags: [], forbids: [].}
Record a NegotiateProtocolVersion reply; the two fields arrive together.
proc noteReplReported(conn: PgConnection; receive, flush, apply: uint64) {.
    ...raises: [], tags: [], forbids: [].}
Record the positions a caller's Standby Status Update just sent. The latest report wins, so a caller may deliberately report lower.
proc noteReplSentFlush(conn: PgConnection; flush: uint64) {.inline, ...raises: [],
    tags: [], forbids: [].}
Record the flush position the library's status is about to send.
proc noteReplWriteFailure(conn: PgConnection; e: ref CatchableError) {.inline,
    ...raises: [], tags: [], forbids: [].}
Latch the write failure that ended the stream.
proc noteSessionLockAcquired(conn: PgConnection) {.inline, ...raises: [], tags: [],
    forbids: [].}
Track one session-level acquire; the sticky flag outlives the counter.
proc noteSessionLockReleased(conn: PgConnection; released: bool) {.inline,
    ...raises: [], tags: [], forbids: [].}
Track a server-confirmed release, clamping at zero for mixed raw/typed use.
proc noteWrite(conn: PgConnection; data: openArray[byte]) {.inline, ...raises: [],
    tags: [], forbids: [].}
Book what these bytes leave the backend owing. Before the write, not after: a failed or cancelled write may still have reached the wire, and a CancelRequest at an idle backend is a harmless no-op.
proc noticeCallback(conn: PgConnection): var NoticeCallback {.inline,
    ...raises: [], tags: [], forbids: [].}
proc notifyCallback(conn: PgConnection): var NotifyCallback {.inline,
    ...raises: [], tags: [], forbids: [].}
func notifyDropped(conn: PgConnection): int {.inline, ...raises: [], tags: [],
    forbids: [].}
Notifications dropped by pull-API queue overflow since the last PgNotifyOverflowError. Not a lifetime total: waitNotification reports the count in that error and resets it to zero.
proc notifyDropped=(conn: PgConnection; value: int) {.inline, ...raises: [],
    tags: [], forbids: [].}
func notifyMaxQueue(conn: PgConnection): int {.inline, ...raises: [], tags: [],
    forbids: [].}
Pull-API count cap; see notifyMaxQueue=.
proc notifyMaxQueue=(conn: PgConnection; value: int) {.inline, ...raises: [],
    tags: [], forbids: [].}
Cap the pull-API queue by count (1024 default; <=0 = unbounded count). Overflow drops the oldest entry and fires onNotifyOverflow.
func notifyMaxQueueBytes(conn: PgConnection): int {.inline, ...raises: [],
    tags: [], forbids: [].}
Pull-API byte cap; see notifyMaxQueueBytes=.
proc notifyMaxQueueBytes=(conn: PgConnection; value: int) {.inline, ...raises: [],
    tags: [], forbids: [].}
Cap queued channel.len + payload.len (16 MiB default; <=0 = unbounded). Overflow drops oldest; a notification larger than the cap is not queued.
proc notifyOverflowCallback(conn: PgConnection): var NotifyOverflowCallback {.
    inline, ...raises: [], tags: [], forbids: [].}
proc ownerPool(conn: PgConnection): var PgPoolOwner {.inline, ...raises: [],
    tags: [], forbids: [].}
func pid(conn: PgConnection): int32 {.inline, ...raises: [], tags: [], forbids: [].}
Backend process id from BackendKeyData; 0 until startup completes.
proc pid=(conn: PgConnection; value: int32) {.inline, ...raises: [], tags: [],
    forbids: [].}
proc popNotification(conn: PgConnection): Notification {.inline, ...raises: [],
    tags: [], forbids: [].}
Take the oldest queued notification; caller checks hasNotification.
func port(conn: PgConnection): int {.inline, ...raises: [], tags: [], forbids: [].}
Port this connection actually reached.
proc port=(conn: PgConnection; value: int) {.inline, ...raises: [], tags: [],
    forbids: [].}
proc queueReplStatus(conn: PgConnection): ReplWrite {....raises: [], tags: [],
    forbids: [].}
Queue the library's status, or share the one at the tail.
proc queueStmtClose(conn: PgConnection; stmtName: string) {....raises: [],
    tags: [], forbids: [].}

Queue a server-side Close for a statement the cache no longer tracks (a dropped entry, or a cache miss the server Parsed but the cache did not keep). The next Extended Query send carries it at its head.

Only for names this cache Parsed: a Close for a name whose Parse failed would drop whoever else holds it.

proc raiseClosedConnection(conn: PgConnection; msg: string) {.noreturn,
    ...raises: [PgStateError, PgConnectionError], tags: [], forbids: [].}
Like checkNotClosed with a custom crClosed message.
proc raiseTransportFailure(conn: PgConnection; what: string;
                           e: ref CatchableError) {.noreturn,
    ...raises: [PgStateError, CatchableError, PgConnectionError], tags: [],
    forbids: [].}
Fold backend transport error into PgError (closedByUser wins).
proc reclaimHandoff(conn: PgConnection) {....raises: [], tags: [], forbids: [].}
Requeue a handoff whose waiter will never claim it, so an abandoned frame cannot make the notification unreachable.
proc reclaimStaleNotifyWaiter(conn: PgConnection) {....raises: [], tags: [],
    forbids: [].}
Drop a finished waiter's registration and put back its unclaimed handoff.
proc reconnectCallback(conn: PgConnection): var ReconnectCallback {.inline,
    ...raises: [], tags: [], forbids: [].}
proc recordParameterStatus(conn: PgConnection; name, value: string) {.
    ...raises: [PgProtocolError], tags: [], forbids: [].}
Store one ParameterStatus under MaxServerParams / MaxServerParamsBytes. Exceeding either cap is treated as a broken peer: the connection is closed and PgProtocolError is raised. Updates to an existing key are always admitted when the resulting byte total fits.
func recvBuf(conn: PgConnection): lent seq[byte] {.inline, ...raises: [], tags: [],
    forbids: [].}
func recvBufLen(conn: PgConnection): int {.inline, ...raises: [], tags: [],
    forbids: [].}
Number of unparsed bytes buffered.
func recvBufStart(conn: PgConnection): int {.inline, ...raises: [], tags: [],
    forbids: [].}
First unparsed byte in recvBuf.
proc registerNotifyWaiter(conn: PgConnection; waiter: Future[void]) {.
    ...raises: [PgStateError], tags: [], forbids: [].}
Park the single allowed waiter. A second would never be woken, so it is rejected here rather than left to hang.
proc removeStmtCache(conn: PgConnection; sql: string) {....raises: [], tags: [],
    forbids: [].}
Remove a statement from the cache by its SQL text. The caller queues the server-side Close (see queueStmtClose).
func replAutoConfirm(conn: PgConnection): bool {.inline, ...raises: [], tags: [],
    forbids: [].}
Whether the logical stream confirms progress itself.
proc replCanStillReport(conn: PgConnection): bool {....raises: [], tags: [],
    forbids: [].}
Whether a position recorded now still reaches the server: always before the client's stop, then only until the stop's final status is encoded, which waits for a running callback to return.
proc replClosedError(conn: PgConnection; msg = "Connection is closed"): ref PgError {.
    ...raises: [], tags: [], forbids: [].}
raiseClosedConnection's error, or nil while open, keeping the replication write that killed the connection as the cause.
func replConfirmedFlushLsn(conn: PgConnection): uint64 {....raises: [], tags: [],
    forbids: [].}
Raw flush LSN (use typed API).
func replCopyDone(conn: PgConnection): ReplWrite {.inline, ...raises: [], tags: [],
    forbids: [].}
The queued CopyDone write, or nil. Read-only: replQueueStop creates it.
func replCopyDoneQueued(conn: PgConnection): bool {.inline, ...raises: [],
    tags: [], forbids: [].}
Whether the client's CopyDone has been queued.
proc replEnterTxn(conn: PgConnection) {.inline, ...raises: [], tags: [],
                                        forbids: [].}
autoConfirm: a pgoutput Begin was seen; a commit now waits for the callback to process it.
proc replExitTxn(conn: PgConnection) {.inline, ...raises: [], tags: [], forbids: [].}
autoConfirm: the commit is processed, so positions may be reported again.
func replFlusher(conn: PgConnection): Future[void] {.inline, ...raises: [],
    tags: [], forbids: [].}
The task draining replWrites, nil when idle. Read-only; a new drain starts through replFlusherIdle + setReplFlusher so two tasks never share the queue.
func replFlusherIdle(conn: PgConnection): bool {.inline, ...raises: [], tags: [],
    forbids: [].}
Whether a drain task may be started.
func replInCallback(conn: PgConnection): bool {.inline, ...raises: [], tags: [],
    forbids: [].}
Whether the stream's callback is running.
func replInTxn(conn: PgConnection): bool {.inline, ...raises: [], tags: [],
    forbids: [].}
autoConfirm: between a pgoutput Begin and Commit.
func replMaxReceivedLsn(conn: PgConnection): uint64 {....raises: [], tags: [],
    forbids: [].}
Raw max-received LSN.
func replPendingStatusQueued(conn: PgConnection): bool {.inline, ...raises: [],
    tags: [], forbids: [].}
Whether a library status is queued and not yet encoded.
proc replQueueStop(conn: PgConnection): ReplWrite {....raises: [], tags: [],
    forbids: [].}
Queue the client's end of the stream — a last status, then CopyDone — and return the CopyDone future's write. Once queued, a later stop waits on that same CopyDone and shares its outcome.
proc replQueueWrite(conn: PgConnection; w: ReplWrite) {.inline, ...raises: [],
    tags: [], forbids: [].}
Append a caller's write to the drain queue, in call order.
func replReported(conn: PgConnection): tuple[receive, flush, apply: uint64] {.
    ...raises: [], tags: [], forbids: [].}
Raw reported positions (see noteReplReported).
proc replResetStream(conn: PgConnection; autoConfirm: bool; serverFlush: uint64) {.
    ...raises: [], tags: [], forbids: [].}
Reset the write cluster for a new stream, so a reused connection never inherits a final status or a failure from the previous one.
func replSentFlush(conn: PgConnection): uint64 {.inline, ...raises: [], tags: [],
    forbids: [].}
Flush position of the library's last Standby Status Update (raw).
func replStopStatusQueued(conn: PgConnection): bool {.inline, ...raises: [],
    tags: [], forbids: [].}
Whether the stop's final status is still waiting to be encoded.
proc replWriteError(conn: PgConnection): ref CatchableError {....raises: [],
    tags: [], forbids: [].}
A fresh error per waiter of a write that did not make it: one raised exception cannot be shared between futures.
func replWriteFailure(conn: PgConnection): ref CatchableError {.inline,
    ...raises: [], tags: [], forbids: [].}
The write failure that ended the stream, kept as the cause of later errors.
func replWritesOpen(conn: PgConnection): bool {.inline, ...raises: [], tags: [],
    forbids: [].}
Whether the stream still accepts writes.
proc reportsIsoDateStyle(value: string): bool {....raises: [], tags: [],
    forbids: [].}
Whether a reported DateStyle has the ISO output style the text decoders parse. The server reports the style first: ISO, MDY.
proc requestListenStop(conn: PgConnection) {.inline, ...raises: [], tags: [],
    forbids: [].}
proc requeueHandoff(conn: PgConnection; notif: Notification) {....raises: [],
    tags: [], forbids: [].}
Requeue an unconsumed handoff at the front.
proc requireStaged(conn: PgConnection; what: string) {.inline, ...raises: [],
    tags: [], forbids: [].}
Reject what when nothing was staged for it: dropping names whose Close was never written leaks those statements for the session, and does so silently.
proc resetWireState(conn: PgConnection) {....raises: [], tags: [], forbids: [].}

Forget what the wire's previous life left behind: the buffered bytes on both sides and the replies the old backend owed.

Sole owner of that reset: a stale count carried onto a fresh backend would dial a CancelRequest at an unrelated PID and retire a healthy connection.

func secretKey(conn: PgConnection): int32 {.inline, ...raises: [], tags: [],
    forbids: [].}
func sendBuf(conn: PgConnection): lent seq[byte] {.inline, ...raises: [], tags: [],
    forbids: [].}
func sendBufLen(conn: PgConnection): int {.inline, ...raises: [], tags: [],
    forbids: [].}
func serverCertDer(conn: PgConnection): lent seq[byte] {.inline, ...raises: [],
    tags: [], forbids: [].}
func serverCertMissing(conn: PgConnection): string {.inline, ...raises: [],
    tags: [], forbids: [].}
Why serverCertDer is empty, as a clause for error messages.
func serverParam(conn: PgConnection; name: string): string {....raises: [],
    tags: [], forbids: [].}
One ParameterStatus value, or "" when the server never sent it.
func serverParams(conn: PgConnection): lent Table[string, string] {.inline,
    ...raises: [], tags: [], forbids: [].}
proc serverParams=(conn: PgConnection; value: Table[string, string]) {.inline,
    ...raises: [], tags: [], forbids: [].}
func sessionLockDirty(conn: PgConnection): bool {.inline, ...raises: [], tags: [],
    forbids: [].}
proc setListenReconnecting(conn: PgConnection; value: bool) {.inline,
    ...raises: [], tags: [], forbids: [].}
proc setReplFlusher(conn: PgConnection; fut: Future[void]) {.inline, ...raises: [],
    tags: [], forbids: [].}
Adopt fut as the drain task; only valid right after replFlusherIdle returned true.
proc setReplInCallback(conn: PgConnection; value: bool) {.inline, ...raises: [],
    tags: [], forbids: [].}
Mark the stream's callback as running or returned; the stop's final status waits for a true one to clear.
proc setServerCertDer(conn: PgConnection; der: seq[byte]) {.inline, ...raises: [],
    tags: [], forbids: [].}
Store the server certificate DER for SCRAM channel binding.
proc setServerCertMissing(conn: PgConnection; reason: string) {.inline,
    ...raises: [], tags: [], forbids: [].}
Record why TLS setup left serverCertDer empty.
proc setServerParam(conn: PgConnection; name, value: string) {.inline,
    ...raises: [], tags: [], forbids: [].}
Store one ParameterStatus value. Prefer recordParameterStatus, which also maintains the bounds and serverParamsBytes.
proc settlePendingSync(conn: PgConnection) {.inline, ...raises: [], tags: [],
    forbids: [].}
One ReadyForQuery reply has been read, so the backend owes one reply less. Counts down rather than clearing: a pipelined batch owes several.
proc settleReplWrite(conn: PgConnection; w: ReplWrite; ok: bool) {.
    ...raises: [Exception], tags: [RootEffect], forbids: [].}
func socket(conn: PgConnection): AsyncSocket {.inline, ...raises: [], tags: [],
    forbids: [].}
func sslEnabled(conn: PgConnection): bool {.inline, ...raises: [], tags: [],
    forbids: [].}
Whether the transport is TLS-wrapped.
proc sslEnabled=(conn: PgConnection; value: bool) {.inline, ...raises: [],
    tags: [], forbids: [].}
func sslHost(conn: PgConnection): string {.inline, ...raises: [], tags: [],
    forbids: [].}
proc stageEvictedClose(conn: PgConnection; buf: var seq[byte]; name: string) {.
    ...raises: [PgTypeError, PgProtocolError], tags: [], forbids: [].}

Stage the Close for a statement the build itself evicted. Staged, not queued: the cache no longer remembers the name, and an aborted build leaves staged names owed just as the queue would.

Only ahead of the build's first Parse/Bind/Describe/Execute: behind a failing one the backend skips it up to Sync, yet the name is dropped once the bytes are sent.

proc stagePendingStmtCloses(conn: PgConnection) {.inline,
    ...raises: [PgTypeError, PgProtocolError], tags: [], forbids: [].}
Stage every owed statement Close into the connection's own send buffer (the assembly path; the two-argument form serves callers building a separate batch).
proc stagePendingStmtCloses(conn: PgConnection; buf: var seq[byte]) {.
    ...raises: [PgTypeError, PgProtocolError], tags: [], forbids: [].}

Append a Close for every owed statement name to buf so they ride along with this operation's Sync, moving them from the queue to stagedStmtCloses.

Only sendStagedBufMsg / sendStagedMsg drop them once on the wire; a re-sent Close is a backend no-op.

buf must already be emptied, or the build truncates the Closes away.

proc startupDateStyle(val: string): string {....raises: [], tags: [], forbids: [].}
The startup DateStyle for a caller's val (empty if none), which names no other output style: ISO, then any field order val sets. The server accepts a repeated ISO.
func state(conn: PgConnection): PgConnState {.inline, ...raises: [], tags: [],
    forbids: [].}
Current state (read-only; see isConnected).
func stmtCacheCapacity(conn: PgConnection): int {.inline, ...raises: [], tags: [],
    forbids: [].}
Statement-cache capacity; see stmtCacheCapacity=.
proc stmtCacheCapacity=(conn: PgConnection; value: int) {....raises: [], tags: [],
    forbids: [].}
Resize the client-side prepared-statement cache (256 default; 0 disables it). Shrinking evicts the least recently used excess at once; their server-side Close rides along with the next Extended Query operation.
func stmtCacheResetGen(conn: PgConnection): int {.inline, ...raises: [], tags: [],
    forbids: [].}
proc stmtCachingEnabled(conn: PgConnection): bool {.inline, ...raises: [],
    tags: [], forbids: [].}
Whether prepared statements are cached on this connection.
proc tailPendingReplStatus(conn: PgConnection): ReplWrite {....raises: [],
    tags: [], forbids: [].}
The library's status still queued at the tail, or nil. It is encoded when written, so it already carries anything newer and can stand for another.
proc takeNotifyHandoff(conn: PgConnection): Option[Notification] {.inline,
    ...raises: [], tags: [], forbids: [].}
Claim the reserved handoff, if any. Only the registered waiter may call this; the handoff is returned directly and never re-enters the capped queue.
func timeZoneChanged(conn: PgConnection): bool {.inline, ...raises: [], tags: [],
    forbids: [].}
Whether TimeZone has moved to a zone a DateTime param would read differently under. A UTC+0 spelling of the connect zone (Etc/UTC for UTC) shifts nothing, so it counts as unchanged.
func timeZoneFollowsServer(conn: PgConnection): bool {.inline, ...raises: [],
    tags: [], forbids: [].}
proc tracer(conn: PgConnection): var PgTracer {.inline, ...raises: [], tags: [],
    forbids: [].}
proc transportCloseFut(conn: PgConnection): var Future[void] {.inline,
    ...raises: [], tags: [], forbids: [].}
proc txAbortFields(conn: PgConnection): var seq[ErrorField] {.inline,
    ...raises: [], tags: [], forbids: [].}
func txStatus(conn: PgConnection): TransactionStatus {.inline, ...raises: [],
    tags: [], forbids: [].}
Tx status from last ReadyForQuery (via bindSym). Read-only to applications; library modules update it through the internal txStatus=.
proc txStatus=(conn: PgConnection; value: TransactionStatus) {.inline,
    ...raises: [], tags: [], forbids: [].}
proc unregisterNotifyWaiter(conn: PgConnection; waiter: Future[void]): bool {.
    ...raises: [], tags: [], forbids: [].}
Drop waiter's registration if it is still the parked one. False means a later waiter owns the slot now; only the owner may claim the handoff.
proc updateReplMaxReceivedLsn(conn: PgConnection; received: uint64): bool {.
    ...raises: [], tags: [], forbids: [].}
Advance max-received LSN if received is greater; return if updated.
proc validateClientCertConfig(config: ConnConfig) {....raises: [PgConfigError],
    tags: [], forbids: [].}
Reject inconsistent client certificate configurations early (at config build time, before any connection is opened). Both halves of an mTLS credential must be present together, and the SSL mode must actually negotiate TLS — otherwise the cert/key would be silently ignored.
proc validateTlsConfig(config: ConnConfig; overTcp = true) {.
    ...raises: [PgConfigError], tags: [], forbids: [].}
Reject TLS settings no server can satisfy (as libpq): a TLS requirement in a build without TLS (asyncdispatch without -d:ssl), or, when overTcp, a verified sslmode without sslrootcert (a Unix socket skips TLS).
proc waitReplWrite(w: ReplWrite): Future[void] {....raises: [], tags: [],
    forbids: [].}
proc warnStderr(msg: string) {....raises: [], tags: [WriteIOEffect], forbids: [].}
Connection-path warnings must never fail the connection: stderr may be closed or broken (e.g. daemonized process), so swallow the IOError.
func wireSettled(conn: PgConnection): bool {.inline, ...raises: [], tags: [],
    forbids: [].}

True when the backend owes nothing: every request written has been answered to its ReadyForQuery, so the stream is parked on a message boundary and the connection is safe to hand to someone else.

Sole reader of the two fields behind it, so no caller can settle for the half of the question that suits it.

Macros

macro addBindDirect(conn: PgConnection; portalName: string; stmtName: string;
                    resultFormats: untyped; args: varargs[untyped]): untyped
Connection-level form of pg_types/encoding.addBindDirect: encodes the Bind straight into the send buffer with per-argument format codes and no intermediate seq[byte]. The operand rules are the encoding macro's.
macro addParseDirect(conn: PgConnection; stmtName: string; sql: string;
                     args: varargs[untyped]): untyped
Connection-level form of pg_types/encoding.addParseDirect: encodes the Parse straight into the send buffer, with parameter OIDs taken from the argument types. The operand rules are the encoding macro's.

Templates

template withConnTracing(conn: PgConnection; startHook, endHook: untyped;
                         startData: typed; EndDataType: typedesc;
                         endDataExpr: typed; body: untyped)
Wrap an operation with connection-scoped tracing hooks. body sees the start hook's context as traceCtx.
template withTracing(tracer: PgTracer; startHook, endHook: untyped;
                     startData: typed; EndDataType: typedesc;
                     endDataExpr: typed; body: untyped)
Wrap an operation with non-connection tracing hooks (connect, pool). traceCtx works as in withConnTracing.