Read the database revision with the Alembic API #19

Merged
alexander merged 3 commits from alembic-api into develop 2026-12-02 14:05:17 +01:00
Showing only changes of commit eb059c1ea5 - Show all commits

Read the database revision with the Alembic API

The `@db_revision` decorator no longer runs `alembic current` in a subprocess,
which only worked from the project folder and reported any failure as a wrong revision.

Also, its docstring now explains that it locks completed stages of the data pipeline.
Alexander Hess 2026-12-02 13:35:16 +01:00
Signed by: alexander
GPG key ID: B46EDB4DFC26805D

View file

@ -3,15 +3,37 @@
import collections.abc as cabc
import functools
import os
import subprocess # noqa:S404
import sys
import typing as t
import click
from alembic.runtime import migration
import velofy
from velofy.db import connection
def current_db_revision() -> str | None: # pragma: no cover
"""The `alembic` revision the database is at."""
with connection.get_engine().connect() as conn:
context = migration.MigrationContext.configure(
conn,
opts={
"version_table": velofy.config.ALEMBIC_TABLE,
"version_table_schema": velofy.config.ALEMBIC_TABLE_SCHEMA,
},
)
return context.get_current_revision()
def db_revision(rev: str) -> cabc.Callable[..., cabc.Callable[..., t.Any]]:
"""A decorator ensuring the database is at a given revision."""
"""A decorator ensuring the database is at a given revision.
The data are transformed and analyzed in stages. For scientific reasons,
a completed stage must not be repeated. So, the CLI command of a stage
only runs at the revision the stage was carried out at and refuses
to run once the database has moved on to a later revision.
"""
def decorator(func: cabc.Callable[..., t.Any]) -> cabc.Callable[..., t.Any]:
@functools.wraps(func)
@ -19,16 +41,15 @@ def db_revision(rev: str) -> cabc.Callable[..., cabc.Callable[..., t.Any]]:
"""Do not execute the `func` if the revision does not match."""
# Skip in tests as the database then either has no or the latest revision
if not os.getenv("TESTING"): # pragma: no cover
result = subprocess.run( # noqa:S603,S607
["alembic", "current"], # noqa:S607
capture_output=True,
check=False,
encoding="utf8",
)
current = current_db_revision()
if not result.stdout.startswith(rev):
if current != rev:
click.echo(
click.style(f"Database is not at revision {rev}", fg="red"),
click.style(
f"Database is at revision {current},"
f" but this stage requires {rev}",
fg="red",
),
)
sys.exit(1)