Shared building blocks for pg_connection submodules (PgConnection, ConnConfig, tracing).
Internal module: not part of the public API. Import the pg_connection hub instead; what it re-exports is the supported surface (see tests/api_surface.golden).
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 (libpq: "scram-sha-256") amScramSha256Plus ## SASL SCRAM-SHA-256-PLUS (libpq: "scram-sha-256-plus")
- 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 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 ## Numeric address dialed instead of resolving `host` (libpq `hostaddr`). ## `host` is still the name used for SSL certificate verification. user*: string password*: string 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). ## On chronos/BearSSL specifically it must be PKCS#8 (RSA or EC); PKCS#1 ## is not supported. Must be paired with ``sslCert``. sslSni*: bool ## Send TLS SNI (default true; suppressed for IP/empty host). 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). applicationName*: string connectTimeout*: Duration ## TCP connect timeout (default: no timeout) keepAlive*: bool ## Enable TCP keepalive (default true via parseDsn) keepAliveIdle*: int ## Seconds before first probe (0 = OS default) keepAliveInterval*: int ## Seconds between probes (0 = OS default) keepAliveCount*: int ## Number of probes before giving up (0 = OS default) 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 startup parameters 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.
HostEntry = object host*: string ## Host name (or Unix socket dir); used for SSL verification hostaddr*: string ## Numeric 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: [].} ## Insecure auth over plaintext. onDeprecatedAuth*: proc (data: TraceDeprecatedAuthData) {....gcsafe, raises: [].} ## Weak auth (MD5). 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.
ReconnectCallback = proc () {....gcsafe, raises: [].}
- Callback invoked after the listen pump reconnects and re-subscribes.
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 rejects expired certs and lacks IP SAN for sslVerifyFull; asyncdispatch matches libpq.
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)
- 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 activeCount*: int maxSize*: int
- 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
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.
RecvBufSize = 131072
- Size of the temporary read buffer for recv operations
Procs
proc checkNotClosed(conn: PgConnection) {.inline, ...raises: [PgStateError, PgConnectionError], tags: [], forbids: [].}
- Reject if closed: PgStateError for deliberate close(), else PgConnectionError.
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.
func closedReason(conn: PgConnection): PgClosedReason {.inline, ...raises: [], tags: [], forbids: [].}
- Why unusable (crClosedByUser outranks crClosed).
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).
func createdAt(conn: PgConnection): Moment {.inline, ...raises: [], tags: [], forbids: [].}
- When the connection was established.
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()).
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 failNotifyWaiter(conn: PgConnection; err: ref PgError = nil) {....raises: [], tags: [RootEffect], forbids: [].}
- Fail parked waiter: closedByUser→PgStateError, else err/csClosed/stopped. Pass fresh err.
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 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: [].}
func host(conn: PgConnection): lent string {.inline, ...raises: [], tags: [], forbids: [].}
proc initReplLsnTracking(conn: PgConnection; startLsn: uint64) {....raises: [], tags: [], forbids: [].}
- Reset per-stream LSN tracking to startLsn.
func listenError(conn: PgConnection): ref PgListenError {.inline, ...raises: [], tags: [], forbids: [].}
- Why the listen pump died permanently, or nil while it is alive.
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).
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).
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 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.
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.
func notifyMaxQueue(conn: PgConnection): int {.inline, ...raises: [], tags: [], forbids: [].}
- Pull-API queue cap; see notifyMaxQueue=.
proc notifyMaxQueue=(conn: PgConnection; value: int) {.inline, ...raises: [], tags: [], forbids: [].}
- Cap the pull-API queue (1024 default; <=0 = unbounded). Overflow drops the oldest entry and fires onNotifyOverflow.
func pid(conn: PgConnection): int32 {.inline, ...raises: [], tags: [], forbids: [].}
- Backend process id from BackendKeyData; 0 until startup completes.
func port(conn: PgConnection): int {.inline, ...raises: [], tags: [], forbids: [].}
- Port this connection actually reached.
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).
func replConfirmedFlushLsn(conn: PgConnection): uint64 {....raises: [], tags: [], forbids: [].}
- Raw flush LSN (use typed API).
func replMaxReceivedLsn(conn: PgConnection): uint64 {....raises: [], tags: [], forbids: [].}
- Raw max-received LSN.
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 sendBuf(conn: PgConnection): var seq[byte] {.inline, ...raises: [], tags: [], forbids: [].}
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: [].}
func sslEnabled(conn: PgConnection): bool {.inline, ...raises: [], tags: [], forbids: [].}
- Whether the transport is TLS-wrapped.
func state(conn: PgConnection): PgConnState {.inline, ...raises: [], tags: [], forbids: [].}
- Current state (read-only; see isConnected / closedReason).
func stmtCacheCapacity(conn: PgConnection): int {.inline, ...raises: [], tags: [], forbids: [].}
- Statement-cache capacity; see stmtCacheCapacity=.
proc stmtCacheCapacity=(conn: PgConnection; value: int) {.inline, ...raises: [], tags: [], forbids: [].}
- Resize the client-side prepared-statement cache (256 default; 0 disables it). Shrinking below the current size leaves the excess to the next operation's eviction pass, which bundles the server-side Close.
func txStatus(conn: PgConnection): TransactionStatus {.inline, ...raises: [], tags: [], forbids: [].}
- Tx status from last ReadyForQuery (read-only, via bindSym).
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 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.
Templates
template withConnTracing(conn: PgConnection; startHook, endHook: untyped; startData: typed; EndDataType: typedesc; endDataExpr: typed; body: untyped)
- Wrap an operation with connection-scoped tracing hooks.
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).