Queries and transactions¶
Connection, Pool, checked-out pool connections, transactions, and savepoints all share the Executor interface, differing only in which session runs the statement and when effects commit.
Fetching rows and running commands¶
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_allreturns every row as alist.fetch_onerequires exactly one row; zero or multiple rows raiseCardinalityError.fetch_optionalreturns one row orNone; multiple rows raiseCardinalityError.executediscards rows and returns aCommand(tag,row_count). Without parameters it can run multiple semicolon-separated statements and returns the lastCommand.
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 atextfirst column raisesDecodingError. - Gres does not inspect every value for
NULL; annotate nullable columns asT | None. scalar(T)keeps a compatible value, converts losslessly for numeric/boolean targets, or constructsT.Literaltargets check membership; ambiguous unions raiseDecodingError. 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 asdictforjsonb(userow=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::integerwhen ambiguous. See Types and adapters for conversions. - For dynamic table names, columns, or filters, use SQL 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.
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:
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
PreparedStatementbelongs to itsConnectionorTransactionand must be awaited inside theasync withblock (calls after exit raiseInterfaceError). - On a
Pool, borrow a session withpool.connection()first. Behind transaction poolers, use ordinary queries instead. - Preparing a bound
Querywithout passingparamsto execution methods reuses its bound values. Each call gets its owntimeout. - If a migration alters the result signature or
DEALLOCATE ALLdrops 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() 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: 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:
# 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, anddeferrablemap directly to PostgreSQL'sBEGINclauses. A savepoint inherits its enclosing transaction's characteristics, so passing any of these to a nestedtransaction()raisesConfigurationError.timeout(defaultNone) sets a monotonic deadline in seconds for the whole transaction, including pauses between queries; it does not inheritoperation_timeout. A nestedtransaction()can only shorten the enclosing deadline, and a child query'stimeoutcannot extend it.- If communication fails during commit, check
tx.outcomeas described in 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):
# 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.
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.