skip to content

In Alembic, when should you run `alembic stamp head` rather than `alembic upgrade head`, and what does stamp change in the database?

level: middleimportance: should knowfreq 35%

answer

  1. schema exists, bookkeeping does not
  2. writes the version row only
  3. no upgrade() function runs
  4. create_all, then stamp

basics

~20 s

alembic stamp writes a revision id into alembic_version without running any upgrade() or downgrade(). Use it when the schema already matches that revision, such as a database built with MetaData.create_all() or one just adopting Alembic.

solid answer

~40 s

`alembic stamp <revision>` changes only Alembic's bookkeeping: it creates `alembic_version` if needed and sets its row to the given revision, logging `Running stamp_revision -> <id>`, without executing a single script. It fits whenever the schema already exists at that revision. A database built with `MetaData.create_all()` is the classic case: `alembic upgrade head` there starts at base and fails on the first `CREATE TABLE` (on SQLite, "table invoices already exists"), while `stamp head` records that the database is current. It also fits adopting Alembic on an existing database, and recording a hand repair. The cost is that nothing is checked: stamping a database whose schema does not match makes later revisions fail or quietly skip changes, and any data a skipped `upgrade()` would have inserted, such as `op.bulk_insert()` seed rows, never arrives.

code

python · 11 lines
python
import sqlalchemy as sa
from alembic import command
from alembic.config import Config

from models import metadata  # the application's MetaData

engine = sa.create_engine("sqlite:///billing.db")
metadata.create_all(engine)  # every table, at today's shape

# record that this database is at the newest revision; no upgrade() runs
command.stamp(Config("alembic.ini"), "head")

go deeper

for a junior

Recall that stamp records a revision without running it, and that create_all() followed by stamp head is the usual fresh-database recipe.

for a middle

Explain why upgrade head fails on a create_all() database, what stamp writes, and how a baseline revision lets existing databases adopt Alembic.

for a senior

Show you know what stamp skips, data steps included, and how you would verify a stamped database really matches before trusting later upgrades.

for a principal

Decide when a team builds environments from create_all() plus stamp versus replaying the chain, and who owns reference data in each case.

## What stamp does and does not do Alembic tracks a database's position in the `alembic_version` table, one `version_num` row per head. `alembic upgrade` moves that position by **running scripts**; `alembic stamp` moves it by **writing the row directly**. Stamp: - creates `alembic_version` if the database has none; - sets the stored revision to the target, for example `head` or an explicit identifier; - runs no `upgrade()` and no `downgrade()`, so no DDL and no data statements are emitted. | | `alembic upgrade head` | `alembic stamp head` | |---|---|---| | Runs revision scripts | yes, every missing one | no | | Changes the schema | yes | no | | Writes `alembic_version` | after each script | once, to the target | | Checks the schema matches | indirectly, by failing | not at all | ## The create_all-then-stamp pattern A fresh database for local development or a throwaway environment can be built in one shot from the models with `MetaData.create_all()`, instead of replaying hundreds of revisions. That database has every table but no `alembic_version`, so Alembic believes it is at base. Running `alembic upgrade head` against it re-runs the first script and fails on its `CREATE TABLE`; SQLite reports "table invoices already exists", PostgreSQL that the relation already exists. The fix is to record the truth: ```python metadata.create_all(engine) command.stamp(Config("alembic.ini"), "head") ``` From then on, new revisions apply normally with `alembic upgrade head`. Alembic's own cookbook describes exactly this recipe. ## Adopting Alembic on an existing database 1. Write a baseline revision whose `upgrade()` creates the schema as it exists today, with `down_revision = None`. 2. On every database that already has that schema, run `alembic stamp <baseline id>` so the baseline is recorded without running. 3. On new, empty databases, run `alembic upgrade head` so the baseline actually creates the tables. 4. Add later changes as ordinary revisions on top of the baseline. ## Repairing the bookkeeping - After finishing a half-applied revision by hand, `alembic stamp <that revision>` records it so the next upgrade does not repeat it. - `alembic stamp` also moves backwards, for example to an older identifier, when a change was reverted by hand. - If `alembic_version` holds an identifier no script declares, for example after old scripts were pruned, the commands that read the version table, `stamp` included, fail with `Can't locate revision identified by '...'`. `alembic stamp --purge head` deletes all rows in the version table first, then stamps. - Stamping works in offline mode too: `alembic stamp <revision> --sql` emits the `CREATE TABLE alembic_version` and `INSERT` a DBA can run, without the schema statements. ## Before you stamp Because stamp performs no check, the checking is yours. A short routine keeps it honest: 1. Confirm the schema matches the revision you are about to name, by comparing it with the models or with a database built by `alembic upgrade head`. 2. List the revisions you are skipping and look inside their `upgrade()` functions for data steps, not only DDL. 3. Stamp the exact revision that matches, not `head` by habit; a database that is two revisions behind should be stamped two revisions back and then upgraded. 4. Record what was stamped and why, since `alembic_version` keeps no history of how it got its value. ## What stamping cannot catch - **Schema drift.** Stamp trusts you. If the database differs from the revision you name, later scripts fail on objects that are missing, or never add objects Alembic thinks already exist. - **Data steps.** A revision's `upgrade()` may insert reference rows with `op.bulk_insert()` or backfill with `op.execute()`. A database built by `create_all()` and stamped never ran them, so those rows must come from the build script itself. - **A cheap cross-check.** With `target_metadata` set in `env.py`, `alembic check` on a database stamped at head compares the models with the live schema and prints "No new upgrade operations detected." when they agree. It refuses with "Target database is not up to date." when the stamped revision is behind head.

  • Why can a database built with `create_all()` and stamped head still be missing rows?
    Stamping skips every `upgrade()`, so data a revision inserts, such as reference rows from `op.bulk_insert()` or a backfill through `op.execute()`, never runs. `create_all()` only creates tables. The build script must seed those rows itself, or the environment should be built by `alembic upgrade head` from base instead.
  • When do you need `alembic stamp --purge`?
    When `alembic_version` holds an identifier that no script declares, for example after old revision files were deleted. A plain `alembic stamp` then fails with `Can't locate revision identified by '...'`, like `current` and `upgrade` do. `--purge` deletes all rows in the version table before stamping the target.

  • alembic stamp head applies the pending migrations without logging them.
  • Stamping is harmless even when the schema differs from the revision named.
  • upgrade head on a create_all() database skips tables that already exist.
  • Seed rows inserted by a revision arrive when the database is stamped.
  • stamp needs the alembic_version table to exist beforehand.