alembic
Database migration tool for SQLAlchemy — tracks schema changes as versioned scripts.
You change a SQLAlchemy model — add a column, rename a table. Now production's DB schema is out of sync with your code. You can't just drop and recreate the DB. You need to apply the change safely, track what version each environment is at, and roll back if something goes wrong.
Alembic is Git for your database schema. Each migration is a versioned Python file with `upgrade()` and `downgrade()` functions. Alembic tracks which version your DB is at in an `alembic_version` table. `alembic upgrade head` runs all pending migrations in order.
Set up Alembic in a new project
pip install alembic
alembic init migrations
# In alembic.ini:
sqlalchemy.url = postgresql://user:pass@localhost/mydb
# In migrations/env.py:
from myapp.models import Base
target_metadata = Base.metadataUse it when
Any production SQLAlchemy app. Column additions/renames, index creation, constraint changes, data backfills as part of schema migrations.
Skip it when
Non-SQLAlchemy databases (use Flyway, Liquibase, or Django migrations). Throwaway dev DBs where you can afford to drop and recreate.
Ready to explore the full API?
See every class, function, and relationship in an interactive graph.