Queries & DML#
pgdorm compiles typed Python query and DML builders into deterministic PostgreSQL and a ShapeHash in Rust — with zero raw SQL execution.
See Patch & Returning, Bulk Insert & Upsert, Joins & Folios, Hierarchy Regions & CTEs, and Staging & Merge Import.
SELECT Builders#
select#
@overload
def select[T: Table](table: type[T]) -> Select[T]: ...
@overload
def select(table: CteTarget) -> Select[ResultRow]: ...
Starts a typed SELECT query targeting a Table, TableAlias, or CteTarget.
select_expr#
@overload
def select_expr[T1: PgValue](first: ProjectableExpr[T1], /) -> Select[tuple[T1]]: ...
@overload
def select_expr(first: ExprBase | ColBase, *rest: ExprBase | ColBase) -> Select[ResultRow]: ...
Starts a table-less SELECT <expr>, ... query (e.g., select_expr(now()) or scalar function calls), returning ResultRow instances.
Select#
@dataclass(frozen=True, kw_only=True, slots=True)
class Select[RetT](_WhereOrderLimitMixin, ReadQuery[RetT]): ...
Immutable SELECT query builder. Every fluent method returns a new Select instance. Enforces FK join hygiene (JoinLintError on ambiguous or unindexed FKs unless .allow_seq_scan(reason=...) is declared).
INSERT, UPDATE, DELETE & MERGE#
insert#
Starts a single-row INSERT INTO <table> builder.
Insert#
@dataclass(frozen=True, kw_only=True, slots=True)
class Insert[T: Table](_OnConflictMixin[T], Executable[T]): ...
Single-row INSERT builder with ON CONFLICT DO NOTHING / DO UPDATE / DO SELECT and RETURNING support.
InsertFromSelect#
@dataclass(frozen=True, kw_only=True, slots=True)
class InsertFromSelect[T: Table](_OnConflictMixin[T], Executable[T]): ...
INSERT INTO <table> (...) SELECT ... builder produced by Insert.from_select(...).
insert_many#
@overload
def insert_many[T: Table](
table: type[T], instances: Sequence[T], *, by_name: Literal[False] = False
) -> InsertMany[T]: ...
@overload
def insert_many[T: Table](
table: type[T],
instances: Sequence[object],
*,
by_name: Literal[True],
exclude: Sequence[ColBase | str] = (),
) -> InsertMany[T]: ...
Starts a constant-shape bulk INSERT using PostgreSQL UNNEST(...) WITH ORDINALITY ORDER BY u.ord so any batch size shares one prepared statement. See Bulk Insert & Upsert.
InsertMany#
@dataclass(frozen=True, kw_only=True, slots=True)
class InsertMany[T: Table](_OnConflictMixin[T], Executable[T]): ...
Bulk UNNEST-backed INSERT builder.
insert_subtype#
def insert_subtype[T: Table](table: type[T], **values: PgValue | UnsetType) -> InsertSubtype[T]: ...
Atomically inserts a Class-Table Inheritance (CTI) base row and subtype row in a single 1-RTT writable CTE. See Inheritance, Payments & Tasks.
InsertSubtype#
@dataclass(frozen=True, kw_only=True, slots=True)
class InsertSubtype[T: Table](_ReturningMixin[T], Executable[T]): ...
Executable 1-RTT CTI subtype insert statement returned by insert_subtype(...).
update#
Starts an UPDATE <table> builder. Raises UnsafeDmlError on compile/execute if neither .where(...) nor .allow_full_table(reason=...) is called.
Update#
@dataclass(frozen=True, kw_only=True, slots=True)
class Update[T: Table](_FilteredDmlMixin[T], Executable[T]): ...
Immutable UPDATE builder supporting SET, Patch[T], FROM, and RETURNING OLD.* / NEW.*.
Assign#
@dataclass(frozen=True, kw_only=True, slots=True)
class Assign:
column: ColBase
value: PgValue | ExprBase | ColBase | ParamRefBase | UnsetType
Column assignment pair produced by Col.set(value) and passed to Update.set(...) or on_conflict_do_update(set_=...).
delete#
Starts a DELETE FROM <table> builder. Raises UnsafeDmlError if neither .where(...) nor .allow_full_table(reason=...) is called.
Delete#
@dataclass(frozen=True, kw_only=True, slots=True)
class Delete[T: Table](_FilteredDmlMixin[T], Executable[T]): ...
Immutable DELETE builder supporting USING and RETURNING.
merge#
Starts a MERGE INTO <target> builder. See Staging & Merge Import.
Merge#
@dataclass(frozen=True, kw_only=True, slots=True)
class Merge[TargetT: Table, SourceT: Table](
_FilterableReturningMixin[TargetT], Executable[TargetT]
): ...
Immutable MERGE builder supporting table, SELECT, or UNNEST sources and RETURNING merge_action(), ....
merge_action#
Emits PostgreSQL's merge_action() expression inside Merge.returning(...) ('INSERT', 'UPDATE', or 'DELETE').
RETURNING & Conflict References#
excluded#
@overload
def excluded[T: PgValue](col: Col[T]) -> Expr[T]: ...
@overload
def excluded(col: ColBase) -> Expr[PgValue]: ...
References EXCLUDED.<column> inside Insert.on_conflict_do_update(...) and InsertMany.on_conflict_do_update(...).
old#
References OLD.<column> inside Update.returning(...), Delete.returning(...), or Merge.returning(...). See Patch & Returning.
new#
References NEW.<column> inside Insert.returning(...), Update.returning(...), or Merge.returning(...).
Returning#
@dataclass(frozen=True, kw_only=True, slots=True)
class Returning[RetT](_TimeoutMixin, Executable[RetT]): ...
Sentinel/type namespace representing RETURNING projections on DML statements.
ReturningRef#
Typed reference to a column, old(col), new(col), or expression returned by a DML RETURNING clause.
CTEs, LATERAL, Set Operations & Subqueries#
cte#
@overload
def cte(
name: str,
query: ReadQuery[object],
*,
materialized: bool | None = None,
columns: Sequence[str] = (),
) -> Cte: ...
@overload
def cte(
name: str,
query: Executable[object],
*,
materialized: bool | None = None,
columns: Sequence[str] = (),
) -> WriteCte: ...
Defines a named Common Table Expression (WITH <name> AS [NOT] MATERIALIZED (...)). Returns WriteCte when wrapping a DML statement (Insert/Update/Delete/Merge), or Cte for read queries.
recursive_cte#
def recursive_cte(
name: str,
base: Select[object],
step: Callable[[CteRef], Select[object]],
*,
union_all: bool = True,
columns: Sequence[str] = (),
search: tuple[SearchOrder, Sequence[str], str] | None = None,
cycle: tuple[Sequence[str], str, str] | None = None,
) -> Cte: ...
Defines a WITH RECURSIVE CTE with optional SQL-standard SEARCH DEPTH/BREADTH FIRST and CYCLE detection clauses. See Hierarchy Regions & CTEs.
Cte#
@dataclass(frozen=True, kw_only=True, slots=True)
class Cte(_CteColMixin):
name: str
columns: tuple[str, ...] = ()
recursive: bool = False
materialized: bool | None = None
base: Select[object] | SetOpBase
recursive_step: tuple[bool, Select[object]] | None = None
search: tuple[SearchOrder, tuple[str, ...], str] | None = None
cycle: tuple[tuple[str, ...], str, str] | None = None
Read-only CTE definition. Access columns via my_cte.c.col_name or my_cte["col_name"].
WriteCte#
@dataclass(frozen=True, kw_only=True, slots=True)
class WriteCte(_CteColMixin):
name: str
columns: tuple[str, ...] = ()
materialized: bool | None = None
base: Executable[object]
Data-modifying CTE wrapping an Insert, Update, Delete, or Merge with RETURNING.
CteRef#
Self-reference handle passed into the step callback of recursive_cte(...).
CteTarget#
class CteTarget(Protocol):
@property
def __pg_is_cte__(self) -> bool: ...
@property
def name(self) -> str: ...
def col(self, col_name: str) -> Expr: ...
Protocol satisfied by Cte, WriteCte, and CteRef when used as a FROM or JOIN target.
with_#
@overload
def with_[RetT](first: Cte, *rest: Cte, query: Select[RetT] | SetOp[RetT]) -> WithQuery[RetT]: ...
@overload
def with_[RetT](
first: Cte | WriteCte, *rest: Cte | WriteCte, query: Executable[RetT]
) -> WriteWithQuery[RetT]: ...
Attaches one or more CTEs to a main query. Returns WithQuery[RetT] (a ReadQuery) when all CTEs and query are read-only, or WriteWithQuery[RetT] (an Executable) when any CTE or query writes.
WithQuery#
@dataclass(frozen=True, kw_only=True, slots=True)
class WithQuery[RetT = ResultRow](_TaggableMixin, ReadQuery[RetT]): ...
Read-only WITH ... SELECT ... query accepted by Pool, ReadPool, Transaction, and ReadTransaction.
WriteWithQuery#
@dataclass(frozen=True, kw_only=True, slots=True)
class WriteWithQuery[RetT = ResultRow](_TaggableMixin, Executable[RetT]): ...
Data-modifying WITH ... query accepted by Pool and Transaction (statically rejected by ReadPool / ReadTransaction).
lateral#
Wraps a correlated Select as a LATERAL (...) AS <alias> join source.
LateralSubquery#
@dataclass(frozen=True, kw_only=True, slots=True)
class LateralSubquery:
subquery: SelectSubquery
alias: str
Correlated lateral subquery descriptor passed to Select.join_lateral(...).
LateralJoinKind#
Join kind for Select.join_lateral(...) (INNER JOIN LATERAL or LEFT JOIN LATERAL ... ON TRUE).
lateral_jsonb#
def lateral_jsonb(
parent: type[Table],
child: type[Table],
*,
on: tuple[ColBase, ColBase],
fields: Sequence[ColBase | tuple[str, str]],
alias: str,
parent_cols: Sequence[ColBase] | None = None,
child_order_by: Sequence[OrderSpec] = (),
) -> LateralJsonb: ...
Builds a LATERAL jsonb_to_recordset(...) AS <alias>(...) set-returning join source.
LateralJsonb#
@dataclass(frozen=True, kw_only=True, slots=True)
class LateralJsonb(_WhereOrderLimitMixin, ReadQuery[ResultRow]): ...
Descriptor for a jsonb_to_recordset lateral join.
JoinKind#
class JoinKind(StrEnum):
INNER = "inner"
LEFT = "left"
RIGHT = "right"
FULL = "full"
CROSS = "cross"
Join type accepted by Select.join(..., kind=...).
RowLockWait#
Row-level lock wait policy for Select.for_update(wait=...) and Select.for_share(wait=...). See Transactions, Locks & Queues.
union#
def union[RetT](left: Select[RetT] | SetOp[RetT], right: Select[RetT] | SetOp[RetT]) -> SetOp[RetT]: ...
Combines two compatible queries with UNION (deduplicating rows).
union_all#
def union_all[RetT](
left: Select[RetT] | SetOp[RetT], right: Select[RetT] | SetOp[RetT]
) -> SetOp[RetT]: ...
Combines two compatible queries with UNION ALL.
intersect#
def intersect[RetT](
left: Select[RetT] | SetOp[RetT], right: Select[RetT] | SetOp[RetT]
) -> SetOp[RetT]: ...
Combines two compatible queries with INTERSECT.
except_#
def except_[RetT](
left: Select[RetT] | SetOp[RetT], right: Select[RetT] | SetOp[RetT]
) -> SetOp[RetT]: ...
Combines two compatible queries with EXCEPT.
SetOp#
@dataclass(frozen=True, kw_only=True, slots=True)
class SetOp[RetT = ResultRow](SetOpBase, ReadQuery[RetT]): ...
Executable set-operation query (UNION, UNION ALL, INTERSECT, EXCEPT).
subquery#
Wraps a scalar Select as a parenthesized scalar subquery expression.
exists#
Emits EXISTS (<subquery>).
not_exists#
Emits NOT EXISTS (<subquery>).
in_subquery#
Emits <lhs> IN (<subquery>).
not_in_subquery#
Emits <lhs> NOT IN (<subquery>).
Compilation, Preparation & Execution Contracts#
compile#
def compile(
stmt: Executable[object],
*,
search_path: str | None = None,
) -> CompiledQuery: ...
Compiles any Executable query or DML builder in Rust without a database connection and returns its canonical CompiledQuery.
CompiledQuery#
@dataclass(frozen=True, kw_only=True, slots=True)
class CompiledQuery:
sql: str
shape_hash: int
param_types: tuple[str, ...]
cacheable: bool
requires_pg19: bool
op_tag: str | None = None
Deterministic Rust compilation output containing canonical SQL, 64-bit shape_hash, PostgreSQL parameter type OIDs/names, and newer-server capability flag.
prepare#
@overload
def prepare[RetT](
stmt_or_fn: ReadQuery[RetT] | Callable[..., ReadQuery[RetT]],
) -> ReadPreparedQuery[RetT]: ...
@overload
def prepare[RetT](
stmt_or_fn: Executable[RetT] | Callable[..., Executable[RetT]],
) -> PreparedQuery[RetT]: ...
Pre-compiles a parameterized statement (using param(...) placeholders) once into a reusable PreparedQuery[RetT] (or ReadPreparedQuery[RetT]). See Pipelining, Prepared & Streaming.
PreparedQuery#
class PreparedQuery[RetT]:
@property
def param_names(self) -> tuple[str, ...]: ...
@property
def sql(self) -> str: ...
def bind(self, *args: PgValue, **kwargs: PgValue) -> BoundQuery[RetT]: ...
Pre-compiled statement ready to bind named param(...) arguments without re-running Python AST construction.
ReadPreparedQuery#
class ReadPreparedQuery[RetT](PreparedQuery[RetT]):
def bind(self, *args: PgValue, **kwargs: PgValue) -> ReadBoundQuery[RetT]: ...
Read-only specialization of PreparedQuery[RetT] whose .bind(...) returns a ReadBoundQuery[RetT].
BoundQuery#
@dataclass(frozen=True, kw_only=True, slots=True)
class BoundQuery[RetT](Executable[RetT]): ...
Executable statement pairing a PreparedQuery[RetT] with concrete parameter bindings.
ReadBoundQuery#
@dataclass(frozen=True, kw_only=True, slots=True)
class ReadBoundQuery[RetT](BoundQuery[RetT], ReadQuery[RetT]): ...
Read-only specialization of BoundQuery[RetT] accepted by ReadPool and ReadTransaction.
Executable#
Base type for all executable statements (reads and writes) accepted by Pool and Transaction.
ReadQuery#
Base type for read-only queries (Select, SetOp, WithQuery, ReadBoundQuery) accepted by ReadPool and ReadTransaction.
ResultRow#
Lightweight projected row returned by .columns(...), select_expr(...), and custom RETURNING projections. Supports both positional indexing and attribute/key access.
currval#
References PostgreSQL currval(pg_get_serial_sequence(...)) for an identity/serial column within a pipelined transaction.
CurrvalRef#
@dataclass(frozen=True, kw_only=True, slots=True)
class CurrvalRef:
table: TableRef
column: str
Descriptor returned by currval(...).