Using Alembic: apply SQLAlchemy changes as migrations
Alembic records schema changes for a SQLAlchemy project as revision scripts and moves a database through them by following their links. The `--autogenerate` option compares SQLAlchemy model metadata with the current database and creates a candidate script; it does not guarantee a finished migration. Review and edit every candidate. A typical workflow is to change a model, generate and inspect a revision, run `upgrade head`, and check the result with `current`.
Using Alembic: apply SQLAlchemy changes as migrations
Alembic records schema changes for a SQLAlchemy project as revision scripts and moves a database through them by following their links. The --autogenerate option compares SQLAlchemy model metadata with the current database and creates a candidate script; it does not guarantee a finished migration. Review and edit every candidate. A typical workflow is to change a model, generate and inspect a revision, run upgrade head, and check the result with current.
This guide covers Alembic CLI in a Python project using SQLAlchemy. Commands and settings can vary with installed versions and the project’s env.py. The Python examples are illustrative and were not run.
How does Alembic track order and state?
An environment created with alembic init contains configuration, env.py, and a versions/ directory for revision scripts. The env.py script configures the database connection and migration run, and can provide SQLAlchemy model MetaData to Alembic. Keep this environment with the application source code. Alembic tutorial
Each revision script has its own revision identifier and a down_revision pointing to its parent. Alembic builds a graph from those links; it does not order scripts by filename or creation time. The database’s current revision is stored in alembic_version. Use alembic current to see the database’s position and alembic history to inspect the scripts. head means the latest end of the graph. There is usually one head, but independent work on multiple branches can create more than one. Revision ordering and execution Working with branches
Generate a candidate from a model change
Suppose the Customer model needs an optional language-code column. A small part of a SQLAlchemy 2.x model could look like this:
from sqlalchemy import String
from sqlalchemy.orm import Mapped, mapped_column
class Customer(Base):
# existing columns omitted
preferred_language: Mapped[str | None] = mapped_column(
String(20), nullable=True
)For autogeneration, env.py must load the model’s Base.metadata as target_metadata. If the models are not imported or the database URL points at the wrong database, the comparison can miss objects or inspect the wrong target. Check both configuration and connection first. Autogenerating migrations
After editing the model, create a candidate revision:
alembic revision --autogenerate -m "add customer preferred language"
alembic current
alembic history --verboseOpen the generated Python script. In this example, upgrade() might contain op.add_column("customer", sa.Column("preferred_language", sa.String(length=20), nullable=True)). Its downgrade() might drop that column, which would also remove values stored in it. Check data preservation, constraints, indexes, locking, and database-specific SQL. Do not approve generated output without comparing it to the intended change.
Autogenerate can detect many table/column additions and removals, nullability changes, and some indexes or named constraints. It does not reliably recognize a table or column rename: those often appear as a drop plus an add and must be edited into a rename operation. Some unnamed constraints and database-specific types/features can also be missed. If a table is absent from target_metadata, Alembic may propose dropping it from the database. Review each operation against the intended target schema. Autogenerate detection and limits Filtering generated DROP TABLE operations
When the candidate is reviewed and the target environment is confirmed, apply it and verify the recorded position:
alembic upgrade head
alembic currentupgrade head runs the necessary upgrade() functions from the current revision to the head. Confirm that current reports the expected revision. For production, review the revision through code review and deployment controls, verify the connection string and privileges, and supply secrets through an approved environment or secret store rather than committing them in plain text. Transactional DDL and partial-failure behavior vary by database, so check the target database’s behavior.
What if revisions branch?
If two development branches create revisions from the same parent, the graph forks and can have multiple heads. In that case, alembic upgrade head may be ambiguous. First use alembic heads and alembic history --verbose to inspect the endpoints and their ancestry.
┌─ B (feature X)
A (shared) ──┤
└─ C (feature Y)
alembic merge -m "merge feature revisions" heads
┌─ B ─┐
A (shared) ──┤ ├─ M (merge revision)
└─ C ─┘A merge revision usually points to both parents through down_revision. The command creates a linking script; it does not resolve logical dependencies between the changes. Check that both branches can be applied together, then review the merge script and graph before upgrading. Alembic branch merging
Bring an existing database under Alembic
Running the full historical migration chain against a database that already has those objects can try to create them again. alembic stamp <revision> records a revision as the database’s current point without running that revision’s upgrade() function. Compare the actual schema with the state represented by that revision first. Only if they match should you stamp the baseline and manage later changes as new revisions. stamp does not alter or validate the schema. Alembic cookbook: stamping a database
The practical rule
Alembic autogenerate is a drafting aid; the revision graph defines order. Configure the correct target_metadata and connection, review and edit every candidate, then use upgrade head. Confirm position with current and inspect history with history. If multiple heads appear, resolve their ancestry and dependencies before merging. For an existing database, use stamp only after verifying that its actual schema matches the revision.