skip to content

When `alembic upgrade head` fails partway through several new revisions, what state is the database left in on PostgreSQL versus MySQL, and how do you recover?

level: seniorimportance: should knowfreq 28%

answer

  1. transactional DDL or not
  2. one transaction for the whole run
  3. transaction_per_migration
  4. version row written after each script
  5. stamp after a hand repair

basics

~20 s

On PostgreSQL, Alembic by default runs the whole upgrade in one transaction, so a failure rolls everything back. On MySQL, DDL commits as it runs: earlier revisions stay applied and recorded, and the failing one can leave half its changes unrecorded.

solid answer

~50 s

Alembic's dialect implementation declares whether DDL is transactional, and logs it: PostgreSQL gets "Will assume transactional DDL.", MySQL and SQLite "Will assume non-transactional DDL.". On PostgreSQL, with `transaction_per_migration` at its default `False`, the `context.begin_transaction()` block in `env.py` wraps the whole run, so a failure in the third of five revisions rolls back all three, version updates included; fix the script and rerun. With `transaction_per_migration=True`, each revision commits on its own and the run stops after the last good one. On MySQL each DDL statement commits implicitly, and Alembic updates `alembic_version` only after a script's `upgrade()` returns, so the failing revision can leave a column added but unrecorded; rerunning then fails with "duplicate column". Recover by inspecting the schema, then either undo the partial change and rerun, or finish it by hand and `alembic stamp` that revision.

code

python · 17 lines
python
from alembic import op
import sqlalchemy as sa

revision = "6f7a8b9c0d1e"
down_revision = "5e6f7a8b9c0d"
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.add_column("invoices", sa.Column("currency", sa.String(3), nullable=True))
    # typo: the table is "currencies"
    op.create_index("ix_currency_code", "currency", ["code"])


def downgrade() -> None:
    op.drop_column("invoices", "currency")

go deeper

for a junior

Recall that PostgreSQL can roll back DDL while MySQL commits it immediately, and that alembic current shows the recorded revision.

for a middle

Explain the transactional_ddl and transaction_per_migration settings and when alembic_version is updated relative to each upgrade().

for a senior

Show how you would reconcile a half-applied MySQL revision, choosing between undo-and-rerun and finish-and-stamp, and why downgrade -1 is wrong here.

for a principal

Weigh one long transaction against per-revision commits for a team's releases: lock time, partial states the application must tolerate, and revision size rules.

## Where Alembic draws transaction boundaries Two settings decide what a failure leaves behind: - **`transactional_ddl`**: declared by Alembic's implementation for each dialect, and overridable in `context.configure()`. It is true for PostgreSQL and false for MySQL and SQLite. Alembic logs the choice at the start of every run. - **`transaction_per_migration`**: a `context.configure()` option in `env.py`, default `False`. In every case Alembic updates `alembic_version` **after** a script's `upgrade()` returns, inside the same transaction scope as that script, never before. | Database | Default boundary | Revision 3 of 5 fails | |---|---|---| | PostgreSQL | one transaction for the whole run | all three roll back; version unchanged | | PostgreSQL, `transaction_per_migration=True` | one per revision | 1 and 2 committed and recorded; 3 rolled back | | MySQL, SQLite | DDL commits as it runs | 1 and 2 recorded; 3 may be half applied and unrecorded | ## PostgreSQL: all or nothing by default The generated `env.py` wraps `context.run_migrations()` in `with context.begin_transaction():`. With transactional DDL and `transaction_per_migration=False`, that is one real database transaction around every revision in the run. A failure anywhere raises out of the block, the transaction rolls back, and the database is exactly where it was: same schema, same `alembic_version` row. Recovery is to fix the script and run `alembic upgrade head` again. Transactional DDL makes PostgreSQL forgiving, but not free. The price is that the whole release holds its locks until the last revision finishes: an `ALTER TABLE` early in the run keeps its lock on that table while every later revision, backfills included, executes. Setting `transaction_per_migration=True` commits each revision separately, which shortens lock time and makes progress durable, but a failure then leaves the database partway along the chain, at a revision you must be ready to serve. The setting lives in the online branch of `env.py`: ```python with connectable.connect() as connection: context.configure( connection=connection, target_metadata=target_metadata, transaction_per_migration=True, # default False ) with context.begin_transaction(): context.run_migrations() ``` ## MySQL and SQLite: statement by statement On MySQL, each DDL statement commits implicitly, whatever transaction is open. Alembic still brackets each revision, but it cannot undo DDL that has already committed. If revision 3 adds a column and then fails on its next statement: - revisions 1 and 2 are applied and recorded; - the new column exists; - `alembic_version` still names revision 2, because the version update comes after `upgrade()`. Rerunning `alembic upgrade head` replays revision 3 from the top and fails on its first statement, as the example shows with "duplicate column name: currency". ## Recovering a half-applied revision 1. Read `alembic current` to see the recorded revision, then inspect the real schema to see what the failing script already did. 2. Fix the script if the failure was a bug in it; if other databases already ran it successfully, ship the correction as a new revision instead. 3. Either undo the partial changes by hand and rerun `alembic upgrade head`, or finish the remaining statements by hand and record them with `alembic stamp <failed revision>`. 4. Do not reach for `alembic downgrade -1`: it would run the downgrade of the last recorded revision, revision 2, not clean up revision 3. 5. Run `alembic current` again and confirm the recorded revision matches what the schema now holds before the next release goes out. ## Designing revisions that fail cleanly - On MySQL, keep each revision small, ideally one DDL change, so a failure leaves at most one statement to reconcile. - Put data steps that may fail, such as a backfill that hits bad rows, in their own revision rather than after DDL in the same one. - Write `downgrade()` so that it works from the fully applied state only; it is no help with a half-applied revision, whose state no script describes. - On PostgreSQL, know that `op.get_context().autocommit_block()`, needed for statements PostgreSQL refuses inside a transaction block such as `CREATE INDEX CONCURRENTLY`, commits the transaction before it unconditionally. Alembic's documentation recommends `transaction_per_migration=True` for environments that use it. - Expect SQLite, often used in development, to behave like MySQL here rather than like PostgreSQL, so a clean local run proves little about rollback.

  • Why does `autocommit_block()` weaken PostgreSQL's all-or-nothing upgrade?
    To run a statement outside any transaction, `op.get_context().autocommit_block()` first commits the migration transaction that precedes it, unconditionally. Every revision earlier in the run is then committed before the block, so a later failure no longer rolls them back. Alembic's documentation recommends `transaction_per_migration=True` with such revisions, so each commit point is a revision boundary.
  • How can you tell from Alembic's own output whether a run was all or nothing?
    One of the first log lines of every run says it: "Will assume transactional DDL." or "Will assume non-transactional DDL.". Combine it with `env.py`: transactional DDL with `transaction_per_migration` left at `False` means one transaction for the run; anything else means each revision, or each statement on MySQL, commits as it goes.

  • Alembic wraps every dialect's upgrade in one transaction, MySQL included.
  • alembic_version is updated before each upgrade() function runs.
  • transaction_per_migration defaults to True in env.py.
  • After a failure, alembic downgrade -1 cleans up the half-applied revision.
  • On PostgreSQL the revisions before the failure stay committed by default.