Assimilating Peewee#
← Assimilation hub · Live test fixture: frameworks/07_peewee/
Peewee (peewee-migrate) PostgreSQL databases share four distinctive traits that make assimilation fast and predictable:
- Auto-indexed foreign keys: Peewee creates a B-tree index on every
ForeignKeyFieldby default (order_account_id,order_status_id,ordertag_order_id,ordertag_tag_id).pgdormdetects and keeps every existing FK index untouched — zero redundant index builds in Phase 4! - Migration ledger (
migratehistory): Pass--ignore-table migratehistorysopeewee-migrate's history table remains untouched. - Lowercase concatenated table names &
CompositeKeyjoin tables: Peewee defaults to lowercase class names (orderstatus,ordertag) andpw.CompositeKey("order", "tag")on junction models.pgdormpromotesordertagto a surrogateordertag_id IDENTITYPK with an online 2-phaseUNIQUE (order_id, tag_id)constraint — or pass a customAdoptionMapif you also want to renameordertag→order_tagandorderstatus→order_status_typein the same cutover. - Naive
DateTimeField(TIMESTAMP WITHOUT TIME ZONE) &INT4 SERIALAutoField: Preserved cleanly viapg.Timestampandpg.Int4+pg.default_expr("nextval(...)")with zero table rewrites.
1. Before & After — Table-by-Table Schema Comparison#
Run pgdorm scaffold while ignoring migratehistory:
pgdorm --dsn "$DATABASE_URL" --ignore-table migratehistory \
scaffold --type-table orderstatus --out app/models.py
Every original Peewee Model lines up directly beside its scaffolded pgdorm class below:
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)
total_eur: pg.Col[Decimal] = pg.col(precision=10, scale=2, default=Decimal('0.00'))
placed_at: pg.Col[pg.Timestamp] = pg.col(default=pg.now())
class Ordertag(pg.Table):
ordertag_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),
)
Left completely untouched via ignore_tables (migratehistory). Never audited, renamed, or dropped by pgdorm.migrate — even when a legacy table name ends in _type.
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):
orderstatus_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[pg.Timestamp] = 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)
total_eur: pg.Col[Decimal] = pg.col(precision=10, scale=2, default=Decimal('0.00'))
placed_at: pg.Col[pg.Timestamp] = 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 Ordertag(pg.Table):
ordertag_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={
'account': pgm.TableMapping(target='account', columns={'id': 'account_id'}, pk_strategy=pgm.enums.PkStrategy.RENAME, migrate_serial_to_identity=True),
'order': pgm.TableMapping(target='order', columns={'id': 'order_id'}, pk_strategy=pgm.enums.PkStrategy.RENAME, migrate_serial_to_identity=True),
'orderstatus': pgm.TableMapping(target='orderstatus_type', columns={'id': 'orderstatus_type_id'}, as_type_table=True, pk_strategy=pgm.enums.PkStrategy.RENAME),
'ordertag': pgm.TableMapping(target='ordertag', pk_strategy=pgm.enums.PkStrategy.ADD_SURROGATE),
'tag': pgm.TableMapping(target='tag', columns={'id': 'tag_id'}, pk_strategy=pgm.enums.PkStrategy.RENAME, migrate_serial_to_identity=True),
},
ignore_tables=frozenset({'migratehistory'}),
)
APP = pgm.MigrationApp(tables=(OrderstatusType, Account, Order, Tag, Ordertag), ignore_tables=frozenset({'migratehistory'}))
import peewee as pw
db = pw.PostgresqlDatabase(None)
class BaseModel(pw.Model):
class Meta:
database = db
class OrderStatus(BaseModel):
code = pw.CharField(max_length=32, unique=True)
class Meta:
table_name = "orderstatus"
class Account(BaseModel):
email = pw.CharField(max_length=120, unique=True)
is_active = pw.BooleanField(default=True)
created_at = pw.DateTimeField()
class Meta:
table_name = "account"
class Tag(BaseModel):
name = pw.CharField(max_length=64, unique=True)
class Meta:
table_name = "tag"
class Order(BaseModel):
account = pw.ForeignKeyField(Account, backref="orders", on_delete="CASCADE")
status = pw.ForeignKeyField(OrderStatus, backref="orders")
total_eur = pw.DecimalField(max_digits=10, decimal_places=2, default=0)
placed_at = pw.DateTimeField()
class Meta:
table_name = "order"
class OrderTag(BaseModel):
order = pw.ForeignKeyField(Order, on_delete="CASCADE")
tag = pw.ForeignKeyField(Tag, on_delete="CASCADE")
class Meta:
table_name = "ordertag"
primary_key = pw.CompositeKey("order", "tag")
CREATE TABLE migratehistory (
id SERIAL NOT NULL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
migrated_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT now()
);
CREATE TABLE orderstatus (
id SERIAL NOT NULL PRIMARY KEY,
code VARCHAR(32) NOT NULL UNIQUE
);
CREATE TABLE account (
id SERIAL NOT NULL PRIMARY KEY,
email VARCHAR(120) NOT NULL UNIQUE,
is_active BOOLEAN NOT NULL DEFAULT true,
created_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT now()
);
CREATE TABLE tag (
id SERIAL NOT NULL PRIMARY KEY,
name VARCHAR(64) NOT NULL UNIQUE
);
CREATE TABLE "order" (
id SERIAL NOT NULL PRIMARY KEY,
account_id INTEGER NOT NULL REFERENCES account(id) ON DELETE CASCADE,
status_id INTEGER NOT NULL REFERENCES orderstatus(id),
total_eur NUMERIC(10, 2) NOT NULL DEFAULT 0.00,
placed_at TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT now()
);
CREATE INDEX order_account_id ON "order" (account_id);
CREATE INDEX order_status_id ON "order" (status_id);
CREATE TABLE ordertag (
order_id INTEGER NOT NULL REFERENCES "order"(id) ON DELETE CASCADE,
tag_id INTEGER NOT NULL REFERENCES tag(id) ON DELETE CASCADE,
PRIMARY KEY (order_id, tag_id)
);
CREATE INDEX ordertag_order_id ON ordertag (order_id);
CREATE INDEX ordertag_tag_id ON ordertag (tag_id);
INSERT INTO migratehistory (name) VALUES ('001_initial');
INSERT INTO orderstatus (id, code) VALUES (1, 'pending'), (2, 'paid'), (3, 'cancelled');
INSERT INTO account (email) VALUES ('[email protected]');
INSERT INTO tag (name) VALUES ('sync');
INSERT INTO "order" (account_id, status_id, total_eur) VALUES (1, 2, 88.50);
INSERT INTO ordertag (order_id, tag_id) VALUES (1, 1);
2. Live catalog audit#
Notice zero UNINDEXED_FK findings because Peewee indexed every ForeignKeyField automatically.
- Table 'account' PK is 'id' instead of 'account_id'.
- Table 'order' PK is 'id' instead of 'order_id'.
- Table 'orderstatus' PK is 'id' instead of 'orderstatus_id'.
- Table 'ordertag' uses composite PK (order_id, tag_id).
- Table 'tag' PK is 'id' instead of 'tag_id'.
- Column account.id uses owned SERIAL sequence default (nextval('account_id_seq'::regclass)).
- Column order.id uses owned SERIAL sequence default (nextval('order_id_seq'::regclass)).
- Column orderstatus.id uses owned SERIAL sequence default (nextval('orderstatus_id_seq'::regclass)).
- Column tag.id uses owned SERIAL sequence default (nextval('tag_id_seq'::regclass)).
- Table 'account' looks like a lookup table (Single integer PK + unique character varying(120)
email, referenced by order.) - Table 'orderstatus' looks like a lookup table (Single integer PK + unique character varying(32)
code, referenced by order.) - Table 'tag' looks like a lookup table (Single integer PK + unique character varying(64)
name, referenced by ordertag.) - Column account.created_at uses TIMESTAMP WITHOUT TIME ZONE.
- Column order.placed_at uses TIMESTAMP WITHOUT TIME ZONE.
Inspect raw machine-readable audit JSON (tests/integration/migrations/onboarding/frameworks/07_peewee/captured/audit.json)
{
"counts": {
"blocker": 0,
"info": 9,
"migration_required": 5,
"unmanaged": 0
},
"findings": [
{
"auto_fixable": true,
"category": "primary_key",
"code": "PK_NAME_MISMATCH",
"doc_anchor": "primary-keys-and-serials",
"message": "Table 'account' PK is 'id' instead of 'account_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": "account"
},
{
"auto_fixable": true,
"category": "primary_key",
"code": "PK_NAME_MISMATCH",
"doc_anchor": "primary-keys-and-serials",
"message": "Table 'order' PK is 'id' instead of 'order_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"
},
{
"auto_fixable": true,
"category": "primary_key",
"code": "PK_NAME_MISMATCH",
"doc_anchor": "primary-keys-and-serials",
"message": "Table 'orderstatus' PK is 'id' instead of 'orderstatus_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": "orderstatus"
},
{
"auto_fixable": true,
"category": "primary_key",
"code": "PK_COMPOSITE",
"doc_anchor": "primary-keys-and-serials",
"message": "Table 'ordertag' 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": "ordertag"
},
{
"auto_fixable": true,
"category": "primary_key",
"code": "PK_NAME_MISMATCH",
"doc_anchor": "primary-keys-and-serials",
"message": "Table 'tag' PK is 'id' instead of 'tag_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": "tag"
},
{
"auto_fixable": true,
"category": "primary_key",
"code": "SERIAL_COLUMN",
"doc_anchor": "primary-keys-and-serials",
"message": "Column account.id uses owned SERIAL sequence default (nextval('account_id_seq'::regclass)).",
"object_kind": "column",
"object_name": "id",
"severity": "info",
"suggestion": "Assimilate upgrades SERIAL PKs to IDENTITY; bind uses `server_managed=True`.",
"table": "account"
},
{
"auto_fixable": true,
"category": "primary_key",
"code": "SERIAL_COLUMN",
"doc_anchor": "primary-keys-and-serials",
"message": "Column order.id uses owned SERIAL sequence default (nextval('order_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"
},
{
"auto_fixable": true,
"category": "primary_key",
"code": "SERIAL_COLUMN",
"doc_anchor": "primary-keys-and-serials",
"message": "Column orderstatus.id uses owned SERIAL sequence default (nextval('orderstatus_id_seq'::regclass)).",
"object_kind": "column",
"object_name": "id",
"severity": "info",
"suggestion": "Assimilate upgrades SERIAL PKs to IDENTITY; bind uses `server_managed=True`.",
"table": "orderstatus"
},
{
"auto_fixable": true,
"category": "primary_key",
"code": "SERIAL_COLUMN",
"doc_anchor": "primary-keys-and-serials",
"message": "Column tag.id uses owned SERIAL sequence default (nextval('tag_id_seq'::regclass)).",
"object_kind": "column",
"object_name": "id",
"severity": "info",
"suggestion": "Assimilate upgrades SERIAL PKs to IDENTITY; bind uses `server_managed=True`.",
"table": "tag"
},
{
"auto_fixable": true,
"category": "type_table",
"code": "TYPE_TABLE_CANDIDATE",
"doc_anchor": "type-table-namespace",
"message": "Table 'account' looks like a lookup table (Single integer PK + unique character varying(120) `email`, referenced by order.)",
"object_kind": "table",
"object_name": "account",
"severity": "info",
"suggestion": "Review candidate; pass `--type-table <table>` or `as_type_table=True` to promote.",
"table": "account"
},
{
"auto_fixable": true,
"category": "type_table",
"code": "TYPE_TABLE_CANDIDATE",
"doc_anchor": "type-table-namespace",
"message": "Table 'orderstatus' looks like a lookup table (Single integer PK + unique character varying(32) `code`, referenced by order.)",
"object_kind": "table",
"object_name": "orderstatus",
"severity": "info",
"suggestion": "Review candidate; pass `--type-table <table>` or `as_type_table=True` to promote.",
"table": "orderstatus"
},
{
"auto_fixable": true,
"category": "type_table",
"code": "TYPE_TABLE_CANDIDATE",
"doc_anchor": "type-table-namespace",
"message": "Table 'tag' looks like a lookup table (Single integer PK + unique character varying(64) `name`, referenced by ordertag.)",
"object_kind": "table",
"object_name": "tag",
"severity": "info",
"suggestion": "Review candidate; pass `--type-table <table>` or `as_type_table=True` to promote.",
"table": "tag"
},
{
"auto_fixable": false,
"category": "types",
"code": "TIMESTAMP_WITHOUT_TZ",
"doc_anchor": "column-types",
"message": "Column account.created_at uses TIMESTAMP WITHOUT TIME ZONE.",
"object_kind": "column",
"object_name": "created_at",
"severity": "info",
"suggestion": "Scaffold emits `pg.Col[pg.Timestamp]` automatically.",
"table": "account"
},
{
"auto_fixable": false,
"category": "types",
"code": "TIMESTAMP_WITHOUT_TZ",
"doc_anchor": "column-types",
"message": "Column order.placed_at uses TIMESTAMP WITHOUT TIME ZONE.",
"object_kind": "column",
"object_name": "placed_at",
"severity": "info",
"suggestion": "Scaffold emits `pg.Col[pg.Timestamp]` automatically.",
"table": "order"
}
],
"ignored_tables": [
"migratehistory"
],
"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 order.",
"referencing_tables": [
"order"
],
"table": "account"
},
{
"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 order.",
"referencing_tables": [
"order"
],
"table": "orderstatus"
},
{
"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 ordertag.",
"referencing_tables": [
"ordertag"
],
"table": "tag"
}
],
"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 all FK indexes already exist, Phase 4 only syncs orderstatus_type seeds and attaches the online 2-phase UNIQUE USING INDEX constraint on ordertag(order_id, tag_id).
-- pgdorm Assimilation Plan: 0001_assimilate (07_peewee)
-- Checksum: de35d595e7d384cf10035968524bb881fd5cdee51062721574b5cd5199f8f5be
-- Ignored tables: migratehistory
-- 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 orderstatus -> orderstatus_type
ALTER TABLE "public"."orderstatus" RENAME TO "orderstatus_type";
-- [2] (ACCESS EXCLUSIVE) Rename column account.id -> account_id
ALTER TABLE "public"."account" RENAME COLUMN "id" TO "account_id";
-- [3] (ACCESS EXCLUSIVE) Rename column order.id -> order_id
ALTER TABLE "public"."order" RENAME COLUMN "id" TO "order_id";
-- [4] (ACCESS EXCLUSIVE) Rename column orderstatus_type.id -> orderstatus_type_id
ALTER TABLE "public"."orderstatus_type" RENAME COLUMN "id" TO "orderstatus_type_id";
-- [5] (ACCESS EXCLUSIVE) Rename column tag.id -> tag_id
ALTER TABLE "public"."tag" RENAME COLUMN "id" TO "tag_id";
-- [6] (ACCESS EXCLUSIVE) Drop default on account.account_id
ALTER TABLE "public"."account" ALTER COLUMN "account_id" DROP DEFAULT;
-- [7] (ACCESS EXCLUSIVE) Add identity on account.account_id
ALTER TABLE "public"."account" ALTER COLUMN "account_id" ADD GENERATED BY DEFAULT AS IDENTITY;
-- [8] (ACCESS EXCLUSIVE) Drop default on order.order_id
ALTER TABLE "public"."order" ALTER COLUMN "order_id" DROP DEFAULT;
-- [9] (ACCESS EXCLUSIVE) Add identity on order.order_id
ALTER TABLE "public"."order" ALTER COLUMN "order_id" ADD GENERATED BY DEFAULT AS IDENTITY;
-- [10] (ACCESS EXCLUSIVE) Drop default on orderstatus_type.orderstatus_type_id
ALTER TABLE "public"."orderstatus_type" ALTER COLUMN "orderstatus_type_id" DROP DEFAULT;
-- [11] (ACCESS EXCLUSIVE) Alter column type orderstatus_type.code -> text
ALTER TABLE "public"."orderstatus_type" ALTER COLUMN "code" TYPE TEXT;
-- [12] (ACCESS EXCLUSIVE) Add column ordertag.ordertag_id
ALTER TABLE "public"."ordertag" ADD COLUMN "ordertag_id" BIGINT GENERATED BY DEFAULT AS IDENTITY NOT NULL;
-- [13] (ACCESS EXCLUSIVE) Drop constraint ordertag_pkey on ordertag
ALTER TABLE "public"."ordertag" DROP CONSTRAINT IF EXISTS "ordertag_pkey";
-- [14] (ACCESS EXCLUSIVE) Add PRIMARY KEY pk_nxvukfeg on ordertag
ALTER TABLE "public"."ordertag" ADD CONSTRAINT "pk_nxvukfeg" PRIMARY KEY ("ordertag_id");
-- [15] (ACCESS EXCLUSIVE) Drop default on tag.tag_id
ALTER TABLE "public"."tag" ALTER COLUMN "tag_id" DROP DEFAULT;
-- [16] (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] (NONE) Sync TypeTable seeds for orderstatus_type
-- (Parameterized query executed automatically by pgm.finalize_external())
INSERT INTO "public"."orderstatus_type" ("orderstatus_type_id", "code")
VALUES ($1, $2), ($3, $4), ($5, $6)
ON CONFLICT ("orderstatus_type_id") DO UPDATE SET "code" = EXCLUDED."code";
-- [post-2] (SHARE UPDATE EXCLUSIVE) Build unique index CONCURRENTLY uq_nhgroisa
CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS "uq_nhgroisa" ON "public"."ordertag" ("order_id", "tag_id");
-- [post-3] (ACCESS EXCLUSIVE) Attach UNIQUE constraint uq_nhgroisa via index
ALTER TABLE "public"."ordertag" ADD CONSTRAINT "uq_nhgroisa" UNIQUE USING INDEX "uq_nhgroisa";
-- [post-4] (SHARE UPDATE EXCLUSIVE) Drop index ordertag_order_id
DROP INDEX CONCURRENTLY IF EXISTS "public"."ordertag_order_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.