async_postgres/pg_connection

Search:
Group by:

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 = object
  name*: string              ## Server-side statement name ("_sc_1", "_sc_2", ...)
  fields*: seq[FieldDescription] ## From Describe(Statement), formatCode=0
  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
A cached prepared statement in the LRU statement cache.
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).
ConnConfig = object
  host*: string
  port*: int
  user*: string
  password*: string
  database*: string
  sslMode*: SslMode
  sslRootCert*: string       ## PEM-encoded CA certificate(s) for sslVerifyCa/sslVerifyFull
  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] ## Allowlist of auth methods the client will accept. An empty set
                                ## (default) means "allow any" — matching libpq when `require_auth` is
                                ## unset. If the server requests a method outside this set, connect
                                ## fails with `PgConnectionError`. For SASL, advertised mechanisms are
                                ## filtered and the selected mechanism is validated.
                                ## 
                                ## Note: libpq's `!`-prefix negation syntax (e.g. `!password`) is not
                                ## yet supported by `parseRequireAuth` — specify the allowed methods
                                ## positively instead.
  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)
  extraParams*: seq[(string, string)] ## Additional startup parameters
  maxMessageSize*: int ## Upper bound (in bytes) on a single backend message including
                       ## its 1-byte type and 4-byte length header. A server claiming a
                       ## larger message is rejected with `ProtocolError` before any
                       ## further recv-buffer growth, capping memory exposure to a
                       ## misbehaving or malicious peer. ``0`` (default) selects
                       ## `DefaultMaxBackendMessageLen` (1 GiB).
  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: seq[byte]): Future[void] {....gcsafe.}
Callback receiving each chunk during streaming COPY OUT.
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
  port*: int
A single host:port entry for multi-host connection.
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.
PgConnection = ref object
  when hasChronos:
  elif hasAsyncDispatch:
  ownerPool*: PgPoolOwner ## Owning pool back-reference. Set when this connection is managed by
                          ## a `PgPool` (or a pool inside `PgPoolCluster`); `nil` for standalone
                          ## connections created via `connect`. Used by `release(conn)` to route
                          ## the connection back to the correct pool.
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: [].}
  onPoolCloseError*: proc (data: TracePoolCloseErrorData) {....gcsafe, raises: [].}
  onTransportCloseError*: proc (data: TraceTransportCloseErrorData) {....gcsafe,
      raises: [].} ## Fires when a transport ``closeWait()`` raises during teardown.
                   ## Advisory only — ``closeTransport`` continues releasing the remaining
                   ## resources regardless. Use this to surface half-closed TLS sessions
                   ## or peer RSTs that would otherwise be invisible.
  onInsecureAuth*: proc (data: TraceInsecureAuthData) {....gcsafe, raises: [].} ## Fires when an auth method is used over an insecure transport
                                                                             ## (currently: cleartext password without SSL). Advisory only; does
                                                                             ## not abort the connection. Use `ConnConfig.requireAuth` to enforce.
  onDeprecatedAuth*: proc (data: TraceDeprecatedAuthData) {....gcsafe, raises: [].} ## Fires when a server-requested auth method is cryptographically
                                                                                 ## weak / deprecated regardless of transport (currently: MD5).
                                                                                 ## Advisory only; does not abort the connection. Use
                                                                                 ## `ConnConfig.requireAuth` to enforce.

Tracing hooks for async-postgres operations. Set only the callbacks you need; nil callbacks are skipped with zero overhead.

Start hooks return a TraceContext (opaque pointer) that is passed to the corresponding End hook for correlation (e.g. timing, span linking). Return nil from Start if you don't need correlation.

QueryResult = object
  fields*: seq[FieldDescription]
  data*: RowData
  rowCount*: int32
  commandTag*: string
Result of a query: field descriptions, row data, and command tag.
RowCallback = proc (row: Row) {....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 (default)
  sslAllow,                 ## Try plaintext; fall back to SSL if refused
  sslPrefer,                ## Try SSL; fall back to plaintext if refused
  sslRequire,               ## Require SSL (no certificate verification)
  sslVerifyCa,              ## Require SSL + verify CA chain (no hostname verification)
  sslVerifyFull              ## Require SSL + verify CA chain and hostname
SSL/TLS negotiation mode 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).
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.
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.
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
Data passed to the transport close-error hook. Fired when a chronos closeWait() call raises while closeTransport is releasing connection resources. These errors are otherwise swallowed because teardown must release every transport resource regardless of individual failures, leaving operators with no signal for half-closed TLS sessions, BearSSL close_notify mismatches, or peer RSTs.
TransportCloseStage = enum
  tcsTlsReader, tcsTlsWriter, tcsBaseReader, tcsBaseWriter, tcsTransport
Which transport resource raised during connection teardown.

Procs

proc addStmtCache(conn: PgConnection; sql: string; cached: CachedStmt) {.
    ...raises: [], tags: [], forbids: [].}
Add a prepared statement to the cache with auto-computed result formats.
proc cancel(conn: PgConnection): Future[void] {....stackTrace: false,
    raises: [Exception, OSError, ValueError, IOError, SslError, LibraryError],
    tags: [RootEffect], forbids: [].}
Send a CancelRequest over a separate connection to abort the running query.
proc cancelNoWait(conn: PgConnection) {....raises: [Exception], tags: [RootEffect],
                                        forbids: [].}
Schedule a best-effort CancelRequest without waiting. For use in timeout handlers.
proc checkReady(conn: PgConnection) {....raises: [PgConnectionError], tags: [],
                                      forbids: [].}
Assert that the connection is in csReady state. Raises PgConnectionError otherwise.
proc clearStmtCache(conn: PgConnection) {....raises: [], tags: [], forbids: [].}
Clear the client-side statement cache. Does not close server-side statements.
proc close(conn: PgConnection): Future[void] {....stackTrace: false,
    raises: [Exception, ValueError, LibraryError, SslError], tags: [RootEffect],
    forbids: [].}
Close the connection. Idempotent: safe to call multiple times.
proc columnIndex(qr: QueryResult; name: string): int {....raises: [PgTypeError],
    tags: [], forbids: [].}
Find the index of a column by name in a query result.
func config(conn: PgConnection): lent ConnConfig {.inline, ...raises: [], tags: [],
    forbids: [].}
proc connect(config: ConnConfig): Future[PgConnection] {.
    ...raises: [Exception, ValueError, CatchableError],
    tags: [RootEffect, TimeEffect, WriteIOEffect], forbids: [].}
Establish a new connection to a PostgreSQL server. Supports multi-host failover: tries each host in order. Respects targetSessionAttrs to select the appropriate server type. The connectTimeout wraps the entire multi-host connection attempt.
proc connect(dsn: string): Future[PgConnection] {.
    ...raises: [Exception, ValueError, CatchableError, PgError],
    tags: [RootEffect, TimeEffect, WriteIOEffect, ReadIOEffect], forbids: [].}
Shorthand for connect(parseDsn(dsn)).
func createdAt(conn: PgConnection): var Moment {.inline, ...raises: [], tags: [],
    forbids: [].}
proc createdAt=(conn: PgConnection; val: Moment) {.inline, ...raises: [], tags: [],
    forbids: [].}
proc dispatchNotice(conn: PgConnection; msg: BackendMessage) {....raises: [],
    tags: [RootEffect], forbids: [].}
proc dispatchNotification(conn: PgConnection; msg: BackendMessage) {....raises: [],
    tags: [RootEffect], forbids: [].}
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.
proc evictStmtCache(conn: PgConnection): CachedStmt {....raises: [KeyError],
    tags: [], forbids: [].}
Evict the least recently used entry from the cache. Returns the evicted entry.
proc fillRecvBuf(conn: PgConnection; timeout: Duration = ZeroDuration): Future[
    void] {....stackTrace: false, raises: [Exception, ValueError, SslError,
                                        AsyncTimeoutError, PgConnectionError],
            tags: [RootEffect, TimeEffect], forbids: [].}
Read data from socket into buffer. The only await point for message reception.
proc filterSaslByRequireAuth(mechs: seq[string]; allowed: set[AuthMethod]): seq[
    string] {....raises: [], tags: [], forbids: [].}
Filter a server-offered SASL mechanism list by the client's requireAuth policy. An empty allowed set performs no filtering (matching libpq semantics when require_auth is unset).
proc getHosts(config: ConnConfig): seq[HostEntry] {....raises: [], tags: [],
    forbids: [].}
Return the list of hosts to try. If hosts is populated, return it; otherwise synthesize a single entry from host/port.
func hstoreArrayOid(conn: PgConnection): int32 {.inline, ...raises: [], tags: [],
    forbids: [].}
Dynamic OID for hstore[] array type; 0 if not available.
func hstoreOid(conn: PgConnection): int32 {.inline, ...raises: [], tags: [],
    forbids: [].}
Dynamic OID for hstore extension type; 0 if not available.
proc initConnConfig(host = "127.0.0.1"; port = 5432; user = ""; password = "";
                    database = ""; sslMode = sslDisable; sslRootCert = "";
                    channelBinding = cbPrefer; applicationName = "";
                    connectTimeout = ZeroDuration; keepAlive = true;
                    keepAliveIdle = 0; keepAliveInterval = 0;
                    keepAliveCount = 0; hosts: seq[HostEntry] = @[];
                    targetSessionAttrs = tsaAny;
                    requireAuth: set[AuthMethod] = {};
                    extraParams: seq[(string, string)] = @[]; maxMessageSize = 0): ConnConfig {.
    ...raises: [], tags: [], forbids: [].}
Create a connection configuration with sensible defaults. For DSN-based configuration, use parseDsn instead.
proc invalidateOnTimeout(conn: PgConnection; reason: string) {.
    ...raises: [Exception, PgTimeoutError], tags: [RootEffect], forbids: [].}

Timeout recovery for a connection whose last request may have left the protocol out of sync. Schedules a best-effort CancelRequest via cancelNoWait, marks the connection csClosed so it cannot be reused, and raises PgTimeoutError with reason.

Under asyncdispatch this is the only safe recovery path: the inner future keeps running in the background after wait() fires, and may still write to the socket. Reusing the connection would interleave its stale write with a new request and corrupt the protocol stream. chronos cancels the inner future properly, but we still invalidate unconditionally — the server may have processed the request partially and the cached session state (prepared statements, portals, transaction status) is no longer reliable.

proc isConnected(conn: PgConnection): bool {....raises: [], tags: [], forbids: [].}

Whether the underlying transport is present.

This is a cheap, non-blocking check (no round trip): it only reports whether the connection object currently holds a transport handle. It does not detect server-side closes that have not yet been observed by a read — use ping for that.

Pair with state == csReady to decide whether a connection is usable before issuing a query.

proc isUnixSocket(host: string): bool {.inline, ...raises: [], tags: [],
                                        forbids: [].}
True if host represents a Unix socket directory (starts with '/'). Compatible with libpq behavior.
proc len(qr: QueryResult): int {.inline, ...raises: [], tags: [], forbids: [].}
Return the number of rows in the query result.
proc listen(conn: PgConnection; channel: string): Future[void] {.
    ...stackTrace: false, raises: [Exception, CancelledError, ValueError,
                                PgConnectionError, CatchableError],
    tags: [RootEffect, TimeEffect, WriteIOEffect], forbids: [].}
Subscribe to a LISTEN channel and start the background notification pump.
func listenChannels(conn: PgConnection): lent HashSet[string] {.inline,
    ...raises: [], tags: [], forbids: [].}
func listenReconnectMaxAttempts(conn: PgConnection): int {.inline, ...raises: [],
    tags: [], forbids: [].}
Max reconnect attempts on listen pump failure (0 or negative = unlimited).
proc listenReconnectMaxAttempts=(conn: PgConnection; val: int) {.inline,
    ...raises: [], tags: [], forbids: [].}
Set the maximum reconnect attempts for the listen pump. 0 or negative = unlimited retries (retry until close()).
func listenReconnectMaxBackoff(conn: PgConnection): int {.inline, ...raises: [],
    tags: [], forbids: [].}
Maximum seconds between reconnect attempts (backoff cap).
proc listenReconnectMaxBackoff=(conn: PgConnection; val: int) {.inline,
    ...raises: [], tags: [], forbids: [].}
Set the maximum seconds between reconnect attempts (backoff cap).
func listenTask(conn: PgConnection): var Future[void] {.inline, ...raises: [],
    tags: [], forbids: [].}
proc listenTask=(conn: PgConnection; val: Future[void]) {.inline, ...raises: [],
    tags: [], forbids: [].}
proc lookupStmtCache(conn: PgConnection; sql: string): ptr CachedStmt {.
    ...raises: [], tags: [], forbids: [].}
Look up a cached prepared statement by SQL text, updating LRU order on hit. Returns nil on miss. The returned pointer is valid until the next cache mutation.
proc newPgQueryError(fields: seq[ErrorField]): ref PgQueryError {....raises: [],
    tags: [], forbids: [].}
Create a PgQueryError from server ErrorResponse fields.
proc nextMessage(conn: PgConnection; rowData: RowData = nil;
                 rowCount: ptr int32 = nil): Option[BackendMessage] {.
    ...raises: [ProtocolError], tags: [RootEffect], forbids: [].}

Synchronously parse the next message from the receive buffer. Returns none if the buffer doesn't contain a complete message. Notification/Notice messages are dispatched internally. DataRow messages are counted (if rowCount != nil) and consumed.

On ProtocolError the protocol stream is desynchronised — the connection is transitioned to csClosed before re-raising so that it is never reused (in particular, by the connection pool).

proc nextStmtName(conn: PgConnection): string {....raises: [], tags: [],
    forbids: [].}
Generate the next unique prepared statement name for the statement cache.
proc noticeCallback=(conn: PgConnection; cb: NoticeCallback) {.inline,
    ...raises: [], tags: [], forbids: [].}
Set the callback invoked when a notice/warning message arrives.
func notifyCallback(conn: PgConnection): NotifyCallback {.inline, ...raises: [],
    tags: [], forbids: [].}
The callback invoked when a NOTIFY message arrives.
func notifyDropped(conn: PgConnection): int {.inline, ...raises: [], tags: [],
    forbids: [].}
Count of notifications dropped due to queue overflow.
func notifyMaxQueue(conn: PgConnection): int {.inline, ...raises: [], tags: [],
    forbids: [].}
The maximum notification queue size (0 = unlimited).
proc notifyMaxQueue=(conn: PgConnection; val: int) {.inline, ...raises: [],
    tags: [], forbids: [].}
Set the maximum notification queue size (0 = unlimited).
proc notifyOverflowCallback=(conn: PgConnection;
                             cb: proc (dropped: int) {....gcsafe, raises: [].}) {.
    inline, ...raises: [], tags: [], forbids: [].}
Set the callback invoked when notifications are dropped due to queue overflow.
func notifyQueue(conn: PgConnection): var Deque[Notification] {.inline,
    ...raises: [], tags: [], forbids: [].}
proc onNotify(conn: PgConnection; callback: NotifyCallback) {....raises: [],
    tags: [], forbids: [].}
Set a callback invoked for each incoming NOTIFY message.
proc parseDsn(dsn: string): ConnConfig {....raises: [PgError],
    tags: [ReadIOEffect], forbids: [].}

Parse a PostgreSQL connection string into a ConnConfig.

Supports two formats:

  • URI: postgresql://[user[:password]@][host[:port]][/database][?param=value&...]
  • keyword=value: host=localhost port=5432 dbname=test (libpq compatible)

Both postgresql:// and postgres:// schemes are accepted for URI format.

proc parseRequireAuth(s: string): set[AuthMethod] {....raises: [PgError], tags: [],
    forbids: [].}
Parse a comma-separated list of auth method names into a set (libpq require_auth syntax; negation prefix ! is not yet supported). Empty input returns the empty set (allow any).
func pid(conn: PgConnection): int32 {.inline, ...raises: [], tags: [], forbids: [].}
The backend process ID for this connection.
proc ping(conn: PgConnection; timeout = ZeroDuration): Future[void] {....raises: [
    Exception, ValueError, PgQueryError, PgConnectionError, SslError,
    ProtocolError, PgTimeoutError, AsyncTimeoutError],
    tags: [RootEffect, TimeEffect], forbids: [].}
Lightweight health check using an empty simple query. Sends Query("") -> expects EmptyQueryResponse + ReadyForQuery. On timeout, the connection is marked csClosed (protocol out of sync).
func portalCounter(conn: PgConnection): var int {.inline, ...raises: [], tags: [],
    forbids: [].}
proc quoteIdentifier(s: string): string {....raises: [], tags: [], forbids: [].}
Quote a SQL identifier (e.g. table/channel name) with double quotes, escaping embedded quotes.
proc reconnectCallback=(conn: PgConnection; cb: proc () {....gcsafe, raises: [].}) {.
    inline, ...raises: [], tags: [], forbids: [].}
Set the callback invoked after a successful automatic reconnect.
func recvBuf(conn: PgConnection): var seq[byte] {.inline, ...raises: [], tags: [],
    forbids: [].}
proc recvBuf=(conn: PgConnection; val: seq[byte]) {.inline, ...raises: [],
    tags: [], forbids: [].}
func recvBufStart(conn: PgConnection): var int {.inline, ...raises: [], tags: [],
    forbids: [].}
proc recvBufStart=(conn: PgConnection; val: int) {.inline, ...raises: [], tags: [],
    forbids: [].}
proc recvMessage(conn: PgConnection; timeout = ZeroDuration;
                 rowData: RowData = nil; rowCount: ptr int32 = nil): Future[
    BackendMessage] {....stackTrace: false, raises: [Exception, ValueError,
    ProtocolError, SslError, AsyncTimeoutError, PgConnectionError],
                      tags: [RootEffect, TimeEffect], forbids: [].}
Receive a single backend message from the connection. Thin wrapper around nextMessage + fillRecvBuf for backward compatibility.
proc removeStmtCache(conn: PgConnection; sql: string) {....raises: [], tags: [],
    forbids: [].}
Remove a statement from the cache by its SQL text.
proc rows(qr: QueryResult): seq[Row] {....raises: [], tags: [], forbids: [].}
Return all rows as lightweight Row views into the flat buffer.
func secretKey(conn: PgConnection): int32 {.inline, ...raises: [], tags: [],
    forbids: [].}
The backend secret key (used for cancel requests).
func sendBuf(conn: PgConnection): var seq[byte] {.inline, ...raises: [], tags: [],
    forbids: [].}
proc sendBufMsg(conn: PgConnection): Future[void] {....stackTrace: false,
    raises: [Exception, SslError, ValueError], tags: [RootEffect], forbids: [].}
Send conn.sendBuf to the server. The transport receives its own copy of the buffer, so conn.sendBuf is safe to mutate while the returned Future is still pending.
proc sendMsg(conn: PgConnection; data: seq[byte]): Future[void] {.
    ...stackTrace: false, raises: [Exception, SslError, ValueError],
    tags: [RootEffect], forbids: [].}
Send raw bytes to the PostgreSQL server over the connection.
func serverParams(conn: PgConnection): lent Table[string, string] {.inline,
    ...raises: [], tags: [], forbids: [].}
proc simpleExec(conn: PgConnection; sql: string;
                timeout: Duration = ZeroDuration): Future[CommandResult] {.
    ...stackTrace: false, raises: [Exception, ValueError, CatchableError],
    tags: [RootEffect, TimeEffect], forbids: [].}

Execute a side-effect SQL command via the simple query protocol, returning the final command tag.

Lighter than exec for parameter-less commands — one Query message, no Parse/Bind/Describe round trip and no plan cache entry. Intended for session-level commands such as BEGIN, SET, VACUUM, LISTEN, NOTIFY.

The SQL string is sent verbatim (no parameters) — only use trusted input, or quote interpolated identifiers yourself via quoteIdentifier.

Multiple ;-separated statements are accepted, but only the last command tag is returned; use simpleQuery if you need per-statement results. For parameterised writes, prefer exec.

On timeout, the connection is marked csClosed (protocol out of sync).

proc simpleQuery(conn: PgConnection; sql: string): Future[seq[QueryResult]] {.
    ...stackTrace: false,
    raises: [Exception, ValueError, PgConnectionError, CatchableError],
    tags: [RootEffect, TimeEffect], forbids: [].}

Execute one or more SQL statements via the simple query protocol.

Returns one QueryResult per statement; supports multiple statements separated by ; in a single round trip — this is the main reason to choose simpleQuery over query.

No parameters are supported (the SQL string is sent verbatim — only use trusted input) and rows are always in the text wire format. No server-side plan cache entry is created.

For single-statement parameterised reads, prefer query; for parameter-less commands without rows, prefer simpleExec.

func sslEnabled(conn: PgConnection): bool {.inline, ...raises: [], tags: [],
    forbids: [].}
Whether SSL/TLS is active on this connection.
func state(conn: PgConnection): var PgConnState {.inline, ...raises: [], tags: [],
    forbids: [].}
proc state=(conn: PgConnection; val: PgConnState) {.inline, ...raises: [],
    tags: [], forbids: [].}
func stmtCache(conn: PgConnection): var Table[string, CachedStmt] {.inline,
    ...raises: [], tags: [], forbids: [].}
func stmtCacheCapacity(conn: PgConnection): var int {.inline, ...raises: [],
    tags: [], forbids: [].}
proc stmtCacheCapacity=(conn: PgConnection; val: int) {.inline, ...raises: [],
    tags: [], forbids: [].}
proc stopListening(conn: PgConnection): owned(Future[void]) {....stackTrace: false,
    raises: [Exception, CancelledError, ValueError], tags: [RootEffect],
    forbids: [].}
Stop the background listen pump and return the connection to csReady.
proc toPgBinaryParam(conn: PgConnection; v: PgHstore): PgParam {.inline,
    ...raises: [PgTypeError], tags: [], forbids: [].}
Convenience overload: encode hstore in binary using conn.hstoreOid. Raises PgTypeError if the hstore extension OID has not been discovered (e.g. extension not installed on the server).
proc toPgBinaryParam(conn: PgConnection; v: seq[PgHstore]): PgParam {.inline,
    ...raises: [PgTypeError, PgError], tags: [], forbids: [].}
Convenience overload: encode hstore[] in binary using conn.hstoreOid and conn.hstoreArrayOid. Raises PgTypeError if either OID has not been discovered.
func tracer(conn: PgConnection): var PgTracer {.inline, ...raises: [], tags: [],
    forbids: [].}
proc tracer=(conn: PgConnection; val: PgTracer) {.inline, ...raises: [], tags: [],
    forbids: [].}
func txStatus(conn: PgConnection): var TransactionStatus {.inline, ...raises: [],
    tags: [], forbids: [].}
proc txStatus=(conn: PgConnection; val: TransactionStatus) {.inline, ...raises: [],
    tags: [], forbids: [].}
proc unixSocketPath(host: string; port: int): string {....raises: [], tags: [],
    forbids: [].}
Build the libpq-compatible Unix socket file path: {dir}/.s.PGSQL.{port}.
proc unlisten(conn: PgConnection; channel: string): Future[void] {.
    ...stackTrace: false, raises: [Exception, CancelledError, ValueError,
                                PgConnectionError, CatchableError],
    tags: [RootEffect, TimeEffect, WriteIOEffect], forbids: [].}
Unsubscribe from a LISTEN channel. Stops the pump if no channels remain.
proc waitNotification(conn: PgConnection; timeout: Duration = ZeroDuration): Future[
    Notification] {....stackTrace: false, raises: [Exception, ValueError,
    PgNotifyOverflowError, PgConnectionError, PgError, PgTimeoutError],
                    tags: [RootEffect, TimeEffect], forbids: [].}
Wait for the next notification from the buffer. If the buffer is empty, blocks until a notification arrives or timeout expires. Raises PgNotifyOverflowError if notifications were dropped due to queue overflow. Raises PgError if the listen pump has died (e.g. reconnection failed).

Iterators

iterator items(qr: QueryResult): Row {....raises: [], tags: [], forbids: [].}
Iterate over all rows in the query result.

Templates

template makeCopyInCallback(body: untyped): CopyInCallback

Create a CopyInCallback that works with both asyncdispatch and chronos. body must evaluate to seq[byte]. Return an empty seq to signal completion.

With asyncdispatch, anonymous async procs cannot return non-void types, so this template wraps the body in manual Future construction.

var idx = 0
let rows = @["1\tAlice\n".toBytes(), "2\tBob\n".toBytes()]
let cb = makeCopyInCallback:
  if idx < rows.len:
    let chunk = rows[idx]
    inc idx
    chunk
  else:
    newSeq[byte]()
template makeCopyOutCallback(body: untyped): CopyOutCallback
Create a CopyOutCallback that works with both asyncdispatch and chronos. Inside body, the current chunk is available as data: seq[byte].
var chunks: seq[seq[byte]]
let cb = makeCopyOutCallback:
  chunks.add(data)
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).