async_postgres/pg_errors

Search:
Group by:

Exception hierarchy. Every library-raised exception derives from PgError.

The hierarchy encodes recovery: PgProtocolError and PgTimeoutError are PgConnectionError because both leave the wire unusable, so reconnect loops must see them; PgStateError and PgConfigError are deliberately siblings, being a programming error and a configuration fault that reconnecting cannot fix.

PgTypeError = caller data the wire format cannot carry; PgQueryError = an error the server reported; ValueError = a precondition, and the one kind not under PgError (except DSN parsing).

Types

ErrorField = object
  code*: char
  value*: string
A single field from an ErrorResponse or NoticeResponse message.
PgConfigError = object of PgError

A ConnConfig fault no retry can fix: a cert/key/CA that will not load, a cert without its key, an sslmode that contradicts another option. Every host shares one config, so connect raises it in place of the per-host PgConnectionError aggregate. A fault of a single host entry (a verify-full entry without a host name) is per host, not config-wide, and stays a PgConnectionError.

Deliberately not a PgConnectionError, so reconnect loops will not spin on it; a PgPool that sees one stops dialing (pekConfigFault).

PgConnectionError = object of PgError
Connection failures, disconnections, TLS handshake and auth errors. A TLS fault that stems from the config itself (a cert, key or CA that will not load) is a PgConfigError instead.
PgError = object of CatchableError
General PostgreSQL error. Base type for all pg-specific errors.
PgListenError = object of PgConnectionError
  reconnectionAttempted*: bool ## True if the pump attempted reconnection before giving up.
  transportAlive*: bool ## True when the pump died but the transport is still up. The pull API
                        ## raises ``PgListenStoppedError`` for that case instead.
Listen pump died permanently (reconnection failed or connection lost with no channels left to re-subscribe).
PgListenStoppedError = object of PgStateError
  reconnectionAttempted*: bool ## True if the pump attempted reconnection before giving up.
  transportAlive*: bool ## Always true here — the type is only raised for a live transport. Kept
                        ## so a caller reading the field need not special-case which error it got.
Listen pump gone from a connection that is still usable: call listen again to recover. Deliberately not a PgConnectionError, so a reconnect loop will not re-dial a live connection. Raised by waitNotification; the push API reports the same death as a PgListenError with transportAlive.
PgMessageTooLargeError = object of PgTypeError
An assembled protocol message exceeds the wire format's Int32 length. Caller data decides the size, so this is input, not connection health: nothing was sent and a reconnect loop must not fire.
PgNoRowsError = object of PgError
Raised by single-row/single-value queries when the result set is empty.
PgNotifyOverflowError = object of PgError
  dropped*: int              ## Number of notifications dropped due to queue overflow
PgNullError = object of PgError
Raised by single-value queries when the value is SQL NULL and the caller requested a non-nullable result.
PgPoolError = object of PgError
  kind*: PoolErrorKind       ## Failure category (see `PoolErrorKind`).

Pool-level acquire/operation failure (closed, acquire timeout, queue full, connect failed, config fault, unservable batch, or a wrapped user-code Defect; the underlying error is preserved as parent).

kind classifies the failure programmatically; the message string is informational only. Errors built without newPoolError have kind == pekUnknown.

PgProtocolError = object of PgConnectionError
Raised on PostgreSQL wire protocol violations. The connection stream is desynchronised after this error and must be torn down.
PgQueryError = object of PgError
  sqlState*: string          ## 5-char SQLSTATE code (e.g. "42P01"), empty if unavailable.
  severity*: string          ## e.g. "ERROR", "FATAL"
  detail*: string            ## DETAIL field, empty if not present.
  hint*: string              ## HINT field, empty if not present.
  fields*: seq[ErrorField] ## All raw ErrorResponse fields as sent by the server, including any not
                           ## covered by the named accessors below.

SQL execution error reported by the server (ErrorResponse).

The most common fields are stored directly; everything else the server sent (schema/table/column/constraint name, error position, …) is kept verbatim in fields and exposed through the accessors below, such as constraintName and position.

PgStateError = object of PgError

An operation attempted on a connection that is alive but in the wrong state for it — most commonly a single connection used concurrently: a second query started while the first is still in flight finds the connection csBusy.

A programming error, not a connection failure: deliberately not a PgConnectionError, so reconnect loops will not spin on it. Give each concurrent caller its own connection (e.g. via a PgPool).

PgTimeoutError = object of PgConnectionError

Raised when an operation times out.

A timeout on a query/exec/copy/prepare/transaction marks the connection csClosed (the wire may be mid-exchange), hence PgConnectionError. waitNotification and an acquire timeout inside withTransactionDeadline / withTransactionRetryDeadline leave the connection usable; catch PgTimeoutError before PgConnectionError to tell them apart.

PgTypeError = object of PgError
Raised when the caller's data cannot be carried by the wire format: a value that will not convert to or from the requested Nim type, or one the protocol cannot encode (count past Int16, length past Int32, embedded NUL).
PoolErrorKind = enum
  pekUnknown, ## Default: a `PgPoolError` built without an explicit `kind`; do not
               ## treat as `pekClosed`.
  pekClosed,                ## The pool is permanently closed; retrying cannot succeed.
  pekAcquireTimeout, ## An acquire deadline elapsed (`acquireTimeout` or cluster fallback);
                      ## retrying later may succeed.
  pekQueueFull,             ## The waiter queue is full (`maxWaiters` bound); retrying later may succeed.
  pekConnectFailed, ## A connect attempt failed during acquire (underlying error in `parent`);
                     ## retrying may succeed.
  pekConfigFault, ## The pool's `connConfig` can never connect: a connect raised
                   ## `PgConfigError` (preserved as `parent`). Retrying cannot succeed, so
                   ## the pool stops opening connections and every later acquire that needs
                   ## one fails with this kind without dialing.
  pekBatchFailed,           ## A pipelined batch was unservable; no connection was acquired.
  pekDefectWrapped ## A user-code `Defect` (body/release block or session reset) wrapped to
                   ## cross an async boundary; preserved as `parent`.
Machine-readable category of a PgPoolError.
ProtocolError {....deprecated: "use PgProtocolError".} = PgProtocolError
Deprecated: use PgProtocolError
Deprecated alias for PgProtocolError, kept for backwards compatibility.

Procs

func columnName(e: ref PgQueryError): string {....raises: [], tags: [], forbids: [].}
Column the error refers to.
func constraintName(e: ref PgQueryError): string {....raises: [], tags: [],
    forbids: [].}
Constraint the error refers to (e.g. the violated unique index).
func dataTypeName(e: ref PgQueryError): string {....raises: [], tags: [],
    forbids: [].}
Data type the error refers to.
func errorField(e: ref PgQueryError; code: char): string {....raises: [], tags: [],
    forbids: [].}
Raw ErrorResponse field by single-char code, "" if not present.
func getErrorField(fields: seq[ErrorField]; code: char): string {....raises: [],
    tags: [], forbids: [].}
Get the value of an error field by its single-char code (e.g. 'M' for message).
func internalPosition(e: ref PgQueryError): int {....raises: [], tags: [],
    forbids: [].}
Like position but for internalQuery, 0 if not reported.
func internalQuery(e: ref PgQueryError): string {....raises: [], tags: [],
    forbids: [].}
Text of the internally-generated query that failed (e.g. inside a function).
func isCheckViolation(e: ref PgQueryError): bool {....raises: [], tags: [],
    forbids: [].}
func isDeadlockDetected(e: ref PgQueryError): bool {....raises: [], tags: [],
    forbids: [].}
func isExclusionViolation(e: ref PgQueryError): bool {....raises: [], tags: [],
    forbids: [].}
func isForeignKeyViolation(e: ref PgQueryError): bool {....raises: [], tags: [],
    forbids: [].}
func isIntegrityConstraintViolation(e: ref PgQueryError): bool {....raises: [],
    tags: [], forbids: [].}
Any SQLSTATE in class 23 (integrity constraint violation).
func isNotNullViolation(e: ref PgQueryError): bool {....raises: [], tags: [],
    forbids: [].}
func isQueryCanceled(e: ref PgQueryError): bool {....raises: [], tags: [],
    forbids: [].}
func isSerializationFailure(e: ref PgQueryError): bool {....raises: [], tags: [],
    forbids: [].}
func isUniqueViolation(e: ref PgQueryError): bool {....raises: [], tags: [],
    forbids: [].}
func position(e: ref PgQueryError): int {....raises: [], tags: [], forbids: [].}
1-based character index into the original query where the error occurred, 0 if the server did not report a position.
func schemaName(e: ref PgQueryError): string {....raises: [], tags: [], forbids: [].}
Schema containing the object the error refers to.
func tableName(e: ref PgQueryError): string {....raises: [], tags: [], forbids: [].}
Table the error refers to.
func where(e: ref PgQueryError): string {....raises: [], tags: [], forbids: [].}
Context call stack (PL/pgSQL traceback etc.).

Templates

template newPoolError(errKind: PoolErrorKind; message: string;
                      parentErr: ref Exception = nil): untyped
Create a PgPoolError with the given errKind (see PoolErrorKind).