---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

# 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` (`django/db/migrations/state.py:ProjectState`) in memory, while `"database_forwards"` delegates DDL generation to **`BaseDatabaseSchemaEditor`** (`django/db/backends/base/schema.py:BaseDatabaseSchemaEditor`). Orchestrating both halves against the live database is the job of **`MigrationExecutor`** (`django/db/migrations/executor.py:MigrationExecutor`).

## How `MigrationExecutor.apply_migration` drives DDL and `"django_migrations"`

Open `MigrationExecutor.migrate` (`django/db/migrations/executor.py:MigrationExecutor.migrate`) and `MigrationExecutor.apply_migration` (`django/db/migrations/executor.py:MigrationExecutor.apply_migration`). First, `MigrationExecutor` ensures the `"django_migrations"` table exists via `MigrationRecorder.ensure_schema` (`django/db/migrations/recorder.py: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:

```python
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__` (`django/db/backends/base/schema.py:BaseDatabaseSchemaEditor`):

- **Transactional DDL (`atomic_migration`):** `BaseDatabaseSchemaEditor.__init__` computes `"self.atomic_migration = self.connection.features.can_rollback_ddl and atomic"`. On PostgreSQL and SQLite, the entire migration (every DDL statement, plus `deferred_sql` like foreign-key constraints and indexes, plus the `"INSERT INTO django_migrations"` row when `deferred_sql` is empty!) runs inside one `atomic` (`django/db/transaction.py:atomic`) transaction. On MySQL and Oracle (`can_rollback_ddl = False`), `atomic_migration` is `False`, and `BaseDatabaseSchemaEditor.execute` even raises `TransactionManagementError` if you try to run DDL inside a manual `atomic` block!
- **Deferred SQL (`deferred_sql`):** Creating foreign-key constraints and secondary indexes is often appended to `"self.deferred_sql"` rather than executed mid-operation, then flushed all at once inside `BaseDatabaseSchemaEditor.__exit__` before the transaction commits — ensuring mutually-referencing tables exist before their constraints bind, and ensuring `"MigrationRecorder.record_applied"` runs *after* deferred constraints succeed (lines 258–262 of `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.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` (`django/db/backends/sqlite3/schema.py:DatabaseSchemaEditor`) falls back to **`DatabaseSchemaEditor._remake_table`** (`django/db/backends/sqlite3/schema.py: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!).

```text figure=migrations-state-and-ddl
Migration state replay pipeline & SQLite ADD COLUMN vs. _remake_table scaling (Django 6.1.3)

1. From migration files to historical StateApps to backend DDL:
   MigrationLoader (20 files -> DAG) -> ProjectState (state_forwards) -> StateApps (__fake__.Story) -> SchemaEditor
   SQLite alter_field(headline, max_length=200) -> 7 statements:
     1 CREATE new__story -> 2 INSERT SELECT * -> 3 DROP story -> 4 RENAME new__story -> 5..7 CREATE INDEX (3 FKs)

2. SQLite SchemaEditor ADD COLUMN O(1) vs. _remake_table O(N) on newsroom_story (5 trials, ms):
        0 rows:  ADD COLUMN 0.576 ms  |  _remake_table  3.198 ms  ( 5.5x)
    1,000 rows:  ADD COLUMN 0.651 ms  |  _remake_table  6.243 ms  ( 9.6x)
    5,000 rows:  ADD COLUMN 1.237 ms  |  _remake_table 16.202 ms  (13.1x)
   10,000 rows:  ADD COLUMN 1.474 ms  |  _remake_table 17.348 ms  (11.8x)
```

*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` (`django/db/backends/base/base.py: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`):

```text recording=ch09-database
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` (`django/db/backends/sqlite3/schema.py: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:

```text recording=ch09-bench
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` (`django/db/migrations/executor.py: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](../presentation.md).
