Skip to content

Pattern 5 — Composite PKs, Natural Keys & Self-Cycles#

← Assimilation hub · Live test fixture: cases/05_composite_pk_and_cycles/

In pgdorm, every permanent table — including many-to-many junction tables and lookup-by-code tables — declares its own <table_name>_id primary key while expressing composite or natural uniqueness via pg.Unique(...). Existing schemas often have:

  1. Composite-PK join tables (user_roles with PRIMARY KEY (user_id, role_id)).
  2. Natural text primary keys (countries with iso_code TEXT PRIMARY KEY).
  3. Self-referential hierarchies (categories.parent_id REFERENCES categories(id)).

What this pattern demonstrates#

  • Automatic surrogate PK promotion (pk_strategy="add_surrogate"): Both user_roles → user_role and countries → country receive a backfilled BIGINT GENERATED BY DEFAULT AS IDENTITY surrogate PK (user_role_id, country_id), while (user_id, role_id) and (iso_code) are demoted to online UNIQUE constraints (CREATE UNIQUE INDEX CONCURRENTLY + metadata-only UNIQUE USING INDEX).
  • Self-referential FKs: categories.parent_id preserves its role name (parent_id) while its FK target updates cleanly to category(category_id) and receives an online FK index.

Before & After — Table-by-Table Comparison#

categories → category
id → category_id
CREATE TABLE categories (
    id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    parent_id BIGINT REFERENCES categories(id) ON DELETE SET NULL,
    title TEXT NOT NULL
);
class Category(pg.Table):
    category_id: pg.Col[int] = pg.pk(default=pg.identity())
    parent_id: pg.Col[int | None] = pg.self_fk(on_delete=pg.enums.OnDelete.SET_NULL, default=None)
    title: pg.Col[str]
countries → country
+ country_id IDENTITY
CREATE TABLE countries (
    iso_code TEXT PRIMARY KEY,
    title TEXT NOT NULL
);
class Country(pg.Table):
    country_id: pg.Col[int] = pg.pk(default=pg.identity())
    iso_code: pg.Col[str] = pg.col(unique=True)
    title: pg.Col[str]
roles → role
id → role_id
CREATE TABLE roles (
    id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    label TEXT NOT NULL UNIQUE
);
class Role(pg.Table):
    role_id: pg.Col[int] = pg.pk(default=pg.identity())
    label: pg.Col[str] = pg.col(unique=True)
users → user
id → user_id
CREATE TABLE users (
    id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    name TEXT NOT NULL
);
class User(pg.Table):
    user_id: pg.Col[int] = pg.pk(default=pg.identity())
    name: pg.Col[str]
user_roles → user_role
+ user_role_id IDENTITY
CREATE TABLE user_roles (
    user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    role_id BIGINT NOT NULL REFERENCES roles(id) ON DELETE CASCADE,
    PRIMARY KEY (user_id, role_id)
);
class UserRole(pg.Table):
    user_role_id: pg.Col[int] = pg.pk(default=pg.identity())
    user_id: pg.Col[int] = pg.fk(User, on_delete=pg.enums.OnDelete.CASCADE)
    role_id: pg.Col[int] = pg.fk(Role, on_delete=pg.enums.OnDelete.CASCADE)

    @classmethod
    def __constraints__(cls) -> tuple[pg.TableConstraint, ...]:
        return (
            pg.Unique(cls.user_id, cls.role_id),
        )
Generated by pgdorm scaffold · tests/integration/migrations/onboarding/cases/05_composite_pk_and_cycles/__captured__/scaffold.py.txt
import pgdorm as pg
import pgdorm.migrate as pgm


class Category(pg.Table):
    category_id: pg.Col[int] = pg.pk(default=pg.identity())
    parent_id: pg.Col[int | None] = pg.self_fk(on_delete=pg.enums.OnDelete.SET_NULL, default=None)
    title: pg.Col[str]


class Country(pg.Table):
    country_id: pg.Col[int] = pg.pk(default=pg.identity())
    iso_code: pg.Col[str] = pg.col(unique=True)
    title: pg.Col[str]


class Role(pg.Table):
    role_id: pg.Col[int] = pg.pk(default=pg.identity())
    label: pg.Col[str] = pg.col(unique=True)


class User(pg.Table):
    user_id: pg.Col[int] = pg.pk(default=pg.identity())
    name: pg.Col[str]


class UserRole(pg.Table):
    user_role_id: pg.Col[int] = pg.pk(default=pg.identity())
    user_id: pg.Col[int] = pg.fk(User, on_delete=pg.enums.OnDelete.CASCADE)
    role_id: pg.Col[int] = pg.fk(Role, on_delete=pg.enums.OnDelete.CASCADE)

    @classmethod
    def __constraints__(cls) -> tuple[pg.TableConstraint, ...]:
        return (
            pg.Unique(cls.user_id, cls.role_id),
        )


ADOPTION_MAP = pgm.AdoptionMap(
    tables={
        'categories': pgm.TableMapping(target='category', columns={'id': 'category_id'}, pk_strategy=pgm.enums.PkStrategy.RENAME),
        'countries': pgm.TableMapping(target='country', pk_strategy=pgm.enums.PkStrategy.ADD_SURROGATE),
        'roles': pgm.TableMapping(target='role', columns={'id': 'role_id'}, pk_strategy=pgm.enums.PkStrategy.RENAME),
        'user_roles': pgm.TableMapping(target='user_role', pk_strategy=pgm.enums.PkStrategy.ADD_SURROGATE),
        'users': pgm.TableMapping(target='user', columns={'id': 'user_id'}, pk_strategy=pgm.enums.PkStrategy.RENAME),
    },
)


APP = pgm.MigrationApp(tables=(Category, Country, Role, User, UserRole))
tests/integration/migrations/onboarding/cases/05_composite_pk_and_cycles/schema.sql
CREATE TABLE users (
    id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    name TEXT NOT NULL
);

CREATE TABLE roles (
    id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    label TEXT NOT NULL UNIQUE
);

CREATE TABLE user_roles (
    user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    role_id BIGINT NOT NULL REFERENCES roles(id) ON DELETE CASCADE,
    PRIMARY KEY (user_id, role_id)
);

CREATE TABLE countries (
    iso_code TEXT PRIMARY KEY,
    title TEXT NOT NULL
);

CREATE TABLE categories (
    id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    parent_id BIGINT REFERENCES categories(id) ON DELETE SET NULL,
    title TEXT NOT NULL
);
tests/integration/migrations/onboarding/cases/05_composite_pk_and_cycles/seed.sql
INSERT INTO users (name) VALUES ('Ada'), ('Grace');
INSERT INTO roles (label) VALUES ('admin'), ('editor');
INSERT INTO user_roles (user_id, role_id) VALUES (1, 1), (1, 2), (2, 2);
INSERT INTO countries (iso_code, title) VALUES ('DE', 'Germany'), ('US', 'United States');
INSERT INTO categories (id, parent_id, title) VALUES (1, NULL, 'Root'), (2, 1, 'Child');

Live audit#

migratable · exit 0
12 migration1 info
  • MIGRATIONUNINDEXED_FK
    categories · categories_parent_id_fkey
    FK 'categories_parent_id_fkey' on categories(parent_id) has no covering B-tree index.
  • MIGRATIONUNINDEXED_FK
    user_roles · user_roles_role_id_fkey
    FK 'user_roles_role_id_fkey' on user_roles(role_id) has no covering B-tree index.
  • MIGRATIONTABLE_NAME_PLURAL
    categories
    Table 'categories' appears plural; assimilate to singular snake_case.
  • MIGRATIONTABLE_NAME_PLURAL
    countries
    Table 'countries' appears plural; assimilate to singular snake_case.
  • MIGRATIONTABLE_NAME_PLURAL
    roles
    Table 'roles' appears plural; assimilate to singular snake_case.
  • MIGRATIONTABLE_NAME_PLURAL
    user_roles
    Table 'user_roles' appears plural; assimilate to singular snake_case.
  • MIGRATIONTABLE_NAME_PLURAL
    users
    Table 'users' appears plural; assimilate to singular snake_case.
  • MIGRATIONPK_NAME_MISMATCH
    categories · id
    Table 'categories' PK is 'id' instead of 'categories_id'.
  • MIGRATIONPK_NAME_MISMATCH
    countries · iso_code
    Table 'countries' PK is 'iso_code' instead of 'countries_id'.
  • MIGRATIONPK_NAME_MISMATCH
    roles · id
    Table 'roles' PK is 'id' instead of 'roles_id'.
  • MIGRATIONPK_COMPOSITE
    user_roles · user_id,role_id
    Table 'user_roles' uses composite PK (user_id, role_id).
  • MIGRATIONPK_NAME_MISMATCH
    users · id
    Table 'users' PK is 'id' instead of 'users_id'.
  • INFOTYPE_TABLE_CANDIDATE
    roles
    Table 'roles' looks like a lookup table (Single bigint PK + unique text label, referenced by user_roles.)
Inspect raw machine-readable audit JSON (tests/integration/migrations/onboarding/cases/05_composite_pk_and_cycles/captured/audit.json)
{
  "counts": {
    "blocker": 0,
    "info": 1,
    "migration_required": 12,
    "unmanaged": 0
  },
  "findings": [
    {
      "auto_fixable": true,
      "category": "indexes",
      "code": "UNINDEXED_FK",
      "doc_anchor": "constraints-and-indexes",
      "message": "FK 'categories_parent_id_fkey' on categories(parent_id) has no covering B-tree index.",
      "object_kind": "foreign_key",
      "object_name": "categories_parent_id_fkey",
      "severity": "migration_required",
      "suggestion": "Assimilation plans online `CREATE INDEX CONCURRENTLY` for uncovered FKs.",
      "table": "categories"
    },
    {
      "auto_fixable": true,
      "category": "indexes",
      "code": "UNINDEXED_FK",
      "doc_anchor": "constraints-and-indexes",
      "message": "FK 'user_roles_role_id_fkey' on user_roles(role_id) has no covering B-tree index.",
      "object_kind": "foreign_key",
      "object_name": "user_roles_role_id_fkey",
      "severity": "migration_required",
      "suggestion": "Assimilation plans online `CREATE INDEX CONCURRENTLY` for uncovered FKs.",
      "table": "user_roles"
    },
    {
      "auto_fixable": true,
      "category": "naming",
      "code": "TABLE_NAME_PLURAL",
      "doc_anchor": "table-naming",
      "message": "Table 'categories' appears plural; assimilate to singular snake_case.",
      "object_kind": "table",
      "object_name": "categories",
      "severity": "migration_required",
      "suggestion": "Rename table to singular snake_case via AdoptionMap.",
      "table": "categories"
    },
    {
      "auto_fixable": true,
      "category": "naming",
      "code": "TABLE_NAME_PLURAL",
      "doc_anchor": "table-naming",
      "message": "Table 'countries' appears plural; assimilate to singular snake_case.",
      "object_kind": "table",
      "object_name": "countries",
      "severity": "migration_required",
      "suggestion": "Rename table to singular snake_case via AdoptionMap.",
      "table": "countries"
    },
    {
      "auto_fixable": true,
      "category": "naming",
      "code": "TABLE_NAME_PLURAL",
      "doc_anchor": "table-naming",
      "message": "Table 'roles' appears plural; assimilate to singular snake_case.",
      "object_kind": "table",
      "object_name": "roles",
      "severity": "migration_required",
      "suggestion": "Rename table to singular snake_case via AdoptionMap.",
      "table": "roles"
    },
    {
      "auto_fixable": true,
      "category": "naming",
      "code": "TABLE_NAME_PLURAL",
      "doc_anchor": "table-naming",
      "message": "Table 'user_roles' appears plural; assimilate to singular snake_case.",
      "object_kind": "table",
      "object_name": "user_roles",
      "severity": "migration_required",
      "suggestion": "Rename table to singular snake_case via AdoptionMap.",
      "table": "user_roles"
    },
    {
      "auto_fixable": true,
      "category": "naming",
      "code": "TABLE_NAME_PLURAL",
      "doc_anchor": "table-naming",
      "message": "Table 'users' appears plural; assimilate to singular snake_case.",
      "object_kind": "table",
      "object_name": "users",
      "severity": "migration_required",
      "suggestion": "Rename table to singular snake_case via AdoptionMap.",
      "table": "users"
    },
    {
      "auto_fixable": true,
      "category": "primary_key",
      "code": "PK_NAME_MISMATCH",
      "doc_anchor": "primary-keys-and-serials",
      "message": "Table 'categories' PK is 'id' instead of 'categories_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": "categories"
    },
    {
      "auto_fixable": true,
      "category": "primary_key",
      "code": "PK_NAME_MISMATCH",
      "doc_anchor": "primary-keys-and-serials",
      "message": "Table 'countries' PK is 'iso_code' instead of 'countries_id'.",
      "object_kind": "primary_key",
      "object_name": "iso_code",
      "severity": "migration_required",
      "suggestion": "Rename single int/UUID PK to `<table_name>_id`, or add surrogate PK.",
      "table": "countries"
    },
    {
      "auto_fixable": true,
      "category": "primary_key",
      "code": "PK_NAME_MISMATCH",
      "doc_anchor": "primary-keys-and-serials",
      "message": "Table 'roles' PK is 'id' instead of 'roles_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": "roles"
    },
    {
      "auto_fixable": true,
      "category": "primary_key",
      "code": "PK_COMPOSITE",
      "doc_anchor": "primary-keys-and-serials",
      "message": "Table 'user_roles' uses composite PK (user_id, role_id).",
      "object_kind": "primary_key",
      "object_name": "user_id,role_id",
      "severity": "migration_required",
      "suggestion": "Add surrogate `<table_name>_id` PK and demote composite PK to `pg.Unique(...)`.",
      "table": "user_roles"
    },
    {
      "auto_fixable": true,
      "category": "primary_key",
      "code": "PK_NAME_MISMATCH",
      "doc_anchor": "primary-keys-and-serials",
      "message": "Table 'users' PK is 'id' instead of 'users_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": "users"
    },
    {
      "auto_fixable": true,
      "category": "type_table",
      "code": "TYPE_TABLE_CANDIDATE",
      "doc_anchor": "type-table-namespace",
      "message": "Table 'roles' looks like a lookup table (Single bigint PK + unique text `label`, referenced by user_roles.)",
      "object_kind": "table",
      "object_name": "roles",
      "severity": "info",
      "suggestion": "Review candidate; pass `--type-table <table>` or `as_type_table=True` to promote.",
      "table": "roles"
    }
  ],
  "ignored_tables": [],
  "migratable": true,
  "schema": "public",
  "table_count": 5,
  "type_table_candidates": [
    {
      "code_column": "label",
      "code_pg_type": "text",
      "confidence": "high",
      "pk_column": "id",
      "pk_pg_type": "bigint",
      "reason": "Single bigint PK + unique text `label`, referenced by user_roles.",
      "referencing_tables": [
        "user_roles"
      ],
      "table": "roles"
    }
  ],
  "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/05_composite_pk_and_cycles/__captured__/plan.sql
-- pgdorm Assimilation Plan: 0001_assimilate (05_composite_pk_and_cycles)
-- Checksum: 207fd486ddafc4e8649ba9e0d3350b6c2716961a86327c22476e342eda8c0f6c
-- 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 categories -> category
ALTER TABLE "public"."categories" RENAME TO "category";
-- [2] (ACCESS EXCLUSIVE) Rename table countries -> country
ALTER TABLE "public"."countries" RENAME TO "country";
-- [3] (ACCESS EXCLUSIVE) Rename table roles -> role
ALTER TABLE "public"."roles" RENAME TO "role";
-- [4] (ACCESS EXCLUSIVE) Rename table user_roles -> user_role
ALTER TABLE "public"."user_roles" RENAME TO "user_role";
-- [5] (ACCESS EXCLUSIVE) Rename table users -> user
ALTER TABLE "public"."users" RENAME TO "user";
-- [6] (ACCESS EXCLUSIVE) Rename column category.id -> category_id
ALTER TABLE "public"."category" RENAME COLUMN "id" TO "category_id";
-- [7] (ACCESS EXCLUSIVE) Rename column role.id -> role_id
ALTER TABLE "public"."role" RENAME COLUMN "id" TO "role_id";
-- [8] (ACCESS EXCLUSIVE) Rename column user.id -> user_id
ALTER TABLE "public"."user" RENAME COLUMN "id" TO "user_id";
-- [9] (ACCESS EXCLUSIVE) Add column country.country_id
ALTER TABLE "public"."country" ADD COLUMN "country_id" BIGINT GENERATED BY DEFAULT AS IDENTITY NOT NULL;
-- [10] (ACCESS EXCLUSIVE) Drop constraint countries_pkey on country
ALTER TABLE "public"."country" DROP CONSTRAINT IF EXISTS "countries_pkey";
-- [11] (ACCESS EXCLUSIVE) Add PRIMARY KEY pk_bwnktuqj on country
ALTER TABLE "public"."country" ADD CONSTRAINT "pk_bwnktuqj" PRIMARY KEY ("country_id");
-- [12] (ACCESS EXCLUSIVE) Add column user_role.user_role_id
ALTER TABLE "public"."user_role" ADD COLUMN "user_role_id" BIGINT GENERATED BY DEFAULT AS IDENTITY NOT NULL;
-- [13] (ACCESS EXCLUSIVE) Drop constraint user_roles_pkey on user_role
ALTER TABLE "public"."user_role" DROP CONSTRAINT IF EXISTS "user_roles_pkey";
-- [14] (ACCESS EXCLUSIVE) Add PRIMARY KEY pk_tqmelnbx on user_role
ALTER TABLE "public"."user_role" ADD CONSTRAINT "pk_tqmelnbx" PRIMARY KEY ("user_role_id");

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_tilfkgrm on category
CREATE INDEX CONCURRENTLY IF NOT EXISTS "ix_tilfkgrm" ON "public"."category" ("parent_id") WHERE parent_id IS NOT NULL;
-- [post-2] (SHARE UPDATE EXCLUSIVE) Build unique index CONCURRENTLY uq_inixjchm
CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS "uq_inixjchm" ON "public"."country" ("iso_code");
-- [post-3] (ACCESS EXCLUSIVE) Attach UNIQUE constraint uq_inixjchm via index
ALTER TABLE "public"."country" ADD CONSTRAINT "uq_inixjchm" UNIQUE USING INDEX "uq_inixjchm";
-- [post-4] (SHARE UPDATE EXCLUSIVE) Build unique index CONCURRENTLY uq_aremkgpy
CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS "uq_aremkgpy" ON "public"."user_role" ("user_id", "role_id");
-- [post-5] (ACCESS EXCLUSIVE) Attach UNIQUE constraint uq_aremkgpy via index
ALTER TABLE "public"."user_role" ADD CONSTRAINT "uq_aremkgpy" UNIQUE USING INDEX "uq_aremkgpy";
-- [post-6] (SHARE UPDATE EXCLUSIVE) Create index ix_vabejtly on user_role
CREATE INDEX CONCURRENTLY IF NOT EXISTS "ix_vabejtly" ON "public"."user_role" ("role_id");