Skip to content

Typing & Testing Reference#

Public typing primitives in pgdorm.typing (strictly types, protocols, and aliases — zero runtime helper functions) and zero-mock PostgreSQL test helpers in pgdorm.testing.

For usage guides, see Testing Your App and Library Authors.


pgdorm.typing — Typing-Only Protocols & Aliases#

These symbols are exported exclusively from pgdorm.typing for static type checking and generic library code.

ArrowStreamExportable#

signature
class ArrowStreamExportable(Protocol):
    def __arrow_c_stream__(self, requested_schema: object | None = None) -> object: ...

PyCapsule Arrow C Stream Interface protocol implemented by ArrowStream and accepted by Pool.copy_arrow() / Transaction.copy_arrow().

ColBase#

signature
class ColBase:
    @property
    def qualifier(self) -> str: ...
    @overload
    def cast[R: PgValue](self, pg_type: str, *, returns: type[R]) -> Expr[R]: ...
    @overload
    def cast(self, pg_type: str, *, returns: None = None) -> Expr[PgValue]: ...
    def asc(self, *, nulls_first: bool = False, nulls_last: bool = False) -> OrderSpec: ...
    def desc(self, *, nulls_first: bool = False, nulls_last: bool = False) -> OrderSpec: ...

Non-generic runtime base class of Col[T], used in generic helper signatures that accept any column descriptor regardless of its Python value type.

CopyOnError#

signature
class CopyOnError(StrEnum): ...

COPY ... (ON_ERROR ...) error-handling mode.

DdlLockMode#

signature
class LockMode(IntEnum):
    NONE = 1
    SHARE_UPDATE_EXCLUSIVE = 2
    SHARE = 3
    SHARE_ROW_EXCLUSIVE = 4
    ACCESS_EXCLUSIVE = 5

Lock severity level (ACCESS_SHARE, SHARE_UPDATE_EXCLUSIVE, SHARE, SHARE_ROW_EXCLUSIVE, ACCESS_EXCLUSIVE) attached to compiled MigrationStep entries.

DmlStatement#

signature
type DmlStatement[T: Table = Table, S: Table = Table] = (
    Insert[T]
    | InsertFromSelect[T]
    | InsertMany[T]
    | InsertSubtype[T]
    | Update[T]
    | Delete[T]
    | Merge[T, S]
)

Generated#

signature
@dataclass(frozen=True, kw_only=True, slots=True)
class Generated:
    col: ColBase
    expr_sql: str

Typed binding returned from @classmethod def __generated__(cls) -> tuple[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[TableConstraint, ...].

Union of all write DML statement builders.

ExprArg#

signature
type ExprArg = ExprBase | _ToRustValue | ParamRefBase | PgValue

Accepted operand type for pg.func(...), pg.case(...), and expression operators.

ExprBase#

signature
class ExprBase:
    def asc(self, *, nulls_first: bool = False, nulls_last: bool = False) -> OrderSpec: ...
    def desc(self, *, nulls_first: bool = False, nulls_last: bool = False) -> OrderSpec: ...
    @overload
    def cast[R: PgValue](self, pg_type: str, *, returns: type[R]) -> Expr[R]: ...
    @overload
    def cast(self, pg_type: str, *, returns: None = None) -> Expr[PgValue]: ...

Non-generic base class of Expr[T] and ValueExpr[T].

HydrationTarget#

signature
type HydrationTarget = type[object] | None

Target class accepted by .into(...) hydration helpers (slot-backed Table, Pydantic BaseModel, or dataclass).

JsonScalar#

signature
type JsonScalar = bool | int | float | str | None

JSON scalar leaf type used in JsonValue and JsonObject.

ParamRefBase#

signature
@dataclass(frozen=True, kw_only=True, slots=True)
class ParamRefBase:
    name: str
    pg_type: str | None = None

Base dataclass for named query parameters (ParamRef[T] and UntypedParamRef).

PgScalar#

signature
type PgScalar = (
    bool | int | float | str | bytes | bytearray | UUID | date | time | datetime | timedelta
    | Decimal | IPv4Address | IPv6Address | IPv4Interface | IPv6Interface | Enum
    | _RangeLike | _ModelDumpable | _DataclassLike | None
)

Union of scalar Python types natively encoded/decoded by pgdorm-wire.

QueryRow#

signature
type QueryRow = Table | ResultRow

Row shape returned by Select[T] and RETURNING projections.

RowLockMode#

signature
class RowLockMode(StrEnum):
    UPDATE = "update"
    NO_KEY_UPDATE = "no_key_update"
    SHARE = "share"
    KEY_SHARE = "key_share"

Row-level locking mode accepted by Select.for_update(...) / .for_share(...) (alias for LockMode).

Statement#

signature
type Statement[T: Table = Table, S: Table = Table, RetT = T] = Select[RetT] | DmlStatement[T, S]

Union of all compilable SQL statement builders.

TableMeta#

signature
class TableMeta(type): ...

Metaclass for pg.Table and pg.TypeTable that validates schema lint rules, generates __slots__, and builds Col descriptors.

TableRef#

signature
class TableRef(Protocol):
    @property
    @property
    def __name__(self) -> str: ...
    @property
    def __pg_table__(self) -> str: ...
    @property
    def __pg_schema__(self) -> str | None: ...

Structural protocol satisfied by Table subclasses and TableAlias references.

UntypedParamRef#

signature
@dataclass(frozen=True, kw_only=True, slots=True)
class UntypedParamRef(ParamRefBase): ...

Parameter reference created by pg.param("name") without an explicit Python type argument.

ValueExpr#

signature
class ValueExpr[T]: ...

Typed value expression protocol/base shared by Col[T] and Expr[T].

Re-exported Symbols in pgdorm.typing#

All remaining symbols in pgdorm.typing.__all__ are direct re-exports of public types from pgdorm (documented in Models & Types, Queries & DML, Expressions & Functions, and Runtime & Pool) and pgdorm.migrate (documented in Migrations & Assimilation).


pgdorm.testing — Zero-Mock Test Helpers#

pgdorm enforces a zero-mock testing pyramid against live PostgreSQL. Import these helpers from pgdorm.testing (testcontainers is lazily imported via PEP 810).

PG18_IMAGE#

signature
PG18_IMAGE = "postgres:18-alpine"

Default Docker image tag used by postgres_container(...).

PgContainerInfo#

signature
@dataclass(frozen=True, kw_only=True, slots=True)
class PgContainerInfo:
    major_version: int
    host: str
    port: int
    user: str
    password: str
    database: str
    pgbouncer: bool = False
    container_id: str | None = None
    dsn_override: str | None = None
    pool_mode_override: pgdorm.enums.PoolMode | None = None

Immutable connection metadata for a running PostgreSQL test container or external --dsn override.

SnapshotValue#

signature
type SnapshotValue = _SnapshotAtom | Sequence[SnapshotValue]

Recursive type of values formatted by the pgdorm Syrupy snapshot serializer.

TestDB#

signature
class TestDB(Pool): ...

Test-scoped Pool subclass pinned to an isolated PostgreSQL schema (search_path=schema).

assert_compiles#

signature
def assert_compiles(
    stmt: Executable[object],
    expected_sql: str,
    *,
    param_types: Sequence[str] | None = None,
    search_path: str | None = None,
    cacheable: bool | None = None,
    requires_pg19: bool | None = None,
) -> CompiledQuery: ...

Compile stmt without a database connection and assert exact canonical SQL plus optional param_types, cacheable, and requires_pg19 metadata.

compile_query#

signature
def compile(
    stmt: Executable[object],
    *,
    search_path: str | None = None,
) -> CompiledQuery: ...

Re-export of pgdorm.compile for pure-unit compilation tests.

make_syrupy_extension#

signature
def make_syrupy_extension() -> type[_SnapshotExtensionProto]: ...

Build a syrupy AmberSnapshotExtension subclass that deterministically serializes Table, Range, Enum, UUID, datetime, ExplainPlan, and Trace values and strips ephemeral schema prefixes.

normalize_sql_for_docs#

signature
def normalize_sql_for_docs(sql: str) -> str: ...

Strip ephemeral per-test schema prefixes ("t_<hex>". and "dorm_ro_...".) from compiled SQL for stable snapshots and documentation.

postgres_container#

signature
def postgres_container(
    *,
    image: str = PG18_IMAGE,
    username: str = "postgres",
    password: str = "pgdorm_test_password",
    dbname: str = "pgdorm",
    command: str | None = None,
) -> PostgresContainer: ...

Construct a configured testcontainers PostgreSQL container (driver=None, defaulting to PG18_IMAGE).

write_or_check_readme#

signature
def write_or_check_readme(readme_path: Path, content: str, *, update: bool, check: bool) -> None: ...

Write a generated README when update=True (--update-readmes) or assert zero drift when check=True (--check-readmes).


pgdorm.enums — Strict StrEnum Option Namespace#

All discrete ORM choices live under pg.enums (pgdorm.enums) and are re-exported from pgdorm.typing. Bare string literals are rejected both statically and at runtime.

enums#

signature
import pgdorm.enums as enums

Submodule namespace exposing all strict ORM StrEnum option types (pg.enums.OnDelete.CASCADE, pg.enums.PoolMode.TRANSACTION, pg.enums.IsolationLevel.SERIALIZABLE, etc.).

ExtractField#

signature
class ExtractField(StrEnum):
    CENTURY = "CENTURY"
    DAY = "DAY"
    DECADE = "DECADE"
    DOW = "DOW"
    DOY = "DOY"
    EPOCH = "EPOCH"
    HOUR = "HOUR"
    ISODOW = "ISODOW"
    ISOYEAR = "ISOYEAR"
    JULIAN = "JULIAN"
    MICROSECONDS = "MICROSECONDS"
    MILLENNIUM = "MILLENNIUM"
    MILLISECONDS = "MILLISECONDS"
    MINUTE = "MINUTE"
    MONTH = "MONTH"
    QUARTER = "QUARTER"
    SECOND = "SECOND"
    TIMEZONE = "TIMEZONE"
    TIMEZONE_HOUR = "TIMEZONE_HOUR"
    TIMEZONE_MINUTE = "TIMEZONE_MINUTE"
    WEEK = "WEEK"
    YEAR = "YEAR"

Closed set of PostgreSQL EXTRACT(field FROM ...) field names accepted by pg.extract(...).

FrameBoundKind#

signature
class FrameBoundKind(StrEnum):
    UNBOUNDED_PRECEDING = "unbounded_preceding"
    CURRENT_ROW = "current_row"
    UNBOUNDED_FOLLOWING = "unbounded_following"

Unbounded/current-row window frame boundary markers (UNBOUNDED_PRECEDING, CURRENT_ROW, UNBOUNDED_FOLLOWING).

FrameOffsetDir#

signature
class FrameOffsetDir(StrEnum):
    PRECEDING = "preceding"
    FOLLOWING = "following"

Offset direction (PRECEDING, FOLLOWING) used in (offset, direction) window frame bounds.

GeneratedMode#

signature
class GeneratedMode(StrEnum):
    VIRTUAL = "virtual"
    STORED = "stored"

Generated column storage mode (VIRTUAL or STORED) accepted by pg.generated(...).

GroupByKind#

signature
class GroupByKind(StrEnum):
    EXPR = "expr"
    ROLLUP = "rollup"
    CUBE = "cube"
    GROUPING_SETS = "grouping_sets"

GROUP BY clause variant (EXPR, ROLLUP, CUBE, GROUPING_SETS).

IndexOrder#

signature
class IndexOrder(StrEnum):
    ASC = ""
    DESC = "DESC"
    ASC_NULLS_FIRST = "ASC NULLS FIRST"
    DESC_NULLS_LAST = "DESC NULLS LAST"

Canonical B-tree index column sort direction and NULLS ordering.

OnCommit#

signature
class OnCommit(StrEnum):
    DELETE_ROWS = "delete_rows"
    DROP = "drop"

Temporary staging table ON COMMIT behavior (DELETE_ROWS, DROP).

OnDelete#

signature
class OnDelete(StrEnum):
    NO_ACTION = "no_action"
    RESTRICT = "restrict"
    CASCADE = "cascade"
    SET_NULL = "set_null"
    SET_DEFAULT = "set_default"

Foreign-key ON DELETE referential action (NO_ACTION, RESTRICT, CASCADE, SET_NULL, SET_DEFAULT).

PartitionStrategy#

signature
class PartitionStrategy(StrEnum):
    RANGE = "range"
    LIST = "list"
    HASH = "hash"

Declarative table partitioning strategy (RANGE, LIST, HASH).

SearchOrder#

signature
class SearchOrder(StrEnum):
    DEPTH = "depth"
    BREADTH = "breadth"

Recursive CTE SEARCH DEPTH/BREADTH FIRST traversal order.

SetOpKind#

signature
class SetOpKind(StrEnum):
    UNION = "union"
    UNION_ALL = "union_all"
    INTERSECT = "intersect"
    INTERSECT_ALL = "intersect_all"
    EXCEPT = "except"
    EXCEPT_ALL = "except_all"

SQL set-operation combinator kind (UNION, UNION_ALL, INTERSECT, INTERSECT_ALL, EXCEPT, EXCEPT_ALL).