Source: https://gres.monicz.dev/guide/bulk/

# 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`](https://gres.monicz.dev/guide/bulk/#stream-query-results) |
| Read columns for PyArrow, Polars, pandas, or DuckDB | [`stream_arrow`](https://gres.monicz.dev/guide/bulk/#stream-arrow-record-batches) |
| Load Python records | [`copy_from_rows`](https://gres.monicz.dev/guide/bulk/#import-python-rows-with-binary-copy) |
| Load Arrow, Polars, or pandas data | [`copy_from_arrow`](https://gres.monicz.dev/guide/bulk/#import-arrow-batches-with-binary-copy) |
| Transfer raw CSV, text, or binary `COPY` bytes | [`copy_in` and `copy_out`](https://gres.monicz.dev/guide/bulk/#copy-input-and-output) |

## Stream query results

```python
# 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](https://gres.monicz.dev/guide/queries/#row-shapes) as `fetch_all` and holds the session until the `async with` block exits.
- Without `fetch_size`, PostgreSQL runs the query to completion; exiting early drains unread rows within `cleanup_timeout` or retires the session.
- Pass `fetch_size=n` to use a resumable portal when you may break early and keep the transaction open.
- Breaking early from `INSERT ... RETURNING` does not cancel the insert; wrap in `transaction()` when downstream success governs commit.
- Passing `timeout=` bounds the entire stream (including consumer pauses); omitting it applies `operation_timeout` per read.

## Stream Arrow record batches

```python
# 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.schema` is available immediately on context entry, even for empty results. Delivered batches outlive the connection.
- `fetch_size` controls portal row fetches, not byte size.
- `schema=` overrides the whole projection schema or maps column names to Arrow types/fields from [arro3](https://kylebarron.dev/arro3/latest/), PyArrow, or any [Arrow PyCapsule](https://arrow.apache.org/docs/format/CDataInterface/PyCapsuleInterface.html) provider. See [Arrow column types](https://gres.monicz.dev/guide/types/#arrow-column-types) and [GeoArrow](https://gres.monicz.dev/guide/spatial/#geoarrow-and-copy).

Consuming batches in downstream libraries:

- [PyArrow](https://arrow.apache.org/docs/python/): `pyarrow.record_batch(batch)`
- [Polars](https://docs.pola.rs/): `polars.DataFrame(batch)`
- pandas: `pyarrow.record_batch(batch).to_pandas(types_mapper=pandas.ArrowDtype)` (preserves nullable `int64`)
- [DuckDB](https://duckdb.org/docs/): register an `arro3.core.Table` built from the batches

Keep original batches when copying back into PostgreSQL so PostgreSQL/GeoArrow field metadata is preserved.

## Import Python rows with binary COPY

```python
# 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 in `columns` order.
- 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](https://gres.monicz.dev/guide/types/#everyday-types). Because binary `COPY` bypasses server text parsing, Gres parses `str` inputs for non-text columns (UUIDs, numbers, PostgreSQL text forms, and ISO 8601 `T`/`Z` timestamps) locally, raising `EncodingError` on invalid text before sending.
- Gres pulls records on the calling task once PostgreSQL accepts the `COPY` and encodes each row before pulling the next, so a producer may reuse a mutable record.
- Atomic as a single `COPY` statement: standalone calls commit their own transaction; inside a transaction, the enclosing transaction commits.

## Import Arrow batches with binary COPY

```python
# 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 `table` is a single table name (including literal dots); use `Identifier('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 from `stream_arrow` to preserve lower bounds. `uuid` columns accept `arrow.uuid` or UUID strings.
- Standalone calls commit before returning `Command`; `timeout` covers checkout, `BEGIN`, transfer, and `COMMIT` (`timeout=None` disables 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

```python
# 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 to `COPY ... FROM STDIN` (pulled on demand; chunks may split rows or UTF-8 characters). A producer exception aborts the `COPY` and re-raises.
- `copy_out(sql)` yields owning `bytes` chunks. Exiting early drains a bounded amount or discards the connection; pass `timeout=` only to bound the whole export.
- `COPY` rejects bound parameters; substitute identifiers and constants with `Identifier`, `Query`, and `Literal` (e.g. `copy_out('COPY (SELECT $n::int) TO STDOUT', {'n': Literal(7)})`; `copy_in` accepts the same via `params=`).

### Export JSON with COPY

PostgreSQL 19 adds `FORMAT json` (newline-delimited JSON objects, or one JSON array with `FORCE_ARRAY`) to [`COPY TO`](https://www.postgresql.org/docs/19/sql-copy.html). `COPY FROM` does not accept JSON.

```python
# 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()]
```
