Skip to content

SQL composition

Composition builds statements from trusted fragments and bound values without formatting values into SQL text. See SQL composition.

Query dataclass

Query(sql: Source, params: Bindings | None = None)

SQL with its own mapping or positional arguments. Reuse by identity, not by value equality.

bind

bind(params: Bindings) -> Query

Override local names or replace the positional sequence; leave this query unchanged.

A template query carries its own values, so binding it raises TypeError.

Identifier dataclass

Identifier(*parts: str)

One or more literal name components. A dot inside a component is part of the name.

parts instance-attribute

parts: tuple[str, ...]

Literal

Literal(value: object, *, type: Source | Identifier | Query | None = None)

Inline a scalar SQL constant rather than a server parameter. Its contents can appear in query logs.

raw_sql

raw_sql(text: str, params: Bindings | None = None) -> Query

Compose trusted runtime SQL. Bind values separately, exactly as for literal query text.

and_

and_(*parts: Predicate) -> Query

Group predicates with AND. None operands are omitted; mapping values of None become IS NULL; an empty conjunction is TRUE.

or_

or_(*parts: Predicate) -> Query

Group predicates with OR. None operands are omitted; mapping values of None become IS NULL; an empty disjunction is FALSE.

assignments

assignments(changes: Mapping[str, object]) -> Query

Build a SET list from single-component column names and bound values or expressions.

cast

cast(value: object, type: Source | Identifier | Query) -> Query

Cast a bound value or SQL expression. Use an Identifier for a dynamic type name.

insert

insert(
    table: str | Identifier,
    records: Mapping[str, object] | Iterable[Mapping[str, object]],
    *,
    columns: Sequence[str] | None = None,
) -> Query

Insert finite records in the selected column order. Without columns, require the first record's keys in every row.

join

join(items: Iterable[object], sep: LiteralString = ', ') -> Query

Separate typed bindings with trusted SQL. Ordinary strings are values, never column names.

values

values(
    records: Mapping[str, object]
    | Iterable[Mapping[str, object] | Sequence[object]],
    *,
    columns: Mapping[str, Source | Identifier | Query],
    alias: str | Identifier,
) -> Query

Build an aliased, explicitly typed VALUES relation. Empty input yields an empty relation of those types.