Alembic, From Zero
You changed a model in your SQLAlchemy code, the table in the database still has the old shape, and now they disagree. Your app boots, then explodes the first time it touches that column. Alembic is the tool that keeps your models and your real database in step, version by version, with a paper trail you can move forward and backward through.
The thing that trips everyone up is autogenerate. It reads your models, looks at the database, and writes a migration for you. It feels like magic, and most of the time it is right. But it quietly misses things, and if you ship its output without reading it, it will eventually drop a column you meant to keep or skip a change you needed. This guide teaches you to drive it, not trust it blind.
How to read this
Read the three phases in order. Phase 1 builds the mental model: what a migration is, how Alembic pairs with SQLAlchemy, and why a version table on the database is the whole trick. Phase 2 is the daily loop you will actually run: edit a model, autogenerate, review, upgrade. Phase 3 is the reality of a team: the autogenerate trap in detail, plus branching, multiple heads, and merging them back together.
If you want the vendor-neutral picture of why migrations exist at all, the companion guide Database Migrations covers the concept across tools. This guide is the SQLAlchemy-specific one.
The phases
- The version table is the whole idea - what a migration is and how Alembic tracks where your database is.
- The daily loop: autogenerate, review, upgrade - the workflow you run every time a model changes.
- The autogenerate trap, heads, and merges - what autogenerate misses, and how branching and merging work on a team.