Alembic Migrations, Transactions & Indexes from the ORM
"It is critical to note that autogenerate is not intended to be perfect. It is always necessary to manually review and correct the candidate migrations that autogenerate produces." — Alembic documentation, "Auto Generating Migrations", alembic.sqlalchemy.org/en/latest/autogenerate.html
Summary: Alembic is the migration tool of SQLAlchemy. A migration environment (alembic.ini, env.py, script.py.mako, versions/) holds an ordered chain of revision files, each with an upgrade() and a downgrade() written with op.* operations, and the database records the revision it is at in the alembic_version table. Autogenerate compares SQLModel.metadata with a live database and writes a candidate revision that a human must review: it cannot see renames, and on SQLite every ALTER that SQLite lacks becomes a "move and copy" batch operation. Shipping a schema change without downtime means expand/contract: add nullable, deploy code that writes the new column, backfill in batches, then add the constraint. On PostgreSQL that last step goes through NOT VALID/VALIDATE, and indexes are built with CREATE INDEX CONCURRENTLY inside autocommit_block(). Migrations run once per deploy from a Job, never from every replica at startup. In the application the same discipline applies to transactions: one unit of work per request, an explicit commit point, savepoints for partial failure, with_for_update() for row locks, and a retry of the whole transaction on serialization failures. Focus: why create_all is not a migration tool; alembic init and its templates; alembic.ini vs an environment-based sqlalchemy.url; target_metadata with SQLModel metadata; autogenerate (what it detects, compare_type, compare_server_default, renames not detected, expression indexes and CHECK constraints skipped, AutoString and import sqlmodel); the MetaData naming convention; revision files and op.create_table, op.add_column, op.alter_column, op.create_index, op.drop_column, op.create_check_constraint; batch_alter_table and render_as_batch for SQLite ALTER limitations; alembic upgrade head, downgrade -1, downgrade base, history, current, heads, stamp, check; branches and merge revisions; offline mode --sql; data migration vs schema migration; transactional DDL (PostgreSQL DDL in transaction, MySQL implicit commit, SQLite's driver behaviour) and partial migration failure; expand/contract, nullable first, backfill in batches, CREATE INDEX CONCURRENTLY with autocommit_block, lock_timeout and statement_timeout; migrations at deploy (Kubernetes Job, init container, never at startup with multiple replicas); migration tests (upgrade/downgrade round trip, stairway, alembic check); async Alembic with run_sync; Session.begin(), begin_nested() and savepoints, rollback, expire_on_commit, isolation_level via execution_options, serialization failure retry, unit of work per request and commit in a dependency with Depends(scope="function"); with_for_update(), skip_locked, nowait, key_share, read; Index, index=True, composite, partial (postgresql_where, sqlite_where) and expression indexes, UniqueConstraint, CheckConstraint; Laravel migrations (php artisan migrate) and Go's goose, atlas and golang-migrate. Learning goal: Set up Alembic for a SQLModel project so the database URL never sits in a file, every constraint has a predictable name and SQLite migrations work. Read an autogenerated revision critically and fix what it got wrong. Ship a NOT NULL column and an index to a busy PostgreSQL table without locking out writes. Know what a half-failed migration leaves behind on each engine, and run migrations once per deploy. Then draw the transaction boundary of every request on purpose: one commit point, savepoints where partial failure is fine, a row lock where two requests race, and a retry loop where the database may abort.
This page owns the Alembic and SQLAlchemy mechanics of schema change and transactions in the python section. It does not re-teach its neighbours. Engine, Session, models and relationships are in SQLAlchemy 2 & SQLModel, and this page reuses its rooms-and-bookings tables. Query recipes and cascade rules are in Queries in Practice. Where the commit of a yield dependency runs is argued in Dependency Injection, and this page only adds the unit-of-work variant. Migration theory as a database topic is in Schema Migrations: expand/contract across ORMs, zero-downtime patterns, backfills and the tool landscape. Transaction theory is in ACID Transactions and Isolation Levels, locks in Locks & Concurrency and Optimistic vs Pessimistic Locking, and index design in Indexing. Database fixtures are in Testing FastAPI and the release process in FastAPI in Production. The migration Job in Kubernetes is in Kubernetes Workloads, the CI stage in CI/CD Pipelines, and the whole API in Project: Rooms & Bookings API. The Go side of transactions is database/sql and pgx.
Facts below were checked against the Alembic documentation (front matter, tutorial, autogenerate, batch migrations, branches, offline mode, cookbook, naming constraints, operations reference, commands and runtime API, and the changelog up to 1.20.2), the SQLAlchemy 2.0 documentation (MetaData, constraints and indexes, defaults, Session transactions, connections and isolation levels, Select.with_for_update, the PostgreSQL, MySQL and SQLite dialect pages, the asyncio extension, the error reference), SQLModel's tutorial and its Advanced User Guide index, FastAPI's "SQL (Relational) Databases" and "Dependencies with yield" pages, PostgreSQL's CREATE INDEX, ALTER TABLE, SELECT, client configuration (lock_timeout, statement_timeout), transaction isolation and error code pages plus the PostgreSQL wiki on transactional DDL, MySQL 8.4's implicit-commit, atomic DDL, locking reads and CREATE INDEX pages, SQLite's ALTER TABLE, transaction and foreign key pages, the Kubernetes Job and init container pages, Helm chart hooks, the Laravel 13 migrations, database and query builder pages, and the goose, atlas and golang-migrate READMEs. The page targets Python 3.12+ and current releases: Alembic 1.20.1 (2026-10-22) needs Python 3.10+, SQLAlchemy 2.1.9 and SQLModel 0.0.50 need 3.11+, according to PyPI metadata. The snippets ran on the only interpreter on the build machine, CPython 3.9.6, so the project pins the newest releases that still install there. Those are Alembic 1.16.5 (2025-08-27, the last for Python 3.9, since 1.17.0 requires 3.10), SQLAlchemy 2.0.58, SQLModel 0.0.34, FastAPI 0.128.8, Starlette 0.49.3, Pydantic 2.13.5, aiosqlite 0.22.1, greenlet 3.2.5, httpx 0.28.1 and pytest 8.4.2. Everything marked "real" was printed by that run against SQLite 3.54.0. The PostgreSQL and MySQL scripts quoted below were rendered by Alembic's offline mode (real output of alembic upgrade head --sql for those dialects), but no PostgreSQL or MySQL server ran them. Their runtime behaviour (locks, transactional DDL, CONCURRENTLY, implicit commits, SKIP LOCKED) is quoted from the vendors' documentation and marked "expected, not run".
Page map
| If you are looking for | Go to |
|---|---|
| The tables you can memorise in one minute | Everything in one minute |
Why create_all is not enough | Why it exists |
| Alembic 0.1 (2011) to 1.20 (2026) | Where it comes from |
| A before/after project with real revisions and tests | Python |
create_all vs migrations | create_all is not a migration tool |
alembic init, env.py, script.py.mako, versions/ | The migration environment |
sqlalchemy.url in alembic.ini or DATABASE_URL | Database URL |
target_metadata = SQLModel.metadata | target_metadata with SQLModel |
| What autogenerate sees and misses | Autogenerate |
ix_, uq_, ck_, fk_, pk_ names | Naming conventions |
upgrade(), downgrade(), op.* | Revision files and operations |
SQLite cannot ALTER, batch_alter_table | Batch mode for SQLite |
upgrade head, downgrade -1, current, stamp | Applying migrations |
Two heads, merge | Branches and merge revisions |
| SQL scripts for a DBA | Offline mode --sql |
| Moving data inside a migration | Data migrations vs schema migrations |
| What a half-failed migration leaves behind | Transactional DDL and partial failure |
| Adding a NOT NULL column without downtime | Expand/contract in Alembic |
CREATE INDEX CONCURRENTLY, lock_timeout | Building indexes without blocking writes |
| Init container, Job, release step | Running migrations at deploy |
Round trip, stairway, alembic check | Testing migrations |
alembic init -t async, run_sync | Async Alembic |
Session.begin(), commit as you go | Transactions in the Session |
begin_nested(), SAVEPOINT | Savepoints |
expire_on_commit | Expire on commit |
execution_options(isolation_level=...) | Isolation level per connection |
SQLSTATE 40001, deadlocks, database is locked | Retrying serialization failures |
| Commit in the route or in the dependency | Unit of work per request |
with_for_update, skip_locked, nowait | Row locks from the ORM |
Index, index=True, partial, expression, UniqueConstraint, CheckConstraint | Indexes and constraints from the ORM |
AutoString, missing imports, metadata not loaded | SQLModel and Alembic gotchas |
What upgrade head does step by step, exact errors, rendered SQL | Mechanics |
| The common failures and their fixes | Solving the classic problems |
| Alembic vs alternatives, which pattern when | Choosing |
| Monolith to distributed system | In architecture |
| Reproduce it on your machine | Lab |
php artisan migrate, DB::transaction | For PHP/Laravel developers |
| goose, atlas, golang-migrate, pgx transactions | The Go angle |
Everything in one minute
The pieces of an Alembic project. Each row is unpacked in the concept catalogue.
| Piece | What it is | Plain words | In the snippet |
|---|---|---|---|
alembic.ini | ConfigParser file: script location, file template, logging, fallback URL | "Where things are" | alembic.ini |
env.py | Python script run by every command: builds the connection, configures the context | "How to reach the database" | migrations/env.py |
script.py.mako | Mako template for new revision files | "The blank form" | adds import sqlmodel |
versions/ | One file per revision, linked by down_revision | "The logbook" | 0001 … 0006 |
alembic_version | One-row table holding the current revision id | "The bookmark" | 0006 after upgrade head |
target_metadata | The MetaData autogenerate compares with the database | "What the code says the schema is" | SQLModel.metadata |
op | alembic.op, the Operations proxy inside a revision | "The toolbox" | op.add_column, op.create_index |
batch_alter_table | Move-and-copy context for SQLite (and a plain ALTER elsewhere) | "Rebuild the table" | revisions 0002, 0004 |
MigrationContext | Runtime object behind op.get_context() | "The engine room" | autocommit_block(), .dialect, .as_sql |
Commands and what they do (real output, Alembic 1.16.5 on SQLite, runs/cli-session.txt).
| Command | Effect | Real output |
|---|---|---|
alembic upgrade head | Run every pending upgrade() in order | Running upgrade 0005 -> 0006, create email_outbox with server defaults |
alembic downgrade -1 | Run one downgrade() | Running downgrade 0006 -> 0005, ... |
alembic downgrade base | Undo everything; the empty alembic_version table stays | .tables → alembic_version |
alembic current | Print the revision in alembic_version | 0006 (head) |
alembic history | Print the chain | <base> -> 0001, create user room booking |
alembic heads | Print the tips of the chain | 0006 (head); two lines = two heads |
alembic stamp head | Write a revision id without running DDL | Running stamp_revision 0005 -> 0006 |
alembic check | Autogenerate dry run; fails (exit 255 here) if models and database differ | No new upgrade operations detected. / FAILED: New upgrade operations detected: [...] |
alembic upgrade head --sql | Print the SQL instead of running it | CREATE INDEX CONCURRENTLY ... (PostgreSQL render) |
alembic revision --autogenerate -m "..." | Write a candidate revision from the diff | Detected added column 'room.floor' |
alembic merge heads -m "..." | One revision with two parents | e5f6 (head) (mergepoint) |
DDL and transactions per engine (vendor docs; the SQLite column is from real runs).
| Behaviour | PostgreSQL | MySQL 8.4 (InnoDB) | SQLite 3.54 via Python's sqlite3 |
|---|---|---|---|
| DDL inside a transaction | yes, rolls back with it | no: DDL causes an implicit commit | yes in SQLite, but the driver sends no BEGIN before DDL |
| Alembic's log line | Will assume transactional DDL. | Will assume non-transactional DDL. | Will assume non-transactional DDL. |
| A revision that fails halfway | nothing left behind | earlier statements stay | earlier statements stay (real) |
| ALTER COLUMN type / ADD CONSTRAINT | yes | yes | no: batch mode recreates the table |
| Build an index without blocking writes | CREATE INDEX CONCURRENTLY, outside a transaction | online DDL (ALGORITHM=INPLACE, LOCK=NONE) | not applicable (one writer) |
| Partial index | postgresql_where | not supported (the WHERE is dropped, real render) | sqlite_where |
| Expression index | (lower(email)) | ((lower(email))) required | yes, but not reflected by SQLAlchemy 2.0 |
FOR UPDATE SKIP LOCKED | yes | yes | omitted when compiled (real) |
Transaction tools in the Session (each one is a test in tests/test_transactions.py).
| Tool | Code | Use it for |
|---|---|---|
| Begin once | with session.begin(): ... | Several writes that commit together |
| Commit as you go | session.add(x); session.commit() | The route decides; the usual FastAPI style |
| Savepoint | with session.begin_nested(): ... | "Try this row, skip it if it fails" |
| Expire on commit | sessionmaker(..., expire_on_commit=False) | Objects read after commit (async, serializers) |
| Isolation per connection | conn.execution_options(isolation_level="SERIALIZABLE") | One report or one money move |
| Retry | new Session + transaction per attempt on 40001 / 40P01 | Serializable or deadlock-prone work |
| Row lock | select(Room).where(...).with_for_update() | Two requests booking the same room |
| Queue claim | .with_for_update(skip_locked=True) | Workers taking jobs without waiting |
Why it exists
SQLModel.metadata.create_all(engine) knows one thing: which tables are missing. It never alters a table that already exists. The first time a model gains a column, the production database and the code disagree, and the result is a runtime error (no such column: room.floor, real run of the Before app). A migration tool turns every schema change into a file that is reviewed in a pull request, applied once, in order, on every environment, and recorded in the database. It can also be reversed, or at least undone by a later file. Alembic is that tool for SQLAlchemy: "Alembic is a lightweight database migration tool for usage with the SQLAlchemy Database Toolkit for Python." It also owns the uncomfortable details: SQLite's missing ALTER statements, PostgreSQL index builds that must run outside a transaction, and MySQL committing every DDL statement on its own.
The second half of this page is about the same problem at a smaller scale. A migration is a change to the schema that must apply completely or be recoverable. A request is a change to the data that must apply completely or not at all. Both need a clear start, a clear commit point and a known behaviour on failure.
create_all() at startup | Alembic migrations |
|---|---|
| Creates missing tables, never alters | op.add_column, op.alter_column, op.create_index, anything SQL can do |
| No record of what ran | alembic_version holds the revision id |
| Runs in every replica on every start | Runs once per deploy from one place |
| No review step | A revision file in the pull request, plus --sql for the DBA |
| No data steps | Data migrations in their own revisions |
| No way back | downgrade() per revision |
| Same schema in tests and production only by luck | alembic check in CI catches the drift autogenerate can see (not CHECKs, renames, expression indexes on SQLite) |
An everyday picture. The hotel from the ORM chapter is being renovated while guests stay in it. Every renovation is a numbered work order (a revision) that names the order before it (down_revision). A plaque in the lobby says which work order was finished last (alembic_version). The site manager (env.py) knows how to get into the building. The blank work-order form (script.py.mako) has the standard checklist printed on it. A new wing is opened before the old corridor is closed (expand/contract), and the guests are moved over floor by floor rather than all at once (backfill in batches). Some jobs must be done with the building open, such as repainting a corridor one half at a time (CREATE INDEX CONCURRENTLY). One foreman runs the work orders for the whole building; if every receptionist tried to do it at once they would collide (never at startup with multiple replicas). Inside the hotel, each guest's check-in is one unit of work at the front desk: the room is held while the form is filled in (with_for_update), and either the booking and the confirmation e-mail are both recorded, or neither is.
Three common misunderstandings, up front
- "Autogenerate writes my migrations." It writes candidates. In the real run it turned a new
floor: intintoadd_column(... nullable=False)with no default, which fails on any table with rows (Cannot add a NOT NULL column with default value NULL). It said nothing about the CHECK constraint, and it skipped the expression index with a warning. Every revision is reviewed and usually edited. - "A failed migration rolls itself back." Only where DDL is transactional and the driver actually sends BEGIN. On SQLite through Python's
sqlite3(real run) and on MySQL (vendor docs), the statements before the failure stay applied whilealembic_versionstill names the old revision, so the re-run fails withduplicate column nameortable ... already exists. - "My request is one transaction because I use a Session." It is one transaction only if exactly one place commits, and that place runs before the response is sent. A commit after
yieldin a default-scope dependency runs after the client has its 201. The real test shows the 201 and an empty table.
Where it comes from
According to PyPI's release history, Alembic 0.1.0 was published on 2011-11-30. The changelog then records the milestones that change how migrations are written today. 0.6.0 came out on July 19, 2013. 0.7.0 (November 24, 2014) introduced "Working with Branches", with alembic merge, alembic heads and alembic branches, and in the same release Operations.batch_alter_table() for SQLite. 1.0.0 followed on 2018-07-13. 1.2.0 (2019-09-20) added MigrationContext.autocommit_block(), "a special directive which will provide for a non-transactional block inside of a migration script". 1.4.0 (February 4, 2020) is the release in which, as the 1.12.0 changelog puts it, "Alembic's autogenerate for types was dramatically improved". 1.5.6 (2021-03-07) added the async template. 1.9.0 (December 15, 2022) "Added new Alembic command alembic check", and 1.12.0 (2023-08-31) changed "the default value of EnvironmentContext.configure.compare_type to True". 1.16.0 (May 21, 2025) "Added optional PEP 621 support", so source-code settings can live in pyproject.toml while "configuration of database connectivity or logging ... remain under the category of 'deployment' configuration". 1.16.5 (2025-08-27) is the last release for Python 3.9, and 1.17.0 (2025-10-11) requires 3.10. 1.19.0 (August 4, 2026) made autogenerate detect named CHECK constraints, and 1.19.2 (September 4, 2026) switched that detection off by default again. 1.20.1 (2026-10-22) is the latest release, and the changelog already lists an unreleased 1.20.2. SQLModel still has no migration helpers: its tutorial says "SQLModel will have migration utilities wrapping Alembic, but for now, you can use Alembic directly", and its Advanced User Guide lists "How to run migrations." as a future topic.
1 2011-11 Alembic 0.1.0
2 2014-11 0.7.0: branches (merge, heads, branches) and batch_alter_table for SQLite
3 2018-07 1.0.0
4 2019-09 1.2.0: MigrationContext.autocommit_block() (CREATE INDEX CONCURRENTLY, ALTER TYPE ... ADD VALUE)
5 2020-02 1.4.0: type comparison "dramatically improved"
6 2021-03 1.5.6: async template (alembic init -t async)
7 2022-12 1.9.0: alembic check
8 2023-08 1.12.0: compare_type defaults to True
9 2025-05 1.16.0: pyproject.toml configuration (PEP 621), path_separator
10 2025-08 1.16.5: last release for Python 3.9 (the snippet pin)
11 2025-10 1.17.0: Python 3.10+
12 2026-08 1.19.0: named CHECK constraints detected (1.19.2, 2026-09: off by default again)
13 2026-10 1.20.1: latest releasePython
Before
The first version most FastAPI apps ship. The schema comes from create_all() in the lifespan, so it runs in every replica on every start and records nothing. It cannot add the floor column to a table that already exists. The commit sits after yield, which with the default dependency scope runs after the response:
"""The first version most apps ship: the schema comes from create_all() at startup.
Bugs pinned by tests/test_before.py:
1. create_all() only creates MISSING tables. A column added to a model never reaches a
database that already has the table: "no such column: room.floor" at runtime.
2. Every replica runs it on every start; nothing records which schema version is live.
3. The commit sits after `yield` in a default-scope dependency, i.e. after the response.
"""
from contextlib import asynccontextmanager
from typing import Annotated, Iterator, List
from fastapi import Depends, FastAPI, Request
from sqlalchemy.engine import Engine
from sqlmodel import Session, SQLModel, select
from app.models import Room
def create_app(engine: Engine) -> FastAPI:
@asynccontextmanager
async def lifespan(app: FastAPI):
SQLModel.metadata.create_all(engine) # BUG 1 + 2: "migrations" by create_all
yield
app = FastAPI(lifespan=lifespan)
app.state.engine = engine
def get_session(request: Request) -> Iterator[Session]:
with Session(request.app.state.engine) as session:
yield session
session.commit() # BUG 3: runs after the response has been sent
@app.get("/rooms")
def list_rooms(session: Annotated[Session, Depends(get_session)]) -> List[Room]:
return list(session.exec(select(Room)).all())
return appThe tests pin the two migration bugs against a database that v1 of the app created. create_all() adds the missing booking table, leaves room without floor, and the next query fails with no such column: room.floor. There is no alembic_version table to say which schema is live. (The late commit is pinned by tests/test_api.py::test_default_scope_commit_failure_arrives_after_a_201, below.)
"""The Before app's create_all() cannot evolve an existing table (real run)."""
import pytest
from fastapi.testclient import TestClient
from sqlalchemy import inspect, text
from sqlalchemy.exc import OperationalError
from app.before import create_app
from app.db import make_engine
def test_create_all_does_not_add_a_new_column_to_an_existing_table(tmp_path):
engine = make_engine(f"sqlite:///{tmp_path / 'old.db'}")
with engine.begin() as conn: # the table as v1 of the app created it, before `floor` existed
conn.execute(text(
"CREATE TABLE room (id INTEGER PRIMARY KEY, name VARCHAR(100) NOT NULL, "
"capacity INTEGER NOT NULL, price_cents INTEGER NOT NULL, version INTEGER NOT NULL)"
))
conn.execute(text("INSERT INTO room (name, capacity, price_cents, version) VALUES ('Garden', 2, 9000, 1)"))
with TestClient(create_app(engine)) as client: # lifespan runs create_all()
assert "floor" not in [c["name"] for c in inspect(engine).get_columns("room")]
assert "booking" in inspect(engine).get_table_names() # missing tables DO get created
with pytest.raises(OperationalError, match="no such column: room.floor"):
client.get("/rooms")
engine.dispose()
def test_create_all_leaves_no_version_record(tmp_path):
engine = make_engine(f"sqlite:///{tmp_path / 'fresh.db'}")
with TestClient(create_app(engine)) as client:
assert client.get("/rooms").json() == []
assert "alembic_version" not in inspect(engine).get_table_names() # which schema is this?
engine.dispose()After
The project is one directory: pyproject.toml, alembic.ini, migrations/ (env, template, six revisions), app/ and tests/. The models are the schema at head, with the naming convention set before the first table, a composite, a partial and an expression index, a CHECK constraint and an outbox table with server defaults:
"""The rooms-and-bookings schema at migration head (revision 0006).
Same table and column names as the SQLAlchemy/SQLModel chapter, reduced to the tables this
chapter migrates: user, room, booking and an email outbox. Indexes and constraints are declared
here so that autogenerate and `alembic check` can compare them with the database.
Deliberately no `from __future__ import annotations`: SQLModel reads the annotations at runtime.
`Optional[X]` keeps the module valid on Python 3.9; on 3.10+ write `X | None`.
"""
import datetime as dt
from typing import Optional
from sqlalchemy import CheckConstraint, Column, Index, Integer, func, text
from sqlmodel import Field, SQLModel
# One naming convention for every constraint and index, set BEFORE any table is defined.
# Without it, SQLite and PostgreSQL invent different names (or none), and a later
# `op.drop_constraint(<name>)` cannot be written portably.
NAMING_CONVENTION = {
"ix": "ix_%(column_0_label)s",
"uq": "uq_%(table_name)s_%(column_0_name)s",
"ck": "ck_%(table_name)s_%(constraint_name)s",
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
"pk": "pk_%(table_name)s",
}
SQLModel.metadata.naming_convention = NAMING_CONVENTION
class User(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
email: str = Field(index=True, unique=True, max_length=255)
full_name: Optional[str] = Field(default=None, max_length=100)
hashed_password: str
__table_args__ = (
# Expression index: case-insensitive lookups `WHERE lower(email) = lower(:e)`.
Index("ix_user_email_lower", func.lower(text("email"))),
)
class Room(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(index=True, unique=True, max_length=100)
capacity: int
price_cents: int
# Added by the expand/contract revisions 0002 (nullable) -> 0003 (backfill) -> 0004 (NOT NULL).
floor: int
version: int = Field(default=1, sa_column=Column("version", Integer, nullable=False))
class Booking(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
# No index=True here: ix_booking_room_id would be a left prefix of the composite index
# below, so revision 0005 drops it (one index fewer to maintain on every INSERT).
room_id: int = Field(foreign_key="room.id", ondelete="CASCADE")
user_id: Optional[int] = Field(default=None, foreign_key="user.id", ondelete="SET NULL")
start_date: dt.date
end_date: dt.date # exclusive
guests: int = 1
cancelled_at: Optional[dt.datetime] = None
__table_args__ = (
CheckConstraint("end_date > start_date", name="end_after_start"),
# Composite index: "bookings of room X starting from date D" (left-most prefix room_id).
Index("ix_booking_room_id_start_date", "room_id", "start_date"),
# Partial index: only active bookings take part in overlap checks.
Index(
"ix_booking_active_room",
"room_id",
"start_date",
"end_date",
sqlite_where=text("cancelled_at IS NULL"),
postgresql_where=text("cancelled_at IS NULL"),
),
)
class EmailOutbox(SQLModel, table=True):
"""Transactional outbox: written in the same transaction as the booking, sent later."""
__tablename__ = "email_outbox"
id: Optional[int] = Field(default=None, primary_key=True)
booking_id: int = Field(foreign_key="booking.id", ondelete="CASCADE")
status: str = Field(
default="pending",
sa_column_kwargs={"server_default": "pending"},
max_length=20,
)
created_at: dt.datetime = Field(
default_factory=lambda: dt.datetime.now(dt.timezone.utc),
sa_column_kwargs={"server_default": func.current_timestamp()},
)
sent_at: Optional[dt.datetime] = None
__table_args__ = (Index("ix_email_outbox_status_id", "status", "id"),)
# Re-exported for env.py and tests: the one MetaData that Alembic compares against.
metadata = SQLModel.metadataalembic.ini (ConfigParser; shown as a fenced block because it is not Python). The URL here is only a fallback:
[alembic]
script_location = %(here)s/migrations
prepend_sys_path = .
file_template = %%(rev)s_%%(slug)s
path_separator = os
# Fallback only. env.py prefers the DATABASE_URL environment variable.
sqlalchemy.url = sqlite:///rooms.db
# [loggers] / [handlers] / [formatters]: the generated defaults (alembic logger at INFO)The environment: URL from DATABASE_URL, target_metadata = SQLModel.metadata, render_as_batch on SQLite, transaction_per_migration=True, per-dialect session setup (PostgreSQL timeouts, SQLite foreign keys off) committed before context.configure(), a connection handed in by tests, the async branch through run_sync, and offline mode:
"""Alembic migration environment for the rooms schema.
- target_metadata is SQLModel.metadata (importing app.models registers every table).
- The URL comes from DATABASE_URL, falling back to sqlalchemy.url in alembic.ini.
- SQLite gets render_as_batch=True (it cannot ALTER most things in place).
- A connection handed in by a test (config.attributes["connection"]) is reused.
- An async URL (sqlite+aiosqlite, postgresql+asyncpg) runs through connection.run_sync().
- Offline mode (--sql) renders the SQL script instead of running it.
"""
import asyncio
import os
from logging.config import fileConfig
from alembic import context
from sqlalchemy import pool, text
from sqlalchemy.engine import Connection, create_engine, make_url
from sqlalchemy.ext.asyncio import create_async_engine
import app.models # noqa: F401 (registers the tables on SQLModel.metadata)
from sqlmodel import SQLModel
config = context.config
if config.config_file_name is not None and config.attributes.get("configure_logger", True):
fileConfig(config.config_file_name, disable_existing_loggers=False)
target_metadata = SQLModel.metadata
# Session settings applied before any migration runs, per dialect.
# PostgreSQL: fail fast instead of queueing behind a long transaction while holding (or
# waiting for) an ACCESS EXCLUSIVE lock. Values are examples; tune per table size.
# SQLite: batch mode drops and recreates tables; with foreign keys ON that DROP would
# cascade into child tables, so make sure they are OFF for this connection.
SESSION_SETUP = {
"postgresql": ("SET lock_timeout = '5s'", "SET statement_timeout = '15min'"),
"sqlite": ("PRAGMA foreign_keys=OFF",),
}
def database_url() -> str:
return os.environ.get("DATABASE_URL") or config.get_main_option("sqlalchemy.url")
def configure_kwargs(dialect_name: str) -> dict:
return dict(
target_metadata=target_metadata,
compare_type=True, # the default since Alembic 1.12; explicit for readers
compare_server_default=True, # off by default; on here, review the diffs it reports
render_as_batch=dialect_name == "sqlite", # autogenerate writes batch_alter_table blocks
transaction_per_migration=True, # one transaction per revision, not one for the whole run
)
def run_migrations_offline() -> None:
"""`alembic upgrade head --sql`: no database connection, the SQL goes to stdout."""
url = make_url(database_url())
context.configure(
url=url,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
**configure_kwargs(url.get_backend_name()),
)
with context.begin_transaction():
if url.get_backend_name() == "postgresql":
for stmt in SESSION_SETUP["postgresql"]:
context.execute(stmt)
context.run_migrations()
def prepare_session(connection: Connection) -> None:
"""Run SESSION_SETUP, then COMMIT.
SQLAlchemy 2.0 autobegins a transaction on the first execute(). If that transaction is
still open when context.configure() runs, Alembic treats it as the caller's and never
commits it: the run exits 0 and alembic_version stays empty (real probe, see the page).
"""
for stmt in SESSION_SETUP.get(connection.dialect.name, ()):
connection.execute(text(stmt))
if connection.in_transaction():
connection.commit()
def do_run_migrations(connection: Connection) -> None:
context.configure(connection=connection, **configure_kwargs(connection.dialect.name))
with context.begin_transaction():
context.run_migrations()
async def run_async_migrations(url: str) -> None:
engine = create_async_engine(url, poolclass=pool.NullPool)
async with engine.connect() as connection:
await connection.run_sync(prepare_session)
await connection.run_sync(do_run_migrations)
await engine.dispose()
def run_migrations_online() -> None:
shared = config.attributes.get("connection")
if shared is not None: # a test (or app code) passed its own connection: caller's settings
do_run_migrations(shared)
return
url = database_url()
if make_url(url).get_dialect().is_async:
asyncio.run(run_async_migrations(url))
return
# NullPool: a migration run is one short-lived process; no pool to keep warm.
engine = create_engine(url, poolclass=pool.NullPool)
with engine.connect() as connection:
prepare_session(connection)
do_run_migrations(connection)
engine.dispose()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()script.py.mako is the generic template from alembic init (real, runs/init-script.py.mako.txt) plus import sqlmodel and a two-line comment, because autogenerate renders SQLModel's string columns as sqlmodel.sql.sqltypes.AutoString():
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# Autogenerate renders SQLModel's string type as sqlmodel.sql.sqltypes.AutoString();
# without this import the generated file fails with NameError: name 'sqlmodel' is not defined.
import sqlmodel
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision: str = ${repr(up_revision)}
down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)}
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
def upgrade() -> None:
"""Upgrade schema."""
${upgrades if upgrades else "pass"}
def downgrade() -> None:
"""Downgrade schema."""
${downgrades if downgrades else "pass"}The six revisions. 0001 is the real output of alembic revision --autogenerate --rev-id 0001 against an empty database, with only the docstring added. 0002 to 0004 are expand, backfill and contract for room.floor. 0005 adds the indexes (with CONCURRENTLY on PostgreSQL), and 0006 creates the outbox:
"""create user room booking
Revision ID: 0001
Revises:
Create Date: 2026-11-29 15:01:14.814677
Generated by `alembic revision --autogenerate --rev-id 0001` against an empty SQLite database
(render_as_batch=True, so indexes are created inside batch_alter_table blocks), then reviewed:
names come from the MetaData naming convention via op.f(), AutoString needs `import sqlmodel`.
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# Autogenerate renders SQLModel's string type as sqlmodel.sql.sqltypes.AutoString();
# without this import the generated file fails with NameError: name 'sqlmodel' is not defined.
import sqlmodel
# revision identifiers, used by Alembic.
revision: str = '0001'
down_revision: Union[str, Sequence[str], None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('room',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sqlmodel.sql.sqltypes.AutoString(length=100), nullable=False),
sa.Column('capacity', sa.Integer(), nullable=False),
sa.Column('price_cents', sa.Integer(), nullable=False),
sa.Column('version', sa.Integer(), nullable=False),
sa.PrimaryKeyConstraint('id', name=op.f('pk_room'))
)
with op.batch_alter_table('room', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_room_name'), ['name'], unique=True)
op.create_table('user',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('email', sqlmodel.sql.sqltypes.AutoString(length=255), nullable=False),
sa.Column('full_name', sqlmodel.sql.sqltypes.AutoString(length=100), nullable=True),
sa.Column('hashed_password', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.PrimaryKeyConstraint('id', name=op.f('pk_user'))
)
with op.batch_alter_table('user', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_user_email'), ['email'], unique=True)
op.create_table('booking',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('room_id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('start_date', sa.Date(), nullable=False),
sa.Column('end_date', sa.Date(), nullable=False),
sa.Column('guests', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['room_id'], ['room.id'], name=op.f('fk_booking_room_id_room'), ondelete='CASCADE'),
sa.ForeignKeyConstraint(['user_id'], ['user.id'], name=op.f('fk_booking_user_id_user'), ondelete='SET NULL'),
sa.PrimaryKeyConstraint('id', name=op.f('pk_booking'))
)
with op.batch_alter_table('booking', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_booking_room_id'), ['room_id'], unique=False)
# ### end Alembic commands ###
def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('booking', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_booking_room_id'))
op.drop_table('booking')
with op.batch_alter_table('user', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_user_email'))
op.drop_table('user')
with op.batch_alter_table('room', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_room_name'))
op.drop_table('room')
# ### end Alembic commands ###"""expand: room.floor and booking.cancelled_at as NULLABLE columns
Revision ID: 0002
Revises: 0001
Create Date: 2026-11-29 15:10:00
Expand step of expand/contract. Old application code that does not know the columns keeps
working: nullable columns with no default need no rewrite of existing rows (PostgreSQL adds
them as a catalog-only change) and old INSERTs that omit them still succeed.
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
revision: str = "0002"
down_revision: Union[str, Sequence[str], None] = "0001"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
# ADD COLUMN of a nullable column is a plain ALTER on SQLite as well; no table copy.
op.add_column("room", sa.Column("floor", sa.Integer(), nullable=True))
op.add_column("booking", sa.Column("cancelled_at", sa.DateTime(), nullable=True))
def downgrade() -> None:
# DROP COLUMN: SQLite 3.35+ can do it in place; batch mode keeps older SQLite working.
with op.batch_alter_table("booking") as batch_op:
batch_op.drop_column("cancelled_at")
with op.batch_alter_table("room") as batch_op:
batch_op.drop_column("floor")"""data migration: backfill room.floor in batches
Revision ID: 0003
Revises: 0002
Create Date: 2026-11-29 15:20:00
A data migration, kept in its own revision so the schema steps around it stay small.
It uses a lightweight table() construct, never the application's models: the models describe
the schema at head, this file must keep working against the schema as it was at 0002.
Batches keep each UPDATE short; on PostgreSQL with transaction_per_migration=True the whole
revision is still one transaction, so very large tables run the backfill as a separate job
(see the page) instead of inside the migration.
"""
import logging
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
revision: str = "0003"
down_revision: Union[str, Sequence[str], None] = "0002"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
BATCH_SIZE = 2 # tiny so the test sees several batches; use 1_000-10_000 in real life
log = logging.getLogger("alembic.data")
room = sa.table("room", sa.column("id", sa.Integer), sa.column("floor", sa.Integer))
def upgrade() -> None:
if op.get_context().as_sql:
# Offline (--sql) mode cannot loop on rowcounts; emit one set-based UPDATE instead.
op.execute(room.update().where(room.c.floor.is_(None)).values(floor=0))
return
bind = op.get_bind()
batches = 0
while True:
ids = bind.execute(
sa.select(room.c.id).where(room.c.floor.is_(None)).order_by(room.c.id).limit(BATCH_SIZE)
).scalars().all()
if not ids:
break
# Rule for existing rooms: ground floor. New rooms get a floor from the API.
bind.execute(room.update().where(room.c.id.in_(ids)).values(floor=0))
batches += 1
log.info("backfilled room.floor in %d batches of up to %d rows", batches, BATCH_SIZE)
def downgrade() -> None:
# Nothing to undo: 0002's downgrade drops the column and the data with it.
pass"""contract: room.floor NOT NULL, booking CHECK (end_date > start_date)
Revision ID: 0004
Revises: 0003
Create Date: 2026-11-29 15:30:00
Contract step: deploy it only after every running version of the app writes `floor`.
SQLite cannot ALTER COLUMN ... SET NOT NULL or ADD CONSTRAINT, so both changes run in
batch mode: Alembic creates _alembic_tmp_<table>, copies the rows, drops the old table and
renames the new one. With PRAGMA foreign_keys=ON that DROP would cascade into booking,
which is why env.py never turns the pragma on (see tests/test_batch_fk_trap.py).
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
revision: str = "0004"
down_revision: Union[str, Sequence[str], None] = "0003"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
if op.get_context().dialect.name == "postgresql":
_upgrade_postgresql()
return
with op.batch_alter_table("room") as batch_op:
batch_op.alter_column("floor", existing_type=sa.Integer(), nullable=False)
with op.batch_alter_table("booking") as batch_op:
# op.f() marks the name as final: the naming convention is not applied twice.
batch_op.create_check_constraint(op.f("ck_booking_end_after_start"), "end_date > start_date")
def _upgrade_postgresql() -> None:
"""Expected, not run here (no PostgreSQL in the build environment); rendered with --sql.
SET NOT NULL and ADD CHECK both scan the whole table under ACCESS EXCLUSIVE.
NOT VALID adds the constraint without the scan; VALIDATE CONSTRAINT scans under the weaker
SHARE UPDATE EXCLUSIVE lock; SET NOT NULL then skips its scan because a valid CHECK
proves there are no NULLs.
autocommit_block() COMMITs the NOT VALID constraints before VALIDATE runs. So that a
failure there can be fixed and the revision simply re-run:
1. online, bad rows are counted first, inside the revision's transaction: if any exist the
revision fails before anything is committed;
2. each constraint is only added if it does not exist yet (a re-run after a failed
VALIDATE finds them and goes straight to validation).
Offline (--sql) has no rows to look at and renders the statements unconditionally.
"""
checks = (
("room", op.f("ck_room_floor_not_null"), "floor IS NOT NULL"),
("booking", op.f("ck_booking_end_after_start"), "end_date > start_date"),
)
offline = op.get_context().as_sql
if not offline:
bind = op.get_bind()
for table, _, condition in checks:
bad = bind.execute(sa.text(f"SELECT count(*) FROM {table} WHERE NOT ({condition})")).scalar_one()
if bad:
raise RuntimeError(f"{bad} rows in {table} violate ({condition}); fix them (or re-run 0003) first")
for table, name, condition in checks:
exists = False
if not offline:
exists = op.get_bind().execute(
sa.text("SELECT 1 FROM pg_constraint WHERE conname = :n"), {"n": str(name)}
).first() is not None
if not exists:
op.create_check_constraint(name, table, condition, postgresql_not_valid=True)
with op.get_context().autocommit_block(): # commit, so the ACCESS EXCLUSIVE locks are released
op.execute("ALTER TABLE room VALIDATE CONSTRAINT ck_room_floor_not_null")
op.execute("ALTER TABLE booking VALIDATE CONSTRAINT ck_booking_end_after_start")
op.alter_column("room", "floor", existing_type=sa.Integer(), nullable=False)
op.drop_constraint(op.f("ck_room_floor_not_null"), "room", type_="check")
def downgrade() -> None:
with op.batch_alter_table("booking") as batch_op:
batch_op.drop_constraint(op.f("ck_booking_end_after_start"), type_="check")
with op.batch_alter_table("room") as batch_op:
batch_op.alter_column("floor", existing_type=sa.Integer(), nullable=True)"""indexes: composite, partial and expression indexes; drop a redundant one
Revision ID: 0005
Revises: 0004
Create Date: 2026-11-29 15:40:00
On PostgreSQL every index is built with CREATE INDEX CONCURRENTLY inside autocommit_block(),
because CONCURRENTLY cannot run inside a transaction block and a plain CREATE INDEX blocks
writes to the table for the whole build. On SQLite the same indexes are created normally.
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
revision: str = "0005"
down_revision: Union[str, Sequence[str], None] = "0004"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
ACTIVE = sa.text("cancelled_at IS NULL")
def _create_indexes(concurrently: bool) -> None:
kw = {"postgresql_concurrently": True} if concurrently else {}
op.create_index("ix_booking_room_id_start_date", "booking", ["room_id", "start_date"], **kw)
op.create_index(
"ix_booking_active_room",
"booking",
["room_id", "start_date", "end_date"],
sqlite_where=ACTIVE,
postgresql_where=ACTIVE,
**kw,
)
op.create_index("ix_user_email_lower", "user", [sa.text("lower(email)")], **kw)
# ix_booking_room_id is a left prefix of ix_booking_room_id_start_date: redundant.
op.drop_index("ix_booking_room_id", table_name="booking", **kw)
def upgrade() -> None:
if op.get_context().dialect.name == "postgresql":
# COMMIT the revision's transaction, run in autocommit, then BEGIN again.
with op.get_context().autocommit_block():
_create_indexes(concurrently=True)
else:
_create_indexes(concurrently=False)
def downgrade() -> None:
op.create_index("ix_booking_room_id", "booking", ["room_id"])
op.drop_index("ix_user_email_lower", table_name="user")
op.drop_index("ix_booking_active_room", table_name="booking")
op.drop_index("ix_booking_room_id_start_date", table_name="booking")"""create email_outbox with server defaults
Revision ID: 0006
Revises: 0005
Create Date: 2026-11-29 15:50:00
server_default values live in the database, so rows inserted by other code paths (a SQL
console, another service) get them too; compare_server_default=True lets autogenerate and
`alembic check` see when the model and the database disagree about them.
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
import sqlmodel
revision: str = "0006"
down_revision: Union[str, Sequence[str], None] = "0005"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.create_table(
"email_outbox",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("booking_id", sa.Integer(), nullable=False),
sa.Column("status", sqlmodel.sql.sqltypes.AutoString(length=20), server_default="pending", nullable=False),
sa.Column("created_at", sa.DateTime(), server_default=sa.text("(CURRENT_TIMESTAMP)"), nullable=False),
sa.Column("sent_at", sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(
["booking_id"], ["booking.id"], name=op.f("fk_email_outbox_booking_id_booking"), ondelete="CASCADE"
),
sa.PrimaryKeyConstraint("id", name=op.f("pk_email_outbox")),
)
op.create_index("ix_email_outbox_status_id", "email_outbox", ["status", "id"])
def downgrade() -> None:
op.drop_index("ix_email_outbox_status_id", table_name="email_outbox")
op.drop_table("email_outbox")The application side: the engine factory (with the SQLite BEGIN recipe as an option), the transaction patterns, the locking statements and a FastAPI app with three commit styles:
"""Engines and sessions for the application side (not for migrations, see migrations/env.py).
No `from __future__ import annotations`: FastAPI reads the dependency signatures at runtime.
"""
from typing import Any, Dict
from sqlalchemy import event
from sqlalchemy.engine import Engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
from sqlmodel import Session, create_engine
def _sqlite_foreign_keys_on(dbapi_connection: Any, connection_record: Any) -> None:
"""SQLite ships with foreign keys OFF per connection. The app wants them ON.
migrations/env.py builds its own engine WITHOUT this listener: batch mode drops and
recreates tables, and with foreign keys ON that DROP cascades into child tables.
"""
cursor = dbapi_connection.cursor()
cursor.execute("PRAGMA foreign_keys=ON")
cursor.close()
def _sqlite_driver_no_begin(dbapi_connection: Any, connection_record: Any) -> None:
# Python's sqlite3 (before 3.12's autocommit attribute) only BEGINs before DML;
# DDL, SELECT and SAVEPOINT run outside any transaction. Take over BEGIN ourselves.
dbapi_connection.isolation_level = None
def _emit_begin(conn: Any) -> None:
conn.exec_driver_sql("BEGIN")
def make_engine(
url: str = "sqlite://",
*,
foreign_keys: bool = True,
sqlite_real_transactions: bool = False,
echo: bool = False,
) -> Engine:
"""One engine per process.
sqlite_real_transactions=True applies the SQLAlchemy docs' recipe ("Serializable isolation /
Savepoints / Transactional DDL"): BEGIN is emitted by SQLAlchemy, so DDL and SAVEPOINT
become part of the transaction and roll back with it.
"""
kwargs: Dict[str, Any] = {"echo": echo}
if url.startswith("sqlite"):
kwargs["connect_args"] = {"check_same_thread": False}
if url in ("sqlite://", "sqlite:///:memory:"):
kwargs["poolclass"] = StaticPool
else: # server databases (expected, not run here)
kwargs.update(pool_size=5, max_overflow=10, pool_pre_ping=True)
engine = create_engine(url, **kwargs)
if url.startswith("sqlite"):
if foreign_keys:
event.listen(engine, "connect", _sqlite_foreign_keys_on)
if sqlite_real_transactions:
event.listen(engine, "connect", _sqlite_driver_no_begin)
event.listen(engine, "begin", _emit_begin)
return engine
def make_session_factory(engine: Engine, *, expire_on_commit: bool = True) -> sessionmaker:
"""sessionmaker bound to the engine; class_=Session gives SQLModel's .exec()."""
return sessionmaker(engine, class_=Session, expire_on_commit=expire_on_commit)"""Transaction patterns with the ORM Session: begin blocks, savepoints, isolation, retries."""
import datetime as dt
import logging
import time
from dataclasses import dataclass, field
from typing import Callable, Iterable, List, Optional, Tuple, TypeVar
from sqlalchemy.engine import Engine
from sqlalchemy.exc import DBAPIError, IntegrityError
from sqlalchemy.orm import sessionmaker
from sqlmodel import Session
from app.models import Booking, EmailOutbox
log = logging.getLogger("app.transactions")
T = TypeVar("T")
# SQLSTATEs that mean "the transaction was aborted, run it again from the start".
# 40001 serialization_failure, 40P01 deadlock_detected (PostgreSQL); MySQL reports
# 1213 (deadlock) and 1205 (lock wait timeout) as error codes instead.
RETRYABLE_SQLSTATES = {"40001", "40P01"}
RETRYABLE_MYSQL_CODES = {1213, 1205}
def create_booking_with_outbox(session: Session, room_id: int, start: dt.date, end: dt.date) -> Booking:
"""Booking row and outbox row commit together or not at all ("begin once" style)."""
with session.begin(): # BEGIN ... COMMIT on success, ROLLBACK on any exception
booking = Booking(room_id=room_id, start_date=start, end_date=end)
session.add(booking)
session.flush() # assigns booking.id, still inside the transaction
session.add(EmailOutbox(booking_id=booking.id))
return booking
@dataclass
class ImportResult:
imported: List[int] = field(default_factory=list)
skipped: List[Tuple[int, str]] = field(default_factory=list)
def import_bookings(session: Session, rows: Iterable[dict]) -> ImportResult:
"""One outer transaction; one SAVEPOINT per row, so a bad row does not fail the batch."""
result = ImportResult()
with session.begin():
for n, row in enumerate(rows):
try:
with session.begin_nested(): # SAVEPOINT sa_savepoint_N
session.add(Booking(**row))
session.flush() # constraint errors surface here, inside the savepoint
result.imported.append(n)
except IntegrityError as exc: # ROLLBACK TO SAVEPOINT already happened
result.skipped.append((n, str(exc.orig)))
return result
def isolation_of(engine: Engine, level: Optional[str] = None) -> str:
"""Read the effective isolation level of one connection, optionally set per connection."""
with engine.connect() as conn:
if level:
conn = conn.execution_options(isolation_level=level)
return conn.get_isolation_level()
def is_retryable(exc: BaseException) -> bool:
if not isinstance(exc, DBAPIError):
return False
orig = exc.orig
sqlstate = getattr(orig, "sqlstate", None) or getattr(orig, "pgcode", None) # asyncpg / psycopg
if sqlstate in RETRYABLE_SQLSTATES:
return True
args = getattr(orig, "args", ())
if args and isinstance(args[0], int) and args[0] in RETRYABLE_MYSQL_CODES: # PyMySQL / mysqlclient
return True
return "database is locked" in str(orig) # SQLite busy (not a serialization failure)
def run_in_transaction(
factory: sessionmaker,
work: Callable[[Session], T],
*,
attempts: int = 3,
backoff: float = 0.05,
) -> T:
"""Run `work` in a fresh Session + transaction; retry the WHOLE unit on retryable errors.
Retrying only the failed statement is wrong: the database aborted the transaction,
every read it made may be stale. A new Session, a new transaction, the same function.
"""
for attempt in range(1, attempts + 1):
try:
with factory() as session, session.begin():
return work(session)
except DBAPIError as exc:
if attempt == attempts or not is_retryable(exc):
raise
log.warning("retryable error on attempt %d: %s", attempt, exc.orig)
time.sleep(backoff * attempt)
raise AssertionError("unreachable")"""Pessimistic locking with SELECT ... FOR UPDATE from the ORM."""
from typing import List
from sqlalchemy import update
from sqlmodel import Session, select
from app.models import EmailOutbox, Room
def lock_room(room_id: int):
"""Serialise all bookings of one room: the second transaction waits on this row lock."""
return select(Room).where(Room.id == room_id).with_for_update()
def lock_room_nowait(room_id: int):
"""Fail at once (PostgreSQL 55P03 lock_not_available) instead of waiting."""
return select(Room).where(Room.id == room_id).with_for_update(nowait=True)
def next_outbox_batch(limit: int):
"""Queue pattern: every worker skips rows another worker has locked."""
return (
select(EmailOutbox)
.where(EmailOutbox.status == "pending")
.order_by(EmailOutbox.id)
.limit(limit)
.with_for_update(skip_locked=True)
)
def claim_outbox_batch(session: Session, limit: int = 10) -> List[int]:
"""Claim up to `limit` pending rows and mark them in the same transaction."""
with session.begin():
rows = session.exec(next_outbox_batch(limit)).all()
ids = [r.id for r in rows]
if ids:
session.execute(update(EmailOutbox).where(EmailOutbox.id.in_(ids)).values(status="sending"))
return ids"""A small FastAPI app that shows where the transaction boundary of a request lives.
- POST /bookings : session from a yield dependency, commit IN THE ROUTE (the KB default).
- POST /bookings/uow : unit-of-work dependency with Depends(scope="function") that commits
after the route returns and BEFORE the response is sent.
- POST /bookings/uow-late : the same dependency with the default scope (anti-pattern).
Schema: created by Alembic (tests run `upgrade head`), never by create_all here.
"""
import datetime as dt
from typing import Annotated, Iterator, List, Optional
from fastapi import Depends, FastAPI, HTTPException, Request
from sqlalchemy import and_
from sqlalchemy.engine import Engine
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import sessionmaker
from sqlmodel import Session, SQLModel, select
from app.db import make_session_factory
from app.locking import lock_room
from app.models import Booking, EmailOutbox
class BookingIn(SQLModel):
room_id: int
start_date: dt.date
end_date: dt.date
class BookingOut(SQLModel):
id: int
room_id: int
start_date: dt.date
end_date: dt.date
cancelled_at: Optional[dt.datetime] = None
def get_factory(request: Request) -> sessionmaker:
return request.app.state.session_factory
def get_session(factory: Annotated[sessionmaker, Depends(get_factory)]) -> Iterator[Session]:
"""Commit in the route; this dependency only rolls back on error and closes."""
with factory() as session:
try:
yield session
except Exception:
session.rollback()
raise
def get_uow(factory: Annotated[sessionmaker, Depends(get_factory)]) -> Iterator[Session]:
"""Unit of work per request: commit if the route returned, roll back if it raised.
Used with Depends(get_uow, scope="function") so the commit happens before the response
is sent and a failed commit still becomes an error response.
"""
with factory() as session:
try:
yield session
session.commit()
except Exception:
session.rollback()
raise
SessionDep = Annotated[Session, Depends(get_session)]
UowDep = Annotated[Session, Depends(get_uow, scope="function")]
# Anti-pattern kept for the test: the default scope ("request") runs the commit AFTER the
# response has been sent, so a failed commit cannot change the 201 the client already has.
LateUowDep = Annotated[Session, Depends(get_uow)]
def _overlaps(session: Session, data: BookingIn) -> bool:
stmt = select(Booking.id).where(
and_(
Booking.room_id == data.room_id,
Booking.cancelled_at.is_(None),
Booking.start_date < data.end_date,
Booking.end_date > data.start_date,
)
)
return session.exec(stmt).first() is not None
def _book(session: Session, data: BookingIn) -> Booking:
if session.exec(lock_room(data.room_id)).first() is None: # FOR UPDATE on PostgreSQL/MySQL
raise HTTPException(404, "Room not found")
if _overlaps(session, data):
raise HTTPException(409, "Room already booked for these dates")
booking = Booking.model_validate(data)
session.add(booking)
session.flush() # id assigned; CHECK constraint evaluated here
session.add(EmailOutbox(booking_id=booking.id))
return booking
def create_app(engine: Engine, *, expire_on_commit: bool = False) -> FastAPI:
app = FastAPI(title="Rooms (Alembic chapter)")
app.state.engine = engine
app.state.session_factory = make_session_factory(engine, expire_on_commit=expire_on_commit)
@app.post("/bookings", response_model=BookingOut, status_code=201)
def create_booking(data: BookingIn, session: SessionDep) -> Booking:
try:
booking = _book(session, data)
session.commit() # the status code reflects the commit
except IntegrityError as exc:
session.rollback()
raise HTTPException(422, f"Rejected by the database: {exc.orig}") from exc
return booking
@app.post("/bookings/uow", response_model=BookingOut, status_code=201)
def create_booking_uow(data: BookingIn, session: UowDep) -> Booking:
return _book(session, data) # no commit here: the dependency owns it
@app.post("/bookings/uow-late", response_model=BookingOut, status_code=201)
def create_booking_uow_late(data: BookingIn, session: LateUowDep) -> Booking:
return _book(session, data)
@app.get("/rooms/{room_id}/bookings", response_model=List[BookingOut])
def list_bookings(room_id: int, session: SessionDep) -> List[Booking]:
return list(session.exec(select(Booking).where(Booking.room_id == room_id).order_by(Booking.start_date)).all())
@app.get("/outbox/count")
def outbox_count(session: SessionDep) -> dict:
return {"pending": len(session.exec(select(EmailOutbox).where(EmailOutbox.status == "pending")).all())}
return appThe tests (70, all real). Shared fixtures, then migrations (upgrade, downgrade, stairway, backfill, stamp, check), autogenerate on separate MetaData copies, offline renders, branches, partial failure, the batch foreign-key trap, the async environment, transactions, locking and the HTTP API:
import io
import shutil
from pathlib import Path
from typing import Iterator
import pytest
from alembic import command
from alembic.config import Config
from sqlalchemy import inspect, text
from sqlalchemy.engine import Engine
from app.db import make_engine
PROJECT = Path(__file__).resolve().parents[1]
def make_config(url: str, script_location: Path = PROJECT / "migrations") -> Config:
"""An Alembic Config pointing at a file database; stdout captured for assertions."""
cfg = Config(str(PROJECT / "alembic.ini"), stdout=io.StringIO())
cfg.set_main_option("script_location", str(script_location))
cfg.set_main_option("sqlalchemy.url", url)
cfg.attributes["configure_logger"] = False # keep pytest's logging setup intact
return cfg
def output(cfg: Config) -> str:
buf = cfg.stdout
text_ = buf.getvalue()
buf.seek(0)
buf.truncate()
return text_
@pytest.fixture
def db_url(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> str:
# A FILE database: every connection of an in-memory SQLite database is a new, empty database.
url = f"sqlite:///{tmp_path / 'rooms.db'}"
monkeypatch.setenv("DATABASE_URL", url) # env.py reads it first
return url
@pytest.fixture
def cfg(db_url: str) -> Config:
return make_config(db_url)
@pytest.fixture
def migrated_engine(cfg: Config, db_url: str) -> Iterator[Engine]:
command.upgrade(cfg, "head")
engine = make_engine(db_url) # the application's engine: foreign keys ON
yield engine
engine.dispose()
@pytest.fixture
def scratch_migrations(tmp_path: Path) -> Path:
"""A private copy of migrations/ for tests that add revision files."""
dst = tmp_path / "migrations"
shutil.copytree(PROJECT / "migrations", dst, ignore=shutil.ignore_patterns("__pycache__"))
return dst
def schema_snapshot(engine: Engine) -> dict:
"""Tables as the inspector sees them plus every index's stored DDL from sqlite_master.
Table DDL text is NOT compared: a batch recreate writes CREATE TABLE "booking" (quoted,
constraints reordered), which is the same schema in different words. The inspector
skips expression indexes (with an SAWarning), so indexes come from sqlite_master.
"""
insp = inspect(engine)
snap: dict = {}
for t in sorted(insp.get_table_names()):
snap[t] = {
"columns": [(c["name"], str(c["type"]), c["nullable"], c["default"]) for c in insp.get_columns(t)],
"fks": sorted(
(fk["name"] or "", tuple(fk["constrained_columns"]), fk["referred_table"], str(fk["options"]))
for fk in insp.get_foreign_keys(t)
),
"checks": sorted((c["name"] or "", c["sqltext"]) for c in insp.get_check_constraints(t)),
"pk": insp.get_pk_constraint(t)["constrained_columns"],
}
with engine.connect() as conn:
snap["indexes"] = conn.execute(text(
"SELECT name, tbl_name, sql FROM sqlite_master WHERE type = 'index' AND sql IS NOT NULL ORDER BY name"
)).all()
return snap
def seed_at_0003(engine: Engine) -> None:
"""Rows as the 0003-era app would write them (floor may be NULL)."""
with engine.begin() as conn:
conn.execute(text(
"INSERT INTO room (id, name, capacity, price_cents, version, floor) VALUES "
"(1, 'Garden', 2, 9000, 1, 0), (2, 'Loft', 3, 12000, 1, 0), (3, 'Studio', 1, 6000, 1, 0)"
))
conn.execute(text(
"INSERT INTO booking (room_id, start_date, end_date, guests) VALUES "
"(1, '2026-12-01', '2026-12-04', 2), (1, '2026-12-10', '2026-12-12', 1), (2, '2026-12-02', '2026-12-05', 3)"
))"""Real Alembic runs against a SQLite file: upgrade, downgrade, stairway, data, stamp, check."""
import logging
import pytest
from alembic import command
from alembic.script import ScriptDirectory
from sqlalchemy import inspect, text
from sqlmodel import SQLModel
from app.db import make_engine
from tests.conftest import make_config, output, schema_snapshot, seed_at_0003
REVISIONS = ["0001", "0002", "0003", "0004", "0005", "0006"]
def test_revision_chain_is_linear(cfg):
script = ScriptDirectory.from_config(cfg)
assert script.get_heads() == ["0006"]
assert [r.revision for r in reversed(list(script.walk_revisions()))] == REVISIONS
def test_upgrade_head_builds_the_schema(migrated_engine):
insp = inspect(migrated_engine)
assert sorted(insp.get_table_names()) == ["alembic_version", "booking", "email_outbox", "room", "user"]
floor = next(c for c in insp.get_columns("room") if c["name"] == "floor")
assert floor["nullable"] is False
assert sorted(i["name"] for i in insp.get_indexes("booking")) == [
"ix_booking_active_room",
"ix_booking_room_id_start_date",
]
assert [c["name"] for c in insp.get_check_constraints("booking")] == ["ck_booking_end_after_start"]
with migrated_engine.connect() as conn:
assert conn.execute(text("SELECT version_num FROM alembic_version")).scalar_one() == "0006"
# SQLite keeps the partial index's WHERE clause in its stored DDL
ddl = conn.execute(text("SELECT sql FROM sqlite_master WHERE name = 'ix_booking_active_room'")).scalar_one()
assert ddl.endswith("WHERE cancelled_at IS NULL")
def test_downgrade_base_leaves_only_the_version_table(cfg, db_url):
command.upgrade(cfg, "head")
command.downgrade(cfg, "base")
engine = make_engine(db_url)
assert inspect(engine).get_table_names() == ["alembic_version"]
with engine.connect() as conn:
assert conn.execute(text("SELECT count(*) FROM alembic_version")).scalar_one() == 0
engine.dispose()
def test_upgrade_downgrade_round_trip_restores_the_same_schema(cfg, db_url):
command.upgrade(cfg, "head")
engine = make_engine(db_url)
at_head = schema_snapshot(engine)
command.downgrade(cfg, "base")
command.upgrade(cfg, "head")
assert schema_snapshot(engine) == at_head
engine.dispose()
@pytest.mark.parametrize("rev", REVISIONS)
def test_stairway_each_revision_up_down_up(cfg, db_url, rev):
"""Every single step: upgrade to rev, downgrade -1, upgrade again, same schema."""
command.upgrade(cfg, rev)
engine = make_engine(db_url)
before = schema_snapshot(engine)
command.downgrade(cfg, "-1")
command.upgrade(cfg, "+1")
assert schema_snapshot(engine) == before
engine.dispose()
def test_backfill_is_a_data_migration_in_batches(cfg, db_url, caplog):
command.upgrade(cfg, "0002")
engine = make_engine(db_url)
with engine.begin() as conn: # rows written by the old app: floor is NULL
for i in range(5):
conn.execute(text(f"INSERT INTO room (name, capacity, price_cents, version) VALUES ('r{i}', 2, 100, 1)"))
caplog.set_level(logging.INFO, logger="alembic.data")
command.upgrade(cfg, "0003")
assert "backfilled room.floor in 3 batches of up to 2 rows" in caplog.text
with engine.connect() as conn:
assert conn.execute(text("SELECT count(*) FROM room WHERE floor IS NULL")).scalar_one() == 0
engine.dispose()
def test_contract_step_refuses_rows_that_were_not_backfilled(cfg, db_url):
command.upgrade(cfg, "0003")
engine = make_engine(db_url)
with engine.begin() as conn: # an old replica wrote a row after the backfill
conn.execute(text("INSERT INTO room (name, capacity, price_cents, version) VALUES ('late', 1, 1, 1)"))
with pytest.raises(Exception) as err:
command.upgrade(cfg, "0004")
assert "NOT NULL constraint failed: _alembic_tmp_room.floor" in str(err.value)
engine.dispose()
def test_contract_on_populated_tables_keeps_child_rows(cfg, db_url):
command.upgrade(cfg, "0003")
engine = make_engine(db_url)
seed_at_0003(engine)
command.upgrade(cfg, "head") # batch mode recreates room and booking
with engine.connect() as conn:
assert conn.execute(text("SELECT count(*) FROM room")).scalar_one() == 3
assert conn.execute(text("SELECT count(*) FROM booking")).scalar_one() == 3
engine.dispose()
def test_downgrade_minus_one_and_current(cfg):
command.upgrade(cfg, "head")
output(cfg)
command.downgrade(cfg, "-1")
command.current(cfg)
assert output(cfg).strip() == "0005"
def test_history_and_heads(cfg):
command.history(cfg)
hist = output(cfg)
assert "0005 -> 0006 (head), create email_outbox with server defaults" in hist
assert "<base> -> 0001, create user room booking" in hist
command.heads(cfg)
assert output(cfg).strip() == "0006 (head)"
def test_stamp_adopts_a_database_built_by_create_all(db_url):
"""A database created by create_all() has no alembic_version: stamp it, then check it."""
import app.models # noqa: F401
engine = make_engine(db_url)
SQLModel.metadata.create_all(engine)
cfg = make_config(db_url)
command.current(cfg)
assert output(cfg).strip() == "" # no version row: Alembic does not know this database
command.stamp(cfg, "head") # writes 0006 into alembic_version, runs no DDL
command.current(cfg)
assert output(cfg).strip() == "0006 (head)"
with pytest.warns(UserWarning, match="expression-based index 'ix_user_email_lower'"):
command.check(cfg) # models == database
engine.dispose()
def test_alembic_check_is_clean_at_head_but_warns_about_expression_index(cfg):
command.upgrade(cfg, "head")
with pytest.warns(UserWarning, match="can't reflect these indexes so they can't be compared"):
command.check(cfg)
assert "No new upgrade operations detected." in output(cfg)
def test_alembic_check_fails_when_the_database_is_behind(cfg):
from alembic.util.exc import CommandError
command.upgrade(cfg, "0005")
with pytest.raises(CommandError, match="Target database is not up to date."):
command.check(cfg)
def test_env_session_setup_is_committed_before_configure(cfg, db_url):
"""env.py runs SESSION_SETUP (PRAGMA foreign_keys=OFF here, SET lock_timeout on PostgreSQL)
before context.configure() and commits it. Without that commit the autobegun transaction
is treated as the caller's: exit 0, nothing recorded (real probe in the chapter)."""
command.upgrade(cfg, "head")
engine = make_engine(db_url)
with engine.connect() as conn:
assert conn.execute(text("SELECT version_num FROM alembic_version")).scalar_one() == "0006"
assert "email_outbox" in inspect(engine).get_table_names()
engine.dispose()"""What autogenerate detects and what it misses (Alembic 1.16.5, SQLite), on SEPARATE MetaData copies."""
import pytest
import sqlalchemy as sa
from alembic.autogenerate import compare_metadata
from alembic.migration import MigrationContext
from alembic.operations import Operations
from sqlalchemy import CheckConstraint, Column, Integer, MetaData, String, Table, UniqueConstraint, text
from app.db import make_engine
from app.models import NAMING_CONVENTION
def room_table(md: MetaData, *, name_type=String(100), price_col="price_cents", extra=()):
return Table(
"room",
md,
Column("id", Integer, primary_key=True),
Column("name", name_type, nullable=False),
Column(price_col, Integer, nullable=False),
*extra,
)
@pytest.fixture
def engine(tmp_path):
eng = make_engine(f"sqlite:///{tmp_path / 'ag.db'}")
room_table(MetaData()).create(eng) # "the database"
yield eng
eng.dispose()
def diff(engine, md, **opts):
with engine.connect() as conn:
ctx = MigrationContext.configure(conn, opts=opts)
return compare_metadata(ctx, md)
def kinds(d):
return [op[0][0] if isinstance(op, list) else op[0] for op in d]
def test_type_change_is_detected_compare_type_defaults_to_true(engine):
d = diff(engine, room_table(MetaData(), name_type=String(200)).metadata)
assert kinds(d) == ["modify_type"]
assert "VARCHAR(length=100), String(length=200)" in repr(d)
def test_type_change_ignored_with_compare_type_false(engine):
assert diff(engine, room_table(MetaData(), name_type=String(200)).metadata, compare_type=False) == []
def test_rename_is_not_detected_it_becomes_add_plus_remove(engine):
d = diff(engine, room_table(MetaData(), price_col="price").metadata)
assert sorted(kinds(d)) == ["add_column", "remove_column"] # data loss if applied as is
def test_server_default_needs_compare_server_default(engine):
md = room_table(MetaData(), extra=(Column("status", String(20), server_default="active"),)).metadata
with engine.begin() as conn:
conn.execute(text("ALTER TABLE room ADD COLUMN status VARCHAR(20) DEFAULT 'inactive'"))
assert diff(engine, md) == [] # compare_server_default is False by default
d = diff(engine, md, compare_server_default=True)
assert kinds(d) == ["modify_default"]
def test_named_check_constraint_is_not_detected_by_1_16(engine):
"""Alembic 1.19.0 added name-based CHECK detection; the pinned 1.16.5 does not have it."""
md = room_table(MetaData(), extra=(CheckConstraint("price_cents >= 0", name="ck_room_price"),)).metadata
assert diff(engine, md) == []
def test_unique_constraint_add_is_detected(engine):
md = room_table(MetaData(naming_convention=NAMING_CONVENTION), extra=(UniqueConstraint("name"),)).metadata
d = diff(engine, md)
assert kinds(d) == ["add_constraint"]
assert d[0][1].name == "uq_room_name" # named by the convention, so it can be dropped later
def test_naming_convention_names_every_constraint():
plain = room_table(MetaData(), extra=(UniqueConstraint("name"),))
named = room_table(MetaData(naming_convention=NAMING_CONVENTION), extra=(UniqueConstraint("name"),))
assert [c.name for c in plain.constraints if isinstance(c, UniqueConstraint)] == [None]
assert [c.name for c in named.constraints if isinstance(c, UniqueConstraint)] == ["uq_room_name"]
assert named.primary_key.name == "pk_room"
def test_not_null_column_without_default_fails_on_existing_rows(engine):
"""What a naive autogenerated add_column(nullable=False) does to a populated table."""
with engine.begin() as conn:
conn.execute(text("INSERT INTO room (name, price_cents) VALUES ('Garden', 9000)"))
with engine.begin() as conn:
op = Operations(MigrationContext.configure(conn))
with pytest.raises(sa.exc.OperationalError, match="Cannot add a NOT NULL column with default value NULL"):
op.add_column("room", Column("floor", Integer, nullable=False))
def test_sqlite_alter_limitations_and_batch_mode(engine):
import sqlite3
with engine.begin() as conn:
op = Operations(MigrationContext.configure(conn))
# Changing a column type has no ALTER form in SQLite at all.
with pytest.raises(sa.exc.OperationalError, match='near "TYPE": syntax error'):
op.alter_column("room", "name", existing_type=String(100), type_=String(200))
# Constraints cannot be added or dropped with ALTER either; Alembic refuses up front.
with pytest.raises(NotImplementedError, match="No support for ALTER of constraints in SQLite dialect"):
op.drop_constraint("uq_room_name", "room", type_="unique")
# SET/DROP NOT NULL arrived in SQLite 3.53.0 (2026-04-09); older SQLite fails here too.
if sqlite3.sqlite_version_info >= (3, 53, 0):
op.alter_column("room", "name", existing_type=String(100), nullable=True)
# Batch mode ("move and copy") does all of it on any SQLite version.
with op.batch_alter_table("room") as batch_op:
batch_op.alter_column("name", existing_type=String(100), type_=String(200), nullable=False)
with engine.connect() as conn:
row = conn.execute(text("SELECT type, [notnull] FROM pragma_table_info('room') WHERE name = 'name'")).one()
assert tuple(row) == ("VARCHAR(200)", 1)"""Offline mode (--sql): Alembic renders the script for a dialect without connecting to it.
The PostgreSQL and MySQL outputs below are real renders by Alembic 1.16.5; nothing ran on a
PostgreSQL or MySQL server.
"""
import io
from alembic import command
from tests.conftest import make_config
def render(monkeypatch, url: str, rng: str = "head") -> str:
monkeypatch.setenv("DATABASE_URL", url)
buf = io.StringIO()
cfg = make_config(url)
cfg.output_buffer = buf
command.upgrade(cfg, rng, sql=True)
return buf.getvalue()
def test_postgresql_script_is_transactional_per_revision(monkeypatch):
sql = render(monkeypatch, "postgresql://app@localhost/rooms")
assert sql.startswith("SET lock_timeout = '5s';")
assert sql.count("BEGIN;") == 8 and sql.count("COMMIT;") == 8 # 6 revisions + 2 autocommit blocks
assert "ALTER TABLE room ALTER COLUMN floor SET NOT NULL;" in sql
def test_postgresql_concurrently_runs_outside_the_transaction(monkeypatch):
sql = render(monkeypatch, "postgresql://app@localhost/rooms", "0004:0005")
body = sql[sql.index("-- Running upgrade 0004 -> 0005"):]
assert body.index("COMMIT;") < body.index("CREATE INDEX CONCURRENTLY ix_booking_room_id_start_date")
assert "CREATE INDEX CONCURRENTLY ix_booking_active_room ON booking (room_id, start_date, end_date) WHERE cancelled_at IS NULL;" in body
assert 'CREATE INDEX CONCURRENTLY ix_user_email_lower ON "user" (lower(email));' in body
assert "DROP INDEX CONCURRENTLY ix_booking_room_id;" in body
def test_postgresql_not_valid_then_validate(monkeypatch):
sql = render(monkeypatch, "postgresql://app@localhost/rooms", "0003:0004")
assert "ADD CONSTRAINT ck_room_floor_not_null CHECK (floor IS NOT NULL) NOT VALID;" in sql
assert sql.index("NOT VALID") < sql.index("COMMIT;") < sql.index("VALIDATE CONSTRAINT ck_room_floor_not_null")
def test_mysql_script_has_no_transaction_and_loses_the_partial_index(monkeypatch):
sql = render(monkeypatch, "mysql+pymysql://app@localhost/rooms")
assert "BEGIN;" not in sql # non-transactional DDL: each statement commits implicitly
assert "CREATE INDEX ix_booking_active_room ON booking (room_id, start_date, end_date);" in sql # no WHERE
# MySQL wants functional key parts in their own parentheses: ((lower(email))). Expected to fail there.
assert "CREATE INDEX ix_user_email_lower ON user (lower(email));" in sql
def test_offline_backfill_is_one_set_based_update(monkeypatch):
sql = render(monkeypatch, "postgresql://app@localhost/rooms", "0002:0003")
assert "UPDATE room SET floor=0 WHERE room.floor IS NULL;" in sql"""Two developers branch from the same head: multiple heads, then a merge revision."""
import pytest
from alembic import command
from alembic.script import ScriptDirectory
from alembic.util.exc import CommandError
from tests.conftest import make_config, output
@pytest.fixture
def bcfg(db_url, scratch_migrations):
return make_config(db_url, scratch_migrations)
def test_two_heads_block_upgrade_head_until_merged(bcfg):
command.upgrade(bcfg, "head")
# Both branches were created from 0006 on two feature branches.
command.revision(bcfg, "add room notes", rev_id="a1b2", head="0006")
command.revision(bcfg, "add booking source", rev_id="c3d4", head="0006", splice=True)
output(bcfg)
command.heads(bcfg)
assert sorted(output(bcfg).split("\n")[:2]) == ["a1b2 (head)", "c3d4 (head)"]
with pytest.raises(CommandError, match="Multiple head revisions are present for given argument 'head'"):
command.upgrade(bcfg, "head")
merge = command.merge(bcfg, "heads", message="merge notes and source", rev_id="e5f6")
assert set(merge.down_revision) == {"a1b2", "c3d4"}
script = ScriptDirectory.from_config(bcfg)
assert script.get_heads() == ["e5f6"]
command.upgrade(bcfg, "head")
command.current(bcfg)
assert output(bcfg).strip().endswith("e5f6 (head) (mergepoint)")
def test_upgrade_heads_applies_both_branches_without_merging(bcfg):
command.upgrade(bcfg, "head")
command.revision(bcfg, "a", rev_id="a1b2", head="0006")
command.revision(bcfg, "b", rev_id="c3d4", head="0006", splice=True)
command.upgrade(bcfg, "heads")
output(bcfg)
command.current(bcfg)
assert sorted(output(bcfg).split()) == sorted(["a1b2", "(head)", "c3d4", "(head)"])"""A revision that fails halfway. What is left behind depends on the engine AND the driver mode."""
import textwrap
import pytest
from alembic import command
from sqlalchemy import inspect, text
from app.db import make_engine
from tests.conftest import make_config
BROKEN = '''
"""broken: adds a column, then fails
Revision ID: 0007
Revises: 0006
"""
from alembic import op
import sqlalchemy as sa
revision = "0007"
down_revision = "0006"
branch_labels = None
depends_on = None
def upgrade():
op.add_column("room", sa.Column("note", sa.String(200), nullable=True))
op.execute("UPDATE no_such_table SET x = 1") # the bug
def downgrade():
op.drop_column("room", "note")
'''
@pytest.fixture
def broken_cfg(db_url, scratch_migrations):
(scratch_migrations / "versions" / "0007_broken.py").write_text(textwrap.dedent(BROKEN))
cfg = make_config(db_url, scratch_migrations)
command.upgrade(cfg, "0006")
return cfg
def state(db_url):
engine = make_engine(db_url)
cols = [c["name"] for c in inspect(engine).get_columns("room")]
with engine.connect() as conn:
version = conn.execute(text("SELECT version_num FROM alembic_version")).scalar_one()
engine.dispose()
return "note" in cols, version
def test_sqlite_default_driver_mode_leaves_a_half_applied_revision(broken_cfg, db_url):
with pytest.raises(Exception, match="no such table: no_such_table"):
command.upgrade(broken_cfg, "head")
# The ALTER TABLE was autocommitted by Python's sqlite3 (no BEGIN before DDL);
# alembic_version still says 0006, so a re-run fails with "duplicate column name: note".
assert state(db_url) == (True, "0006")
with pytest.raises(Exception, match="duplicate column name: note"):
command.upgrade(broken_cfg, "head")
def test_sqlite_with_real_begin_rolls_the_whole_revision_back(broken_cfg, db_url):
engine = make_engine(db_url, foreign_keys=False, sqlite_real_transactions=True)
with engine.connect() as conn:
broken_cfg.attributes["connection"] = conn
with pytest.raises(Exception, match="no such table: no_such_table"):
command.upgrade(broken_cfg, "head")
engine.dispose()
assert state(db_url) == (False, "0006") # transactional DDL: nothing left behind"""Batch mode drops and recreates the table. With SQLite foreign keys ON that DROP cascades."""
from alembic import command
from sqlalchemy import text
from app.db import make_engine
from tests.conftest import seed_at_0003
def count(engine, table):
with engine.connect() as conn:
return conn.execute(text(f"SELECT count(*) FROM {table}")).scalar_one()
def test_batch_with_foreign_keys_on_deletes_child_rows(cfg, db_url):
command.upgrade(cfg, "0003")
app_engine = make_engine(db_url) # PRAGMA foreign_keys=ON, as the application uses it
seed_at_0003(app_engine)
with app_engine.connect() as conn:
cfg.attributes["connection"] = conn # WRONG: migrate through the app's engine
command.upgrade(cfg, "0004")
conn.commit()
assert count(app_engine, "room") == 3
assert count(app_engine, "booking") == 0 # DROP TABLE room -> ON DELETE CASCADE
app_engine.dispose()
def test_batch_with_the_migration_engine_keeps_child_rows(cfg, db_url):
command.upgrade(cfg, "0003")
app_engine = make_engine(db_url)
seed_at_0003(app_engine)
command.upgrade(cfg, "0004") # env.py's own engine: foreign keys OFF during the copy
assert count(app_engine, "booking") == 3
with app_engine.connect() as conn: # ...and the foreign keys are intact afterwards
assert conn.execute(text("PRAGMA foreign_key_check")).all() == []
app_engine.dispose()"""The async branch of env.py: an aiosqlite URL runs the same revisions via run_sync()."""
from alembic import command
from tests.conftest import make_config, output
def test_async_url_upgrades_and_downgrades(tmp_path, monkeypatch):
url = f"sqlite+aiosqlite:///{tmp_path / 'async.db'}"
monkeypatch.setenv("DATABASE_URL", url)
cfg = make_config(url)
command.upgrade(cfg, "head")
command.current(cfg)
assert output(cfg).strip() == "0006 (head)"
command.downgrade(cfg, "base")
command.current(cfg)
assert output(cfg).strip() == """""Session.begin(), savepoints, expire_on_commit, isolation levels and retries (SQLite, real)."""
import datetime as dt
import sqlite3
import threading
import pytest
from sqlalchemy import event, text
from sqlalchemy.exc import DBAPIError, IntegrityError, OperationalError
from sqlmodel import Session, select
from app.db import make_engine, make_session_factory
from app.models import Booking, Room
from app.transactions import (
create_booking_with_outbox,
import_bookings,
is_retryable,
isolation_of,
run_in_transaction,
)
D = dt.date
@pytest.fixture
def rooms(migrated_engine):
with Session(migrated_engine) as s, s.begin():
s.add_all([Room(id=1, name="Garden", capacity=2, price_cents=9000, floor=0),
Room(id=2, name="Loft", capacity=3, price_cents=12000, floor=1)])
return migrated_engine
def counts(engine):
with engine.connect() as c:
return (c.execute(text("SELECT count(*) FROM booking")).scalar_one(),
c.execute(text("SELECT count(*) FROM email_outbox")).scalar_one())
def test_begin_block_commits_booking_and_outbox_together(rooms):
with Session(rooms) as s:
b = create_booking_with_outbox(s, 1, D(2026, 12, 1), D(2026, 12, 3))
assert b.id == 1 # expired by the commit: this read sends a SELECT, fine inside the session
assert counts(rooms) == (1, 1)
def test_object_used_after_commit_and_close_is_detached(rooms):
from sqlalchemy.orm.exc import DetachedInstanceError
with Session(rooms) as s:
b = create_booking_with_outbox(s, 1, D(2026, 12, 1), D(2026, 12, 3))
with pytest.raises(DetachedInstanceError, match="is not bound to a Session; attribute refresh operation cannot proceed"):
_ = b.id # expire_on_commit=True (the default) + closed session
def test_begin_block_rolls_back_both_rows_on_a_constraint_error(rooms):
with Session(rooms) as s, pytest.raises(IntegrityError, match="CHECK constraint failed: ck_booking_end_after_start"):
create_booking_with_outbox(s, 1, D(2026, 12, 3), D(2026, 12, 1))
assert counts(rooms) == (0, 0)
ROWS = [
dict(room_id=1, start_date=D(2026, 12, 1), end_date=D(2026, 12, 2)),
dict(room_id=1, start_date=D(2026, 12, 5), end_date=D(2026, 12, 4)), # violates the CHECK
dict(room_id=999, start_date=D(2026, 12, 5), end_date=D(2026, 12, 6)), # violates the FK
dict(room_id=2, start_date=D(2026, 12, 5), end_date=D(2026, 12, 6)),
]
@pytest.fixture
def recipe_engine(rooms, db_url):
"""Same database, but SQLAlchemy emits BEGIN itself: SAVEPOINTs join the transaction."""
engine = make_engine(db_url, sqlite_real_transactions=True)
yield engine
engine.dispose()
def test_savepoint_per_row_skips_bad_rows_and_keeps_good_ones(recipe_engine):
statements = []
event.listen(recipe_engine, "before_cursor_execute", lambda *a: statements.append(a[2].split()[0]))
with Session(recipe_engine) as s:
result = import_bookings(s, ROWS)
assert result.imported == [0, 3]
assert [n for n, _ in result.skipped] == [1, 2]
assert result.skipped[0][1] == "CHECK constraint failed: ck_booking_end_after_start"
assert result.skipped[1][1] == "FOREIGN KEY constraint failed"
assert statements[0] == "BEGIN"
assert statements.count("SAVEPOINT") == 4 and statements.count("ROLLBACK") == 2 # ROLLBACK TO SAVEPOINT
assert counts(recipe_engine) == (2, 0)
def outer_failure_after_savepoints(engine):
with Session(engine) as s:
with pytest.raises(RuntimeError):
with s.begin():
for row in (ROWS[0], ROWS[3]):
with s.begin_nested():
s.add(Booking(**row))
s.flush()
raise RuntimeError("outer failure after the loop")
return counts(engine)[0]
def test_outer_rollback_undoes_released_savepoints_with_the_begin_recipe(recipe_engine):
assert outer_failure_after_savepoints(recipe_engine) == 0
def test_outer_rollback_does_not_undo_savepoints_in_default_sqlite3_mode(rooms):
"""No BEGIN is ever sent (the first statement is SAVEPOINT), so each released savepoint
is its own transaction: the "atomic" import is not atomic on default pysqlite."""
assert outer_failure_after_savepoints(rooms) == 2
def test_sqlite_legacy_mode_savepoint_escapes_the_outer_rollback(tmp_path):
"""The SQLAlchemy docs' warning, reproduced: without the BEGIN recipe a SAVEPOINT issued
before any DML is its own transaction, and an outer ROLLBACK does not undo it."""
url = f"sqlite:///{tmp_path / 'sp.db'}"
results = {}
for mode, real in (("legacy", False), ("recipe", True)):
engine = make_engine(url, sqlite_real_transactions=real)
with engine.begin() as c:
c.exec_driver_sql("DROP TABLE IF EXISTS t")
c.exec_driver_sql("CREATE TABLE t (x INTEGER)")
with engine.connect() as conn:
trans = conn.begin()
with conn.begin_nested(): # SAVEPOINT ... RELEASE SAVEPOINT
conn.exec_driver_sql("INSERT INTO t VALUES (1)")
trans.rollback() # should undo everything
with engine.connect() as c:
results[mode] = c.exec_driver_sql("SELECT count(*) FROM t").scalar_one()
engine.dispose()
assert results == {"legacy": 1, "recipe": 0}
def test_expire_on_commit_true_reloads_false_does_not(rooms):
seen = []
def count(*args):
seen.append(args[2])
event.listen(rooms, "before_cursor_execute", count)
try:
for expire, extra_selects in ((True, 1), (False, 0)):
with make_session_factory(rooms, expire_on_commit=expire)() as s:
room = s.get(Room, 1)
s.commit()
seen.clear()
assert room.name == "Garden"
assert len(seen) == extra_selects, (expire, seen)
finally:
event.remove(rooms, "before_cursor_execute", count)
def test_isolation_level_per_connection(migrated_engine):
assert isolation_of(migrated_engine) == "SERIALIZABLE" # SQLite's default as reported by pysqlite
assert isolation_of(migrated_engine, "READ UNCOMMITTED") == "READ UNCOMMITTED" # PRAGMA read_uncommitted
# AUTOCOMMIT is a driver mode, not a database level: the database still reports SERIALIZABLE.
with migrated_engine.connect() as conn:
auto = conn.execution_options(isolation_level="AUTOCOMMIT")
assert auto.get_isolation_level() == "SERIALIZABLE"
assert auto.get_execution_options()["isolation_level"] == "AUTOCOMMIT"
with pytest.raises(Exception, match="Invalid value 'REPEATABLE READ' for isolation_level"):
isolation_of(migrated_engine, "REPEATABLE READ")
class FakePgError(Exception):
sqlstate = "40001" # psycopg 3 / asyncpg expose the SQLSTATE like this
def test_is_retryable_by_sqlstate_and_message():
assert is_retryable(DBAPIError("UPDATE ...", {}, FakePgError("could not serialize access")))
assert is_retryable(OperationalError("INSERT ...", {}, sqlite3.OperationalError("database is locked")))
assert not is_retryable(IntegrityError("INSERT ...", {}, sqlite3.IntegrityError("UNIQUE constraint failed")))
def test_retry_whole_unit_of_work_while_another_writer_holds_the_lock(tmp_path, cfg, db_url, caplog):
from alembic import command
command.upgrade(cfg, "head")
holder = sqlite3.connect(str(tmp_path / "rooms.db"), isolation_level=None, check_same_thread=False)
holder.execute("BEGIN IMMEDIATE") # takes SQLite's write lock
holder.execute("INSERT INTO room (name, capacity, price_cents, floor, version) VALUES ('Held', 1, 1, 0, 1)")
threading.Timer(0.25, holder.commit).start() # the other writer finishes a bit later
# timeout=0: do not wait in the driver's busy handler, fail with "database is locked".
fast_fail = make_engine(db_url + "?timeout=0")
attempts = []
def work(session):
attempts.append(1)
session.add(Room(name="Retried", capacity=1, price_cents=1, floor=0))
session.flush()
return session.exec(select(Room.id).where(Room.name == "Retried")).one()
room_id = run_in_transaction(make_session_factory(fast_fail), work, attempts=10, backoff=0.05)
assert room_id and len(attempts) >= 2
assert "retryable error on attempt 1: database is locked" in caplog.text
holder.close()
fast_fail.dispose()"""SELECT ... FOR UPDATE variants: the SQL each dialect gets (compiled, real) and a queue claim on SQLite.
Lock waits, NOWAIT errors and SKIP LOCKED behaviour need PostgreSQL or MySQL: expected, not run.
"""
import pytest
from sqlalchemy.dialects import mysql, postgresql, sqlite
from sqlmodel import Session, select
from app.locking import claim_outbox_batch, lock_room, lock_room_nowait, next_outbox_batch
from app.models import Booking, EmailOutbox, Room
def sql(stmt, dialect) -> str:
return " ".join(str(stmt.compile(dialect=dialect)).split())
@pytest.mark.parametrize(
"stmt, pg, my, lite",
[
(lock_room(1), "FOR UPDATE", "FOR UPDATE", ""),
(lock_room_nowait(1), "FOR UPDATE NOWAIT", "FOR UPDATE NOWAIT", ""),
(next_outbox_batch(10), "FOR UPDATE SKIP LOCKED", "FOR UPDATE SKIP LOCKED", ""),
(select(Room).where(Room.id == 1).with_for_update(read=True), "FOR SHARE", "LOCK IN SHARE MODE", ""),
(select(Room).where(Room.id == 1).with_for_update(key_share=True), "FOR NO KEY UPDATE", "FOR UPDATE", ""),
],
)
def test_lock_clause_per_dialect(stmt, pg, my, lite):
assert sql(stmt, postgresql.dialect()).endswith(pg)
assert sql(stmt, mysql.dialect()).endswith(my)
assert "FOR UPDATE" not in sql(stmt, sqlite.dialect()) # SQLite has no row locks: silently omitted
def test_for_update_of_one_table_in_a_join():
stmt = select(Booking, Room).join(Room).where(Room.id == 1).with_for_update(of=Room)
assert sql(stmt, postgresql.dialect()).endswith("FOR UPDATE OF room")
def test_full_queue_claim_statement_on_postgresql():
assert sql(next_outbox_batch(10), postgresql.dialect()) == (
"SELECT email_outbox.id, email_outbox.booking_id, email_outbox.status, email_outbox.created_at, "
"email_outbox.sent_at FROM email_outbox WHERE email_outbox.status = %(status_1)s "
"ORDER BY email_outbox.id LIMIT %(param_1)s FOR UPDATE SKIP LOCKED"
)
def test_claim_outbox_batch_marks_rows_in_the_same_transaction(migrated_engine):
import datetime as dt
with Session(migrated_engine) as s, s.begin():
s.add(Room(id=1, name="Garden", capacity=2, price_cents=1, floor=0))
s.flush()
for d in range(1, 6):
b = Booking(room_id=1, start_date=dt.date(2026, 12, d), end_date=dt.date(2026, 12, d + 1))
s.add(b)
s.flush()
s.add(EmailOutbox(booking_id=b.id))
with Session(migrated_engine) as s:
assert claim_outbox_batch(s, 3) == [1, 2, 3]
with Session(migrated_engine) as s:
assert claim_outbox_batch(s, 3) == [4, 5]
assert s.exec(select(EmailOutbox.status).distinct()).all() == ["sending"]"""Transaction boundary per request: commit in the route vs a unit-of-work dependency."""
import pytest
from fastapi.testclient import TestClient
from sqlalchemy import event
from sqlmodel import Session
from app.main import create_app
from app.models import Room
@pytest.fixture
def engine(migrated_engine):
with Session(migrated_engine) as s, s.begin():
s.add(Room(id=1, name="Garden", capacity=2, price_cents=9000, floor=0))
return migrated_engine
@pytest.fixture
def client(engine):
with TestClient(create_app(engine)) as c:
yield c
BODY = {"room_id": 1, "start_date": "2026-12-01", "end_date": "2026-12-04"}
def test_commit_in_route_creates_booking_and_outbox_row(client):
r = client.post("/bookings", json=BODY)
assert r.status_code == 201 and r.json()["id"] == 1
assert client.get("/outbox/count").json() == {"pending": 1}
def test_overlap_is_409_and_nothing_is_written(client):
client.post("/bookings", json=BODY)
r = client.post("/bookings", json={**BODY, "start_date": "2026-12-03", "end_date": "2026-12-05"})
assert r.status_code == 409
assert len(client.get("/rooms/1/bookings").json()) == 1
assert client.get("/outbox/count").json() == {"pending": 1}
def test_database_check_constraint_becomes_422(client):
r = client.post("/bookings", json={**BODY, "end_date": "2026-11-30"})
assert r.status_code == 422
assert r.json() == {"detail": "Rejected by the database: CHECK constraint failed: ck_booking_end_after_start"}
assert client.get("/outbox/count").json() == {"pending": 0}
def test_unit_of_work_dependency_commits_before_the_response(client):
r = client.post("/bookings/uow", json=BODY)
assert r.status_code == 201
assert [b["id"] for b in client.get("/rooms/1/bookings").json()] == [1]
assert client.get("/outbox/count").json() == {"pending": 1}
def test_unit_of_work_rolls_back_when_the_route_raises(client):
client.post("/bookings/uow", json=BODY)
r = client.post("/bookings/uow", json=BODY) # overlap -> HTTPException inside the unit of work
assert r.status_code == 409
assert client.get("/outbox/count").json() == {"pending": 1}
def failing_commit(app):
def boom(session):
raise RuntimeError("commit failed (simulated)")
event.listen(app.state.session_factory, "before_commit", boom)
def test_scope_function_commit_failure_becomes_a_500(engine):
app = create_app(engine)
failing_commit(app)
with TestClient(app, raise_server_exceptions=False) as c:
r = c.post("/bookings/uow", json=BODY)
assert r.status_code == 500 # the client learns that nothing was saved
with TestClient(create_app(engine)) as c:
assert c.get("/rooms/1/bookings").json() == []
def test_commit_in_route_failure_is_a_500(engine):
app = create_app(engine)
failing_commit(app)
with TestClient(app, raise_server_exceptions=False) as c:
assert c.post("/bookings", json=BODY).status_code == 500
with TestClient(create_app(engine)) as c:
assert c.get("/rooms/1/bookings").json() == []
def test_default_scope_commit_failure_arrives_after_a_201(engine):
app = create_app(engine)
failing_commit(app)
with TestClient(app) as c:
with pytest.raises(RuntimeError, match="commit failed"): # raised after the response
c.post("/bookings/uow-late", json=BODY)
with TestClient(app, raise_server_exceptions=False) as c:
r = c.post("/bookings/uow-late", json=BODY)
assert r.status_code == 201 # ...but the client was told "created"
with TestClient(create_app(engine)) as c:
assert c.get("/rooms/1/bookings").json() == [] # and nothing was saved
def test_scope_function_serializes_the_response_before_the_commit(engine):
"""With expire_on_commit=True a read after commit+close would raise DetachedInstanceError.
The 201 with a full body shows FastAPI 0.128.8 serialized the response before the
function-scoped dependency committed and closed the session."""
with TestClient(create_app(engine, expire_on_commit=True)) as c:
r = c.post("/bookings/uow", json=BODY)
assert r.status_code == 201
assert r.json() == {"id": 1, "room_id": 1, "start_date": "2026-12-01", "end_date": "2026-12-04", "cancelled_at": None}[project]
name = "alembic-migrations-transactions"
version = "0.1.0"
description = "Snippets for the Alembic chapter: migrations, transactions, savepoints, locking and indexes from the ORM"
# The page targets Python 3.12+; the pins below are the newest releases that still install on 3.9,
# the only interpreter on the build machine. On 3.12+ move to the latest releases
# (Alembic 1.17+ needs Python >= 3.10, SQLModel 0.0.50 and SQLAlchemy 2.1.x need >= 3.11).
requires-python = ">=3.9"
dependencies = [
"fastapi==0.128.8",
"starlette==0.49.3",
"pydantic==2.13.5",
# 2.0.58 is the newest 2.0.x (maintenance series); 2.1.x needs Python 3.11.
"sqlalchemy==2.0.58",
# 0.0.34 is the last SQLModel release for Python 3.9 (0.0.35 dropped it).
"sqlmodel==0.0.34",
# 1.16.5 is the last Alembic release for Python 3.9 (1.17.0 needs 3.10).
"alembic==1.16.5",
# Async SQLite driver, used by the async branch of migrations/env.py.
"aiosqlite==0.22.1",
# SQLAlchemy's asyncio layer runs on greenlet; 3.2.5 is the last release for 3.9.
"greenlet==3.2.5",
# Lets Pydantic evaluate `str | None` annotations on Python 3.9; not needed on 3.10+.
"eval-type-backport==0.4.0; python_version < '3.10'",
]
[project.optional-dependencies]
test = [
"httpx==0.28.1",
"pytest==8.4.2",
]
[build-system]
requires = ["setuptools>=61"]
build-backend = "setuptools.build_meta"
[tool.setuptools]
packages = ["app"]
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-q -p no:cacheprovider"
pythonpath = ["."]
filterwarnings = [
# SQLite cannot reflect expression indexes; the tests read sqlite_master instead.
"ignore:Skipped unsupported reflection of expression-based index:sqlalchemy.exc.SAWarning",
]The Python angle
Alembic leans on four Python features. Modules as plugins: env.py and every revision file are plain modules that Alembic imports by path. That is why prepend_sys_path = . matters (so import app.models works) and why a revision must never import the application's models: they describe the schema at head, and a revision must keep working against the schema as it was. Revision 0003 therefore declares its own sa.table("room", sa.column("id"), sa.column("floor")). Context managers: with op.batch_alter_table(...), with op.get_context().autocommit_block(), with session.begin(), with session.begin_nested() and with context.begin_transaction() all scope a resource or a transaction, and their exit paths (commit, rollback, release, copy-and-rename) are where the interesting behaviour lives. Import-time side effects: SQLModel.metadata only knows the tables whose modules were imported, so env.py imports app.models before it reads target_metadata. The naming convention is assigned at import time too, before the first class body runs. Runtime annotations: SQLModel builds columns from Optional[int] and Field(...). X | None needs Python 3.10, or eval-type-backport on 3.9, which is why the snippet writes Optional. On the Alembic side, revision files use Union[str, Sequence[str], None] from the generated template for the same reason.
The concept catalogue
create_all is not a migration tool Must-know
In plain words: create_all() creates tables that do not exist yet. It never changes a table that is already there, and it does not remember what it did. A migration tool applies numbered changes in order and writes down the last one it applied.
Common misunderstanding: "create_all picks up my new column." It checks for existence only. The Before app's test starts with a room table without floor: create_all() creates the missing booking table, leaves room alone, and the first SELECT fails with no such column: room.floor (real). The opposite mistake is to drop create_all everywhere. It is the right tool for throwaway test databases, for example a per-test SQLite file.
Definition: The SQLModel tutorial: "For this simple example, and for most of the Tutorial - User Guide, using SQLModel.metadata.create_all() is enough. But for a production system you would probably want to use a system to migrate the database. This would be useful and important, for example, whenever you add or remove a column, add a new table, change a type, etc." FastAPI's SQL tutorial repeats SQLModel's line: "SQLModel will have migration utilities wrapping Alembic, but for now, you can use Alembic directly."
database created by app v1 app v2 starts (real: test_before.py, runs/before-create-all-echo.txt)
1 room(id, name, capacity, price_cents, version) lifespan: SQLModel.metadata.create_all(engine)
2 PRAGMA main.table_info("room") -> exists -> skipped
3 PRAGMA main.table_info("booking") -> missing -> CREATE TABLE booking (also user, email_outbox)
4 room columns afterwards: id, name, capacity, price_cents, version
5 GET /rooms -> no such column: room.floor
6 alembic_version: does not exist nobody can tell which schema this database hasReal scenario: a model gains floor and the staging database starts failing; three replicas start at once and race on CREATE TABLE; a column type changes in the model and nothing happens in the database; an index added to the model never reaches production.
| Need | create_all() | Alembic |
|---|---|---|
| Fresh database for a test | yes, fastest | upgrade head (slower, tests the migrations too) |
| Add or drop a column on a live table | no | op.add_column / op.drop_column |
| Change type, nullability, constraints | no | op.alter_column, op.create_check_constraint (batch on SQLite) |
| Record which schema is live | no | alembic_version |
| Review in a pull request | no | revision file and --sql |
Adopt a database built by create_all | n/a | alembic stamp head (real test) |
Fix / how to use it: keep create_all in unit-test fixtures only; let alembic upgrade head build every shared database, including the CI database; adopt an existing create_all database once with alembic stamp head, then alembic check it.
The migration environment: alembic init, alembic.ini, env.py, script.py.mako Must-know
In plain words: alembic init migrations creates a folder with a configuration script (env.py), a template for new files (script.py.mako) and an empty versions/ folder, plus alembic.ini next to it. Every alembic command reads alembic.ini. The commands that touch a database (upgrade, downgrade, current, stamp, check, revision --autogenerate, and any --sql run) also run env.py, and env.py runs the revision functions. Pure script commands such as history, heads or a plain revision -m only read the files in versions/; they run env.py only when revision_environment = true is set in alembic.ini, which the generated file leaves off.
Common misunderstanding: "env.py is generated boilerplate, don't touch it." It is the part you are meant to edit: the URL source, target_metadata, render_as_batch, timeouts, async engines and connection sharing all live there. The other misreading is that script.py.mako only matters once. Every future revision is rendered from it, so a missing import sqlmodel there breaks every autogenerated file.
Definition: The tutorial defines the files. alembic.ini "is Alembic's main configuration file which is generated by all templates". env.py "is a Python script that is run whenever the alembic migration tool is invoked. At the very least, it contains instructions to configure and generate a SQLAlchemy engine, procure a connection from that engine along with a transaction, and then invoke the migration engine". script.py.mako "is a Mako template file which is used to generate new migration scripts". versions/ "holds the individual version scripts", and "the ordering of version scripts is relative to directives within the scripts themselves". The real alembic list_templates on 1.16.5 offers generic, async, multidb, pyproject and pyproject_async.
$ alembic init migrations (real, runs/alembic-init.txt)
1 Creating directory .../migrations ... done
2 Creating directory .../migrations/versions ... done
3 Generating .../migrations/script.py.mako ... done
4 Generating .../migrations/env.py ... done
5 Generating .../migrations/README ... done
6 Generating .../alembic.ini ... done
7 Please edit configuration/connection/logging settings in .../alembic.ini before proceeding.Real scenario: a new service starts from alembic init -t async migrations because it uses asyncpg; a monorepo with two databases starts from multidb; a team that keeps all tool settings in pyproject.toml starts from pyproject (1.16+), keeping only URL and logging out of it.
| File | Who edits it | What goes in it |
|---|---|---|
alembic.ini | once | script_location, prepend_sys_path, file_template, path_separator, logging, a fallback URL |
pyproject.toml [tool.alembic] (1.16+) | once | the same source-code settings; not URL, not logging |
migrations/env.py | once, then rarely | URL source, target_metadata, configure() flags, online/offline/async runners |
migrations/script.py.mako | once | imports every revision needs (sqlmodel), header layout |
migrations/versions/*.py | every schema change | upgrade(), downgrade(), revision, down_revision |
alembic_version (table) | Alembic only | the current revision id(s) |
Fix / how to use it: run alembic init once and commit the result. Edit env.py for URL, metadata and flags, and add import sqlmodel to the template. Keep versions/ free of generated code nobody has read.
Database URL: alembic.ini sqlalchemy.url vs environment Important
In plain words: Alembic needs to know which database to migrate. The generated env.py reads sqlalchemy.url from alembic.ini, but a real project reads it from the environment (the same DATABASE_URL the app uses), so no password is ever committed and the same files work in every environment.
Common misunderstanding: "Put the production URL in alembic.ini." That commits a secret and ties the file to one environment. The other mistake is a URL that differs from the app's: Alembic migrates rooms.db in the repo root while the app reads ./data/rooms.db, and "the migration ran but my app has no table".
Definition: The tutorial: "If the SQLAlchemy URL should come from some other source, such as from environment variables or a global registry, or if the migration environment makes use of multiple database URLs, the developer is encouraged to alter the env.py file to use whatever methods are appropriate in order to acquire the database URL or URLs." The snippet's database_url() returns os.environ.get("DATABASE_URL") or config.get_main_option("sqlalchemy.url"). Tests call cfg.set_main_option("sqlalchemy.url", url) and set DATABASE_URL for the same file.
shell / Job env.py result
1 DATABASE_URL unset falls back to alembic.ini: sqlite:///rooms.db local dev
2 DATABASE_URL=sqlite+aiosqlite:///async.db is_async dialect -> asyncio.run(run_sync(...)) real: 0006 (head)
3 DATABASE_URL=postgresql://app@db/rooms --sql offline: no connection, renders SQL real render
4 DATABASE_URL from a Kubernetes Secret Job runs alembic upgrade head expected, not runReal scenario: CI points DATABASE_URL at a throwaway PostgreSQL service; the production Job mounts the URL from a secret; a developer renders the production script with --sql from a laptop that has no access to production at all.
| Source | Pros | Cons |
|---|---|---|
sqlalchemy.url in alembic.ini | zero code | secret in git, one environment |
DATABASE_URL read in env.py | same as the app, 12-factor | must be set in every shell |
-x url=... (context.get_x_argument()) | explicit per run | easy to forget, appears in shell history |
| The app's settings object (Pydantic Settings) | one source of truth | env.py imports app config |
config.attributes["connection"] | tests share a connection | code only |
Fix / how to use it: read the URL in env.py from the same variable or settings object as the app; keep a harmless SQLite fallback in alembic.ini for local work; never print the URL in logs.
target_metadata with SQLModel metadata Must-know
In plain words: Autogenerate and alembic check compare the database with a MetaData object, the in-memory description of all tables. In a SQLModel app that is SQLModel.metadata, and it only contains the tables whose modules have been imported.
Common misunderstanding: "target_metadata = SQLModel.metadata is enough." Only if env.py imports the models first. Without import app.models the metadata is empty, and autogenerate concludes that every table in the database should be dropped (real probe: four Detected removed table lines). The second misreading is "SQLModel has its own metadata per model". All table=True classes share the one SQLModel.metadata, unless you define a separate base class.
Definition: The generated env.py (real, runs/init-generic-env.py.txt) has target_metadata = None under the comment "add your model's MetaData object here". The snippet sets target_metadata = SQLModel.metadata after import app.models # noqa: F401. Data models (without table=True) add nothing to the metadata.
env.py variant alembic revision --autogenerate, database at head (real, runs/target-metadata-probe.txt)
1 target_metadata = None FAILED: Can't proceed with --autogenerate option; environment script ... does not
provide a MetaData object or sequence of objects to the context.
2 SQLModel.metadata, models NOT imported Detected removed table 'email_outbox' / 'user' / 'room' / 'booking' (+ their indexes)
3 SQLModel.metadata after import app.models an empty revision (upgrade: pass); alembic check: No new upgrade operations detected.Real scenario: a new module app/reviews/models.py is not imported by app/models.py, so its table never gets a migration; a test helper imports half the models and alembic check reports drops; two Alembic environments in a monorepo each import their own package.
| Setting | Effect |
|---|---|
target_metadata = SQLModel.metadata | All imported table=True models |
target_metadata = [meta_a, meta_b] | Several metadata objects in one environment |
include_object= callable | Skip tables (for example views or tables owned by another service) |
include_name= callable | Filter by name before reflection (cheaper) |
version_table="alembic_version_rooms" | Several environments in one database |
Fix / how to use it: import the models package at the top of env.py, assert in a test that sorted(SQLModel.metadata.tables) is what you expect, and filter foreign tables with include_object.
Autogenerate: what it detects and what it misses Must-know
In plain words: alembic revision --autogenerate -m "..." reflects the database, compares it with target_metadata and writes the difference as op.* calls. It is a diff tool with blind spots, not a migration author.
Common misunderstanding: "If autogenerate produced nothing, the schema matches." Not for CHECK constraints on 1.16.5, not for expression indexes on SQLite (skipped with a warning), and not for server defaults unless compare_server_default=True. And "if it produced something, it is right" fails on renames and on NOT NULL columns for tables with rows.
Definition: The docs: "Autogenerate will detect: Table additions, removals. Column additions, removals. Change of nullable status on columns. Basic changes in indexes and explicitly-named unique constraints. Basic changes in foreign key constraints." Type changes are detected "by default unless the parameter EnvironmentContext.configure.compare_type is set to False". Server defaults are compared "if you set the EnvironmentContext.configure.compare_server_default parameter to True". "Autogenerate can not detect: Changes of table name. These will come out as an add/drop of two different tables ... Changes of column name. Like table name changes, these are detected as a column add/drop pair, which is not at all the same as a name change. Anonymously named constraints." The current docs list named CHECK constraints as optional: "Added in version 1.19.0. Changed in version 1.19.2: This feature is no longer enabled by default."
$ alembic revision --autogenerate (v1 database -> head models, real, runs/autogen-diff.log)
1 Detected added table 'email_outbox'
2 Detected added index 'ix_email_outbox_status_id' on '('status', 'id')'
3 Detected added column 'booking.cancelled_at'
4 Detected removed index 'ix_booking_room_id' on 'booking'
5 Detected added index 'ix_booking_active_room' on '('room_id', 'start_date', 'end_date')'
6 Detected added index 'ix_booking_room_id_start_date' on '('room_id', 'start_date')'
7 Detected added column 'room.floor' -> add_column(..., nullable=False): fails on rows
8 UserWarning: autogenerate skipping metadata-specified expression-based index 'ix_user_email_lower'
9 (no line at all for CheckConstraint ck_booking_end_after_start: not detected by 1.16.5)Real scenario: a developer renames price_cents to price; autogenerate writes add_column('price') + drop_column('price_cents') (real test), which would delete every price on deploy. A String(100) widened to String(200) is caught as modify_type (real). A server default changed from 'inactive' to 'active' only shows up with compare_server_default=True (real).
| Change in the models | 1.16.5 on SQLite (real tests) | What to write instead |
|---|---|---|
| New table / column | detected | review nullability and defaults |
| New NOT NULL column | detected as nullable=False | nullable first, backfill, then NOT NULL |
| Column rename | add + drop (data loss) | op.alter_column("room", "price_cents", new_column_name="price") |
| Table rename | add + drop | op.rename_table |
| Type change | modify_type (compare_type=True default since 1.12) | check data conversion (postgresql_using=) |
| Server default change | only with compare_server_default=True | review the rendered default text |
| Named CHECK added | not detected (1.19.0+ optional plugin) | op.create_check_constraint by hand |
| Expression index | skipped with UserWarning on SQLite | op.create_index(..., [sa.text("lower(email)")]) by hand |
| Partial index | detected, sqlite_where/postgresql_where rendered | check the WHERE text |
| Unnamed constraint | no stable name to drop later | naming convention |
Fix / how to use it: run autogenerate, then read every line. Turn add+drop pairs into renames, split NOT NULL additions into expand/backfill/contract, add hand-written constraints and expression indexes, and set compare_server_default=True if you rely on server defaults. Finish with alembic check in CI.
Naming conventions: MetaData naming convention Must-know
In plain words: Every constraint and index should have a name that you can predict, because a later migration has to say drop_constraint("uq_room_name"). A naming convention on the MetaData generates those names from templates such as uq_%(table_name)s_%(column_0_name)s.
Common misunderstanding: "The database names constraints, that's fine." Each database invents its own names, and the metadata knows none of them: UniqueConstraint("name").name is None without a convention (real test), so Alembic has nothing to put in a later drop_constraint. A migration written against your laptop's names then fails in production. The second trap: set the convention after the models are defined and nothing changes, because names are assigned when each constraint is attached to its table.
Definition: Alembic's "The Importance of Naming Constraints" page explains that constraints need names so they can be dropped or altered later, and it recommends a naming_convention on the MetaData. Autogenerate then renders names wrapped in op.f(), which marks them as final so the convention is not applied twice. The snippet sets SQLModel.metadata.naming_convention = NAMING_CONVENTION before the first class. The real 0001 then contains name=op.f('pk_room') and name=op.f('fk_booking_room_id_room').
template real name in the snippet
1 "ix": "ix_%(column_0_label)s" ix_room_name, ix_user_email
2 "uq": "uq_%(table_name)s_%(column_0_name)s" uq_room_name (test_unique_constraint_add_is_detected)
3 "ck": "ck_%(table_name)s_%(constraint_name)s" ck_booking_end_after_start (from name="end_after_start")
4 "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s" fk_booking_room_id_room
5 "pk": "pk_%(table_name)s" pk_room, pk_booking
6 without a convention UniqueConstraint("name").name -> None (real test)Real scenario: dropping a unique constraint whose name differs between the developer's SQLite and production PostgreSQL; batch mode on SQLite that must recreate a CHECK constraint (an unnamed one is skipped, per the batch docs); a team that adds the convention in year two and must rename every existing constraint once.
| Object | Without convention | With the snippet's convention |
|---|---|---|
| Primary key | chosen by the backend | pk_room |
| Unique | chosen by the backend, or none on SQLite | uq_room_name |
| Check | must pass name= or none | ck_booking_end_after_start |
| Foreign key | backend default | fk_booking_room_id_room |
Index from index=True | ix_room_name (SQLAlchemy default) | ix_room_name |
Fix / how to use it: define the convention in the module that defines the metadata, before any table. With SQLModel, assign it to SQLModel.metadata.naming_convention. Use op.f("...") for names in hand-written revisions, and give CHECK constraints a short name= that the template expands.
Revision files and operations: upgrade, downgrade, op.* Must-know
In plain words: A revision is a Python file with an id (revision), the id of its parent (down_revision), an upgrade() that moves the schema forward and a downgrade() that moves it back. Inside them you call op.* functions, which Alembic turns into DDL for the current dialect.
Common misunderstanding: "Revision ids must be increasing numbers." Order comes from down_revision, not from the file name; Alembic generates random hex ids by default, and the snippet uses --rev-id 0001 only for readability. The other mistake is a downgrade() that just says pass for a schema change. That makes downgrade -1 silently lie. For data that cannot be restored, raise in downgrade() instead.
Definition: The operations reference documents op.create_table, op.drop_table, op.add_column, op.drop_column, op.alter_column (nullable, type_, server_default, new_column_name, existing_type), op.create_index/op.drop_index, op.create_unique_constraint, op.create_check_constraint, op.create_foreign_key, op.drop_constraint, op.rename_table, op.execute, op.bulk_insert, op.batch_alter_table, op.f(), op.get_bind() and op.get_context(). Dialect keywords pass through (postgresql_concurrently=True, postgresql_not_valid=True, postgresql_where=, sqlite_where=).
0004_contract_room_floor_not_null.py
1 revision = "0004"; down_revision = "0003"
2 upgrade(): if op.get_context().dialect.name == "postgresql": NOT VALID -> autocommit_block(VALIDATE) -> SET NOT NULL
3 else: with op.batch_alter_table("room"): alter_column("floor", nullable=False)
4 with op.batch_alter_table("booking"): create_check_constraint(op.f("ck_booking_end_after_start"), ...)
5 downgrade(): drop the check, make floor nullable again
6 alembic_version: UPDATE ... SET version_num='0004' WHERE version_num = '0003' (real echo)Real scenario: a revision that adds a column and an index; one that branches on the dialect because PostgreSQL can do more online; one that carries op.execute("ALTER TYPE mood ADD VALUE 'soso'") inside autocommit_block(), as in the runtime API docs' own example.
| Operation | SQLite (real, 3.54 + Alembic 1.16.5) | PostgreSQL (rendered) |
|---|---|---|
op.add_column(nullable=True) | ALTER TABLE room ADD COLUMN floor INTEGER | same |
op.add_column(nullable=False) no default | Cannot add a NOT NULL column with default value NULL on rows | fails on rows too (NOT NULL violation, expected) |
op.alter_column(type_=...) | near "TYPE": syntax error → batch | ALTER COLUMN ... TYPE ... |
op.alter_column(nullable=...) | works in place since SQLite 3.53.0; batch still recreates | SET NOT NULL / DROP NOT NULL |
op.drop_constraint | NotImplementedError: No support for ALTER of constraints in SQLite dialect → batch | ALTER TABLE ... DROP CONSTRAINT |
op.create_index(postgresql_concurrently=True) | plain CREATE INDEX | CREATE INDEX CONCURRENTLY |
Fix / how to use it: one concern per revision; explicit existing_type= on every alter_column (batch mode needs it); a real downgrade() or a deliberate raise; no imports from app.models inside revisions.
Batch mode for SQLite: batch_alter_table and render_as_batch Must-know
In plain words: SQLite can add and rename columns, but it cannot change a column's type or add and drop constraints with ALTER. Alembic's batch mode works around it: it builds a new table with the desired shape, copies the rows, drops the old table and renames the new one. render_as_batch=True makes autogenerate write with op.batch_alter_table(...) blocks for SQLite.
Common misunderstanding: "Batch mode is just a slower ALTER." It drops the old table. With PRAGMA foreign_keys=ON on the migration connection, DROP TABLE room performs an implicit DELETE that fires ON DELETE CASCADE. The real test counted 3 bookings before and 0 after, with no error and no warning. Batch mode is also not available offline (--sql) without copy_from=, because it has to reflect the table.
Definition: "The SQLite database presents a challenge to migration tools in that it has almost no support for the ALTER statement which relational schema migrations rely upon ... Migration tools are instead expected to produce copies of SQLite tables that correspond to the new structure, transfer the data from the existing table to the new one, then drop the old table." On foreign keys: "batch table operations do not work with foreign keys that enforce referential integrity ... On SQLite, whether or not foreign keys actually enforce is controlled by the PRAGMA FOREIGN KEYS pragma; this pragma, if in use, must be disabled when the workflow mode proceeds." SQLite's own page: "The DROP TABLE command performs an implicit DELETE to remove all rows from the table before dropping the table." SQLite's ALTER TABLE page adds: "The ability to set or drop NOT NULL constraints from a column using the ALTER TABLE ALTER COLUMN syntax was added in SQLite 3.53.0 (2026-04-09)."
revision 0004 on SQLite (real echo, runs/batch-echo.txt)
1 SELECT sql FROM sqlite_master WHERE name = 'room' -- reflect
2 CREATE TABLE _alembic_tmp_room (... floor INTEGER NOT NULL ...)
3 INSERT INTO _alembic_tmp_room (...) SELECT ... FROM room
4 DROP TABLE room -- implicit DELETE: cascades if FKs are ON
5 ALTER TABLE _alembic_tmp_room RENAME TO room
6 CREATE UNIQUE INDEX ix_room_name ON room (name) -- indexes recreated
7 same four steps for booking, now with CONSTRAINT ck_booking_end_after_start CHECK (end_date > start_date)Real scenario: a local SQLite database for development and tests while production is PostgreSQL. The same revision has to work on both, and batch_alter_table is a plain ALTER on PostgreSQL. A NOT NULL contract step on SQLite fails because one row was missed by the backfill: NOT NULL constraint failed: _alembic_tmp_room.floor (real test). The name of the temporary table in the error is the clue.
| Situation | Behaviour |
|---|---|
render_as_batch=True in configure() | autogenerate emits with op.batch_alter_table(...) for every table change |
| Batch on PostgreSQL / MySQL | emits ordinary ALTER TABLE statements (recreate="auto") |
recreate="always" / "never" | force or forbid the copy |
| Foreign keys ON during batch | child rows deleted by cascade (real) or FOREIGN KEY constraint failed |
| Unnamed CHECK / UNIQUE | cannot be carried over reliably; name them |
--sql with batch on SQLite | batch mode with dialect sqlite requires a live database connection (real) |
Fix / how to use it: render_as_batch=True for SQLite only, always existing_type=, migrations through env.py's own engine without the FK pragma (and PRAGMA foreign_key_check afterwards, which the real test shows empty), seed rows before testing a batch revision, and name every constraint.
Applying migrations: upgrade head, downgrade -1, history, current, heads, stamp Must-know
In plain words: alembic upgrade head runs every revision that is not applied yet. downgrade -1 steps back one. current says where the database is, history lists the chain, heads lists its tips, and stamp writes a revision id into alembic_version without running anything.
Common misunderstanding: "stamp is a quick way to skip a broken migration." It only changes the bookmark. The schema stays as it is, and the next upgrade runs from the stamped point. That is correct when you adopt a database built by create_all (real test: stamp, then check is clean) and dangerous everywhere else. Also, "downgrade restores my data": a downgrade restores structure, while dropped data is gone.
Definition: The commands API documents upgrade(config, revision, sql=False, tag=None), downgrade(...), current(config, verbose=False), history(config, rev_range=None, verbose=False, indicate_current=False), heads, branches, stamp(config, revision, sql=False, tag=None, purge=False), check(config), merge, revision and show. Relative targets are +1, -1, 0003+2; base means "before the first revision"; head is the single tip and heads all tips.
real session (runs/cli-session.txt)
1 $ alembic current -> (empty: no version row)
2 $ alembic upgrade head -> Running upgrade -> 0001 ... Running upgrade 0005 -> 0006
3 $ alembic current -> 0006 (head)
4 $ alembic downgrade -1 -> Running downgrade 0006 -> 0005, create email_outbox with server defaults
5 $ alembic stamp 0005 / head -> Running stamp_revision 0006 -> 0005 / 0005 -> 0006 (no DDL)
6 $ alembic downgrade base -> ... Running downgrade 0001 -> ; .tables -> alembic_versionReal scenario: a deploy Job runs upgrade head and fails on revision 0004; the operator reads current (0003), fixes the data, re-runs. A developer resets a local database with downgrade base and upgrade head. A production database restored from a dump before Alembic was introduced is adopted with stamp.
| Command | Changes schema | Changes alembic_version | Typical use |
|---|---|---|---|
upgrade head / +1 / <rev> | yes | yes | deploy |
downgrade -1 / <rev> / base | yes | yes | local work, emergency |
current [--verbose] | no | no | "where are we?" |
history [-r a:b] [--verbose] [-i] | no | no | review, docs |
heads / branches | no | no | CI: exactly one head |
stamp <rev> | no | yes | adopt an existing schema |
check | no | no | CI: models == migrations |
upgrade head --sql | no | no (prints SQL) | DBA review |
Fix / how to use it: upgrade head from one place per deploy; current in the deploy log; stamp only after proving the schema matches (check); prefer a new forward revision to a production downgrade.
Branches and merge revisions Important
In plain words: Two developers each create a revision on top of 0006. After both pull requests merge, the chain has two heads. alembic upgrade head refuses to guess. alembic merge heads creates a revision with two parents, and the chain has one head again.
Common misunderstanding: "Multiple heads means the repository is broken." It is a normal outcome of parallel work; the fix is one merge revision, usually empty. The opposite mistake is upgrade heads in production to "make it work". That applies both branches in an order nobody reviewed, and leaves two rows in alembic_version (real test: current prints both).
Definition: The branches docs show the exact failure: "FAILED: Multiple head revisions are present for given argument 'head'; please specify a specific target revision, '<branchname>@head' to narrow to a specific head, or 'heads' for all heads". A merge revision has a tuple down_revision; history marks it (mergepoint) and its parent (branchpoint). Branch labels (branch_labels) and depends_on support long-lived independent branches, for example one per module.
two feature branches, then main (real, tests/test_branches.py)
1 dev A: alembic revision -m "add room notes" --rev-id a1b2 (down_revision 0006)
2 dev B: alembic revision -m "add booking source" --rev-id c3d4 (down_revision 0006, --splice)
3 alembic heads -> a1b2 (head) / c3d4 (head)
4 alembic upgrade head -> CommandError: Multiple head revisions are present for given argument 'head'
5 alembic merge heads -m "merge notes and source" --rev-id e5f6 -> down_revision = ('a1b2', 'c3d4')
6 alembic upgrade head; alembic current -> e5f6 (head) (mergepoint)Real scenario: a busy monolith where two teams ship migrations the same day; a hotfix revision created on a release branch from an older head; a modular monolith whose billing module keeps its own branch label.
| Situation | Command | Result |
|---|---|---|
| Two heads after a merge of pull requests | alembic merge heads -m "merge" | one head; empty upgrade() |
| Want to apply both without merging (local only) | alembic upgrade heads | two version rows |
| Independent module | alembic revision --head=base --branch-label=billing | own chain, billing@head |
| Revision needs another branch first | depends_on = "a1b2" | ordering without a merge |
| CI guard | test len(ScriptDirectory.get_heads()) == 1 | fails the pull request that adds a second head |
Fix / how to use it: a CI test that asserts exactly one head (the snippet's test_revision_chain_is_linear); merge revisions created on main right after the second branch lands; no upgrade heads in deploy scripts.
Offline mode --sql: SQL scripts for review Important
In plain words: alembic upgrade head --sql prints the SQL that the upgrade would run, without connecting to the database. You get a reviewable script, and you can hand it to a DBA or apply it with psql.
Common misunderstanding: "Offline output equals what online mode does." Mostly, but not where the revision needs the database: a data migration that loops on query results cannot loop offline (revision 0003 detects op.get_context().as_sql and emits one set-based UPDATE), and SQLite batch mode cannot reflect tables (This operation cannot proceed in --sql mode; batch mode with dialect sqlite requires a live database connection, real). Offline output is also dialect-specific: render it for the production dialect, not for your SQLite.
Definition: "A major capability of Alembic is to generate migrations as SQL scripts, instead of running them against the database - this is also referred to as offline mode. This is a critical feature when working in large organizations where access to DDL is restricted, and SQL scripts must be handed off to DBAs. Alembic makes this easy via the --sql option passed to any upgrade or downgrade command." env.py's run_migrations_offline() calls context.configure(url=..., literal_binds=True), and ranges such as 0003:0004 render one step.
$ DATABASE_URL=postgresql://app@localhost/rooms alembic upgrade 0004:0005 --sql (real render)
1 BEGIN;
2 -- Running upgrade 0004 -> 0005
3 COMMIT; <- autocommit_block() ends the transaction
4 CREATE INDEX CONCURRENTLY ix_booking_room_id_start_date ON booking (room_id, start_date);
5 CREATE INDEX CONCURRENTLY ix_booking_active_room ON booking (room_id, start_date, end_date) WHERE cancelled_at IS NULL;
6 DROP INDEX CONCURRENTLY ix_booking_room_id;
7 BEGIN;
8 UPDATE alembic_version SET version_num='0005' WHERE alembic_version.version_num = '0004';
9 COMMIT;Real scenario: a bank where application accounts have no DDL rights and DBAs apply reviewed scripts; a pull request bot that attaches the PostgreSQL script for every new revision; a migration rehearsal that diffs the script between two branches.
| Target | Command | Notes |
|---|---|---|
| Full script | alembic upgrade head --sql > up.sql | creates alembic_version too |
| One step | alembic upgrade 0004:0005 --sql | start:end range required offline |
| Downgrade | alembic downgrade 0006:0004 --sql | real render saved |
| Another dialect | set the URL to that dialect | no server needed (real for PostgreSQL and MySQL) |
| Batch on SQLite | copy_from=Table(...) in the revision | otherwise refuses offline |
| Data steps | branch on op.get_context().as_sql | emit set-based SQL |
Fix / how to use it: render the production dialect's script in CI and attach it to the pull request; keep data loops behind as_sql checks; never edit the rendered script by hand and then apply it, change the revision instead.
Data migrations vs schema migrations Must-know
In plain words: A schema migration changes structure (tables, columns, constraints, indexes). A data migration changes rows: backfilling a new column, splitting a name into two fields, fixing bad values. They have different risks, so keep them in separate revisions or outside Alembic entirely.
Common misunderstanding: "Use the app's models in the data migration." Models describe the schema at head. Revision 0003 must work against the 0002 schema forever, so it defines sa.table("room", sa.column("id"), sa.column("floor")) locally. The other trap is one giant UPDATE room SET floor = 0 on a table with 50 million rows inside the deploy transaction, which locks every row it touches until the transaction ends.
Definition: The Alembic cookbook: "Alembic migrations are designed for schema migrations. The nature of data migrations are inherently different and it's not in fact advisable in the general case to write data migrations that integrate with Alembic's schema versioning model. For example downgrades are difficult to address since they might require deletion of data, which may even not be possible to detect." It names three approaches: small data with Operations.bulk_insert(), a "separate migration script" between the initial and final Alembic migrations, and "Online migration", where "Writes are performed on both places, while the background script move all the remaining data across."
revision 0003, real run with 5 rooms whose floor IS NULL (test_backfill_is_a_data_migration_in_batches)
1 SELECT room.id FROM room WHERE room.floor IS NULL ORDER BY room.id LIMIT 2 -> [1, 2]
2 UPDATE room SET floor=0 WHERE room.id IN (1, 2)
3 ... [3, 4] ... [5] ... [] -> stop
4 log: backfilled room.floor in 3 batches of up to 2 rows
5 offline (--sql): UPDATE room SET floor=0 WHERE room.floor IS NULL; -> one set-based statementReal scenario: seeding a lookup table with op.bulk_insert; backfilling a computed column on a big table as a separate job between two deploys; a data fix that must not run in every developer's database (a one-off script, not a revision).
| Kind | Where | Idempotent? | Downgrade |
|---|---|---|---|
| Small reference data | revision with op.bulk_insert | make it so (ON CONFLICT / check first) | delete the rows |
| Backfill, small table | own revision, batches | yes (WHERE floor IS NULL) | usually pass with a comment |
| Backfill, large table | separate job between expand and contract | yes | n/a |
| Dual write (online) | application code | n/a | stop writing |
| One-off fix | script with a ticket | must be | n/a |
Fix / how to use it: data steps in their own revision with a local sa.table(), bounded batches, a WHERE that makes re-runs harmless, and a big-table backfill moved to a job outside the deploy transaction.
Transactional DDL and partial migration failure Must-know
In plain words: On PostgreSQL a failed migration rolls back completely, DDL included, as long as the revision stays inside one transaction. A revision with an autocommit_block() does not: everything before the block is committed, so a failure after it leaves that part behind. On MySQL every DDL statement commits on its own, so a revision that fails on its third statement leaves the first two applied. On SQLite the database could roll DDL back, but Python's sqlite3 driver never sends BEGIN before DDL, so by default it behaves like MySQL (real run).
Common misunderstanding: "Will assume non-transactional DDL. is just a log line." It is Alembic telling you the rollback promise does not hold. In the real run a revision did add_column("room", "note") and then failed. alembic_version still said 0006 while the column existed, and the re-run failed with duplicate column name: note. Second misunderstanding: "PostgreSQL rolls back everything, so long migrations are safe." The whole revision holds its locks until COMMIT, which is why PostgreSQL migrations should be short, and the escape hatch for that (autocommit_block()) gives up the single rollback. The runtime docs say so: "the database transaction preceding the block is unconditionally committed". The snippet's revision 0004 commits its NOT VALID constraints before VALIDATE. If validation failed and the revision were re-run as written naively, ADD CONSTRAINT would hit the existing name. 0004 therefore counts bad rows first, inside the transaction, so it fails before anything is committed, and it adds each constraint only if pg_constraint does not have it yet, so a re-run after a failed VALIDATE goes straight to validation (expected, not run: no PostgreSQL here; the offline render is real).
Definition: The PostgreSQL wiki: "one of the more advanced features of PostgreSQL is its ability to perform transactional DDL via its Write-Ahead Log design. This design supports backing out even large changes to DDL, such as table creation." MySQL 8.4: the listed statements "implicitly end any transaction active in the current session, as if you had done a COMMIT before executing the statement", and the list includes ALTER TABLE, CREATE INDEX, CREATE TABLE, DROP INDEX and DROP TABLE. SQLAlchemy's SQLite page: the driver "skips this step for DQL (e.g. SELECT) statements, and also skips it for DDL (e.g. CREATE TABLE etc.) statements for more legacy reasons", leading to "Incorrect support for transactional DDL". The fix it documents is to set dbapi_connection.isolation_level = None on connect and emit BEGIN from the begin event, which is make_engine(..., sqlite_real_transactions=True) in the snippet.
broken revision 0007: add_column("room", "note"); then UPDATE no_such_table (real, tests/test_partial_failure.py)
1 SQLite, default driver mode ALTER TABLE ADD COLUMN autocommitted; error; version stays 0006; column EXISTS
2 re-run -> duplicate column name: note
3 SQLite, BEGIN recipe BEGIN; ALTER ...; error -> ROLLBACK; version 0006; column ABSENT
4 PostgreSQL BEGIN; ALTER ...; error -> ROLLBACK (expected, not run)
5 MySQL ALTER commits implicitly; error; column exists, version not bumped (expected, not run)The naive autogenerated revision from Autogenerate hit exactly row 1 in a real run. email_outbox was created and booking altered, then room.floor NOT NULL failed and the version stayed at 0001. The re-run failed with table email_outbox already exists (runs/autogen-diff-upgrade-fails.txt).
Real scenario: a MySQL deploy that dies halfway through a five-statement revision at 02:00 and needs hand repair; a PostgreSQL revision that blocks the booking table for twenty minutes because its UPDATE and ALTER share one transaction; a SQLite-backed desktop app that ships migrations to users' machines and must not leave half-applied files.
| Engine | Transactional DDL | Recovery after a mid-revision failure |
|---|---|---|
| PostgreSQL | yes, except statements that must run outside a transaction block (CREATE INDEX CONCURRENTLY) | fix and re-run, if the revision has no autocommit_block(); otherwise only if it is written to be re-runnable (existence checks, if_not_exists), as 0004 is |
| MySQL 8.4 | no: implicit commit per DDL statement; each single statement is atomic ("atomic DDL") | inspect, undo or finish by hand, stamp |
SQLite + sqlite3 default | effectively no (driver sends no BEGIN) | as MySQL (real) |
SQLite + BEGIN recipe / Python 3.12 autocommit=False | yes | fix and re-run (real) |
Fix / how to use it: one statement's worth of risk per revision on MySQL; transaction_per_migration=True so a failure only rolls back one revision on PostgreSQL; the BEGIN recipe (or connect_args={"autocommit": False} on Python 3.12+) where SQLite migrations must be atomic; and after any failure on a non-transactional engine, compare alembic current with the real schema before re-running.
Expand/contract in Alembic: nullable first, backfill in batches, then NOT NULL Must-know
In plain words: Never make a change that the currently running code cannot survive. Add things in a compatible way first (expand), deploy code that uses them, move the data, and only then remove or tighten (contract). In Alembic terms that is several small revisions spread over several deploys.
Common misunderstanding: "A NOT NULL column is always unsafe" or "always safe with a default". A server_default does protect old writers: they omit the column, and the database fills it ("Column defaults are only invoked when there is no value present for a column in a SQL DML statement"), and PostgreSQL adds a column with a constant default without rewriting the table ("making the ALTER TABLE very fast even on large tables"). So ADD COLUMN floor INTEGER NOT NULL DEFAULT 0 is a legitimate one-step expand when one constant is a correct value for every old and future row. It is the wrong tool when the real value differs per row (it hides missing data behind a fake 0), when the default is volatile (PostgreSQL then updates every row), or when old code explicitly writes NULL. For floor, 0 is not true for most rooms, which is why the snippet goes nullable first, backfills, then adds NOT NULL, and on PostgreSQL a direct SET NOT NULL would scan the whole table under ACCESS EXCLUSIVE. The theory (why, rollout windows, renames) is in Schema Migrations. This block shows the Alembic files.
Definition: The snippet's chain is 0002 add_column(floor, nullable=True) (expand), then the app writes floor, then 0003 backfills in batches (data), then 0004 sets NOT NULL (contract). PostgreSQL's ALTER TABLE page explains the contract step: "SET NOT NULL ... Ordinarily this is checked during the ALTER TABLE by scanning the entire table ... however, if a valid CHECK constraint exists (and is not dropped in the same command) which proves no NULL can exist, then the table scan is skipped." And on NOT VALID: "the ADD CONSTRAINT command does not scan the table and can be committed immediately. After that, a VALIDATE CONSTRAINT command can be issued ... validation acquires only a SHARE UPDATE EXCLUSIVE lock on the table being altered." SQLAlchemy accepts postgresql_not_valid=True "as an additional keyword argument within the operation that creates the constraint".
revision 0004 on PostgreSQL (real render, runs/offline-postgresql.sql.txt; locks per the PostgreSQL docs, not run)
1 BEGIN;
2 ALTER TABLE room ADD CONSTRAINT ck_room_floor_not_null CHECK (floor IS NOT NULL) NOT VALID; -- no scan
3 ALTER TABLE booking ADD CONSTRAINT ck_booking_end_after_start CHECK (end_date > start_date) NOT VALID;
4 COMMIT; -- ACCESS EXCLUSIVE released
5 ALTER TABLE room VALIDATE CONSTRAINT ck_room_floor_not_null; -- scan, SHARE UPDATE EXCLUSIVE
6 ALTER TABLE booking VALIDATE CONSTRAINT ck_booking_end_after_start;
7 BEGIN;
8 ALTER TABLE room ALTER COLUMN floor SET NOT NULL; -- scan skipped: valid CHECK
9 ALTER TABLE room DROP CONSTRAINT ck_room_floor_not_null;
10 UPDATE alembic_version SET version_num='0004' ...; COMMIT;Real scenario: adding floor while three replicas serve traffic (this page); renaming price_cents to price_minor with dual writes over two deploys; splitting full_name into first_name/last_name; changing an INTEGER id to BIGINT with a shadow column.
| Step | Revision / deploy | Old code still running? | Safe because |
|---|---|---|---|
| Expand | 0002: nullable column, no default | yes | old INSERTs omit it, NULL allowed |
| Write | app v2 | rolling out | new code writes it, reads tolerate NULL |
| Backfill | 0003 (or a job) | no (v1 gone) or yes | idempotent WHERE floor IS NULL, small batches |
| Contract | 0004: NOT NULL / CHECK | must be gone | every writer sets the column |
| Cleanup | later revision drops old columns | must be gone | nothing reads them |
Fix / how to use it: split every incompatible change into expand → code → backfill → contract revisions; deploy them separately; on PostgreSQL use NOT VALID + VALIDATE + SET NOT NULL; test the contract revision against a database with rows (the snippet's test_contract_step_refuses_rows_that_were_not_backfilled shows the failure you want CI to catch).
Building indexes without blocking writes: CREATE INDEX CONCURRENTLY, autocommit_block, lock_timeout Must-know
In plain words: A normal CREATE INDEX on PostgreSQL blocks inserts, updates and deletes on the table until the index is built. CREATE INDEX CONCURRENTLY does not, but it cannot run inside a transaction. Alembic's autocommit_block() commits the revision's transaction, runs the statements in autocommit mode, then starts a new transaction. lock_timeout makes any DDL give up quickly instead of queueing behind a long query.
Common misunderstanding: "CONCURRENTLY is just slower." It also fails differently. A failed concurrent build leaves an INVALID index behind that still costs write overhead, and only one concurrent build per table can run at a time. Second: "lock_timeout is about the statement's duration." It limits waiting for a lock. statement_timeout limits the whole statement, and a long CONCURRENTLY build may need a larger value or 0 ("A value of zero (the default) disables the timeout").
Definition: PostgreSQL: "When this option is used, PostgreSQL will build the index without taking any locks that prevent concurrent inserts, updates, or deletes on the table; whereas a standard index build locks out writes (but not reads) on the table until it's done." "a regular CREATE INDEX command can be performed within a transaction block, but CREATE INDEX CONCURRENTLY cannot." "If a problem arises while scanning the table, such as a deadlock or a uniqueness violation in a unique index, the CREATE INDEX command will fail but leave behind an 'invalid' index." lock_timeout: "Abort any statement that waits longer than the specified amount of time while attempting to acquire a lock on a table, index, row, or other database object." Alembic: autocommit_block() is "intended to support the occasional database DDL or system operation that specifically has to be run outside of any kind of transaction block", and "the database transaction preceding the block is unconditionally committed", so "It is recommended that when an application includes migrations with 'autocommit' blocks, that EnvironmentContext.transaction_per_migration be used".
why lock_timeout matters for an ALTER (expected, not run; PostgreSQL lock queue)
1 T1 (report) BEGIN; SELECT ... FROM booking; -- runs 10 minutes, holds ACCESS SHARE
2 T2 (migration) ALTER TABLE booking ADD CONSTRAINT ...; -- needs ACCESS EXCLUSIVE: waits behind T1
3 T3..Tn (app) INSERT INTO booking ...; -- queue behind T2: the whole API stalls
4 with SET lock_timeout = '5s' in env.py: T2 fails after 5 s, T3..Tn proceed, the Job retries laterReal scenario: an index on a 200-million-row booking table during business hours; an ALTER TYPE booking_status ADD VALUE 'no_show' (the runtime API docs' own autocommit_block example); a migration that waits behind an analyst's open transaction and freezes checkout.
| Need | Alembic | Rendered SQL (real render for PostgreSQL) |
|---|---|---|
| Index without blocking writes | op.create_index(..., postgresql_concurrently=True) in autocommit_block() | COMMIT; CREATE INDEX CONCURRENTLY ...; BEGIN; |
| Drop index without blocking | op.drop_index(..., postgresql_concurrently=True) | DROP INDEX CONCURRENTLY ix_booking_room_id; |
| Unique index online | unique=True + postgresql_concurrently=True | on failure: INVALID index; drop and retry |
| Fail fast on locks | SET lock_timeout = '5s' in env.py | first line of the script |
| Cap runaway statements | SET statement_timeout = '15min' | raise for big CONCURRENTLY builds |
| MySQL online index | raw op.execute("ALTER TABLE ... ADD INDEX ..., ALGORITHM=INPLACE, LOCK=NONE") | expected, not run |
Fix / how to use it: transaction_per_migration=True in env.py, every big-table index in its own revision inside autocommit_block() with postgresql_concurrently=True, lock_timeout set for every migration session, and a runbook step that checks for INVALID indexes after a failed run.
Running migrations at deploy: Job, init container, never at startup with multiple replicas Must-know
In plain words: Migrations run once per release, from one process, before the new application version takes traffic. In Kubernetes that is usually a Job (or a Helm hook Job) and sometimes an init container, and on a PaaS it is a release command. They are not run by the application at startup, because ten replicas would try to migrate the same database at the same moment.
Common misunderstanding: "An init container runs once." It runs once per pod: ten replicas mean ten migration attempts racing on alembic_version. The other misconception is "Alembic will serialise concurrent runs". None of the Alembic pages saved for this chapter describe a migration lock, so two concurrent upgrade head runs are something to prevent, not something to rely on. Laravel added migrate --isolated (an atomic cache lock) for exactly this. With Alembic, guaranteeing a single runner is your job.
Definition: Kubernetes: "A Job creates one or more Pods and will continue to retry execution of the Pods until a specified number of them successfully terminate." Init containers "run to completion during Pod initialization" and "Init containers always run to completion." Helm's pre-upgrade hook "Executes on an upgrade request after templates are rendered, but before any resources are updated", which is where a migration Job usually hangs. The architecture of the Job (backoff, deadlines, secrets) is in Kubernetes Workloads, the pipeline stage in CI/CD Pipelines.
release N+1 (expected, not run: no Kubernetes in the build environment)
1 CI: alembic check; upgrade/downgrade round trip; render --sql; build image (contains migrations/)
2 helm upgrade: pre-upgrade hook Job "migrate": alembic upgrade head (one pod, DATABASE_URL from a Secret)
3 Job succeeds -> Deployment rolls pods to N+1 (old pods still serve: schema is expand-compatible)
4 Job fails -> release stops; pods stay on N; alembic current tells where it stopped
5 never: FastAPI lifespan: command.upgrade(cfg, "head") x 10 replicasReal scenario: a three-replica FastAPI Deployment migrated by a Helm pre-upgrade hook; a single VM where alembic upgrade head && exec uvicorn ... in one systemd unit is acceptable because there is exactly one process; a serverless function that cannot run DDL at all and gets its schema from a pipeline step.
| Where | Runs | Good for | Risk |
|---|---|---|---|
| CI/CD step before deploy | once | most teams | needs network access to the DB |
| Kubernetes Job / Helm hook | once per release | Kubernetes | hook ordering, cleanup of old Jobs |
| Init container | once per pod | single-replica apps | races with replicas > 1 |
| App startup (lifespan) | once per process | local dev only | races, slow starts, app needs DDL rights |
DBA applies --sql | once, by hand | regulated environments | drift if someone skips a step |
Fix / how to use it: one runner per release (pipeline step or Job), the image contains migrations/, the migration role has DDL rights and the app role does not, the deploy waits for the Job, and the app at startup at most checks the revision (cookbook: "Test current database revision is at head(s)") instead of applying it.
Testing migrations: upgrade downgrade round trip, stairway, alembic check Must-know
In plain words: Migration tests run the real revision files against a real (throwaway) database. The round trip runs upgrade head, downgrade base, upgrade head again and checks that the schema is the same. The stairway does up/down/up for every single revision. alembic check runs the autogenerate comparison against a database at head and fails if it would write any operation. It inherits every autogenerate blind spot: the docs note it "uses the same model comparison process as the alembic revision --autogenerate process", and the snippet's own test shows a named CHECK constraint that differs and is not reported. A clean check means "no difference autogenerate can see", not "identical schemas".
Common misunderstanding: "My app tests pass, so the migrations are fine." App tests usually build the schema with create_all, so they never execute a revision. And "round trip on an empty database is enough": batch mode, backfills and NOT NULL steps only fail with rows present. That is why the snippet seeds bookings before the contract revision and asserts the counts.
Definition: "When developing code it's useful to know if a set of code changes has made any net change to the database model, such that new revisions would need to be generated. To automate this, Alembic provides the alembic check command." It "returns an error code plus a message if it is detected that new operations would be rendered into a new revision". With a model change and no revision the real CLI run prints FAILED: New upgrade operations detected: [('add_column', None, 'room', Column('view', AutoString(length=20), table=<room>))] and exits 255 (runs/check-drift.txt). On a database that is behind it fails with Target database is not up to date. (real test). Alembic 1.9.0 added the command.
the snippet's migration tests (real, 70 tests in total)
1 test_revision_chain_is_linear heads == ["0006"]; walk order 0001..0006
2 test_upgrade_downgrade_round_trip_... snapshot(head) == snapshot(head after base and back)
3 test_stairway_each_revision_up_down_up[0001..0006] six parametrised steps
4 test_contract_on_populated_tables_keeps_child_rows 3 rooms, 3 bookings survive batch mode
5 test_alembic_check_is_clean_at_head_but_warns_... No new upgrade operations detected. (+ UserWarning)
6 test_alembic_check_fails_when_the_database_is_behind Target database is not up to date.Real scenario: a pull request adds a model field but forgets the revision, so alembic check fails CI; a downgrade that forgot to drop an index fails the stairway; a contract revision passes on an empty database and fails on staging data, unless the test seeds rows.
| Test | Catches | Needs |
|---|---|---|
alembic check | model change without revision | database at head |
| Round trip | broken downgrades, leftovers | file database |
| Stairway | one bad step among many | parametrised test |
| Seeded upgrade | NOT NULL / batch / backfill on real rows | fixture rows at the right revision |
| One head | parallel revisions not merged | ScriptDirectory.get_heads() |
| Offline render | CONCURRENTLY outside the transaction, missing NOT VALID | --sql for the production dialect |
| Production-dialect run | PostgreSQL-only behaviour | PostgreSQL in CI (expected, not run here) |
Fix / how to use it: a migration test module like the snippet's: file database per test (tmp_path), schema snapshots compared through the inspector plus sqlite_master for expression indexes, seeded rows before risky revisions, alembic check and a single-head assertion, and the same suite against PostgreSQL in CI.
Async Alembic: async env.py and run_sync Important
In plain words: Alembic's API is synchronous. With an async driver (asyncpg, aiosqlite), env.py creates an async engine, opens an AsyncConnection and calls await connection.run_sync(do_run_migrations), which runs the normal synchronous migration code on that connection.
Common misunderstanding: "An async app needs async migrations." The revision files stay exactly the same. Only env.py's runner changes, and a sync URL (postgresql+psycopg://) works just as well for the migration Job even when the app uses asyncpg. The other trap is calling asyncio.run() from inside an already running event loop (for example, from a pytest-asyncio test or the app's lifespan), which raises because a loop is already running. There you pass a connection in through config.attributes instead.
Definition: Cookbook: "Alembic currently does not provide an async api directly, but it can use an use SQLAlchemy Async engine to run the migrations and autogenerate. New configurations can use the template 'async' or 'pyproject_async' to bootstrap an environment which can be used with async DBAPI like asyncpg, running the command: alembic init -t async". The generated async env.py (real, runs/init-async-env.py.txt) uses poolclass=pool.NullPool and await connection.run_sync(do_run_migrations). The snippet's env.py picks the async path when make_url(url).get_dialect().is_async.
$ DATABASE_URL=sqlite+aiosqlite:///async.db alembic upgrade head (real, runs/cli-async.txt)
1 run_migrations_online(): dialect is_async -> asyncio.run(run_async_migrations(url))
2 create_async_engine(url, poolclass=NullPool); async with engine.connect() as connection:
3 await connection.run_sync(do_run_migrations) # sync Alembic on the async connection
4 Running upgrade -> 0001 ... -> 0006
5 $ alembic current -> 0006 (head); test_async_url_upgrades_and_downgrades also runs downgrade baseReal scenario: a FastAPI service on asyncpg whose migration Job uses the same URL; a test suite with an async engine that migrates its schema with run_sync inside the fixture; a team that keeps a sync driver only for migrations.
| Setup | URL | env.py |
|---|---|---|
| Sync app, sync migrations | postgresql+psycopg:// | generic template |
| Async app, async migrations | postgresql+asyncpg:// | async template, run_sync |
| Async app, sync migrations | app: asyncpg; Job: psycopg | generic template, two URLs |
| Migrations from inside a running loop | async engine, connection.run_sync(lambda c: command.upgrade(...)) | cookbook "Programmatic API use (connection sharing) With Asyncio" |
Fix / how to use it: one env.py that handles both, as in the snippet; NullPool for the migration engine; never asyncio.run inside a running loop; revision files unchanged.
Transactions in the Session: Session.begin, commit as you go, rollback Must-know
In plain words: A SQLAlchemy Session opens a transaction automatically on its first statement ("autobegin"). You end it either by calling commit() or rollback() yourself ("commit as you go"), or by wrapping the work in with session.begin():, which commits when the block ends normally and rolls back when it raises ("begin once").
Common misunderstanding: "I need with session.begin() to have a transaction." You already have one after the first query. begin() only changes who ends it. The opposite error: wrapping the route body in session.begin() and committing in the dependency means two places own the same transaction. The session chapter covers flush and object states. This block is about the boundary.
Definition: SQLAlchemy names the two styles "Commit as you go" and "Begin Once". In the second, "Both sessionmaker and Engine feature a Engine.begin() method that will both procure a new object with which to execute SQL statements (the Session and Connection, respectively) and then return a context manager that will maintain a begin/commit/rollback context for that object." The snippet's create_booking_with_outbox() uses with session.begin():, then session.flush() to get booking.id, then adds the outbox row. Both rows commit together, or the CHECK violation rolls both back (counts == (0, 0), real).
create_booking_with_outbox(end < start) (real, test_begin_block_rolls_back_both_rows_on_a_constraint_error)
1 with session.begin(): BEGIN (implicit)
2 session.add(Booking(...))
3 session.flush() INSERT INTO booking ... -> CHECK constraint failed: ck_booking_end_after_start
4 block exits with IntegrityError ROLLBACK
5 SELECT count(*) booking, email_outbox -> (0, 0)Real scenario: a booking plus its confirmation-mail outbox row; a transfer that debits one account and credits another; an import job where each file is one with session.begin() block.
| Style | Code | Ends the transaction | Fits |
|---|---|---|---|
| Commit as you go | session.add(x); session.commit() | your explicit call | FastAPI routes (commit in the route) |
| Begin once | with session.begin(): ... | block exit | services, jobs, the snippet's helpers |
| Factory begin | with factory.begin() as session: | block exit, session closed | scripts, workers |
| Engine/Core | with engine.begin() as conn: | block exit | migrations, raw SQL |
| Rollback | session.rollback() | now | after a caught IntegrityError |
Fix / how to use it: pick one owner of the transaction per unit of work: the route, a service function with session.begin(), or a unit-of-work dependency. After a caught database error, rollback() before using the session again.
Savepoints: begin_nested Must-know
In plain words: A savepoint is a bookmark inside a transaction. with session.begin_nested(): sets one. If the block fails, only the work since the bookmark is undone, and the outer transaction continues. Use it for "try this row, skip it if it fails".
Common misunderstanding: "A released savepoint is committed." It is part of the outer transaction and disappears with it on rollback. That holds on PostgreSQL, and on SQLite only with the BEGIN recipe. In Python's default sqlite3 mode no BEGIN is ever sent when the first statement is a SAVEPOINT, so each released savepoint is its own transaction. The real tests show it twice: a Core connection keeps its row after the outer rollback (legacy: 1, recipe: 0), and the snippet's own savepoint import, forced to fail after its loop, keeps 2 bookings on the default engine and 0 with the recipe.
Definition: "SAVEPOINT transactions, if supported by the underlying engine, may be delineated using the Session.begin_nested() method". "Each time Session.begin_nested() is called, a new 'BEGIN SAVEPOINT' command is emitted to the database within the scope of the current database transaction (starting one if not already in progress) ... When the .commit() method on this object is called, 'RELEASE SAVEPOINT' is emitted to the database, and if instead the .rollback() method is called, 'ROLLBACK TO SAVEPOINT' is emitted." SQLAlchemy's SQLite page warns: "as the SAVEPOINT statement does not imply a BEGIN, a new SAVEPOINT emitted before a BEGIN will function on its own but fails to participate in the enclosing transaction, meaning a ROLLBACK of the transaction will not rollback elements that were part of a released savepoint."
import_bookings(4 rows; row 1 breaks the CHECK, row 2 the FK) on the BEGIN-recipe engine (real, test_savepoint_per_row_...)
1 BEGIN -> emitted by SQLAlchemy's "begin" event
2 SAVEPOINT sa_savepoint_1; INSERT row 0; RELEASE SAVEPOINT -> imported
3 SAVEPOINT sa_savepoint_2; INSERT row 1 -> CHECK constraint failed: ck_booking_end_after_start; ROLLBACK TO SAVEPOINT
4 SAVEPOINT sa_savepoint_3; INSERT row 2 -> FOREIGN KEY constraint failed; ROLLBACK TO SAVEPOINT
5 SAVEPOINT sa_savepoint_4; INSERT row 3; RELEASE SAVEPOINT -> imported
6 COMMIT -> imported [0, 3], skipped [1, 2]; 4 SAVEPOINT and 2 ROLLBACK statements countedReal scenario: a CSV import that reports bad lines instead of failing; "insert, and on duplicate key fetch the existing row" inside a larger transaction; a test fixture that wraps each test in a savepoint (see Testing FastAPI).
| Engine | begin_nested() | Notes |
|---|---|---|
| PostgreSQL | SAVEPOINT / ROLLBACK TO SAVEPOINT | after an error inside the savepoint the outer transaction stays usable (expected, not run) |
| MySQL InnoDB | SAVEPOINT | DDL inside still commits implicitly |
| SQLite + BEGIN recipe | correct (real: outer failure leaves 0 rows) | needs isolation_level = None + BEGIN event |
SQLite, sqlite3 default | no BEGIN at all; each released savepoint is committed on its own (real: outer failure leaves 2 rows) | skipping bad rows still works; atomicity of the batch does not |
Fix / how to use it: one savepoint per independently failing unit inside a session.begin() block, catch IntegrityError outside the begin_nested() block (it has already rolled back to the savepoint), and on SQLite always use the BEGIN recipe (or Python 3.12's autocommit=False) when savepoints are involved.
Expire on commit Important
In plain words: After commit(), the Session forgets the attribute values of every object it holds (expire_on_commit=True, the default), so the next read fetches fresh values with a SELECT. Outside the session that read is impossible and raises DetachedInstanceError.
Common misunderstanding: "expire_on_commit=False is a performance hack." It is a correctness choice for code that reads objects after the commit: async code, and response serialisation after a dependency-owned commit. The values may then be stale by the time you read them, but no hidden SQL runs. The ORM chapter covers object states in depth (Flush, commit and object states).
Definition: The real tests show both sides. With the default, reading room.name after commit() sends exactly 1 SELECT, and with expire_on_commit=False it sends 0. A booking returned from create_booking_with_outbox() after the session closed raises DetachedInstanceError: Instance <Booking at 0x...> is not bound to a Session; attribute refresh operation cannot proceed.
expire_on_commit after commit: read room.name after close: read booking.id (real)
1 True (default) 1 SELECT (refresh) DetachedInstanceError
2 False 0 statements value from memoryReal scenario: a unit-of-work dependency that commits after the route returned an ORM object; an AsyncSession where an implicit refresh would raise MissingGreenlet; a background job that logs the ids of objects after commit.
| Code path | Recommended |
|---|---|
Commit in the route, then refresh() and return | default is fine |
| Commit in a dependency after the route returns | expire_on_commit=False (the snippet's default in create_app) |
AsyncSession | async_sessionmaker(..., expire_on_commit=False) |
| Long-lived objects after commit | re-query in a new session |
Fix / how to use it: choose per sessionmaker, not per call: make_session_factory(engine, expire_on_commit=False) for web and async code that serialises after commit.
Isolation level per connection: execution_options(isolation_level=...) Important
In plain words: The isolation level decides which concurrent changes a transaction can see. You can set it for the whole engine (create_engine(..., isolation_level=...)) or for one connection with conn.execution_options(isolation_level="SERIALIZABLE"). What each level guarantees per database is in Isolation Levels.
Common misunderstanding: "AUTOCOMMIT is an isolation level." SQLAlchemy accepts it in the same parameter, but it is a driver mode: each statement commits on its own. In the real test the connection reports AUTOCOMMIT in its execution options while get_isolation_level() still returns the database's SERIALIZABLE. The other trap is portability. SQLite through pysqlite accepts only READ UNCOMMITTED, SERIALIZABLE and AUTOCOMMIT, and REPEATABLE READ raises Invalid value 'REPEATABLE READ' for isolation_level. Valid isolation levels for 'sqlite' are READ UNCOMMITTED, SERIALIZABLE, AUTOCOMMIT (real).
Definition: "For an individual Connection object that's acquired from Engine.connect(), the isolation level can be set for the duration of that Connection object using the Connection.execution_options() method. The parameter is known as Connection.execution_options.isolation_level and the values are strings which are typically a subset of the following names: 'AUTOCOMMIT' 'READ COMMITTED' 'READ UNCOMMITTED' 'REPEATABLE READ' 'SERIALIZABLE'. Not every DBAPI supports every value; if an unsupported value is used for a certain backend, an error is raised." With the ORM, bind a Session to such a connection (Session(bind=conn)) or use session.connection(execution_options={"isolation_level": ...}) before the first statement.
isolation_of(engine, level) (real, SQLite 3.54 + pysqlite)
1 None -> SERIALIZABLE (SQLite's default as reported)
2 "READ UNCOMMITTED" -> READ UNCOMMITTED (PRAGMA read_uncommitted)
3 "AUTOCOMMIT" -> get_isolation_level(): SERIALIZABLE; execution option: AUTOCOMMIT
4 "REPEATABLE READ" -> ArgumentError: Invalid value 'REPEATABLE READ' for isolation_level ...Real scenario: a monthly report at REPEATABLE READ so all its queries see one snapshot (PostgreSQL); a wallet transfer at SERIALIZABLE with a retry loop; CREATE INDEX CONCURRENTLY from application code with AUTOCOMMIT, which is what Alembic's autocommit_block() does underneath.
| Default level | PostgreSQL | MySQL InnoDB | SQLite |
|---|---|---|---|
| Engine default | READ COMMITTED | REPEATABLE READ | SERIALIZABLE (as reported) |
| Values accepted by SQLAlchemy | AUTOCOMMIT, READ COMMITTED, READ UNCOMMITTED, REPEATABLE READ, SERIALIZABLE | same | READ UNCOMMITTED, SERIALIZABLE, AUTOCOMMIT (real) |
| Serialization failures | 40001 at REPEATABLE READ and SERIALIZABLE | deadlocks (1213) instead | database is locked (busy, not a serialization failure) |
Fix / how to use it: keep the engine at the database default, raise the level per connection for the few operations that need it, and pair every SERIALIZABLE use with the retry loop below.
Retrying serialization failures Must-know
In plain words: At REPEATABLE READ and SERIALIZABLE, PostgreSQL may abort a transaction with SQLSTATE 40001 to protect consistency, and any engine can abort one of two deadlocked transactions (40P01 on PostgreSQL, error 1213 on MySQL). The right reaction is to run the whole transaction again from the start, in a new transaction, a bounded number of times.
Common misunderstanding: "Retry the failed statement." The database aborted the transaction, and every value you read in it may be stale. The retry has to re-read. The other misconception: "SQLite's database is locked is the same thing." It means another connection holds the write lock (busy timeout exceeded). Retrying helps, but it is not a serialization anomaly, so the snippet's is_retryable() treats it as a separate case.
Definition: PostgreSQL: "Applications using this level must be prepared to retry transactions due to serialization failures." "When an application receives this error message, it should abort the current transaction and retry the whole transaction from the beginning." The error codes appendix lists 40001 serialization_failure, 40P01 deadlock_detected and 55P03 lock_not_available. The snippet's run_in_transaction(factory, work, attempts=3) opens a new Session and session.begin() per attempt and retries on 40001/40P01 (read from orig.sqlstate or orig.pgcode), MySQL 1213/1205, and SQLite's "database is locked".
real run: another connection holds SQLite's write lock for 0.25 s (test_retry_whole_unit_of_work_...)
1 holder: BEGIN IMMEDIATE; INSERT ... (write lock held; commits after 0.25 s)
2 attempt 1: new Session, BEGIN, INSERT room 'Retried' -> OperationalError: database is locked (timeout=0)
3 log: retryable error on attempt 1: database is locked; sleep 0.05 x attempt
4 attempt 2, 3 ...: same until the holder commits
5 attempt n: INSERT, SELECT id, COMMIT -> returns the new idReal scenario: a seat reservation at SERIALIZABLE under load; two transfers that lock accounts in opposite order and deadlock; a SQLite-backed worker that collides with a nightly import.
| Error | Engine | Retry? | How |
|---|---|---|---|
40001 serialization_failure | PostgreSQL | yes | whole transaction, backoff |
40P01 deadlock_detected | PostgreSQL | yes | whole transaction; fix lock order too |
1213 ER_LOCK_DEADLOCK (SQLSTATE 40001): "Deadlock found when trying to get lock; try restarting transaction" | MySQL | yes | whole transaction |
1205 ER_LOCK_WAIT_TIMEOUT: "Lock wait timeout exceeded; try restarting transaction" | MySQL | maybe | whole transaction, or fail fast |
55P03 lock_not_available (NOWAIT, lock_timeout) | PostgreSQL | maybe | the caller decides (409, retry later) |
database is locked | SQLite | yes, briefly | busy timeout, then whole transaction |
23505 / UNIQUE constraint failed | any | no | business error (409) |
Fix / how to use it: wrap retryable units in a function that takes a fresh Session, so the whole unit can run again. Keep side effects (HTTP calls, e-mails) out of it, or move them to the outbox. Cap the attempts and add backoff. Laravel's DB::transaction(fn, attempts: 5) does the same for deadlocks.
Unit of work per request: commit in the route or commit in the dependency Must-know
In plain words: One HTTP request should be one unit of work with exactly one commit point. Two placements work: the route commits explicitly (this KB's default), or a unit-of-work dependency commits after the route returns, declared with Depends(..., scope="function") so the commit runs before the response is sent. Committing after yield with the default scope is the one placement that does not work.
Common misunderstanding: "Commit in the dependency is cleaner, so put it after yield." With the default "request" scope that code runs after the response. The real test returns 201 and the booking table stays empty when the commit fails. The other belief, "scope=function means the response is built after the session closed", is wrong for 0.128.8: the real test with expire_on_commit=True returns a full body, so serialisation ran before the commit and close. Where the default teardown runs is analysed in Dependency Injection.
Definition: FastAPI: "if you know that you won't need to use the dependency after returning from the path operation function, you can use Depends(scope="function") to tell FastAPI that it should close the dependency after the path operation function returns, but before the response is sent." "If not specified and the dependency has yield, it will have a scope of "request" by default." The snippet has three routes: /bookings (commit in the route, 409/422 from IntegrityError), /bookings/uow (get_uow with scope="function") and /bookings/uow-late (same dependency, default scope, anti-pattern).
commit forced to fail with a before_commit listener (real, tests/test_api.py)
1 POST /bookings/uow route returns -> response serialised -> get_uow: commit() raises -> 500; table empty
2 POST /bookings/uow-late route returns -> 201 sent to the client -> get_uow: commit() raises -> table empty
3 POST /bookings commit in the route raises -> 500 too (test_commit_in_route_failure_is_a_500); a CHECK failure at flush -> 422Real scenario: a booking API whose clients retry on 5xx but not on 201 (a lost write after 201 is never retried); a service layer that wants routes free of commit() calls; a test suite that overrides the session dependency and must still see one commit per request.
| Placement | Status reflects commit | Who owns errors | Verdict |
|---|---|---|---|
Route calls session.commit() | yes | the route (409/422 mapping) | default here |
Depends(get_uow, scope="function") | yes (500 on failure) | the dependency; map known errors in the route before return | good |
Depends(get_uow) (default scope) | no (201 then failure) | nobody | never |
Service function with session.begin() | yes | the service | good for reuse outside HTTP |
Fix / how to use it: commit in the route (or in a service with session.begin()). If you want the commit in a dependency, give it scope="function", keep expire_on_commit=False for safety, and test the failure path with a before_commit listener as the snippet does.
Row locks from the ORM: with_for_update, skip_locked, nowait Must-know
In plain words: select(Room).where(Room.id == 1).with_for_update() sends SELECT ... FOR UPDATE. On PostgreSQL and MySQL, the row is then locked until the transaction ends, and a second transaction that wants it waits. nowait=True makes the second one fail immediately instead, and skip_locked=True makes it skip locked rows (the job-queue pattern).
Common misunderstanding: "with_for_update() protects me on SQLite too." SQLite has no row locks, and SQLAlchemy silently omits the clause there (real compile: no FOR UPDATE). A test suite on SQLite therefore cannot catch a missing lock. Second: "a lock outside a transaction still helps." The lock ends with the transaction, so a SELECT ... FOR UPDATE in one session and the write in another gives no protection. Which lock to choose and why is in Optimistic vs Pessimistic Locking.
Definition: Select.with_for_update(*, nowait=False, read=False, of=None, skip_locked=False, key_share=False): "When called with no arguments, the statement will render with the suffix FOR UPDATE." nowait "will render FOR UPDATE NOWAIT on Oracle Database and PostgreSQL dialects", read "will render LOCK IN SHARE MODE on MySQL, FOR SHARE on PostgreSQL", skip_locked "will render FOR UPDATE SKIP LOCKED", key_share "will render FOR NO KEY UPDATE". PostgreSQL: "With NOWAIT, the statement reports an error, rather than waiting, if a selected row cannot be locked immediately. With SKIP LOCKED, any selected rows that cannot be immediately locked are skipped."
two workers claim outbox rows (expected on PostgreSQL, not run; SQLite run claims sequentially)
1 W1 BEGIN; SELECT ... WHERE status='pending' ORDER BY id LIMIT 3 FOR UPDATE SKIP LOCKED -> 1,2,3 locked
2 W2 BEGIN; same statement -> 4,5 (skips 1-3)
3 W1 UPDATE email_outbox SET status='sending' WHERE id IN (1,2,3); COMMIT
4 W2 UPDATE ... WHERE id IN (4,5); COMMIT
real on SQLite (test_claim_outbox_batch_...): first claim [1, 2, 3], second claim [4, 5], status 'sending'Real scenario: two guests booking the last free night of the same room (lock the room row, then check overlaps); an outbox or e-mail queue drained by several workers; an admin screen that should fail fast with "someone else is editing" (nowait).
| ORM call | PostgreSQL (compiled, real) | MySQL (compiled, real) | SQLite |
|---|---|---|---|
.with_for_update() | FOR UPDATE | FOR UPDATE | omitted |
nowait=True | FOR UPDATE NOWAIT | FOR UPDATE NOWAIT | omitted |
skip_locked=True | FOR UPDATE SKIP LOCKED | FOR UPDATE SKIP LOCKED | omitted |
read=True | FOR SHARE | LOCK IN SHARE MODE | omitted |
key_share=True | FOR NO KEY UPDATE | FOR UPDATE | omitted |
of=Room (in a join) | FOR UPDATE OF room | depends on version | omitted |
Fix / how to use it: lock inside the same transaction that writes; lock the parent row (the room) to serialise competing child inserts (bookings); skip_locked for queues, nowait for "fail fast" UIs; test lock behaviour against PostgreSQL in CI, because SQLite tests pass without it.
Indexes and constraints from the ORM: Index, index=True, composite, partial, expression, UniqueConstraint, CheckConstraint Must-know
In plain words: Indexes and constraints are declared on the model (Field(index=True), Field(unique=True), __table_args__ = (Index(...), CheckConstraint(...))) so that autogenerate and alembic check know about them, and they reach the database through a migration. Which index to build is a database design question (Indexing). This block is about how to declare it.
Common misunderstanding: "index=True on every foreign key is free." Each index costs work on every write. In the snippet, ix_booking_room_id was a left prefix of the composite ix_booking_room_id_start_date, so revision 0005 drops it. Second: "the partial index works the same everywhere." MySQL has no partial indexes: the real MySQL render of 0005 drops the WHERE and builds a full index. The expression index needs ((lower(email))) on MySQL, while Alembic rendered (lower(email)), which MySQL's rules reject ("enclose expressions within parentheses", expected, not run).
Definition: SQLModel's Field(index=True) creates Index("ix_<table>_<column>") (here ix_room_name), and unique=True together with index=True makes it a unique index. Index(name, *expressions, unique=False, **dialect_kw) accepts columns, column names and SQL expressions (func.lower(text("email"))) plus dialect keywords such as postgresql_where=, sqlite_where=, postgresql_using=, postgresql_include= and postgresql_concurrently=. UniqueConstraint("name") and CheckConstraint("end_date > start_date", name="end_after_start") go in __table_args__ and take their final names from the naming convention.
declared in app/models.py created by revision DDL (SQLite, real)
1 Field(index=True, unique=True) on email 0001 (autogenerate) CREATE UNIQUE INDEX ix_user_email ON "user" (email)
2 Index("ix_booking_room_id_start_date", ...) 0005 (hand-written) CREATE INDEX ... ON booking (room_id, start_date)
3 Index(..., sqlite_where=..., postgresql_where=) 0005 ... WHERE cancelled_at IS NULL
4 Index("ix_user_email_lower", func.lower(...)) 0005 (autogenerate skips it) CREATE INDEX ix_user_email_lower ON "user" (lower(email))
5 CheckConstraint(..., name="end_after_start") 0004 (autogenerate misses it) CONSTRAINT ck_booking_end_after_start CHECK (...)Real scenario: availability queries filter room_id and a date range on active bookings only (partial composite index); case-insensitive login by e-mail (expression index or a citext column on PostgreSQL); a data rule "end after start" that every writer must respect, including SQL consoles (CHECK).
| Declaration | SQLModel / SQLAlchemy | Autogenerate (1.16.5) | Migration op |
|---|---|---|---|
| Single-column index | Field(index=True) | yes | op.create_index("ix_room_name", "room", ["name"]) |
| Unique index | Field(unique=True, index=True) | yes | unique=True |
| Unique constraint | UniqueConstraint("a", "b") | yes, if named | op.create_unique_constraint(op.f("uq_..."), ...) |
| Composite index | Index("ix_...", "room_id", "start_date") | yes | op.create_index(..., ["room_id", "start_date"]) |
| Partial index | postgresql_where=text(...), sqlite_where= | yes | same keywords |
| Expression index | Index("ix_...", func.lower(text("email"))) | skipped on SQLite (warning) | [sa.text("lower(email)")] |
| Check constraint | CheckConstraint(..., name=...) | no (1.19.0+ optional) | op.create_check_constraint |
| Foreign key | Field(foreign_key="room.id", ondelete=...) | yes | op.create_foreign_key |
Fix / how to use it: declare every index and constraint on the model so alembic check sees most of them. Create them in hand-reviewed revisions, with CONCURRENTLY on big PostgreSQL tables. Drop redundant left-prefix indexes, and check what each dialect renders with --sql.
SQLModel and Alembic gotchas Important
In plain words: SQLModel works with Alembic, but a handful of small things go wrong in almost every project. Most of them come from SQLModel's own column type and from the fact that both tools read the same models at import time.
Common misunderstanding: "If autogenerate ran, the revision file is importable." The real 0001 contains sqlmodel.sql.sqltypes.AutoString(length=100). Without import sqlmodel in the template, the file fails with NameError the first time anyone runs it, often only in CI.
Definition: The list below comes from the snippet's real runs. str fields become AutoString (a VARCHAR, with length from max_length). Data models without table=True add nothing to the metadata. sa_column=Column(...) and sa_column_kwargs={"server_default": ...} are how you reach SQLAlchemy options that Field lacks. A Field(default=...) is a Python-side default and never appears in the DDL, while server_default does.
gotcha symptom (real unless marked) fix
1 no `import sqlmodel` in script.py.mako NameError: name 'sqlmodel' is not defined (expected) template line
2 models module not imported in env.py autogenerate proposes dropping every table (real probe) import app.models
3 guests: int = 1 (Python default only) DDL: guests INTEGER NOT NULL, no DEFAULT (real) sa_column_kwargs server_default
4 naming convention set after the classes constraints keep backend names set it first
5 revision imports app.models breaks when the model changes later sa.table() in the revision
6 expression index on SQLite UserWarning on every autogenerate / check accept, or filter in include_object
7 SET / PRAGMA in env.py before context.configure() exit 0, nothing recorded (real probe) commit first (prepare_session)Real scenario: a new developer's first autogenerated revision breaks CI; an outbox table whose status default lives only in Python, so rows inserted by a SQL console get NULL; a refactor that renames app/models.py to app/db/models.py and silently empties the metadata in env.py.
| Item | SQLModel | Plain SQLAlchemy 2.0 |
|---|---|---|
| Metadata | SQLModel.metadata | Base.metadata (DeclarativeBase) |
| String type in revisions | sqlmodel.sql.sqltypes.AutoString | sa.String |
| Server default | sa_column_kwargs={"server_default": ...} | mapped_column(server_default=...) |
| Table args | __table_args__ on the class | same |
| Migration helpers | none ("use Alembic directly") | none (Alembic is the tool) |
Fix / how to use it: template with import sqlmodel, models imported in env.py, naming convention first, server defaults where other writers exist, and a CI job that runs alembic upgrade head on an empty database so a broken revision fails before review.
Mechanics
What alembic upgrade head does, step by step Important
$ DATABASE_URL=sqlite:///rooms.db alembic upgrade head (real; the snippet's env.py)
1 Config("alembic.ini"): script_location=%(here)s/migrations, prepend_sys_path=. -> sys.path
2 ScriptDirectory loads versions/*.py, builds the graph from revision/down_revision; resolves "head" -> 0006
3 env.py runs: import app.models (fills SQLModel.metadata); context.is_offline_mode() -> False
4 database_url(): DATABASE_URL; not async -> create_engine(url, poolclass=NullPool); connect()
prepare_session(): PRAGMA foreign_keys=OFF (SET lock_timeout ... on PostgreSQL), then COMMIT
5 context.configure(connection, target_metadata, compare_type, compare_server_default,
render_as_batch=True (sqlite), transaction_per_migration=True)
6 log: Context impl SQLiteImpl. / Will assume non-transactional DDL.
7 SELECT version_num FROM alembic_version -> table missing -> CREATE TABLE alembic_version (version_num VARCHAR(32) ...)
8 for each pending revision: begin transaction -> upgrade() -> INSERT/UPDATE alembic_version -> commit
9 log: Running upgrade 0005 -> 0006, create email_outbox with server defaults
10 connection closed, engine disposed; exit code 0 (255 with "FAILED: ..." on failure, real)The SQL Alembic renders per dialect Must-know
The same six revisions, rendered by alembic upgrade head --sql for PostgreSQL (real render by Alembic 1.16.5, not executed on a server; excerpt from runs/offline-postgresql.sql.txt). Note the timeouts before the first BEGIN, one transaction per revision, and the COMMIT that autocommit_block() inserts around the CONCURRENTLY statements:
SET lock_timeout = '5s';
SET statement_timeout = '15min';
BEGIN;
CREATE TABLE alembic_version (
version_num VARCHAR(32) NOT NULL,
CONSTRAINT alembic_version_pkc PRIMARY KEY (version_num)
);
-- Running upgrade -> 0001
CREATE TABLE room (
id SERIAL NOT NULL,
name VARCHAR(100) NOT NULL,
capacity INTEGER NOT NULL,
price_cents INTEGER NOT NULL,
version INTEGER NOT NULL,
CONSTRAINT pk_room PRIMARY KEY (id)
);
CREATE UNIQUE INDEX ix_room_name ON room (name);
-- (user, booking, ix_user_email, ix_booking_room_id omitted)
INSERT INTO alembic_version (version_num) VALUES ('0001') RETURNING alembic_version.version_num;
COMMIT;
BEGIN;
-- Running upgrade 0001 -> 0002
ALTER TABLE room ADD COLUMN floor INTEGER;
ALTER TABLE booking ADD COLUMN cancelled_at TIMESTAMP WITHOUT TIME ZONE;
UPDATE alembic_version SET version_num='0002' WHERE alembic_version.version_num = '0001';
COMMIT;
BEGIN;
-- Running upgrade 0002 -> 0003
UPDATE room SET floor=0 WHERE room.floor IS NULL;
UPDATE alembic_version SET version_num='0003' WHERE alembic_version.version_num = '0002';
COMMIT;
BEGIN;
-- Running upgrade 0004 -> 0005
COMMIT;
CREATE INDEX CONCURRENTLY ix_booking_room_id_start_date ON booking (room_id, start_date);
CREATE INDEX CONCURRENTLY ix_booking_active_room ON booking (room_id, start_date, end_date) WHERE cancelled_at IS NULL;
CREATE INDEX CONCURRENTLY ix_user_email_lower ON "user" (lower(email));
DROP INDEX CONCURRENTLY ix_booking_room_id;
BEGIN;
UPDATE alembic_version SET version_num='0005' WHERE alembic_version.version_num = '0004';
COMMIT;
BEGIN;
-- Running upgrade 0005 -> 0006
CREATE TABLE email_outbox (
id SERIAL NOT NULL,
booking_id INTEGER NOT NULL,
status VARCHAR(20) DEFAULT 'pending' NOT NULL,
created_at TIMESTAMP WITHOUT TIME ZONE DEFAULT (CURRENT_TIMESTAMP) NOT NULL,
sent_at TIMESTAMP WITHOUT TIME ZONE,
CONSTRAINT pk_email_outbox PRIMARY KEY (id),
CONSTRAINT fk_email_outbox_booking_id_booking FOREIGN KEY(booking_id) REFERENCES booking (id) ON DELETE CASCADE
);
CREATE INDEX ix_email_outbox_status_id ON email_outbox (status, id);
UPDATE alembic_version SET version_num='0006' WHERE alembic_version.version_num = '0005';
COMMIT;The same revisions for MySQL (real render, runs/offline-mysql.sql.txt, excerpt). There is no BEGIN/COMMIT at all ("Will assume non-transactional DDL."), the contract step is MODIFY, the partial index lost its WHERE, and the expression index lacks the extra parentheses MySQL requires:
ALTER TABLE room ADD COLUMN floor INTEGER;
ALTER TABLE booking ADD COLUMN cancelled_at DATETIME;
UPDATE room SET floor=0 WHERE room.floor IS NULL;
ALTER TABLE room MODIFY floor INTEGER NOT NULL;
ALTER TABLE booking ADD CONSTRAINT ck_booking_end_after_start CHECK (end_date > start_date);
CREATE INDEX ix_booking_room_id_start_date ON booking (room_id, start_date);
CREATE INDEX ix_booking_active_room ON booking (room_id, start_date, end_date);
CREATE INDEX ix_user_email_lower ON user (lower(email));
DROP INDEX ix_booking_room_id ON booking;And what batch mode actually executes on SQLite for revision 0004 (real sqlalchemy.engine log with parameters removed, runs/batch-echo.txt):
CREATE TABLE _alembic_tmp_room (
id INTEGER NOT NULL,
name VARCHAR(100) NOT NULL,
capacity INTEGER NOT NULL,
price_cents INTEGER NOT NULL,
version INTEGER NOT NULL,
floor INTEGER NOT NULL,
CONSTRAINT pk_room PRIMARY KEY (id)
);
INSERT INTO _alembic_tmp_room (id, name, capacity, price_cents, version, floor)
SELECT room.id, room.name, room.capacity, room.price_cents, room.version, room.floor FROM room;
DROP TABLE room;
ALTER TABLE _alembic_tmp_room RENAME TO room;
CREATE UNIQUE INDEX ix_room_name ON room (name);
-- the same four steps for booking, now carrying CONSTRAINT ck_booking_end_after_start CHECK (end_date > start_date)
UPDATE alembic_version SET version_num='0004' WHERE alembic_version.version_num = '0003';
COMMIT;The SQL blocks above are trimmed: trailing spaces after commas are removed, the PostgreSQL script skips the user and booking tables of 0001 and the 0003 → 0004 step (shown in Expand/contract), and the INFO log lines interleaved by Alembic are dropped.
Exact errors, warnings and outputs Must-know
Every line below was printed by the snippet's runs (runs/*.txt, runs/pytest-v.txt).
| Trigger | Exception / exit | Exact output |
|---|---|---|
Before app: model has floor, table does not | OperationalError | no such column: room.floor |
| Naive autogenerated NOT NULL column on rows | OperationalError | Cannot add a NOT NULL column with default value NULL / [SQL: ALTER TABLE room ADD COLUMN floor INTEGER NOT NULL] |
| Re-running that half-applied revision | OperationalError | table email_outbox already exists |
| Contract step with a row that was not backfilled | IntegrityError | NOT NULL constraint failed: _alembic_tmp_room.floor |
| Broken revision, re-run (SQLite default mode) | OperationalError | duplicate column name: note |
Autogenerate with target_metadata = None | FAILED, exit 255 | Can't proceed with --autogenerate option; environment script ... does not provide a MetaData object or sequence of objects to the context. |
| Expression index during autogenerate / check | UserWarning | autogenerate skipping metadata-specified expression-based index 'ix_user_email_lower'; dialect 'sqlite' under SQLAlchemy 2.0.58 can't reflect these indexes so they can't be compared |
| Same, from the inspector | SAWarning | Skipped unsupported reflection of expression-based index ix_user_email_lower |
alembic check at head | exit 0 | No new upgrade operations detected. |
alembic check on a database at 0005 | CommandError | Target database is not up to date. |
alembic check after adding room.view to the model only | FAILED, exit 255 | New upgrade operations detected: [('add_column', None, 'room', Column('view', AutoString(length=20), table=<room>))] |
env.py runs a statement before configure() without committing | exit 0 (!) | alembic current prints nothing; alembic_version has 0 rows (runs/env-statement-before-configure-probe.txt) |
Two heads, upgrade head | CommandError | Multiple head revisions are present for given argument 'head'; please specify a specific target revision, '<branchname>@head' to narrow to a specific head, or 'heads' for all heads |
--sql with batch mode on SQLite | FAILED, exit 255 | This operation cannot proceed in --sql mode; batch mode with dialect sqlite requires a live database connection with which to reflect the table "room". |
op.alter_column(type_=...) on SQLite | OperationalError | near "TYPE": syntax error |
op.drop_constraint on SQLite | NotImplementedError | No support for ALTER of constraints in SQLite dialect. Please refer to the batch mode feature which allows for SQLite migrations using a copy-and-move strategy. |
Booking with end_date before start_date | IntegrityError → 422 | {"detail":"Rejected by the database: CHECK constraint failed: ck_booking_end_after_start"} |
| Import row for room 999 (FKs on) | IntegrityError in a savepoint | FOREIGN KEY constraint failed |
| Object read after commit and close | DetachedInstanceError | Instance <Booking at 0x...> is not bound to a Session; attribute refresh operation cannot proceed |
| Unsupported isolation level on SQLite | ArgumentError | Invalid value 'REPEATABLE READ' for isolation_level. Valid isolation levels for 'sqlite' are READ UNCOMMITTED, SERIALIZABLE, AUTOCOMMIT |
| Second writer while SQLite is write-locked | OperationalError (retried) | database is locked; log retryable error on attempt 1: database is locked |
| Data migration log | INFO | backfilled room.floor in 3 batches of up to 2 rows |
| SQLite context | INFO | Context impl SQLiteImpl. / Will assume non-transactional DDL. |
| PostgreSQL context (offline) | INFO | Context impl PostgresqlImpl. / Generating static SQL / Will assume transactional DDL. |
Solving the classic problems
| Problem | Symptom | Fix | Cost |
|---|---|---|---|
Schema from create_all | no such column after a deploy | Alembic, stamp head once to adopt | one-time setup |
| Autogenerated NOT NULL on a populated table | migration fails, half-applied on SQLite/MySQL | nullable → backfill → NOT NULL | three revisions |
| Rename detected as add + drop | data deleted on deploy | op.alter_column(new_column_name=...) or expand/contract | review |
| Unnamed constraints | cannot drop them portably | naming convention before the models | one dict |
| SQLite ALTER limitations | near "TYPE", NotImplementedError | render_as_batch=True, batch_alter_table | slower copy |
| Batch with FKs on | child rows silently deleted | migrate with an engine without the FK pragma | small |
| Long lock on PostgreSQL | API stalls during the migration | lock_timeout, CONCURRENTLY, NOT VALID | runbook |
| Two heads | Multiple head revisions | alembic merge heads + single-head test | one revision |
| Migrations at startup in every replica | races, slow starts | Job / pipeline step | deploy change |
| Revision imports app models | old revisions break later | sa.table() inside the revision | a few lines |
Commit after yield (default scope) | 201 for a lost write | commit in the route or scope="function" | one line |
| Savepoint on SQLite without BEGIN | rows survive the outer rollback | BEGIN recipe / autocommit=False (3.12+) | two listeners |
| Double booking race | two overlapping bookings | lock the room row (with_for_update) or exclusion constraint | one option |
| Serialization failures | random 500s at SERIALIZABLE | retry the whole unit of work | a wrapper |
One schema history, reviewed and tested
The Before app had no history at all. The After project keeps every change in versions/, checks in CI that the chain has one head and that alembic check reports nothing (within autogenerate's limits), and runs the round trip and the stairway on a file database. Seeding rows before risky revisions turns "works on an empty database" into "works on data". That is how test_contract_step_refuses_rows_that_were_not_backfilled caught the missed row with a clear error before production could.
Changes the running code can survive
Revision 0002 adds only nullable columns, 0003 fills them in batches, 0004 tightens them, and on PostgreSQL it does so through NOT VALID and VALIDATE, so the long scan never holds ACCESS EXCLUSIVE. 0005 builds indexes CONCURRENTLY outside the transaction. Each file is safe for the code version that is running while it applies.
A failure you can recover from
transaction_per_migration=True keeps a PostgreSQL failure limited to one revision. On MySQL and on SQLite in default driver mode a failed revision leaves earlier statements behind, so each revision does as little as possible, and the runbook says: compare alembic current with the actual schema, finish or undo by hand, then stamp. For SQLite files that must stay consistent (desktop apps, tests), the BEGIN recipe makes revisions atomic (real test).
One transaction boundary per request
The route commits, or a scope="function" dependency commits. Both put the commit before the response, which the real tests prove by forcing the commit to fail: a 500, not a 201. Every database error that is a business answer (CHECK, unique, overlap) is mapped in the route to 409/422, and every retryable error is handled by re-running the whole unit with a fresh session.
Choosing
| Situation | Use | Extra technique | Reason |
|---|---|---|---|
| New FastAPI + SQLModel project | Alembic, generic template, env.py reading DATABASE_URL | naming convention, import sqlmodel in the template | standard, reviewable |
| Async app (asyncpg) | async template or sync driver for the Job | run_sync, NullPool | revisions stay sync |
| SQLite in dev/tests, PostgreSQL in production | render_as_batch=True for SQLite only | dialect branches in risky revisions | one chain for both |
| Add NOT NULL column to a big table | expand/contract over 2–3 deploys | PostgreSQL: NOT VALID + VALIDATE | no long exclusive lock |
| Index on a big PostgreSQL table | own revision, autocommit_block(), postgresql_concurrently=True | check for INVALID after failure | writes keep flowing |
| DBA-controlled production | alembic upgrade head --sql per release | attach the script to the change ticket | no DDL rights for the app |
| Large backfill | separate job between expand and contract | batches, idempotent WHERE | no deploy-time lock |
| Kubernetes | Job or Helm pre-upgrade hook | one runner, wait for completion | no replica race |
| Request writes several rows | one commit per request | session.begin() or commit in the route | atomic |
| Partial success allowed | begin_nested() per item | catch IntegrityError outside the block | skip bad rows |
| Competing writers on one row | with_for_update() on the parent row | nowait=True for UIs | serialised writes |
| Job queue in SQL | with_for_update(skip_locked=True) | small batches, ORDER BY id | workers never wait |
| Money or seats at SERIALIZABLE | per-connection isolation_level | retry loop on 40001 / 40P01 | correctness under concurrency |
Alembic vs the alternatives
| Question | Alembic | Laravel migrations | goose | golang-migrate | atlas |
|---|---|---|---|---|---|
| Language of migrations | Python (op.*) or raw SQL via op.execute | PHP Schema builder | SQL (-- +goose Up / Down) or Go | SQL files (*.up.sql / *.down.sql) | HCL/SQL/ORM desired state + generated migrations |
| Ordering | down_revision graph (branches, merges) | timestamped file names | versioned files | versioned files | migration directory |
| Diff from models | autogenerate (review required) | no (hand-written) | no | no | yes, declarative ("Similar to Terraform") |
| Version record | alembic_version | the migrations table (with batches) | goose_db_version | not in the README | not in the README |
| Transactions | transaction_per_migration=True (dialect permitting) | not in the migrations page | "By default, all migrations are run within a transaction" | not in the README | not in the README |
| No-transaction escape | autocommit_block() | not in the migrations page | -- +goose NO TRANSACTION | not in the README | not in the README |
| Preview the SQL | --sql | migrate --pretend | n/a | n/a | atlas migrate diff, atlas schema apply plan |
| Concurrency guard | none described in the saved Alembic docs (use one Job) | migrate --isolated | not in the README | not in the README | not in the README |
The Laravel, goose, golang-migrate and atlas columns state only what their saved pages say. "Not in the README" means the page does not say, not that the tool lacks the feature. Schema Migrations compares the tools in depth.
In architecture: from a single process to a distributed system
Monolith: one process, one database
One FastAPI app, one Alembic environment in the repository, one alembic_version row, migrations applied by the deploy pipeline before the new process starts. This chapter's snippet is that shape. Requests use one Session per request with the commit in the route, the booking route locks the room row, and the outbox row is written in the same transaction as the booking. A typical shop backend follows the same pattern: orders, order lines and stock reservations in one transaction, with_for_update() on the product row for the last item, a nightly report at REPEATABLE READ, and every schema change as an expand/contract pair in the same pull request series.
Modular monolith and multiple databases
Several modules in one process, still one database: one Alembic environment with branch labels per module (billing@head), or several environments with their own version_table (alembic_version_billing) and include_object filters so each environment only sees its own tables. Two databases means two environments (or the multidb template) and two engines in the app. There is no transaction spanning both, so a write that touches both goes through an outbox in one of them. Revisions of one module must never alter another module's tables. That rule is what lets a module become a service later.
Microservices
Each service owns its database and its migrations. A booking service migrates booking and email_outbox, a rooms service migrates room, and neither touches the other's schema. Backward compatibility now crosses services: a column a consumer reads through an API or an event cannot be dropped until every consumer stopped reading it. The expand/contract discipline applies to API fields and event payloads exactly as to columns. Transactions end at the service boundary. "Book a room and charge the card" is a saga, and each local step is one transaction plus an outbox row. That is the snippet's create_booking_with_outbox(), which a relay process later publishes. Per-service migration Jobs run in each service's own release.
Distributed data: replicas, caches, sharded databases, multi-region
Replicas apply the primary's DDL through replication, so a long ALTER or a non-concurrent index build on the primary also lags every replica behind it, and read-your-writes breaks for its duration. Large backfills cause the same lag and need batching and pauses. On a sharded database (an engine per shard, or Citus), a migration is "run on every shard", either with an environment that loops over shard URLs or with the distributed database's own DDL propagation. A shard that fails leaves the fleet on two schema versions, which is fine only if every revision is expand-compatible. Caches hold serialised data of the old shape after a deploy. Version the cache keys with the schema-relevant model version. Multi-region writes add clock and conflict problems that a row lock in one region does not solve, so idempotency keys and per-region ownership come first.
Scaling path: 1×, 10×, 100×
| Load | What changes | Migration and transaction practice |
|---|---|---|
| 1× (one process, small tables) | defaults work | Alembic in the pipeline, round-trip tests, commit in the route, with_for_update on hot rows |
| 10× (replicas, tables in the millions) | locks hurt, deploys overlap | expand/contract always, lock_timeout, CONCURRENTLY, NOT VALID, migration Job, retries on 40001/40P01, skip_locked queues |
| 100× (many services, huge tables) | backfills take hours, many teams | backfills as jobs with throttling, online schema-change tools on MySQL, per-service migrations, contract steps scheduled weeks later, schema-change review as a team process (Schema Migrations) |
Lab
All commands run from docs/snippets/python/alembic-migrations-transactions/. Outputs marked "real" were produced on CPython 3.9.6 (macOS) with the pinned versions and SQLite 3.54.0. The transcripts are saved under pipeline/sources/alembic-migrations-transactions/runs/. Python 3.12 with Alembic 1.20, SQLAlchemy 2.1 and SQLModel 0.0.50 was not run (unverified): expect different version numbers in the logs and, on SQLAlchemy 2.1, possibly different warning texts. The PostgreSQL step is "expected, not run".
1. Install and run the tests (real)
python3 -m venv ~/venvs/alembic # keep the venv outside the repo
~/venvs/alembic/bin/pip install --upgrade pip # pip 21 on 3.9 is too old for some pyproject installs
~/venvs/alembic/bin/pip install '.[test]' # (the verified run installed from a scratch copy)
PYTHONDONTWRITEBYTECODE=1 ~/venvs/alembic/bin/python -m pytest
# real: 70 passed in 1.6s (runs/pytest-v.txt lists every test)2. Walk the commands (real)
Transcript: runs/lab-2-3.txt (this exact sequence, scratch copy of the final tree).
export DATABASE_URL=sqlite:///rooms.db # use a scratch directory, not the repository
alembic current # (empty)
alembic upgrade head # Running upgrade -> 0001 ... 0005 -> 0006
alembic current # 0006 (head)
alembic history # <base> -> 0001, create user room booking ... 0005 -> 0006 (head)
alembic check # No new upgrade operations detected. (+ the expression-index UserWarning)
alembic downgrade -1 # Running downgrade 0006 -> 0005, create email_outbox with server defaults
alembic stamp head # Running stamp_revision 0005 -> 0006 <- no DDL ran! the table is gone
alembic check # Detected added table 'email_outbox' ... FAILED: New upgrade operations detected (exit 255)
alembic stamp 0005 # Running stamp_revision 0006 -> 0005 <- put the bookmark back
alembic upgrade head # Running upgrade 0005 -> 0006
alembic downgrade base && sqlite3 rooms.db .tables # ... Running downgrade 0001 -> ; alembic_version
alembic upgrade head # back to 0006The stamp head after downgrade -1 is deliberately wrong: the bookmark says 0006 while email_outbox does not exist. alembic check notices this particular lie because a missing table is something autogenerate can see. A missing CHECK constraint would have passed silently. A downgrade from the wrong bookmark would try to drop an index that is not there, which is why the lab stamps back to 0005 before going on.
3. Watch batch mode copy a table (real)
# alembic-echo.ini = a copy of alembic.ini in the same directory with [logger_sqlalchemy] level = INFO
export DATABASE_URL=sqlite:///batch.db # a fresh database: Lab 2 left rooms.db at 0006
alembic upgrade 0003
sqlite3 batch.db "INSERT INTO room (name,capacity,price_cents,version,floor) VALUES ('Garden',2,9000,1,0);"
alembic -c alembic-echo.ini upgrade 0004
# real: CREATE TABLE _alembic_tmp_room ... INSERT INTO _alembic_tmp_room ... SELECT ... FROM room
# DROP TABLE room; ALTER TABLE _alembic_tmp_room RENAME TO room; CREATE UNIQUE INDEX ix_room_name ...
# then the same for bookingKeep the copy next to the original: script_location = %(here)s/migrations resolves relative to the file passed with -c. (Instead of a fresh file, alembic downgrade 0003 on rooms.db works too.)
4. Break it: the naive autogenerated revision (real)
Changing the models does not change the migration files, so this lab needs a history that really stops at v1. Transcript: runs/lab-4.txt.
# scratch copy of the project; delete versions 0002..0006 so versions/ holds only 0001 (the v1 schema)
export DATABASE_URL=sqlite:///v1.db
alembic upgrade head # Running upgrade -> 0001 (v1: no floor, no outbox)
sqlite3 v1.db "INSERT INTO room (name,capacity,price_cents,version) VALUES ('Garden',2,9000,1),('Loft',3,12000,1);"
# app/models.py is the head schema; autogenerate the difference between it and v1.db:
alembic revision --autogenerate --rev-id 9999 -m "diff to final models"
# Detected added table 'email_outbox' ... Detected added column 'room.floor'
# UserWarning: autogenerate skipping metadata-specified expression-based index 'ix_user_email_lower'
alembic upgrade head
# Running upgrade 0001 -> 9999, diff to final models
# sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) Cannot add a NOT NULL column with default value NULL
# [SQL: ALTER TABLE room ADD COLUMN floor INTEGER NOT NULL]
sqlite3 v1.db "select version_num from alembic_version" # 0001
sqlite3 v1.db ".tables" # alembic_version booking email_outbox room user <- half applied
alembic upgrade head # table email_outbox already exists5. Render the production script (real render, not executed)
DATABASE_URL=postgresql://app@localhost/rooms alembic upgrade head --sql > up-postgresql.sql
DATABASE_URL=mysql+pymysql://app@localhost/rooms alembic upgrade head --sql > up-mysql.sql
grep -n "CONCURRENTLY\|NOT VALID\|COMMIT" up-postgresql.sql | head
# COMMIT; then CREATE INDEX CONCURRENTLY ix_booking_room_id_start_date ...; ... NOT VALID ...
grep -c "BEGIN" up-mysql.sql # 0
DATABASE_URL=sqlite:///x.db alembic upgrade head --sql # FAILED: ... batch mode with dialect sqlite requires a live database connectionNo driver was installed for PostgreSQL or MySQL: offline mode needs only the SQLAlchemy dialect.
6. PostgreSQL for real (expected, not run)
# expected, not run: no Docker or PostgreSQL server in the build environment
docker run --rm -d -p 5432:5432 -e POSTGRES_PASSWORD=app --name pg postgres:18
pip install 'psycopg[binary]'
export DATABASE_URL=postgresql+psycopg://postgres:app@localhost:5432/postgres
alembic upgrade head # expected: "Will assume transactional DDL."
# terminal B: alembic downgrade 0003 -- first, with nobody else connected (its DROP CONSTRAINT also needs ACCESS EXCLUSIVE)
# terminal A (psql): BEGIN; SELECT * FROM booking; -- now open a reader and keep it open
# terminal B: alembic upgrade 0004
# expected: the bad-row counts pass (they only read), then ADD CONSTRAINT ... NOT VALID waits for A's lock
# and fails after 5 s: ERROR: canceling statement due to lock timeout (SQLSTATE 55P03);
# nothing was committed yet, alembic current still says 0003
# terminal A: COMMIT; terminal B: alembic upgrade head -- succeeds
# two psql sessions running the outbox claim with FOR UPDATE SKIP LOCKED: each gets different rowsFor PHP/Laravel developers
Laravel's migrations solve the same problem with a different model. Its docs put it this way: "Migrations are like version control for your database, allowing your team to define and share the application's database schema definition. If you have ever had to tell a teammate to manually add a column to their local database schema after pulling in your changes from source control, you've faced the problem that database migrations solve." Migrations are ordered by timestamped file names rather than by a down_revision graph, so there are no branches to merge. Applied files are recorded in a migrations table in "batches", and php artisan migrate:rollback undoes the last batch (Alembic: downgrade to a revision). php artisan migrate --pretend shows "the SQL statements that will be executed by the migrations without actually running them", which is Alembic's --sql. php artisan migrate --force skips the production prompt. For multi-server deploys Laravel has a guard that none of the saved Alembic pages describe: "you may use the isolated option when invoking the migrate command", and "Laravel will acquire an atomic lock using your application's cache driver before attempting to run your migrations". There is no autogenerate, since every migration is written with the Schema builder, so renames are explicit. On the transaction side, DB::transaction(fn, attempts: 5) retries "when a deadlock occurs", the counterpart of the snippet's run_in_transaction, and lockForUpdate() is with_for_update().
// database/migrations/2026_11_29_000002_add_floor_to_rooms.php (Laravel 13): the expand step
return new class extends Migration {
public function up(): void
{
Schema::table('rooms', function (Blueprint $table) {
$table->integer('floor')->nullable(); // 0002: nullable first
});
}
public function down(): void
{
Schema::table('rooms', fn (Blueprint $table) => $table->dropColumn('floor'));
}
};
// BookingController@store: one transaction, room row locked, retried on deadlock (= run_in_transaction)
$booking = DB::transaction(function () use ($data) {
$room = Room::whereKey($data['room_id'])->lockForUpdate()->firstOrFail(); // with_for_update()
abort_if($room->bookings()->overlapping($data)->exists(), 409, 'Room already booked');
$booking = $room->bookings()->create($data);
EmailOutbox::create(['booking_id' => $booking->id]); // same transaction
return $booking;
}, attempts: 5);
// deploy step (one server or a Kubernetes Job): php artisan migrate --force --isolated| Laravel | Alembic / SQLAlchemy |
|---|---|
php artisan make:migration add_floor_to_rooms | alembic revision -m "add floor" (or --autogenerate) |
php artisan migrate | alembic upgrade head |
php artisan migrate:rollback / --step=5 | alembic downgrade -1 / downgrade <rev> |
php artisan migrate:status | alembic current + alembic history -i |
php artisan migrate --pretend | alembic upgrade head --sql |
php artisan migrate --isolated | one Job / pipeline step (no lock described in the saved Alembic docs) |
php artisan schema:dump | no equivalent; squash by hand into a new base revision |
migrations table with batches | alembic_version (current revision only) |
Schema::table(...)->change() | op.alter_column(...) (batch on SQLite) |
| Timestamp ordering | down_revision graph, alembic merge heads |
DB::transaction(fn, attempts: 5) | run_in_transaction(factory, work, attempts=5) |
lockForUpdate() / sharedLock() | with_for_update() / with_for_update(read=True) |
The Go angle
Go services usually manage schema with a standalone tool and plain SQL files. goose describes itself as "a database migration tool. Both a CLI and a library", with SQL migrations annotated -- +goose Up / -- +goose Down. It states that "By default, all migrations are run within a transaction" and offers -- +goose NO TRANSACTION for statements like CREATE INDEX CONCURRENTLY, the counterpart of autocommit_block(). golang-migrate is "Database migrations written in Go. Use as CLI or import as library", with *.up.sql/*.down.sql pairs. atlas is declarative: "Similar to Terraform, Atlas compares the current state of the database to the desired state, as defined in an HCL, SQL, or ORM schema", which is the closest thing to autogenerate. On the transaction side Go has no Session or unit of work. Code calls pool.Begin(ctx) and then tx.Commit(ctx), sets the isolation level per transaction in pgx.TxOptions, and retries on SQLSTATE 40001 itself. The connection and transaction details are in database/sql and pgx, and the tool comparison in Schema Migrations.
// Go (pgx v5): the booking transaction with a row lock and a retry on 40001/40P01.
// Migration side: goose file 00005_booking_indexes.sql starts with "-- +goose NO TRANSACTION"
// and contains CREATE INDEX CONCURRENTLY ... (the autocommit_block() equivalent).
func Book(ctx context.Context, pool *pgxpool.Pool, b Booking) (int64, error) {
for attempt := 1; ; attempt++ {
id, err := bookOnce(ctx, pool, b)
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && (pgErr.Code == "40001" || pgErr.Code == "40P01") && attempt < 3 {
time.Sleep(time.Duration(attempt) * 50 * time.Millisecond)
continue // retry the WHOLE transaction, as run_in_transaction does
}
return id, err
}
}
func bookOnce(ctx context.Context, pool *pgxpool.Pool, b Booking) (int64, error) {
tx, err := pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.ReadCommitted})
if err != nil {
return 0, err
}
defer tx.Rollback(ctx) // no-op after Commit
if _, err := tx.Exec(ctx, `SELECT id FROM room WHERE id = $1 FOR UPDATE`, b.RoomID); err != nil {
return 0, err // with_for_update()
}
var id int64
if err := tx.QueryRow(ctx, `INSERT INTO booking (room_id, start_date, end_date, guests)
VALUES ($1, $2, $3, $4) RETURNING id`, b.RoomID, b.Start, b.End, b.Guests).Scan(&id); err != nil {
return 0, err // CHECK / FK violations surface here (SQLSTATE 23514 / 23503)
}
if _, err := tx.Exec(ctx, `INSERT INTO email_outbox (booking_id) VALUES ($1)`, id); err != nil {
return 0, err
}
return id, tx.Commit(ctx)
}| SQLAlchemy / Alembic | Go |
|---|---|
Alembic revision (op.*) | goose / golang-migrate SQL file |
alembic upgrade head | goose up, migrate up |
| autogenerate from models | atlas migrate diff from a desired schema |
autocommit_block() | -- +goose NO TRANSACTION |
alembic_version | goose_db_version |
with session.begin(): | tx, _ := pool.Begin(ctx); defer tx.Rollback(ctx); ...; tx.Commit(ctx) |
begin_nested() | tx.Begin(ctx) ("pseudo nested transaction" with a savepoint, pgx tx.go) |
execution_options(isolation_level=...) | pgx.TxOptions{IsoLevel: pgx.Serializable} |
with_for_update(skip_locked=True) | ... FOR UPDATE SKIP LOCKED in the SQL string |
run_in_transaction retry | loop on pgconn.PgError.Code == "40001" |
Common misconceptions
| Belief | Reality |
|---|---|
create_all() keeps the schema up to date | It only creates missing tables; existing tables never change (real: no such column: room.floor) |
| Autogenerate writes correct migrations | It writes candidates: renames become add + drop, NOT NULL columns fail on rows, CHECKs and expression indexes are missed |
| An empty autogenerate means the schema matches | Not for CHECK constraints (1.16.5), expression indexes on SQLite, or server defaults without compare_server_default |
| Revision files run in file-name order | Order comes from down_revision; names are cosmetic |
| A failed migration rolls back | Only with transactional DDL and a driver that sends BEGIN; SQLite default mode and MySQL leave earlier statements applied |
stamp fixes a broken migration | It moves the bookmark only; the schema is untouched |
downgrade restores data | It restores structure; dropped data is gone |
| Batch mode is a slow ALTER | It drops and recreates the table; with SQLite foreign keys ON that cascades into child tables (real: 3 → 0 bookings) |
| A NOT NULL column needs nullable-first in every case | With a constant server_default that is a correct value for all rows it is one safe step (old writers get the default); nullable-first is for per-row values and backfills |
CREATE INDEX CONCURRENTLY works in any migration | It cannot run in a transaction block; use autocommit_block() and transaction_per_migration=True |
lock_timeout limits how long the migration runs | It limits waiting for each lock; statement_timeout limits run time |
Running alembic upgrade head at app startup is convenient | With several replicas it races; run it once per deploy from a Job or pipeline step |
| An init container runs once per release | It runs once per pod |
| Data migrations can use the app's models | Models describe head; a revision must work against its own point in history |
| Two heads mean a corrupt history | Normal after parallel work; alembic merge heads |
| A released savepoint is committed | It is part of the outer transaction; on SQLite default mode it does escape it, because no BEGIN is sent (real: 2 rows survive) |
Commit after yield is the same as committing in the route | With the default scope it runs after the response: 201 for a lost write (real) |
with_for_update() is tested by my SQLite suite | SQLite has no row locks and the clause is omitted (real compile) |
AUTOCOMMIT is an isolation level | It is a driver mode; the database still reports its level (real) |
| Retrying the failed statement is enough | After 40001 / 40P01 the whole transaction must run again |
Cheat sheet
| Topic | Remember |
|---|---|
| Setup | alembic init migrations (or -t async); import sqlmodel in script.py.mako; import app.models in env.py; commit any SET/PRAGMA before context.configure() |
| URL | os.environ.get("DATABASE_URL") or config.get_main_option("sqlalchemy.url") |
| Metadata | target_metadata = SQLModel.metadata; naming convention set before the first model |
| configure() | compare_type=True, compare_server_default=True, render_as_batch=(dialect == "sqlite"), transaction_per_migration=True |
| New revision | alembic revision --autogenerate -m "...", then review every line |
| Review checklist | renames, NOT NULL on old rows, data steps, CHECKs, expression indexes, op.f() names, existing_type= |
| Apply | alembic upgrade head; downgrade -1; current; history; heads; stamp head only to adopt |
| CI | alembic check; one head; round trip; stairway; seeded rows; --sql for the production dialect |
| SQLite | batch mode; migration engine without the FK pragma; BEGIN recipe for atomic revisions |
| PostgreSQL | lock_timeout, statement_timeout; NOT VALID + VALIDATE + SET NOT NULL; CONCURRENTLY in autocommit_block() |
| MySQL | each DDL commits implicitly; one risky statement per revision; no partial indexes; ((expr)) for expression indexes |
| Zero downtime | expand (nullable first) → code → backfill in batches → contract |
| Deploy | one Job / pipeline step before the rollout; never at startup with multiple replicas |
| Async env | create_async_engine(url, poolclass=NullPool); await connection.run_sync(do_run_migrations) |
| Request transaction | commit in the route, or Depends(get_uow, scope="function"); never commit after yield in default scope |
| Savepoint | with session.begin_nested(): per item inside with session.begin(): |
| Isolation | conn.execution_options(isolation_level="SERIALIZABLE") per connection |
| Retry | new Session per attempt on 40001 / 40P01 / MySQL 1213; bounded, with backoff |
| Locks | .with_for_update(), nowait=True, skip_locked=True, read=True, of=Room |
| Indexes | Field(index=True), Index(name, *cols, postgresql_where=..., sqlite_where=...), func.lower(...), UniqueConstraint, CheckConstraint(name=...) |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why is SQLModel.metadata.create_all() not a migration tool, and where is it still the right choice? Must-know
Answer
Answer: It only creates tables that do not exist. It never alters an existing table, never drops anything, and records nothing about which schema is live. A model change therefore reaches new databases but not old ones: the Before app's test gets no such column: room.floor (real). It is still right for throwaway test databases and demos. Every shared database (dev, CI, staging, production) should be built and evolved by alembic upgrade head, and a database that was built by create_all is adopted once with alembic stamp head followed by alembic check. See create_all is not a migration tool.
2 — Autogenerate produced op.add_column("room", sa.Column("floor", sa.Integer(), nullable=False)). What is wrong with it, and what do you ship instead? Must-know
Answer
Answer: On a table with rows, adding a NOT NULL column without a default fails (SQLite: Cannot add a NOT NULL column with default value NULL, real), and on SQLite and MySQL the statements before it in the same revision stay applied. With a constant server_default the old code's inserts stay safe (the database fills the value), so a one-step ADD COLUMN ... NOT NULL DEFAULT 0 is legitimate when that constant is the right value for every existing row. Here the real floor has to be backfilled, so the chapter ships expand/contract. 0002 adds the column as nullable. The new app version then writes it. 0003 backfills in batches with an idempotent WHERE floor IS NULL. 0004 sets NOT NULL, which on PostgreSQL goes through ADD CONSTRAINT ... CHECK (floor IS NOT NULL) NOT VALID, VALIDATE CONSTRAINT and then SET NOT NULL, so the full-table scan never holds ACCESS EXCLUSIVE. See Expand/contract.
3 — What can autogenerate not detect, and how do you protect against it? Must-know
Answer
Answer: Table and column renames come out as add + drop pairs, which would delete data. Anonymous constraints have no stable name. On the pinned 1.16.5, named CHECK constraints are not detected (detection arrived in 1.19.0 and is off by default since 1.19.2). Expression indexes are skipped on SQLite with a UserWarning, and server defaults are only compared with compare_server_default=True. Type changes are detected by default since 1.12. Protection: a naming convention, a human review of every revision (renames into alter_column(new_column_name=...) or expand/contract), hand-written op.create_check_constraint and expression indexes, and alembic check plus a round-trip test in CI. See Autogenerate.
4 — A revision fails on its third statement. What state is the database in on PostgreSQL, MySQL and SQLite? Must-know
Answer
Answer: PostgreSQL has transactional DDL, so the whole revision rolls back and alembic_version still names the previous revision. Fix the bug and re-run (expected, not run). MySQL commits each DDL statement implicitly, so the first two statements stay applied while alembic_version was not bumped, and the re-run fails (vendor docs). SQLite could roll DDL back, but Python's sqlite3 sends no BEGIN before DDL, so in default mode it behaves like MySQL. The real test left the column behind and the re-run failed with duplicate column name: note. With the BEGIN recipe the same test rolled back cleanly. Recovery on non-transactional engines: compare alembic current with the real schema, finish or undo by hand, then stamp. See Transactional DDL.
5 — Where should alembic upgrade head run in a Kubernetes deployment with five replicas, and why not in the FastAPI lifespan? Must-know
Answer
Answer: Once per release, from a single runner: a pipeline step, a Kubernetes Job, or a Helm pre-upgrade hook Job. The Deployment rolls out only after the Job succeeded. In the lifespan, five replicas would start five concurrent migrations against one alembic_version, and none of the Alembic pages saved for this chapter describe a lock that would serialise them. Startup would also be slow, and the app role would need DDL rights. An init container has the same problem, because it runs once per pod. Laravel offers migrate --isolated with a cache lock for this situation, while Alembic leaves it to the deploy design. See Running migrations at deploy.
6 — How do you add an index to a 200-million-row PostgreSQL table with Alembic without blocking writes? Important
Answer
Answer: Put it in its own revision. Wrap op.create_index(..., postgresql_concurrently=True) in with op.get_context().autocommit_block():, because CREATE INDEX CONCURRENTLY cannot run inside a transaction block. The block commits the revision's transaction first, which is why transaction_per_migration=True is recommended. Set lock_timeout so the DDL does not queue behind long transactions, and give the session a generous statement_timeout. After a failure, look for an INVALID index, drop it and retry. The real offline render shows COMMIT; CREATE INDEX CONCURRENTLY ...; BEGIN;. See Building indexes without blocking writes.
7 — Why does the snippet's env.py not enable PRAGMA foreign_keys=ON, although the application does? Important
Answer
Answer: SQLite batch mode recreates a table: it creates _alembic_tmp_room, copies the rows, runs DROP TABLE room and renames. SQLite's DROP TABLE "performs an implicit DELETE", so with foreign keys ON, ON DELETE CASCADE on booking.room_id deletes every booking. The real test counted 3 bookings before and 0 after, with no error. Alembic's batch docs say the pragma "must be disabled when the workflow mode proceeds". The migration engine therefore has no FK listener, and the test runs PRAGMA foreign_key_check afterwards to prove the references are intact. See Batch mode.
8 — Two developers each added a revision on top of 0006. What happens on alembic upgrade head, and how do you fix it? Important
Answer
Answer: Alembic refuses: Multiple head revisions are present for given argument 'head'; please specify a specific target revision, '<branchname>@head' to narrow to a specific head, or 'heads' for all heads (real). Fix it with alembic merge heads -m "merge ...", which writes a revision whose down_revision is the tuple of both heads. upgrade head then works and current shows (mergepoint). Prevent it from surprising you with a CI test that asserts exactly one head. upgrade heads in production is not a fix, because it applies both branches in an unreviewed order. See Branches.
9 — Commit in the route or commit in a dependency? What exactly goes wrong with a commit after yield? Important
Answer
Answer: Either works if the commit happens before the response is sent. Committing in the route makes the status code reflect the commit and lets the route map IntegrityError to 409/422. A unit-of-work dependency declared with Depends(get_uow, scope="function") commits after the route returns and before the response, and a failed commit becomes a 500 (real test). With the default "request" scope, the code after yield runs after the response, so the client gets 201 and the booking is not saved (real test with a failing before_commit listener). On FastAPI 0.128.8 the response is serialised before the function-scoped teardown (real test with expire_on_commit=True). See Unit of work per request.
10 — How do you import 10,000 bookings so that bad rows are skipped but good rows are kept, all in one transaction? Important
Answer
Answer: Use one outer with session.begin(): and a with session.begin_nested(): per row. Flush inside the savepoint and catch IntegrityError outside it, where SQLAlchemy has already issued ROLLBACK TO SAVEPOINT. The snippet's real run (BEGIN-recipe engine) imported rows 0 and 3 and skipped row 1 (CHECK constraint failed: ck_booking_end_after_start) and row 2 (FOREIGN KEY constraint failed), with one BEGIN, 4 SAVEPOINT and 2 ROLLBACK statements. On SQLite the recipe is required: in Python's default mode the first statement is a SAVEPOINT, no BEGIN is ever sent, and the real test shows the "one transaction" keeping 2 rows after an outer failure. See Savepoints.
11 — Two requests try to book the last free night of room 12. What does with_for_update() do, and why does your SQLite test suite not prove it? Good to know
Answer
Answer: select(Room).where(Room.id == 12).with_for_update() sends SELECT ... FOR UPDATE on PostgreSQL and MySQL, so the second transaction waits until the first commits, then re-checks overlaps and gets a 409. nowait=True makes it fail at once (PostgreSQL 55P03), and skip_locked=True is for queues. SQLite has no row locks, so SQLAlchemy omits the clause when compiling for it (real), and the suite passes with or without the lock. Lock behaviour needs a PostgreSQL job in CI. An exclusion constraint on the booking range is the stronger database-side guarantee. See Row locks.
12 — How do goose and Laravel express what Alembic does with autocommit_block() and --sql? Good to know
Answer
Answer: goose runs every migration in a transaction by default and offers -- +goose NO TRANSACTION at the top of a file for statements such as CREATE INDEX CONCURRENTLY. That is the counterpart of autocommit_block(). Laravel's php artisan migrate --pretend prints "the SQL statements that will be executed by the migrations without actually running them", Alembic's --sql. Laravel's migrate --isolated adds a cache lock against concurrent runs; none of the saved Alembic pages describe an equivalent. atlas goes further than both and diffs a desired schema, like autogenerate. See For PHP/Laravel developers and The Go angle.
Glossary
| Term | Meaning |
|---|---|
| Alembic | SQLAlchemy's migration tool: revision files, a version table, autogenerate, offline SQL |
| Migration environment | The alembic init output: alembic.ini, env.py, script.py.mako, versions/ |
| alembic init | Command that creates the environment from a template (generic, async, multidb, pyproject, pyproject_async) |
| alembic.ini | ConfigParser file with script_location, file_template, prepend_sys_path, logging and a fallback sqlalchemy.url |
| sqlalchemy.url | The database URL key Alembic's generated env.py reads; better taken from DATABASE_URL |
| env.py | The script every command runs: builds the connection and calls context.configure() and context.run_migrations() |
| script.py.mako | Mako template for new revision files; add import sqlmodel for SQLModel projects |
| versions/ | Directory of revision files |
| Revision | One migration file with revision, down_revision, upgrade(), downgrade() |
| upgrade / downgrade | The functions that move the schema forward / back one revision |
| down_revision | The parent revision id (a tuple for merge revisions); defines the order |
| alembic_version | Table holding the current revision id(s) of a database |
| head / heads / base | The tip of the chain / all tips / the point before the first revision |
| alembic upgrade head | Apply every pending revision |
| downgrade -1 | Undo the most recent revision (downgrade base undoes all) |
| alembic history | List the revision chain (-r a:b, --verbose, -i) |
| alembic current | Print the revision recorded in alembic_version |
| alembic heads | Print the tips; more than one means branches |
| alembic stamp | Write a revision id without running DDL (adopt an existing schema) |
| alembic check | Autogenerate dry run; non-zero exit when models and database differ (Alembic 1.9.0+) |
| Branches | Two revisions with the same parent; produce multiple heads |
| Merge revisions | A revision with two parents created by alembic merge heads (mergepoint) |
| branch_labels / depends_on | Named long-lived branches / ordering dependencies across branches |
| target_metadata | The MetaData that autogenerate compares with the database |
| SQLModel metadata | SQLModel.metadata, shared by every table=True class that has been imported |
| Autogenerate | alembic revision --autogenerate: writes a candidate revision from the metadata/database diff |
| compare_type | configure() flag to compare column types (default True since 1.12) |
| compare_server_default | configure() flag to compare server defaults (default False) |
| Renames not detected | Autogenerate renders renamed tables/columns as add + drop pairs |
| naming_convention | Templates (ix, uq, ck, fk, pk) that name constraints and indexes |
| MetaData naming convention | The naming_convention set on MetaData (here SQLModel.metadata) before tables are defined |
| op.f() | Marks a name as final so the convention is not applied again |
| op.create_table / op.add_column / op.alter_column / op.create_index / op.drop_column | The core Alembic operations used in revisions |
| op.create_check_constraint | Adds a named CHECK; postgresql_not_valid=True skips the validation scan |
| batch_alter_table | Context manager that applies table changes via move-and-copy on SQLite, plain ALTER elsewhere |
| render_as_batch | configure() flag that makes autogenerate emit batch blocks |
| SQLite ALTER limitations | SQLite cannot change column types or add/drop constraints with ALTER; NOT NULL changes only since 3.53.0 |
| Move and copy | Batch strategy: create _alembic_tmp_<table>, copy rows, drop old, rename |
| Offline mode --sql | alembic upgrade head --sql: render SQL without connecting |
| Data migration | A revision (or job) that changes rows, not structure |
| Schema migration | A revision that changes tables, columns, constraints or indexes |
| Transactional DDL | DDL that participates in a transaction and rolls back with it |
| PostgreSQL DDL in transaction | PostgreSQL runs most DDL inside transactions (exceptions such as CREATE INDEX CONCURRENTLY) |
| MySQL implicit commit | MySQL commits before and after most DDL statements, ending any open transaction |
| Partial migration failure | A revision that failed after some statements were already committed |
| transaction_per_migration | configure() flag: one transaction per revision instead of one for the whole run |
| Expand contract | Zero-downtime pattern: add compatibly, migrate code and data, then remove or tighten |
| Nullable first | Add new columns as nullable; make them NOT NULL only after the backfill |
| Backfill in batches | Fill a new column in bounded, idempotent chunks |
| NOT VALID / VALIDATE CONSTRAINT | PostgreSQL: add a constraint without the scan, validate later under a weaker lock |
| CREATE INDEX CONCURRENTLY | PostgreSQL index build that does not block writes; cannot run in a transaction block |
| autocommit_block | op.get_context().autocommit_block(): commit, run in autocommit mode, begin again |
| lock_timeout | PostgreSQL setting: abort a statement that waits longer than this for a lock |
| statement_timeout | PostgreSQL setting: abort a statement that runs longer than this |
| Migrations at deploy | Running upgrade head once per release from a pipeline step or Job |
| Init container | Container that runs to completion before a pod's app containers; once per pod |
| Job | Kubernetes object that runs pods to successful completion; the usual migration runner |
| Never at startup with multiple replicas | Rule: replicas must not each run migrations in their lifespan |
| Migration tests | Tests that execute revision files against a real throwaway database |
| Upgrade downgrade round trip | upgrade head → downgrade base → upgrade head gives the same schema |
| Stairway test | Up/down/up for every single revision |
| Async Alembic | env.py with an async engine that calls connection.run_sync(do_run_migrations) |
| run_sync | AsyncConnection.run_sync(fn): run synchronous code on an async connection |
| Session.begin | with session.begin(): begin-once block; commits on success, rolls back on exception |
| begin_nested | session.begin_nested(): a SAVEPOINT inside the current transaction |
| Savepoint | Named point inside a transaction to which a rollback can return |
| rollback | Undo the current transaction (or savepoint); required before reusing a session after an error |
| expire_on_commit | Session option: drop loaded attribute values on commit (default True) |
| isolation_level | Transaction isolation; per connection via execution_options(isolation_level=...) |
| execution_options | Connection.execution_options(...): per-connection settings such as isolation_level |
| Serialization failure retry | Re-running the whole transaction after SQLSTATE 40001 (or 40P01 / MySQL 1213) |
| Unit of work per request | One Session and one commit point per HTTP request |
| Commit in dependency | A yield dependency that commits after the route returns; safe only with scope="function" |
| Depends(scope="function") | FastAPI option: dependency teardown runs before the response is sent |
| with_for_update | Select.with_for_update(): SELECT ... FOR UPDATE row lock |
| skip_locked | with_for_update(skip_locked=True): skip rows locked by others (queues) |
| nowait | with_for_update(nowait=True): fail instead of waiting for a lock |
| Index | SQLAlchemy Index(name, *expressions, **dialect_kw) declared in __table_args__ |
| index=True | Field(index=True): single-column index named by the convention (ix_room_name) |
| Composite index | Index over several columns; usable by queries on its left-most prefix |
| Partial index postgresql_where | Index(..., postgresql_where=text(...)) (and sqlite_where): index only matching rows |
| Expression index | Index on an expression such as lower(email) |
| UniqueConstraint | Table constraint for uniqueness across one or more columns |
| CheckConstraint | Table constraint with a SQL condition, named via the convention |
| server_default | A default stored in the DDL, applied by the database for every writer |
| AutoString | SQLModel's string column type, rendered as sqlmodel.sql.sqltypes.AutoString() in revisions |
| Outbox | Table written in the same transaction as the business change, published later |
| Laravel migrations | Laravel's timestamped PHP migration classes using the Schema builder |
| php artisan migrate | Laravel's command to run pending migrations (--pretend, --force, --isolated) |
| goose | Go migration tool (CLI and library) with SQL or Go migrations |
| golang-migrate | Go migration tool with up/down SQL files |
| atlas | Declarative schema-as-code tool that diffs a desired state |
References
- Alembic, documentation index: https://alembic.sqlalchemy.org/en/latest/
- Alembic, "Front Matter" (installation, requirements): https://alembic.sqlalchemy.org/en/latest/front.html
- Alembic, "Tutorial" (environment, alembic.ini, env.py, script.py.mako): https://alembic.sqlalchemy.org/en/latest/tutorial.html
- Alembic, "Auto Generating Migrations" (detects / cannot detect, compare_type, alembic check): https://alembic.sqlalchemy.org/en/latest/autogenerate.html
- Alembic, "Running 'Batch' Migrations for SQLite and Other Databases": https://alembic.sqlalchemy.org/en/latest/batch.html
- Alembic, "Working with Branches": https://alembic.sqlalchemy.org/en/latest/branches.html
- Alembic, "Generating SQL Scripts (a.k.a. 'Offline Mode')": https://alembic.sqlalchemy.org/en/latest/offline.html
- Alembic, "Cookbook" (data migrations, asyncio, current revision at head): https://alembic.sqlalchemy.org/en/latest/cookbook.html
- Alembic, "The Importance of Naming Constraints": https://alembic.sqlalchemy.org/en/latest/naming.html
- Alembic, "Operation Reference": https://alembic.sqlalchemy.org/en/latest/ops.html
- Alembic, "Operations" API: https://alembic.sqlalchemy.org/en/latest/api/operations.html
- Alembic, "Commands" API: https://alembic.sqlalchemy.org/en/latest/api/commands.html
- Alembic, "Runtime Objects" (MigrationContext.autocommit_block, transaction_per_migration): https://alembic.sqlalchemy.org/en/latest/api/runtime.html
- Alembic, "Autogeneration" API (compare_metadata): https://alembic.sqlalchemy.org/en/latest/api/autogenerate.html
- Alembic, "Changelog": https://alembic.sqlalchemy.org/en/latest/changelog.html
- PyPI JSON, Alembic (release dates, requires_python): https://pypi.org/pypi/alembic/json
- PyPI JSON, SQLAlchemy: https://pypi.org/pypi/sqlalchemy/json
- PyPI JSON, SQLModel: https://pypi.org/pypi/sqlmodel/json
- PyPI JSON, Mako: https://pypi.org/pypi/mako/json
- SQLAlchemy 2.0, "Describing Databases with MetaData": https://docs.sqlalchemy.org/en/20/core/metadata.html
- SQLAlchemy 2.0, "Defining Constraints and Indexes" (naming conventions, Index): https://docs.sqlalchemy.org/en/20/core/constraints.html
- SQLAlchemy 2.0, "Column INSERT/UPDATE Defaults" (server_default): https://docs.sqlalchemy.org/en/20/core/defaults.html
- SQLAlchemy 2.0, "Transactions and Connection Management" (begin, begin_nested): https://docs.sqlalchemy.org/en/20/orm/session_transaction.html
- SQLAlchemy 2.0, "Session Basics": https://docs.sqlalchemy.org/en/20/orm/session_basics.html
- SQLAlchemy 2.0, "Working with Engines and Connections" (isolation levels, AUTOCOMMIT): https://docs.sqlalchemy.org/en/20/core/connections.html
- SQLAlchemy 2.0, "SELECT and Related Constructs" (with_for_update): https://docs.sqlalchemy.org/en/20/core/selectable.html
- SQLAlchemy 2.0, "ORM-Enabled INSERT, UPDATE, and DELETE statements": https://docs.sqlalchemy.org/en/20/orm/queryguide/dml.html
- SQLAlchemy 2.0, "ORM API Features for Querying": https://docs.sqlalchemy.org/en/20/orm/queryguide/api.html
- SQLAlchemy 2.0, "PostgreSQL" dialect (CONCURRENTLY, NOT VALID, partial indexes): https://docs.sqlalchemy.org/en/20/dialects/postgresql.html
- SQLAlchemy 2.0, "SQLite" dialect (transactional DDL, savepoints, BEGIN recipe): https://docs.sqlalchemy.org/en/20/dialects/sqlite.html
- SQLAlchemy 2.0, "MySQL and MariaDB" dialect: https://docs.sqlalchemy.org/en/20/dialects/mysql.html
- SQLAlchemy 2.0, "Asynchronous I/O (asyncio)" (run_sync): https://docs.sqlalchemy.org/en/20/orm/extensions/asyncio.html
- SQLAlchemy 2.0, "Error Messages": https://docs.sqlalchemy.org/en/20/errors.html
- SQLAlchemy 2.0, "Core Exceptions": https://docs.sqlalchemy.org/en/20/core/exceptions.html
- SQLModel, "Create a Table with SQLModel - Use the Engine" (create_all, migrations note): https://sqlmodel.tiangolo.com/tutorial/create-db-and-table/
- SQLModel, "Indexes - Optimize Queries": https://sqlmodel.tiangolo.com/tutorial/indexes/
- SQLModel, "Advanced User Guide" ("How to run migrations."): https://sqlmodel.tiangolo.com/advanced/
- FastAPI, "SQL (Relational) Databases": https://fastapi.tiangolo.com/tutorial/sql-databases/
- FastAPI, "Dependencies with yield" (scope="function"): https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/
- PostgreSQL, "CREATE INDEX" (CONCURRENTLY, invalid indexes): https://www.postgresql.org/docs/current/sql-createindex.html
- PostgreSQL, "ALTER TABLE" (lock levels, NOT VALID, SET NOT NULL): https://www.postgresql.org/docs/current/sql-altertable.html
- PostgreSQL, "Modifying Tables": https://www.postgresql.org/docs/current/ddl-alter.html
- PostgreSQL, "Client Connection Defaults" (lock_timeout, statement_timeout): https://www.postgresql.org/docs/current/runtime-config-client.html
- PostgreSQL, "Partial Indexes": https://www.postgresql.org/docs/current/indexes-partial.html
- PostgreSQL, "Indexes on Expressions": https://www.postgresql.org/docs/current/indexes-expressional.html
- PostgreSQL, "Explicit Locking": https://www.postgresql.org/docs/current/explicit-locking.html
- PostgreSQL, "SELECT" (FOR UPDATE, NOWAIT, SKIP LOCKED): https://www.postgresql.org/docs/current/sql-select.html
- PostgreSQL, "Transaction Isolation" (retry on serialization failure): https://www.postgresql.org/docs/current/transaction-iso.html
- PostgreSQL, "PostgreSQL Error Codes": https://www.postgresql.org/docs/current/errcodes-appendix.html
- PostgreSQL, "BEGIN": https://www.postgresql.org/docs/current/sql-begin.html
- PostgreSQL wiki, "Transactional DDL in PostgreSQL: A Competitive Analysis": https://wiki.postgresql.org/wiki/Transactional_DDL_in_PostgreSQL:_A_Competitive_Analysis
- MySQL 8.4, "Statements That Cause an Implicit Commit": https://dev.mysql.com/doc/refman/8.4/en/implicit-commit.html
- MySQL 8.4, "Atomic Data Definition Statement Support": https://dev.mysql.com/doc/refman/8.4/en/atomic-ddl.html
- MySQL 8.4, "Online DDL Operations": https://dev.mysql.com/doc/refman/8.4/en/innodb-online-ddl-operations.html
- MySQL 8.4, "CREATE INDEX Statement" (functional key parts): https://dev.mysql.com/doc/refman/8.4/en/create-index.html
- MySQL 8.4, "Locking Reads" (NOWAIT, SKIP LOCKED): https://dev.mysql.com/doc/refman/8.4/en/innodb-locking-reads.html
- MySQL 8.4, "Transaction Isolation Levels": https://dev.mysql.com/doc/refman/8.4/en/innodb-transaction-isolation-levels.html
- MySQL 8.4, "Deadlocks in InnoDB": https://dev.mysql.com/doc/refman/8.4/en/innodb-deadlocks.html
- MySQL 8.4, "Server Error Message Reference" (1205, 1213): https://dev.mysql.com/doc/mysql-errors/8.4/en/server-error-reference.html
- SQLite, "ALTER TABLE" (ALTER COLUMN NOT NULL in 3.53.0): https://www.sqlite.org/lang_altertable.html
- SQLite, "Transaction": https://www.sqlite.org/lang_transaction.html
- SQLite, "SQLite Foreign Key Support" (DROP TABLE implicit DELETE): https://www.sqlite.org/foreignkeys.html
- Kubernetes, "Jobs": https://kubernetes.io/docs/concepts/workloads/controllers/job/
- Kubernetes, "Init Containers": https://kubernetes.io/docs/concepts/workloads/pods/init-containers/
- Helm, "Chart Hooks": https://helm.sh/docs/topics/charts_hooks/
- Laravel 13, "Database: Migrations": https://laravel.com/docs/13.x/migrations
- Laravel 13, "Database: Getting Started" (transactions, deadlock attempts): https://laravel.com/docs/13.x/database
- Laravel 13, "Database: Query Builder" (lockForUpdate): https://laravel.com/docs/13.x/queries
- goose README: https://raw.githubusercontent.com/pressly/goose/main/README.md
- atlas README: https://raw.githubusercontent.com/ariga/atlas/master/README.md
- golang-migrate README: https://raw.githubusercontent.com/golang-migrate/migrate/master/README.md
- pgx source,
tx.go(pseudo nested transactions): https://raw.githubusercontent.com/jackc/pgx/master/tx.go