Skip to content

Chapter 1 — Opening the Blueprints#

Act I · Chapter 1 Year 2 · Spring · 08:30 8 min readDifficulty 2 of 5

Query pg_catalog with typed models, baseline an existing schema, sync declaratively, and catch out-of-band drift.

baseline_schema()plan_migration()sync_schema()check_drift()PgClass / _pgdorm
▶ Run it yourself · examples/151_mig_blueprints_and_sync.py
Year 2 · Spring, 08:30. Maya spreads the Lisbon blueprints across the desk. The hostel launched with `create_all()`, and now Management wants a `quiet_hours` flag and a `maintenance_note` log.

Year 2 · Spring, 08:30. Maya spreads the Lisbon blueprints across the desk. The hostel launched with create_all(), and now Management wants a quiet_hours flag and a maintenance_note log.

Panda: Easy! Let's copy-paste a YAML schema file into Confluence and diff it by hand before running psql!

Ferris: A YAML file lies the moment someone touches production. PostgreSQL already owns the truth in pg_catalog — let's query it with typed ORM models and baseline _pgdorm first.

Maya: Wait — pgdorm even models pg_catalog and its own _pgdorm ledger as real pg.Table classes?

The mission#

Before changing a single column in Year 2, Maya needs a trustworthy baseline and a repeatable diff loop. Using pgdorm.migrate (pgm), she will:

  1. query PostgreSQL's live pg_catalog through typed read-only ORM models (pgm.PgClass, pgm.PgNamespace) with zero raw SQL,
  2. adopt an existing create_all() schema cleanly via pgm.baseline_schema() and prove zero catalog diff (pgm.introspect_schema() + pgm.snapshot_from_tables() + pgm.canonicalize_snapshot_with_pg()),
  3. evolve V1 → V2 declaratively with pgm.plan_migration() and pgm.sync_schema(), verifying idempotency and inspecting the self-hosted _pgdorm ledger (migration_history, migration_steps, migration_events),
  4. catch an out-of-band table change with pgm.check_drift() and pgm.DriftError, then isolate it with ignore_tables or reconcile it explicitly with allow_drift=True.

The Panda's plan

Maintain a hand-edited schema spreadsheet alongside production, run ad-hoc ALTER TABLE scripts in psql, and find out six months later that staging and Lisbon drifted apart.

1. The V1 and V2 blueprints#

Each renovation chapter defines explicit V1 and V2 model namespaces in the same script so you can see the exact schema transition side by side:

examples/151_mig_blueprints_and_sync.py · V1
class V1:
    class Wing(pg.Table):
        wing_id: pg.Col[int] = pg.pk(default=pg.identity())
        code: pg.Col[str] = pg.col(unique=True)
        name: pg.Col[str] = pg.col()
examples/151_mig_blueprints_and_sync.py · V2
class V2:
    class Wing(pg.Table):
        wing_id: pg.Col[int] = pg.pk(default=pg.identity())
        code: pg.Col[str] = pg.col(unique=True)
        name: pg.Col[str] = pg.col()
        quiet_hours: pg.Col[bool] = pg.col(default=True)
examples/151_mig_blueprints_and_sync.py · MaintenanceNote
class MaintenanceNote(pg.Table):
    maintenance_note_id: pg.Col[int] = pg.pk(default=pg.identity())
    wing_id: pg.Col[int] = pg.fk(V2.Wing.wing_id, on_delete=pg.enums.OnDelete.CASCADE)
    summary: pg.Col[str] = pg.col()

2. Reading pg_catalog and baselining an existing schema#

Apps often start with pool.create_all() during prototyping and later graduate to tracked migrations. pgm.baseline_schema() adopts those existing tables into _pgdorm.migration without re-executing CREATE TABLE, recording the canonical live catalog snapshot as revision 0000_baseline:

examples/151_mig_blueprints_and_sync.py · adopt_and_inspect_catalog
async def adopt_and_inspect_catalog(pool: pg.Pool) -> None:
    # Existing app created V1 tables with pool.create_all() before turning on migrations.
    await pool.create_all(V1.Wing)
    await pool.execute(pg.insert(V1.Wing).values(V1.Wing(code="TAGUS", name="Tagus Wing")))

    # Read PostgreSQL's own pg_catalog with typed ORM models on a ReadPool (zero raw SQL!).
    (schema_name,) = await pool.one(pg.select_expr(pg.func("current_schema")))
    assert isinstance(schema_name, str)
    ro = pool.read_only()
    rel_rows = await ro.all(
        pg.select(pgm.PgClass)
        .join(pgm.PgNamespace)
        .where((pgm.PgNamespace.nspname == schema_name) & (pgm.PgClass.relkind == "r"))
        .order_by(pgm.PgClass.relname.asc())
    )
    print(f"catalog tables: {[r.relname for r in rel_rows]}")
    # => catalog tables: ['wing']

    # Adopt the existing schema into _pgdorm without re-running DDL.
    base = await pgm.baseline_schema(pool, (V1.Wing,), version="0000_baseline", name="adopt_v1")
    live = await pgm.introspect_schema(pool, schema_name)
    desired = pgm.snapshot_from_tables(V1.Wing, schema=schema_name)
    canon = await pgm.canonicalize_snapshot_with_pg(pool, desired)
    diff_ops = pgm.diff_snapshots(live, canon)
    print(f"baseline={base.version} mode={base.migration_mode_id.name} diff_ops={len(diff_ops)}")
    # => baseline=0000_baseline mode=BASELINE diff_ops=0

What just happened

  • pool.read_only() queried pg_catalog.pg_class joined to pg_catalog.pg_namespace using typed pgdorm models — zero raw SQL strings, hydrated straight into slotted PgClass instances.
  • pgm.baseline_schema() bootstrapped the self-hosted _pgdorm ledger (migration, migration_step, migration_event, plus five TypeTable lookups) and recorded 0000_baseline with mode=BASELINE.
  • pgm.canonicalize_snapshot_with_pg() normalized default/check expressions through PostgreSQL's own parser so pgm.diff_snapshots(live, canon) returned 0 spurious diffs.

3. Declarative sync (Mode A) and the _pgdorm ledger#

With a clean baseline in place, Mode A (plan_migration → sync_schema) diffs your Python models directly against live pg_catalog, executes online DDL, and persists every step and lifecycle event in _pgdorm:

examples/151_mig_blueprints_and_sync.py · declarative_sync_and_ledger
async def declarative_sync_and_ledger(pool: pg.Pool) -> None:
    v2_tables = (V2.Wing, MaintenanceNote)

    # Dry-run plan before touching PostgreSQL.
    plan = await pgm.plan_migration(pool, v2_tables, version="0001_add_notes", name="add_notes")
    print(f"planned ops={[op.op_kind for op in plan.ops]} hazards={len(plan.hazards)}")
    # => planned ops=['create_table', 'add_column'] hazards=0

    rec = await pgm.sync_schema(pool, v2_tables, version="0001_add_notes", name="add_notes")
    assert rec is not None
    # Golden rule: immediate re-plan is empty and sync_schema returns None.
    replan = await pgm.plan_migration(pool, v2_tables)
    noop = await pgm.sync_schema(pool, v2_tables)
    is_idem = replan.is_empty and noop is None
    print(f"synced={rec.version} parent={rec.parent_version} idempotent={is_idem}")
    # => synced=0001_add_notes parent=0000_baseline idempotent=True

    # Inspect the self-hosted _pgdorm ledger via helper functions!
    history = await pgm.migration_history(pool)
    steps = await pgm.migration_steps(pool, migration_id=rec.migration_id)
    events = await pgm.migration_events(pool, migration_id=rec.migration_id)
    print(f"ledger history: {[h.version for h in history]}")
    # => ledger history: ['0000_baseline', '0001_add_notes']
    print(f"ledger steps: {[s.op_kind for s in steps]} ({len(events)} events)")
    # => ledger steps: ['create_table', 'create_table', 'add_column'] (5 events)
Ferris' basement: the golden rule of schema diffing

Immediately after sync_schema() finishes, plan_migration() MUST return is_empty=True and sync_schema() MUST return None. If a planner ever emits a diff against the schema it just applied, you can't trust it in CI or production.

4. Three-way drift detection (DriftError, ignore_tables, allow_drift)#

pgm.check_drift() compares three sources of truth: the last recorded _pgdorm.migration snapshot, live pg_catalog, and your Python tables. If someone runs out-of-band DDL behind the ledger's back, sync_schema() halts with pgm.DriftError until you either exclude that table via ignore_tables or reconcile explicitly with allow_drift=True:

examples/151_mig_blueprints_and_sync.py · detect_and_resolve_drift
async def detect_and_resolve_drift(pool: pg.Pool) -> None:
    v2_tables = (V2.Wing, MaintenanceNote)

    # Someone creates an out-of-band table directly in the schema behind the ledger's back!
    await pool.create_all(ScratchTempLog)

    report = await pgm.check_drift(pool, tables=v2_tables)
    items = [(d.kind, d.table) for d in report.items]
    print(f"drift: in_sync={report.in_sync} items={items}")
    # => drift: in_sync=False items=[('create_table', 'scratch_temp_log')]

    # sync_schema refuses to overwrite a drifted schema unless you ignore it or pass allow_drift.
    try:
        await pgm.sync_schema(pool, v2_tables, version="0002_blocked")
    except pgm.DriftError as exc:
        print(f"blocked by DriftError: {len(exc.report.items)} item(s)")
        # => blocked by DriftError: 1 item(s)

    # Option 1: isolate unmanaged/external tables with ignore_tables.
    ignored_report = await pgm.check_drift(
        pool, tables=v2_tables, ignore_tables=frozenset({"scratch_temp_log"})
    )
    print(f"with ignore_tables: in_sync={ignored_report.in_sync}")
    # => with ignore_tables: in_sync=True

    # Option 2: reconcile explicitly with allow_drift=True + allow_destructive=True.
    cleaned = await pgm.sync_schema(
        pool,
        v2_tables,
        version="0002_reconcile",
        name="drop_scratch",
        allow_drift=True,
        allow_destructive=True,
    )
    assert cleaned is not None
    final = await pgm.check_drift(pool, tables=v2_tables)
    print(f"reconciled={cleaned.version} in_sync={final.in_sync}")
    # => reconciled=0002_reconcile in_sync=True

What PostgreSQL actually received#

🔭 What PostgreSQL received: 267 statements in 127 round trips (captured live on PostgreSQL)
-- ⚙ schema setup (create_all): 3 statements omitted · full transcript in examples/__wire__/mig_blueprints_and_sync.sql

-- ── round trip 1 ──
INSERT INTO "wing" ("code", "name")
VALUES ($1, $2);
-- → 1 affected

-- ── round trip 2 ──
SELECT current_schema();
-- → 1 row

-- ── round trip 3 · 3 statements pipelined ──
BEGIN READ ONLY;
SELECT
  "pg_class"."oid",
  "pg_class"."relname",
  "pg_class"."relnamespace",
  "pg_class"."relkind",
  "pg_class"."relispartition",
  "pg_class"."relam",
  "pg_class"."relrowsecurity"
FROM "pg_catalog"."pg_class"
INNER JOIN "pg_catalog"."pg_namespace" ON "pg_class"."relnamespace" = "pg_namespace"."oid"
WHERE "pg_namespace"."nspname" = $1 AND "pg_class"."relkind" = $2
ORDER BY "pg_class"."relname" ASC;
-- → 1 row
COMMIT;

-- ── round trip 4 ──
SELECT "pg_class"."relname"
FROM "pg_catalog"."pg_class"
INNER JOIN "pg_catalog"."pg_namespace" ON "pg_class"."relnamespace" = "pg_namespace"."oid"
WHERE "pg_namespace"."nspname" = $1 AND "pg_class"."relname" = $2;
-- → 1 row

-- ── round trip 5 ──
SELECT
  "migration_id",
  "target_schema",
  "version",
  "parent_version",
  "name",
  "migration_mode_id",
  "migration_status_id",
  "checksum",
  "ops_json",
  "schema_snapshot",
  "locked_by",
  "lease_expires_at",
  "started_at",
  "finished_at",
  "duration_ms",
  "error_detail"
FROM "_pgdorm"."migration"
WHERE "target_schema" = $1 AND "migration_status_id" = $2
ORDER BY "migration_id" ASC;

-- ── round trip 6 ──
SELECT
  "pg_class"."oid",
  "pg_class"."relname",
  "pg_class"."relnamespace",
  "pg_class"."relkind",
  "pg_class"."relispartition",
  "pg_class"."relam",
  "pg_class"."relrowsecurity"
FROM "pg_catalog"."pg_class"
INNER JOIN "pg_catalog"."pg_namespace" ON "pg_class"."relnamespace" = "pg_namespace"."oid"
WHERE "pg_namespace"."nspname" = $1 AND "pg_class"."relkind" = ANY($2) AND "pg_class"."relispartition" = $3
ORDER BY "pg_class"."relname" ASC;
-- → 1 row

-- ── round trip 7 · 7 statements pipelined ──
SELECT
  "attrelid",
  "attnum",
  "attname",
  pg_catalog.format_type("atttypid", "atttypmod"),
  "attnotnull",
  "attidentity",
  "attgenerated"
FROM "pg_catalog"."pg_attribute"
WHERE "attrelid" = ANY($1) AND "attnum" > $2 AND "attisdropped" = $3
ORDER BY "attrelid" ASC, "attnum" ASC;
-- → 3 rows
SELECT "adrelid", "adnum", pg_catalog.pg_get_expr("adbin", "adrelid")
FROM "pg_catalog"."pg_attrdef"
WHERE "adrelid" = ANY($1);
SELECT
  "conrelid",
  "conname",
  "contype",
  "convalidated",
  "conkey",
  "confrelid",
  "confkey",
  "confdeltype",
  "confdelsetcols",
  "conindid",
  pg_catalog.pg_get_constraintdef("oid"),
  "condeferrable",
  "condeferred"
FROM "pg_catalog"."pg_constraint"
WHERE "conrelid" = ANY($1) AND "conparentid" = $2 AND "contype" = ANY($3)
ORDER BY "conname" ASC;
-- → 5 rows
SELECT
  "pg_index"."indrelid",
  "pg_index"."indexrelid",
  "idx_cls"."relname",
  "pg_index"."indkey",
  "pg_index"."indnatts",
  "pg_index"."indnkeyatts",
  "pg_index"."indisunique",
  "pg_index"."indisprimary",
  "pg_index"."indisvalid",
  pg_catalog.pg_get_expr("pg_index"."indpred", "pg_index"."indrelid"),
  "pg_am"."amname",
  pg_catalog.pg_get_indexdef("pg_index"."indexrelid"),
  "pg_index"."indoption"
FROM "pg_catalog"."pg_index"
INNER JOIN "pg_catalog"."pg_class" AS "idx_cls" ON "pg_index"."indexrelid" = "idx_cls"."oid"
INNER JOIN "pg_catalog"."pg_am" ON "idx_cls"."relam" = "pg_am"."oid"
WHERE "pg_index"."indrelid" = ANY($1) AND "pg_index"."indisprimary" = $2
ORDER BY "idx_cls"."relname" ASC;
-- → 1 row
SELECT "partrelid", "partstrat", "partattrs"
FROM "pg_catalog"."pg_partitioned_table"
WHERE "partrelid" = ANY($1);
SELECT
  "view_nsp"."nspname",
  "view_cls"."relname",
  "view_cls"."relkind",
  "pg_depend"."refobjid",
  "pg_depend"."refobjsubid"
FROM "pg_catalog"."pg_depend"
INNER JOIN "pg_catalog"."pg_rewrite" ON "pg_depend"."objid" = "pg_rewrite"."oid"
INNER JOIN "pg_catalog"."pg_class" AS "view_cls" ON "pg_rewrite"."ev_class" = "view_cls"."oid"
INNER JOIN "pg_catalog"."pg_namespace" AS "view_nsp" ON "view_cls"."relnamespace" = "view_nsp"."oid"
WHERE "pg_depend"."refobjid" = ANY($1) AND "pg_depend"."deptype" = $2 AND "view_cls"."relkind" = ANY($3) AND NOT ("view_nsp"."nspname" = ANY($4));
SELECT "oid", "extname", "extnamespace"
FROM "pg_catalog"."pg_extension"
ORDER BY "extname" ASC;
-- → 3 rows

-- ── round trip 8 · 2 statements pipelined ──
BEGIN;
SELECT pg_advisory_xact_lock(hashtext($1));
-- → 1 row

-- ── round trip 9 ──
SELECT "oid", "nspname"
FROM "pg_catalog"."pg_namespace"
WHERE "nspname" = $1;
-- → 1 row

-- ── round trip 10 ──
SELECT
  "pg_class"."oid",
  "pg_class"."relname",
  "pg_class"."relnamespace",
  "pg_class"."relkind",
  "pg_class"."relispartition",
  "pg_class"."relam",
  "pg_class"."relrowsecurity"
FROM "pg_catalog"."pg_class"
INNER JOIN "pg_catalog"."pg_namespace" ON "pg_class"."relnamespace" = "pg_namespace"."oid"
WHERE "pg_namespace"."nspname" = $1 AND "pg_class"."relkind" = ANY($2) AND "pg_class"."relispartition" = $3
ORDER BY "pg_class"."relname" ASC;
-- → 8 rows

-- ── round trip 11 · 12 statements pipelined ──
SELECT
  "attrelid",
  "attnum",
  "attname",
  pg_catalog.format_type("atttypid", "atttypmod"),
  "attnotnull",
  "attidentity",
  "attgenerated"
FROM "pg_catalog"."pg_attribute"
WHERE "attrelid" = ANY($1) AND "attnum" > $2 AND "attisdropped" = $3
ORDER BY "attrelid" ASC, "attnum" ASC;
-- → 46 rows
SELECT "adrelid", "adnum", pg_catalog.pg_get_expr("adbin", "adrelid")
FROM "pg_catalog"."pg_attrdef"
WHERE "adrelid" = ANY($1);
-- → 3 rows
SELECT
  "conrelid",
  "conname",
  "contype",
  "convalidated",
  "conkey",
  "confrelid",
  "confkey",
  "confdeltype",
  "confdelsetcols",
  "conindid",
  pg_catalog.pg_get_constraintdef("oid"),
  "condeferrable",
  "condeferred"
FROM "pg_catalog"."pg_constraint"
WHERE "conrelid" = ANY($1) AND "conparentid" = $2 AND "contype" = ANY($3)
ORDER BY "conname" ASC;
-- → 54 rows
SELECT
  "pg_index"."indrelid",
  "pg_index"."indexrelid",
  "idx_cls"."relname",
  "pg_index"."indkey",
  "pg_index"."indnatts",
  "pg_index"."indnkeyatts",
  "pg_index"."indisunique",
  "pg_index"."indisprimary",
  "pg_index"."indisvalid",
  pg_catalog.pg_get_expr("pg_index"."indpred", "pg_index"."indrelid"),
  "pg_am"."amname",
  pg_catalog.pg_get_indexdef("pg_index"."indexrelid"),
  "pg_index"."indoption"
FROM "pg_catalog"."pg_index"
INNER JOIN "pg_catalog"."pg_class" AS "idx_cls" ON "pg_index"."indexrelid" = "idx_cls"."oid"
INNER JOIN "pg_catalog"."pg_am" ON "idx_cls"."relam" = "pg_am"."oid"
WHERE "pg_index"."indrelid" = ANY($1) AND "pg_index"."indisprimary" = $2
ORDER BY "idx_cls"."relname" ASC;
-- → 17 rows
SELECT "partrelid", "partstrat", "partattrs"
FROM "pg_catalog"."pg_partitioned_table"
WHERE "partrelid" = ANY($1);
SELECT
  "view_nsp"."nspname",
  "view_cls"."relname",
  "view_cls"."relkind",
  "pg_depend"."refobjid",
  "pg_depend"."refobjsubid"
FROM "pg_catalog"."pg_depend"
INNER JOIN "pg_catalog"."pg_rewrite" ON "pg_depend"."objid" = "pg_rewrite"."oid"
INNER JOIN "pg_catalog"."pg_class" AS "view_cls" ON "pg_rewrite"."ev_class" = "view_cls"."oid"
INNER JOIN "pg_catalog"."pg_namespace" AS "view_nsp" ON "view_cls"."relnamespace" = "view_nsp"."oid"
WHERE "pg_depend"."refobjid" = ANY($1) AND "pg_depend"."deptype" = $2 AND "view_cls"."relkind" = ANY($3) AND NOT ("view_nsp"."nspname" = ANY($4));
SELECT "oid", "extname", "extnamespace"
FROM "pg_catalog"."pg_extension"
ORDER BY "extname" ASC;
-- → 3 rows
SELECT "migration_mode_type_id", "code"
FROM "_pgdorm"."migration_mode_type"
ORDER BY "migration_mode_type_id" ASC;
-- → 3 rows
SELECT "migration_status_type_id", "code"
FROM "_pgdorm"."migration_status_type"
ORDER BY "migration_status_type_id" ASC;
-- → 4 rows
SELECT "migration_event_type_id", "code"
FROM "_pgdorm"."migration_event_type"
ORDER BY "migration_event_type_id" ASC;
-- → 7 rows
SELECT "hazard_level_type_id", "code"
FROM "_pgdorm"."hazard_level_type"
ORDER BY "hazard_level_type_id" ASC;
-- → 4 rows
SELECT "lock_mode_type_id", "code"
FROM "_pgdorm"."lock_mode_type"
ORDER BY "lock_mode_type_id" ASC;
-- → 5 rows

-- ── round trip 12 ──
COMMIT;

-- ── round trip 13 ──
INSERT INTO "_pgdorm"."migration" ("target_schema", "version", "parent_version", "name", "migration_mode_id", "migration_status_id", "checksum", "ops_json", "schema_snapshot", "locked_by", "lease_expires_at", "finished_at", "duration_ms", "error_detail")
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
RETURNING "migration_id", "target_schema", "version", "parent_version", "name", "migration_mode_id", "migration_status_id", "checksum", "ops_json", "schema_snapshot", "locked_by", "lease_expires_at", "started_at", "finished_at", "duration_ms", "error_detail";
-- → 1 row

-- ── round trip 14 ──
INSERT INTO "_pgdorm"."migration_event" ("migration_id", "migration_event_type_id", "step_index", "duration_ms", "detail")
VALUES ($1, $2, $3, $4, $5);
-- → 1 affected

-- ── round trip 15 ──
SELECT
  "pg_class"."oid",
  "pg_class"."relname",
  "pg_class"."relnamespace",
  "pg_class"."relkind",
  "pg_class"."relispartition",
  "pg_class"."relam",
  "pg_class"."relrowsecurity"
FROM "pg_catalog"."pg_class"
INNER JOIN "pg_catalog"."pg_namespace" ON "pg_class"."relnamespace" = "pg_namespace"."oid"
WHERE "pg_namespace"."nspname" = $1 AND "pg_class"."relkind" = ANY($2) AND "pg_class"."relispartition" = $3
ORDER BY "pg_class"."relname" ASC;
-- → 1 row

-- ── round trip 16 · 7 statements pipelined ──
SELECT
  "attrelid",
  "attnum",
  "attname",
  pg_catalog.format_type("atttypid", "atttypmod"),
  "attnotnull",
  "attidentity",
  "attgenerated"
FROM "pg_catalog"."pg_attribute"
WHERE "attrelid" = ANY($1) AND "attnum" > $2 AND "attisdropped" = $3
ORDER BY "attrelid" ASC, "attnum" ASC;
-- → 3 rows
SELECT "adrelid", "adnum", pg_catalog.pg_get_expr("adbin", "adrelid")
FROM "pg_catalog"."pg_attrdef"
WHERE "adrelid" = ANY($1);
SELECT
  "conrelid",
  "conname",
  "contype",
  "convalidated",
  "conkey",
  "confrelid",
  "confkey",
  "confdeltype",
  "confdelsetcols",
  "conindid",
  pg_catalog.pg_get_constraintdef("oid"),
  "condeferrable",
  "condeferred"
FROM "pg_catalog"."pg_constraint"
WHERE "conrelid" = ANY($1) AND "conparentid" = $2 AND "contype" = ANY($3)
ORDER BY "conname" ASC;
-- → 5 rows
SELECT
  "pg_index"."indrelid",
  "pg_index"."indexrelid",
  "idx_cls"."relname",
  "pg_index"."indkey",
  "pg_index"."indnatts",
  "pg_index"."indnkeyatts",
  "pg_index"."indisunique",
  "pg_index"."indisprimary",
  "pg_index"."indisvalid",
  pg_catalog.pg_get_expr("pg_index"."indpred", "pg_index"."indrelid"),
  "pg_am"."amname",
  pg_catalog.pg_get_indexdef("pg_index"."indexrelid"),
  "pg_index"."indoption"
FROM "pg_catalog"."pg_index"
INNER JOIN "pg_catalog"."pg_class" AS "idx_cls" ON "pg_index"."indexrelid" = "idx_cls"."oid"
INNER JOIN "pg_catalog"."pg_am" ON "idx_cls"."relam" = "pg_am"."oid"
WHERE "pg_index"."indrelid" = ANY($1) AND "pg_index"."indisprimary" = $2
ORDER BY "idx_cls"."relname" ASC;
-- → 1 row
SELECT "partrelid", "partstrat", "partattrs"
FROM "pg_catalog"."pg_partitioned_table"
WHERE "partrelid" = ANY($1);
SELECT
  "view_nsp"."nspname",
  "view_cls"."relname",
  "view_cls"."relkind",
  "pg_depend"."refobjid",
  "pg_depend"."refobjsubid"
FROM "pg_catalog"."pg_depend"
INNER JOIN "pg_catalog"."pg_rewrite" ON "pg_depend"."objid" = "pg_rewrite"."oid"
INNER JOIN "pg_catalog"."pg_class" AS "view_cls" ON "pg_rewrite"."ev_class" = "view_cls"."oid"
INNER JOIN "pg_catalog"."pg_namespace" AS "view_nsp" ON "view_cls"."relnamespace" = "view_nsp"."oid"
WHERE "pg_depend"."refobjid" = ANY($1) AND "pg_depend"."deptype" = $2 AND "view_cls"."relkind" = ANY($3) AND NOT ("view_nsp"."nspname" = ANY($4));
SELECT "oid", "extname", "extnamespace"
FROM "pg_catalog"."pg_extension"
ORDER BY "extname" ASC;
-- → 3 rows

-- … 225 more statements in examples/__wire__/mig_blueprints_and_sync.sql

Shift report

  • Queried pg_catalog via typed read-only PgClass / PgNamespace models
  • Adopted a create_all() schema cleanly with pgm.baseline_schema()
  • Planned, synced, and proved zero-op idempotency with plan_migration() and sync_schema()
  • Audited _pgdorm ledger rows via migration_history(), migration_steps(), and migration_events()
  • Caught out-of-band DDL with check_drift() / DriftError and resolved via ignore_tables and allow_drift=True

Try it yourself

Add a floor_count: pg.Col[int] = pg.col(default=3) column to V2.Wing and re-run the script — watch plan_migration() detect the new column and sync_schema() apply it idempotently in a single metadata-only ALTER TABLE.

Go deeper: tests/integration/migrations/test_sync_lifecycle.py (live PostgreSQL test suites & snapshots)

Sticky note from Management

"Great blueprints, Maya! Now add a unique RFID index, a NOT NULL constraint, and widen weight_kg during peak afternoon check-in — WITHOUT freezing the lobby!"