Skip to content

Migrations

Every database recipe assumes the schema already exists. This one is about the step before that: how the schema comes into being, and why the hand-written version of that step is wrong in a way that stays invisible for weeks.

The SDK ships the whole path as one method — AlembicHelper.sync_schema() — and the rest of this page explains what it decides, so you can recognise which state your database is in.

The complete bootstrap

There are three steps, and only the last one runs on every boot. A project generated by tempest new already ships with all three done.

1. Generate the environment with AlembicHelper.init

Do not write alembic.ini or alembic/env.py by hand:

# scripts/alembic_init.py
from tempest_fastapi_sdk import AlembicHelper

AlembicHelper("alembic.ini").init(
    "alembic",
    metadata_module="src.db.models",
    metadata_attr="BaseModel",
)
uv run python scripts/alembic_init.py

metadata_module is the module that exposes BaseModel with every model already imported — in a tempest new project, src.db.models; in a layout where only src/db/__init__.py re-exports BaseModel, src.db. tempest db init makes the same call. Running the script above in an empty directory, the generated alembic.ini is this:

[alembic]
script_location = %(here)s/alembic
prepend_sys_path = %(here)s
path_separator = os
sqlalchemy.url =
file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
timezone = UTC

[post_write_hooks]
hooks = ruff
ruff.type = module
ruff.module = tempest_fastapi_sdk.db._ruff_post_write
ruff.options = REVISION_SCRIPT_FILENAME

Three things in it that the hand-written version usually gets wrong:

  • An empty sqlalchemy.url. The credential stays out of version control; the URL arrives through the AlembicHelper's db_url= or, without it, through the DATABASE_URL environment variable.
  • No [loggers]/[handlers]/[formatters] section. The generated env.py only calls logging's fileConfig when the section exists, so a migration running inside the service process does not reconfigure the logging tree configure_logging already set up. The stock block from alembic init -t async ships a [logger_root] with level = WARNING.
  • [post_write_hooks] running ruff format and then ruff check --fix, so a generated revision comes out lint-clean. The hook looks for a ruff that runs (on PATH, then in the environment of the Python running Alembic); with none, as on the [cli-ops] server install, the revision is created unformatted and without an error message.

The generated alembic/env.py is a single call to run_alembic_env(target_metadata) — see The generated env.py.

2. Generate the initial revision

The tempest command needs the [cli] extra (or [cli-ops] on a server)

Without either, tempest exits with code 2 and prints how to install it. In development: uv add --dev "tempest-fastapi-sdk[cli]". Details in Installation → CLI.

uv run tempest db revision -m "initial"

With no revision at all, step 3 creates no table: it returns SchemaSyncOutcomeEnum.NO_MIGRATIONS and leaves the database as it is. Measured on an empty SQLite before the first revision: outcome: no_migrations, zero tables.

3. Sync the schema in the lifespan

The shape is the one tempest new generates — a run_migrations in src/db/configs/migrations.py, with the absolute path of alembic.ini so the lifespan finds it from any directory:

# src/db/configs/migrations.py
from pathlib import Path

from tempest_fastapi_sdk import AlembicHelper, SchemaSyncOutcomeEnum

ALEMBIC_INI_PATH: Path = Path(__file__).resolve().parents[3] / "alembic.ini"


async def run_migrations(database_url: str) -> SchemaSyncOutcomeEnum:
    """Bring the database schema to the Alembic head."""
    return await AlembicHelper(
        str(ALEMBIC_INI_PATH),
        db_url=database_url,
    ).sync_schema_async()

Call it from the lifespan and the service boots with the right schema from any starting state:

# src/api/app.py
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager

from fastapi import FastAPI

from src.core.settings import settings
from src.db.configs import run_migrations


@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
    """Sync the schema before the first request is served."""
    outcome = await run_migrations(settings.DATABASE_URL)
    print(f"schema: {outcome.value}")
    yield


app: FastAPI = FastAPI(lifespan=lifespan)

Measured with one model, one initial revision and the lifespan above booting three SQLite databases: the empty one comes out synced with alembic_version and the table; the one created earlier by create_tables() comes out adopted; the second boot of the first comes out synced without changing anything.

No create_tables() in the lifespan

# src/api/app.py — wrong: the schema stops evolving on the second boot.
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager

from fastapi import FastAPI

from src.api.dependencies.resources import db


@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
    """Create the tables on every boot."""
    await db.connect()
    await db.create_tables()
    yield
    await db.disconnect()

The first boot works, which is why this shape survives review. A new column on the model never reaches the database on the boots after it: create_tables() is CREATE TABLE IF NOT EXISTS — the why is in Why create_tables() is not the answer. The rule is a single one: in the lifespan, run_migrations; create_tables() only in a test fixture over in-memory SQLite (Where create_tables() is legitimate).

From async code, use the _async method

The lifespan runs inside uvicorn's event loop. Every AlembicHelper method that executes alembic/env.py has an _async twin — upgrade_async, safe_upgrade_async, downgrade_async, stamp_async, revision_async, check_async, current_async, has_existing_schema_async, adopt_async, sync_schema_async, squash_async, pending_destructive_ops_async — with the same signature, and that is the one you call from async code. The one difference is the readers' bind=, which on the _async twin takes an async engine/connection (see the revision in a readiness probe).

The reason is the env.py the SDK generates: it starts the async engine with asyncio.run(...), and asyncio.run cannot be called while a loop is already running. Calling the sync method from the lifespan now fails immediately, with the right instruction:

RuntimeError: AlembicHelper.upgrade() was called from a running event loop. It runs alembic/env.py, which drives migrations with asyncio.run() and cannot nest inside the loop; use `await helper.upgrade_async(...)` instead.

Before, the same error came from deep inside Alembic as asyncio.run() cannot be called from a running event loop, together with a RuntimeWarning: coroutine 'run_async_migrations' was never awaited — and check() did not even raise: it swallowed the error and answered False, as if the schema had drifted.

The _async method runs the sync one in a worker thread, which has no loop of its own, so the asyncio.run in env.py works there and the service's loop keeps serving while the migration runs. Since the thread needs nothing new in env.py, the env.py already in your repository keeps working — no need to regenerate it.

Sync current() still works on the loop

Reading the revision does not go through env.py: with a sync driver installed (the stdlib sqlite3, or psycopg2 on PostgreSQL), helper.current() works from async code as before. Only an async-only install (asyncpg with no sync driver) takes the asyncio.run path — and then it raises too, asking for current_async().

Technical details: sharing the connection instead of a thread

Alembic has an official recipe for running the migration on the loop itself: open an AsyncConnection and hand the sync connection that run_sync provides over as config.attributes["connection"]. The env.py the SDK generates from this release on accepts it — given the connection, it migrates on it, without creating an engine or calling asyncio.run:

# src/db/shared_connection.py
from alembic import command
from sqlalchemy.engine import Connection
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
from tempest_fastapi_sdk import AlembicHelper

from src.core.settings import settings


async def upgrade_on_shared_connection() -> None:
    """Run every pending migration on a connection this code owns."""
    helper: AlembicHelper = AlembicHelper(
        "alembic.ini",
        db_url=settings.DATABASE_URL,
    )
    config = helper.config

    def _upgrade(connection: Connection) -> None:
        """Hand the sync connection to env.py and upgrade on it."""
        config.attributes["connection"] = connection
        command.upgrade(config, "head")

    engine: AsyncEngine = create_async_engine(settings.DATABASE_URL)
    async with engine.begin() as conn:
        await conn.run_sync(_upgrade)
    await engine.dispose()

The _async methods do not take that path, and the reason is compatibility: an env.py generated before this release ignores config.attributes and calls asyncio.run regardless — inside run_sync the loop is running, and it fails with the same error as before. The thread works with every env.py already generated. Use the path above when the migration must run on your connection or transaction, and regenerate env.py for it: run tempest db init in an empty directory and copy the generated alembic/env.py over yours, checking the metadata import (the default is from src.db.models import BaseModel).

The new env.py also refuses, with its own message, to be executed from inside a loop without a connection handed over — the case of calling command.upgrade straight from async code.

The revision in a readiness probe

"Is the database at the head?" is a readiness-probe question, and it runs every few seconds. AlembicHelper ships the check ready for make_health_router:

# src/api/health.py
from fastapi import APIRouter
from tempest_fastapi_sdk import AlembicHelper, AsyncDatabaseManager, make_health_router

from src.core.settings import settings

db: AsyncDatabaseManager = AsyncDatabaseManager(settings.DATABASE_URL)
helper: AlembicHelper = AlembicHelper("alembic.ini", db_url=settings.DATABASE_URL)

health_router: APIRouter = make_health_router(
    db=db,
    checks={"schema": helper.schema_at_head_check(db)},
)

schema_at_head_check(db) returns the Callable[[], Awaitable[bool]] that checks= expects. On each call it reads the revision with current_async(bind=db.engine) — the pool the app already has open, resolved at call time, which is why the check can be built before the lifespan connects — and compares it with heads(). It answers True only when the tree has one head and the database is stamped at it; an empty tree, an unstamped database or one behind the head give False, and readiness answers 503.

Run against a SQLite database with one revision, before and after upgrade_async():

before upgrade: 503 {'status': 'not_ready', 'checks': {'database': True, 'schema': False}}
after upgrade: 200 {'status': 'ready', 'checks': {'database': True, 'schema': True}}

Two things keep this cheap:

  • The read does not log. current() and current_async() read alembic_version with a plain SELECT, without building Alembic's MigrationContext. Up to 0.369.1, every read logged Context impl ... and Will assume ... DDL. at INFO on the alembic.runtime.migration logger — two lines per probe. With that logger at INFO, an upgrade_async() followed by three readiness calls produces only the upgrade's lines:

    alembic.runtime.migration Context impl SQLiteImpl.
    alembic.runtime.migration Will assume non-transactional DDL.
    alembic.runtime.migration Running upgrade  -> a172a1a0e250, first
    

    upgrade, downgrade and stamp still go through Alembic and log as before, including while a read runs concurrently in another thread.

  • With bind=, no engine is created. Without it, current() opens a short-lived engine from the URL and disposes of it at the end (and, on an async-only install, starts an asyncio.run with a fresh async engine). With bind= — Engine/Connection on the sync method, AsyncEngine/AsyncConnection on the _async one — the read uses what you passed and neither creates nor disposes of an engine; on _async it runs on your loop through run_sync, with no worker thread. This applies to current, current_async, has_existing_schema and has_existing_schema_async:

    # src/db/revision.py
    from tempest_fastapi_sdk import AlembicHelper, AsyncDatabaseManager
    
    
    async def stamped_revision(helper: AlembicHelper, db: AsyncDatabaseManager) -> str | None:
        """Read the stamped revision over the app's pool."""
        return await helper.current_async(bind=db.engine)
    

A custom version_table is not read

The read targets the alembic_version table in the connection's default schema — what the SDK-generated env.py configures, and what current() always read. A hand-edited env.py passing version_table= or version_table_schema= to context.configure is not seen by it.

The three states it tells apart

sync_schema() asks the question almost every hand-written bootstrap forgets: does the database hold tables Alembic did not create?

Starting state What runs Return
Empty database upgrade() — the base revision creates the tables, without the destructive guard SchemaSyncOutcomeEnum.SYNCED
Database that predates Alembic stamps the base, then safe_upgrade() SchemaSyncOutcomeEnum.ADOPTED
Database already under Alembic safe_upgrade() SchemaSyncOutcomeEnum.SYNCED
Project with no revisions yet nothing SchemaSyncOutcomeEnum.NO_MIGRATIONS

The empty database is the easy case, and it is what makes the rest work: the schema the base revision builds is, by construction, the same one later revisions assume they are altering — because it came from them.

An empty database goes through the history's drop_column

On a database with no stamp and no application table, every revision is pending. The safe_upgrade guard reads their source, not the database: a project that ever dropped a column would be refused on its first boot, before a single table exists. That is why this path runs upgrade() directly — there is no row to delete. In the other two states the database holds data, and the guard applies as always.

Why create_tables() is not the answer

The Database recipe says db.create_tables() is for tests and local development only. It is worth also saying what happens if you use it, because the prohibition without the consequence does not make anyone see the defect in their own code:

create_all is CREATE TABLE IF NOT EXISTS

Against a table that already exists, create_tables() adds no column at all. It does not fail, does not warn, and does not return anything different. It is a silent no-op.

The real defect, which took a service down for a day:

# scripts/broken_bootstrap.py — the defect, reproduced; not a recipe.
from tempest_fastapi_sdk import AlembicHelper, AsyncDatabaseManager

from src.core.settings import settings

db: AsyncDatabaseManager = AsyncDatabaseManager(settings.DATABASE_URL)


async def broken_bootstrap() -> None:
    """Reach the worst possible state: old schema, Alembic reporting head."""
    helper: AlembicHelper = AlembicHelper(
        "alembic.ini",
        db_url=settings.DATABASE_URL,
    )
    if await helper.current_async() is None:
        await db.create_tables()
        await helper.stamp_async("head")
        return
    await helper.safe_upgrade_async()

Every line is plausible. Together they produce the worst possible state: an old schema, and Alembic declaring itself up to date.

$ alembic current
a3f9c21e88b4 (head)

$ alembic upgrade head
INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.

Nothing to do. alembic history flags nothing. Weeks later, the first query touching a new column blows up far from the cause:

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column: messages.edited_at

On the user's side that reads as "sending messages stopped working": the history GET returns 500, and nothing at boot said a word.

Adopting a database that predates Alembic

This is the case the code above was trying to handle. The right answer is not to stamp head — it is to stamp the base revision:

# src/db/schema.py
from tempest_fastapi_sdk import AlembicHelper

from src.core.settings import settings


def adopt_existing_database() -> bool:
    """Bring a pre-Alembic schema under Alembic, without upgrading it."""
    helper: AlembicHelper = AlembicHelper(
        "alembic.ini",
        db_url=settings.DATABASE_URL,
    )
    return helper.adopt()

Stamping the base says "the baseline is already applied" — which is true, because the tables exist — and leaves every revision after it pending, which is also true. The safe_upgrade() that follows runs exactly those.

Stamping head says "everything is already applied", which is false for all but the first.

adopt() does nothing when that is not the case: a database already stamped has nothing to adopt, and an empty one needs the baseline to run, not to be skipped. That is why sync_schema() can call it unconditionally.

The question is answered by has_existing_schema()

It lists the tables and discounts alembic_version, which Alembic writes itself — its presence says nothing about the application schema.

Repairing a database stamped wrong

If you are already in the bad state, the fix has two steps. The first clears the pointer; the second re-adopts properly:

# scripts/repair_schema.py
from tempest_fastapi_sdk import AlembicHelper, SchemaSyncOutcomeEnum

from src.core.settings import settings


def repair() -> SchemaSyncOutcomeEnum:
    """Clear a wrong stamp and re-adopt the schema from the base."""
    helper: AlembicHelper = AlembicHelper(
        "alembic.ini",
        db_url=settings.DATABASE_URL,
    )
    helper.stamp("base")
    return helper.sync_schema()

stamp("base") is not the same as stamp(helper.base_revision()): "base" is Alembic's word for no revision applied, and it deletes the alembic_version row. After that the database looks like what it is — an existing schema with no pointer — and sync_schema() takes the adoption path.

Check what is pending before you upgrade

After stamp("base"), the revisions between base and head will run against a schema that may already carry part of them. Run helper.pending_destructive_ops() and read helper.history() first — and have a backup. safe_upgrade refuses destructive migrations without force=True, which helps, but does not replace looking.

SQLite: migrations run with foreign keys off

On SQLite, Alembic alters a table in batch mode (the generated env.py sets render_as_batch=True): it creates a copy with the new shape, copies the rows, drops the original and renames the copy. With PRAGMA foreign_keys=ON, that DROP TABLE runs the foreign-key actions of the dropped table — and a child with ON DELETE CASCADE goes with it.

Measured with Alembic 1.19.1 and SQLite 3.47.1, adding one nullable column to the parent table with batch_alter_table("org", recreate="always"):

PRAGMA foreign_keys Rows in member before → after Error
0 3 → 3 none
1 3 → 0 none

So the engines the SDK builds to migrate — the generated env.py's and the AlembicHelper read engines (current(), has_existing_schema()) — keep FK off, while AsyncDatabaseManager turns it on by default. If you use the connection-sharing recipe (config.attributes["connection"], described above), the generated env.py checks the pragma of the connection it receives and refuses before migrating:

RuntimeError: refusing to run migrations on a SQLite connection with PRAGMA foreign_keys=ON: Alembic batch mode recreates tables, and dropping the old copy of a parent table runs ON DELETE CASCADE on its children, deleting their rows without an error. ...

The way out is migrating on a connection from an engine without FK — a manager just for that:

# src/db/shared_connection.py
from alembic import command
from sqlalchemy.engine import Connection
from tempest_fastapi_sdk import AlembicHelper, AsyncDatabaseManager

from src.core.settings import settings


async def upgrade_on_shared_connection() -> None:
    """Migrate on a connection that does not enforce foreign keys."""
    helper: AlembicHelper = AlembicHelper(
        "alembic.ini",
        db_url=settings.DATABASE_URL,
    )
    config = helper.config

    def _upgrade(connection: Connection) -> None:
        """Hand the connection to env.py and migrate on it."""
        config.attributes["connection"] = connection
        command.upgrade(config, "head")

    migrations_db: AsyncDatabaseManager = AsyncDatabaseManager(
        settings.DATABASE_URL,
        sqlite_foreign_keys=False,
    )
    await migrations_db.connect()
    try:
        async with migrations_db.engine.begin() as conn:
            await conn.run_sync(_upgrade)
    finally:
        await migrations_db.disconnect()

PRAGMA foreign_keys=OFF cannot fix an open connection

SQLite ignores the pragma inside a transaction, and the connection that reaches env.py is already in one. Turning it off has to happen when the engine is built (sqlite_foreign_keys=False, or a plain create_async_engine(url)), not on the connection.

An env.py generated before this version does not refuse

The check lives in env.py, and yours was copied into the repository when you ran tempest db init. If it receives a connection from an AsyncDatabaseManager — which now turns FK on by default —, switch to a connection without FK as above and regenerate env.py (run tempest db init in an empty directory and copy alembic/env.py over yours, checking the metadata import). Migrating through AlembicHelper or the CLI is not affected: those paths open their own engine, without FK.

The generated env.py

tempest db init (or AlembicHelper.init) writes an alembic/env.py of three statements — the docstring is the only prose, with no inline comment:

"""Alembic environment script generated by tempest-fastapi-sdk."""

from tempest_fastapi_sdk.db import run_alembic_env

from src.db.models import BaseModel

target_metadata = BaseModel.metadata

run_alembic_env(target_metadata)

Everything the file used to do now lives in run_alembic_env: resolving DATABASE_URL, the revision hooks, render_enum_types, batch mode, the offline and online paths, and the connection handed over in config.attributes["connection"]. Two reasons, both seen on a real service:

  • A copy drifts. A service rewrote env.py by hand to pass lint, ended up with its own copy of the SDK's logic — later fixes never reached it — and lost the sys.path handling along the way, so uv run alembic downgrade -1 stopped importing src. With a call into the SDK, the fix arrives when the package is upgraded.
  • A full script cannot be lint-clean under every configuration. The alembic/ directory next to pyproject.toml makes ruff's default (src = [".", "src"]) treat alembic as first-party, and the tempest new scaffold (src = ["src", "tests"]) as third-party. from alembic import context lands in a different import block under each, so one of the two always reports I001. The generated file imports no alembic, and sorts the same under both.

The guard tests/test_alembic_env_lint_guard.py generates the file in a temporary project and runs ruff check --select E,W,F,I under both configurations (plus the scaffold's whole configuration): zero errors and zero inline comments.

The bare Alembic CLI works too

The generated alembic.ini carries script_location = %(here)s/alembic and prepend_sys_path = %(here)s, both anchored on the ini's own directory. So uv run alembic upgrade head and uv run alembic downgrade -1 import your package without the tempest CLI, and a lifespan that passes the ini's absolute path (AlembicHelper("/app/alembic.ini")) finds the scripts whatever directory the process started in. Up to 0.312.x the ini carried alembic and ., relative to the working directory, and only worked from the project root. path_separator = os comes with it: without it, Alembic 1.19.1 emits a DeprecationWarning about the legacy splitting of prepend_sys_path, and anyone running with -W error (or filterwarnings = ["error"]) sees the migration fail.

One more hook

The hooks every revision goes through are in DEFAULT_REVISION_HOOKS. To add your own, compose and pass it as process_revision_directives= — the value replaces the default, so include the SDK's:

"""Alembic environment script with one extra revision hook."""

from collections.abc import Iterable

from alembic.operations.ops import MigrationScript
from alembic.runtime.migration import MigrationContext
from tempest_fastapi_sdk.db import (
    DEFAULT_REVISION_HOOKS,
    compose_hooks,
    run_alembic_env,
)

from src.db.models import BaseModel


def skip_empty_revisions(
    context: MigrationContext,
    revision: str | Iterable[str | None],
    directives: list[MigrationScript],
) -> None:
    """Write no file when autogenerate finds no change."""
    script = directives[0]
    if script.upgrade_ops is not None and script.upgrade_ops.is_empty():
        directives[:] = []


run_alembic_env(
    BaseModel.metadata,
    process_revision_directives=compose_hooks(
        *DEFAULT_REVISION_HOOKS,
        skip_empty_revisions,
    ),
)

Measured against PostgreSQL 16: after upgrade head, an alembic revision --autogenerate with no model change writes no file.

Already have an env.py generated earlier?

It keeps working. To start receiving the SDK's fixes, replace its content with the three statements above (keeping your metadata import) and add prepend_sys_path = %(here)s and path_separator = os to the [alembic] section of alembic.ini. Migrations already written do not change: op.replace_enum and op.drop_enum_type are registered when env.py imports tempest_fastapi_sdk.db.

Each revision file

tempest db revision -m "Cria tabela de anotações" (and AlembicHelper.revision) writes:

alembic/versions/2026_10_11_2317-c16a7545f8f9_cria_tabela_de_anotacoes.py
  • An ASCII name. The message is folded to ASCII only to build the file name, so alembic/versions/ holds no accented module name; the migration's docstring starts with the message as you wrote it, accents included.
  • No comment line. tempest db init writes the SDK's own script.py.mako, without the # revision identifiers line of Alembic's template, and the revision drops the # ### commands auto generated by Alembic ### markers autogenerate puts around the operations.

With bare alembic revision

The new template applies (no # revision identifiers), but the name keeps its accents and the markers stay: measured with alembic revision --autogenerate -m "Cria anotações", the file came out as ..._cria_anotações.py with all four markers. Use tempest db revision.

Project initialized before this?

The ASCII name and the marker removal already apply, because they live in tempest db revision. For the comment-free template, replace alembic/script.py.mako with the SDK's:

uv run python -c "from importlib import resources; print(resources.files('tempest_fastapi_sdk.db._alembic_templates').joinpath('script.py.mako').read_text())" > alembic/script.py.mako

Where create_tables() is legitimate

In tests and throwaway local development — where the database is born and dies in the same process, and there is no migration to drift from:

# tests/conftest.py
from collections.abc import AsyncIterator

import pytest
from sqlalchemy.ext.asyncio import AsyncSession
from tempest_fastapi_sdk import AsyncDatabaseManager


@pytest.fixture
async def session() -> AsyncIterator[AsyncSession]:
    """Yield a session over a fresh in-memory schema."""
    db: AsyncDatabaseManager = AsyncDatabaseManager(
        "sqlite+aiosqlite:///:memory:"
    )
    await db.create_tables()
    async with db.get_session_context() as opened:
        yield opened
    await db.drop_tables()

The technical reason it works here and not in production is the same in both cases: create_all only knows how to create what is missing. In a database that was just born, "what is missing" is everything — so it gets it right. In one that has already run, "what is missing" is no table at all, but possibly several columns — and columns it does not look at.

Recap

  • alembic.ini and alembic/env.py come from AlembicHelper.init(...) (or tempest db init), never by hand; without an initial revision sync_schema_async() returns NO_MIGRATIONS and creates no table.
  • In the lifespan, run_migrations (the scaffold's sync_schema_async()); never create_tables().
  • sync_schema() is the whole bootstrap: it tells an empty database, a pre-Alembic one and an already-migrated one apart, and reports which path it took.
  • On an empty database the whole tree runs without the destructive guard (there is no data to lose); with an application table, a pending drop_* still raises DestructiveMigrationError without force=True.
  • From async code (lifespan, endpoint), call the _async twin (await helper.sync_schema_async()); the sync method raises with a loop running, naming the _async one to use.
  • For readiness, helper.schema_at_head_check(db) in make_health_router's checks=: it reads the revision over the app's pool (current_async(bind=db.engine)), creating no engine and logging nothing.
  • create_tables() is CREATE TABLE IF NOT EXISTS — a silent no-op on an existing table. It is never the step that evolves a schema.
  • When adopting an existing schema, stamp the base revision (helper.base_revision(), or just helper.adopt()), never head.
  • To repair a wrong stamp("head"): stamp("base"), then sync_schema().
  • create_tables() stays legitimate where there is no migration to drift from: tests and in-memory SQLite.
  • On SQLite, migrations run on a connection without foreign keys: batch mode rebuilds the table and the cascade would delete the children. The generated env.py refuses a handed-over connection with FK on.
  • The generated env.py is one call to run_alembic_env: SDK fixes arrive with the package upgrade, and the file passes ruff with no inline comment. prepend_sys_path = %(here)s lets the bare Alembic CLI import your package.

See also

  • Database » — session, repository, AsyncDatabaseManager.
  • CLI » — tempest db upgrade, revision, stamp, check.
  • Safe deploys » — safe_upgrade and the CI drift gate.