async_postgres/pg_client/copy

Search:
Group by:

COPY IN / COPY OUT via the simple-query protocol, including the streaming copyInStream / copyOutStream variants that move data through callbacks, and copyInRows, which writes typed rows in binary COPY.

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

Types

CopyInRowsCallback[T] = proc (): Future[seq[T]] {....gcsafe.}
Callback supplying the next batch of rows to copyInRowsStream. Return an empty seq to finish.

Procs

proc copyIn(conn: PgConnection; sql: string; data: openArray[byte];
            timeout: Duration = ZeroDuration): Future[CommandResult] {.
    ...raises: [Exception, ValueError, CatchableError],
    tags: [RootEffect, TimeEffect, WriteIOEffect], forbids: [].}
Execute COPY ... FROM STDIN with a single contiguous buffer. Slices data into CopyData messages internally. Returns the command result (e.g. "COPY 5").
proc copyIn(conn: PgConnection; sql: string; data: seq[byte];
            timeout: Duration = ZeroDuration): Future[CommandResult] {.
    ...stackTrace: false, raises: [Exception, ValueError, CatchableError],
    tags: [RootEffect, TimeEffect, WriteIOEffect], forbids: [].}

Execute COPY ... FROM STDIN with a single contiguous seq[byte]. Avoids the copy that the openArray[byte] overload performs.

A server-side abort (constraint violation, disk full, …) is detected between batches, so a doomed COPY stops streaming early and raises the server's PgQueryError instead of sending the whole input first.

A statement that is not COPY ... FROM STDIN (e.g. COPY ... TO STDOUT or a plain query) raises PgQueryError instead of silently succeeding without sending any data.

proc copyIn(conn: PgConnection; sql: string; data: seq[seq[byte]];
            timeout: Duration = ZeroDuration): Future[CommandResult] {.
    ...raises: [PgProtocolError, Exception, ValueError, CatchableError],
    tags: [RootEffect, TimeEffect, WriteIOEffect], forbids: [].}
Execute COPY ... FROM STDIN via simple query protocol. Concatenates chunks and delegates to the seq[byte] overload. Returns the command result (e.g. "COPY 5").
proc copyIn(conn: PgConnection; sql: string; data: string;
            timeout: Duration = ZeroDuration): Future[CommandResult] {.
    ...raises: [PgProtocolError, Exception, ValueError, CatchableError],
    tags: [RootEffect, TimeEffect, WriteIOEffect], forbids: [].}
Execute COPY ... FROM STDIN with text data as a string. Converts to bytes internally; avoids manual toOpenArrayByte.
proc copyInRows[T: object | tuple | ref object](conn: PgConnection;
    table: string; rows: sink seq[T]; columns: openArray[string] = [];
    schema = ""; timeout: Duration = ZeroDuration): Future[CommandResult]

Write rows to table with COPY ... FROM STDIN (FORMAT binary); affectedRows is the number of rows written.

Each field goes to the column its name matches by to's rules (createdAt writes created_at; pgColumn, pgSkip). Without columns every field must match a column; with them, each column must be matched and other fields are skipped. An unnamed tuple writes columns by position. table and schema are quoted: pass a schema in schema, not as "schema.table".

Binary COPY would read a mismatched payload as another value, so each field's type is checked against a Describe of the target first; outside a transaction both run in one. A field of type F may be written to:

  • int / int16 / int32 / int64: smallint, integer, bigint or numeric; a value out of the column's range fails.
  • float32 / float64: real or double precision; a value that overflows real or underflows to 0 fails.
  • bool: boolean. seq[byte]: bytea.
  • string: text, varchar, char(n), name, json, jsonb, xml, uuid (its text form) or numeric (a plain decimal).
  • DateTime: timestamp (its UTC wall clock), timestamptz (its instant, whatever the session TimeZone) or date (its UTC calendar day).
  • JsonNode: json or jsonb.
  • an enum without a toPgBinaryParam: its $ label (not its toPgParam), to text, varchar, char(n), name or an enum type.
  • seq of an integer type or DateTime, or of Option of one: an array of any of the column types above for the element.
  • Option[F]: as F, none as NULL.
  • a type with a toPgBinaryParam: a column of the type it encodes, any text type for a text type, any text array type for a text array.
  • a distinct type without one (a domain): as its base type, not through its toPgParam.

Composite types, arrays of enums, hstore and arrays of ranges are not supported, nor are strings for types outside PostgreSQL's own.

A mismatch raises PgTypeError before the COPY. A value that cannot be written (out of range, uninitialized DateTime, nil row) aborts it with CopyFail, writing no row and leaving the connection usable, and raises PgTypeError naming the row, field and column. On timeout the connection is retired unless the wire had settled, and always inside a transaction this call opened.

type User = object
  id {.pgSkip.}: int64
  name: string
  createdAt: DateTime

let res = await conn.copyInRows("users", users)
echo res.affectedRows
proc copyInRowsStream[T: object | tuple | ref object](conn: PgConnection;
    table: string; callback: CopyInRowsCallback[T];
    columns: openArray[string] = []; schema = "";
    timeout: Duration = ZeroDuration): Future[CommandResult]

copyInRows, pulling rows from callback in batches until it returns an empty one, gathered into sends of about 256 KiB.

callback is first called once the columns are checked and the COPY has started. If it raises, the COPY is aborted as for an unwritable value and its error is raised; row indexes in errors count across batches.

proc copyInStream(conn: PgConnection; sql: string; callback: CopyInCallback;
                  timeout: Duration = ZeroDuration): Future[CopyInInfo] {.
    ...stackTrace: false, raises: [Exception, ValueError, CatchableError],
    tags: [RootEffect, TimeEffect, WriteIOEffect], forbids: [].}

Execute COPY ... FROM STDIN via simple query protocol, streaming data from callback. The callback is called repeatedly; returning an empty seq[byte] signals EOF. If the callback raises, CopyFail is sent and the connection returns to csReady.

Oversized chunk raises PgTypeError via CopyFail.

If the server aborts the COPY (constraint violation, disk full, …) while the client is still streaming, the error is detected between batches and the COPY stops pulling from callback instead of draining it in full; the server's PgQueryError is then raised. Detection is best-effort — an error arriving mid-batch only surfaces after the current batch — so a doomed COPY is bounded by one batch of extra streaming, not the whole input. On timeout, the connection is retired (csClosed) unless the wire had settled (asyncdispatch always retires: the timed-out op stays on the socket).

A statement that is not COPY ... FROM STDIN raises PgQueryError instead of silently succeeding without pulling from callback.

proc copyOut(conn: PgConnection; sql: string; timeout: Duration = ZeroDuration): Future[
    CopyResult] {....stackTrace: false,
                  raises: [Exception, ValueError, CatchableError],
                  tags: [RootEffect, TimeEffect, WriteIOEffect], forbids: [].}

Execute COPY ... TO STDOUT via simple query protocol. Collects all CopyData messages and returns them in a CopyResult, so the whole output is held in memory; use copyOutStream for large exports. On timeout, the connection is retired (csClosed) unless the wire had settled (asyncdispatch always retires: the timed-out op stays on the socket).

A statement that is not COPY ... TO STDOUT raises PgQueryError; a COPY ... FROM STDIN statement is aborted with CopyFail instead of deadlocking.

proc copyOutStream(conn: PgConnection; sql: string; callback: CopyOutCallback;
                   timeout: Duration = ZeroDuration): Future[CopyOutInfo] {.
    ...stackTrace: false, raises: [Exception, ValueError, CatchableError],
    tags: [RootEffect, TimeEffect, WriteIOEffect], forbids: [].}

Execute COPY ... TO STDOUT via simple query protocol, streaming each CopyData chunk through callback. The callback is awaited, providing natural TCP backpressure.

If the callback raises, COPY OUT has no client->server abort (CopyFail is COPY IN only), so the remaining CopyData is drained up to ReadyForQuery to keep the protocol in sync; the connection returns to csReady and stays usable, and the callback's error is then re-raised. Because the server still streams the whole result before ReadyForQuery, a callback failure on an early chunk of a large COPY can mean draining a substantial amount of data before the error surfaces — cancel the query out-of-band (cancel) if you need to abort a large COPY OUT promptly. On timeout the connection is retired (csClosed) unless the wire had settled (asyncdispatch always retires: the timed-out op stays on the socket).

A statement that is not COPY ... TO STDOUT raises PgQueryError without invoking callback; COPY ... FROM STDIN is aborted with CopyFail instead of deadlocking.

Templates

template makeCopyInRowsCallback(T: typedesc; body: untyped): CopyInRowsCallback[
    T]
Create a CopyInRowsCallback[T] that works with both asyncdispatch and chronos. body must evaluate to seq[T]; an empty one finishes.
var page = 0
let cb = makeCopyInRowsCallback(User):
  inc page
  await fetchUsers(page) # empty past the last page
discard await conn.copyInRowsStream("users", cb)