Skip to content

Migrations ​

All migrations live in host/migrations/versions/ — not in module packages. Alembic runs from the repo root via host/alembic.ini and shares the app's .env / SM_DATABASE_URL.

Autogenerate's make_include_object() filter preserves foreign keys declared only in migrations by ignoring unmatched reflected constraints. Newly modeled foreign keys on existing tables still generate CreateForeignKeyOp; set ignore_unmodeled_fks=False to allow dropping database-only constraints (#812). A foreign key with the same columns and target but different options (ondelete, deferrable) is emitted as a drop plus a create; one with other columns or another target is a different constraint and stays preserved. SQLite cannot ALTER constraints: wrap such ops in op.batch_alter_table(...) by hand before applying the revision there.

For sa.Enum columns backed by Python StrEnum, generated revisions freeze the column's actual configured labels and preserve name, native_enum, create_constraint, length and configured values_callable behavior without importing application enums/callables. Plain enum fields store member names (e.g. READY); to store values (e.g. ready), configure the runtime type with values_callable=lambda e: [m.value for m in e]. Custom callable labels are frozen in the revision. Existing revisions are not rewritten (#813).

Why centralized? ​

  • Dependency ordering is global. If invoices depends on orders_order.id, their migrations must order correctly. One shared Alembic history, with down_revision links between modules, enforces this.
  • Autogenerate sees everything. host/migrations/env.py delegates to run_migrations(context), which calls build_module_metadata() to union every installed module's MetaData. Autogenerate diffs the DB against that union and writes one migration covering all changes.
  • Operators run one command. make migrate is the only target. No "did you also run orders/migrate?" footgun.

Module data upgrades in consuming hosts (#711) ​

Scaffolded hosts own their migration graphs. A schema-only baseline generated from current models does not include this repository's historical data changes. Before deploying upgraded packages, run make doctor or uv run smpy doctor. Semantic module checks (SM033) recognize equivalent/manual ports independently of upstream revision ids.

uv run smpy migrations prepare <upgrade-id> --head <host-head-or-label@head> copies a frozen, self-contained recipe beside the selected host revision. Apply the generated revision separately. An explicit current head is required. Automatic remediation requires exactly one matching installed recipe registration when the issue omits explicit instructions. See the lifecycle recipe contract. The bundled ids are mail.settings_namespace_v1 (system settings move, target wins, matching d7b3a9e5c1f2) and users.hashed_bearer_tokens_v1 (invalidate credentials before altering both token columns, matching a626b1c8d023). The first recipe for an unlabelled module declares mail/users; existing labels are not redeclared. Review the generated revision before applying it with upgrade heads.

Boot checks run before module settings hydration/startup; token incompatibility refuses boot outside development, while obsolete mail keys warn. Never-migrated first runs defer checks until the wizard applies migrations. No automatic credential deletion happens at startup. See the scaffolded host upgrade guide for the operator workflow and token sign-out risk.

Doctor uses the DB session factory and listeners used at boot: soft-deleted rows are hidden and tenant queries are scoped. Because doctor has no host settings, it always enforces strict tenant isolation, which is stricter than a single-tenant boot: a check that passes doctor also passes boot. A check must use tenant_context(id) for one tenant or explicitly use all_tenants() / execution_options(all_tenants=True) for an installation-wide check. Add execution_options(include_deleted=True) only when the check also needs trashed rows. These opt-ins work at boot too (#815).

Upgrading an app across framework versions ​

Module packages (simple_module_users, simple_module_audit_log, etc.) ship SQLModel models, not Alembic revisions. When CHANGELOG.md cites a revision ID such as a1054e9c7b62, b1153e9c7b62, 819d8c5714a5, or d3e9a5b7c124, that ID identifies the reference migration in this repository's host/migrations/versions/ — not a revision that downstream apps apply directly.

When you upgrade an app across framework versions (for example from 0.0.45 to 0.0.51 or newer), your host's own Alembic history must pick up every installed module's schema changes since your previous version:

  1. Back up the database and read CHANGELOG.md for every version you are crossing, noting any Behaviour change entries, data-upgrade recipes, and items in Schema changes Alembic autogenerate misses.

  2. Bump package pins with uv run smpy update (or update pyproject.toml and uv sync), then run uv run smpy doctor. If SM033 reports bundled data recipes, prepare them (uv run smpy migrations prepare <upgrade-id> --head <host-head-or-label@head>), review them, and apply those prepared revisions to a disposable copy of your existing database by overriding SM_DATABASE_URL before running --autogenerate against that copy — Alembic resolves its database URL from app settings (so running upgrade heads without SM_DATABASE_URL would mutate your configured database), and refuses to autogenerate while the target database is behind any head (Target database is not up to date). See Upgrading a scaffolded host.

  3. Autogenerate a host revision against the up-to-date disposable copy, covering all remaining module schema changes at once:

    bash
    # Workspace host (from the repo root)
    SM_DATABASE_URL="sqlite+aiosqlite:///./upgrade-copy.db" \
      uv run --project host alembic -c host/alembic.ini upgrade heads
    SM_DATABASE_URL="sqlite+aiosqlite:///./upgrade-copy.db" \
      uv run --project host alembic -c host/alembic.ini revision --autogenerate -m "upgrade framework"
    # Flat host
    SM_DATABASE_URL="sqlite+aiosqlite:///./upgrade-copy.db" \
      uv run alembic -c alembic.ini upgrade heads
    SM_DATABASE_URL="sqlite+aiosqlite:///./upgrade-copy.db" \
      uv run alembic -c alembic.ini revision --autogenerate -m "upgrade framework"

    If your host graph has multiple heads (for example after preparing a labelled data recipe), pass --head <rev_id> for an unlabelled head or --head <label>@head for an existing branch label. Only use the scaffold's SM_DATABASE_URL="sqlite+aiosqlite:///./upgrade-copy.db" make migration LABEL=<existing-label> msg="upgrade framework" shortcut when <existing-label> is an already-existing branch label (smpy migrations new creates a new independent root with --head base if the label does not exist).

  4. Inspect the generated revision against the checklist below. Add any partial/expression index updates, pre-migration conflict checks, data backfills, or SQLite batch_alter_table wrappers that autogenerate cannot emit.

  5. Verify and apply: test upgrade heads → downgrade → upgrade heads against the disposable copy with SM_DATABASE_URL set (and against a disposable PostgreSQL database if you deploy on Postgres), then deploy and run the full chain in order against your target database:

    bash
    # Workspace host (from the repo root)
    uv run --project host alembic -c host/alembic.ini upgrade heads
    # Flat host
    uv run alembic -c alembic.ini upgrade heads
    uv run smpy doctor

Schema changes Alembic autogenerate misses ​

Autogenerate compares the live database against build_module_metadata(), which covers new tables, new/altered columns, and plain indexes/constraints. It does not reliably detect or emit the following changes — add them by hand (or call the shipped helpers from users.contracts.migrations, available from simple_module_users >= 0.0.52 / unreleased at 0.0.51) when upgrading across releases that introduce them:

  • Expression and partial index changes (for example ix_users_user_email_lower becoming unique in 0.0.43 / e731a1b2c3d4, and becoming partial with WHERE email IS NOT NULL in 0.0.51 / d3e9a5b7c124). On SQLite, SQLAlchemy cannot reflect expression index definitions at all (neither uniqueness nor WHERE predicates), and when existing index names are inspectable, SM026 (INFO) suppresses indexes that already exist by name — so an existing index whose definition changed is silently skipped. Alembic's autogenerate also misses WHERE predicate changes on expression indexes on PostgreSQL. On simple_module_users >= 0.0.52, call recreate_user_email_lower_index from users.contracts.migrations — always after any op.batch_alter_table("users_user") block in both upgrade() and downgrade() (SQLite batch rebuilds do not reflect expression indexes, so running batch_alter_table after creating the index would silently drop it):

    python
    from alembic import op
    from users.contracts.migrations import recreate_user_email_lower_index
    
    
    def upgrade() -> None:
        with op.batch_alter_table("users_user") as batch:
            ...
        recreate_user_email_lower_index(op, partial=True)
    
    
    def downgrade() -> None:
        # Before restoring NOT NULL email or pre-issuer OAuth uniqueness, guard
        # against NULL emails, NULL account_email, issuer bindings, and
        # cross-issuer (oauth_name, account_id) collisions — see
        # host/migrations/versions/d3e9a5b7c124_users_oidc_issuer_and_nullable_email.py.
        with op.batch_alter_table("users_user") as batch:
            ...
        # Restores the full unique index (for 0.0.43–0.0.50 baselines). If
        # downgrading across 0.0.43 (e731a1b2c3d4), recreate a non-unique index
        # inline with unique=False instead.
        recreate_user_email_lower_index(op, partial=False)

    If you are targeting simple_module_users <= 0.0.51 (before users.contracts.migrations existed) or prefer inline Alembic operations without importing the helper, place the drop + create after the batch_alter_table("users_user") block inside upgrade() — and on SQLite, ensure the batch rebuild and index replacement run inside an explicit transaction (e.g. BEGIN / begin_nested()) so a failing CREATE UNIQUE INDEX rolls back both the table rebuild and the DROP INDEX:

    python
    import sqlalchemy as sa
    from alembic import op
    
    
    def upgrade() -> None:
        with op.batch_alter_table("users_user") as batch:
            ...
        op.drop_index("ix_users_user_email_lower", table_name="users_user", if_exists=True)
        op.create_index(
            "ix_users_user_email_lower",
            "users_user",
            [sa.text("lower(email)")],
            unique=True,
            sqlite_where=sa.text("email IS NOT NULL"),
            postgresql_where=sa.text("email IS NOT NULL"),
        )
  • Pre-migration uniqueness and data-integrity checks (for example the duplicate OAuth identity precheck in 0.0.50 / b1153e9c7b62 before adding uq_users_oauth_account_identity). Autogenerate emits create_unique_constraint, which fails with a raw database integrity error if duplicate rows exist. On simple_module_users >= 0.0.52, call check_unique_oauth_identities(op) from users.contracts.migrations right before adding uq_users_oauth_account_identity so the migration refuses cleanly with the bounded list of conflicting links and remediation steps. If your upgrade adds the issuer column (0.0.51+) and targets the issuer-scoped constraint (oauth_name, issuer, account_id), add and populate issuer before running the precheck and creating the constraint (the helper automatically checks (oauth_name, issuer, account_id) when issuer exists, and (oauth_name, account_id) on pre-issuer schemas):

    python
    from alembic import op
    from users.contracts.migrations import check_unique_oauth_identities
    
    
    def upgrade() -> None:
        # When jumping to 0.0.51+, add/populate users_oauth_account.issuer first
        # so the precheck matches the target (oauth_name, issuer, account_id) key.
        check_unique_oauth_identities(op)
        with op.batch_alter_table("users_oauth_account") as batch:
            ...

    On simple_module_users <= 0.0.51 (before users.contracts.migrations existed), run an inline duplicate check inside upgrade() right before creating the constraint, matching your target key ((oauth_name, issuer, account_id) once issuer exists, or (oauth_name, account_id) before issuer):

    python
    import sqlalchemy as sa
    from alembic import op
    
    
    def upgrade() -> None:
        if not op.get_context().as_sql:
            bind = op.get_bind()
            cols = {c["name"] for c in sa.inspect(bind).get_columns("users_oauth_account")}
            key = "oauth_name, issuer, account_id" if "issuer" in cols else "oauth_name, account_id"
            dups = bind.execute(
                sa.text(
                    f"SELECT {key}, count(*) FROM users_oauth_account "
                    f"GROUP BY {key} HAVING count(*) > 1 LIMIT 20"
                )
            ).all()
            if dups:
                raise RuntimeError(f"Duplicate OAuth identities must be removed first: {dups}")
        with op.batch_alter_table("users_oauth_account") as batch:
            ...
  • Data backfills and destructive transitions: autogenerate never emits UPDATE/DELETE statements. Use uv run smpy migrations prepare <upgrade-id> --head <host-head-or-label@head> for bundled data recipes (mail.settings_namespace_v1, users.hashed_bearer_tokens_v1), or write idempotent op.execute(...) backfills before adding NOT NULL constraints.

  • PostgreSQL ENUM changes and cleanup: autogenerate does not add/remove PostgreSQL enum values, and op.drop_table leaves CREATE TYPE behind on Postgres. Call drop_enums_if_postgres(op, ...) from simple_module_db.schema.migration_portability at the end of downgrade().

Reference revisionShipped inWhat autogenerate missesWhat to add in your app migration
e731a1b2c3d40.0.43ix_users_user_email_lower non-unique → uniqueResolve case-variant email duplicates, then call recreate_user_email_lower_index(op, partial=False) (or partial=True if jumping straight to 0.0.51+; use inline drop_index + create_index on <= 0.0.51); in downgrade() across 0.0.43, recreate the index inline with unique=False
b1153e9c7b620.0.50Duplicate OAuth identity precheck before uq_users_oauth_account_identityCall users.contracts.migrations.check_unique_oauth_identities(op) (>= 0.0.52) or run the inline duplicate query above before adding the unique constraint
d3e9a5b7c1240.0.51ix_users_user_email_lower full → partial (WHERE email IS NOT NULL)After batch_alter_table("users_user"), call users.contracts.migrations.recreate_user_email_lower_index(op, partial=True) in upgrade() and partial=False in downgrade() (>= 0.0.52), or use inline drop_index + create_index

The real graph ​

The history is not a single linear chain. It has several roots and several heads, and make migrate runs upgrade heads for that reason. On main today:

RootBranch
77162e7b184b initial schemathe users trunk (also holds file_storage, background_tasks, api_tokens revisions)
a738c2e4f601 auth refresh outcomes (#738)auth (root and head)
c9d2e4f6a810 OIDC identity cache (#192)oidc (root and head)
e36ab09c4a92 tenants initial schematenants (f1a9c3d7b2e4 head)
f733c7938fd1 sharing resource sharesharing (root and head)
d263ea727663 framework sm_lease tableleases (its own head; leases)
HeadOwning moduleLabel Alembic reports
f999a1b2c3d4file_storage (module-owned file access, #999)api_tokens, background_tasks, file_storage, users
819d8c5714a5audit_logaudit_log
f1a9c3d7b2e4tenantstenants
d263ea727663framework (sm_lease)leases
f6a3b9d2e8c4keycloakkeycloak
f733c7938fd1sharingsharing
c9d2e4f6a810oidcoidc
a738c2e4f601authauth

audit_log forks off the trunk at 41cf2c53660e, and keycloak forks off the users revision 873ca2015033.

A module's first migration sets branch_labels = ("<module_name>",). Alembic inherits a label onto every descendant, so the label names a revision and everything above it, and it does not isolate the module. It is only a named target (upgrade <label>@head, revision --head <label>@head) and the source of the Doctor's module column, which reads the first label on each revision.

Known mislabels ​

The declared branch_labels are auth (added by a738c2e4f601), audit_log, api_tokens, background_tasks, keycloak, tenants, sharing, leases, users (added by a625f0b7c912), oidc (added by c9d2e4f6a810) and file_storage (added by f5b1c3e8a207). The graph carries these defects; they are documented rather than rewritten, because changing labels on revisions that installed databases already applied is not worth the risk:

  • 51b2058d8afd_api_tokens_initial sits in the middle of the trunk, so every revision above it (file_storage, background_tasks including the outbox, and the users revisions through c8e4f1a2b6d9) reports the api_tokens label. The api_tokens head is therefore a shared-trunk revision, currently owned by file_storage.
  • keycloak branches off a users revision, so a Keycloak-only install still builds the users schema.
  • settings, permissions and feature_flags have no label of their own. users and file_storage gained labels late (a625f0b7c912, f5b1c3e8a207), so their earlier revisions stay unlabelled and report api_tokens.

Guidance: give an unlabelled module a branch_labels on its next revision. Adding a label to an existing revision file is technically possible, because alembic_version stores revision ids and never labels, but it also relabels every descendant and changes what <label>@head resolves to, so treat it as a deliberate, reviewed change rather than a cleanup.

host/tests/test_migration_graph.py pins the roots, heads, each revision's owning module and the mislabels above. Adding a root, head or revision fails it until the table is updated.

Browser refresh coordination (#738) ​

Migration a738c2e4f601 creates auth_refresh_outcome on an independent auth root. Apply upgrade heads before using OIDC or Keycloak renewal. The 30-second outcomes contain only the principal, expiry, sealed refresh token and session coordination keys; expired rows are purged when a later renewal publishes its outcome (lookups never write). outcome_key (primary key) is a hash of the session, its sealed refresh token being spent and the provider; lock_key (indexed) is the per-session hash, which logout uses to delete the session's outcomes. Independent transactions publish outcomes before releasing the session lease, without waiting for the request transaction. No Redis is required. Downgrade drops this short-lived cache; it does not alter user accounts.

Users token storage upgrade (#626) ​

Migration a626b1c8d023 follows a625f0b7c912 on users@head and changes refresh and access token keys to SHA-256 digests. Behaviour change: upgrade deletes existing refresh/access token rows, requiring one re-login for clients using them (including sm_auth cookies). Other session cookies are unaffected. Downgrade also deletes token rows: hashes cannot be restored to bearer secrets. Cookie login, token login and refresh prune up to 100 spent rows per table for that user. Refresh reuse evidence is retained while the family has a live token, including when an ancestor has expired; inactive users' rows wait until their next login.

Day-to-day workflow ​

Create a migration ​

bash
make migration msg="add orders tables"

This runs alembic -c host/alembic.ini revision --autogenerate from the repo root. The resulting file lands in host/migrations/versions/XXXX_add_orders_tables.py.

A post_write_hooks entry in host/alembic.ini (this repo's and every scaffolded app's) runs the project's ruff on each new revision: ruff check --select I --fix, then ruff format. A fresh revision therefore passes make lint. Only the import rules are fixed, so an empty handwritten revision keeps its sa and op imports. Ruff must be installed in the venv Alembic runs from: every scaffold puts it in the default dev dependency group (the workspace root's, or the host's for smpy create-host). Without it Alembic writes the file and then fails with Could not find module ruff; run uv add --dev ruff. An app scaffolded before 0.0.45 can copy the [post_write_hooks] block from a new smpy new app's host/alembic.ini, provided its Alembic is 1.16.3 or newer, the first release with the module hook runner (#896).

Always open and read the generated file before committing. Autogenerate is good but not perfect:

  • It detects column additions, drops, type changes, index/constraint changes, new tables.
  • It misses semantic constraints (e.g. "this ENUM now has one more value"), and it sometimes produces drops that should be renames.
  • Constraint naming needs to be stable — provide explicit name="..." kwargs when creating indexes/constraints in your models.

Apply migrations ​

bash
make migrate

Runs alembic -c host/alembic.ini upgrade heads. Idempotent.

Downgrade ​

bash
make downgrade                                                 # back one revision
uv run --project host alembic -c host/alembic.ini downgrade <revision_id>   # to a specific revision

Do not use downgrade orders@base to roll back just the orders module. The label names a revision, and orders@base unwinds that revision, all of its descendants, and everything beneath it down to the root it sits on, including other modules'. With this graph, downgrade api_tokens@base would drop the whole users trunk (users, file_storage, the background_tasks outbox and the initial schema), not only the api_tokens tables.

Removing one module's schema ​

  • If the module's revisions are the latest on their branch (nothing from another module sits above them), downgrade to the down_revision of the module's first revision: alembic -c host/alembic.ini downgrade <that down_revision id>.
  • Otherwise write a dedicated migration that drops the module's tables (and anything depending on them). Other modules are untouched.

First migration of a new module ​

When you scaffold a module with smpy create-module, the first autogenerate revision produces a file that needs this marker added by hand:

python
# host/migrations/versions/XXXX_add_orders_tables.py

revision = "..."
down_revision = "..."
branch_labels = ("orders",)  # ← add this
depends_on = None

The marker names the revision so you can target it (for example alembic upgrade orders@head); later orders revisions do not need it. It does not turn the module into an independent branch, and it is inherited by every revision stacked on top of it, so put it on the module's own first revision and not on a revision that other modules build on.

Alembic environment setup ​

host/migrations/env.py delegates to the public framework runner:

python
from alembic import context
from simple_module_hosting.boot.migrations_env import run_migrations

run_migrations(context)

The runner discovers metadata from every installed module, regardless of the web app's enabled-module subset. Both offline SQL generation and online migration runs use the same hooks:

  • build_module_metadata() unions module metadata.
  • make_include_object() restricts autogenerate to those tables, preserving host-owned tables outside the module system.
  • render_item renders SQLModel strings and enums without application imports.
  • make_process_revision_directives() preserves SQLite expression indexes and rewrites Boolean defaults portably, with the existing SQLite check warnings.

The runner reads Settings().database_url, converts async drivers to sync drivers, and logs the target with its password masked. A URL supplied in config.attributes[ALEMBIC_DATABASE_URL_ATTRIBUTE] (from simple_module_hosting.boot.migrations) takes precedence, so the setup wizard migrates its locked database. Relative SQLite URLs retain settings' project-root anchoring. Module extensions are emitted offline or committed before online revisions. Alembic logging keeps existing application loggers enabled for in-process runs.

Existing copied environments continue working. To receive future fixes, replace the copied environment with the snippet above, retaining application-specific customizations separately. Revision files and Alembic configuration stay in the host.

Boot-time migration check ​

On startup, migration_status() in simple_module_hosting.boot.migrations compares the stamps in alembic_version to every head.

  • Every environment: a database behind head fails the boot (Database is N revision(s) behind … Run: make migrate), except a never-migrated first run, which boots far enough to serve the /setup wizard. The result is stored on app.state.migration.
  • Boot, setup, Doctor, and prepare share project-root discovery. They check alembic.ini before host/alembic.ini. SM_PROJECT_ROOT overrides the root search. smpy migrations prepare --config selects an explicit cwd-relative path.
  • An unavailable migration history leaves the state unknown. Development logs an SM010 warning and leaves the migration step pending. Other environments refuse boot. The wizard rechecks the history and only applies migrations on a verified first run.
  • make doctor reports migration problems as SM010 before you boot.

Fix locally with make migrate. In production, run migrations before rolling over the web tier.

Diagnostic: SM011 ​

Fires as a warning when a database at every head lacks a table a module's models declare, so no migration creates it. make doctor checks the database SM_DATABASE_URL points at; a development boot checks its own database once it is open. Typical causes:

  • You added a model but haven't generated a migration for it yet.
  • You renamed a table but the old migration still references the old name.
  • You used __abstract__ = True somewhere it shouldn't be.

make doctor and the dev-mode boot log print the offending table names; while the database is behind head the check is skipped, since the table may be in a pending revision. Resolution: run make migration msg="...", review, make migrate.

Cross-module foreign keys ​

If invoices has an FK to orders_order.id:

  • Alembic will emit ADD CONSTRAINT in the invoices table's migration.
  • The migration that creates invoices_invoice must come after the one that creates orders_order in the history (an ancestor, not a sibling branch).
  • smpy create-module + make migration handle this naturally as long as depends_on is correct in ModuleMeta.

All tables share the host's single schema on both Postgres and SQLite, so a cross-module FK is just an ordinary same-schema reference (orders_order.id ← invoices_invoice.order_id).

On SQLite, FKs are off by default but the test suite enables them; in production SQLite use (rare), set PRAGMA foreign_keys = ON.

Data migrations ​

Alembic supports ad-hoc op.execute("UPDATE ...") inside a migration. Use for:

  • Backfilling new NOT NULL columns — add as nullable, backfill, alter to NOT NULL.
  • Renaming columns — op.alter_column with new_column_name=... preserves data.
  • Migrating enum values.

Data migrations run as part of alembic upgrade. If they fail mid-way, you're left at an intermediate state — design them to be idempotent (use ON CONFLICT, IF EXISTS, UPDATE ... WHERE x IS NULL).

For long-running backfills on big tables, break into batches and run outside Alembic:

python
# scripts/backfill_orders_total.py
async def backfill(batch_size=1000): ...

Migration drift in monorepos ​

git pull introducing two parallel branches of Alembic revisions:

text
revision A  ← you created
revision B  ← teammate's branch created

Both have down_revision = <previous>, so the same branch now has two heads. (Heads on different labelled branches are expected and need no merge; upgrade heads applies them all.) Resolve a same-branch fork by:

  1. uv run alembic heads — list them.
  2. uv run alembic merge -m "merge A and B" <rev-A> <rev-B> — creates a merge revision with both as parents.
  3. Commit the merge revision.

Keep merges small; a merge revision with its own op.* logic is a code smell.

Initial-migration gotchas ​

When you autogenerate a migration for a freshly-added module, autogenerate writes op.create_table(...) for every table in the module's MetaData. Inspect:

  • Are the table names right (the module-prefixed orders_order, identical on Postgres and SQLite)?
  • Do indexes and constraints have stable names? Rename via name=... on the model if not.
  • Did autogenerate also pick up any other module's tables? That means you forgot make migrate after the last scaffold. Squash the file down to just this module's changes.

Testing migrations ​

The db_session fixture stamps alembic_version at head on a fresh in-memory DB, which validates that build_module_metadata() + your migrations produce a schema the tables can operate against. That said, integration tests don't run every Alembic op — if you want to exercise the migrations explicitly:

python
def test_migration_up_then_down(tmp_path, monkeypatch):
    from alembic.config import Config
    from alembic import command

    db_url = f"sqlite:///{tmp_path}/migrate_test.db"
    monkeypatch.setenv("SM_DATABASE_URL", db_url)
    cfg = Config("host/alembic.ini")

    command.upgrade(cfg, "heads")
    command.downgrade(cfg, "base")

That catches the common "autogenerate wrote a broken downgrade" class of bugs. The migration environment reads SM_DATABASE_URL through settings, overriding cfg.set_main_option("sqlalchemy.url", ...); set the environment variable so the test migrates only its temporary database. Alembic's command API is synchronous, so the test needs no async marker.

Released under the MIT License.