Concept Explanation
Your app ships. Two weeks later the product team wants a phone_number on every user. Your local fix is easy — delete the database, change the model, start again. In production that deletes your customers.
A migration is a small, versioned, reversible script that transforms a live schema from one shape to the next without losing the rows already in it. Alembic is the migration tool built by SQLAlchemy's author, and it is the default answer for Python.
Think of it as Git for your database structure: each change is a numbered revision, revisions form a chain, and you can move forwards or backwards along it.
The Core Commands
| Command | What it does |
|---|---|
alembic init migrations | One-time setup; creates the config and script folder |
alembic revision --autogenerate -m "msg" | Compares your models to the live DB and writes a script |
alembic upgrade head | Applies every pending revision |
alembic downgrade -1 | Undoes the most recent revision |
alembic current | Prints which revision the database is on |
alembic history | Shows the whole chain |
Anatomy of a Revision File
Every generated script has exactly two functions:
revision = "a1b2c3d4e5f6"
down_revision = "9f8e7d6c5b4a" # the link that forms the chain
def upgrade():
op.add_column("users", sa.Column("phone_number", sa.String(20)))
def downgrade():
op.drop_column("users", "phone_number")
upgrade() moves forwards. downgrade() must undo it exactly. If you cannot write a truthful downgrade(), you have found a change that needs a plan rather than a command.
How Alembic Knows Where You Are
It creates one table, alembic_version, holding a single row: the current revision id. That is the entire state machine.
Code Example #1 (Basic)
Adding a column to a live table.
# 1. Change the model in models.py first
# phone_number = Column(String(20))
# 2. Let Alembic diff models against the database
alembic revision --autogenerate -m "add phone_number to users"
# 3. READ the generated file in migrations/versions/ -- always
# 4. Apply it
alembic upgrade head
The generated script:
"""add phone_number to users"""
from alembic import op
import sqlalchemy as sa
revision = "3f2a91bc45de"
down_revision = "1a0b7c88e912"
def upgrade():
op.add_column("users", sa.Column("phone_number", sa.String(20), nullable=True))
def downgrade():
op.drop_column("users", "phone_number")
Note nullable=True. Adding a NOT NULL column to a table that already has rows fails immediately — there is no value for the existing rows.
Code Example #2 (Intermediate)
A three-step migration for the change autogenerate cannot do safely: making a new column required.
"""make phone_number required"""
from alembic import op
import sqlalchemy as sa
revision = "77aa1e0cbb31"
down_revision = "3f2a91bc45de"
def upgrade():
# Step 1: backfill existing rows so none are NULL
op.execute("UPDATE users SET phone_number = 'unknown' WHERE phone_number IS NULL")
# Step 2: only now can the constraint hold
op.alter_column(
"users",
"phone_number",
existing_type=sa.String(20),
nullable=False,
)
def downgrade():
op.alter_column(
"users",
"phone_number",
existing_type=sa.String(20),
nullable=True,
)
# We deliberately do NOT undo the backfill: the original NULLs are gone
# for good, and pretending otherwise would be a lie in the script.
This is the shape of every risky migration: widen, backfill, then tighten — three steps, each safe on its own, so a deployment can pause between them.
Common Mistakes
- Trusting autogenerate blindly: it detects added and dropped columns well. It does not reliably detect renames — it emits a drop plus an add, which silently destroys the data in that column. Always read the script before applying it.
- Adding a NOT NULL column with no default: fails on any table that already has rows. Add it nullable, backfill, then tighten.
- Editing an already-applied revision: your machine is on the new code, production is on the old — the chain diverges. Write a new revision instead.
- Skipping
downgrade(): leaving it aspassmeans the one night you need to roll back, you cannot. - Data and schema in one revision without thought: an
UPDATEacross ten million rows inside a schema migration can lock the table for minutes. Batch it, or split it into its own step.
Best Practices
- Commit migrations alongside the model change: the schema and the code that assumes it must travel together in one commit.
- Write descriptive messages:
-m "add phone_number to users"beats-m "fix"when you are readingalembic historyat 2am. - Test the round trip: run
alembic upgrade headthenalembic downgrade -1thenupgrade headagain on a scratch copy before merging. - Never edit the schema by hand in production: any change made outside Alembic makes the next autogenerate produce nonsense.
- Back up before applying: a migration is a one-way door for data even when it is reversible for structure.
- Run migrations as a deploy step, not at app start-up: two web workers booting at once will both try to migrate, and one will fail.
Practice Exercises
- The First Migration: Set up Alembic on a small SQLAlchemy project, add a
created_attimestamp column to a model, autogenerate the revision, read it, and apply it. - The Safe Rename: Rename a column from
fullnametofull_namewithout losing data — hand-write a revision that adds the new column, copies the values across withop.execute, then drops the old one. - The Rollback Drill: Create two revisions, upgrade to head, then downgrade twice back to base, checking
alembic currentafter each step. Note which of yourdowngrade()functions could not truly restore the previous state, and why.