Migrations & Assimilation Reference#
Complete API reference for all 172 public exports of pgdorm.migrate — online PostgreSQL schema migrations, catalog introspection, AST diffing, lock-timeout guards, and legacy schema assimilation.
For conceptual walkthroughs and operational playbooks, see The Renovations — Migrations Story (8 live-verified chapters), Online Migrations (Launch Day), Schema Assimilation, and Library Authors.
Execution & Lifecycle#
apply_ddl#
async def apply_ddl(
conn: Pool | Transaction,
*ops: MigrationOp,
schema: str | None = None,
online: bool = True,
) -> MigrationPlan: ...
Compile and execute typed MigrationOps directly without writing to the ledger.
baseline_schema#
async def baseline_schema(
pool: Pool,
tables: Sequence[type[Table]] = (),
*,
schema: str | None = None,
version: str = "0000_baseline",
name: str = "baseline",
ignore_tables: frozenset[str] = frozenset(),
) -> MigrationRecord: ...
Adopt an existing schema (e.g. from create_all()) into _pgdorm.migration.
check_drift#
async def check_drift(
pool: Pool,
*,
schema: str | None = None,
tables: Sequence[type[Table]] = (),
ignore_tables: frozenset[str] = frozenset(),
) -> DriftReport: ...
Compare last _pgdorm.migration snapshot against live pg_catalog state.
cli_main#
Public cli_main export from pgdorm.migrate.
ensure_pgdorm_schema#
Self-hosted bootstrap & self-migration of the internal _pgdorm schema.
execute_step#
Execute one compiler-produced MigrationStep (sealed Rust DDL, binary query, or Python).
migration_events#
async def migration_events(
pool: Pool,
*,
schema: str | None = None,
migration_id: int | None = None,
) -> list[MigrationEventRecord]: ...
Return _pgdorm.migration_event rows as hydrated MigrationEventRecords.
migration_history#
async def migration_history(pool: Pool, *, schema: str | None = None) -> list[MigrationRecord]: ...
Return all _pgdorm.migration rows for schema as hydrated MigrationRecords.
migration_steps#
async def migration_steps(
pool: Pool,
*,
schema: str | None = None,
migration_id: int | None = None,
) -> list[MigrationStepRecord]: ...
Return _pgdorm.migration_step rows as hydrated MigrationStepRecords.
plan_migration#
async def plan_migration(
pool: Pool,
tables: Sequence[type[Table]],
*,
schema: str | None = None,
name: str = "sync",
version: str | None = None,
online: bool = True,
ignore_tables: frozenset[str] = frozenset(),
) -> MigrationPlan: ...
Dry-run diff of tables against live pg_catalog and compile online steps.
run_cli#
Public run_cli export from pgdorm.migrate.
sync_schema#
async def sync_schema(
pool: Pool,
tables: Sequence[type[Table]],
*,
schema: str | None = None,
name: str = "sync",
version: str | None = None,
online: bool = True,
lock_timeout: str = "2s",
statement_timeout: str = "30s",
lock_retries: int = 3,
lock_retry_delay: float = 0.2,
allow_destructive: bool = False,
allow_breaking: bool = False,
allow_drift: bool = False,
lease_seconds: int = 300,
ignore_tables: frozenset[str] = frozenset(),
) -> MigrationRecord | None: ...
Mode A: zero-file declarative sync returning the persisted _pgdorm.migration record.
upgrade_schema#
async def upgrade_schema(
pool: Pool,
migrations: Sequence[Migration],
*,
schema: str | None = None,
tables: Sequence[type[Table]] = (),
online: bool = True,
lock_timeout: str = "2s",
statement_timeout: str = "30s",
lock_retries: int = 3,
lock_retry_delay: float = 0.2,
allow_destructive: bool = False,
allow_breaking: bool = False,
verify_checksums: bool = True,
lease_seconds: int = 300,
ignore_tables: frozenset[str] = frozenset(),
) -> list[MigrationRecord]: ...
Mode B: apply ordered pg.Migration values with checksum & baseline verification.
Planning, Drift & Snapshots#
LEGACY_MIGRATION_TABLES#
LEGACY_MIGRATION_TABLES: frozenset[str] = frozenset(
{
"alembic_version",
"ar_internal_metadata",
"django_migrations",
"flyway_schema_history",
"knex_migrations",
"knex_migrations_lock",
"_prisma_migrations",
"schema_migrations",
"spatial_ref_sys",
}
)
Build an immutable unordered collection of unique elements.
ONBOARDING_RULES#
ONBOARDING_RULES: tuple[OnboardingRule, ...] = (
OnboardingRule(
code="TABLE_NAME_NON_SNAKE",
category=RuleCategory.NAMING,
severity=AuditSeverity.BLOCKER,
support_status=SupportStatus.MIGRATABLE,
title="Non-snake_case or mixed-case table name",
summary="Table name is not snake_case (`mode='bind'` requires singular snake_case).",
action="Use `mode='assimilate'` so AdoptionMap renames it, or exclude via `ignore_tables`.",
auto_fixable=True,
doc_anchor="table-naming",
),
OnboardingRule(
code="TABLE_NAME_BUILTIN_COLLISION",
category=RuleCategory.NAMING,
severity=AuditSeverity.BLOCKER,
support_status=SupportStatus.MIGRATABLE,
title="Table class name collides with a Python builtin",
summary="PascalCase model name shadows a Python builtin (e.g. `ImportError`).",
action="Use `mode='assimilate'` to map to `<name>_record`, or exclude via `ignore_tables`.",
auto_fixable=True,
doc_anchor="table-naming",
),
OnboardingRule(
code="TABLE_NAME_PLURAL",
category=RuleCategory.NAMING,
severity=AuditSeverity.MIGRATION_REQUIRED,
support_status=SupportStatus.MIGRATABLE,
title="Plural table name",
summary="Table name appears plural (`users`, `order_items`); pgdorm models are singular.",
action="Rename table to singular snake_case via AdoptionMap.",
auto_fixable=True,
doc_anchor="table-naming",
),
OnboardingRule(
code="TABLE_NAME_RESERVED",
category=RuleCategory.NAMING,
severity=AuditSeverity.MIGRATION_REQUIRED,
support_status=SupportStatus.MIGRATABLE,
title="Python keyword or reserved identifier",
summary="Table or column name collides with a Python keyword (`class`, `from`, `type`).",
action="Rename table or column to a valid Python identifier via AdoptionMap.",
auto_fixable=True,
doc_anchor="table-naming",
),
OnboardingRule(
code="NON_TYPE_TABLE_ENDS_WITH_TYPE",
category=RuleCategory.NAMING,
severity=AuditSeverity.MIGRATION_REQUIRED,
support_status=SupportStatus.MIGRATABLE,
title="Regular entity table ending in `_type`",
summary="The `_type` suffix is strictly reserved for `pg.TypeTable` enum lookup tables.",
action="Either promote to `pg.TypeTable` or rename the entity table (e.g. `*_kind`).",
auto_fixable=True,
doc_anchor="type-table-namespace",
),
OnboardingRule(
code="PK_NAME_MISMATCH",
category=RuleCategory.PRIMARY_KEY,
severity=AuditSeverity.MIGRATION_REQUIRED,
support_status=SupportStatus.MIGRATABLE,
title="Primary key not named `<table_name>_id`",
summary="Permanent tables declare `<table_name>_id` so joins auto-emit `JOIN ... USING`.",
action="Rename single int/UUID PK to `<table_name>_id`, or add surrogate PK.",
auto_fixable=True,
doc_anchor="primary-keys-and-serials",
),
OnboardingRule(
code="PK_COMPOSITE",
category=RuleCategory.PRIMARY_KEY,
severity=AuditSeverity.MIGRATION_REQUIRED,
support_status=SupportStatus.MIGRATABLE,
title="Composite primary key on permanent table",
summary="Junction/entity tables use a surrogate `<table_name>_id` PK + `pg.Unique(...)`.",
action="Add surrogate `<table_name>_id` PK and demote composite PK to `pg.Unique(...)`.",
auto_fixable=True,
doc_anchor="primary-keys-and-serials",
),
OnboardingRule(
code="PK_MISSING",
category=RuleCategory.PRIMARY_KEY,
severity=AuditSeverity.MIGRATION_REQUIRED,
support_status=SupportStatus.MIGRATABLE,
title="Table has no primary key",
summary="Permanent tables require a `<table_name>_id` primary key.",
action="Add `<table_name>_id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY`.",
auto_fixable=True,
doc_anchor="primary-keys-and-serials",
),
OnboardingRule(
code="SERIAL_COLUMN",
category=RuleCategory.PRIMARY_KEY,
severity=AuditSeverity.INFO,
support_status=SupportStatus.SUPPORTED,
title="Legacy SERIAL / sequence `nextval(...)` default",
summary="SERIAL PKs auto-upgrade to `pg.identity()` (or `server_managed=True` in bind).",
action="Assimilate upgrades SERIAL PKs to IDENTITY; bind uses `server_managed=True`.",
auto_fixable=True,
doc_anchor="primary-keys-and-serials",
),
OnboardingRule(
code="TYPE_TABLE_CANDIDATE",
category=RuleCategory.TYPE_TABLE,
severity=AuditSeverity.INFO,
support_status=SupportStatus.MIGRATABLE,
title="Lookup table candidate for `pg.TypeTable`",
summary="Referenced table has an int/UUID PK and unique short text column.",
action="Review candidate; pass `--type-table <table>` or `as_type_table=True` to promote.",
auto_fixable=True,
doc_anchor="type-table-namespace",
),
OnboardingRule(
code="PG_NATIVE_ENUM",
category=RuleCategory.TYPES,
severity=AuditSeverity.INFO,
support_status=SupportStatus.MIGRATABLE,
title="PostgreSQL native `CREATE TYPE ... AS ENUM`",
summary="Zero-DDL Bind binds PG enums via `CustomType` (no `CREATE TYPE` DDL).",
action="Use `mode='assimilate'` to migrate PG enums into seeded `IntEnum` `pg.TypeTable`s.",
auto_fixable=True,
doc_anchor="column-types",
),
OnboardingRule(
code="CUSTOM_OR_EXTENSION_TYPE",
category=RuleCategory.TYPES,
severity=AuditSeverity.INFO,
support_status=SupportStatus.SUPPORTED,
title="Extension, domain, or custom column type",
summary="Types like `citext`, `ltree`, `vector`, or PG domains bind via `pg.CustomType`.",
action="Scaffold emits `Annotated[str, pg.CustomType(pg_type=...)]` for review.",
auto_fixable=False,
doc_anchor="column-types",
),
OnboardingRule(
code="TIMESTAMP_WITHOUT_TZ",
category=RuleCategory.TYPES,
severity=AuditSeverity.INFO,
support_status=SupportStatus.SUPPORTED,
title="`TIMESTAMP WITHOUT TIME ZONE` column",
summary="Supported natively via `pg.Timestamp` (plain `datetime` maps to `TIMESTAMPTZ`).",
action="Scaffold emits `pg.Col[pg.Timestamp]` automatically.",
auto_fixable=False,
doc_anchor="column-types",
),
OnboardingRule(
code="UNINDEXED_FK",
category=RuleCategory.INDEXES,
severity=AuditSeverity.MIGRATION_REQUIRED,
support_status=SupportStatus.MIGRATABLE,
title="Foreign key missing a leftmost-prefix B-tree index",
summary="pgdorm enforces indexed FKs (`auto_index=True`) to avoid parent-delete seq scans.",
action="Assimilation plans online `CREATE INDEX CONCURRENTLY` for uncovered FKs.",
auto_fixable=True,
doc_anchor="constraints-and-indexes",
),
OnboardingRule(
code="UNVALIDATED_CONSTRAINT",
category=RuleCategory.CONSTRAINTS,
severity=AuditSeverity.MIGRATION_REQUIRED,
support_status=SupportStatus.MIGRATABLE,
title="Unvalidated `NOT VALID` constraint",
summary="An existing CHECK, FK, or NOT NULL constraint is marked `NOT VALID` in PG.",
action="Assimilation schedules online `VALIDATE CONSTRAINT` under SHARE UPDATE EXCLUSIVE.",
auto_fixable=True,
doc_anchor="constraints-and-indexes",
),
OnboardingRule(
code="INVALID_INDEX",
category=RuleCategory.INDEXES,
severity=AuditSeverity.MIGRATION_REQUIRED,
support_status=SupportStatus.MIGRATABLE,
title="Invalid leftover index (`indisvalid = false`)",
summary="Likely left behind by an interrupted `CREATE INDEX CONCURRENTLY`.",
action="Assimilation drops the invalid index concurrently before rebuilding.",
auto_fixable=True,
doc_anchor="constraints-and-indexes",
),
OnboardingRule(
code="FK_ON_UPDATE_ACTION",
category=RuleCategory.CONSTRAINTS,
severity=AuditSeverity.INFO,
support_status=SupportStatus.UNMANAGED,
title="Foreign key with non-default `ON UPDATE` action",
summary="pgdorm models `ON DELETE` actions; `ON UPDATE` clauses are not currently modeled.",
action="Matched by signature; review if PK updates rely on `ON UPDATE CASCADE`.",
auto_fixable=False,
doc_anchor="constraints-and-indexes",
),
OnboardingRule(
code="DEFERRABLE_CONSTRAINT",
category=RuleCategory.CONSTRAINTS,
severity=AuditSeverity.INFO,
support_status=SupportStatus.UNMANAGED,
title="Deferrable constraint (`DEFERRABLE`)",
summary="Constraint deferrability attributes are not modeled on `pg.Table`.",
action="Existing constraint is preserved when untouched; recreate manually if altered.",
auto_fixable=False,
doc_anchor="constraints-and-indexes",
),
OnboardingRule(
code="FUNCTION_OR_PROC_PRESENT",
category=RuleCategory.UNMANAGED,
severity=AuditSeverity.UNMANAGED,
support_status=SupportStatus.UNMANAGED,
title="Functions and stored procedures (`pg_proc`)",
summary="Stored routines are intentionally excluded from `pgdorm.migrate` versioning.",
action="Preserved untouched; review any routine referencing renamed tables or columns.",
auto_fixable=False,
doc_anchor="unmanaged-objects",
),
OnboardingRule(
code="TRIGGER_PRESENT",
category=RuleCategory.UNMANAGED,
severity=AuditSeverity.UNMANAGED,
support_status=SupportStatus.UNMANAGED,
title="User triggers (`pg_trigger`)",
summary="Triggers are intentionally left unmanaged by `pgdorm.migrate`.",
action="Preserved untouched; verify trigger function bodies after table/column renames.",
auto_fixable=False,
doc_anchor="unmanaged-objects",
),
OnboardingRule(
code="VIEW_PRESENT",
category=RuleCategory.UNMANAGED,
severity=AuditSeverity.UNMANAGED,
support_status=SupportStatus.UNMANAGED,
title="Views and materialized views",
summary="Views are left unmanaged; column renames or type changes may require recreating.",
action="Use the external-TX bridge (`psycopg3`) to recreate impacted views atomically.",
auto_fixable=False,
doc_anchor="unmanaged-objects",
),
OnboardingRule(
code="UNMANAGED_INDEX_PRESENT",
category=RuleCategory.UNMANAGED,
severity=AuditSeverity.UNMANAGED,
support_status=SupportStatus.UNMANAGED,
title="Non-B-tree (GIN/GiST/BRIN/Hash), expression, or `INCLUDE` index",
summary="Recorded in `TableSnapshot.unmanaged_indexes` and never dropped by diffing.",
action="Preserved automatically; verify expression predicates if columns are renamed.",
auto_fixable=False,
doc_anchor="unmanaged-objects",
),
OnboardingRule(
code="RLS_POLICY_PRESENT",
category=RuleCategory.UNMANAGED,
severity=AuditSeverity.UNMANAGED,
support_status=SupportStatus.UNMANAGED,
title="Existing Row-Level Security policies",
summary="Existing RLS policies are preserved untouched during schema diffing.",
action="Review policy expressions if referenced columns are renamed.",
auto_fixable=False,
doc_anchor="unmanaged-objects",
),
OnboardingRule(
code="EXTENSION_PRESENT",
category=RuleCategory.UNMANAGED,
severity=AuditSeverity.UNMANAGED,
support_status=SupportStatus.UNMANAGED,
title="Installed PostgreSQL extension",
summary="Extension installed inside the app schema; DROP SCHEMA ... CASCADE removes it.",
action="pgdorm creates the extensions its models need (btree_gist) in `public`.",
auto_fixable=False,
doc_anchor="unmanaged-objects",
),
OnboardingRule(
code="LEGACY_MIGRATION_TABLE",
category=RuleCategory.UNMANAGED,
severity=AuditSeverity.UNMANAGED,
support_status=SupportStatus.UNMANAGED,
title="Third-party migration ledger table",
summary="Detected legacy tool ledger (`alembic_version`, `django_migrations`, etc.).",
action="Auto-added to `ignore_tables` so `pgdorm.migrate` leaves it untouched.",
auto_fixable=True,
doc_anchor="unmanaged-objects",
),
OnboardingRule(
code="PG_TABLE_INHERITANCE",
category=RuleCategory.UNSUPPORTED,
severity=AuditSeverity.BLOCKER,
support_status=SupportStatus.UNSUPPORTED,
title="PostgreSQL classical `INHERITS` table inheritance",
summary="Classical `INHERITS` is unsupported; pgdorm uses STI/CTI or partitioning.",
action="Flatten or convert to declarative partitioning / CTI before assimilating.",
auto_fixable=False,
doc_anchor="unsupported-blockers",
),
OnboardingRule(
code="FOREIGN_TABLE_PRESENT",
category=RuleCategory.UNSUPPORTED,
severity=AuditSeverity.BLOCKER,
support_status=SupportStatus.UNSUPPORTED,
title="Foreign table (`FDW` / `relkind = 'f'`)",
summary="Foreign Data Wrapper tables cannot be migrated by `pgdorm.migrate`.",
action="Exclude via `--ignore-table` or access via a separate `read_only=True` model.",
auto_fixable=False,
doc_anchor="unsupported-blockers",
),
OnboardingRule(
code="EXCLUSION_CONSTRAINT",
category=RuleCategory.UNMANAGED,
severity=AuditSeverity.UNMANAGED,
support_status=SupportStatus.UNMANAGED,
title="Exclusion constraint (`EXCLUDE USING ...`)",
summary="Arbitrary `EXCLUDE USING` constraints are preserved untouched during diffing.",
action="Preserved automatically; replace overlaps with `WITHOUT OVERLAPS` if desired.",
auto_fixable=False,
doc_anchor="unmanaged-objects",
),
OnboardingRule(
code="COMPOSITE_COLUMN_TYPE",
category=RuleCategory.UNSUPPORTED,
severity=AuditSeverity.BLOCKER,
support_status=SupportStatus.UNSUPPORTED,
title="User-defined composite column type",
summary="Columns using custom `CREATE TYPE ... AS (...)` row types are not supported.",
action="Normalize into columns or `JSONB` before assimilating.",
auto_fixable=False,
doc_anchor="unsupported-blockers",
),
OnboardingRule(
code="MULTIDIM_ARRAY_TYPE",
category=RuleCategory.UNSUPPORTED,
severity=AuditSeverity.BLOCKER,
support_status=SupportStatus.UNSUPPORTED,
title="Multi-dimensional PostgreSQL array column",
summary="pgdorm binary array codecs support 1-D arrays (`T[]`), not `T[][]`.",
action="Store nested arrays as `JSONB` or normalize into a child table.",
auto_fixable=False,
doc_anchor="unsupported-blockers",
),
OnboardingRule(
code="RESERVED_SCHEMA_PGDORM",
category=RuleCategory.UNSUPPORTED,
severity=AuditSeverity.BLOCKER,
support_status=SupportStatus.UNSUPPORTED,
title="Reserved `_pgdorm` schema",
summary="The `_pgdorm` schema is reserved exclusively for pgdorm's internal ledger.",
action="Move user tables into another schema (e.g. `public` or `app`).",
auto_fixable=False,
doc_anchor="unsupported-blockers",
),
)
Built-in immutable sequence.
OperationDependency#
@dataclass(frozen=True, kw_only=True, slots=True)
class OperationDependency:
kind: str
schema: str
table: str
name: str
state: DependencyState
Typed resource state produced or required by a MigrationOp.
PGDORM_LEDGER_TABLES#
PGDORM_LEDGER_TABLES: tuple[type[Table], ...] = (
MigrationModeType,
MigrationStatusType,
MigrationEventType,
HazardLevelType,
LockModeType,
Migration,
MigrationStep,
MigrationEvent,
)
Built-in immutable sequence.
PGDORM_SCHEMA#
str(object='') -> str
RULE_BY_CODE#
RULE_BY_CODE: frozendict[str, OnboardingRule] = frozendict({r.code: r for r in ONBOARDING_RULES})
frozendict() -> new empty immutable dictionary
apply_op#
Pure in-memory schema replay applying one MigrationOp with strict preconditions (JQ2).
apply_ops#
Apply an ordered sequence of MigrationOps to snapshot in memory.
compile_plan#
def compile_plan(
ops: Sequence[MigrationOp],
*,
schema: str,
version: str = "plan",
name: str = "adhoc",
online: bool = True,
target_snapshot: SchemaSnapshot | None = None,
current_snapshot: SchemaSnapshot | None = None,
) -> MigrationPlan: ...
Compile typed MigrationOps into online lock-safe MigrationSteps + hazards.
detect_drift#
Public detect_drift export from pgdorm.migrate.
detect_potential_renames#
def detect_potential_renames(
current: SchemaSnapshot, desired: SchemaSnapshot
) -> tuple[tuple[str, str, str], ...]: ...
Return (table, old_col, new_col) hints where a dropped & added column share PG type.
diff_snapshots#
def diff_snapshots(
current: SchemaSnapshot,
desired: SchemaSnapshot,
*,
canonical_desired: SchemaSnapshot | None = None,
) -> tuple[MigrationOp, ...]: ...
Compute ordered declarative MigrationOps transforming current into desired.
order_ops_by_dependencies#
def order_ops_by_dependencies(
ops: Sequence[MigrationOp],
*,
schema: str,
current: SchemaSnapshot | None = None,
) -> list[MigrationOp]: ...
Deterministically order migration ops via graphlib.TopologicalSorter (DJ1).
render_python_migration#
def render_python_migration(plan: MigrationPlan, *, var_name: str | None = None) -> str: ...
Render a self-contained, type-check-clean pgm.Migration data value from plan.
Migration Operations (MigrationOp)#
AddCheck#
@dataclass(frozen=True, kw_only=True, slots=True)
class AddCheck(_TableOp):
op_kind: ClassVar[str] = "add_check"
table: str
check: CheckSnapshot
AddCheck(*, table: str, check: pgdorm.migrate._catalog._models.CheckSnapshot)
AddColumn#
@dataclass(frozen=True, kw_only=True, slots=True)
class AddColumn(_TableOp):
op_kind: ClassVar[str] = "add_column"
table: str
column: ColumnSnapshot
AddColumn(*, table: str, column: pgdorm.migrate._catalog._models.ColumnSnapshot)
AddColumnIdentity#
@dataclass(frozen=True, kw_only=True, slots=True)
class AddColumnIdentity(_TableOp):
op_kind: ClassVar[str] = "add_column_identity"
table: str
column: str
AddColumnIdentity(*, table: str, column: str)
AddForeignKey#
@dataclass(frozen=True, kw_only=True, slots=True)
class AddForeignKey(_TableOp):
op_kind: ClassVar[str] = "add_foreign_key"
table: str
fk: FkSnapshot
AddForeignKey(*, table: str, fk: pgdorm.migrate._catalog._models.FkSnapshot)
AddPrimaryKey#
@dataclass(frozen=True, kw_only=True, slots=True)
class AddPrimaryKey(_TableOp):
op_kind: ClassVar[str] = "add_primary_key"
table: str
name: str
columns: tuple[str, ...]
AddPrimaryKey(*, table: str, name: str, columns: tuple[str, ...])
AddTemporalConstraint#
@dataclass(frozen=True, kw_only=True, slots=True)
class AddTemporalConstraint(_TableOp):
op_kind: ClassVar[str] = "add_temporal_constraint"
table: str
temporal: TemporalSnapshot
AddTemporalConstraint(*, table: str, temporal: pgdorm.migrate._catalog._models.TemporalSnapshot)
AddUnique#
@dataclass(frozen=True, kw_only=True, slots=True)
class AddUnique(_TableOp):
op_kind: ClassVar[str] = "add_unique"
table: str
unique: UniqueSnapshot
transactional_only: bool = False
AddUnique(*, table: str, unique: pgdorm.migrate._catalog._models.UniqueSnapshot, transactional_only: bool = False)
AlterColumnExpression#
@dataclass(frozen=True, kw_only=True, slots=True)
class AlterColumnExpression(_TableOp):
op_kind: ClassVar[str] = "alter_column_expression"
table: str
column: str
old_expr: str | None = None
new_expr: str
stored: bool = False
AlterColumnExpression(*, table: str, column: str, old_expr: str | None = None, new_expr: str, stored: bool = False)
AlterColumnType#
@dataclass(frozen=True, kw_only=True, slots=True)
class AlterColumnType(_TableOp):
op_kind: ClassVar[str] = "alter_column_type"
table: str
column: str
old_type: str | None = None
new_type: str
using_sql: str | None = None
AlterColumnType(*, table: str, column: str, old_type: str | None = None, new_type: str, using_sql: str | None = None)
AnalyzeTable#
@dataclass(frozen=True, kw_only=True, slots=True)
class AnalyzeTable(_TableOp):
op_kind: ClassVar[str] = "analyze_table"
table: str
AnalyzeTable(*, table: str)
CreateIndex#
@dataclass(frozen=True, kw_only=True, slots=True)
class CreateIndex(_TableOp):
op_kind: ClassVar[str] = "create_index"
table: str
index: IndexSnapshot
partitioned: bool = False
CreateIndex(*, table: str, index: pgdorm.migrate._catalog._models.IndexSnapshot, partitioned: bool = False)
CreatePolicy#
@dataclass(frozen=True, kw_only=True, slots=True)
class CreatePolicy(_TableOp):
op_kind: ClassVar[str] = "create_policy"
table: str
name: str
using_sql: str
with_check_sql: str | None = None
CreatePolicy(*, table: str, name: str, using_sql: str, with_check_sql: str | None = None)
CreateExtension#
@dataclass(frozen=True, kw_only=True, slots=True)
class CreateExtension(_BaseOp):
op_kind: ClassVar[str] = "create_extension"
name: str
schema: str = EXTENSION_SCHEMA
Installs a database-wide extension the schema needs, with CREATE EXTENSION IF NOT EXISTS ... WITH SCHEMA "public". You rarely write it yourself: snapshot_from_tables() records the extensions your models need (today btree_gist, for WITHOUT OVERLAPS keys that include a scalar column), and diff_snapshots() plans this op ahead of the tables that depend on it. pool.create_all() installs the same extensions. pgdorm never drops an extension, because other schemas in the database may rely on it; check_drift() reports a required extension that has gone missing.
CreateSchema#
@dataclass(frozen=True, kw_only=True, slots=True)
class CreateSchema(_BaseOp):
op_kind: ClassVar[str] = "create_schema"
schema: str
if_not_exists: bool = True
CreateSchema(*, schema: str, if_not_exists: bool = True)
CreateTable#
@dataclass(frozen=True, kw_only=True, slots=True)
class CreateTable(_BaseOp):
op_kind: ClassVar[str] = "create_table"
table: TableSnapshot
defer_fks: tuple[str, ...] = ()
CreateTable(*, table: pgdorm.migrate._catalog._models.TableSnapshot, defer_fks: tuple[str, ...] = ())
DropColumn#
@dataclass(frozen=True, kw_only=True, slots=True)
class DropColumn(_TableOp):
op_kind: ClassVar[str] = "drop_column"
table: str
column: str
DropColumn(*, table: str, column: str)
DropColumnDefault#
@dataclass(frozen=True, kw_only=True, slots=True)
class DropColumnDefault(_TableOp):
op_kind: ClassVar[str] = "drop_column_default"
table: str
column: str
DropColumnDefault(*, table: str, column: str)
DropColumnIdentity#
@dataclass(frozen=True, kw_only=True, slots=True)
class DropColumnIdentity(_TableOp):
op_kind: ClassVar[str] = "drop_column_identity"
table: str
column: str
DropColumnIdentity(*, table: str, column: str)
DropConstraint#
@dataclass(frozen=True, kw_only=True, slots=True)
class DropConstraint(_TableOp):
op_kind: ClassVar[str] = "drop_constraint"
table: str
name: str
constraint_kind: ConstraintKind = ConstraintKind.UNKNOWN
DropConstraint(*, table: str, name: str, constraint_kind: Literal['fk', 'pk', 'unique', 'check', 'temporal', 'unknown'] = 'unknown')
DropIndex#
@dataclass(frozen=True, kw_only=True, slots=True)
class DropIndex(_TableOp):
op_kind: ClassVar[str] = "drop_index"
table: str
name: str
partitioned: bool = False
DropIndex(*, table: str, name: str, partitioned: bool = False)
DropNotNull#
@dataclass(frozen=True, kw_only=True, slots=True)
class DropNotNull(_TableOp):
op_kind: ClassVar[str] = "drop_not_null"
table: str
column: str
DropNotNull(*, table: str, column: str)
DropSchema#
@dataclass(frozen=True, kw_only=True, slots=True)
class DropSchema(_BaseOp):
op_kind: ClassVar[str] = "drop_schema"
schema: str
if_exists: bool = True
cascade: bool = False
DropSchema(*, schema: str, if_exists: bool = True, cascade: bool = False)
DropTable#
@dataclass(frozen=True, kw_only=True, slots=True)
class DropTable(_TableOp):
op_kind: ClassVar[str] = "drop_table"
table: str
cascade: bool = False
DropTable(*, table: str, cascade: bool = False)
EnableRls#
@dataclass(frozen=True, kw_only=True, slots=True)
class EnableRls(_TableOp):
op_kind: ClassVar[str] = "enable_rls"
table: str
force: bool = True
EnableRls(*, table: str, force: bool = True)
GrantSchema#
@dataclass(frozen=True, kw_only=True, slots=True)
class GrantSchema(_BaseOp):
op_kind: ClassVar[str] = "grant_schema"
schema: str
role: str
scope: GrantScope = GrantScope.SCHEMA_USAGE
GrantSchema(*, schema: str, role: str, scope: GrantScopeName = 'schema_usage')
GrantScope#
class GrantScope(StrEnum):
SCHEMA_USAGE = "schema_usage"
ALL_TABLES = "all_tables"
ALL_SEQUENCES = "all_sequences"
Schema grant scope accepted by grant_schema(...) (pgm.enums.GrantScope).
Migration#
@dataclass(frozen=True, kw_only=True, slots=True)
class Migration:
version: str
name: str
ops: tuple[MigrationOp, ...]
Pure immutable migration value (no subclassing ceremony required).
MigrationApp#
@dataclass(frozen=True, kw_only=True, slots=True)
class MigrationApp:
tables: tuple[type[Table], ...]
migrations: tuple[Migration, ...] = ()
schema: str = "public"
ignore_tables: frozenset[str] = frozenset()
online: bool = True
lock_timeout: str = "2s"
statement_timeout: str = "30s"
lock_retries: int = 3
lock_retry_delay: float = 0.2
Typed application manifest pointed to by [tool.pgdorm] app = "module:attr".
MigrationOp#
type MigrationOp = (
CreateExtension
| CreateSchema
| DropSchema
| CreateTable
| DropTable
| RenameTable
| AddColumn
| DropColumn
| RenameColumn
| AlterColumnType
| AlterColumnExpression
| AddColumnIdentity
| DropColumnIdentity
| AddTemporalConstraint
| SetColumnDefault
| DropColumnDefault
| SetNotNull
| DropNotNull
| AddForeignKey
| AddCheck
| AddUnique
| AddPrimaryKey
| RestartIdentity
| DropConstraint
| ValidateConstraint
| CreateIndex
| DropIndex
| SyncTypeTable
| AnalyzeTable
| EnableRls
| CreatePolicy
| GrantSchema
| RunPython
)
Type alias.
MigrationPlan#
@dataclass(frozen=True, kw_only=True, slots=True)
class MigrationPlan:
version: str
name: str
ops: tuple[MigrationOp, ...]
steps: tuple[MigrationStep, ...]
hazards: tuple[MigrationHazard, ...]
checksum: str
target_snapshot: SchemaSnapshot | None = None
MigrationPlan(*, version: str, name: str, ops: tuple[pgdorm.migrate._plan._ops.MigrationOp, ...], steps: tuple[pgdorm.migrate._catalog._models.MigrationStep, ...], hazards: tuple[pgdorm.migrate._catalog._models.MigrationHazard, ...], checksum: str, target_snapshot: pgdorm.migrate._catalog._models.SchemaSnapshot | None = None)
RenameColumn#
@dataclass(frozen=True, kw_only=True, slots=True)
class RenameColumn(_TableOp):
op_kind: ClassVar[str] = "rename_column"
table: str
old_name: str
new_name: str
RenameColumn(*, table: str, old_name: str, new_name: str)
RenameTable#
@dataclass(frozen=True, kw_only=True, slots=True)
class RenameTable(_BaseOp):
op_kind: ClassVar[str] = "rename_table"
old_name: str
new_name: str
RenameTable(*, old_name: str, new_name: str)
RestartIdentity#
@dataclass(frozen=True, kw_only=True, slots=True)
class RestartIdentity(_TableOp):
op_kind: ClassVar[str] = "restart_identity"
table: str
column: str
start_with: int
RestartIdentity(*, table: str, column: str, start_with: int)
RunPython#
@dataclass(frozen=True, kw_only=True, slots=True)
class RunPython(_BaseOp):
op_kind: ClassVar[str] = "run_python"
name: str
fn: Callable[[Transaction], Awaitable[None]]
target_table: str | None = None
RunPython(*, name: str, fn: collections.abc.Callable[[pgdorm.runtime._executors.Transaction], collections.abc.Awaitable[None]], target_table: str | None = None)
SetColumnDefault#
@dataclass(frozen=True, kw_only=True, slots=True)
class SetColumnDefault(_TableOp):
op_kind: ClassVar[str] = "set_column_default"
table: str
column: str
default_sql: str
SetColumnDefault(*, table: str, column: str, default_sql: str)
SetNotNull#
@dataclass(frozen=True, kw_only=True, slots=True)
class SetNotNull(_TableOp):
op_kind: ClassVar[str] = "set_not_null"
table: str
column: str
constraint_name: str | None = None
SetNotNull(*, table: str, column: str, constraint_name: str | None = None)
SyncTypeTable#
@dataclass(frozen=True, kw_only=True, slots=True)
class SyncTypeTable(_TableOp):
op_kind: ClassVar[str] = "sync_type_table"
table: str
pk_column: str
pk_pg_type: str
seeds: tuple[tuple[str, str], ...]
SyncTypeTable(*, table: str, pk_column: str, pk_pg_type: str, seeds: tuple[tuple[str, str], ...])
ValidateConstraint#
@dataclass(frozen=True, kw_only=True, slots=True)
class ValidateConstraint(_TableOp):
op_kind: ClassVar[str] = "validate_constraint"
table: str
name: str
ValidateConstraint(*, table: str, name: str)
add_check#
def add_check(
table: type[Table] | str, predicate: Expr[bool], *, name: str | None = None
) -> AddCheck: ...
Public add_check export from pgdorm.migrate.
add_column#
Build an AddColumn op directly from a typed Table.col descriptor.
add_primary_key#
def add_primary_key(
table: type[Table] | str, *columns: ColBase | str, name: str | None = None
) -> AddPrimaryKey: ...
Public add_primary_key export from pgdorm.migrate.
add_unique#
def add_unique(
table: type[Table] | str, *columns: ColBase | str, name: str | None = None
) -> AddUnique: ...
Public add_unique export from pgdorm.migrate.
analyze_table#
Public analyze_table export from pgdorm.migrate.
create_index#
def create_index(
table: type[Table] | str,
*columns: ColBase | str,
name: str | None = None,
unique: bool = False,
where: Expr[bool] | None = None,
) -> CreateIndex: ...
Public create_index export from pgdorm.migrate.
create_policy#
def create_policy(
table: type[Table] | str,
*,
name: str,
using: Expr[bool],
with_check: Expr[bool] | None = None,
) -> CreatePolicy: ...
Public create_policy export from pgdorm.migrate.
create_schema#
Public create_schema export from pgdorm.migrate.
drop_column#
Public drop_column export from pgdorm.migrate.
drop_not_null#
Public drop_not_null export from pgdorm.migrate.
drop_schema#
def drop_schema(schema: str, *, if_exists: bool = True, cascade: bool = False) -> DropSchema: ...
Public drop_schema export from pgdorm.migrate.
enable_rls#
Public enable_rls export from pgdorm.migrate.
grant_schema#
def grant_schema(
schema: str, *, role: str, scope: GrantScope = GrantScope.SCHEMA_USAGE
) -> GrantSchema: ...
Public grant_schema export from pgdorm.migrate.
rename_column#
def rename_column(
table: type[Table] | str, *, old: ColBase | str, new: ColBase | str
) -> RenameColumn: ...
Public rename_column export from pgdorm.migrate.
rename_table#
Public rename_table export from pgdorm.migrate.
restart_identity#
def restart_identity(
table: type[Table] | str, column: ColBase | str, *, start_with: int
) -> RestartIdentity: ...
Public restart_identity export from pgdorm.migrate.
set_not_null#
Public set_not_null export from pgdorm.migrate.
sync_type_table#
Public sync_type_table export from pgdorm.migrate.
Schema Onboarding & Assimilation#
AdoptionImpactWarning#
@dataclass(frozen=True, kw_only=True, slots=True)
class AdoptionImpactWarning:
object_kind: str
object_name: str
table: str | None
referenced_old: str
detail: str
definition: str | None = None
Warning when a planned rename/PK change impacts an unmanaged or dependent DB object.
AdoptionMap#
@dataclass(frozen=True, kw_only=True, slots=True)
class AdoptionMap:
tables: Mapping[str, TableMapping] = frozendict()
ignore_tables: frozenset[str] = frozenset()
drop_tables: frozenset[str] = frozenset()
enum_types: Mapping[str, tuple[str, ...]] = frozendict()
Bijective source->target mapping guaranteeing exact table/column targeting.
AdoptionPlan#
@dataclass(frozen=True, kw_only=True, slots=True)
class AdoptionPlan:
plan: MigrationPlan
adoption: AdoptionMap
impact_warnings: tuple[AdoptionImpactWarning, ...] = ()
ignored_tables: frozenset[str] = frozenset()
preserved_unmanaged_count: int = 0
Complete verified assimilation plan with compiled PostgreSQL steps and impact warnings.
AuditSeverity#
Enum where members are also (and must be) ints
CatalogExtras#
@dataclass(frozen=True, kw_only=True, slots=True)
class CatalogExtras:
views: tuple[ViewInfo, ...] = ()
routines: tuple[RoutineInfo, ...] = ()
triggers: tuple[TriggerInfo, ...] = ()
pg_enums: Mapping[str, tuple[str, ...]] = frozendict()
pg_domains: frozenset[str] = frozenset()
pg_composites: frozenset[str] = frozenset()
inherited_tables: tuple[tuple[str, str], ...] = ()
foreign_tables: tuple[str, ...] = ()
exclusion_constraints: tuple[ExclusionConstraintInfo, ...] = ()
rls_policies: tuple[tuple[str, str], ...] = ()
extensions: tuple[str, ...] = ()
fk_metas: tuple[FkMetaInfo, ...] = ()
serial_owned_columns: frozenset[tuple[str, str]] = frozenset()
multidim_array_columns: frozenset[tuple[str, str]] = frozenset()
Read-only inventory of PG objects outside SchemaSnapshot tables.
ExclusionConstraintInfo#
@dataclass(frozen=True, kw_only=True, slots=True)
class ExclusionConstraintInfo:
table: str
name: str
definition: str
ExclusionConstraintInfo(*, table: str, name: str, definition: str)
ExternalPlanPhases#
@dataclass(frozen=True, kw_only=True, slots=True)
class ExternalPlanPhases:
transactional_steps: tuple[MigrationStep, ...]
post_commit_steps: tuple[MigrationStep, ...]
Split a MigrationPlan into atomic transactional steps and post-commit online steps.
ExternalSqlExecutor#
Type alias.
FkMetaInfo#
@dataclass(frozen=True, kw_only=True, slots=True)
class FkMetaInfo:
table: str
name: str
on_update: str | None = None
deferrable: bool = False
FkMetaInfo(*, table: str, name: str, on_update: str | None = None, deferrable: bool = False)
OnboardingFinding#
@dataclass(frozen=True, kw_only=True, slots=True)
class OnboardingFinding:
code: str
severity: AuditSeverity
category: RuleCategory
object_kind: str
object_name: str
table: str | None
message: str
suggestion: str
auto_fixable: bool
doc_anchor: str
OnboardingFinding(*, code: str, severity: pgdorm.migrate._assimilate._rules.AuditSeverity, category: RuleCategory, object_kind: str, object_name: str, table: str | None, message: str, suggestion: str, auto_fixable: bool, doc_anchor: str)
OnboardingReport#
@dataclass(frozen=True, kw_only=True, slots=True)
class OnboardingReport:
schema: str
snapshot: SchemaSnapshot
extras: CatalogExtras
findings: tuple[OnboardingFinding, ...]
type_table_candidates: tuple[TypeTableCandidate, ...]
workflow_steps: tuple[OnboardingWorkflowStep, ...]
ignored_tables: frozenset[str] = frozenset()
Structured readiness checklist and agentic gap report for an existing PG schema.
OnboardingRule#
@dataclass(frozen=True, kw_only=True, slots=True)
class OnboardingRule:
code: str
category: RuleCategory
severity: AuditSeverity
support_status: SupportStatus
title: str
summary: str
action: str
auto_fixable: bool
doc_anchor: str
Single-source-of-truth compatibility rule shared by audit_schema() and docsgen.
OnboardingWorkflowStep#
@dataclass(frozen=True, kw_only=True, slots=True)
class OnboardingWorkflowStep:
phase: OnboardingPhase
order: int
summary: str
detail: str
OnboardingWorkflowStep(*, phase: Literal['pre_ddl', 'ddl', 'post_ddl', 'post_commit'], order: int, summary: str, detail: str)
PkStrategy#
Primary-key assimilation strategy (pgm.enums.PkStrategy).
RoutineInfo#
@dataclass(frozen=True, kw_only=True, slots=True)
class RoutineInfo:
name: str
kind: RoutineKind
source: str = ""
definition: str | None = None
Stored function, procedure, aggregate, or window routine discovered during schema auditing.
RuleCategory#
class RuleCategory(StrEnum):
NAMING = "naming"
PRIMARY_KEY = "primary_key"
TYPE_TABLE = "type_table"
TYPES = "types"
CONSTRAINTS = "constraints"
INDEXES = "indexes"
UNMANAGED = "unmanaged"
UNSUPPORTED = "unsupported"
Onboarding audit rule category (pgm.enums.RuleCategory).
ScaffoldMode#
Model scaffolding mode (pgm.enums.ScaffoldMode).
ScaffoldResult#
@dataclass(frozen=True, kw_only=True, slots=True)
class ScaffoldResult:
code: str
adoption_map: AdoptionMap
table_names: tuple[str, ...]
warnings: tuple[str, ...] = ()
Generated compliant pgdorm models and paired AdoptionMap.
SupportStatus#
class SupportStatus(StrEnum):
SUPPORTED = "supported"
MIGRATABLE = "migratable"
UNMANAGED = "unmanaged"
UNSUPPORTED = "unsupported"
Onboarding rule support classification (pgm.enums.SupportStatus).
SurrogatePkType#
Surrogate primary-key column type (pgm.enums.SurrogatePkType).
TableMapping#
@dataclass(frozen=True, kw_only=True, slots=True)
class TableMapping:
target: str
columns: Mapping[str, str] = frozendict()
as_type_table: bool = False
pk_strategy: PkStrategy = PkStrategy.RENAME
migrate_serial_to_identity: bool = False
migrate_uuid_to_uuidv7: bool = False
surrogate_pk: SurrogatePkType = SurrogatePkType.BIGINT
Explicit assimilation rule mapping one existing table to its pgdorm target shape.
TriggerInfo#
@dataclass(frozen=True, kw_only=True, slots=True)
class TriggerInfo:
name: str
table: str
function_name: str
definition: str | None = None
TriggerInfo(*, name: str, table: str, function_name: str, definition: str | None = None)
TypeTableCandidate#
@dataclass(frozen=True, kw_only=True, slots=True)
class TypeTableCandidate:
table: str
pk_column: str
pk_pg_type: str
code_column: str
code_pg_type: str
referencing_tables: tuple[str, ...]
confidence: Confidence
reason: str
TypeTableCandidate(*, table: str, pk_column: str, pk_pg_type: str, code_column: str, code_pg_type: str, referencing_tables: tuple[str, ...], confidence: Literal['high', 'medium'], reason: str)
ViewInfo#
@dataclass(frozen=True, kw_only=True, slots=True)
class ViewInfo:
name: str
materialized: bool = False
depends_on_tables: tuple[str, ...] = ()
definition: str | None = None
ViewInfo(*, name: str, materialized: bool = False, depends_on_tables: tuple[str, ...] = (), definition: str | None = None)
analyze_onboarding#
def analyze_onboarding(
snapshot: SchemaSnapshot,
extras: CatalogExtras | None = None,
*,
ignore_tables: frozenset[str] = frozenset(),
) -> OnboardingReport: ...
Pure analyzer producing a deterministic readiness checklist & agentic gap report.
assimilate_column_name#
Compute a compliant snake_case Python identifier for a column.
assimilate_table_name#
Compute a compliant singular snake_case target table name for full assimilation.
audit_schema#
async def audit_schema(
conn: Pool | Transaction,
*,
schema: str | None = None,
ignore_tables: frozenset[str] = frozenset(),
include_definitions: bool = True,
) -> OnboardingReport: ...
Inspect a live PostgreSQL schema and return a full assimilation readiness report.
build_adoption_ops#
def build_adoption_ops(
live: SchemaSnapshot,
desired: SchemaSnapshot,
adoption: AdoptionMap,
*,
canonical_desired: SchemaSnapshot | None = None,
allow_unmapped_drops: bool = False,
) -> tuple[MigrationOp, ...]: ...
Validate adoption, emit cycle-safe renames + PK assimilation, and diff remaining gaps.
detect_rename_impacts#
def detect_rename_impacts(
adoption: AdoptionMap,
live: SchemaSnapshot,
extras: CatalogExtras,
) -> tuple[AdoptionImpactWarning, ...]: ...
Identify views, triggers, routines, CHECKs, and FKs affected by planned renames.
execute_plan_tx#
async def execute_plan_tx(plan: MigrationPlan, execute_sql: ExternalSqlExecutor) -> int: ...
Feed compiled transactional DDL steps into a caller's external TX (e.g. psycopg3).
finalize_external#
async def finalize_external(
pool: Pool,
plan: MigrationPlan,
*,
tables: Sequence[type[Table]],
schema: str | None = None,
ignore_tables: frozenset[str] = frozenset(),
lease_seconds: int = 300,
) -> MigrationRecord: ...
Run post-commit online steps (CONCURRENTLY/VALIDATE) and record ledger state.
introspect_catalog_extras#
async def introspect_catalog_extras(
conn: Pool | Transaction, schema: str, *, include_definitions: bool = True
) -> CatalogExtras: ...
Read-only pipelined inspection of views, routines, triggers, enums, and blockers.
plan_adoption#
async def plan_adoption(
pool: Pool,
tables: Sequence[type[Table]],
*,
adoption: AdoptionMap,
schema: str | None = None,
version: str | None = None,
name: str = "adopt",
online: bool = True,
allow_unmapped_drops: bool = False,
) -> AdoptionPlan: ...
Introspect live catalog, validate adoption, and compile an assimilation plan.
render_phased_sql#
Render a reviewable 4-phase SQL blueprint for DBAs and AI agents.
scaffold_from_db#
async def scaffold_from_db(
pool: Pool,
*,
schema: str | None = None,
adoption: AdoptionMap | None = None,
type_tables: frozenset[str] = frozenset(),
ignore_tables: frozenset[str] = frozenset(),
mode: ScaffoldMode = ScaffoldMode.ASSIMILATE,
assimilate_enums: bool = False,
modernize: bool = False,
surrogate_pk: SurrogatePkType = SurrogatePkType.BIGINT,
emit_app: bool = True,
) -> ScaffoldResult: ...
Introspect live PostgreSQL and scaffold pgdorm models (assimilate or bind).
scaffold_models#
def scaffold_models(
snapshot: SchemaSnapshot,
*,
adoption: AdoptionMap | None = None,
type_table_rows: Mapping[str, Sequence[tuple[str, str]]] = {},
enum_types: Mapping[str, Sequence[str]] = frozendict(),
mode: ScaffoldMode = ScaffoldMode.ASSIMILATE,
emit_app: bool = True,
) -> ScaffoldResult: ...
Generate pg.Table / pg.TypeTable code from a schema snapshot.
singularize_ident#
Deterministically singularize the trailing token of a snake_case identifier.
snake_to_pascal#
Convert a snake_case table identifier to a PascalCase Python class name.
split_plan_phases#
Partition plan.steps into atomic TX DDL and autocommit/online post-commit steps.
suggest_adoption_map#
def suggest_adoption_map(
snapshot: SchemaSnapshot,
*,
candidates: Sequence[TypeTableCandidate] = (),
type_tables: frozenset[str] = frozenset(),
ignore_tables: frozenset[str] = frozenset(),
enum_types: Mapping[str, Sequence[str]] = frozendict(),
modernize: bool = False,
surrogate_pk: SurrogatePkType = SurrogatePkType.BIGINT,
mode: ScaffoldMode = ScaffoldMode.ASSIMILATE,
) -> AdoptionMap: ...
Propose an AdoptionMap (assimilate normalizes names/PKs; bind keeps live schema).
sync_identity_from_max#
async def sync_identity_from_max(
conn: Pool | Transaction,
table: type[Table],
column: str,
*,
schema: str | None = None,
) -> int: ...
Compute MAX(column) + 1 via typed ORM and emit ALTER COLUMN ... RESTART WITH.
validate_adoption_map#
def validate_adoption_map(
live: SchemaSnapshot,
desired: SchemaSnapshot,
adoption: AdoptionMap,
*,
allow_unmapped_drops: bool = False,
) -> None: ...
Strictly verify bijection, live existence, and zero-implicit-drop invariants.
Catalog Introspection Models#
CheckSnapshot#
@dataclass(frozen=True, kw_only=True, slots=True)
class CheckSnapshot:
name: str
expr_sql: str
validated: bool = True
CheckSnapshot(*, name: str, expr_sql: str, validated: bool = True)
ColumnSnapshot#
@dataclass(frozen=True, kw_only=True, slots=True)
class ColumnSnapshot:
name: str
pg_type: str
nullable: bool = False
not_null_constraint: str | None = None
not_null_validated: bool = True
primary_key: bool = False
identity: bool = False
default_sql: str | None = None
generated_expr: str | None = None
generated_stored: bool = False
server_managed: bool = False
ColumnSnapshot(*, name: str, pg_type: str, nullable: bool = False, not_null_constraint: str | None = None, not_null_validated: bool = True, primary_key: bool = False, identity: bool = False, default_sql: str | None = None, generated_expr: str | None = None, generated_stored: bool = False)
DriftItem#
@dataclass(frozen=True, kw_only=True, slots=True)
class DriftItem:
kind: str
table: str
detail: str
DriftItem(*, kind: str, table: str, detail: str)
DriftReport#
@dataclass(frozen=True, kw_only=True, slots=True)
class DriftReport:
schema: str
items: tuple[DriftItem, ...]
invalid_indexes: tuple[tuple[str, str], ...] = ()
unvalidated_constraints: tuple[tuple[str, str], ...] = ()
DriftReport(*, schema: str, items: tuple[pgdorm.migrate._catalog._models.DriftItem, ...], invalid_indexes: tuple[tuple[str, str], ...] = (), unvalidated_constraints: tuple[tuple[str, str], ...] = ())
FkSnapshot#
@dataclass(frozen=True, kw_only=True, slots=True)
class FkSnapshot:
name: str
columns: tuple[str, ...]
ref_schema: str | None = None
ref_table: str
ref_columns: tuple[str, ...]
on_delete: str | None = None
validated: bool = True
deferrable: bool = False
initially_deferred: bool = False
FkSnapshot(*, name: str, columns: tuple[str, ...], ref_schema: str | None = None, ref_table: str, ref_columns: tuple[str, ...], on_delete: str | None = None, validated: bool = True, deferrable: bool = False, initially_deferred: bool = False)
HazardLevel#
Enum where members are also (and must be) ints
IndexSnapshot#
@dataclass(frozen=True, kw_only=True, slots=True)
class IndexSnapshot:
name: str
columns: tuple[str, ...]
column_orders: tuple[str, ...] = ()
unique: bool = False
where_sql: str | None = None
valid: bool = True
IndexSnapshot(*, name: str, columns: tuple[str, ...], column_orders: tuple[str, ...] = (), unique: bool = False, where_sql: str | None = None, valid: bool = True)
LockMode#
class LockMode(IntEnum):
NONE = 1
SHARE_UPDATE_EXCLUSIVE = 2
SHARE = 3
SHARE_ROW_EXCLUSIVE = 4
ACCESS_EXCLUSIVE = 5
Enum where members are also (and must be) ints
MigrationEventTypeEnum#
class MigrationEventTypeEnum(IntEnum):
START = 1
STEP_OK = 2
STEP_FAIL = 3
COMPLETE = 4
ROLLBACK = 5
BASELINE = 6
DRIFT = 7
Enum where members are also (and must be) ints
MigrationHazard#
@dataclass(frozen=True, kw_only=True, slots=True)
class MigrationHazard:
level: HazardLevel
code: str
table: str | None = None
message: str
suggestion: str | None = None
MigrationHazard(*, level: pgdorm.migrate._catalog._models.HazardLevel, code: str, table: str | None = None, message: str, suggestion: str | None = None)
MigrationModeEnum#
Enum where members are also (and must be) ints
MigrationStatusEnum#
Enum where members are also (and must be) ints
MigrationStep#
@dataclass(frozen=True, kw_only=True, slots=True)
class MigrationStep:
action: StepAction
description: str
op_kind: str
target_table: str | None = None
transactional: bool = True
separate_tx: bool = False
lock_mode: LockMode = LockMode.NONE
hazard_level: HazardLevel = HazardLevel.SAFE
retry_on_lock_timeout: bool = False
MigrationStep(*, action: StepAction, description: str, op_kind: str, target_table: str | None = None, transactional: bool = True, separate_tx: bool = False, lock_mode: pgdorm.migrate._catalog._models.LockMode =
PartitionSnapshot#
@dataclass(frozen=True, kw_only=True, slots=True)
class PartitionSnapshot:
strategy: str
columns: tuple[str, ...]
PartitionSnapshot(*, strategy: str, columns: tuple[str, ...])
PgAttrdef#
class PgAttrdef(Table, schema="pg_catalog", read_only=True):
oid: Col[int] = pk()
adrelid: Col[int] = fk(PgClass.oid)
adnum: Col[Int2] = col()
adbin: Col[str] = col()
Read-only ORM model for pg_catalog.pg_attrdef.
PgAttribute#
class PgAttribute(Table, schema="pg_catalog", read_only=True):
attrelid: Col[int] = fk(PgClass.oid)
attname: Col[str] = col()
atttypid: Col[int] = col()
atttypmod: Col[Int4] = col()
attnum: Col[Int2] = col()
attndims: Col[Int2] = col()
attnotnull: Col[bool] = col()
attisdropped: Col[bool] = col()
attidentity: Col[str] = col()
attgenerated: Col[str] = col()
Read-only ORM model for pg_catalog.pg_attribute.
PgClass#
class PgClass(Table, schema="pg_catalog", read_only=True):
oid: Col[int] = pk()
relname: Col[str] = col()
relnamespace: Col[int] = fk(PgNamespace.oid)
relkind: Col[str] = col()
relispartition: Col[bool] = col()
relam: Col[int] = fk(PgAm.oid)
relrowsecurity: Col[bool] = col()
Read-only ORM model for pg_catalog.pg_class.
PgConstraint#
class PgConstraint(Table, schema="pg_catalog", read_only=True):
oid: Col[int] = pk()
conname: Col[str] = col()
conrelid: Col[int] = fk(PgClass.oid)
confrelid: Col[int] = col()
conparentid: Col[int] = col()
contype: Col[str] = col()
convalidated: Col[bool] = col()
conindid: Col[int] = col()
conkey: Col[list[Int2] | None] = col(default=None)
confkey: Col[list[Int2] | None] = col(default=None)
confdeltype: Col[str] = col()
confupdtype: Col[str] = col()
condeferrable: Col[bool] = col()
condeferred: Col[bool] = col()
confdelsetcols: Col[list[Int2] | None] = col(default=None)
Read-only ORM model for pg_catalog.pg_constraint.
PgExtension#
class PgExtension(Table, schema="pg_catalog", read_only=True):
oid: Col[int] = pk()
extname: Col[str] = col()
extnamespace: Col[int] = fk(PgNamespace.oid)
Read-only ORM model for pg_catalog.pg_extension.
PgIndex#
class PgIndex(Table, schema="pg_catalog", read_only=True):
indexrelid: Col[int] = fk(PgClass.oid)
indrelid: Col[int] = fk(PgClass.oid)
indnatts: Col[Int2] = col()
indnkeyatts: Col[Int2] = col()
indisunique: Col[bool] = col()
indisprimary: Col[bool] = col()
indisvalid: Col[bool] = col()
indkey: Col[list[Int2]] = col()
indoption: Col[list[Int2]] = col()
indpred: Col[str | None] = col(default=None)
Read-only ORM model for pg_catalog.pg_index.
PgIndexes#
class PgIndexes(Table, schema="pg_catalog", read_only=True):
schemaname: Col[str] = col()
tablename: Col[str] = col()
indexname: Col[str] = col()
indexdef: Col[str] = col()
Read-only ORM model for pg_catalog.pg_indexes.
PgNamespace#
class PgNamespace(Table, schema="pg_catalog", read_only=True):
oid: Col[int] = pk()
nspname: Col[str] = col()
Read-only ORM model for pg_catalog.pg_namespace.
PgTables#
class PgTables(Table, schema="pg_catalog", read_only=True):
schemaname: Col[str] = col()
tablename: Col[str] = col()
tableowner: Col[str] = col()
Read-only ORM model for pg_catalog.pg_tables.
PgType#
class PgType(Table, schema="pg_catalog", read_only=True):
oid: Col[int] = pk()
typname: Col[str] = col()
typnamespace: Col[int] = fk(PgNamespace.oid)
typtype: Col[str] = col()
typbasetype: Col[int] = col()
Read-only ORM model for pg_catalog.pg_type.
SchemaSnapshot#
@dataclass(frozen=True, kw_only=True, slots=True)
class SchemaSnapshot:
schema: str
tables: Mapping[str, TableSnapshot]
view_dependencies: tuple[ViewDependencySnapshot, ...] = ()
extensions: tuple[str, ...] = ()
SchemaSnapshot(*, schema: str, tables: collections.abc.Mapping[str, pgdorm.migrate._catalog._models.TableSnapshot], view_dependencies: tuple[pgdorm.migrate._catalog._view_deps.ViewDependencySnapshot, ...] = ())
TableSnapshot#
@dataclass(frozen=True, kw_only=True, slots=True)
class TableSnapshot:
name: str
schema: str | None = None
columns: tuple[ColumnSnapshot, ...]
primary_key_columns: tuple[str, ...] = ()
primary_key_name: str | None = None
foreign_keys: tuple[FkSnapshot, ...] = ()
unique_constraints: tuple[UniqueSnapshot, ...] = ()
checks: tuple[CheckSnapshot, ...] = ()
temporal_constraints: tuple[TemporalSnapshot, ...] = ()
indexes: tuple[IndexSnapshot, ...] = ()
unmanaged_indexes: tuple[UnmanagedIndexSnapshot, ...] = ()
preserved_constraints: tuple[str, ...] = ()
partition_by: PartitionSnapshot | None = None
type_seeds: tuple[tuple[str, str], ...] = ()
TableSnapshot(*, name: str, schema: str | None = None, columns: tuple[pgdorm.migrate._catalog._models.ColumnSnapshot, ...], primary_key_columns: tuple[str, ...] = (), primary_key_name: str | None = None, foreign_keys: tuple[pgdorm.migrate._catalog._models.FkSnapshot, ...] = (), unique_constraints: tuple[pgdorm.migrate._catalog._models.UniqueSnapshot, ...] = (), checks: tuple[pgdorm.migrate._catalog._models.CheckSnapshot, ...] = (), temporal_constraints: tuple[pgdorm.migrate._catalog._models.TemporalSnapshot, ...] = (), indexes: tuple[pgdorm.migrate._catalog._models.IndexSnapshot, ...] = (), unmanaged_indexes: tuple[pgdorm.migrate._catalog._models.UnmanagedIndexSnapshot, ...] = (), preserved_constraints: tuple[str, ...] = (), partition_by: pgdorm.migrate._catalog._models.PartitionSnapshot | None = None, type_seeds: tuple[tuple[str, str], ...] = ())
TemporalSnapshot#
@dataclass(frozen=True, kw_only=True, slots=True)
class TemporalSnapshot:
name: str
columns: tuple[str, ...]
range_column: str
is_primary_key: bool
TemporalSnapshot(*, name: str, columns: tuple[str, ...], range_column: str, is_primary_key: bool)
UniqueSnapshot#
@dataclass(frozen=True, kw_only=True, slots=True)
class UniqueSnapshot:
name: str
columns: tuple[str, ...]
UniqueSnapshot(*, name: str, columns: tuple[str, ...])
UnmanagedIndexSnapshot#
@dataclass(frozen=True, kw_only=True, slots=True)
class UnmanagedIndexSnapshot:
name: str
access_method: str
indexdef: str
reason: str
Index preserved untouched by pgdorm.migrate (non-B-tree, expression, or INCLUDE).
canonicalize_snapshot_with_pg#
async def canonicalize_snapshot_with_pg(pool: Pool, desired: SchemaSnapshot) -> SchemaSnapshot: ...
Canonicalize CHECK/DEFAULT/generated expressions via PostgreSQL inside a rolled-back temp tx.
introspect_schema#
async def introspect_schema(
conn: Pool | Transaction,
schema: str,
*,
ignore_tables: frozenset[str] = frozenset(),
type_tables: Sequence[type[Table]] = (),
) -> SchemaSnapshot: ...
Introspect live pg_catalog via 100% pure pipelined pgdorm ORM queries.
snapshot_from_tables#
Convert pg.Table classes into a canonical SchemaSnapshot matching live introspection.
Migration Ledger & Constants#
HazardLevelType#
class HazardLevelType(TypeTable, schema=PGDORM_SCHEMA, enum=HazardLevel):
hazard_level_type_id: Col[HazardLevel] = pk()
Lookup table base class backed by a Python Enum (enforces unique code column).
LockModeType#
class LockModeType(TypeTable, schema=PGDORM_SCHEMA, enum=LockMode):
lock_mode_type_id: Col[LockMode] = pk()
Lookup table base class backed by a Python Enum (enforces unique code column).
MigrationEventRecord#
Immutable append-only migration audit event in _pgdorm.migration_event.
MigrationEventType#
class MigrationEventType(TypeTable, schema=PGDORM_SCHEMA, enum=MigrationEventTypeEnum):
migration_event_type_id: Col[MigrationEventTypeEnum] = pk()
Lookup table base class backed by a Python Enum (enforces unique code column).
MigrationMode#
Lookup table base class backed by a Python Enum (enforces unique code column).
MigrationRecord#
Persisted migration execution record in _pgdorm.migration.
MigrationStatus#
Lookup table base class backed by a Python Enum (enforces unique code column).
MigrationStepRecord#
Persisted per-step DDL/Python execution row in _pgdorm.migration_step.
Migration Exceptions#
AdoptionTargetError#
Base exception for all Python-side pgdorm errors.
ChecksumMismatchError#
Base exception for all Python-side pgdorm errors.
DriftError#
Base exception for all Python-side pgdorm errors.
HistoryDivergenceError#
Base exception for all Python-side pgdorm errors.
MigrationError#
Base exception for all Python-side pgdorm errors.
MigrationLockError#
Base exception for all Python-side pgdorm errors.
UnsafeMigrationError#
Base exception for all Python-side pgdorm errors.
Migration Enums (pgdorm.migrate.enums)#
Strict StrEnum option namespaces exposed as pgm.enums.* and re-exported as types from pgdorm.typing.
enums#
Submodule namespace holding all migration StrEnum option types (pgm.enums.*).
AdoptOutputFormat#
CLI output format for adopt-plan (TEXT, JSON, SQL).
Confidence#
Heuristic confidence level for detected TypeTable candidates (HIGH, MEDIUM).
ConstraintKind#
class ConstraintKind(StrEnum):
FK = "fk"
PK = "pk"
UNIQUE = "unique"
CHECK = "check"
TEMPORAL = "temporal"
UNKNOWN = "unknown"
Constraint classification accepted by DropConstraint (FK, PK, UNIQUE, CHECK, TEMPORAL, UNKNOWN).
DependencyState#
Dependency graph edge target state (PRESENT, ABSENT).
OnboardingPhase#
class OnboardingPhase(StrEnum):
PRE_DDL = "pre_ddl"
DDL = "ddl"
POST_DDL = "post_ddl"
POST_COMMIT = "post_commit"
Assimilation workflow phase (PRE_DDL, DDL, POST_DDL, POST_COMMIT).
RoutineKind#
class RoutineKind(StrEnum):
FUNCTION = "function"
PROCEDURE = "procedure"
AGGREGATE = "aggregate"
WINDOW = "window"
PostgreSQL routine kind from pg_proc.prokind (FUNCTION, PROCEDURE, AGGREGATE, WINDOW).
Legacy Brownfield Expression Escape Hatches#
Emitted by scaffold_models() only when an existing database CHECK, partial index WHERE, or GENERATED ALWAYS AS (...) expression cannot be represented as a typed pg.Expr.
legacy_check#
Wraps a pre-existing brownfield PostgreSQL CHECK expression inside @classmethod def __constraints__(cls).
legacy_where#
Wraps a pre-existing brownfield PostgreSQL partial-index WHERE predicate for pg.Index(..., where=pgm.legacy_where(...)).
legacy_generated#
Wraps a pre-existing brownfield PostgreSQL GENERATED ALWAYS AS (...) expression inside @classmethod def __generated__(cls).