Assimilation — Switching Stacks & Onboarding Existing Databases#
Coming from Pure SQL, SQLAlchemy, SQLModel, Django, Tortoise, Piccolo, or Peewee? Switching stacks usually fails in one of two places: translating your mental model for queries, or migrating an existing production schema without breaking live views, sequences, or indexes.
- Translating your mental model first? Start with the 5-minute Coming From Another ORM? vocabulary map (
Session→Pool,selectinload→split_load,in_→in_any, Alembic →pgdorm.migrate). - Shared database or external SQL contract? Start with Zero-DDL Bind (
pgdorm scaffold --mode bind): it generates typedpgdormmodels that bind directly to your untouched PostgreSQL tables (strict_pk=False, exactpk_order,preserved_constraints, zero renames, zero DDL,plan_migration().ops == ()). - Ready to normalize onto full
pgdormconventions? Use the default Full Assimilation (pgdorm scaffold --mode assimilate): it audits your live catalog, scaffolds compliant Python models plus an exactAdoptionMap, compiles atomic transactional DDL + onlineCONCURRENTLYsteps, coordinates unmanaged views/triggers/routines atomically, and verifies zero drift and zero FK loss.
Info
Built for AI coding agents and DBAs alike. Nobody wants to hand-translate 60 tables and rewrite every view by memory. Every command below supports --json and deterministic 4-phase SQL blueprints so a coding agent can inspect the gap, plan exact renames, wrap view updates in an atomic transaction, and verify check_drift().in_sync == True without guesswork.
Pathway A — Start From Your Framework#
All seven walkthroughs below assimilate the same Billing & Orders domain (order_statuses, accounts, orders, tags, and a many-to-many join table) expressed in each framework's authentic idioms — matching all six peer ORMs from our Benchmarks plus Pure SQL, each opening with a table-aligned side-by-side Before ↔ After comparison. Every audit report, generated Python model file, and compiled SQL plan is captured directly from live PostgreSQL integration tests.
Pure SQL#
Plural tables, BIGSERIAL PKs, composite-PK join table, an unmanaged GIN index, and a live view rewritten atomically via the external transaction bridge.
SQLAlchemy 2#
Mapped classes + secondary Table('order_tags') composite PK + unindexed FKs + alembic_version preserved untouched via --ignore-table.
SQLModel#
INT4 SERIAL PKs, VARCHAR lengths, OrderTagLink composite PK, and alembic_version assimilated into slotted pgdorm models with zero Pydantic import overhead.
Django ORM#
billing_* app-prefixed tables, django_migrations + django_content_type (_type!) isolated safely, existing FK indexes kept, and M2M table normalized.
Tortoise ORM#
INT4 SERIAL PKs, aerich ledger ignored untouched, unindexed FKs indexed online, and keyless M2M table (orders_tags) promoted with a surrogate IDENTITY PK.
Piccolo ORM#
Already-singular tables with zero entity renames, naive TIMESTAMP mapped cleanly to pg.Timestamp, migration ledger ignored, and missing FK indexes added online.
Peewee#
Existing FK indexes preserved untouched, migratehistory ignored, naive DateTimeField mapped to pg.Timestamp, and CompositeKey M2M promoted online.
Agent Playbook (Copy-Paste Protocol)#
Give this 5-step loop to any coding agent (or run it yourself) against a staging copy of your PostgreSQL database:
# 1. Inspect the live catalog (read-only, no --app required).
# Exit 0 = migratable, Exit 3 = blockers present.
# Note: global flags (--dsn, --schema, --ignore-table, --json) precede the subcommand;
# subcommand flags (--type-table, --out, --adoption, --format) follow it.
pgdorm --dsn "$DATABASE_URL" --schema public \
--ignore-table alembic_version --ignore-table django_migrations \
--json audit-schema > audit.json
# 2. Check audit.json:
# - If migratable == false, resolve or isolate every BLOCKER finding first.
# - Inspect type_table_candidates and decide which lookup tables to promote.
# - Inspect unmanaged_objects (views, matviews, triggers, routines, special indexes).
# 3. Scaffold Python models + APP directly from PostgreSQL.
# Repeat the same --ignore-table flags you passed to audit-schema.
#
# Option A — Zero-DDL Bind (shared DBs, external SQL, or phased adoption):
# Generates models bound to your exact existing tables/columns with ZERO DDL
# (plan_migration().ops == () on the live database immediately).
pgdorm --dsn "$DATABASE_URL" --schema public \
--ignore-table alembic_version --ignore-table django_migrations \
scaffold --mode bind --out app/models.py
# Option B — Full Assimilation (default: --mode assimilate):
# Normalizes plural tables, bare id PKs, TypeTables, and missing FK indexes.
# Optional zero-rewrite cleanup flags:
# --modernize Upgrade SERIAL/BIGSERIAL PKs -> IDENTITY and gen_random_uuid() -> uuidv7()
# --surrogate-pk uuidv7 Use UUID DEFAULT uuidv7() (instead of BIGINT IDENTITY) for newly added surrogate PKs
pgdorm --dsn "$DATABASE_URL" --schema public \
--ignore-table alembic_version --ignore-table django_migrations \
scaffold --type-table order_statuses --modernize --out app/models.py
# 4. Preview the exact 4-phase SQL plan + rename impact warnings (read-only).
# Include PYTHONPATH=. when app/models.py is not installed as a package yet.
# (adopt-plan reads ignore_tables directly from ADOPTION_MAP.)
PYTHONPATH=. pgdorm --dsn "$DATABASE_URL" --schema public \
--app app.models:APP adopt-plan \
--adoption app.models:ADOPTION_MAP \
--format sql > assimilation.sql
# 5. Execute and verify BOTH zero drift AND zero pending model diffs:
# - Review every hazard in assimilation.sql first! Never pass blanket
# `allow_destructive=True` blindly: table/column renames and constraint swaps
# require `allow_breaking=True`; only enable `allow_destructive=True` if you
# explicitly intend to drop a table or column.
# - Zero impact warnings? Wrap `ap.plan.ops` in `pgm.Migration(...)` and call
# `pgm.upgrade_schema(pool, (mig,), tables=APP.tables, allow_breaking=True,
# ignore_tables=APP.ignore_tables)`.
# - Views/matviews/triggers reference renamed tables? Call `plan_adoption()` ONCE
# *before* running Phase 2 DDL, wrap Phase 1 (DROP VIEW) +
# `execute_plan_tx(ap.plan, ...)` + Phase 3 (CREATE VIEW) in one atomic external
# transaction (`psycopg` or `psql --single-transaction`), then pass that SAME
# `ap.plan` into `finalize_external(pool, ap.plan, tables=APP.tables, ...)`.
# - Finally assert BOTH zero drift (`drift`) AND zero pending ops (`status`):
PYTHONPATH=. pgdorm --dsn "$DATABASE_URL" --schema public --app app.models:APP drift
PYTHONPATH=. pgdorm --dsn "$DATABASE_URL" --schema public --app app.models:APP status
Warning
Critical invariant for external transactions: Always call plan_adoption(pool, APP.tables, adoption=ADOPTION_MAP, schema=...) once before executing Phase 2 renames, and pass that same ap.plan to finalize_external(). Never re-run plan_adoption() after tables have already been renamed — otherwise Phase 4 post-commit steps (CREATE INDEX CONCURRENTLY, UNIQUE USING INDEX, SyncTypeTable) will be skipped! Always run pgdorm ... status afterward to verify pending_ops == 0 in addition to drift.
Tip
Why pgdorm stays 100% raw-SQL-free even during complex assimilations: pgdorm intentionally exposes no raw SQL execution API (pg.Pool.connect(dsn, search_path=...) only accepts typed queries). When unmanaged views or PL/pgSQL functions need custom SQL adjustments alongside table renames, execute_plan_tx() feeds pgdorm's compiled transactional DDL into your external driver (psycopg or psql --single-transaction), and finalize_external() runs online CONCURRENTLY / VALIDATE / SyncTypeTable steps afterward and records the verified snapshot in _pgdorm. Note that TypeTable code values preserve exact enum seed casing (e.g. 'paid'), so verify WHERE s.code = '...' predicates when recreating views.
Pathway B — Hard Patterns & Deal Breakers (Pure SQL)#
Every framework eventually meets raw PostgreSQL reality: legacy SERIAL sequences, tables whose names already end in _type, GIN and expression indexes, PL/pgSQL triggers and views, native PostgreSQL ENUMs, composite primary keys, and features pgdorm intentionally refuses to guess about. Explore each hard case directly from minimal, live-tested Pure SQL schemas:
Serials, Plurals & Primary Keys#
Rename plural tables and bare id columns to
TypeTables & _type Clashes#
Promote order_statuses into an IntEnum-backed pg.TypeTable while automatically renaming a colliding regular entity table (content_type → content_kind).
Views, Triggers & GIN Indexes#
Protect GIN, expression, and INCLUDE indexes from drops; export live SQL definitions for views, matviews, functions, and triggers; rewrite views atomically.
Native Enums, Timestamps & Defaults#
Bind PostgreSQL ENUMs via CustomType, TIMESTAMP WITHOUT TIME ZONE via pg.Timestamp, declarative column defaults, and online VALIDATE CONSTRAINT for NOT VALID checks.
Composite PKs, Natural Keys & Self-Cycles#
Promote composite-PK join tables and natural-text PKs to surrogate IDENTITY keys with pg.Unique(...), and handle self-referential parent_id foreign keys.
Unsupported Features & Support Matrix#
INHERITS table inheritance, foreign tables (FDW), non-temporal EXCLUDE constraints, multi-dimensional arrays, and composite types — plus the full rule matrix.
Pathway C — Real-World Benchmark Schemas#
Real databases don't look like toy tutorials. Every schema below is audited and tested live against PostgreSQL in CI (tests/integration/migrations/corpora/) — verifying zero-DDL --mode bind (plan_migration().ops == ()) on all four corpora plus full atomic assimilation with zero FK loss where no unmanaged views block renames:
pgbench (TPC-B-Like)#
4 tables, fixed-width character(84) filler columns, keyless pgbench_history. Zero-DDL bind keeps external pgbench SQL compatible while running 1-RTT pipelines.
Derived from TPC-C#
9 tables, ordered 2- and 3-column composite PKs and composite FKs, keyless history. Zero false UNINDEXED_FK findings and atomic 1-tx assimilation with zero FK loss.
Pagila (DVD Rental)#
15 tables, partitioned payment table, native enum, domain, aggregate, triggers, tsvector, text[], and 7 views — audited safely and bound with zero DDL.
Chinook#
11 tables including media_type (_type suffix!), self-FK employee hierarchy, and composite-PK playlist_track — bound with zero DDL and full-assimilated cleanly.
Quick rule check: what changes vs. what stays untouched#
| Category | Assimilation behavior |
|---|---|
| Table & column names | Normalized to singular snake_case (OrderItem ↔ order_item), <table_name>_id PKs, and aligned FKs for automatic JOIN ... USING. |
| Lookup tables | Regular pg.Table by default; pass --type-table <table> to promote to an Enum-backed pg.TypeTable (*_type). Regular tables ending in _type auto-rename (content_type → content_kind). |
| Serials, UUIDs & defaults | Conservative by default (SERIAL/BIGSERIAL preserved via pg.default_expr(...), gen_random_uuid() kept). Pass --modernize for zero-rewrite metadata upgrades (SERIAL → IDENTITY + sync_identity_from_max(), legacy UUID PK defaults → pg.uuidv7()), and --surrogate-pk uuidv7 to emit UUID DEFAULT uuidv7() on newly added surrogate PKs. |
Missing FK indexes & NOT VALID constraints |
Auto-planned online (CREATE INDEX CONCURRENTLY, VALIDATE CONSTRAINT) in Phase 4 without blocking reads/writes. |
| Legacy migration tables | Left completely untouched via --ignore-table / MigrationApp(ignore_tables=...) (alembic_version, django_migrations, django_content_type). |
Views, matviews, triggers, routines, GIN/GiST/expression/INCLUDE indexes |
Unmanaged — never dropped, altered, or versioned in _pgdorm. Live SQL definitions are exported in audit-schema --json, and impact warnings flag every rename dependency. |
Deal breakers (INHERITS, FDW, EXCLUDE, multi-dim arrays, composite types) |
Hard BLOCKER findings (migratable=false, exit code 3) — see Deal Breakers & Support Matrix. |
← PreviousChapter 8 · Buying the Building Next DoorChapter 8 · Audit, Scaffold & AdoptionMap