Pattern 2 — TypeTables & _type Naming Clashes#
← Assimilation hub · Live test fixture: cases/02_type_tables_and_naming_clash/
pgdorm enforces a disjoint TypeTable namespace: every pg.TypeTable enum-backed lookup table must end with _type, while ordinary pg.Table entities are forbidden from ending in _type. Existing databases often break both halves of that rule at once:
- A lookup table like
order_statuses(withslug VARCHAR(32)) does not end in_type. - An ordinary entity table like
content_typedoes end in_type(and is referenced byinvoices.content_type_id).
What this pattern demonstrates#
audit-schemaflagsorder_statusesasTYPE_TABLE_CANDIDATEandcontent_typeasNON_TYPE_TABLE_ENDS_WITH_TYPE.- Passing
--type-table order_statusespromotesorder_statuses→order_status_type(OrderStatusType+IntEnum), renamesslug→code, and widensVARCHAR(32)→TEXT(metadata-only in PostgreSQL!). - Simultaneously,
content_typeauto-renames tocontent_kind(PKcontent_kind_id), andinvoices.content_type_idaligns tocontent_kind_idso foreign keys stay symmetric.
Before & After — Table-by-Table Comparison#
Generated by pgdorm scaffold · tests/integration/migrations/onboarding/cases/02_type_tables_and_naming_clash/__captured__/scaffold.py.txt
from enum import IntEnum
import pgdorm as pg
import pgdorm.migrate as pgm
class OrderStatusKind(IntEnum):
PENDING = 1
PAID = 2
CANCELLED = 3
class OrderStatusType(pg.TypeTable, enum=OrderStatusKind):
order_status_type_id: pg.Col[OrderStatusKind] = pg.pk()
class ContentKind(pg.Table):
content_kind_id: pg.Col[int] = pg.pk(default=pg.identity())
title: pg.Col[str]
class Invoice(pg.Table):
invoice_id: pg.Col[int] = pg.pk(default=pg.identity())
status_id: pg.Col[pg.Int4] = pg.fk(OrderStatusType)
content_kind_id: pg.Col[int | None] = pg.fk(ContentKind, default=None)
ADOPTION_MAP = pgm.AdoptionMap(
tables={
'content_type': pgm.TableMapping(target='content_kind', columns={'id': 'content_kind_id'}, pk_strategy=pgm.enums.PkStrategy.RENAME),
'invoices': pgm.TableMapping(target='invoice', columns={'content_type_id': 'content_kind_id', 'id': 'invoice_id'}, pk_strategy=pgm.enums.PkStrategy.RENAME),
'order_statuses': pgm.TableMapping(target='order_status_type', columns={'id': 'order_status_type_id', 'slug': 'code'}, as_type_table=True, pk_strategy=pgm.enums.PkStrategy.RENAME),
},
)
APP = pgm.MigrationApp(tables=(OrderStatusType, ContentKind, Invoice))
tests/integration/migrations/onboarding/cases/02_type_tables_and_naming_clash/schema.sql
CREATE TABLE order_statuses (
id INTEGER PRIMARY KEY,
slug VARCHAR(32) NOT NULL UNIQUE
);
CREATE TABLE content_type (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
title TEXT NOT NULL
);
CREATE TABLE invoices (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
status_id INTEGER NOT NULL REFERENCES order_statuses(id),
content_type_id BIGINT REFERENCES content_type(id)
);
tests/integration/migrations/onboarding/cases/02_type_tables_and_naming_clash/seed.sql
INSERT INTO order_statuses (id, slug) VALUES (1, 'pending'), (2, 'paid'), (3, 'cancelled');
INSERT INTO content_type (title) VALUES ('article'), ('video');
INSERT INTO invoices (status_id, content_type_id) VALUES (1, 1), (2, 2);
Live audit#
migratable · exit 0
8 migration1 info
- FK 'invoices_content_type_id_fkey' on invoices(content_type_id) has no covering B-tree index.
- FK 'invoices_status_id_fkey' on invoices(status_id) has no covering B-tree index.
- Table 'content_type' ends with
_type(reserved for pg.TypeTable). - Table 'invoices' appears plural; assimilate to singular snake_case.
- Table 'order_statuses' appears plural; assimilate to singular snake_case.
- Table 'content_type' PK is 'id' instead of 'content_type_id'.
- Table 'invoices' PK is 'id' instead of 'invoices_id'.
- Table 'order_statuses' PK is 'id' instead of 'order_statuses_id'.
- Table 'order_statuses' looks like a lookup table (Single integer PK + unique character varying(32)
slug, referenced by invoices.)
Inspect raw machine-readable audit JSON (tests/integration/migrations/onboarding/cases/02_type_tables_and_naming_clash/captured/audit.json)
{
"counts": {
"blocker": 0,
"info": 1,
"migration_required": 8,
"unmanaged": 0
},
"findings": [
{
"auto_fixable": true,
"category": "indexes",
"code": "UNINDEXED_FK",
"doc_anchor": "constraints-and-indexes",
"message": "FK 'invoices_content_type_id_fkey' on invoices(content_type_id) has no covering B-tree index.",
"object_kind": "foreign_key",
"object_name": "invoices_content_type_id_fkey",
"severity": "migration_required",
"suggestion": "Assimilation plans online `CREATE INDEX CONCURRENTLY` for uncovered FKs.",
"table": "invoices"
},
{
"auto_fixable": true,
"category": "indexes",
"code": "UNINDEXED_FK",
"doc_anchor": "constraints-and-indexes",
"message": "FK 'invoices_status_id_fkey' on invoices(status_id) has no covering B-tree index.",
"object_kind": "foreign_key",
"object_name": "invoices_status_id_fkey",
"severity": "migration_required",
"suggestion": "Assimilation plans online `CREATE INDEX CONCURRENTLY` for uncovered FKs.",
"table": "invoices"
},
{
"auto_fixable": true,
"category": "naming",
"code": "NON_TYPE_TABLE_ENDS_WITH_TYPE",
"doc_anchor": "type-table-namespace",
"message": "Table 'content_type' ends with `_type` (reserved for pg.TypeTable).",
"object_kind": "table",
"object_name": "content_type",
"severity": "migration_required",
"suggestion": "Either promote to `pg.TypeTable` or rename the entity table (e.g. `*_kind`).",
"table": "content_type"
},
{
"auto_fixable": true,
"category": "naming",
"code": "TABLE_NAME_PLURAL",
"doc_anchor": "table-naming",
"message": "Table 'invoices' appears plural; assimilate to singular snake_case.",
"object_kind": "table",
"object_name": "invoices",
"severity": "migration_required",
"suggestion": "Rename table to singular snake_case via AdoptionMap.",
"table": "invoices"
},
{
"auto_fixable": true,
"category": "naming",
"code": "TABLE_NAME_PLURAL",
"doc_anchor": "table-naming",
"message": "Table 'order_statuses' appears plural; assimilate to singular snake_case.",
"object_kind": "table",
"object_name": "order_statuses",
"severity": "migration_required",
"suggestion": "Rename table to singular snake_case via AdoptionMap.",
"table": "order_statuses"
},
{
"auto_fixable": true,
"category": "primary_key",
"code": "PK_NAME_MISMATCH",
"doc_anchor": "primary-keys-and-serials",
"message": "Table 'content_type' PK is 'id' instead of 'content_type_id'.",
"object_kind": "primary_key",
"object_name": "id",
"severity": "migration_required",
"suggestion": "Rename single int/UUID PK to `<table_name>_id`, or add surrogate PK.",
"table": "content_type"
},
{
"auto_fixable": true,
"category": "primary_key",
"code": "PK_NAME_MISMATCH",
"doc_anchor": "primary-keys-and-serials",
"message": "Table 'invoices' PK is 'id' instead of 'invoices_id'.",
"object_kind": "primary_key",
"object_name": "id",
"severity": "migration_required",
"suggestion": "Rename single int/UUID PK to `<table_name>_id`, or add surrogate PK.",
"table": "invoices"
},
{
"auto_fixable": true,
"category": "primary_key",
"code": "PK_NAME_MISMATCH",
"doc_anchor": "primary-keys-and-serials",
"message": "Table 'order_statuses' PK is 'id' instead of 'order_statuses_id'.",
"object_kind": "primary_key",
"object_name": "id",
"severity": "migration_required",
"suggestion": "Rename single int/UUID PK to `<table_name>_id`, or add surrogate PK.",
"table": "order_statuses"
},
{
"auto_fixable": true,
"category": "type_table",
"code": "TYPE_TABLE_CANDIDATE",
"doc_anchor": "type-table-namespace",
"message": "Table 'order_statuses' looks like a lookup table (Single integer PK + unique character varying(32) `slug`, referenced by invoices.)",
"object_kind": "table",
"object_name": "order_statuses",
"severity": "info",
"suggestion": "Review candidate; pass `--type-table <table>` or `as_type_table=True` to promote.",
"table": "order_statuses"
}
],
"ignored_tables": [],
"migratable": true,
"schema": "public",
"table_count": 3,
"type_table_candidates": [
{
"code_column": "slug",
"code_pg_type": "character varying(32)",
"confidence": "high",
"pk_column": "id",
"pk_pg_type": "integer",
"reason": "Single integer PK + unique character varying(32) `slug`, referenced by invoices.",
"referencing_tables": [
"invoices"
],
"table": "order_statuses"
}
],
"unmanaged_objects": {
"extensions": [],
"indexes": [],
"rls_policies": [],
"routines": [],
"triggers": [],
"views": []
},
"workflow_steps": [
{
"detail": "Run `pgdorm scaffold` and `pgdorm adopt-plan` (use `execute_plan_tx` inside a psycopg3 transaction when recreating views/functions atomically).",
"order": 1,
"phase": "ddl",
"summary": "Scaffold models, review AdoptionMap, and execute transactional DDL"
},
{
"detail": "Run `finalize_external()` or `pgdorm upgrade`, then verify `pgdorm drift`.",
"order": 2,
"phase": "post_commit",
"summary": "Run CONCURRENTLY indexes, VALIDATE constraints, and record ledger"
}
]
}
Compiled assimilation SQL#
Generated by pgdorm adopt-plan --format sql · tests/integration/migrations/onboarding/cases/02_type_tables_and_naming_clash/__captured__/plan.sql
-- pgdorm Assimilation Plan: 0001_assimilate (02_type_tables_and_naming_clash)
-- Checksum: 940c48200b8178c955742ff1281b897d85de1b09918ffa72b9b2e6ec326b0135
-- Ignored tables: (none)
-- Preserved unmanaged objects: 0
-- ===========================================================================
-- PHASE 2 (TRANSACTIONAL DDL): Atomic pgdorm compiled schema assimilation
-- ===========================================================================
BEGIN;
-- (Optional PRE-DDL hook: DROP blocking views/matviews here)
-- [1] (ACCESS EXCLUSIVE) Rename table content_type -> content_kind
ALTER TABLE "public"."content_type" RENAME TO "content_kind";
-- [2] (ACCESS EXCLUSIVE) Rename table invoices -> invoice
ALTER TABLE "public"."invoices" RENAME TO "invoice";
-- [3] (ACCESS EXCLUSIVE) Rename table order_statuses -> order_status_type
ALTER TABLE "public"."order_statuses" RENAME TO "order_status_type";
-- [4] (ACCESS EXCLUSIVE) Rename column content_kind.id -> content_kind_id
ALTER TABLE "public"."content_kind" RENAME COLUMN "id" TO "content_kind_id";
-- [5] (ACCESS EXCLUSIVE) Rename column invoice.content_type_id -> content_kind_id
ALTER TABLE "public"."invoice" RENAME COLUMN "content_type_id" TO "content_kind_id";
-- [6] (ACCESS EXCLUSIVE) Rename column invoice.id -> invoice_id
ALTER TABLE "public"."invoice" RENAME COLUMN "id" TO "invoice_id";
-- [7] (ACCESS EXCLUSIVE) Rename column order_status_type.id -> order_status_type_id
ALTER TABLE "public"."order_status_type" RENAME COLUMN "id" TO "order_status_type_id";
-- [8] (ACCESS EXCLUSIVE) Rename column order_status_type.slug -> code
ALTER TABLE "public"."order_status_type" RENAME COLUMN "slug" TO "code";
-- [9] (ACCESS EXCLUSIVE) Alter column type order_status_type.code -> text
ALTER TABLE "public"."order_status_type" ALTER COLUMN "code" TYPE TEXT;
COMMIT;
-- ===========================================================================
-- PHASE 4 (POST-COMMIT ONLINE / AUTOCOMMIT): CONCURRENTLY & VALIDATE steps
-- Run outside any BEGIN ... COMMIT block (or call pgm.finalize_external()).
-- ===========================================================================
-- [post-1] (SHARE UPDATE EXCLUSIVE) Create index ix_aqhitvoe on invoice
CREATE INDEX CONCURRENTLY IF NOT EXISTS "ix_aqhitvoe" ON "public"."invoice" ("status_id");
-- [post-2] (SHARE UPDATE EXCLUSIVE) Create index ix_guzlyydt on invoice
CREATE INDEX CONCURRENTLY IF NOT EXISTS "ix_guzlyydt" ON "public"."invoice" ("content_kind_id") WHERE content_kind_id IS NOT NULL;
-- [post-3] (NONE) Sync TypeTable seeds for order_status_type
-- (Parameterized query executed automatically by pgm.finalize_external())
INSERT INTO "public"."order_status_type" ("order_status_type_id", "code")
VALUES ($1, $2), ($3, $4), ($5, $6)
ON CONFLICT ("order_status_type_id") DO UPDATE SET "code" = EXCLUDED."code";