Assimilating SQLAlchemy 2#
← Assimilation hub · Live test fixture: frameworks/02_sqlalchemy/
SQLAlchemy 2 + Alembic projects typically share four recognizable patterns in PostgreSQL:
- An
alembic_versionmetadata table that must stay untouched during cutover (--ignore-table alembic_version). - Plural table names with bare
id BIGSERIALprimary keys andForeignKey(...)columns withoutindex=True(SQLAlchemy does not auto-index foreign keys by default). - Bare secondary association tables (
Table("order_tags", ..., primary_key=True)) using a composite primary key instead of a surrogate key. - Lookup tables (
order_statuses) modeled as ordinary tables withString(32)codes.
1. Before & After — Table-by-Table Schema Comparison#
Run pgdorm scaffold against the live database to emit compliant pgdorm models alongside ADOPTION_MAP and APP while keeping alembic_version untouched:
pgdorm --dsn "$DATABASE_URL" --ignore-table alembic_version \
scaffold --type-table order_statuses --out app/models.py
Every original SQLAlchemy 2 model lines up directly beside its scaffolded pgdorm class below:
class Account(Base):
__tablename__ = "accounts"
id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
email: Mapped[str] = mapped_column(String(120), unique=True, nullable=False)
is_active: Mapped[bool] = mapped_column(Boolean, server_default=text("true"), nullable=False)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now(), nullable=False
)
class Order(Base):
__tablename__ = "orders"
id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
account_id: Mapped[int] = mapped_column(
ForeignKey("accounts.id", ondelete="CASCADE"), nullable=False
)
status_id: Mapped[int] = mapped_column(ForeignKey("order_statuses.id"), nullable=False)
total_eur: Mapped[Decimal] = mapped_column(
Numeric(10, 2), server_default=text("0.00"), nullable=False
)
placed_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now(), nullable=False
)
tags: Mapped[list[Tag]] = relationship(secondary=order_tags)
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'))
placed_at: pg.Col[datetime] = pg.col(default=pg.now())
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),
)
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'))
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),
},
ignore_tables=frozenset({'alembic_version'}),
)
APP = pgm.MigrationApp(tables=(OrderStatusType, Account, Order, Tag, OrderTag), ignore_tables=frozenset({'alembic_version'}))
from datetime import datetime
from decimal import Decimal
from sqlalchemy import (
BigInteger,
Boolean,
Column,
DateTime,
ForeignKey,
Integer,
Numeric,
String,
Table,
func,
text,
)
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship
class Base(DeclarativeBase):
pass
order_tags = Table(
"order_tags",
Base.metadata,
Column("order_id", ForeignKey("orders.id", ondelete="CASCADE"), primary_key=True),
Column("tag_id", ForeignKey("tags.id", ondelete="CASCADE"), primary_key=True),
)
class OrderStatus(Base):
__tablename__ = "order_statuses"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
code: Mapped[str] = mapped_column(String(32), unique=True, nullable=False)
class Account(Base):
__tablename__ = "accounts"
id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
email: Mapped[str] = mapped_column(String(120), unique=True, nullable=False)
is_active: Mapped[bool] = mapped_column(Boolean, server_default=text("true"), nullable=False)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now(), nullable=False
)
class Order(Base):
__tablename__ = "orders"
id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
account_id: Mapped[int] = mapped_column(
ForeignKey("accounts.id", ondelete="CASCADE"), nullable=False
)
status_id: Mapped[int] = mapped_column(ForeignKey("order_statuses.id"), nullable=False)
total_eur: Mapped[Decimal] = mapped_column(
Numeric(10, 2), server_default=text("0.00"), nullable=False
)
placed_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now(), nullable=False
)
tags: Mapped[list[Tag]] = relationship(secondary=order_tags)
class Tag(Base):
__tablename__ = "tags"
id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
name: Mapped[str] = mapped_column(String(64), unique=True, nullable=False)
CREATE TABLE alembic_version (
version_num VARCHAR(32) NOT NULL PRIMARY KEY
);
CREATE TABLE order_statuses (
id INTEGER NOT NULL PRIMARY KEY,
code VARCHAR(32) NOT NULL UNIQUE
);
CREATE TABLE accounts (
id BIGSERIAL NOT NULL 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 NOT NULL 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,
placed_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE tags (
id BIGSERIAL NOT NULL 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)
);
INSERT INTO alembic_version (version_num) VALUES ('20261128_0001');
INSERT INTO order_statuses (id, code) VALUES (1, 'pending'), (2, 'paid'), (3, 'cancelled');
INSERT INTO accounts (email) VALUES ('[email protected]');
INSERT INTO orders (account_id, status_id, total_eur) VALUES (1, 2, 79.00);
INSERT INTO tags (name) VALUES ('annual');
INSERT INTO order_tags (order_id, tag_id) VALUES (1, 1);
2. Live catalog audit#
Pass --ignore-table alembic_version so Alembic's revision history is neither audited nor dropped. audit-schema immediately flags every plural table, bare id PK, BIGSERIAL, unindexed foreign key, composite PK on order_tags, and order_statuses as a TYPE_TABLE_CANDIDATE.
- FK 'order_tags_tag_id_fkey' on order_tags(tag_id) has no covering B-tree index.
- 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.
- Table 'accounts' appears plural; assimilate to singular snake_case.
- Table 'order_statuses' appears plural; assimilate to singular snake_case.
- Table 'order_tags' appears plural; assimilate to singular snake_case.
- Table 'orders' 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 'order_tags' uses composite PK (order_id, tag_id).
- Table 'orders' PK is 'id' instead of 'orders_id'.
- Table 'tags' PK is 'id' instead of 'tags_id'.
- Column accounts.id uses owned SERIAL sequence default (nextval('accounts_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 bigint 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 bigint PK + unique character varying(64)
name, referenced by order_tags.)
Inspect raw machine-readable audit JSON (tests/integration/migrations/onboarding/frameworks/02_sqlalchemy/captured/audit.json)
{
"counts": {
"blocker": 0,
"info": 6,
"migration_required": 13,
"unmanaged": 0
},
"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": 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": [
"alembic_version"
],
"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": [],
"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#
Because no unmanaged views or routines block the renames, this entire plan can be applied straight through pgdorm's online migration runner (upgrade_schema()), automatically creating every missing FK index CONCURRENTLY and promoting order_tag to a surrogate BIGINT GENERATED BY DEFAULT AS IDENTITY PK with UNIQUE (order_id, tag_id).
-- pgdorm Assimilation Plan: 0001_assimilate (02_sqlalchemy)
-- Checksum: 645f82aca4842b19d1cd640957a0afc3b05ccfcd63712b141477327094541412
-- Ignored tables: alembic_version
-- 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 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;
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");
Tip
Post-assimilation ergonomics: Once assimilated, Order.account_id matches Account.account_id, so pg.select(Order, Account).join(Account) automatically emits JOIN "account" USING ("account_id") — and every foreign key is backed by an index verified by JoinLintError.
4. Apply directly with upgrade_schema()#
Because no unmanaged views or routines block the renames, wrap ap.plan.ops in a Migration and apply it online (table/column renames are BREAKING hazards, so allow_breaking=True opts in explicitly):
async def assimilate_sqlalchemy(
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="sqlalchemy_billing",
)
mig = pgm.Migration(
version="0001_assimilate",
name="sqlalchemy_billing",
ops=ap.plan.ops,
)
await pgm.upgrade_schema(
pool,
(mig,),
schema=schema,
tables=app.tables,
online=True,
allow_breaking=True,
allow_destructive=True,
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