Source: https://gres.monicz.dev/api/queries/

# Queries and results

`Connection`, `Pool`, and `Transaction` all provide the [`Executor`](https://gres.monicz.dev/api/queries/#gres.Executor "Executor") methods. [Queries and transactions](https://gres.monicz.dev/guide/queries/) shows them in use.

## Executor

SQL execution interface shared by pools, connections, and transactions.

Accept an `Executor` when a helper issues statements without owning commit or
close authority. Gres provides every implementation; the class is not
constructed directly.

Positional parameters use `$1`, `$2`, ... and named parameters use `$name`
with a mapping. Common keyword options across query methods:

- `row`: Result shape — `dict` (default), `tuple`, a typed `tuple[...]` /
  `TypedDict` / `NamedTuple` / dataclass, `scalar(...)`, or a callable.
- `prepare`: Override automatic statement preparation (`True` / `False`);
  `None` uses the connection's `auto_prepare` setting.
- `decoding`: Per-call `Decoding` overrides; unspecified fields inherit the
  connection policy.
- `adapters`: Sequence of `EnumBinding`, `CompositeBinding`, `Adapter`, or
  `Codec` overrides replacing the connection's adapters for this call.
- `column_adapters`: Mapping of result column name or zero-based index to a
  decoding binding for this call.
- `timeout`: Monotonic budget in seconds. `INHERIT` (default) uses the
  connection or pool `operation_timeout`; `None` disables the deadline.

### invalidate\_types

```python
invalidate_types() -> None
```

Discard cached type metadata after a committed type migration. No SQL is sent.

### execute `async`

```python
execute(
    sql: Source | Query,
    params: Bindings | None = None,
    *,
    prepare: bool | None = None,
    adapters: Sequence[Binding] | None = None,
    timeout: float | InheritType | None = INHERIT,
) -> Command
```

Execute trusted SQL and discard result rows; return the last command.

### transaction

```python
transaction(
    *,
    isolation: IsolationLevel | None = None,
    read_only: bool | None = None,
    deferrable: bool | None = None,
    timeout: float | None = None,
) -> Transaction
```

Create a transaction context; `BEGIN` runs on entry, not construction.

Entered on a connection or transaction that already has a transaction open,
this creates a savepoint of the innermost open transaction: it can roll back
alone and commits with the enclosing transaction. A savepoint keeps the
enclosing isolation level and access mode, so passing `isolation`,
`read_only`, or `deferrable` raises `ConfigurationError`.

`timeout` sets a monotonic deadline in seconds for the whole transaction;
`None` (default) sets no transaction deadline and does not inherit
`operation_timeout`. A savepoint's `timeout` can only shorten the enclosing
deadline. A pool's transaction checks out its own session.

### execute\_many `async`

```python
execute_many(
    sql: Source | Query,
    parameter_sets: Iterable[Bindings] | AsyncIterable[Bindings],
    *,
    prepare: bool | None = None,
    adapters: Sequence[Binding] | None = None,
    timeout: float | InheritType | None = INHERIT,
) -> BatchResult
```

Run one statement once per parameter set, discarding any rows.

The batch is atomic. Outside a transaction it runs in its own transaction, which
commits only if every execution succeeds. Inside a transaction it runs in that
transaction; a failure after the first execution was sent leaves the transaction
to be rolled back. Lazy producers advance only after the previous execution is
acknowledged. `prepare` overrides automatic statement preparation for this batch.

### copy\_from\_arrow `async`

```python
copy_from_arrow(
    table: str | Identifier,
    source: ArrowStreamExportable
    | ArrowArrayExportable
    | Iterable[ArrowArrayExportable]
    | AsyncIterable[ArrowArrayExportable],
    *,
    columns: Sequence[str] | None = None,
    timeout: float | InheritType | None = INHERIT,
) -> Command
```

Write Arrow columns into a table with binary COPY; a standalone call commits its own transaction.

The source is a record batch, a table or reader exporting an Arrow C stream, an
iterable of record batches such as a list, or an async iterable of record batches
such as an open `stream_arrow` result. A synchronous iterable is consumed on a
worker thread, one batch at a time. Keep each batch's buffers unchanged until
Gres requests the next batch or the transfer ends.

Each source field fills the table column of the same name. `columns` selects
which fields to write; by default every field of the source is written. An
empty source that advertises no schema writes nothing and reports `COPY 0`.

### copy\_from\_rows `async`

```python
copy_from_rows(
    table: str | Identifier,
    rows: Iterable[object] | AsyncIterable[object],
    *,
    columns: Sequence[str],
    adapters: Sequence[Binding] | None = None,
    timeout: float | InheritType | None = INHERIT,
) -> Command
```

Stream rows into the selected columns with binary COPY; a standalone call commits its own transaction.

A tuple, list or other sequence supplies values by position, and a mapping by key.
Any other record, such as a NamedTuple, dataclass, attrs class, pydantic model or
msgspec struct, supplies them by attribute name, so its field order does not matter.

### copy\_in `async`

```python
copy_in(
    sql: Source | Query,
    chunks: Iterable[_Buffer] | AsyncIterable[_Buffer],
    *,
    params: Bindings | None = None,
    adapters: Sequence[Binding] | None = None,
    timeout: float | InheritType | None = INHERIT,
) -> Command
```

Feed buffers to one COPY FROM STDIN statement. The producer starts only after the server requests data.

### copy\_out `async`

```python
copy_out(
    sql: Source | Query,
    params: Bindings | None = None,
    *,
    adapters: Sequence[Binding] | None = None,
    timeout: float | InheritType | None = INHERIT,
) -> AsyncGenerator[AsyncIterator[bytes], None]
```

Stream the bytes of a single COPY TO STDOUT statement within an async context.

### fetch\_all `async`

```python
fetch_all(
    sql: Source | Query,
    params: Bindings | None = None,
    *,
    prepare: bool | None = None,
    decoding: Decoding | None = None,
    adapters: Sequence[Binding] | None = None,
    column_adapters: ColumnBindings | None = None,
    timeout: float | InheritType | None = ...,
) -> list[dict[str, object]]
```

```python
fetch_all(
    sql: Source | Query,
    params: Bindings | None = None,
    *,
    prepare: bool | None = None,
    row: type[_N],
    decoding: Decoding | None = None,
    adapters: Sequence[Binding] | None = None,
    column_adapters: ColumnBindings | None = None,
    timeout: float | InheritType | None = ...,
) -> list[_N]
```

```python
fetch_all(
    sql: Source | Query,
    params: Bindings | None = None,
    *,
    prepare: bool | None = None,
    row: type[tuple[*_Ts,]],
    decoding: Decoding | None = None,
    adapters: Sequence[Binding] | None = None,
    column_adapters: ColumnBindings | None = None,
    timeout: float | InheritType | None = ...,
) -> list[tuple[*_Ts,]]
```

```python
fetch_all(
    sql: Source | Query,
    params: Bindings | None = None,
    *,
    prepare: bool | None = None,
    row: type[dict[str, _T]],
    decoding: Decoding | None = None,
    adapters: Sequence[Binding] | None = None,
    column_adapters: ColumnBindings | None = None,
    timeout: float | InheritType | None = ...,
) -> list[dict[str, _T]]
```

```python
fetch_all(
    sql: Source | Query,
    params: Bindings | None = None,
    *,
    prepare: bool | None = None,
    row: _Scalar[_T] | Callable[..., _T],
    decoding: Decoding | None = None,
    adapters: Sequence[Binding] | None = None,
    column_adapters: ColumnBindings | None = None,
    timeout: float | InheritType | None = ...,
) -> list[_T]
```

```python
fetch_all(
    sql: Source | Query,
    params: Bindings | None = None,
    *,
    prepare: bool | None = None,
    row: Any = dict,
    decoding: Decoding | None = None,
    adapters: Sequence[Binding] | None = None,
    column_adapters: ColumnBindings | None = None,
    timeout: float | InheritType | None = INHERIT,
) -> list[Any]
```

Return every row in server order.

### fetch\_one `async`

```python
fetch_one(
    sql: Source | Query,
    params: Bindings | None = None,
    *,
    prepare: bool | None = None,
    decoding: Decoding | None = None,
    adapters: Sequence[Binding] | None = None,
    column_adapters: ColumnBindings | None = None,
    timeout: float | InheritType | None = ...,
) -> dict[str, object]
```

```python
fetch_one(
    sql: Source | Query,
    params: Bindings | None = None,
    *,
    prepare: bool | None = None,
    row: type[_N],
    decoding: Decoding | None = None,
    adapters: Sequence[Binding] | None = None,
    column_adapters: ColumnBindings | None = None,
    timeout: float | InheritType | None = ...,
) -> _N
```

```python
fetch_one(
    sql: Source | Query,
    params: Bindings | None = None,
    *,
    prepare: bool | None = None,
    row: type[tuple[*_Ts,]],
    decoding: Decoding | None = None,
    adapters: Sequence[Binding] | None = None,
    column_adapters: ColumnBindings | None = None,
    timeout: float | InheritType | None = ...,
) -> tuple[*_Ts,]
```

```python
fetch_one(
    sql: Source | Query,
    params: Bindings | None = None,
    *,
    prepare: bool | None = None,
    row: type[dict[str, _T]],
    decoding: Decoding | None = None,
    adapters: Sequence[Binding] | None = None,
    column_adapters: ColumnBindings | None = None,
    timeout: float | InheritType | None = ...,
) -> dict[str, _T]
```

```python
fetch_one(
    sql: Source | Query,
    params: Bindings | None = None,
    *,
    prepare: bool | None = None,
    row: _Scalar[_T] | Callable[..., _T],
    decoding: Decoding | None = None,
    adapters: Sequence[Binding] | None = None,
    column_adapters: ColumnBindings | None = None,
    timeout: float | InheritType | None = ...,
) -> _T
```

```python
fetch_one(
    sql: Source | Query,
    params: Bindings | None = None,
    *,
    prepare: bool | None = None,
    row: Any = dict,
    decoding: Decoding | None = None,
    adapters: Sequence[Binding] | None = None,
    column_adapters: ColumnBindings | None = None,
    timeout: float | InheritType | None = INHERIT,
) -> Any
```

Return exactly one row after command completion, or raise `CardinalityError`.

### fetch\_optional `async`

```python
fetch_optional(
    sql: Source | Query,
    params: Bindings | None = None,
    *,
    prepare: bool | None = None,
    decoding: Decoding | None = None,
    adapters: Sequence[Binding] | None = None,
    column_adapters: ColumnBindings | None = None,
    timeout: float | InheritType | None = ...,
) -> dict[str, object] | None
```

```python
fetch_optional(
    sql: Source | Query,
    params: Bindings | None = None,
    *,
    prepare: bool | None = None,
    row: type[_N],
    decoding: Decoding | None = None,
    adapters: Sequence[Binding] | None = None,
    column_adapters: ColumnBindings | None = None,
    timeout: float | InheritType | None = ...,
) -> _N | None
```

```python
fetch_optional(
    sql: Source | Query,
    params: Bindings | None = None,
    *,
    prepare: bool | None = None,
    row: type[tuple[*_Ts,]],
    decoding: Decoding | None = None,
    adapters: Sequence[Binding] | None = None,
    column_adapters: ColumnBindings | None = None,
    timeout: float | InheritType | None = ...,
) -> tuple[*_Ts,] | None
```

```python
fetch_optional(
    sql: Source | Query,
    params: Bindings | None = None,
    *,
    prepare: bool | None = None,
    row: type[dict[str, _T]],
    decoding: Decoding | None = None,
    adapters: Sequence[Binding] | None = None,
    column_adapters: ColumnBindings | None = None,
    timeout: float | InheritType | None = ...,
) -> dict[str, _T] | None
```

```python
fetch_optional(
    sql: Source | Query,
    params: Bindings | None = None,
    *,
    prepare: bool | None = None,
    row: _Scalar[_T] | Callable[..., _T],
    decoding: Decoding | None = None,
    adapters: Sequence[Binding] | None = None,
    column_adapters: ColumnBindings | None = None,
    timeout: float | InheritType | None = ...,
) -> _T | None
```

```python
fetch_optional(
    sql: Source | Query,
    params: Bindings | None = None,
    *,
    prepare: bool | None = None,
    row: Any = dict,
    decoding: Decoding | None = None,
    adapters: Sequence[Binding] | None = None,
    column_adapters: ColumnBindings | None = None,
    timeout: float | InheritType | None = INHERIT,
) -> Any
```

Return the only row, or `None` when the query returns no rows. Multiple rows raise `CardinalityError`.

### stream `async`

```python
stream(
    sql: Source | Query,
    params: Bindings | None = None,
    *,
    prepare: bool | None = None,
    decoding: Decoding | None = None,
    adapters: Sequence[Binding] | None = None,
    column_adapters: ColumnBindings | None = None,
    fetch_size: int | None = None,
    timeout: float | InheritType | None = ...,
) -> AbstractAsyncContextManager[AsyncIterator[dict[str, object]]]
```

```python
stream(
    sql: Source | Query,
    params: Bindings | None = None,
    *,
    prepare: bool | None = None,
    row: type[_N],
    decoding: Decoding | None = None,
    adapters: Sequence[Binding] | None = None,
    column_adapters: ColumnBindings | None = None,
    fetch_size: int | None = None,
    timeout: float | InheritType | None = ...,
) -> AbstractAsyncContextManager[AsyncIterator[_N]]
```

```python
stream(
    sql: Source | Query,
    params: Bindings | None = None,
    *,
    prepare: bool | None = None,
    row: type[tuple[*_Ts,]],
    decoding: Decoding | None = None,
    adapters: Sequence[Binding] | None = None,
    column_adapters: ColumnBindings | None = None,
    fetch_size: int | None = None,
    timeout: float | InheritType | None = ...,
) -> AbstractAsyncContextManager[AsyncIterator[tuple[*_Ts,]]]
```

```python
stream(
    sql: Source | Query,
    params: Bindings | None = None,
    *,
    prepare: bool | None = None,
    row: type[dict[str, _T]],
    decoding: Decoding | None = None,
    adapters: Sequence[Binding] | None = None,
    column_adapters: ColumnBindings | None = None,
    fetch_size: int | None = None,
    timeout: float | InheritType | None = ...,
) -> AbstractAsyncContextManager[AsyncIterator[dict[str, _T]]]
```

```python
stream(
    sql: Source | Query,
    params: Bindings | None = None,
    *,
    prepare: bool | None = None,
    row: _Scalar[_T] | Callable[..., _T],
    decoding: Decoding | None = None,
    adapters: Sequence[Binding] | None = None,
    column_adapters: ColumnBindings | None = None,
    fetch_size: int | None = None,
    timeout: float | InheritType | None = ...,
) -> AbstractAsyncContextManager[AsyncIterator[_T]]
```

```python
stream(
    sql: Source | Query,
    params: Bindings | None = None,
    *,
    prepare: bool | None = None,
    row: Any = dict,
    decoding: Decoding | None = None,
    adapters: Sequence[Binding] | None = None,
    column_adapters: ColumnBindings | None = None,
    fetch_size: int | None = None,
    timeout: float | InheritType | None = INHERIT,
) -> AsyncGenerator[AsyncIterator[Any], None]
```

Iterate a query inside an async context. A positive `fetch_size` requests a resumable portal.

### stream\_arrow `async`

```python
stream_arrow(
    sql: Source | Query,
    params: Bindings | None = None,
    *,
    prepare: bool | None = None,
    temporal: Literal['standard', 'exact'] = 'standard',
    geometry: Literal['geoarrow', 'exact'] = 'geoarrow',
    schema: ArrowSchemaExportable
    | Mapping[str, ArrowSchemaExportable]
    | None = None,
    adapters: Sequence[Binding] | None = None,
    fetch_size: int | None = None,
    timeout: float | InheritType | None = INHERIT,
) -> AsyncGenerator[ArrowStream, None]
```

Read owning Arrow record batches; the stream schema is available on context entry.

PostGIS columns arrive as GeoArrow: a column declared with one geometry kind uses
that kind's native layout, any other column `geoarrow.wkb`, with the CRS of the
column's SRID (or of its first non-NULL value when the column declares none).
A value in another CRS raises `DecodingError`. `geometry='exact'` keeps each
value's EWKB and SRID and needs neither gometry nor `spatial_ref_sys`. `schema`
replaces the whole result schema or, as a mapping, individual columns.

## Transaction

A transaction context; inside another transaction it is a savepoint.

Obtained from `Executor.transaction()`; not constructed directly. Statements
on the transaction, on its connection, or on an enclosing transaction all
run in the innermost active transaction until it ends.

### outcome `property`

```python
outcome: Outcome | None
```

How the transaction ended, or `None` until it ends.

`'committed'`, `'rolled_back'`, `'released'` for a savepoint, or `'unknown'`
while a lost commit acknowledgment is still awaited.

### prepare

```python
prepare(
    sql: Source | Query,
    *,
    decoding: Decoding | None = None,
    adapters: Sequence[Binding] | None = None,
    column_adapters: ColumnBindings | None = None,
    timeout: float | InheritType | None = ...,
) -> AbstractAsyncContextManager[PreparedStatement[dict[str, object]]]
```

```python
prepare(
    sql: Source | Query,
    *,
    row: type[_N],
    decoding: Decoding | None = None,
    adapters: Sequence[Binding] | None = None,
    column_adapters: ColumnBindings | None = None,
    timeout: float | InheritType | None = ...,
) -> AbstractAsyncContextManager[PreparedStatement[_N]]
```

```python
prepare(
    sql: Source | Query,
    *,
    row: type[tuple[*_Ts,]],
    decoding: Decoding | None = None,
    adapters: Sequence[Binding] | None = None,
    column_adapters: ColumnBindings | None = None,
    timeout: float | InheritType | None = ...,
) -> AbstractAsyncContextManager[PreparedStatement[tuple[*_Ts,]]]
```

```python
prepare(
    sql: Source | Query,
    *,
    row: type[dict[str, _T]],
    decoding: Decoding | None = None,
    adapters: Sequence[Binding] | None = None,
    column_adapters: ColumnBindings | None = None,
    timeout: float | InheritType | None = ...,
) -> AbstractAsyncContextManager[PreparedStatement[dict[str, _T]]]
```

```python
prepare(
    sql: Source | Query,
    *,
    row: _Scalar[_T] | Callable[..., _T],
    decoding: Decoding | None = None,
    adapters: Sequence[Binding] | None = None,
    column_adapters: ColumnBindings | None = None,
    timeout: float | InheritType | None = ...,
) -> AbstractAsyncContextManager[PreparedStatement[_T]]
```

```python
prepare(
    sql: Source | Query,
    *,
    row: Any = dict,
    decoding: Decoding | None = None,
    adapters: Sequence[Binding] | None = None,
    column_adapters: ColumnBindings | None = None,
    timeout: float | InheritType | None = INHERIT,
) -> AbstractAsyncContextManager[PreparedStatement[Any]]
```

Prepare one fixed-signature query on this held session. The context closes its server statement.

### rollback `async`

```python
rollback() -> None
```

Roll back now; the context exit then does nothing. Repeating a rollback is a no-op.

## PreparedStatement

A fixed-signature PostgreSQL query owned by its `prepare()` context and physical session.

### fetch\_one `async`

```python
fetch_one(
    params: Bindings | None = None, *, timeout: float | InheritType | None = ...
) -> _R
```

Return exactly one row, or raise `CardinalityError` after command completion.

### fetch\_optional `async`

```python
fetch_optional(
    params: Bindings | None = None, *, timeout: float | InheritType | None = ...
) -> _R | None
```

Return one row or `None`; multiple rows raise `CardinalityError`.

### fetch\_all `async`

```python
fetch_all(
    params: Bindings | None = None, *, timeout: float | InheritType | None = ...
) -> list[_R]
```

Return all rows in order using the prepared projection.

### execute `async`

```python
execute(
    params: Bindings | None = None, *, timeout: float | InheritType | None = ...
) -> Command
```

Execute once and return the command tag, discarding result rows.

## scalar

```python
scalar() -> _Scalar[object]
```

```python
scalar(target: TypeForm[_T_co]) -> _Scalar[_T_co]
```

```python
scalar(target: Callable[..., _T_co]) -> _Scalar[_T_co]
```

```python
scalar(target: Any = object) -> _Scalar[Any]
```

Select one decoded column, checked against a type form or passed to a factory.

Built-in numeric, boolean and decimal targets accept another representation only when
the value converts without loss: a numeric `sum()` becomes `int` when integral, and
`SHOW` text parses with PostgreSQL's own input rules. Other classes, such as enums,
are constructed from the decoded value. Explicit factories receive every value,
including NULL.

## Command `dataclass`

```python
Command(tag: str)
```

PostgreSQL's final completion tag, not necessarily a transaction commit.

### tag `instance-attribute`

```python
tag: str
```

### row\_count `property`

```python
row_count: int | None
```

Affected row count parsed from `tag`, or `None` when the command reports no count.

## BatchResult `dataclass`

```python
BatchResult(commands: int, row_count: int | None)
```

Acknowledged executions and summed row count, or `None` for commands without a count. Not a commit receipt.

### commands `instance-attribute`

```python
commands: int
```

### row\_count `instance-attribute`

```python
row_count: int | None
```

## ArrowStream

Arrow record batches of one query, read inside its `async with` block.

Obtained from `Executor.stream_arrow()`; not constructed directly. The
schema and any batches already delivered remain valid after the block exits.

### schema `property`

```python
schema: Schema
```

The PostgreSQL projection's Arrow schema, including for an empty result.

## Notification

```python
Notification(channel: str, payload: str, pid: int)
```

A committed notification as delivered by PostgreSQL. The PID identifies the sending backend.

### channel `property`

```python
channel: str
```

### payload `property`

```python
payload: str
```

### pid `property`

```python
pid: int
```

## INHERIT `module-attribute`

```python
INHERIT = InheritType.INHERIT
```

Default for a per-call timeout: use the connection or pool `operation_timeout`. `None` disables the deadline.

## InheritType

Type of `INHERIT`, for annotating a timeout that a wrapper forwards unchanged.

### INHERIT `class-attribute` `instance-attribute`

```python
INHERIT = 0
```
