Models & Types#
pgdorm models are slot-backed Python classes (__slots__, zero __dict__) that compile directly to PostgreSQL DDL and Rust IR specs.
See Hello Dorm, Column Types & DDL, Temporal Bookings, Inheritance, Payments & Tasks, and Partitioning Door Events.
Tables & Columns#
Table#
class Table(metaclass=TableMeta):
@property
def xmin(self) -> int | None: ...
@classmethod
def alias(cls, name: str) -> type[Self]: ...
Base class for all pgdorm entity tables. Derives the PostgreSQL table name strictly in singular snake_case from the class name (explicit name="..." overrides raise SchemaLintError). Enforces own-PK hygiene (<table_name>_id), disjoint TypeTable naming, and __slots__ layout. Supports class keyword options such as schema=, temp=, on_commit=, partition_by=, strict_pk=, and inherits= / discriminator_value= for class-table inheritance.
TypeTable#
Base class for lookup / enum-backed reference tables. Subclass names must end with Type (_type), use an int4 primary key, and declare a unique code column. Raises SchemaLintError on naming or IntEnum mapping collisions. See Type Tables & Enums.
Col#
class Col[T](ColBase, _ExprOpsMixin[T], ValueExpr[T]):
def alias(self, name: str) -> Expr[T]: ...
def in_any(
self,
values: Sequence[T] | ParamRef[Sequence[T]] | ParamRef[list[T]] | UntypedParamRef,
) -> Expr[bool]: ...
def ne_all(self, values: Sequence[T]) -> Expr[bool]: ...
def overlaps(self, other: TypedOperand[T]) -> Expr[bool]: ...
def contains(self, other: ExprArg) -> Expr[bool]: ...
def to(self, value: TypedOperand[T] | UnsetType) -> Assign: ...
@classmethod
def from_resolved(
cls,
*,
name: str,
resolved: ResolvedColType,
owner: TableRef,
spec: _FieldSpec,
pg_type: str | None = None,
nullable: bool | None = None,
py_type: TypeFormLike | UnsetType | None = UNSET,
enum_type: type[Enum] | UnsetType | None = UNSET,
) -> ColBase: ...
Typed column descriptor bound to a Table class attribute. Accessing MyTable.column_name returns a Col[T] that supports typed comparison, arithmetic, ordering (.asc(), .desc()), JSONB, and full-text operators; accessing the same attribute on an instance returns the hydrated Python value T.
col#
def col(
*,
unique: bool = False,
index: bool = False,
max_len: int | None = None,
precision: int | None = None,
scale: int | None = None,
server_managed: bool = False,
secret: bool = False,
default: PgValue | ServerDefault | ServerDefaultExprBase | UnsetType = UNSET,
default_factory: Callable[[], PgValue] | None = None,
) -> Any: ...
Declares column metadata on a Table field: uniqueness (unique), server-populated values (server_managed), redaction in repr/logs (secret), and literal, server-side, or client-side defaults.
pk#
def pk(
*,
default: ServerDefault | UnsetType = UNSET,
server_managed: bool = False,
) -> Any: ...
Marks a field as the table's primary key (<table_name>_id). Entity int PKs default to BIGINT (int8); TypeTable PKs default to INTEGER (int4). Pair with identity() or uuidv7().
fk#
def fk(
target: ColBase | TableRef,
*,
on_delete: OnDelete | None = None,
auto_index: bool = True,
unique: bool = False,
deferrable: bool = False,
initially_deferred: bool = False,
default: PgValue | ServerDefault | ServerDefaultExprBase | UnsetType = UNSET,
) -> Any: ...
Declares a single-column foreign key referencing target (either a Table class or an explicit Table.column). Automatically generates a supporting B-tree index (auto_index=True, deduplicated against leftmost-prefix indexes) and supports unique=True and DEFERRABLE / INITIALLY DEFERRED constraints.
self_fk#
def self_fk(
target_col: str | None = None,
*,
on_delete: OnDelete | None = None,
auto_index: bool = True,
unique: bool = False,
deferrable: bool = False,
initially_deferred: bool = False,
default: PgValue | ServerDefault | ServerDefaultExprBase | UnsetType = UNSET,
) -> Any: ...
Declares an inline self-referential foreign key pointing to the table's own primary key (or target_col), eliminating the need for table-level ForeignKey(...) on tree/hierarchy models.
identity#
Returns a PostgreSQL GENERATED BY DEFAULT AS IDENTITY server default for pk(default=identity()).
uuidv7#
Returns a native DEFAULT uuidv7() server default (or a client-generated UUIDv7 default when client_generated=True). See Column Types & DDL.
new_uuidv7#
Generates a monotonic RFC 9562 UUIDv7 in Rust without a database round-trip.
generated#
def generated(
*,
mode: GeneratedMode = GeneratedMode.VIRTUAL,
init: Literal[False] = False,
) -> Any: ...
Declares a generated column (GENERATED ALWAYS AS (...) VIRTUAL by default, or STORED), paired with a pg.Generated(cls.<col>, <expr>) entry inside @classmethod def __generated__(cls). Excluded from __init__ and INSERT payloads.
Generated#
@dataclass(frozen=True, kw_only=True, slots=True)
class Generated:
col: ColBase
expr_sql: str
Typed binding between a pg.generated() column descriptor and its typed pg.Expr[T] expression, returned from @classmethod def __generated__(cls) -> tuple[pg.Generated, ...].
TableConstraint#
type TableConstraint = (
PrimaryKey
| Unique
| Index
| Check
| ForeignKey
| TemporalPrimaryKey
| TemporalUnique
| PartitionBy
)
Union of all table-level constraint and partitioning descriptors returned from @classmethod def __constraints__(cls) -> tuple[pg.TableConstraint, ...].
uuidv4#
PostgreSQL gen_random_uuid() default for random UUIDv4 keys (set client_generated=True to mint UUIDv4 values in Python).
current_date#
PostgreSQL CURRENT_DATE server-side default for date columns.
discriminator#
def discriminator(
target: ColBase,
*,
on_delete: OnDelete = OnDelete.RESTRICT,
auto_index: bool = True,
init: Literal[False] = False,
) -> Any: ...
Declares an IntEnum/TypeTable-backed discriminator column for Class-Table Inheritance (CTI). String discriminators are forbidden (SchemaLintError). See Inheritance, Payments & Tasks.
xmin#
Returns a typed Col[int] descriptor for PostgreSQL's xmin system column on table, used for optimistic concurrency control.
Table Constraints & Partitioning#
PrimaryKey#
@dataclass(frozen=True, kw_only=True, slots=True)
class PrimaryKey:
col_refs: tuple[ColRefArg, ...]
Declares a composite table-level PRIMARY KEY inside __constraints__.
ForeignKey#
@dataclass(frozen=True, kw_only=True, slots=True)
class ForeignKey:
local_refs: tuple[ColRefArg, ...]
ref_cols: tuple[ColRefArg, ...]
on_delete: OnDelete | SetNull | None = None
auto_index: bool = True
deferrable: bool = False
initially_deferred: bool = False
Declares a composite or table-level FOREIGN KEY constraint inside __constraints__. Supports deferrable=True, initially_deferred=True, SetNull(...) partial-column nullification, and auto_index=True.
Unique#
@dataclass(frozen=True, kw_only=True, slots=True)
class Unique:
col_refs: tuple[ColRefArg, ...]
Declares a UNIQUE constraint across one or more columns.
Check#
Declares a CHECK (<expr_sql>) constraint on a Table.
Index#
@dataclass(frozen=True, kw_only=True, slots=True)
class Index:
col_refs: tuple[IndexColArg, ...]
unique: bool = False
where_sql: str | None = None
Declares a B-tree, unique, or partial (where_sql=...) index inside __indexes__.
TemporalPrimaryKey#
@dataclass(frozen=True, kw_only=True, slots=True)
class TemporalPrimaryKey:
col_refs: tuple[ColRefArg, ...]
Declares a PostgreSQL PRIMARY KEY (..., <range_col> WITHOUT OVERLAPS) constraint. Exempts the table from the single-column <table_name>_id lint rule. See Temporal Bookings.
TemporalUnique#
@dataclass(frozen=True, kw_only=True, slots=True)
class TemporalUnique:
col_refs: tuple[ColRefArg, ...]
Declares a PostgreSQL UNIQUE (..., <range_col> WITHOUT OVERLAPS) constraint.
PartitionBy#
@dataclass(frozen=True, kw_only=True, slots=True)
class PartitionBy:
strategy: PartitionStrategy
columns: tuple[str, ...]
Configures declarative PostgreSQL partitioning (PARTITION BY RANGE | LIST | HASH (...)) on a Table. See Partitioning Door Events.
SetNull#
@dataclass(frozen=True, kw_only=True, slots=True)
class SetNull:
col_refs: tuple[ColRefArg, ...]
Specifies PostgreSQL ON DELETE SET NULL (<col_refs>) for partial-column nullification on composite ForeignKey constraints.
Registry & DTOs#
Registry#
class Registry:
def register(self, *tables: type[Table]) -> Self: ...
def freeze(self) -> FrozenRegistry: ...
Mutable collector for a set of Table classes. Calling .freeze() validates schema-set uniqueness (SchemaLintError on duplicate physical tables, index names, TypeTable enum mappings, constraint names, or CTI parent collisions) and returns an immutable FrozenRegistry.
FrozenRegistry#
@dataclass(frozen=True, kw_only=True, slots=True)
class FrozenRegistry:
tables: tuple[type[Table], ...]
ir_specs: tuple[TableIrSpec, ...]
Immutable, validated snapshot of a Registry ready for DDL generation, migrations, and ERD rendering.
Create#
class Create[T: Table = Table](_DtoBase[T]):
def to_dict(self) -> dict[str, PgValue]: ...
def to_model(self, **overrides: PgValue | UnsetType) -> T: ...
Typed creation DTO for Pool.insert(...) and insert(...), omitting server-managed and generated columns. See Patch & Returning.
Patch#
class Patch[T: Table = Table](_DtoBase[T]):
@property
def dirty_mask(self) -> int: ...
@overload
def set(self, column: ColBase, value: UnsetType) -> Self: ...
@overload
def set[V: PgValue](self, column: Col[V], value: V | UnsetType) -> Self: ...
def get[V: PgValue](self, column: Col[V]) -> V | UnsetType: ...
def dirty_fields(self) -> tuple[str, ...]: ...
def to_values(self) -> dict[str, PgValue]: ...
Typed partial-update DTO distinguishing omitted fields (UNSET) from explicit None (NULL) values. Used with Update.patch(...) and Pool.update_versioned(...).
UNSET#
Singleton sentinel indicating an omitted field in a Patch or column default.
UnsetType#
Type of the UNSET sentinel.
Custom Types & PostgreSQL Type Markers#
TypeDecorator#
class TypeDecorator[PyT, WireT: PgValue]:
impl: str = "text"
def process_bind_param(self, value: PyT) -> WireT: ...
def process_result_value(self, value: WireT) -> PyT: ...
def apply_pg_type(self, inner: ResolvedColType) -> ResolvedColType: ...
Base class for user-defined Python-to-PostgreSQL value codecs. Subclass and attach via Annotated[PyT, MyDecorator()].
CustomType#
Annotated metadata marker that maps a Python field to an arbitrary PostgreSQL type name (e.g., Annotated[str, CustomType("citext")]).
Int2#
Maps a Python int field to PostgreSQL SMALLINT (int2).
Int4#
Maps a Python int field to PostgreSQL INTEGER (int4).
BigInt#
Maps a Python int field to PostgreSQL BIGINT (int8).
Float4#
Maps a Python float field to PostgreSQL REAL (float4).
Numeric#
@dataclass(frozen=True, kw_only=True, slots=True)
class Numeric:
precision: int
scale: int | None = None
Annotated metadata marker for Decimal fields, emitting NUMERIC(precision) or NUMERIC(precision, scale).
MaxLen#
Annotated metadata marker for str fields, emitting VARCHAR(length).
Timestamp#
Maps a datetime field to TIMESTAMP WITHOUT TIME ZONE (bare datetime defaults to TIMESTAMPTZ).
Range#
@dataclass(frozen=True, kw_only=True, slots=True)
class Range[T]:
lower: T | None = None
upper: T | None = None
lower_inc: bool = True
upper_inc: bool = False
empty: bool = False
Immutable representation of PostgreSQL range types (int4range, int8range, numrange, daterange, tsrange, tstzrange). See Temporal Bookings.
Json#
Maps a field (dict, list, dataclass, or Pydantic model) to PostgreSQL JSON.
Jsonb#
Maps a field (dict, list, dataclass, or Pydantic model) to PostgreSQL JSONB.
JsonValue#
Recursive type alias for any JSON-compatible value.
JsonObject#
Type alias for a JSON object (dict[str, JsonValue]).
JsonPath#
Maps a str field or parameter to PostgreSQL's jsonpath type.
JsonMode#
Controls whether Pool.json(...) / Pool.json_one(...) serializes JSON in Rust ("client", zero Python object allocation) or via PostgreSQL ("server"). See Wire & JSON.
TsVector#
Maps a str field to PostgreSQL tsvector for full-text search.
TsQuery#
Maps a str field or parameter to PostgreSQL tsquery.
PgValue#
Union of all Python values accepted as bind parameters by the Rust wire encoder.
ERD & Engine Introspection#
to_svg_erd#
Validates the schema set (SchemaLintError on collisions) and renders a deterministic SVG Entity-Relationship Diagram in Rust.
Pass focus=(...) to draw an excerpt: the focus tables in full with a highlighted border and a NEW tag, their direct foreign-key neighbours faded with key columns only, and every other table left out. The Renovations tutorial uses this to show each step's additions in context.
engine_version#
Returns the compiled pgdorm Rust/Python package version string.
min_postgres_version#
Returns the minimum supported PostgreSQL server_version_num (see Requirements).