Streaming, Arrow and COPY¶
Use streaming and COPY when results or loads shouldn't be materialized as Python lists; memory stays bounded by a batch or chunk.
| Task | Method |
|---|---|
| Read rows incrementally | stream |
| Read columns for PyArrow, Polars, pandas, or DuckDB | stream_arrow |
| Load Python records | copy_from_rows |
| Load Arrow, Polars, or pandas data | copy_from_arrow |
Transfer raw CSV, text, or binary COPY bytes |
copy_in and copy_out |
Stream query results¶
# Partial: db is an open connection and station(id int, name text) exists.
async with db.stream('SELECT id, name FROM station ORDER BY id') as rows:
async for row in rows:
print(row['id'], row['name'])
- Accepts the same
row=shapes asfetch_alland holds the session until theasync withblock exits. - Without
fetch_size, PostgreSQL runs the query to completion; exiting early drains unread rows withincleanup_timeoutor retires the session. - Pass
fetch_size=nto use a resumable portal when you may break early and keep the transaction open. - Breaking early from
INSERT ... RETURNINGdoes not cancel the insert; wrap intransaction()when downstream success governs commit. - Passing
timeout=bounds the entire stream (including consumer pauses); omitting it appliesoperation_timeoutper read.
Stream Arrow record batches¶
# Partial: db is an open connection and
# reading(station int, at timestamptz, value float8) exists.
import polars as pl
async with db.stream_arrow('SELECT station, at, value FROM reading') as stream:
frame = pl.concat([pl.DataFrame(batch) async for batch in stream])
stream_arrow yields owning arro3.core.RecordBatch instances without constructing Python rows.
stream.schemais available immediately on context entry, even for empty results. Delivered batches outlive the connection.fetch_sizecontrols portal row fetches, not byte size.schema=overrides the whole projection schema or maps column names to Arrow types/fields from arro3, PyArrow, or any Arrow PyCapsule provider. See Arrow column types and GeoArrow.
Consuming batches in downstream libraries:
- PyArrow:
pyarrow.record_batch(batch) - Polars:
polars.DataFrame(batch) - pandas:
pyarrow.record_batch(batch).to_pandas(types_mapper=pandas.ArrowDtype)(preserves nullableint64) - DuckDB: register an
arro3.core.Tablebuilt from the batches
Keep original batches when copying back into PostgreSQL so PostgreSQL/GeoArrow field metadata is preserved.
Import Python rows with binary COPY¶
# Partial: db is an open connection and
# reading(station int, at timestamptz, value float8) exists.
import datetime as dt
now = dt.datetime(2026, 1, 1, tzinfo=dt.UTC)
done = await db.copy_from_rows(
'reading',
[(1, now, 2.5), (1, now + dt.timedelta(hours=1), None)],
columns=['station', 'at', 'value'],
)
assert done.row_count == 2
copy_from_rows takes a list, iterable, or async iterable of records and a required columns= sequence naming the destination columns:
- Sequences (
tuple,list) supply values by position incolumnsorder. - Mappings supply values by key.
- Other objects (
NamedTuple, dataclass, attrs, pydantic, msgspec) supply values by attribute name in any field order.
Omitted table columns use their defaults; None is SQL NULL.
- Values follow parameter conversions. Because binary
COPYbypasses server text parsing, Gres parsesstrinputs for non-text columns (UUIDs, numbers, PostgreSQL text forms, and ISO 8601T/Ztimestamps) locally, raisingEncodingErroron invalid text before sending. - Gres pulls records on the calling task once PostgreSQL accepts the
COPYand encodes each row before pulling the next, so a producer may reuse a mutable record. - Atomic as a single
COPYstatement: standalone calls commit their own transaction; inside a transaction, the enclosing transaction commits.
Import Arrow batches with binary COPY¶
# Partial: continues the examples above; reading_archive has the same columns as reading.
done = await db.copy_from_arrow('reading_archive', frame)
assert done.row_count == frame.height
copy_from_arrow accepts a record batch, table/stream exporting the Arrow C stream interface, iterable of batches, or async iterable (such as an open stream_arrow).
- Source fields match table columns by name in any order (omitted columns keep defaults). Pass optional
columns=[...]to write a subset of source fields. - A string
tableis a single table name (including literal dots); useIdentifier('app', 'events')for schema-qualified tables. - Struct fields match composite attributes by name. Array columns accept
list/large_list(rectangular nested lists; leaf nulls allowed, intermediate nulls rejected) or the array struct fromstream_arrowto preserve lower bounds.uuidcolumns acceptarrow.uuidor UUID strings. - Standalone calls commit before returning
Command;timeoutcovers checkout,BEGIN, transfer, andCOMMIT(timeout=Nonedisables it).
Gres buffers one source batch at a time; keep batch buffers immutable until the next batch is requested or transfer ends. Synchronous iterables run on a worker thread (use an async iterable if production requires the event loop); after cancellation, aclose() waits up to cleanup_timeout for any running sync callback to exit.
COPY input and output¶
# Partial: source and target are open connections, and station exists in both databases.
async with source.copy_out('COPY station TO STDOUT (FORMAT binary)') as chunks:
await target.copy_in('COPY station FROM STDIN (FORMAT binary)', chunks)
copy_in(sql, chunks)feeds an iterable or async iterable of byte buffers toCOPY ... FROM STDIN(pulled on demand; chunks may split rows or UTF-8 characters). A producer exception aborts theCOPYand re-raises.copy_out(sql)yields owningbyteschunks. Exiting early drains a bounded amount or discards the connection; passtimeout=only to bound the whole export.COPYrejects bound parameters; substitute identifiers and constants withIdentifier,Query, andLiteral(e.g.copy_out('COPY (SELECT $n::int) TO STDOUT', {'n': Literal(7)});copy_inaccepts the same viaparams=).
Export JSON with COPY¶
PostgreSQL 19 adds FORMAT json (newline-delimited JSON objects, or one JSON array with FORCE_ARRAY) to COPY TO. COPY FROM does not accept JSON.
# Partial: db is an open connection to PostgreSQL 19 and station(id int, name text) exists.
import json
output = bytearray()
async with db.copy_out('COPY station TO STDOUT (FORMAT json)') as chunks:
async for chunk in chunks:
output += chunk
stations = [json.loads(line) for line in output.splitlines()]