Skip to content

Pattern 1 — Serials, Plural Tables & Primary Keys#

← Assimilation hub · Live test fixture: cases/01_rails_django_plural_id/

The most common brownfield pattern across Rails, Django, Laravel, and hand-written PostgreSQL schemas: plural table names (accounts, orders), bare id BIGSERIAL PRIMARY KEY columns, an unindexed foreign key, and a framework migration ledger (django_migrations).

What this pattern demonstrates#

  • Automatic SERIAL → IDENTITY modernization: In assimilate mode, legacy BIGSERIAL / SERIAL / SMALLSERIAL primary keys automatically modernize to PostgreSQL GENERATED BY DEFAULT AS IDENTITY (pg.identity()) — followed by await pgm.sync_identity_from_max(pool, Account, "account_id") so the next insert starts at MAX(account_id) + 1. In zero-DDL bind mode, untouched serial defaults stay bound via pg.pk(server_managed=True).
  • Automatic JOIN ... USING alignment: Renaming accounts.id → account_id aligns it with orders.account_id.

Before & After — Table-by-Table Comparison#

accounts → account
SERIAL → IDENTITYid → account_id
CREATE TABLE accounts (
    id BIGSERIAL PRIMARY KEY,
    email VARCHAR(120) NOT NULL UNIQUE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
class Account(pg.Table):
    account_id: pg.Col[int] = pg.pk(default=pg.identity())
    email: pg.Col[str] = pg.col(max_len=120, unique=True)
    created_at: pg.Col[datetime] = pg.col(default=pg.now())
orders → order
SERIAL → IDENTITYid → order_id
CREATE TABLE orders (
    id BIGSERIAL PRIMARY KEY,
    account_id BIGINT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
    total NUMERIC(10, 2) NOT NULL DEFAULT 0.00,
    paid BOOLEAN NOT NULL DEFAULT false
);
class Order(pg.Table):
    order_id: pg.Col[int] = pg.pk(default=pg.identity())
    account_id: pg.Col[int] = pg.fk(Account, on_delete=pg.enums.OnDelete.CASCADE)
    total: pg.Col[Decimal] = pg.col(precision=10, scale=2, default=Decimal('0.00'))
    paid: pg.Col[bool] = pg.col(default=False)
Ignored framework tables
--ignore-tablePreserved untouched
CREATE TABLE django_migrations (
    id BIGSERIAL PRIMARY KEY,
    app TEXT NOT NULL,
    name TEXT NOT NULL
);

Left completely untouched via ignore_tables (django_migrations). Never audited, renamed, or dropped by pgdorm.migrate — even when a legacy table name ends in _type.

Generated by pgdorm scaffold · tests/integration/migrations/onboarding/cases/01_rails_django_plural_id/__captured__/scaffold.py.txt
from datetime import datetime
from decimal import Decimal

import pgdorm as pg
import pgdorm.migrate as pgm


class Account(pg.Table):
    account_id: pg.Col[int] = pg.pk(default=pg.identity())
    email: pg.Col[str] = pg.col(max_len=120, unique=True)
    created_at: pg.Col[datetime] = pg.col(default=pg.now())


class Order(pg.Table):
    order_id: pg.Col[int] = pg.pk(default=pg.identity())
    account_id: pg.Col[int] = pg.fk(Account, on_delete=pg.enums.OnDelete.CASCADE)
    total: pg.Col[Decimal] = pg.col(precision=10, scale=2, default=Decimal('0.00'))
    paid: pg.Col[bool] = pg.col(default=False)


ADOPTION_MAP = pgm.AdoptionMap(
    tables={
        'accounts': pgm.TableMapping(target='account', columns={'id': 'account_id'}, pk_strategy=pgm.enums.PkStrategy.RENAME, migrate_serial_to_identity=True),
        'orders': pgm.TableMapping(target='order', columns={'id': 'order_id'}, pk_strategy=pgm.enums.PkStrategy.RENAME, migrate_serial_to_identity=True),
    },
    ignore_tables=frozenset({'django_migrations'}),
)


APP = pgm.MigrationApp(tables=(Account, Order), ignore_tables=frozenset({'django_migrations'}))
tests/integration/migrations/onboarding/cases/01_rails_django_plural_id/schema.sql
CREATE TABLE django_migrations (
    id BIGSERIAL PRIMARY KEY,
    app TEXT NOT NULL,
    name TEXT NOT NULL
);

CREATE TABLE accounts (
    id BIGSERIAL PRIMARY KEY,
    email VARCHAR(120) NOT NULL UNIQUE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE orders (
    id BIGSERIAL PRIMARY KEY,
    account_id BIGINT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
    total NUMERIC(10, 2) NOT NULL DEFAULT 0.00,
    paid BOOLEAN NOT NULL DEFAULT false
);
tests/integration/migrations/onboarding/cases/01_rails_django_plural_id/seed.sql
INSERT INTO django_migrations (app, name) VALUES ('core', '0001_initial');
INSERT INTO accounts (email) VALUES ('[email protected]'), ('[email protected]');
INSERT INTO orders (account_id, total, paid) VALUES (1, 42.50, true), (2, 19.99, false);

Live audit#

migratable · exit 0
5 migration3 info
  • MIGRATIONUNINDEXED_FK
    orders · orders_account_id_fkey
    FK 'orders_account_id_fkey' on orders(account_id) has no covering B-tree index.
  • MIGRATIONTABLE_NAME_PLURAL
    accounts
    Table 'accounts' appears plural; assimilate to singular snake_case.
  • MIGRATIONTABLE_NAME_PLURAL
    orders
    Table 'orders' appears plural; assimilate to singular snake_case.
  • MIGRATIONPK_NAME_MISMATCH
    accounts · id
    Table 'accounts' PK is 'id' instead of 'accounts_id'.
  • MIGRATIONPK_NAME_MISMATCH
    orders · id
    Table 'orders' PK is 'id' instead of 'orders_id'.
  • INFOSERIAL_COLUMN
    accounts · id
    Column accounts.id uses owned SERIAL sequence default (nextval('accounts_id_seq'::regclass)).
  • INFOSERIAL_COLUMN
    orders · id
    Column orders.id uses owned SERIAL sequence default (nextval('orders_id_seq'::regclass)).
  • INFOTYPE_TABLE_CANDIDATE
    accounts
    Table 'accounts' looks like a lookup table (Single bigint PK + unique character varying(120) email, referenced by orders.)
Inspect raw machine-readable audit JSON (tests/integration/migrations/onboarding/cases/01_rails_django_plural_id/captured/audit.json)
{
  "counts": {
    "blocker": 0,
    "info": 3,
    "migration_required": 5,
    "unmanaged": 0
  },
  "findings": [
    {
      "auto_fixable": true,
      "category": "indexes",
      "code": "UNINDEXED_FK",
      "doc_anchor": "constraints-and-indexes",
      "message": "FK 'orders_account_id_fkey' on orders(account_id) has no covering B-tree index.",
      "object_kind": "foreign_key",
      "object_name": "orders_account_id_fkey",
      "severity": "migration_required",
      "suggestion": "Assimilation plans online `CREATE INDEX CONCURRENTLY` for uncovered FKs.",
      "table": "orders"
    },
    {
      "auto_fixable": true,
      "category": "naming",
      "code": "TABLE_NAME_PLURAL",
      "doc_anchor": "table-naming",
      "message": "Table 'accounts' appears plural; assimilate to singular snake_case.",
      "object_kind": "table",
      "object_name": "accounts",
      "severity": "migration_required",
      "suggestion": "Rename table to singular snake_case via AdoptionMap.",
      "table": "accounts"
    },
    {
      "auto_fixable": true,
      "category": "naming",
      "code": "TABLE_NAME_PLURAL",
      "doc_anchor": "table-naming",
      "message": "Table 'orders' appears plural; assimilate to singular snake_case.",
      "object_kind": "table",
      "object_name": "orders",
      "severity": "migration_required",
      "suggestion": "Rename table to singular snake_case via AdoptionMap.",
      "table": "orders"
    },
    {
      "auto_fixable": true,
      "category": "primary_key",
      "code": "PK_NAME_MISMATCH",
      "doc_anchor": "primary-keys-and-serials",
      "message": "Table 'accounts' PK is 'id' instead of 'accounts_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": "accounts"
    },
    {
      "auto_fixable": true,
      "category": "primary_key",
      "code": "PK_NAME_MISMATCH",
      "doc_anchor": "primary-keys-and-serials",
      "message": "Table 'orders' PK is 'id' instead of 'orders_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": "orders"
    },
    {
      "auto_fixable": true,
      "category": "primary_key",
      "code": "SERIAL_COLUMN",
      "doc_anchor": "primary-keys-and-serials",
      "message": "Column accounts.id uses owned SERIAL sequence default (nextval('accounts_id_seq'::regclass)).",
      "object_kind": "column",
      "object_name": "id",
      "severity": "info",
      "suggestion": "Assimilate upgrades SERIAL PKs to IDENTITY; bind uses `server_managed=True`.",
      "table": "accounts"
    },
    {
      "auto_fixable": true,
      "category": "primary_key",
      "code": "SERIAL_COLUMN",
      "doc_anchor": "primary-keys-and-serials",
      "message": "Column orders.id uses owned SERIAL sequence default (nextval('orders_id_seq'::regclass)).",
      "object_kind": "column",
      "object_name": "id",
      "severity": "info",
      "suggestion": "Assimilate upgrades SERIAL PKs to IDENTITY; bind uses `server_managed=True`.",
      "table": "orders"
    },
    {
      "auto_fixable": true,
      "category": "type_table",
      "code": "TYPE_TABLE_CANDIDATE",
      "doc_anchor": "type-table-namespace",
      "message": "Table 'accounts' looks like a lookup table (Single bigint PK + unique character varying(120) `email`, referenced by orders.)",
      "object_kind": "table",
      "object_name": "accounts",
      "severity": "info",
      "suggestion": "Review candidate; pass `--type-table <table>` or `as_type_table=True` to promote.",
      "table": "accounts"
    }
  ],
  "ignored_tables": [
    "django_migrations"
  ],
  "migratable": true,
  "schema": "public",
  "table_count": 2,
  "type_table_candidates": [
    {
      "code_column": "email",
      "code_pg_type": "character varying(120)",
      "confidence": "medium",
      "pk_column": "id",
      "pk_pg_type": "bigint",
      "reason": "Single bigint PK + unique character varying(120) `email`, referenced by orders.",
      "referencing_tables": [
        "orders"
      ],
      "table": "accounts"
    }
  ],
  "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/01_rails_django_plural_id/__captured__/plan.sql
-- pgdorm Assimilation Plan: 0001_assimilate (01_rails_django_plural_id)
-- Checksum: 2feb78c83c35166d2c6924f04d8fe6caeea0a26f01abfd2e6c3f5bae5f4ee40a
-- Ignored tables: django_migrations
-- 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 accounts -> account
ALTER TABLE "public"."accounts" RENAME TO "account";
-- [2] (ACCESS EXCLUSIVE) Rename table orders -> order
ALTER TABLE "public"."orders" RENAME TO "order";
-- [3] (ACCESS EXCLUSIVE) Rename column account.id -> account_id
ALTER TABLE "public"."account" RENAME COLUMN "id" TO "account_id";
-- [4] (ACCESS EXCLUSIVE) Rename column order.id -> order_id
ALTER TABLE "public"."order" RENAME COLUMN "id" TO "order_id";
-- [5] (ACCESS EXCLUSIVE) Drop default on account.account_id
ALTER TABLE "public"."account" ALTER COLUMN "account_id" DROP DEFAULT;
-- [6] (ACCESS EXCLUSIVE) Add identity on account.account_id
ALTER TABLE "public"."account" ALTER COLUMN "account_id" ADD GENERATED BY DEFAULT AS IDENTITY;
-- [7] (ACCESS EXCLUSIVE) Drop default on order.order_id
ALTER TABLE "public"."order" ALTER COLUMN "order_id" DROP DEFAULT;
-- [8] (ACCESS EXCLUSIVE) Add identity on order.order_id
ALTER TABLE "public"."order" ALTER COLUMN "order_id" ADD GENERATED BY DEFAULT AS IDENTITY;

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_hltnpbgg on order
CREATE INDEX CONCURRENTLY IF NOT EXISTS "ix_hltnpbgg" ON "public"."order" ("account_id");