Queries and results¶
Connection, Pool, and Transaction all provide the Executor methods. Queries and transactions 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 typedtuple[...]/TypedDict/NamedTuple/ dataclass,scalar(...), or a callable.prepare: Override automatic statement preparation (True/False);Noneuses the connection'sauto_preparesetting.decoding: Per-callDecodingoverrides; unspecified fields inherit the connection policy.adapters: Sequence ofEnumBinding,CompositeBinding,Adapter, orCodecoverrides 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 pooloperation_timeout;Nonedisables the deadline.
invalidate_types
¶
invalidate_types() -> None
Discard cached type metadata after a committed type migration. No SQL is sent.
execute
async
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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]]
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]
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,]]
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]]
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]
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
¶
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]
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
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,]
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]
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
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
¶
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
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
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
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
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
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
¶
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]]]
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]]
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,]]]
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]]]
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]]
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
¶
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
¶
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
¶
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]]]
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]]
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,]]]
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]]]
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]]
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
¶
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
¶
fetch_one(
params: Bindings | None = None, *, timeout: float | InheritType | None = ...
) -> _R
Return exactly one row, or raise CardinalityError after command completion.
fetch_optional
async
¶
fetch_optional(
params: Bindings | None = None, *, timeout: float | InheritType | None = ...
) -> _R | None
Return one row or None; multiple rows raise CardinalityError.
fetch_all
async
¶
fetch_all(
params: Bindings | None = None, *, timeout: float | InheritType | None = ...
) -> list[_R]
Return all rows in order using the prepared projection.
execute
async
¶
execute(
params: Bindings | None = None, *, timeout: float | InheritType | None = ...
) -> Command
Execute once and return the command tag, discarding result rows.
scalar
¶
scalar() -> _Scalar[object]
scalar(target: TypeForm[_T_co]) -> _Scalar[_T_co]
scalar(target: Callable[..., _T_co]) -> _Scalar[_T_co]
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
¶
Command(tag: str)
BatchResult
dataclass
¶
BatchResult(commands: int, 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
¶
schema: Schema
The PostgreSQL projection's Arrow schema, including for an empty result.
Notification
¶
Notification(channel: str, payload: str, pid: int)
INHERIT
module-attribute
¶
INHERIT = InheritType.INHERIT
Default for a per-call timeout: use the connection or pool operation_timeout. None disables the deadline.