← Back to FastAPI, page 4

fastapi-0071 · Medium mid

How do Alembic migrations work with SQLAlchemy in a FastAPI project: autogenerate, upgrade, downgrade, and what must you review?

Alembic keeps a chain of revision scripts, each with upgrade() and downgrade(), and records the current revision in the alembic_version table. alembic revision --autogenerate compares your SQLAlchemy metadata with the live database and drafts operations; you must review them because autogenerate misses renames, some constraints and data changes. alembic upgrade head applies pending revisions, and downgrade moves back. SQLite needs batch mode for many ALTERs.

Full answer

Workflow:

  1. alembic init migrations creates alembic.ini and migrations/env.py. In env.py set target_metadata = Base.metadata and read the database URL from your settings, not from the ini file.
  2. Change models, then alembic revision --autogenerate -m "add email". Alembic connects, reflects the database, diffs it against target_metadata, and writes versions/<rev>_add_email.py with op.add_column(...) etc.
  3. Review the file: autogenerate cannot detect table or column renames (it sees drop and add, which loses data), often misses changes to server defaults, check constraints and enum types, and never moves data.
  4. alembic upgrade head applies revisions; alembic downgrade -1 reverts one; alembic current, alembic history and alembic upgrade head --sql (offline SQL for DBAs) help operations.

Rules of thumb:

  • The database must be at the latest revision before generating a new one, or Alembic reports "Target database is not up to date".
  • Revisions form a linear chain through down_revision; two branches create multiple heads and alembic merge is needed.
  • Import all models in env.py (or in the package it imports) so that Base.metadata is complete.
  • Write real downgrade() functions or consciously raise in them; test upgrade and downgrade in CI against a clean database.
  • SQLite supports few ALTER statements. Set render_as_batch=True in context.configure so Alembic emits batch_alter_table, which recreates the table.
  • Zero-downtime changes follow expand and contract: add nullable column, deploy code that writes it, backfill in batches, then add constraints (on PostgreSQL use NOT VALID then VALIDATE, and create indexes CONCURRENTLY outside a transaction).
  • Run migrations as a deploy step, not at app start-up with several replicas racing.
  • Naming conventions for constraints (MetaData(naming_convention=...)) make later drops and renames predictable.
python
import contextlib
import io
import os
import sqlite3
import sys
import tempfile
from pathlib import Path

from alembic import command
from alembic.config import Config

work = Path(tempfile.mkdtemp())
sys.path.insert(0, str(work))
db_path = work / "app.db"

(work / "models.py").write_text("""import os
from sqlalchemy import Column, Integer, MetaData, String, Table


def build_metadata():
    md = MetaData()
    columns = [Column("id", Integer, primary_key=True), Column("name", String(40), nullable=False)]
    if os.environ.get("SCHEMA_STAGE") == "2":
        columns.append(Column("email", String(80)))
    Table("student", md, *columns)
    return md
""")

cfg = Config(str(work / "alembic.ini"))
cfg.set_main_option("script_location", str(work / "migrations"))
cfg.set_main_option("sqlalchemy.url", f"sqlite:///{db_path}")
quiet = contextlib.redirect_stdout(io.StringIO())          # Alembic prints temporary paths; keep the output stable
with quiet:
    command.init(cfg, str(work / "migrations"))

(work / "migrations" / "env.py").write_text("""import models
from alembic import context
from sqlalchemy import create_engine

config = context.config
engine = create_engine(config.get_main_option("sqlalchemy.url"))
with engine.connect() as connection:
    context.configure(connection=connection, target_metadata=models.build_metadata(), render_as_batch=True)
    with context.begin_transaction():
        context.run_migrations()
""")


def columns():
    with sqlite3.connect(db_path) as conn:
        return [row[1] for row in conn.execute("PRAGMA table_info(student)")]


with quiet:
    command.revision(cfg, message="create student", autogenerate=True, rev_id="0001")
    command.upgrade(cfg, "head")
print("after 0001:", columns())

os.environ["SCHEMA_STAGE"] = "2"                           # the model gained a column
with quiet:
    command.revision(cfg, message="add email", autogenerate=True, rev_id="0002")
print(sorted(p.name for p in (work / "migrations" / "versions").glob("0*.py")))
generated = (work / "migrations" / "versions" / "0002_add_email.py").read_text()
print([line.strip() for line in generated.splitlines() if "add_column" in line or "batch_alter_table" in line or "drop_column" in line])

with quiet:
    command.upgrade(cfg, "head")
print("after 0002:", columns())
with quiet:
    command.downgrade(cfg, "-1")
print("after downgrade:", columns())

Standalone script. Run it with `python file.py`; it uses Alembic's command API with a temporary SQLite database. Requires `pip install alembic sqlalchemy`. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0, alembic 1.20.1): after 0001: ['id', 'name'] ['0001_create_student.py', '0002_add_email.py'] ["with op.batch_alter_table('student', schema=None) as batch_op:", "batch_op.add_column(sa.Column('email', sa.String(length=80), nullable=True))", "with op.batch_alter_table('student', schema=None) as batch_op:", "batch_op.drop_column('email')"] after 0002: ['id', 'name', 'email'] after downgrade: ['id', 'name']

Key points

  • Revision chain with upgrade and downgrade; alembic_version tracks state
  • Autogenerate drafts; review for renames, defaults and data
  • Database must be current before generating the next revision
  • SQLite needs batch mode; set render_as_batch
  • Run migrations as a deploy step; test both directions

Common mistakes

  • Trusting autogenerate without reading the generated file
  • Renaming a column in the model and shipping the drop and add that autogenerate produces
  • Generating a revision while the database is behind the latest revision
  • Running migrations from every app replica at start-up
  • Skipping batch mode on SQLite and getting unsupported ALTER errors

Follow-ups

  • How do you handle two developers creating revisions from the same parent?
  • How do you run a data migration safely?
  • How do you create an index concurrently on PostgreSQL?

Tips

  • Describe the workflow in four steps
  • Name autogenerate blind spots
  • Mention expand and contract