---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
part: The ORM
promise: The database is always ready and migrations just diff models.
contents: connections, backends, transactions, on-commit, project-state, autodetector, schema-editor
---

# Connections, transactions, and migrations

Connection lifecycles, `atomic` savepoints, `on_commit` hooks, how migrations replay history into a `ProjectState` graph, and how `BaseDatabaseSchemaEditor` rewrites live tables.

Above `django/db/models/`, Django feels stateless and immediate: call `"Story.objects.create(...)"` and a row lands on disk; edit `"models.py"`, run `"makemigrations"` and `"migrate"`, and the database matches your class definitions.

Open the bottom half of `django/db/` and both halves of that promise dissolve. First, Django does **not** hold a pre-opened pool of sockets waiting for your views: `ConnectionHandler` (`django/db/utils.py:ConnectionHandler`) isolates one lazy `BaseDatabaseWrapper` (`django/db/backends/base/base.py:BaseDatabaseWrapper`) per thread, opens the socket only on the first query, runs every statement in autocommit unless wrapped in `Atomic` (`django/db/transaction.py:Atomic`), and tears down expired or broken connections on `"request_started"` and `"request_finished"`. Second, migrations **never** diff your Python models against the live database tables: `MigrationLoader` (`django/db/migrations/loader.py:MigrationLoader`) replays every historical migration file into an in-memory `ProjectState` (`django/db/migrations/state.py:ProjectState`) and renders synthetic `"__fake__"` model classes inside `StateApps` (`django/db/migrations/state.py:StateApps`) before `BaseDatabaseSchemaEditor` (`django/db/backends/base/schema.py:BaseDatabaseSchemaEditor`) translates abstract operations into backend-specific DDL.

## Connection lifecycles and the real cost of autocommit

```text figure=connection-and-tx-lifecycle
Connection lifecycle & 100-row insert transaction cost on Django 6.1.3 (file-backed SQLite, 7 trials)

1. Request-scoped connection lifecycle (per thread):
   request_started  -> reset_queries() + close_old_connections(); connection stays None until 1st query
   ensure_connection-> connect() opens socket; close_at = t0 + CONN_MAX_AGE; optional CONN_HEALTH_CHECKS
   queries & atomic -> wrap_database_errors (IntegrityError keeps errors_occurred=False; OperationalError=True)
   request_finished -> close_old_connections() drops connection if CONN_MAX_AGE=0, expired, or unusable

2. 100 Correction inserts on file-backed SQLite (7 trials, median ms):
   autocommit (100 commits)          559.239 ms  ( 1.00x — 100 disk fsyncs)
   1 atomic() + 100 savepoints        30.377 ms  (18.41x faster)
   1 atomic() (0 savepoints)          23.796 ms  (23.50x faster)
   1 atomic() + bulk_create(100)       8.738 ms  (64.00x faster)
```

*Every latency bar is parsed directly from `ch09-bench` on a real file-backed SQLite database using Django's default settings, and every lifecycle hook is verified in `ch09-database`. Wrapping 100 saves in one `atomic` block cuts wall-clock time from `559.239 ms` to `23.796 ms` (`23.50x` faster), and pairing `atomic` with `QuerySet.bulk_create` reaches `8.738 ms` (`64.00x` faster).*

## What closes Part II

This chapter traces the entire persistence boundary from socket to schema across seven steps:

We begin with how `ConnectionHandler` isolates thread-local connections, when `BaseDatabaseWrapper.ensure_connection` (`django/db/backends/base/base.py:BaseDatabaseWrapper.ensure_connection`) actually opens a socket, and how `"CONN_MAX_AGE"` and `"CONN_HEALTH_CHECKS"` interact with request signals. Next we inspect the five-class anatomy that lets SQLite, PostgreSQL, MySQL, and Oracle diverge cleanly behind one API via `BaseDatabaseFeatures` (`django/db/backends/base/features.py:BaseDatabaseFeatures`) and `BaseDatabaseOperations` (`django/db/backends/base/operations.py:BaseDatabaseOperations`). From there we trace autocommit, nested `Atomic` savepoints, the `"needs_rollback"` poisoned-block trap, and why side effects belong inside `on_commit` (`django/db/transaction.py:on_commit`) commit hooks. Finally, we open the migration engine from end to end: `MigrationGraph` (`django/db/migrations/graph.py:MigrationGraph`) and historical `ProjectState` models, `MigrationAutodetector` (`django/db/migrations/autodetector.py:MigrationAutodetector`) and `MigrationOptimizer` (`django/db/migrations/optimizer.py:MigrationOptimizer`), and `MigrationExecutor` (`django/db/migrations/executor.py:MigrationExecutor`) driving `BaseDatabaseSchemaEditor` — including why altering one column on SQLite rebuilds the entire table.

We start at the bottom of the connection stack — how Django creates, reuses, and closes database connections per thread — in [Connection handlers, CONN_MAX_AGE, and teardown](database/connections.md).
