Skip to content

Assimilating Pure SQL#

← Assimilation hub · Live test fixture: frameworks/01_pure_sql/

Hand-written PostgreSQL schemas often combine everything at once: plural table names, bare id BIGSERIAL primary keys, unindexed foreign keys, composite-PK join tables, specialized GIN indexes on JSONB, and reporting views. Here is how pgdorm assimilates our shared Billing & Orders schema while keeping the GIN index intact and updating v_open_orders atomically inside one transaction.

1. Before & After — Table-by-Table Schema Comparison#

Running pgdorm --dsn "$DATABASE_URL" scaffold --type-table order_statuses reads the live (id, code) rows from order_statuses over a zero-raw-SQL query and emits compliant Python models, ADOPTION_MAP, and APP. Every original PostgreSQL table lines up directly beside its scaffolded pgdorm class below:

order_statuses → order_status_type
TypeTable + IntEnumid → order_status_type_id
CREATE TABLE order_statuses (
    id INTEGER PRIMARY KEY,
    code VARCHAR(32) NOT NULL UNIQUE
);
class OrderStatusKind(IntEnum):
    PENDING = 1
    PAID = 2
    CANCELLED = 3


class OrderStatusType(pg.TypeTable, enum=OrderStatusKind):
    order_status_type_id: pg.Col[OrderStatusKind] = pg.pk()
accounts → account
SERIAL → IDENTITYid → account_id
CREATE TABLE accounts (
    id BIGSERIAL PRIMARY KEY,
    email VARCHAR(120) NOT NULL UNIQUE,
    is_active BOOLEAN NOT NULL DEFAULT true,
    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)
    is_active: pg.Col[bool] = pg.col(default=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,
    status_id INTEGER NOT NULL REFERENCES order_statuses(id),
    total_eur NUMERIC(10, 2) NOT NULL DEFAULT 0.00,
    meta JSONB NOT NULL DEFAULT '{}'::jsonb,
    placed_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX idx_orders_meta_gin ON orders USING gin (meta);
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)
    status_id: pg.Col[pg.Int4] = pg.fk(OrderStatusType)
    total_eur: pg.Col[Decimal] = pg.col(precision=10, scale=2, default=Decimal('0.00'))
    meta: pg.Col[pg.Jsonb[pg.JsonValue]] = pg.col(default={})
    placed_at: pg.Col[datetime] = pg.col(default=pg.now())
tags → tag
SERIAL → IDENTITYid → tag_id
CREATE TABLE tags (
    id BIGSERIAL PRIMARY KEY,
    name VARCHAR(64) NOT NULL UNIQUE
);
class Tag(pg.Table):
    tag_id: pg.Col[int] = pg.pk(default=pg.identity())
    name: pg.Col[str] = pg.col(max_len=64, unique=True)
order_tags → order_tag
+ order_tag_id IDENTITY
CREATE TABLE order_tags (
    order_id BIGINT NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
    tag_id BIGINT NOT NULL REFERENCES tags(id) ON DELETE CASCADE,
    PRIMARY KEY (order_id, tag_id)
);
class OrderTag(pg.Table):
    order_tag_id: pg.Col[int] = pg.pk(default=pg.identity())
    order_id: pg.Col[int] = pg.fk(Order, on_delete=pg.enums.OnDelete.CASCADE)
    tag_id: pg.Col[int] = pg.fk(Tag, on_delete=pg.enums.OnDelete.CASCADE)

    @classmethod
    def __constraints__(cls) -> tuple[pg.TableConstraint, ...]:
        return (
            pg.Unique(cls.order_id, cls.tag_id),
        )
Unmanaged PostgreSQL objects
Preserved outside pgdorm
CREATE VIEW v_open_orders AS
SELECT o.id, a.email, o.total_eur
FROM orders o
JOIN accounts a ON a.id = o.account_id
JOIN order_statuses s ON s.id = o.status_id
WHERE s.code = 'pending';

Preserved untouched outside _pgdorm. Live definitions are exported in audit-schema --json; views referencing renamed tables are dropped and recreated atomically inside Phase 3 via execute_plan_tx().

Generated by pgdorm scaffold · tests/integration/migrations/onboarding/frameworks/01_pure_sql/__captured__/scaffold.py.txt
from datetime import datetime
from decimal import Decimal
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 Account(pg.Table):
    account_id: pg.Col[int] = pg.pk(default=pg.identity())
    email: pg.Col[str] = pg.col(max_len=120, unique=True)
    is_active: pg.Col[bool] = pg.col(default=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)
    status_id: pg.Col[pg.Int4] = pg.fk(OrderStatusType)
    total_eur: pg.Col[Decimal] = pg.col(precision=10, scale=2, default=Decimal('0.00'))
    meta: pg.Col[pg.Jsonb[pg.JsonValue]] = pg.col(default={})
    placed_at: pg.Col[datetime] = pg.col(default=pg.now())


class Tag(pg.Table):
    tag_id: pg.Col[int] = pg.pk(default=pg.identity())
    name: pg.Col[str] = pg.col(max_len=64, unique=True)


class OrderTag(pg.Table):
    order_tag_id: pg.Col[int] = pg.pk(default=pg.identity())
    order_id: pg.Col[int] = pg.fk(Order, on_delete=pg.enums.OnDelete.CASCADE)
    tag_id: pg.Col[int] = pg.fk(Tag, on_delete=pg.enums.OnDelete.CASCADE)

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


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),
        'order_statuses': pgm.TableMapping(target='order_status_type', columns={'id': 'order_status_type_id'}, as_type_table=True, pk_strategy=pgm.enums.PkStrategy.RENAME),
        'order_tags': pgm.TableMapping(target='order_tag', pk_strategy=pgm.enums.PkStrategy.ADD_SURROGATE),
        'orders': pgm.TableMapping(target='order', columns={'id': 'order_id'}, pk_strategy=pgm.enums.PkStrategy.RENAME, migrate_serial_to_identity=True),
        'tags': pgm.TableMapping(target='tag', columns={'id': 'tag_id'}, pk_strategy=pgm.enums.PkStrategy.RENAME, migrate_serial_to_identity=True),
    },
)


APP = pgm.MigrationApp(tables=(OrderStatusType, Account, Order, Tag, OrderTag))
tests/integration/migrations/onboarding/frameworks/01_pure_sql/schema.sql
CREATE TABLE order_statuses (
    id INTEGER PRIMARY KEY,
    code VARCHAR(32) NOT NULL UNIQUE
);

CREATE TABLE accounts (
    id BIGSERIAL PRIMARY KEY,
    email VARCHAR(120) NOT NULL UNIQUE,
    is_active BOOLEAN NOT NULL DEFAULT true,
    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,
    status_id INTEGER NOT NULL REFERENCES order_statuses(id),
    total_eur NUMERIC(10, 2) NOT NULL DEFAULT 0.00,
    meta JSONB NOT NULL DEFAULT '{}'::jsonb,
    placed_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX idx_orders_meta_gin ON orders USING gin (meta);

CREATE TABLE tags (
    id BIGSERIAL PRIMARY KEY,
    name VARCHAR(64) NOT NULL UNIQUE
);

CREATE TABLE order_tags (
    order_id BIGINT NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
    tag_id BIGINT NOT NULL REFERENCES tags(id) ON DELETE CASCADE,
    PRIMARY KEY (order_id, tag_id)
);

CREATE VIEW v_open_orders AS
SELECT o.id, a.email, o.total_eur
FROM orders o
JOIN accounts a ON a.id = o.account_id
JOIN order_statuses s ON s.id = o.status_id
WHERE s.code = 'pending';
tests/integration/migrations/onboarding/frameworks/01_pure_sql/seed.sql
INSERT INTO order_statuses (id, code) VALUES (1, 'pending'), (2, 'paid'), (3, 'cancelled');
INSERT INTO accounts (email) VALUES ('[email protected]'), ('[email protected]');
INSERT INTO orders (account_id, status_id, total_eur, meta)
VALUES (1, 1, 49.90, '{"channel": "web"}'), (2, 2, 120.00, '{"channel": "api"}');
INSERT INTO tags (name) VALUES ('priority'), ('eu-vat');
INSERT INTO order_tags (order_id, tag_id) VALUES (1, 1), (1, 2), (2, 2);

2. Live catalog audit (pgdorm audit-schema)#

Notice how audit-schema simultaneously identifies every naming/key delta, surfaces order_statuses as a TYPE_TABLE_CANDIDATE, classifies idx_orders_meta_gin as an unmanaged index (protected from drops), and captures the live pg_get_viewdef SQL for v_open_orders.

migratable · exit 0
13 migration2 unmanaged6 info
  • MIGRATIONUNINDEXED_FK
    order_tags · order_tags_tag_id_fkey
    FK 'order_tags_tag_id_fkey' on order_tags(tag_id) has no covering B-tree index.
  • MIGRATIONUNINDEXED_FK
    orders · orders_account_id_fkey
    FK 'orders_account_id_fkey' on orders(account_id) has no covering B-tree index.
  • MIGRATIONUNINDEXED_FK
    orders · orders_status_id_fkey
    FK 'orders_status_id_fkey' on orders(status_id) has no covering B-tree index.
  • MIGRATIONTABLE_NAME_PLURAL
    accounts
    Table 'accounts' appears plural; assimilate to singular snake_case.
  • MIGRATIONTABLE_NAME_PLURAL
    order_statuses
    Table 'order_statuses' appears plural; assimilate to singular snake_case.
  • MIGRATIONTABLE_NAME_PLURAL
    order_tags
    Table 'order_tags' appears plural; assimilate to singular snake_case.
  • MIGRATIONTABLE_NAME_PLURAL
    orders
    Table 'orders' appears plural; assimilate to singular snake_case.
  • MIGRATIONTABLE_NAME_PLURAL
    tags
    Table 'tags' appears plural; assimilate to singular snake_case.
  • MIGRATIONPK_NAME_MISMATCH
    accounts · id
    Table 'accounts' PK is 'id' instead of 'accounts_id'.
  • MIGRATIONPK_NAME_MISMATCH
    order_statuses · id
    Table 'order_statuses' PK is 'id' instead of 'order_statuses_id'.
  • MIGRATIONPK_COMPOSITE
    order_tags · order_id,tag_id
    Table 'order_tags' uses composite PK (order_id, tag_id).
  • MIGRATIONPK_NAME_MISMATCH
    orders · id
    Table 'orders' PK is 'id' instead of 'orders_id'.
  • MIGRATIONPK_NAME_MISMATCH
    tags · id
    Table 'tags' PK is 'id' instead of 'tags_id'.
  • UNMANAGEDVIEW_PRESENT
    v_open_orders
    View 'v_open_orders' (depends on: accounts, order_statuses, orders) is unmanaged by pgdorm.migrate.
  • UNMANAGEDUNMANAGED_INDEX_PRESENT
    orders · idx_orders_meta_gin
    Index 'idx_orders_meta_gin' on 'orders' (gin, non_btree:gin) will be preserved untouched.
  • 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)).
  • INFOSERIAL_COLUMN
    tags · id
    Column tags.id uses owned SERIAL sequence default (nextval('tags_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.)
  • INFOTYPE_TABLE_CANDIDATE
    order_statuses
    Table 'order_statuses' looks like a lookup table (Single integer PK + unique character varying(32) code, referenced by orders.)
  • INFOTYPE_TABLE_CANDIDATE
    tags
    Table 'tags' looks like a lookup table (Single bigint PK + unique character varying(64) name, referenced by order_tags.)
Inspect raw machine-readable audit JSON (tests/integration/migrations/onboarding/frameworks/01_pure_sql/captured/audit.json)
{
  "counts": {
    "blocker": 0,
    "info": 6,
    "migration_required": 13,
    "unmanaged": 2
  },
  "findings": [
    {
      "auto_fixable": true,
      "category": "indexes",
      "code": "UNINDEXED_FK",
      "doc_anchor": "constraints-and-indexes",
      "message": "FK 'order_tags_tag_id_fkey' on order_tags(tag_id) has no covering B-tree index.",
      "object_kind": "foreign_key",
      "object_name": "order_tags_tag_id_fkey",
      "severity": "migration_required",
      "suggestion": "Assimilation plans online `CREATE INDEX CONCURRENTLY` for uncovered FKs.",
      "table": "order_tags"
    },
    {
      "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": "indexes",
      "code": "UNINDEXED_FK",
      "doc_anchor": "constraints-and-indexes",
      "message": "FK 'orders_status_id_fkey' on orders(status_id) has no covering B-tree index.",
      "object_kind": "foreign_key",
      "object_name": "orders_status_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 '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": "naming",
      "code": "TABLE_NAME_PLURAL",
      "doc_anchor": "table-naming",
      "message": "Table 'order_tags' appears plural; assimilate to singular snake_case.",
      "object_kind": "table",
      "object_name": "order_tags",
      "severity": "migration_required",
      "suggestion": "Rename table to singular snake_case via AdoptionMap.",
      "table": "order_tags"
    },
    {
      "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": "naming",
      "code": "TABLE_NAME_PLURAL",
      "doc_anchor": "table-naming",
      "message": "Table 'tags' appears plural; assimilate to singular snake_case.",
      "object_kind": "table",
      "object_name": "tags",
      "severity": "migration_required",
      "suggestion": "Rename table to singular snake_case via AdoptionMap.",
      "table": "tags"
    },
    {
      "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 '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": "primary_key",
      "code": "PK_COMPOSITE",
      "doc_anchor": "primary-keys-and-serials",
      "message": "Table 'order_tags' uses composite PK (order_id, tag_id).",
      "object_kind": "primary_key",
      "object_name": "order_id,tag_id",
      "severity": "migration_required",
      "suggestion": "Add surrogate `<table_name>_id` PK and demote composite PK to `pg.Unique(...)`.",
      "table": "order_tags"
    },
    {
      "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": "PK_NAME_MISMATCH",
      "doc_anchor": "primary-keys-and-serials",
      "message": "Table 'tags' PK is 'id' instead of 'tags_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": "tags"
    },
    {
      "auto_fixable": false,
      "category": "unmanaged",
      "code": "VIEW_PRESENT",
      "doc_anchor": "unmanaged-objects",
      "message": "View 'v_open_orders' (depends on: accounts, order_statuses, orders) is unmanaged by pgdorm.migrate.",
      "object_kind": "view",
      "object_name": "v_open_orders",
      "severity": "unmanaged",
      "suggestion": "Use the external-TX bridge (`psycopg3`) to recreate impacted views atomically.",
      "table": null
    },
    {
      "auto_fixable": false,
      "category": "unmanaged",
      "code": "UNMANAGED_INDEX_PRESENT",
      "doc_anchor": "unmanaged-objects",
      "message": "Index 'idx_orders_meta_gin' on 'orders' (gin, non_btree:gin) will be preserved untouched.",
      "object_kind": "index",
      "object_name": "idx_orders_meta_gin",
      "severity": "unmanaged",
      "suggestion": "Preserved automatically; verify expression predicates if columns are renamed.",
      "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": "primary_key",
      "code": "SERIAL_COLUMN",
      "doc_anchor": "primary-keys-and-serials",
      "message": "Column tags.id uses owned SERIAL sequence default (nextval('tags_id_seq'::regclass)).",
      "object_kind": "column",
      "object_name": "id",
      "severity": "info",
      "suggestion": "Assimilate upgrades SERIAL PKs to IDENTITY; bind uses `server_managed=True`.",
      "table": "tags"
    },
    {
      "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"
    },
    {
      "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) `code`, referenced by orders.)",
      "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"
    },
    {
      "auto_fixable": true,
      "category": "type_table",
      "code": "TYPE_TABLE_CANDIDATE",
      "doc_anchor": "type-table-namespace",
      "message": "Table 'tags' looks like a lookup table (Single bigint PK + unique character varying(64) `name`, referenced by order_tags.)",
      "object_kind": "table",
      "object_name": "tags",
      "severity": "info",
      "suggestion": "Review candidate; pass `--type-table <table>` or `as_type_table=True` to promote.",
      "table": "tags"
    }
  ],
  "ignored_tables": [],
  "migratable": true,
  "schema": "public",
  "table_count": 5,
  "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"
    },
    {
      "code_column": "code",
      "code_pg_type": "character varying(32)",
      "confidence": "high",
      "pk_column": "id",
      "pk_pg_type": "integer",
      "reason": "Single integer PK + unique character varying(32) `code`, referenced by orders.",
      "referencing_tables": [
        "orders"
      ],
      "table": "order_statuses"
    },
    {
      "code_column": "name",
      "code_pg_type": "character varying(64)",
      "confidence": "high",
      "pk_column": "id",
      "pk_pg_type": "bigint",
      "reason": "Single bigint PK + unique character varying(64) `name`, referenced by order_tags.",
      "referencing_tables": [
        "order_tags"
      ],
      "table": "tags"
    }
  ],
  "unmanaged_objects": {
    "extensions": [],
    "indexes": [
      {
        "access_method": "gin",
        "indexdef": "CREATE INDEX idx_orders_meta_gin ON public.orders USING gin (meta)",
        "name": "idx_orders_meta_gin",
        "reason": "non_btree:gin",
        "table": "orders"
      }
    ],
    "rls_policies": [],
    "routines": [],
    "triggers": [],
    "views": [
      {
        "definition": " SELECT o.id,\n    a.email,\n    o.total_eur\n   FROM orders o\n     JOIN accounts a ON a.id = o.account_id\n     JOIN order_statuses s ON s.id = o.status_id\n  WHERE s.code::text = 'pending'::text;",
        "depends_on_tables": [
          "accounts",
          "order_statuses",
          "orders"
        ],
        "materialized": false,
        "name": "v_open_orders"
      }
    ]
  },
  "workflow_steps": [
    {
      "detail": "Review 1 view(s), 0 trigger(s), and 0 routine(s); drop blocking views inside an external TX if altering columns.",
      "order": 1,
      "phase": "pre_ddl",
      "summary": "Inspect unmanaged views, triggers, and routines"
    },
    {
      "detail": "Run `pgdorm scaffold` and `pgdorm adopt-plan` (use `execute_plan_tx` inside a psycopg3 transaction when recreating views/functions atomically).",
      "order": 2,
      "phase": "ddl",
      "summary": "Scaffold models, review AdoptionMap, and execute transactional DDL"
    },
    {
      "detail": "Update SQL bodies to target assimilated table/column names before committing the external TX.",
      "order": 3,
      "phase": "post_ddl",
      "summary": "Recreate adjusted views, materialized views, and routines"
    },
    {
      "detail": "Run `finalize_external()` or `pgdorm upgrade`, then verify `pgdorm drift`.",
      "order": 4,
      "phase": "post_commit",
      "summary": "Run CONCURRENTLY indexes, VALIDATE constraints, and record ledger"
    }
  ]
}

3. Compiled 4-phase assimilation SQL (pgdorm adopt-plan --format sql)#

Look closely at the 4 phases:

  • Phase 1 warns that v_open_orders references orders, accounts, and order_statuses and prints its live SQL definition.
  • Phase 2 runs all transactional table/column renames, order_status_type.code widening (VARCHAR(32) → TEXT), and surrogate PK addition on order_tag.
  • Phase 3 marks the exact spot inside the same transaction to recreate v_open_orders.
  • Phase 4 runs outside the transaction via finalize_external(): SyncTypeTable, CREATE INDEX CONCURRENTLY for the missing FK indexes, and online 2-phase UNIQUE USING INDEX for order_tag(order_id, tag_id). Notice idx_orders_meta_gin is never dropped.
Generated by pgdorm adopt-plan --format sql · tests/integration/migrations/onboarding/frameworks/01_pure_sql/__captured__/plan.sql
-- pgdorm Assimilation Plan: 0001_assimilate (01_pure_sql)
-- Checksum: 86af3740be04059b22661f001a57eb527c05dbf48734c76fe403d0e6958ff664
-- Ignored tables: (none)
-- Preserved unmanaged objects: 2

-- ===========================================================================
-- PHASE 1 (PRE-DDL): Review impacted unmanaged views, triggers, and routines
-- Drop any blocking views/matviews inside the transaction below before DDL.
-- ===========================================================================
-- [VIEW] v_open_orders: View 'v_open_orders' depends on renamed table(s) accounts, order_statuses, orders; recreate in external TX if column types or definitions change.
--   SELECT o.id,
--       a.email,
--       o.total_eur
--      FROM orders o
--        JOIN accounts a ON a.id = o.account_id
--        JOIN order_statuses s ON s.id = o.status_id
--     WHERE s.code::text = 'pending'::text;

-- ===========================================================================
-- 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 order_statuses -> order_status_type
ALTER TABLE "public"."order_statuses" RENAME TO "order_status_type";
-- [3] (ACCESS EXCLUSIVE) Rename table order_tags -> order_tag
ALTER TABLE "public"."order_tags" RENAME TO "order_tag";
-- [4] (ACCESS EXCLUSIVE) Rename table orders -> order
ALTER TABLE "public"."orders" RENAME TO "order";
-- [5] (ACCESS EXCLUSIVE) Rename table tags -> tag
ALTER TABLE "public"."tags" RENAME TO "tag";
-- [6] (ACCESS EXCLUSIVE) Rename column account.id -> account_id
ALTER TABLE "public"."account" RENAME COLUMN "id" TO "account_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.id -> order_id
ALTER TABLE "public"."order" RENAME COLUMN "id" TO "order_id";
-- [9] (ACCESS EXCLUSIVE) Rename column tag.id -> tag_id
ALTER TABLE "public"."tag" RENAME COLUMN "id" TO "tag_id";
-- [10] (ACCESS EXCLUSIVE) Drop default on account.account_id
ALTER TABLE "public"."account" ALTER COLUMN "account_id" DROP DEFAULT;
-- [11] (ACCESS EXCLUSIVE) Add identity on account.account_id
ALTER TABLE "public"."account" ALTER COLUMN "account_id" ADD GENERATED BY DEFAULT AS IDENTITY;
-- [12] (ACCESS EXCLUSIVE) Drop default on order.order_id
ALTER TABLE "public"."order" ALTER COLUMN "order_id" DROP DEFAULT;
-- [13] (ACCESS EXCLUSIVE) Add identity on order.order_id
ALTER TABLE "public"."order" ALTER COLUMN "order_id" ADD GENERATED BY DEFAULT AS IDENTITY;
-- [14] (ACCESS EXCLUSIVE) Alter column type order_status_type.code -> text
ALTER TABLE "public"."order_status_type" ALTER COLUMN "code" TYPE TEXT;
-- [15] (ACCESS EXCLUSIVE) Add column order_tag.order_tag_id
ALTER TABLE "public"."order_tag" ADD COLUMN "order_tag_id" BIGINT GENERATED BY DEFAULT AS IDENTITY NOT NULL;
-- [16] (ACCESS EXCLUSIVE) Drop constraint order_tags_pkey on order_tag
ALTER TABLE "public"."order_tag" DROP CONSTRAINT IF EXISTS "order_tags_pkey";
-- [17] (ACCESS EXCLUSIVE) Add PRIMARY KEY pk_czstclug on order_tag
ALTER TABLE "public"."order_tag" ADD CONSTRAINT "pk_czstclug" PRIMARY KEY ("order_tag_id");
-- [18] (ACCESS EXCLUSIVE) Drop default on tag.tag_id
ALTER TABLE "public"."tag" ALTER COLUMN "tag_id" DROP DEFAULT;
-- [19] (ACCESS EXCLUSIVE) Add identity on tag.tag_id
ALTER TABLE "public"."tag" ALTER COLUMN "tag_id" ADD GENERATED BY DEFAULT AS IDENTITY;

-- ===========================================================================
-- PHASE 3 (POST-DDL): Recreate adjusted views, matviews, and routines here
-- ===========================================================================
-- TODO: Verify/recreate view v_open_orders

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_gmxltmzo on order
CREATE INDEX CONCURRENTLY IF NOT EXISTS "ix_gmxltmzo" ON "public"."order" ("status_id");
-- [post-2] (SHARE UPDATE EXCLUSIVE) Create index ix_hltnpbgg on order
CREATE INDEX CONCURRENTLY IF NOT EXISTS "ix_hltnpbgg" ON "public"."order" ("account_id");
-- [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";
-- [post-4] (SHARE UPDATE EXCLUSIVE) Build unique index CONCURRENTLY uq_ebwjdgfd
CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS "uq_ebwjdgfd" ON "public"."order_tag" ("order_id", "tag_id");
-- [post-5] (ACCESS EXCLUSIVE) Attach UNIQUE constraint uq_ebwjdgfd via index
ALTER TABLE "public"."order_tag" ADD CONSTRAINT "uq_ebwjdgfd" UNIQUE USING INDEX "uq_ebwjdgfd";
-- [post-6] (SHARE UPDATE EXCLUSIVE) Create index ix_tedtbckb on order_tag
CREATE INDEX CONCURRENTLY IF NOT EXISTS "ix_tedtbckb" ON "public"."order_tag" ("tag_id");

4. Atomic execution with the external transaction bridge#

Run plan_adoption() once before executing Phase 2 DDL, then execute Phases 1–3 atomically via either psycopg or psql --single-transaction (zero extra Python dependencies) and pass that same ap.plan into finalize_external():

tests/unit/docs/test_doc_guide_snippets.py · assimilate_pure_sql_psycopg
async def assimilate_pure_sql(
    dsn: str,
    app: pgm.MigrationApp,
    adoption_map: pgm.AdoptionMap,
    connect_ext: Callable[[str], AbstractAsyncContextManager[_AsyncExtConn]],
    schema: str = "public",
) -> None:
    async with await pg.Pool.connect(dsn, search_path=schema) as pool:
        ap = await pgm.plan_adoption(
            pool,
            app.tables,
            adoption=adoption_map,
            schema=schema,
            version="0001_assimilate",
            name="pure_sql_billing",
        )

    # Phases 1-3: DROP VIEW + pgdorm transactional DDL + recreated VIEW in ONE atomic TX.
    async with connect_ext(dsn) as ext_conn, ext_conn.transaction():
        await ext_conn.execute(f'SET LOCAL search_path TO "{schema}", public')
        await ext_conn.execute("DROP VIEW v_open_orders")
        await pgm.execute_plan_tx(ap.plan, ext_conn.execute)
        await ext_conn.execute(
            """
            CREATE VIEW v_open_orders AS
            SELECT o.order_id, a.email, o.total_eur
            FROM "order" o
            JOIN account a USING (account_id)
            JOIN order_status_type s ON s.order_status_type_id = o.status_id
            WHERE s.code = 'pending'
            """
        )

    # Phase 4: run SyncTypeTable + CONCURRENTLY indexes + UNIQUE attach and record ledger.
    async with await pg.Pool.connect(dsn, search_path=schema) as pool:
        await pgm.finalize_external(
            pool, ap.plan, tables=app.tables, schema=schema, ignore_tables=app.ignore_tables
        )
        drift = await pgm.check_drift(
            pool, schema=schema, tables=app.tables, ignore_tables=app.ignore_tables
        )
        assert drift.in_sync
tests/unit/docs/test_doc_guide_snippets.py · assimilate_pure_sql_psql
async def assimilate_via_psql(
    dsn: str,
    app: pgm.MigrationApp,
    adoption_map: pgm.AdoptionMap,
    schema: str = "public",
) -> None:
    async with await pg.Pool.connect(dsn, search_path=schema) as pool:
        ap = await pgm.plan_adoption(
            pool,
            app.tables,
            adoption=adoption_map,
            schema=schema,
            version="0001_assimilate",
            name="pure_sql_billing",
        )

        tx_sql: list[str] = []

        async def _collect(stmt: str) -> None:
            tx_sql.append(stmt)

        await pgm.execute_plan_tx(ap.plan, _collect)
        script = (
            ";\n".join(
                [
                    f'SET search_path TO "{schema}", public',
                    "DROP VIEW v_open_orders",
                    *tx_sql,
                    """CREATE VIEW v_open_orders AS
                    SELECT o.order_id, a.email, o.total_eur
                    FROM "order" o
                    JOIN account a USING (account_id)
                    JOIN order_status_type s ON s.order_status_type_id = o.status_id
                    WHERE s.code = 'pending'""",
                ]
            )
            + ";\n"
        )

        subprocess.run(
            ["psql", dsn, "-v", "ON_ERROR_STOP=1", "--single-transaction"],
            input=script,
            text=True,
            check=True,
        )

        # Pass the SAME ap.plan into finalize_external() for Phase 4 online steps + ledger.
        await pgm.finalize_external(
            pool, ap.plan, tables=app.tables, schema=schema, ignore_tables=app.ignore_tables
        )