The Alembic Loop: Autogenerate, Review, Apply
Wire Alembic into the reading-list project, generate a migration from a model change, review what autogenerate really wrote, apply it, roll it back, and gate the whole loop with alembic check.
Contentsand lesson path
On this page
- The task
- Step 1: wire Alembic to the models
- Step 2: change the model, generate, and read the draft
- Step 3: apply, prove, and roll the loop
- Mistakes this loop exists to catch
- Check your understanding
- Apply it
- Review prompt
Lessons of Database Schema Migrations
- Why Schemas Need Version Control Concept · 15 min
- The Alembic Loop: Autogenerate, Review, Apply Worked example · 25 min
- Moving Data, Not Just Columns Worked example · 20 min
- Zero-Downtime Changes with Expand and Contract Concept · 25 min
- Lab: Ship a Column Rename Through CI Without Downtime Lab · 30 min
- Check: Is This Migration Safe to Ship? Knowledge check · 8 questions
What you will learn
- Generate, review and correct Alembic migrations from model changes, and apply or roll them back across environments.
Prerequisites: Data Access with SQLAlchemy
01. The task
The reading list needs a read_status on every book so the UI can show what is unread, in progress or finished. Today the models (printed in step 1) give books an id, author_id, title and created_at; the change must reach the development database, staging and production as the same reviewed script — never as a hand-run ALTER TABLE.
The loop you will practise in this lesson is the one you will run for the rest of your career:
- change the models;
- run
alembic revision --autogenerate; - read the generated file and correct it;
alembic upgrade head, thenalembic checkto prove models and migrations agree.
Step 3 is the step people skip, and the one that saves them. Autogenerate diffs what your models say against what the connected database actually contains, and writes the difference as a draft. It is a strong drafting tool and a poor decision-maker: it cannot know what you meant, only what changed.
The lab database is the throwaway PostgreSQL 17 container from the first SQL lesson, here on port 55434. Versions used in this run: Python 3.12.13, SQLAlchemy 2.1.9, Alembic 1.20.1, psycopg 3.3.9, PostgreSQL 17.12.
02. Step 1: wire Alembic to the models
uv venv --python 3.12 .venv && source .venv/bin/activate
uv pip install sqlalchemy==2.1.9 alembic==1.20.1 "psycopg[binary]==3.3.9"
alembic init alembicalembic init creates an alembic.ini and an alembic/ folder with an env.py. Two edits connect it to your project. In alembic.ini, point at the database; in env.py, give Alembic your metadata so autogenerate has something to compare:
sqlalchemy.url = postgresql+psycopg://lab:lab@localhost:55434/readinglistfrom models import Base # noqa: E402
target_metadata = Base.metadataenv.py imports Base from models.py in the project folder. This lesson uses a smaller pair than the models lesson: the release 1 models of this skill's lab plus a created_at column, so the lab's seed.py fits them:
from datetime import datetime
from sqlalchemy import ForeignKey, String, func
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
class Base(DeclarativeBase):
pass
class Author(Base):
__tablename__ = "authors"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(100))
class Book(Base):
__tablename__ = "books"
id: Mapped[int] = mapped_column(primary_key=True)
author_id: Mapped[int] = mapped_column(ForeignKey("authors.id"))
title: Mapped[str] = mapped_column(String(200))
created_at: Mapped[datetime] = mapped_column(server_default=func.now())With that in place, generate the baseline: the migration that creates the schema you already have. Review it, apply it, and the ledger starts recording:
$ alembic revision --autogenerate -m 'reading list baseline'
Detected added table 'authors'
Detected added table 'books'
$ alembic upgrade head
Running upgrade -> 29f5ac319ce0, reading list baselineSeed some production-shaped data — 3 authors and 60 books — so the table has rows. Use the seed.py printed in this skill's lab, which writes five copies of twelve titles (Refactoring (copy 1) and so on), with its from release import URL line replaced by URL = "postgresql://lab:lab@localhost:55434/readinglist". Existing rows are what make the next steps interesting: an empty table forgives every mistake a populated one punishes.
03. Step 2: change the model, generate, and read the draft
class Book(Base):
__tablename__ = "books"
id: Mapped[int] = mapped_column(primary_key=True)
author_id: Mapped[int] = mapped_column(ForeignKey("authors.id"))
title: Mapped[str] = mapped_column(String(200))
read_status: Mapped[str] = mapped_column(String(20), server_default="unread")
created_at: Mapped[datetime] = mapped_column(server_default=func.now())The column is Mapped[str], so it is NOT NULL, and it carries a server_default: the database itself fills "unread" when a row is inserted without a value. That default matters more than it looks. Add a NOT NULL column with no default to a table that already has rows and PostgreSQL refuses, because the existing rows would have no value:
readinglist=# ALTER TABLE books ADD COLUMN isbn text NOT NULL;
ERROR: column "isbn" of relation "books" contains null valuesWith the model fixed, autogenerate writes the draft — and you read it before applying. This is the file Alembic produced (reindented here to fit the page):
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('books', sa.Column('read_status',
sa.String(length=20),
server_default='unread', nullable=False))
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('books', 'read_status')
# ### end Alembic commands ###Read it as four checks. Does it touch only what my change needs? Here, one table, one column — yes. Is the type and nullability what the model says? String(20), nullable=False — yes. Does existing data survive? Yes, because server_default='unread' gives the 60 rows a value the moment the column appears. And is the downgrade honest? Dropping the column we added restores the previous schema, losing only data written into the new column since — acceptable for this change, and worth writing down in review.
The comment banner Alembic prints — please adjust — is not decoration. Autogenerate knows the shape of the difference, not its meaning. It cannot detect a rename: if you rename title to full_title in a model, autogenerate sees a removed column and an added one and drafts a drop that destroys the data; you must rewrite that as a rename or an expand-and-contract (the final lessons of this skill). It does not compare server defaults unless you switch on compare_server_default, and it ignores CHECK constraints by default: the opt-in plugin added in Alembic 1.19 notices only named CHECK constraints being added or dropped, not a changed condition. Type changes it does detect by default (compare_type=True since Alembic 1.12), but it only drafts a plain alter_column with the new type: you still decide whether the change needs a USING clause or an expand-and-contract. The draft is the beginning of the migration, not the end.
04. Step 3: apply, prove, and roll the loop
$ alembic upgrade head
Running upgrade 29f5ac319ce0 -> 67ead21a23e9, add read_status with default
readinglist=# select read_status, count(*) from books group by 1;
read_status | count
-------------+-------
unread | 60
(1 row)The 60 existing rows all read unread — the server default applied to them at ADD COLUMN time, which is exactly what the review step predicted. In development it is cheap to prove the reverse path too:
$ alembic downgrade -1
Running downgrade 67ead21a23e9 -> 29f5ac319ce0, add read_status with default
$ alembic upgrade head
Running upgrade 29f5ac319ce0 -> 67ead21a23e9, add read_status with defaultdowngrade -1 runs only the current revision's downgrade() and steps the version table back one; upgrading again replays it. That round trip is a development convenience — production recovery stays forward-only, as the first lesson established.
The loop closes with the drift gate. alembic check runs the same comparison as autogenerate but stops before writing a file: it fails when the models and a database at head disagree, which is precisely what "someone changed a model and forgot the migration" looks like.
$ alembic check
No new upgrade operations detected.
# (a rating column is added to the model, no migration written)
$ alembic check
Detected added column 'books.rating'
New upgrade operations detected: [('add_column', None,
'books', Column('rating', Integer(), table=<books>))]
FAILED: New upgrade operations detected: [('add_column', None,
'books', Column('rating', Integer(), table=<books>))]
$ echo $?
255Exit code 255 is the point: a non-zero exit turns the command into a CI job, the subject of the lab that closes this skill.
05. Mistakes this loop exists to catch
06. Check your understanding
07. Apply it
Run the loop once end to end on your own copy of the reading list:
- Add a
rating: Mapped[int | None]column to the model, with no default. Autogenerate, review the draft, and apply it. Then write the migration you would have preferred: nullable first, backfill later, NOT NULL last — the expand-and-contract shape you will meet later in this skill. - Break the gate on purpose: add a column to the model, do not migrate, and confirm
alembic checkexits non-zero. Wire it into a script so the failure is one command anyone can run. - With a teammate, create two revisions from the same parent and observe the multiple-heads error; resolve it with
alembic merge heads.
08. Review prompt
Without looking back: what exactly does autogenerate compare, and what four things do you check when reading a draft? Why does a NOT NULL column without a default fail on a table with rows, and what are the two safe ways to add one? Finally, what does alembic check prove, and why does a non-zero exit code matter more than its message?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.