Django 6.1.3

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.migrate and MigrationExecutor.apply_migration. First, MigrationExecutor ensures the "django_migrations" table exists via MigrationRecorder.ensure_schema — using a floating model defined on MigrationRecorder.Migration inside a private Apps() instance! Next it computes the exact (Migration, backwards) plan via MigrationExecutor.migration_plan (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.__enter__ and BaseDatabaseSchemaEditor.__exit__:

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.sql_alter_column_type: "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._remake_table — executing the full five-stage rebuild recommended by SQLite’s own documentation while foreign-key checks are temporarily suspended (DatabaseSchemaEditor.__enter__ disables "PRAGMA foreign_keys", and __exit__ verifies integrity with "PRAGMA foreign_key_check" before re-enabling them!).

Figure 9.3 Every statement count and median millisecond bar is parsed directly from 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.schema_editor (BaseDatabaseWrapper.schema_editor, 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):

Recorded on Django 6.1.3 ch09-database script
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.add_field 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.__exit__ runs "PRAGMA foreign_key_check" across the table before re-enabling foreign-key constraints:

Recorded on Django 6.1.3 ch09-bench script
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.detect_soft_applied — 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.collected_sql" without executing a single DDL command.


That closes Part II · The ORM. We have traced a Django model from ModelBase.__new__, 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.