Assimilating Tortoise ORM#
← Assimilation hub · Live test fixture: frameworks/05_tortoise/
Tortoise ORM + Aerich projects bring four distinctive PostgreSQL traits that pgdorm handles cleanly without table rewrites:
- Aerich migration ledger (
aerich): Pass--ignore-table aerichso Aerich's JSONB migration history stays completely untouched during cutover. - Keyless many-to-many junction tables (
PK_MISSING): Tortoise'sManyToManyField(..., through="orders_tags")generates a junction table withUNIQUE (order_id, tag_id)and no primary key.pgdormflagsPK_MISSINGand promotesorders_tags→orders_tagwith a backfilledBIGINT GENERATED BY DEFAULT AS IDENTITYPK (orders_tag_id) while keeping the existingUNIQUEconstraint intact. INT4 SERIALprimary keys:fields.IntField(primary_key=True)maps toSERIAL;pgdorm scaffoldpreservespg.Int4+pg.default_expr("nextval(...)")so existing foreign keys stay binary-compatible.- Unindexed foreign keys:
ForeignKeyFielddoes not create a B-tree index unlessdb_index=Trueis set; missing FK indexes are added online viaCREATE INDEX CONCURRENTLYin Phase 4.
1. Before & After — Table-by-Table Schema Comparison#
Run pgdorm scaffold against the live database while isolating aerich:
pgdorm --dsn "$DATABASE_URL" --ignore-table aerich \
scaffold --type-table order_statuses --out app/models.py
Every original Tortoise model (plus the implicit keyless orders_tags M2M table) lines up directly beside its scaffolded pgdorm class below:
class Order(Model):
id = fields.IntField(primary_key=True)
account = fields.ForeignKeyField("models.Account", on_delete=fields.CASCADE)
status = fields.ForeignKeyField("models.OrderStatus", on_delete=fields.RESTRICT)
total_eur = fields.DecimalField(max_digits=10, decimal_places=2, default=0)
placed_at = fields.DatetimeField(auto_now_add=True)
tags = fields.ManyToManyField("models.Tag", through="orders_tags", related_name="orders")
class Meta:
table = "orders"
class Order(pg.Table):
order_id: pg.Col[pg.Int4] = pg.pk(default=pg.identity())
account_id: pg.Col[pg.Int4] = pg.fk(Account, on_delete=pg.enums.OnDelete.CASCADE)
status_id: pg.Col[pg.Int4] = pg.fk(OrderStatusType, on_delete=pg.enums.OnDelete.RESTRICT)
total_eur: pg.Col[Decimal] = pg.col(precision=10, scale=2, default=Decimal('0.00'))
placed_at: pg.Col[datetime] = pg.col(default=pg.now())
class OrdersTag(pg.Table):
orders_tag_id: pg.Col[int] = pg.pk(default=pg.identity())
order_id: pg.Col[pg.Int4] = pg.fk(Order, on_delete=pg.enums.OnDelete.CASCADE)
tag_id: pg.Col[pg.Int4] = 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),
)
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[pg.Int4] = 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[pg.Int4] = pg.pk(default=pg.identity())
account_id: pg.Col[pg.Int4] = pg.fk(Account, on_delete=pg.enums.OnDelete.CASCADE)
status_id: pg.Col[pg.Int4] = pg.fk(OrderStatusType, on_delete=pg.enums.OnDelete.RESTRICT)
total_eur: pg.Col[Decimal] = pg.col(precision=10, scale=2, default=Decimal('0.00'))
placed_at: pg.Col[datetime] = pg.col(default=pg.now())
class Tag(pg.Table):
tag_id: pg.Col[pg.Int4] = pg.pk(default=pg.identity())
name: pg.Col[str] = pg.col(max_len=64, unique=True)
class OrdersTag(pg.Table):
orders_tag_id: pg.Col[int] = pg.pk(default=pg.identity())
order_id: pg.Col[pg.Int4] = pg.fk(Order, on_delete=pg.enums.OnDelete.CASCADE)
tag_id: pg.Col[pg.Int4] = 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),
'orders': pgm.TableMapping(target='order', columns={'id': 'order_id'}, pk_strategy=pgm.enums.PkStrategy.RENAME, migrate_serial_to_identity=True),
'orders_tags': pgm.TableMapping(target='orders_tag', pk_strategy=pgm.enums.PkStrategy.ADD_SURROGATE),
'tags': pgm.TableMapping(target='tag', columns={'id': 'tag_id'}, pk_strategy=pgm.enums.PkStrategy.RENAME, migrate_serial_to_identity=True),
},
ignore_tables=frozenset({'aerich'}),
)
APP = pgm.MigrationApp(tables=(OrderStatusType, Account, Order, Tag, OrdersTag), ignore_tables=frozenset({'aerich'}))
from tortoise import fields
from tortoise.models import Model
class OrderStatus(Model):
id = fields.IntField(primary_key=True)
code = fields.CharField(max_length=32, unique=True)
class Meta:
table = "order_statuses"
class Account(Model):
id = fields.IntField(primary_key=True)
email = fields.CharField(max_length=120, unique=True)
is_active = fields.BooleanField(default=True)
created_at = fields.DatetimeField(auto_now_add=True)
class Meta:
table = "accounts"
class Tag(Model):
id = fields.IntField(primary_key=True)
name = fields.CharField(max_length=64, unique=True)
class Meta:
table = "tags"
class Order(Model):
id = fields.IntField(primary_key=True)
account = fields.ForeignKeyField("models.Account", on_delete=fields.CASCADE)
status = fields.ForeignKeyField("models.OrderStatus", on_delete=fields.RESTRICT)
total_eur = fields.DecimalField(max_digits=10, decimal_places=2, default=0)
placed_at = fields.DatetimeField(auto_now_add=True)
tags = fields.ManyToManyField("models.Tag", through="orders_tags", related_name="orders")
class Meta:
table = "orders"
CREATE TABLE aerich (
id SERIAL NOT NULL PRIMARY KEY,
version VARCHAR(255) NOT NULL,
app VARCHAR(100) NOT NULL,
content JSONB NOT NULL
);
CREATE TABLE order_statuses (
id SERIAL NOT NULL PRIMARY KEY,
code VARCHAR(32) NOT NULL UNIQUE
);
CREATE TABLE accounts (
id SERIAL NOT NULL PRIMARY KEY,
email VARCHAR(120) NOT NULL UNIQUE,
is_active BOOLEAN NOT NULL DEFAULT true,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE tags (
id SERIAL NOT NULL PRIMARY KEY,
name VARCHAR(64) NOT NULL UNIQUE
);
CREATE TABLE orders (
id SERIAL NOT NULL PRIMARY KEY,
account_id INTEGER NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
status_id INTEGER NOT NULL REFERENCES order_statuses(id) ON DELETE RESTRICT,
total_eur NUMERIC(10, 2) NOT NULL DEFAULT 0.00,
placed_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE orders_tags (
order_id INTEGER NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
tag_id INTEGER NOT NULL REFERENCES tags(id) ON DELETE CASCADE,
UNIQUE (order_id, tag_id)
);
INSERT INTO aerich (version, app, content) VALUES ('0_20261128_init.py', 'models', '{}'::jsonb);
INSERT INTO order_statuses (id, code) VALUES (1, 'pending'), (2, 'paid'), (3, 'cancelled');
INSERT INTO accounts (email) VALUES ('[email protected]');
INSERT INTO tags (name) VALUES ('async');
INSERT INTO orders (account_id, status_id, total_eur) VALUES (1, 2, 149.00);
INSERT INTO orders_tags (order_id, tag_id) VALUES (1, 1);
2. Live catalog audit#
Notice PK_MISSING on orders_tags alongside plural table names, SERIAL defaults, and unindexed foreign keys — all resolved automatically with zero blockers.
- FK 'orders_account_id_fkey' on orders(account_id) has no covering B-tree index.
- FK 'orders_status_id_fkey' on orders(status_id) has no covering B-tree index.
- FK 'orders_tags_tag_id_fkey' on orders_tags(tag_id) has no covering B-tree index.
- Table 'accounts' appears plural; assimilate to singular snake_case.
- Table 'order_statuses' appears plural; assimilate to singular snake_case.
- Table 'orders' appears plural; assimilate to singular snake_case.
- Table 'orders_tags' appears plural; assimilate to singular snake_case.
- Table 'tags' appears plural; assimilate to singular snake_case.
- Table 'accounts' PK is 'id' instead of 'accounts_id'.
- Table 'order_statuses' PK is 'id' instead of 'order_statuses_id'.
- Table 'orders' PK is 'id' instead of 'orders_id'.
- Table 'orders_tags' has no primary key.
- Table 'tags' PK is 'id' instead of 'tags_id'.
- Column accounts.id uses owned SERIAL sequence default (nextval('accounts_id_seq'::regclass)).
- Column order_statuses.id uses owned SERIAL sequence default (nextval('order_statuses_id_seq'::regclass)).
- Column orders.id uses owned SERIAL sequence default (nextval('orders_id_seq'::regclass)).
- Column tags.id uses owned SERIAL sequence default (nextval('tags_id_seq'::regclass)).
- Table 'accounts' looks like a lookup table (Single integer PK + unique character varying(120)
email, referenced by orders.) - Table 'order_statuses' looks like a lookup table (Single integer PK + unique character varying(32)
code, referenced by orders.) - Table 'tags' looks like a lookup table (Single integer PK + unique character varying(64)
name, referenced by orders_tags.)
Inspect raw machine-readable audit JSON (tests/integration/migrations/onboarding/frameworks/05_tortoise/captured/audit.json)
{
"counts": {
"blocker": 0,
"info": 7,
"migration_required": 13,
"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": "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": "indexes",
"code": "UNINDEXED_FK",
"doc_anchor": "constraints-and-indexes",
"message": "FK 'orders_tags_tag_id_fkey' on orders_tags(tag_id) has no covering B-tree index.",
"object_kind": "foreign_key",
"object_name": "orders_tags_tag_id_fkey",
"severity": "migration_required",
"suggestion": "Assimilation plans online `CREATE INDEX CONCURRENTLY` for uncovered FKs.",
"table": "orders_tags"
},
{
"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 '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 'orders_tags' appears plural; assimilate to singular snake_case.",
"object_kind": "table",
"object_name": "orders_tags",
"severity": "migration_required",
"suggestion": "Rename table to singular snake_case via AdoptionMap.",
"table": "orders_tags"
},
{
"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_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_MISSING",
"doc_anchor": "primary-keys-and-serials",
"message": "Table 'orders_tags' has no primary key.",
"object_kind": "primary_key",
"object_name": "orders_tags",
"severity": "migration_required",
"suggestion": "Add `<table_name>_id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY`.",
"table": "orders_tags"
},
{
"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": 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 order_statuses.id uses owned SERIAL sequence default (nextval('order_statuses_id_seq'::regclass)).",
"object_kind": "column",
"object_name": "id",
"severity": "info",
"suggestion": "Assimilate upgrades SERIAL PKs to IDENTITY; bind uses `server_managed=True`.",
"table": "order_statuses"
},
{
"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 integer 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 integer PK + unique character varying(64) `name`, referenced by orders_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": [
"aerich"
],
"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": "integer",
"reason": "Single integer 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": "integer",
"reason": "Single integer PK + unique character varying(64) `name`, referenced by orders_tags.",
"referencing_tables": [
"orders_tags"
],
"table": "tags"
}
],
"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"
}
]
}
3. Compiled assimilation SQL#
Notice that orders_tag receives orders_tag_id + PRIMARY KEY ("orders_tag_id") in Phase 2 without needing to drop or rebuild its existing UNIQUE (order_id, tag_id) constraint, and all missing FK indexes build online CONCURRENTLY in Phase 4.
-- pgdorm Assimilation Plan: 0001_assimilate (05_tortoise)
-- Checksum: 7bd8bd293a7ae906cd5b9012a2227956e63840b13334cd069771157870973f2a
-- Ignored tables: aerich
-- 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 order_statuses -> order_status_type
ALTER TABLE "public"."order_statuses" RENAME TO "order_status_type";
-- [3] (ACCESS EXCLUSIVE) Rename table orders -> order
ALTER TABLE "public"."orders" RENAME TO "order";
-- [4] (ACCESS EXCLUSIVE) Rename table orders_tags -> orders_tag
ALTER TABLE "public"."orders_tags" RENAME TO "orders_tag";
-- [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) Drop default on order_status_type.order_status_type_id
ALTER TABLE "public"."order_status_type" ALTER COLUMN "order_status_type_id" DROP DEFAULT;
-- [15] (ACCESS EXCLUSIVE) Alter column type order_status_type.code -> text
ALTER TABLE "public"."order_status_type" ALTER COLUMN "code" TYPE TEXT;
-- [16] (ACCESS EXCLUSIVE) Add column orders_tag.orders_tag_id
ALTER TABLE "public"."orders_tag" ADD COLUMN "orders_tag_id" BIGINT GENERATED BY DEFAULT AS IDENTITY NOT NULL;
-- [17] (ACCESS EXCLUSIVE) Add PRIMARY KEY pk_ulybwing on orders_tag
ALTER TABLE "public"."orders_tag" ADD CONSTRAINT "pk_ulybwing" PRIMARY KEY ("orders_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;
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) Create index ix_lecybvts on orders_tag
CREATE INDEX CONCURRENTLY IF NOT EXISTS "ix_lecybvts" ON "public"."orders_tag" ("tag_id");
4. Apply directly with upgrade_schema()#
With zero unmanaged view dependencies, apply ap.plan.ops via pgm.Migration + pgm.upgrade_schema(..., allow_breaking=True, allow_destructive=True, ignore_tables=APP.ignore_tables) (same pattern as SQLAlchemy Step 4), then verify zero drift with pgdorm ... status.