Expressions & Functions#
Typed SQL expression builders, aggregates, grouping sets, window functions, PostgreSQL full-text search, and JSONB / SQL-JSON helpers.
See Analytics Revenue Report, Keyset Pagination & Plans, and Column Types & DDL.
Core Expressions & Operators#
Expr#
class Expr[T = PgValue](ExprBase, _ExprOpsMixin[T], ValueExpr[T]):
def alias(self, name: str) -> Self: ...
def filter(self, predicate: Expr[bool]) -> Self: ...
def within_group(self, *order_by: OrderSpec | _Orderable) -> Self: ...
def over(
self,
*,
partition_by: Sequence[ExprArg] = (),
order_by: Sequence[OrderSpec] = (),
frame: WindowFrame | None = None,
) -> Self: ...
def in_any(
self, values: Sequence[T] | ParamRef[Sequence[T]] | ParamRef[list[T]] | UntypedParamRef
) -> Expr[bool]: ...
Typed SQL expression node backed by RustExpr. Supports Python comparison (==, !=, <, <=, >, >=), arithmetic (+, -, *, /), boolean (&, |, ~), aliasing (.as_(...)), ordering, and .over(...) window clauses. .in_(...) compiles to constant-shape = ANY($1).
OrderSpec#
@dataclass(frozen=True, kw_only=True, slots=True)
class OrderSpec:
column: str
descending: bool = False
nulls_first: bool = False
nulls_last: bool = False
table: str | None = None
expr: RustExpr | None = None
Ordering specification produced by .asc(...) or .desc(...) on a Col or Expr, passed to Select.order_by(...), Index(...), or window/aggregate order_by=.
ParamRef#
@dataclass(frozen=True, kw_only=True, slots=True)
class ParamRef[T = PgValue](ParamRefBase, ValueExpr[T]): ...
Named typed parameter placeholder returned by param(...) for use with prepare(...).
param#
@overload
def param[T](name: str, py_type: TypeForm[T], *, pg_type: str | None = None) -> ParamRef[T]: ...
@overload
def param(name: str, py_type: None = None, *, pg_type: str | None = None) -> UntypedParamRef: ...
Declares a named bind parameter placeholder for prepare(...).
lit#
Wraps a Python value as a bound SQL expression parameter.
col_ref#
@overload
def col_ref[R: PgValue](name: str, *, table: str | None = None, returns: type[R]) -> Expr[R]: ...
@overload
def col_ref(name: str, *, table: str | None = None, returns: None = None) -> Expr[PgValue]: ...
Constructs an explicit column reference expression (e.g., referencing a CTE or lateral alias column by name).
func#
@overload
def func[R: PgValue](
name: str,
*args: ExprArg,
pg_type: str | None = None,
order_by: Sequence[OrderSpec] = (),
returns: type[R],
) -> Expr[R]: ...
@overload
def func(
name: str,
*args: ExprArg,
pg_type: str | None = None,
order_by: Sequence[OrderSpec] = (),
returns: None = None,
) -> Expr[PgValue]: ...
Dynamic namespace for calling arbitrary PostgreSQL SQL functions (e.g., func.lower(Guest.email), func.date_trunc("day", Booking.created_at)).
cast#
@overload
def cast[R: PgValue](
value: ColBase | ExprBase | PgValue, pg_type: str, *, returns: type[R]
) -> Expr[R]: ...
@overload
def cast(
value: ColBase | ExprBase | PgValue, pg_type: str, *, returns: None = None
) -> Expr[PgValue]: ...
Emits CAST(<expr> AS <pg_type>).
case#
@overload
def case[R: PgValue](
*whens: tuple[Expr[bool], TypedOperand[R]], else_: TypedOperand[R], pg_type: str | None = None
) -> Expr[R]: ...
@overload
def case[R: PgValue](
*whens: tuple[Expr[bool], TypedOperand[R]], else_: UnsetType = UNSET, pg_type: str | None = None
) -> Expr[R | None]: ...
Emits a SQL CASE WHEN ... THEN ... ELSE ... END expression.
extract#
def extract(field: ExtractField, source: ColBase | ExprBase | PgValue) -> Expr[Decimal]: ...
Emits EXTRACT(<field> FROM <source>).
now#
Emits PostgreSQL now() returning TIMESTAMPTZ.
tuple_#
@overload
def tuple_[T1: PgValue, T2: PgValue](
c1: Col[T1] | Expr[T1], c2: Col[T2] | Expr[T2], /
) -> Expr[tuple[T1, T2]]: ...
@overload
def tuple_[T1: PgValue, T2: PgValue, T3: PgValue](
c1: Col[T1] | Expr[T1], c2: Col[T2] | Expr[T2], c3: Col[T3] | Expr[T3], /
) -> Expr[tuple[T1, T2, T3]]: ...
@overload
def tuple_[T1: PgValue, T2: PgValue, T3: PgValue, T4: PgValue](
c1: Col[T1] | Expr[T1],
c2: Col[T2] | Expr[T2],
c3: Col[T3] | Expr[T3],
c4: Col[T4] | Expr[T4],
/,
) -> Expr[tuple[T1, T2, T3, T4]]: ...
@overload
def tuple_(
first: ColBase | ExprBase, second: ColBase | ExprBase, *rest: ColBase | ExprBase
) -> Expr[tuple[PgValue, ...]]: ...
Builds a SQL row-value tuple (a, b, ...) for keyset pagination comparisons (tuple_(Booking.created_at, Booking.booking_id) > (last_ts, last_id)). See Keyset Pagination & Plans.
and_#
@overload
def and_(first: Expr[bool], /, *rest: Expr[bool] | None) -> Expr[bool]: ...
@overload
def and_(*exprs: Expr[bool] | None) -> Expr[bool] | None: ...
Combines boolean expressions with SQL AND.
or_#
@overload
def or_(first: Expr[bool], /, *rest: Expr[bool] | None) -> Expr[bool]: ...
@overload
def or_(*exprs: Expr[bool] | None) -> Expr[bool] | None: ...
Combines boolean expressions with SQL OR.
coalesce#
def coalesce[T: PgValue](
first: ValueExpr[T | None] | ValueExpr[T], *rest: TypedOperand[T]
) -> Expr[T]: ...
Emits COALESCE(arg1, arg2, ...).
nullif#
def nullif[T: PgValue](a: ValueExpr[T] | ValueExpr[T | None], b: TypedOperand[T]) -> Expr[T | None]: ...
Emits NULLIF(a, b).
greatest#
Emits GREATEST(arg1, arg2, ...).
least#
Emits LEAST(arg1, arg2, ...).
Aggregates & Grouping Sets#
count#
def count(col: ColBase | ExprBase | None = None, *, distinct: bool = False) -> Expr[int]: ...
Emits count(*) (when col is None) or count([DISTINCT] <col>) [FILTER (WHERE <filter>)].
sum#
@overload
def sum(col: Col[Decimal] | Expr[Decimal], *, distinct: bool = False) -> Expr[Decimal | None]: ...
@overload
def sum(col: Col[int] | Expr[int], *, distinct: bool = False) -> Expr[int | Decimal | None]: ...
@overload
def sum(col: Col[float] | Expr[float], *, distinct: bool = False) -> Expr[float | None]: ...
@overload
def sum(col: ColBase | ExprBase, *, distinct: bool = False) -> Expr[PgValue]: ...
Emits sum([DISTINCT] <col>).
avg#
Emits avg([DISTINCT] <col>).
min#
Emits min(<col>).
max#
Emits max(<col>).
array_agg#
def array_agg[T: PgValue](
expr: ValueExpr[T],
*,
distinct: bool = False,
order_by: Sequence[OrderSpec] = (),
filter: Expr[bool] | None = None,
) -> Expr[list[T] | None]: ...
Emits array_agg([DISTINCT] <expr> [ORDER BY ...]) [FILTER (WHERE ...)].
string_agg#
def string_agg(
expr: ValueExpr[str] | ValueExpr[str | None],
sep: str | ValueExpr[str],
*,
distinct: bool = False,
order_by: Sequence[OrderSpec] = (),
filter: Expr[bool] | None = None,
) -> Expr[str | None]: ...
Emits string_agg([DISTINCT] <expr>, <sep> [ORDER BY ...]) [FILTER (WHERE ...)].
jsonb_agg#
def jsonb_agg(
expr: ExprArg,
*,
distinct: bool = False,
order_by: Sequence[OrderSpec] = (),
filter: Expr[bool] | None = None,
) -> Expr[JsonValue | None]: ...
Emits jsonb_agg([DISTINCT] <expr> [ORDER BY ...]) [FILTER (WHERE ...)].
bool_and#
def bool_and(
expr: ValueExpr[bool] | ValueExpr[bool | None], *, filter: Expr[bool] | None = None
) -> Expr[bool | None]: ...
Emits bool_and(<expr>) [FILTER (WHERE ...)].
bool_or#
def bool_or(
expr: ValueExpr[bool] | ValueExpr[bool | None], *, filter: Expr[bool] | None = None
) -> Expr[bool | None]: ...
Emits bool_or(<expr>) [FILTER (WHERE ...)].
percentile_cont#
def percentile_cont(
fraction: float | ValueExpr[float],
*,
order_by: OrderSpec | ColBase | Sequence[OrderSpec | ColBase],
) -> Expr[float | None]: ...
Emits the ordered-set aggregate percentile_cont(<fraction>) WITHIN GROUP (ORDER BY ...).
percentile_disc#
def percentile_disc[T: PgValue](
fraction: float | ValueExpr[float],
*,
order_by: OrderSpec | ColBase | Sequence[OrderSpec | ColBase],
) -> Expr[T | None]: ...
Emits the ordered-set aggregate percentile_disc(<fraction>) WITHIN GROUP (ORDER BY ...).
rollup#
Produces a ROLLUP(...) grouping specification for Select.group_by(...). See Analytics Revenue Report.
cube#
Produces a CUBE(...) grouping specification for Select.group_by(...).
grouping_sets#
Produces a GROUPING SETS ((...), ...) specification for Select.group_by(...).
grouping#
Emits PostgreSQL GROUPING(...) bitmask expression for distinguishing subtotal rows.
GroupBySpec#
@dataclass(frozen=True, kw_only=True, slots=True)
class GroupBySpec:
kind: GroupByKind
sets: tuple[tuple[RustExpr, ...], ...]
Structured grouping-set specification returned by rollup(...), cube(...), and grouping_sets(...).
Window Functions & Frames#
row_number#
Emits row_number(). Chain with .over(...).
rank#
Emits rank(). Chain with .over(...).
dense_rank#
Emits dense_rank(). Chain with .over(...).
lag#
def lag[T: PgValue](
col: ValueExpr[T],
offset: int | None = None,
default: TypedOperand[T] | None = None,
) -> Expr[T | None]: ...
Emits lag(<expr>, <offset>, <default>). Chain with .over(...).
lead#
def lead[T: PgValue](
col: ValueExpr[T],
offset: int | None = None,
default: TypedOperand[T] | None = None,
) -> Expr[T | None]: ...
Emits lead(<expr>, <offset>, <default>). Chain with .over(...).
first_value#
Emits first_value(<expr>). Chain with .over(...).
last_value#
Emits last_value(<expr>). Chain with .over(...).
WindowFrame#
@dataclass(frozen=True, kw_only=True, slots=True)
class WindowFrame:
units: FrameUnits = FrameUnits.ROWS
start: FrameBound = FrameBoundKind.UNBOUNDED_PRECEDING
end: FrameBound | None = FrameBoundKind.CURRENT_ROW
Window frame clause passed to Expr.over(frame=...).
FrameUnits#
Window frame mode (ROWS, RANGE, or GROUPS).
FrameBound#
Start or end boundary of a WindowFrame.
rows_between#
Constructs a ROWS BETWEEN <start> AND <end> window frame.
range_between#
Constructs a RANGE BETWEEN <start> AND <end> window frame.
groups_between#
Constructs a GROUPS BETWEEN <start> AND <end> window frame.
Full-Text Search#
to_tsvector#
Emits to_tsvector([<config>, ]<document>).
to_tsquery#
Emits to_tsquery([<config>, ]<query>).
plainto_tsquery#
Emits plainto_tsquery([<config>, ]<query>).
phraseto_tsquery#
Emits phraseto_tsquery([<config>, ]<query>).
websearch_to_tsquery#
Emits websearch_to_tsquery([<config>, ]<query>).
ts_rank#
Emits ts_rank(<vector>, <query>).
ts_rank_cd#
Emits ts_rank_cd(<vector>, <query>) (cover-density ranking).
JSONB & SQL/JSON Helpers#
jsonb_path_exists#
def jsonb_path_exists(
target: ExprArg,
path: str | ExprArg,
*,
vars: Mapping[str, JsonValue] | ExprBase | None = None,
silent: bool | Expr[bool] | None = None,
) -> Expr[bool]: ...
Emits jsonb_path_exists(<target>, <path>[, <vars>[, <silent>]]).
jsonb_path_match#
def jsonb_path_match(
target: ExprArg,
path: str | ExprArg,
*,
vars: Mapping[str, JsonValue] | ExprBase | None = None,
silent: bool | Expr[bool] | None = None,
) -> Expr[bool]: ...
Emits jsonb_path_match(<target>, <path>[, <vars>[, <silent>]]).
jsonb_path_query_array#
def jsonb_path_query_array(
target: ExprArg,
path: str | ExprArg,
*,
vars: Mapping[str, JsonValue] | ExprBase | None = None,
silent: bool | Expr[bool] | None = None,
) -> Expr[list[JsonValue]]: ...
Emits jsonb_path_query_array(<target>, <path>[, <vars>[, <silent>]]).
jsonb_path_query_first#
def jsonb_path_query_first(
target: ExprArg,
path: str | ExprArg,
*,
vars: Mapping[str, JsonValue] | ExprBase | None = None,
silent: bool | Expr[bool] | None = None,
) -> Expr[JsonValue | None]: ...
Emits jsonb_path_query_first(<target>, <path>[, <vars>[, <silent>]]).
table_row#
References a whole-row composite value (<table>) for use with row_to_json(...) or to_jsonb(...).
row_to_json#
Emits row_to_json(<target>).
to_jsonb#
Emits to_jsonb(<target>).
json_object#
Emits SQL/JSON json_build_object(k1, v1, ...) from keyword pairs.