Database Migrations with Alembic — ELI5
Imagine you live in a house, and every time you want to change something — add a closet, knock down a wall, install a new sink — you write it down in a notebook. Each page describes exactly what you changed and how to undo it if you don’t like the result.
That notebook is what Alembic does for your database.
Your code and your database need to agree on what the data looks like. If your code expects a column called “email” in the users table, the database better have it. When you change your code — say, you want to add a “phone_number” column — the database needs to change too.
You could log into the database and type the change by hand. But what about your teammate’s database? And the test server? And the production server? Are you going to remember to do it everywhere, in exactly the right order? Probably not.
Alembic creates migration files — step-by-step instructions for changing the database. Each file has an “upgrade” (make the change) and a “downgrade” (undo the change). They’re numbered in order, so anyone can run them to bring their database up to date.
The best part: Alembic can look at your Python code (your SQLAlchemy models) and figure out what changed automatically. Added a new column to your model? Alembic says, “I see you added phone_number — want me to write the migration for that?” It’s not perfect, but it catches most changes.
Every team member, every server, every environment runs the same migration files in the same order. No more “works on my machine” surprises because someone forgot to add a column.
One thing to remember: Alembic is the version control system for your database structure — like Git, but for tables and columns instead of code files.
See Also
- Python Aioredis Understand Aioredis through a practical analogy so your Python decisions become faster and clearer.
- Python Alembic Understand Alembic through a practical analogy so your Python decisions become faster and clearer.
- Python Asyncpg Database asyncpg is the fastest way for Python to talk to PostgreSQL without making your program sit around waiting.
- Python Asyncpg Understand Asyncpg through a practical analogy so your Python decisions become faster and clearer.
- Python Cassandra Python Understand Cassandra Python through a practical analogy so your Python decisions become faster and clearer.