Automatic Alembic migration chaining based on git commit history
Actively maintained. Last release 2 months ago, commits in 15 of the last 26 weeks. A safe choice.
pip install alembic-git-revisionsalembic-git-revisions
Automatic Alembic migration chaining based on git commit history. No more Multiple head revisions are present for given argument 'head'.
The problem
You merged two branches and Alembic now refuses to run:
ERROR [alembic.util.messaging] Multiple head revisions are present for given argument 'head'; please specify a specific target revision, '<branchname>@head' to narrow to a specific head, or 'heads' for all heads
When multiple developers create Alembic migrations on separate branches, they often end up with the same down_revision — the current head at the time each branch was created. When these branches merge, Alembic fails with this MultipleHeads error because two migrations point to the same predecessor.
The usual fix is manual: rebase, update down_revision, and hope nobody else merges in the meantime.
How it works
Instead of hardcoding down_revision, this library determines the migration chain automatically from git history. It uses git log --reverse --diff-filter=A to find the order in which migration files were first committed, then chains them linearly after the last "static" (hardcoded) migration.
This means:
- New migrations never conflict with each other
- The chain is always linear, regardless of branch merge order
- Existing migrations with hardcoded
down_revisioncontinue to work
Installation
pip install alembic-git-revisions
Setup
Copy the provided template to your Alembic script.py.mako:
"""${message}
Revision ID: ${up_revision}
Create Date: ${create_date}
"""
from alembic import op
from alembic_git_revisions import get_down_revision
import sqlalchemy
${imports if imports else ""}
revision = ${repr(up_revision)}
down_revision = get_down_revision(revision)
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}
def upgrade() -> None:
${upgrades if upgrades else "pass"}
def downgrade() -> None:
${downgrades if downgrades else "pass"}
A reference template is included in the package at alembic_git_revisions/templates/script.py.mako.
That's it. New migrations generated with alembic revision --autogenerate will automatically chain themselves using git history.