8. Alembic migrations¶
Use to bootstrap Alembic, generate and apply revisions, block drift in CI and migrate constraints from the old convention.
Part of the Database recipe.
AlembicHelper wraps Alembic with a curated config (UTC timezone,
date-prefixed files, target_metadata already wired, batch mode). Full
flow: bootstrap → revision → apply → CI gate.
Bootstrap, once per project¶
# scripts/alembic_init.py
from tempest_fastapi_sdk import AlembicHelper
from src.core.settings import settings
helper = AlembicHelper(config_path="alembic.ini", db_url=settings.DATABASE_URL)
helper.init(
directory="alembic",
metadata_module="src.db.models", # exposes BaseModel
metadata_attr="BaseModel",
db_url=settings.DATABASE_URL,
)
Creates:
alembic.ini # SDK-curated config (UTC, date prefix, post-write hooks, prepend_sys_path)
alembic/
├── env.py # run_alembic_env(target_metadata): hooks, compare_type, batch
├── script.py.mako
└── versions/
Generate revisions¶
# scripts/make_migration.py
import sys
from tempest_fastapi_sdk import AlembicHelper
from src.core.settings import settings
helper = AlembicHelper("alembic.ini", db_url=settings.DATABASE_URL)
helper.revision(message=sys.argv[1], autogenerate=True)
The file lands in
alembic/versions/2026_05_16_1432-ae12cd34_add_users_table.py — the date
prefix orders files chronologically and makes merge conflicts obvious.
Migrations come out lint-clean
The alembic.ini that init() writes includes [post_write_hooks]
that runs ruff format and then ruff check --fix on every
revision. Without it, Alembic's files fail tempest lint (W291 on
the empty Revises:, E501 on long sa.Column(...) lines) — which
is why the formatter goes first: it is the one that wraps the long
line and strips the trailing space, so running the linter first would
report errors the next hook is about to fix. The hooks use
your project's ruff config. Without ruff (on PATH or in
the environment of the Python running Alembic) the revision comes out
unformatted and without an error; every tempest new scaffold already
has it as a dev dependency.
Apply on startup¶
# src/api/app.py — inside the lifespan
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
from fastapi import FastAPI
from tempest_fastapi_sdk import AlembicHelper
from src.api.dependencies.resources import db
from src.core.settings import settings
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
"""Run pending migrations, then serve."""
helper = AlembicHelper("alembic.ini", db_url=settings.DATABASE_URL)
await helper.sync_schema_async()
await db.connect()
yield
await db.disconnect()
sync_schema_async() is the whole bootstrap: an empty database runs the
whole tree, a database created before Alembic is stamped at the base
revision and then migrated, and a database already migrated only gets what
is missing — the return value (SchemaSyncOutcomeEnum) says which path ran.
In a project generated by tempest new this call already lives in
run_migrations (Lifecycle in the lifespan).
It runs in a worker thread: the SDK's env.py calls asyncio.run, which
cannot nest inside the lifespan's loop, so the synchronous
helper.sync_schema() there raises a RuntimeError naming
sync_schema_async. Every command that runs env.py has the same _async
twin — see
Migrations ».
Destructive migrations: use safe_upgrade
helper.pending_destructive_ops() lists pending column/table DROPs;
helper.safe_upgrade() raises DestructiveMigrationError instead of
silently dropping data. The full deploy guide (migration + graceful
shutdown) is in Safe deploys ».
CI gate — the schema must match the models¶
# scripts/check_migrations.py
import sys
from tempest_fastapi_sdk import AlembicHelper
from src.core.settings import settings
helper = AlembicHelper("alembic.ini", db_url=settings.DATABASE_URL)
if not helper.check():
print("Schema drift detected — run make_migration.py and commit.")
sys.exit(1)
print("Schema is in sync.")
# .github/workflows/ci.yml
- name: Check migrations are in sync
run: uv run python scripts/check_migrations.py
check() no longer reports phantom enum drift on SQLite (v0.313.0, #483)
On SQLite an enum column is a VARCHAR plus a CHECK
(ck_<table>_<enum>). Alembic's CHECK comparator read the
constraint from the database but dropped it from the metadata side —
they are _type_bound, attached to the column type — so check()
proposed a phantom remove_constraint right after a clean
upgrade head, and the drift gate stayed off. run_alembic_env
passes an include_object that ignores that CHECK, keyed by
(table, name) so two tables with a same-named CHECK cannot hide
each other's drift. Real drift is still reported — a new column, and
also a changed enum member: sync_enum_types appends a
replace_enum, and ReplaceEnumOp gained to_diff_tuple, without
which check() raised NotImplementedError while building the diff
instead of reporting it.
Base columns always first
The SDK's env.py installs the reorder_base_columns_first hook, so
every generated migration lists id / is_active / created_at /
updated_at ahead of your columns — consistent diffs across people.
A new NOT NULL column no longer explodes (v0.67.0)
Adding a NOT NULL column to a table that already has rows blows
up on PostgreSQL with NotNullViolationError: column "x" contains null
values — because a Python-side default= only fires on ORM inserts,
never as DDL. The SDK now installs a second hook,
backfill_non_nullable_defaults: every added column that is
nullable=False, has no server_default, but does declare a
scalar Python default gets a server_default derived from that
default — so the generated migration backfills existing rows in the
same statement.
# In the model — just the Python default:
is_professional: Mapped[bool] = mapped_column(default=False)
# The generated migration now reads (note server_default):
op.add_column(
"users",
sa.Column(
"is_professional",
sa.Boolean(),
nullable=False,
server_default=sa.text("false"),
),
)
Covers bool / int / float / str / Enum (uses .value). It
does not act when the default is a callable (uuid4,
func.now()) or absent — those need a hand-written data migration,
since the SDK cannot infer a safe backfill value.
Already have an old env.py? Update the import + wiring to compose
both hooks:
# alembic/env.py
from tempest_fastapi_sdk.db.alembic_hooks import (
backfill_non_nullable_defaults,
compose_hooks,
reorder_base_columns_first,
)
_process_revision_directives = compose_hooks(
reorder_base_columns_first,
backfill_non_nullable_defaults,
)
# ...and pass it to context.configure(process_revision_directives=...)
For a migration that already exploded, add
server_default=sa.text("...") by hand to the op.add_column (or
backfill + alter_column to drop the default afterwards).
Migrate composite constraints from the old convention¶
If your database was created before the composite naming fix, every unique, index and foreign key with more than one column is still named after its first column only. Single-column names did not change. After upgrading the SDK the drift gate reports a difference — and what autogenerate proposes is not what you want to apply.
On a database with UniqueConstraint("title", "release_year"),
Index(None, "author", "title") and a composite FK,
alembic revision --autogenerate renders (measured against PostgreSQL 16 and
Alembic 1.19.1):
from alembic import op
def upgrade() -> None:
"""What autogenerate renders on the legacy database."""
with op.batch_alter_table("books", schema=None) as batch_op:
batch_op.drop_index(batch_op.f("ix_books_author"))
batch_op.drop_constraint(batch_op.f("uq_books_title"), type_="unique")
batch_op.create_index(
batch_op.f("ix_books_author_books_title"),
["author", "title"],
unique=False,
)
batch_op.create_unique_constraint(
batch_op.f("uq_books_title_release_year"),
["title", "release_year"],
)
Do not apply that drop + create on PostgreSQL
Two measured problems, and a cost:
- It breaks when an FK depends on the unique. With a composite FK
pointing at the unique it drops, PostgreSQL refuses:
cannot drop constraint uq_authors_tenant_id on table authors because other objects depend on it. - It does not see the foreign keys. A composite FK whose name changed
does not show up in the diff; it keeps its old name in the database,
and that is the name
parse_integrity_errorreturns. - It rebuilds the index. Creating the unique again builds its index
by reading the whole table.
RENAMEonly changes the name — and on PostgreSQL renaming the constraint also renames the index behind it (measured inpg_indexes).
legacy_constraint_renames compares the metadata against the old
convention and lists every composite constraint whose name changed — foreign
keys included — with the RENAME ready. Run it once, with every model
imported:
# scripts/constraint_renames.py
from sqlalchemy.dialects import postgresql
import src.db.models
from tempest_fastapi_sdk import BaseModel, legacy_constraint_renames
dialect = postgresql.dialect()
renames = legacy_constraint_renames(BaseModel.metadata)
print("def upgrade() -> None:")
for rename in renames:
print(f" op.execute({rename.statement(dialect)!r})")
print("def downgrade() -> None:")
for rename in renames:
print(f" op.execute({rename.inverse().statement(dialect)!r})")
Create an empty revision (helper.revision(message="rename composite
constraints", autogenerate=False)) and paste the output into it:
"""rename composite constraints to the per-column convention."""
from alembic import op
revision: str = "b7e1c2d3a4f5"
down_revision: str | None = "ae12cd34"
def upgrade() -> None:
"""Rename composite constraints to the per-column convention."""
op.execute("ALTER INDEX ix_books_author RENAME TO ix_books_author_books_title")
op.execute(
"ALTER TABLE books RENAME CONSTRAINT uq_books_title "
"TO uq_books_title_release_year"
)
def downgrade() -> None:
"""Go back to the old convention's names."""
op.execute("ALTER INDEX ix_books_author_books_title RENAME TO ix_books_author")
op.execute(
"ALTER TABLE books RENAME CONSTRAINT uq_books_title_release_year "
"TO uq_books_title"
)
After the upgrade, autogenerate sees no difference at all, and the
single-column constraints were left untouched (measured: compare_metadata
returns [] on the renamed database, in tests/db/test_naming_live.py).
Why paste, instead of calling the function inside the migration
A migration has to do tomorrow what it does today. Called inside
upgrade(), the function would compute the renames from the models on
the day the migration runs — a composite constraint added later would
leak into an old file. Earlier revisions need nothing: autogenerate
wrote the name into each of them with op.f(...).
Details worth knowing
- The SDK has one too.
make_user_oauth_account_modeldeclaresUniqueConstraint("provider", "subject")andUniqueConstraint("user_id", "provider"):uq_<table>_providerbecomesuq_<table>_provider_subject, anduq_<table>_user_idbecomesuq_<table>_user_id_provider. With the model imported, the function lists them next to yours. - Two entries with the same
old_nameare the old collision: PostgreSQL refused the secondCREATE, so the database holds only one of them. Keep the entry whose columns are those of the constraint that exists. - SQLite cannot rename a constraint — the name lives in the
CREATE TABLEtext —, andstatement()raisesValueErroroutside PostgreSQL. On a development SQLite, apply the batch migration autogenerate renders (it rebuilds the table and works, measured) or recreate the database. - Want to postpone? Give the constraint the name it already has in
the database:
UniqueConstraint("title", "release_year", name="uq_books_title"). An explicit name wins over the convention, and the function then skips it.
Recap: init once, revision --autogenerate per change, upgrade on
startup, check in CI, safe_upgrade to protect data. A database created
before the composite naming fix: legacy_constraint_renames writes the
RENAMEs, and you paste them into an empty revision.