From eb059c1ea5010f496c729cc0cb7e4bd8ccc7ef12 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Wed, 2 Dec 2026 13:35:16 +0100 Subject: [PATCH] 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. --- src/velofy/console/decorators.py | 41 ++++++++++++++++++++++++-------- 1 file changed, 31 insertions(+), 10 deletions(-) diff --git a/src/velofy/console/decorators.py b/src/velofy/console/decorators.py index 4c9a5d9..313198a 100644 --- a/src/velofy/console/decorators.py +++ b/src/velofy/console/decorators.py @@ -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)