Skip to content

Chapter 6 — Wings, Policies & Living Lookups#

Act III · Chapter 6 Year 2 · Autumn · 10:00 6 min readDifficulty 4 of 5

Evolve TypeTables lock-free, manage RLS policies and deferrable FK graphs, and introspect partitioned tables.

SyncTypeTableDEFERRABLE FKsenable_rls() / create_policy()PartitionBy.range()order_ops_by_dependencies()
▶ Run it yourself · examples/170_mig_advanced_pg_evolution.py
Year 2 · Autumn, 10:00. The estate expands across Lisbon and Porto: new suite tiers, multi-tenant Row-Level Security policies, deferrable foreign-key graphs, and partitioned door-scan tables.

Year 2 · Autumn, 10:00. The estate expands across Lisbon and Porto: new suite tiers, multi-tenant Row-Level Security policies, deferrable foreign-key graphs, and partitioned door-scan tables.

Polar Bear: We need to rename STANDARD to CLASSIC and add PENTHOUSE to our room tiers without taking an ACCESS EXCLUSIVE lock on a native PostgreSQL ENUM!

Rocco: And every wing_badge row needs Row-Level Security enabled in a tracked migration — not pasted manually in psql.

Ferris: SyncTypeTable runs at LockMode.NONE, DEFERRABLE INITIALLY DEFERRED FKs round-trip cleanly through pg_constraint, and enable_rls + create_policy are first-class MigrationOps!

The mission#

Real PostgreSQL schemas go far beyond plain columns and single-table indexes. In this renovation, Maya exercises pgdorm.migrate's advanced PostgreSQL-native primitives:

  1. Lock-free TypeTable evolution (SyncTypeTable): rename STANDARD → CLASSIC and add PENTHOUSE on an IntEnum TypeTable (alongside a UUID-PK HubRegionType) at LockMode.NONE — zero DDL table locks,
  2. Self-referential & DEFERRABLE INITIALLY DEFERRED foreign keys: order dependencies cleanly (order_ops_by_dependencies) and prove child-before-parent inserts inside a single transaction,
  3. Security in migrations (EnableRls, CreatePolicy, GrantSchema, CreateSchema): enable forced Row-Level Security and tenant policies as checksummed, versioned Migration ops,
  4. Partitioned tables: sync and introspect PartitionBy.range(...) parent tables idempotently.

The Panda's plan

Use PostgreSQL CREATE TYPE suite_tier AS ENUM (...), discover you can never remove an enum value without rewriting the table, and configure Row-Level Security by hand in production so staging and Lisbon silently disagree.

1. Living lookups (TypeTable), deferrable FKs, and partitioned tables#

examples/170_mig_advanced_pg_evolution.py · V1
class V1:
    class SuiteTierType(pg.TypeTable, enum=SuiteTierV1):
        suite_tier_type_id: pg.Col[SuiteTierV1] = pg.pk()
examples/170_mig_advanced_pg_evolution.py · V2
class V2:
    class SuiteTierType(pg.TypeTable, enum=SuiteTierV2):
        suite_tier_type_id: pg.Col[SuiteTierV2] = pg.pk()
examples/170_mig_advanced_pg_evolution.py · EstateWing
class EstateWing(pg.Table):
    estate_wing_id: pg.Col[int] = pg.pk(default=pg.identity())
    parent_wing_id: pg.Col[int | None] = pg.col(default=None)
    hub_region_type_id: pg.Col[HubRegion] = pg.fk(HubRegionType.hub_region_type_id)
    code: pg.Col[str] = pg.col(unique=True)

    @classmethod
    def __constraints__(cls) -> tuple[pg.TableConstraint, ...]:
        return (
            pg.ForeignKey(
                local_refs=(cls.parent_wing_id,),
                ref_cols=(cls.estate_wing_id,),
                on_delete=pg.enums.OnDelete.SET_NULL,
            ),
        )
examples/170_mig_advanced_pg_evolution.py · WingBadge
class WingBadge(pg.Table):
    wing_badge_id: pg.Col[int] = pg.pk(default=pg.identity())
    estate_wing_id: pg.Col[int] = pg.fk(
        EstateWing.estate_wing_id,
        on_delete=pg.enums.OnDelete.CASCADE,
        deferrable=True,
        initially_deferred=True,
    )
    tenant_code: pg.Col[str] = pg.col()
    label: pg.Col[str] = pg.col()
examples/170_mig_advanced_pg_evolution.py · DoorScan
class DoorScan(pg.Table):
    door_scan_id: pg.Col[int] = pg.pk(default=pg.identity())
    scanned_at: pg.Col[datetime] = pg.pk()
    badge_code: pg.Col[str] = pg.col()

    @classmethod
    def __constraints__(cls) -> tuple[pg.TableConstraint, ...]:
        return (pg.PartitionBy.range(cls.scanned_at),)

2. Evolving TypeTable lookups at LockMode.NONE#

Because pg.TypeTable stores enum codes as real indexed rows (with foreign keys pointing to integer or UUID PKs), renaming a code or adding a new tier compiles to pure idempotent INSERT ... ON CONFLICT DO UPDATE DML — LockMode.NONE, never touching a table lock:

examples/170_mig_advanced_pg_evolution.py · evolve_type_tables_lock_free
async def evolve_type_tables_lock_free(pool: pg.Pool) -> None:
    # Initial sync seeds BOTH INT4 and UUID TypeTables + self-FK, deferrable FK & partitioned table.
    v1_tables = (V1.SuiteTierType, HubRegionType, EstateWing, WingBadge, DoorScan)
    await pgm.sync_schema(pool, v1_tables, version="0001_estate_v1", name="estate_v1")

    # Evolve SuiteTierType V1 -> V2: rename STANDARD->CLASSIC & add PENTHOUSE with LockMode.NONE!
    v2_tables = (V2.SuiteTierType, HubRegionType, EstateWing, WingBadge, DoorScan)
    plan = await pgm.plan_migration(pool, v2_tables, version="0002_tiers_v2", name="tiers_v2")
    locks = [(s.op_kind, s.lock_mode.name) for s in plan.steps]
    print(f"type_table evolution locks: {locks}")
    # => type_table evolution locks: [('sync_type_table', 'NONE')]

    await pgm.sync_schema(pool, v2_tables, version="0002_tiers_v2", name="tiers_v2")
    tiers = await pool.all(
        pg.select(V2.SuiteTierType).order_by(V2.SuiteTierType.suite_tier_type_id.asc())
    )
    print(f"synced tiers: {[(t.suite_tier_type_id.value, t.code) for t in tiers]}")
    # => synced tiers: [(1, 'classic'), (2, 'deluxe'), (3, 'penthouse')]

3. DEFERRABLE foreign keys, RLS policies, and partitioned catalog parity#

pgdorm.migrate captures condeferrable, condeferred, relrowsecurity, and pg_partitioned_table directly from PostgreSQL's catalog so deferrable FKs, RLS enablement, and range partitions stay 100% in sync:

examples/170_mig_advanced_pg_evolution.py · deferrable_fk_and_rls_migrations
async def deferrable_fk_and_rls_migrations(pool: pg.Pool) -> None:
    # DEFERRABLE INITIALLY DEFERRED lets child insert precede parent within one transaction!
    async with pool.transaction() as tx:
        await tx.insert(
            WingBadge(wing_badge_id=10, estate_wing_id=100, tenant_code="lisbon", label="Badge-A")
        )
        await tx.insert(
            EstateWing(
                estate_wing_id=100,
                hub_region_type_id=HubRegion.LISBON,
                code="NORTH",
            )
        )
    count = await pool.one(pg.select(WingBadge).columns(pg.count()))
    print(f"deferrable FK committed badges: {count[0]}")
    # => deferrable FK committed badges: 1

    # Apply EnableRls + CreatePolicy + CreateSchema/DropSchema inside a versioned Migration!
    m_rls = pgm.Migration(
        version="0003_rls_policies",
        name="enable_badge_rls",
        ops=(
            pgm.enable_rls(WingBadge, force=True),
            pgm.create_policy(
                WingBadge,
                name="wing_badge_tenant_iso",
                using=WingBadge.tenant_code
                == pg.func("current_setting", "app.tenant", True, returns=str),
            ),
        ),
    )
    applied = await pgm.upgrade_schema(pool, (m_rls,))
    (schema_name,) = await pool.one(pg.select_expr(pg.func("current_schema")))
    assert isinstance(schema_name, str)
    badge_rel = await pool.read_only().one(
        pg.select(pgm.PgClass)
        .join(pgm.PgNamespace)
        .where((pgm.PgNamespace.nspname == schema_name) & (pgm.PgClass.relname == "wing_badge"))
    )
    live = await pgm.introspect_schema(
        pool, schema_name, type_tables=(V2.SuiteTierType, HubRegionType)
    )
    scan_snap = live.tables["door_scan"]
    print(f"rls applied={[r.version for r in applied]} relrowsecurity={badge_rel.relrowsecurity}")
    # => rls applied=['0003_rls_policies'] relrowsecurity=True
    print(f"partitioned door_scan={scan_snap.partition_by is not None}")
    # => partitioned door_scan=True

What PostgreSQL actually received#

🔭 What PostgreSQL received: 215 statements in 113 round trips (captured live on PostgreSQL)
-- ── round trip 1 ──
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;

-- ── round trip 2 ──
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 3 ──
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" DESC
LIMIT $3;

-- ── round trip 4 ──
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;

-- ── round trip 5 ──
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 6 ──
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" DESC
LIMIT $3;

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

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

-- ── round trip 9 ──
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 10 · 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 11 ──
COMMIT;

-- ── round trip 12 ──
UPDATE "_pgdorm"."migration"
SET
  "migration_status_id" = $1,
  "finished_at" = $2,
  "error_detail" = $3
WHERE "target_schema" = $4 AND "migration_status_id" = $5 AND "lease_expires_at" < $6;

-- ── 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 · 4 statements pipelined ──
BEGIN;
SELECT set_config($1, $2, true);
-- → 1 row
SELECT set_config($1, $2, true);
-- → 1 row
SELECT pg_advisory_xact_lock(hashtext($1));
-- → 1 row

-- ── round trip 16 ──
CREATE TABLE IF NOT EXISTS "door_scan" ("door_scan_id" BIGINT GENERATED BY DEFAULT AS IDENTITY NOT NULL, "scanned_at" TIMESTAMP WITH TIME ZONE NOT NULL, "badge_code" TEXT NOT NULL, CONSTRAINT "pk_oxvftfcf" PRIMARY KEY ("door_scan_id", "scanned_at")) PARTITION BY RANGE ("scanned_at");

-- ── round trip 17 ──
CREATE TABLE IF NOT EXISTS "hub_region_type" ("hub_region_type_id" UUID NOT NULL, "code" TEXT NOT NULL, CONSTRAINT "pk_rpfzodco" PRIMARY KEY ("hub_region_type_id"), CONSTRAINT "uq_wzphjutr" UNIQUE ("code"));

-- ── round trip 18 ──
INSERT INTO "hub_region_type" ("hub_region_type_id", "code")
VALUES ($1, $2), ($3, $4)
ON CONFLICT ("hub_region_type_id") DO UPDATE SET "code" = EXCLUDED."code";
-- → 2 affected

-- ── round trip 19 ──
CREATE TABLE IF NOT EXISTS "suite_tier_type" ("suite_tier_type_id" INTEGER NOT NULL, "code" TEXT NOT NULL, CONSTRAINT "pk_bbbdhxye" PRIMARY KEY ("suite_tier_type_id"), CONSTRAINT "uq_oksgvles" UNIQUE ("code"));

-- ── round trip 20 ──
INSERT INTO "suite_tier_type" ("suite_tier_type_id", "code")
VALUES ($1, $2), ($3, $4)
ON CONFLICT ("suite_tier_type_id") DO UPDATE SET "code" = EXCLUDED."code";
-- → 2 affected

-- ── round trip 21 ──
CREATE TABLE IF NOT EXISTS "estate_wing" ("estate_wing_id" BIGINT GENERATED BY DEFAULT AS IDENTITY NOT NULL, "parent_wing_id" BIGINT, "hub_region_type_id" UUID NOT NULL, "code" TEXT NOT NULL, CONSTRAINT "pk_yvrwyywm" PRIMARY KEY ("estate_wing_id"), CONSTRAINT "uq_yspsjpse" UNIQUE ("code"), CONSTRAINT "fk_fhwxwxvb" FOREIGN KEY ("hub_region_type_id") REFERENCES "hub_region_type" ("hub_region_type_id"), CONSTRAINT "fk_qhzkpolu" FOREIGN KEY ("parent_wing_id") REFERENCES "estate_wing" ("estate_wing_id") ON DELETE SET NULL);

-- ── round trip 22 ──
CREATE INDEX IF NOT EXISTS "ix_dxtbfaan" ON "estate_wing" ("hub_region_type_id");

-- ── round trip 23 ──
CREATE INDEX IF NOT EXISTS "ix_wnlvhmtk" ON "estate_wing" ("parent_wing_id") WHERE parent_wing_id IS NOT NULL;

-- ── round trip 24 ──
CREATE TABLE IF NOT EXISTS "wing_badge" ("wing_badge_id" BIGINT GENERATED BY DEFAULT AS IDENTITY NOT NULL, "estate_wing_id" BIGINT NOT NULL, "tenant_code" TEXT NOT NULL, "label" TEXT NOT NULL, CONSTRAINT "pk_rxdtzztp" PRIMARY KEY ("wing_badge_id"), CONSTRAINT "fk_xpglrcak" FOREIGN KEY ("estate_wing_id") REFERENCES "estate_wing" ("estate_wing_id") ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED);

-- ── round trip 25 ──
CREATE INDEX IF NOT EXISTS "ix_clsbxctb" ON "wing_badge" ("estate_wing_id");

-- … 175 more statements in examples/__wire__/mig_advanced_pg_evolution.sql

Shift report

  • Evolved IntEnum and UUID TypeTable lookups with SyncTypeTable at LockMode.NONE
  • Created and verified self-referential and DEFERRABLE INITIALLY DEFERRED foreign keys
  • Applied enable_rls() and create_policy() as checksummed versioned Migration steps
  • Verified PartitionBy.range() catalog introspection and zero-drift parity

Try it yourself

Add pgm.grant_schema(schema_name, role="pgdorm_rls_user", scope="schema_usage") to m_rls alongside enable_rls and create_policy to provision least-privilege tenant roles in the same migration!

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

Sticky note from Management

"The estate is growing fast — now wire up pyproject.toml, the pgdorm CLI, --json plans for our coding agents, and CI drift alarms with Moby!"