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

# Queries and transactions

`Connection`, `Pool`, checked-out pool connections, transactions, and savepoints all share the [`Executor`](https://gres.monicz.dev/api/queries/#gres.Executor) interface, differing only in which session runs the statement and when effects commit.

## Fetching rows and running commands

```python
import asyncio
from dataclasses import dataclass
from gres import Connection, scalar


@dataclass
class Station:
    id: int
    name: str


async def main() -> None:
    async with Connection() as db:
        await db.execute(
            'CREATE TEMP TABLE station(id int PRIMARY KEY, name text NOT NULL)'
        )
        command = await db.execute(
            "INSERT INTO station VALUES (1, 'Harbour'), (2, 'Airport')"
        )
        print(command.tag, command.row_count)  # INSERT 0 2 2

        stations = await db.fetch_all(
            'SELECT id, name FROM station ORDER BY id', row=Station
        )
        print(len(stations), stations[0])  # 2 Station(id=1, name='Harbour')
        first = await db.fetch_one('SELECT * FROM station WHERE id = $1', (1,))
        print(first)  # {'id': 1, 'name': 'Harbour'}
        count = await db.fetch_one(
            'SELECT count(*) FROM station', row=scalar(int)
        )
        print(count)  # 2
        missing = await db.fetch_optional(
            'SELECT name FROM station WHERE id = $id', {'id': 3}
        )
        print(missing)  # None


asyncio.run(main())
```

- `fetch_all` returns every row as a `list`.
- `fetch_one` requires exactly one row; zero or multiple rows raise `CardinalityError`.
- `fetch_optional` returns one row or `None`; multiple rows raise `CardinalityError`.
- `execute` discards rows and returns a `Command` (`tag`, `row_count`). Without parameters it can run multiple semicolon-separated statements and returns the last `Command`.

`CardinalityError` is raised after the statement completes, so a write with `RETURNING` has already taken effect. Inside a transaction, a returned `Command` does not mean the change has committed.

### Row shapes

Pass `row=` to control row construction. Gres checks columns against the declared shape before building any row.

| `row=` | Each row | Checked against result columns |
| --- | --- | --- |
| omitted | `dict` keyed by column name | names are unique |
| `tuple` | `tuple` in column order | nothing; duplicate names allowed |
| `tuple[int, str]` | `tuple` | column count and built-in types |
| dataclass, `NamedTuple`, or `TypedDict` | that class, filled by column name | names and built-in types; fields with defaults may be omitted |
| `scalar(T)` | single column decoded as `T` | exactly one column |
| any other callable | `row(**columns)` | names are unique |

- Built-in SQL types (`integer`, `text`, `boolean`, `numeric`, `uuid`, etc.) must match the annotated class: `row=tuple[int, str]` on a `text` first column raises `DecodingError`.
- Gres does not inspect every value for `NULL`; annotate nullable columns as `T | None`.
- `scalar(T)` keeps a compatible value, converts losslessly for numeric/boolean targets, or constructs `T`. `Literal` targets check membership; ambiguous unions raise `DecodingError`. Pass a callable for custom conversion.
- Model classes (pydantic, msgspec `Struct`, attrs) receive decoded columns as keyword arguments. Pydantic validates nested structures automatically; msgspec and attrs keep decoded values such as `dict` for `jsonb` (use `row=lambda **cols: msgspec.convert(cols, Station)` for nested conversion).
- Alias duplicate columns in SQL or use `row=tuple`.

### Parameter binding

- Bind a sequence positionally (`$1`, `$2`, ...) or a mapping by name (`$name`), one style per statement. Repeated placeholders reuse their value.
- A mapping may include unused keys; every positional value must be referenced.
- PostgreSQL infers parameter types from SQL context; add casts like `$1::integer` when ambiguous. See [Types and adapters](https://gres.monicz.dev/guide/types/) for conversions.
- For dynamic table names, columns, or filters, use [SQL composition](https://gres.monicz.dev/guide/composition/).

## Prepared statements

Gres prepares repeated SQL automatically on direct and session-pooled connections, caching statements and result signatures (never values or rows) across [pool resets](https://gres.monicz.dev/guide/pools/#reset-on-return).

Call `prepare()` when you want a fixed signature from the first execution, explicit lifetime control, or to skip repeated statement-cache lookups on hot sequential reads:

```python
import asyncio
from gres import Connection, scalar


async def main() -> None:
    async with Connection() as db:
        await db.execute(
            'CREATE TEMP TABLE station(id int PRIMARY KEY, name text NOT NULL)'
        )
        await db.execute(
            "INSERT INTO station VALUES (1, 'Harbour'), (2, 'Airport')"
        )
        async with db.prepare(
            'SELECT name FROM station WHERE id = $id', row=scalar(str)
        ) as lookup:
            assert await lookup.fetch_one({'id': 1}) == 'Harbour'
            assert await lookup.fetch_optional({'id': 3}) is None


asyncio.run(main())
```

- A `PreparedStatement` belongs to its `Connection` or `Transaction` and must be awaited inside the `async with` block (calls after exit raise `InterfaceError`).
- On a `Pool`, borrow a session with `pool.connection()` first. Behind transaction poolers, use ordinary queries instead.
- Preparing a bound `Query` without passing `params` to execution methods reuses its bound values. Each call gets its own `timeout`.
- If a migration alters the result signature or `DEALLOCATE ALL` drops the server statement, Gres raises the error without re-preparing or replaying.

### Automatic preparation

Pass `prepare=False` to a call that must infer fresh types (such as a migration step), or set `auto_prepare=False` on a `Connection` or `Pool` (`prepare=True` re-enables it per call). After an external type migration commits, call [`invalidate_types()`](https://gres.monicz.dev/guide/types/#refresh-type-metadata-after-a-migration) on application pools.

## Transactions and savepoints

`async with db.transaction() as tx` commits on normal exit and rolls back on exception; `await tx.rollback()` rolls back early. On a `Connection`, statements on `db` also run in the active transaction, whereas on a `Pool` you must use `tx` (statements on `pool` borrow a separate session).

Entering `transaction()` inside an active transaction on the same session creates a [savepoint](https://www.postgresql.org/docs/current/sql-savepoint.html): it can roll back independently and commits with its enclosing transaction. Helpers typed as `gres.Executor` can therefore run standalone or inside a caller's transaction:

```python
# Partial: the station and audit tables exist.
from gres import Executor


async def add_station(db: Executor, station: int, name: str) -> None:
    async with db.transaction() as tx:
        await tx.execute('INSERT INTO station VALUES ($1, $2)', (station, name))
        await tx.execute('INSERT INTO audit(event) VALUES ($1)', (f'added {name}',))
```

- `isolation` (`'read_uncommitted'`, `'read_committed'`, `'repeatable_read'`, `'serializable'`), `read_only`, and `deferrable` map directly to PostgreSQL's [`BEGIN`](https://www.postgresql.org/docs/current/sql-begin.html) clauses. A savepoint inherits its enclosing transaction's characteristics, so passing any of these to a nested `transaction()` raises `ConfigurationError`.
- `timeout` (default `None`) sets a monotonic deadline in seconds for the whole transaction, including pauses between queries; it does not inherit `operation_timeout`. A nested `transaction()` can only shorten the enclosing deadline, and a child query's `timeout` cannot extend it.
- If communication fails during commit, check `tx.outcome` as described in [Retry safety](https://gres.monicz.dev/guide/errors/#retry-safety).

### Retrying serialization failures

Under `repeatable_read` and `serializable`, `SerializationFailure` and `DeadlockDetected` mean PostgreSQL rolled back the transaction, so retrying from the start is safe (still acquire row locks in a consistent order to avoid waiting on `deadlock_timeout`):

```python
# Partial: pool is an open Pool and account(id int PRIMARY KEY, balance int) exists.
import asyncio
import random
from gres import Pool, errors


async def transfer(pool: Pool, source: int, target: int, amount: int) -> None:
    for attempt in range(8):
        try:
            async with pool.transaction(isolation='serializable') as tx:
                for account, delta in sorted([(source, -amount), (target, amount)]):
                    await tx.execute(
                        'UPDATE account SET balance = balance + $1 WHERE id = $2',
                        (delta, account),
                    )
            return
        except (errors.SerializationFailure, errors.DeadlockDetected):
            await asyncio.sleep(random.uniform(0, 0.01 * 2**attempt))
    raise RuntimeError('transfer did not commit')
```

Retry only these server errors directly; for transport or commit failures, see [Retry safety](https://gres.monicz.dev/guide/errors/#retry-safety).

## Batched execution

`execute_many(sql, parameter_sets)` runs one statement per parameter set, discards rows, and returns a `BatchResult` (`commands`, summed `row_count`).

- **Atomic:** outside a transaction it runs in its own transaction and commits only if every set succeeds; inside one it joins that transaction.
- **Pipelining vs. streaming:** pass a sequence (`list`/`tuple`) for pipelined groups of inserts, updates, or deletes; pass an iterator or async generator when producing the next item depends on the previous execution completing.
- **Mid-batch failures:** a producer or encoder error after earlier sets ran marks an enclosing transaction rollback-only even if caught; wrap the batch in a nested `transaction()` to isolate it.
- Cancellation can interrupt a pipelined group after more than one execution ran; rollbacks do not revert sequences. Empty input sends nothing and reports `commands=0`.

For bulk table loads, use [binary `COPY`](https://gres.monicz.dev/guide/bulk/).
