9.7 Connections, transactions, and migrations
BaseDatabaseSchemaEditor and table rewrites
How does BaseDatabaseSchemaEditor turn abstract migration operations into backend-specific DDL, and why does altering one column on SQLite recreate the entire table?
Every abstract operation inside a migration file (CreateModel, AddField, AlterField, AddConstraint) exposes two completely separate methods: "state_forwards" mutates ProjectState in memory, while "database_forwards" delegates DDL generation to BaseDatabaseSchemaEditor. Orchestrating both halves against the live database is the job of MigrationExecutor.
How MigrationExecutor.apply_migration drives DDL and "django_migrations"
Open MigrationExecutor and MigrationExecutor. First, MigrationExecutor ensures the "django_migrations" table exists via MigrationRecorder — using a floating model defined on MigrationRecorder inside a private Apps() instance! Next it computes the exact (Migration, backwards) plan via MigrationExecutor (refusing mixed forward/backward plans with InvalidMigrationPlan), replays applied migrations into a starting ProjectState, renders "state.apps", and runs each migration inside a schema_editor context manager:
with self.connection.schema_editor(atomic=migration.atomic) as schema_editor:
state = migration.apply(state, schema_editor)
if not schema_editor.deferred_sql:
self.record_migration(migration.app_label, migration.name)
migration_recorded = True
Look closely at two details inside BaseDatabaseSchemaEditor and BaseDatabaseSchemaEditor:
- Transactional DDL (
atomic_migration):BaseDatabaseSchemaEditorcomputes.__init__ "self. On PostgreSQL and SQLite, the entire migration (every DDL statement, plus.atomic_migration = self .connection .features .can_rollback_ddl and atomic" deferred_sqllike foreign-key constraints and indexes, plus the"INSERT INTO django_migrations"row whendeferred_sqlis empty!) runs inside oneatomictransaction. On MySQL and Oracle (can_rollback_ddl = False),atomic_migrationisFalse, andBaseDatabaseSchemaEditoreven raises.execute TransactionManagementErrorif you try to run DDL inside a manualatomicblock! - Deferred SQL (
deferred_sql): Creating foreign-key constraints and secondary indexes is often appended to"selfrather than executed mid-operation, then flushed all at once inside.deferred_sql" BaseDatabaseSchemaEditorbefore the transaction commits — ensuring mutually-referencing tables exist before their constraints bind, and ensuring.__exit__ "MigrationRecorderruns after deferred constraints succeed (lines 258–262 of.record_applied" executor.py).
Why altering one column on SQLite rebuilds the entire table
On PostgreSQL, widening "Story.headline" from max_length=160 to max_length=200 executes a single in-place statement from BaseDatabaseSchemaEditor: "ALTER TABLE newsroom_story ALTER COLUMN headline TYPE varchar(200)".
SQLite’s "ALTER TABLE" grammar has no "ALTER COLUMN" clause, cannot add "NOT NULL" or "UNIQUE" columns with arbitrary defaults, and cannot drop indexed or foreign-key columns directly. So Django’s SQLite DatabaseSchemaEditor falls back to DatabaseSchemaEditor — executing the full five-stage rebuild recommended by SQLite’s own documentation while foreign-key checks are temporarily suspended (DatabaseSchemaEditor disables "PRAGMA foreign_keys", and __exit__ verifies integrity with "PRAGMA foreign_key_check" before re-enabling them!).
ch09-database and ch09-bench. Even on an empty table (0 rows), _remake_table costs 5.5x as much as ADD COLUMN; by 5,000–10,000 rows, copying every row and rebuilding three foreign-key indexes climbs to 16.2–17.3 ms (11.8x–13.1x slower).Watch the exact SQL emitted by BaseDatabaseWrapper (BaseDatabaseWrapper, called with collect_sql=True) on "desk/"'s "Story" model — comparing a nullable "add_field" (1 statement) against widening "headline" via "alter_field" (7 statements via _remake_table):
7. BaseDatabaseSchemaEditor: SQLite ADD COLUMN vs _remake_table
sqlite_add_nullable_field (1 statements):
ALTER TABLE "newsroom_story" ADD COLUMN "kicker" varchar(80) NULL;
sqlite_alter_field_remake_table (7 statements):
CREATE TABLE "new__newsroom_story" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "headline" varchar(200) NOT NULL, "slug" varchar(160) NOT NULL UNIQUE, "body" text NOT NULL, "priority" smallint unsigned NOT NULL CHECK ("priority" >= 0), "status" varchar(16) NOT NULL, "published_at" datetime NULL, "desk_id" bigint NOT NULL REFERENCES "newsroom_desk" ("id") DEFERRABLE INITIALLY DEFERRED, "reporter_id" bigint NOT NULL REFERENCES "newsroom_reporter" ("id") DEFERRABLE INITIALLY DEFERRED, "edition_id" bigint NOT NULL REFERENCES "newsroom_edition" ("id") DEFERRABLE INITIALLY DEFERRED);
INSERT INTO "new__newsroom_story" ("id", "slug", "body", "priority", "status", "published_at", "desk_id", "reporter_id", "edition_id", "headline") SELECT "id", "slug", "body", "priority", "status", "published_at", "desk_id", "reporter_id", "edition_id", "headline" FROM "newsroom_story";
DROP TABLE "newsroom_story";
ALTER TABLE "new__newsroom_story" RENAME TO "newsroom_story";
CREATE INDEX "newsroom_story_desk_id_e230087a" ON "newsroom_story" ("desk_id");
CREATE INDEX "newsroom_story_reporter_id_ef8ca261" ON "newsroom_story" ("reporter_id");
CREATE INDEX "newsroom_story_edition_id_b9299bd3" ON "newsroom_story" ("edition_id");
django_migrations_desk_rows = ['newsroom.0001_initial', 'subscribers.0001_initial']
Look closely at DatabaseSchemaEditor too: on SQLite, add_field only takes the fast 1-statement "ALTER TABLE ADD COLUMN" path when the new column is nullable, non-unique, non-PK, and has no Python default (or only a constant db_default). Adding a non-nullable column with a Python "default=..." forces _remake_table as well! And look at ch09-bench Part 2 showing why even "add_col_ms" rose gently from 0.576 ms to 1.474 ms at 10,000 rows — DatabaseSchemaEditor runs "PRAGMA foreign_key_check" across the table before re-enabling foreign-key constraints:
2. SQLite SchemaEditor: ADD COLUMN vs _remake_table by table size (5 trials, ms)
rows add_col_ms remake_ms ratio
0 0.576 3.198 5.5x
1000 0.651 6.243 9.6x
5000 1.237 16.202 13.1x
10000 1.474 17.348 11.8x
Two final migration flags round out production reality: "migrate --fake-initial" invokes MigrationExecutor — the one place in MigrationExecutor that does introspect live tables (table_names and get_table_description) so an existing database adopting migrations can mark 0001_initial applied if its tables and columns already exist; and "sqlmigrate" simply runs MigrationExecutor with collect_sql=True, collecting every statement into "schema_editor without executing a single DDL command.
That closes Part II · The ORM. We have traced a Django model from ModelBase, through lazy QuerySet cloning and FETCH_PEERS, down through Q, WhereNode, Query, and SQLCompiler, and all the way across ConnectionHandler, Atomic savepoints, on_commit hooks, ProjectState, and BaseDatabaseSchemaEditor.
With data fetched and persisted reliably, Django turns those objects into HTML — and turns submitted HTML forms back into validated Python objects. We open Part III · Presentation and systems next in Templates and forms.