Runtime & Pool#
The pgdorm runtime executes compiled queries over a Tokio PostgreSQL v3 binary wire pool with 1-RTT pipelining, prepared statement caching, zero-copy Arrow streaming, and structured diagnostics.
See Transactions, Locks & Queues, Pipelining, Prepared & Streaming, Arrow & Polars Analytics, and Web API & Telemetry.
Pools & Connections#
Pool#
class Pool(_WriteExecutor, ReadPool):
def read_only(self) -> ReadPool: ...
async def create_schema(self, name: str, *, if_not_exists: bool = True) -> None: ...
async def drop_schema(
self, name: str, *, if_exists: bool = True, cascade: bool = False
) -> None: ...
async def create_all(self, *tables: type[Table]) -> list[str]: ...
async def simulate_scale(
self,
table: type[Table],
*,
relpages: int,
reltuples: float,
) -> None: ...
async def create_partition(
self,
parent: type[Table],
*,
name: str,
for_values: str | None = None,
default: bool = False,
) -> str: ...
async def listen(self, channel: str, *extra_channels: str) -> AsyncGenerator[Listener]: ...
def pipeline(self) -> AbstractAsyncContextManager[Pipeline]: ...
@overload
def transaction(
self,
*,
isolation: IsolationLevel | None = None,
read_only: Literal[True],
deferrable: bool = False,
local_settings: Mapping[str, str] | None = None,
max_savepoints: int = 64,
) -> AbstractAsyncContextManager[ReadTransaction]: ...
@overload
def transaction(
self,
*,
isolation: IsolationLevel | None = None,
read_only: Literal[False] = False,
deferrable: bool = False,
local_settings: Mapping[str, str] | None = None,
max_savepoints: int = 64,
) -> AbstractAsyncContextManager[Transaction]: ...
@overload
def transaction(
self,
*,
isolation: IsolationLevel | None = None,
read_only: bool,
deferrable: bool = False,
local_settings: Mapping[str, str] | None = None,
max_savepoints: int = 64,
) -> AbstractAsyncContextManager[ReadTransaction]: ...
@overload
async def retry_transaction[R](
self,
fn: Callable[[ReadTransaction], Awaitable[R]],
*,
max_attempts: int = 3,
base_delay: float = 0.05,
max_delay: float = 1.0,
isolation: IsolationLevel | None = None,
read_only: Literal[True],
deferrable: bool = False,
local_settings: Mapping[str, str] | None = None,
max_savepoints: int = 64,
) -> R: ...
@overload
async def retry_transaction[R](
self,
fn: Callable[[Transaction], Awaitable[R]],
*,
max_attempts: int = 3,
base_delay: float = 0.05,
max_delay: float = 1.0,
isolation: IsolationLevel | None = None,
read_only: Literal[False] = False,
deferrable: bool = False,
local_settings: Mapping[str, str] | None = None,
max_savepoints: int = 64,
) -> R: ...
Async PostgreSQL connection pool backed by Tokio. Supports async with await Pool.connect(...) as pool:.
pool_mode="transaction": Enables PgBouncer transaction-pooling hygiene (omits startupoptions, injectsset_config('search_path', ..., true)inside transactions, rejectson_commit="delete_rows").one/one_or_none: RaiseNoResultError(forone) orMultipleResultsError(for both).retry_transaction: RetriesRetryablePgError(40001,40P01) with exponential backoff up tomax_attempts.
ReadPool#
class ReadPool(_ReadExecutor):
@classmethod
async def connect(
cls,
dsn: str,
*,
max_size: int = 8,
search_path: str | Sequence[str] | None = None,
pool_mode: PoolMode = PoolMode.DIRECT,
prepared_statements: bool = True,
prepare_threshold: int = 1,
acquire_timeout: float | None = 30.0,
max_waiting: int | None = None,
max_queries: int | None = None,
max_lifetime: float | None = None,
idle_timeout: float | None = None,
test_before_acquire: bool = False,
application_name: str | None = None,
after_connect: Callable[[Connection], Awaitable[None]] | None = None,
telemetry: TelemetryHook | None = None,
password: str | Callable[[], str | Awaitable[str]] | None = None,
) -> Self: ...
def set_telemetry(self, hook: TelemetryHook | None) -> None: ...
def stats(self) -> PoolStats: ...
@property
def server_version(self) -> str: ...
@property
def server_version_num(self) -> int: ...
@property
def is_pg19(self) -> bool: ...
@property
def tls_active(self) -> bool: ...
@property
def channel_binding(self) -> bool: ...
@property
def pool_mode(self) -> PoolMode: ...
@property
def prepared_statements(self) -> bool: ...
def drain(self) -> None: ...
async def close(self) -> None: ...
async def explain(
self,
stmt: Executable[object],
*,
disable_seqscan: bool = True,
analyze: bool = False,
buffers: bool = False,
) -> ExplainPlan: ...
def read_transaction(
self,
*,
isolation: IsolationLevel | None = None,
deferrable: bool = False,
local_settings: Mapping[str, str] | None = None,
) -> AbstractAsyncContextManager[ReadTransaction]: ...
async def split_load[ParentT: Table](
self,
parent_stmt: Select[ParentT],
*,
relations: Sequence[SplitRelationProto],
dedup: bool = True,
) -> SplitResult[ParentT]: ...
async def trace(self) -> AsyncGenerator[Trace]: ...
Read-only view returned by Pool.read_only(). Statically restricts execution to ReadQuery[RetT] statements (type checkers reject Insert, Update, Delete, and Merge).
PoolMode#
Connection pooling mode: "direct" (default, direct PostgreSQL or session pooler) or "transaction" (PgBouncer / Supavisor transaction pooling). See Cloud Postgres.
PoolStats#
@dataclass(frozen=True, kw_only=True, slots=True)
class PoolStats:
max_size: int
connections_idle: int
connections_in_use: int
connections_opened: int
connections_closed: int
queries_executed: int
rtts_total: int
prepared_hits: int
prepared_misses: int
errors_total: int
acquire_wait_us_total: int
Point-in-time snapshot of pool capacity, active/idle connections, waiter queue depth, and prepared statement cache size returned by Pool.stats().
Connection#
class Connection:
async def all[RetT](self, stmt: Executable[RetT]) -> list[RetT]: ...
async def execute(self, stmt: Executable[object]) -> int: ...
async def set_config(self, setting: str, value: str) -> None: ...
Dedicated session wrapper passed to Pool.connect(..., after_connect=...) for per-connection initialization.
Transactions & Pipelining#
Transaction#
class Transaction(_WriteExecutor, ReadTransaction):
def on_commit(self, callback: Callable[[], object]) -> None: ...
async def advisory_xact_lock(self, key: str) -> None: ...
@overload
async def stage[T: Table](
self,
table: type[T],
rows: Sequence[T],
*,
index_on: Sequence[ColBase] = (),
analyze: bool = True,
by_name: Literal[False] = False,
) -> None: ...
@overload
async def stage[T: Table](
self,
table: type[T],
rows: Sequence[object],
*,
index_on: Sequence[ColBase] = (),
analyze: bool = True,
by_name: Literal[True],
exclude: Sequence[ColBase | str] = (),
) -> None: ...
def pipeline(self, *, commit: bool = False) -> AbstractAsyncContextManager[Pipeline]: ...
async def savepoint(self) -> AsyncGenerator[str]: ...
Active read-write transaction context returned by async with pool.transaction() as tx:. Fuses lazy BEGIN, local_settings (set_config(..., true)), and COMMIT into minimal round-trips. Enforces max_savepoints (SubtransactionLimitError).
ReadTransaction#
Read-only transaction context returned by pool.read_transaction(...) or pool.transaction(read_only=True). Statically restricts execution to ReadQuery[RetT].
IsolationLevel#
class IsolationLevel(StrEnum):
READ_COMMITTED = "read_committed"
REPEATABLE_READ = "repeatable_read"
SERIALIZABLE = "serializable"
PostgreSQL transaction isolation level passed to Pool.transaction(isolation=...) and Pool.retry_transaction(isolation=...).
Pipeline#
class Pipeline:
def add[RetT](self, stmt: Executable[RetT]) -> PipeHandle[RetT]: ...
@overload
def stage[T: Table](
self,
table: type[T],
rows: Sequence[T],
*,
index_on: Sequence[ColBase] = (),
analyze: bool = True,
by_name: Literal[False] = False,
) -> None: ...
@overload
def stage[T: Table](
self,
table: type[T],
rows: Sequence[object],
*,
index_on: Sequence[ColBase] = (),
analyze: bool = True,
by_name: Literal[True],
exclude: Sequence[ColBase | str] = (),
) -> None: ...
def wave(self, builder: Callable[[Pipeline], None]) -> Callable[[Pipeline], None]: ...
async def flush(self) -> None: ...
Batches multiple statements into a single PostgreSQL v3 Sync flush (1 RTT). Statements queued via pipe.add(...) resolve when the async with pool.pipeline() as pipe: block exits. See Pipelining, Prepared & Streaming.
PipeHandle#
class PipeHandle[RetT]:
def all(self) -> list[RetT]: ...
def one(self) -> RetT: ...
@property
def rows_affected(self) -> int: ...
Future-like result handle returned by Pipeline.add(...). Read its hydrated rows after the pipeline() context manager completes.
Streaming, Arrow & Split Loading#
RowStream#
Async iterator returned by Pool.stream(...), fetching rows in server-side portal batches (batch_size) without buffering the entire result set in memory.
ArrowStream#
class ArrowStream:
@property
@property
def num_rows(self) -> int: ...
@property
def num_batches(self) -> int: ...
@property
def column_names(self) -> list[str]: ...
Zero-copy Arrow PyCapsule stream (__arrow_c_stream__) returned by Pool.arrow(...) and Pool.copy_to_arrow(...). Consumed directly by Polars (pl.from_arrow), DuckDB, and PyArrow with minimal Python heap allocation. See Arrow & Polars Analytics.
SplitResult#
@dataclass(frozen=True, kw_only=True, slots=True)
class SplitResult[ParentT: Table]:
parents: tuple[ParentT, ...]
children: Mapping[str, dict[PgValue, list[Table]]]
Structured result returned by Pool.split_load(...), avoiding N+1 queries and Cartesian row explosion by executing parent and child queries in a single pipelined round-trip. See Nested Hydration.
SplitRelation#
@dataclass(frozen=True, kw_only=True, slots=True)
class SplitRelation[ChildT: Table = Table]:
name: str
child_table: type[ChildT]
child_fk: ColBase
parent_key: ColBase
where: Expr[bool] | None = None
order_by: tuple[OrderSpec, ...] = ()
unfiltered_reason: str | None = None
Descriptor defining a child relation for Pool.split_load(...).
LISTEN / NOTIFY#
Listener#
class Listener:
async def recv(self, *, timeout: float | None = None) -> Notification | None: ...
async def listen(self, channel: str) -> None: ...
async def unlisten(self, channel: str) -> None: ...
async def close(self) -> None: ...
Dedicated PostgreSQL LISTEN session returned by async with pool.listen(...) as listener:.
Notification#
@dataclass(frozen=True, kw_only=True, slots=True)
class Notification:
pid: int
channel: str
payload: str
Payload delivered by PostgreSQL NOTIFY and yielded by Listener.
Explain, Trace, Telemetry & Doctor#
ExplainPlan#
class ExplainPlan:
@property
def node_types(self) -> list[str]: ...
@property
def index_names(self) -> list[str]: ...
@property
def total_cost(self) -> float: ...
def summary(self) -> str: ...
def assert_no_seq_scan(self, *, except_tables: Iterable[type[Table]] = ()) -> None: ...
def assert_uses_index(self, index_name: str) -> None: ...
def format_structure(self) -> str: ...
Parsed PostgreSQL EXPLAIN (FORMAT JSON) plan returned by Pool.explain(...). See Keyset Pagination & Plans.
PlanNode#
@dataclass(frozen=True, kw_only=True, slots=True)
class PlanNode:
node_type: str
operation: str | None = None
join_type: str | None = None
relation_name: str | None = None
index_name: str | None = None
scan_direction: str | None = None
parent_relationship: str | None = None
total_cost: float = 0.0
sort_key: tuple[str, ...] = ()
index_cond: str | None = None
recheck_cond: str | None = None
hash_cond: str | None = None
merge_cond: str | None = None
join_filter: str | None = None
filter: str | None = None
plans: tuple[PlanNode, ...] = ()
Typed node in an ExplainPlan tree.
Trace#
class Trace:
@property
def events(self) -> list[WireFlushInfo]: ...
@property
def rtts(self) -> int: ...
@property
def statements(self) -> list[ExecutedStmtInfo]: ...
@property
def statement_count(self) -> int: ...
@property
def all_prepared_cache_hits(self) -> bool: ...
def n_plus_1_patterns(self, *, threshold: int = 3) -> list[NPlusOnePattern]: ...
def assert_no_n_plus_1(self, *, threshold: int = 3) -> None: ...
def format_report(self) -> str: ...
Wire-level execution trace captured by async with pool.trace() as tr:. Records exact round-trip count (tr.rtts), wire flushes, and executed statements for deterministic 1-RTT assertions.
NPlusOnePattern#
@dataclass(frozen=True, kw_only=True, slots=True)
class NPlusOnePattern:
count: int
shape_hash: int
op_tag: str | None
sql: str
Structured N+1 pattern entry returned by Trace.n_plus_1_patterns().
WireFlushInfo#
@dataclass(frozen=True, kw_only=True, slots=True)
class WireFlushInfo:
wave_index: int
statements: tuple[ExecutedStmtInfo, ...]
sync_count: int
bytes_sent: int
bytes_recv: int
wall_us: int
pool_wait_us: int = 0
error_sqlstate: str | None = None
error_message: str | None = None
Metadata for a single PostgreSQL wire Sync flush recorded inside Trace.flushes.
ExecutedStmtInfo#
@dataclass(frozen=True, kw_only=True, slots=True)
class ExecutedStmtInfo:
sql: str
shape_hash: int
prepared_hit: bool
rows: int
rows_affected: int
op_tag: str | None = None
Per-statement execution metadata recorded inside Trace.statements.
TelemetryHook#
Zero-dependency observability protocol passed to Pool.connect(..., telemetry=...), Pool.set_telemetry(...), or pgdorm.runtime.set_telemetry(...) (module-level default hook). See Web API & Telemetry.
doctor#
Runs non-destructive PostgreSQL readiness checks against pool (server version, TLS, SCRAM channel binding, pooler compatibility, search_path, and an optional write_probe=True round-trip). Returns a DoctorReport.
DoctorReport#
@dataclass(frozen=True, kw_only=True, slots=True)
class DoctorReport:
server_version: str
server_version_num: int
pool_mode: PoolMode
tls_active: bool
channel_binding: bool
checks: tuple[DoctorCheck, ...]
recommended_connect_snippet: str
Structured diagnostic report returned by doctor(...).
DoctorCheck#
@dataclass(frozen=True, kw_only=True, slots=True)
class DoctorCheck:
name: str
status: CheckStatus
detail: str
remediation: str | None = None
Individual check result inside DoctorReport.checks.
CheckStatus#
Outcome status of a DoctorCheck.
DoctorCheckDict#
class DoctorCheckDict(TypedDict):
name: str
status: CheckStatus
detail: str
remediation: str | None
Typed JSON dictionary shape returned by DoctorCheck.to_dict().
DoctorReportDict#
class DoctorReportDict(TypedDict):
ok: bool
server_version: str
server_version_num: int
pool_mode: PoolMode
tls_active: bool
channel_binding: bool
checks: list[DoctorCheckDict]
recommended_connect_snippet: str
Typed JSON dictionary shape returned by DoctorReport.to_dict().