Skip to content

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#

signature
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#

signature
class TypeTable(Table, abstract=True):
    code: Col[str] = col(unique=True)

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#

signature
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#

signature
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#

signature
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#

signature
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#

signature
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#

signature
def identity() -> ServerDefault: ...

Returns a PostgreSQL GENERATED BY DEFAULT AS IDENTITY server default for pk(default=identity()).

uuidv7#

signature
def uuidv7(*, client_generated: bool = False) -> ServerDefault: ...

Returns a native DEFAULT uuidv7() server default (or a client-generated UUIDv7 default when client_generated=True). See Column Types & DDL.

new_uuidv7#

signature
def new_uuidv7() -> UUID: ...

Generates a monotonic RFC 9562 UUIDv7 in Rust without a database round-trip.

generated#

signature
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#

signature
@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#

signature
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#

signature
def uuidv4(*, client_generated: bool = False) -> ServerDefault: ...

PostgreSQL gen_random_uuid() default for random UUIDv4 keys (set client_generated=True to mint UUIDv4 values in Python).

current_date#

signature
def current_date() -> ServerDefault: ...

PostgreSQL CURRENT_DATE server-side default for date columns.

discriminator#

signature
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#

signature
def xmin(table: TableRef) -> Col[int]: ...

Returns a typed Col[int] descriptor for PostgreSQL's xmin system column on table, used for optimistic concurrency control.


Table Constraints & Partitioning#

PrimaryKey#

signature
@dataclass(frozen=True, kw_only=True, slots=True)
class PrimaryKey:
    col_refs: tuple[ColRefArg, ...]

Declares a composite table-level PRIMARY KEY inside __constraints__.

ForeignKey#

signature
@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#

signature
@dataclass(frozen=True, kw_only=True, slots=True)
class Unique:
    col_refs: tuple[ColRefArg, ...]

Declares a UNIQUE constraint across one or more columns.

Check#

signature
@dataclass(frozen=True, kw_only=True, slots=True)
class Check:
    expr_sql: str

Declares a CHECK (<expr_sql>) constraint on a Table.

Index#

signature
@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#

signature
@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#

signature
@dataclass(frozen=True, kw_only=True, slots=True)
class TemporalUnique:
    col_refs: tuple[ColRefArg, ...]

Declares a PostgreSQL UNIQUE (..., <range_col> WITHOUT OVERLAPS) constraint.

PartitionBy#

signature
@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#

signature
@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#

signature
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#

signature
@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#

signature
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#

signature
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#

signature
UNSET = UnsetType()

Singleton sentinel indicating an omitted field in a Patch or column default.

UnsetType#

signature
class UnsetType: ...

Type of the UNSET sentinel.


Custom Types & PostgreSQL Type Markers#

TypeDecorator#

signature
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#

signature
@dataclass(frozen=True, kw_only=True, slots=True)
class CustomType:
    pg_type: str

Annotated metadata marker that maps a Python field to an arbitrary PostgreSQL type name (e.g., Annotated[str, CustomType("citext")]).

Int2#

signature
type Int2 = Annotated[int, _PgTypeHint(pg_type="int2", explicit_int_width=True)]

Maps a Python int field to PostgreSQL SMALLINT (int2).

Int4#

signature
type Int4 = Annotated[int, _PgTypeHint(pg_type="int4", explicit_int_width=True)]

Maps a Python int field to PostgreSQL INTEGER (int4).

BigInt#

signature
type BigInt = Annotated[int, _PgTypeHint(pg_type="int8", explicit_int_width=True)]

Maps a Python int field to PostgreSQL BIGINT (int8).

Float4#

signature
type Float4 = Annotated[float, _PgTypeHint(pg_type="float4")]

Maps a Python float field to PostgreSQL REAL (float4).

Numeric#

signature
@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#

signature
@dataclass(frozen=True, kw_only=True, slots=True)
class MaxLen:
    length: int

Annotated metadata marker for str fields, emitting VARCHAR(length).

Timestamp#

signature
type Timestamp = Annotated[datetime, _PgTypeHint(pg_type="timestamp")]

Maps a datetime field to TIMESTAMP WITHOUT TIME ZONE (bare datetime defaults to TIMESTAMPTZ).

Range#

signature
@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#

signature
type Json[T] = Annotated[T, _PgTypeHint(pg_type="json")]

Maps a field (dict, list, dataclass, or Pydantic model) to PostgreSQL JSON.

Jsonb#

signature
type Jsonb[T] = Annotated[T, _PgTypeHint(pg_type="jsonb")]

Maps a field (dict, list, dataclass, or Pydantic model) to PostgreSQL JSONB.

JsonValue#

signature
type JsonValue = JsonScalar | Sequence[JsonValue] | Mapping[str, JsonValue]

Recursive type alias for any JSON-compatible value.

JsonObject#

signature
type JsonObject = dict[str, JsonValue]

Type alias for a JSON object (dict[str, JsonValue]).

JsonPath#

signature
type JsonPath = Annotated[str, _PgTypeHint(pg_type="jsonpath")]

Maps a str field or parameter to PostgreSQL's jsonpath type.

JsonMode#

signature
class JsonMode(StrEnum):
    CLIENT = "client"
    SERVER = "server"

Controls whether Pool.json(...) / Pool.json_one(...) serializes JSON in Rust ("client", zero Python object allocation) or via PostgreSQL ("server"). See Wire & JSON.

TsVector#

signature
type TsVector = Annotated[str, _PgTypeHint(pg_type="tsvector")]

Maps a str field to PostgreSQL tsvector for full-text search.

TsQuery#

signature
type TsQuery = Annotated[str, _PgTypeHint(pg_type="tsquery")]

Maps a str field or parameter to PostgreSQL tsquery.

PgValue#

signature
type PgValue = PgScalar | Sequence[PgValue] | Mapping[str, PgValue]

Union of all Python values accepted as bind parameters by the Rust wire encoder.


ERD & Engine Introspection#

to_svg_erd#

signature
def to_svg_erd(*tables: type[Table], focus: Sequence[type[Table]] = ()) -> str: ...

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#

signature
def engine_version() -> str: ...

Returns the compiled pgdorm Rust/Python package version string.

min_postgres_version#

signature
def min_postgres_version() -> int: ...

Returns the minimum supported PostgreSQL server_version_num (see Requirements).