From eb059c1ea5010f496c729cc0cb7e4bd8ccc7ef12 Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Wed, 2 Dec 2026 13:35:16 +0100 Subject: [PATCH 1/3] 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) From 2add322a2572316f58f84d8870f4aeb01a41d06c Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Wed, 2 Dec 2026 13:41:50 +0100 Subject: [PATCH 2/3] Test the revision lock of the CLI stages The `@db_revision` decorator no longer skips its check under `TESTING`. The tests replace `current_db_revision()` with the revision they need. --- src/velofy/console/decorators.py | 23 +++++++++---------- tests/console/test_decorators.py | 38 ++++++++++++++++++++++++++++++++ tests/console/test_gridify.py | 7 ++++++ 3 files changed, 55 insertions(+), 13 deletions(-) create mode 100644 tests/console/test_decorators.py diff --git a/src/velofy/console/decorators.py b/src/velofy/console/decorators.py index 313198a..0850b03 100644 --- a/src/velofy/console/decorators.py +++ b/src/velofy/console/decorators.py @@ -2,7 +2,6 @@ import collections.abc as cabc import functools -import os import sys import typing as t @@ -39,19 +38,17 @@ def db_revision(rev: str) -> cabc.Callable[..., cabc.Callable[..., t.Any]]: @functools.wraps(func) def ensure(*args: t.Any, **kwargs: t.Any) -> 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 - current = current_db_revision() + current = current_db_revision() - if current != rev: - click.echo( - click.style( - f"Database is at revision {current}," - f" but this stage requires {rev}", - fg="red", - ), - ) - sys.exit(1) + if current != rev: + click.echo( + click.style( + f"Database is at revision {current}," + f" but this stage requires {rev}", + fg="red", + ), + ) + sys.exit(1) return func(*args, **kwargs) diff --git a/tests/console/test_decorators.py b/tests/console/test_decorators.py new file mode 100644 index 0000000..a5e3866 --- /dev/null +++ b/tests/console/test_decorators.py @@ -0,0 +1,38 @@ +"""Test the `velofy.console.decorators` module.""" + +import click + +from velofy.console import decorators + + +REQUIRED = "abcdef123456" + + +@click.command() +@decorators.db_revision(REQUIRED) +def stage() -> None: + """A stage locked to the `REQUIRED` revision.""" + click.echo("stage executed") + + +def test_stage_runs_at_the_required_revision(cli, monkeypatch): + """The stage runs if the database is at the required revision.""" + monkeypatch.setattr(decorators, "current_db_revision", lambda: REQUIRED) + + result = cli.invoke(stage) + + assert result.exit_code == 0 + assert "stage executed" in result.output + + +def test_stage_refuses_at_another_revision(cli, monkeypatch): + """The stage refuses to run once the database has moved on.""" + current = "fedcba654321" + monkeypatch.setattr(decorators, "current_db_revision", lambda: current) + + result = cli.invoke(stage) + + assert result.exit_code == 1 + assert "stage executed" not in result.output + assert current in result.output + assert REQUIRED in result.output diff --git a/tests/console/test_gridify.py b/tests/console/test_gridify.py index 8a7af2a..0e7e92a 100644 --- a/tests/console/test_gridify.py +++ b/tests/console/test_gridify.py @@ -47,6 +47,13 @@ def test_two_pixels_with_two_addresses( # Hack the configuration regarding the grids to be created. monkeypatch.setattr(velofy.config, "GRID_SIDE_LENGTHS", (side_length,)) + # The `gridify` stage is locked to the revision it was carried out at. + monkeypatch.setattr( + gridify.decorators, + "current_db_revision", + lambda: "e86290e7305e", + ) + result = cli.invoke(gridify.gridify) assert result.exit_code == 0 From 35d0c7b409d3f2359c1b9c07a5f28d0d2cbd5e7a Mon Sep 17 00:00:00 2001 From: Alexander Hess Date: Wed, 2 Dec 2026 13:51:49 +0100 Subject: [PATCH 3/3] Test reading the database revision In the "sequentially" variant of the test database, `current_db_revision()` must return the head of the migrations; in the "all_at_once" variant, there is no version table. --- src/velofy/console/decorators.py | 2 +- tests/console/test_decorators.py | 27 +++++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/velofy/console/decorators.py b/src/velofy/console/decorators.py index 0850b03..1d41fbc 100644 --- a/src/velofy/console/decorators.py +++ b/src/velofy/console/decorators.py @@ -12,7 +12,7 @@ import velofy from velofy.db import connection -def current_db_revision() -> str | None: # pragma: no cover +def current_db_revision() -> str | None: """The `alembic` revision the database is at.""" with connection.get_engine().connect() as conn: context = migration.MigrationContext.configure( diff --git a/tests/console/test_decorators.py b/tests/console/test_decorators.py index a5e3866..9d9991c 100644 --- a/tests/console/test_decorators.py +++ b/tests/console/test_decorators.py @@ -1,7 +1,11 @@ """Test the `velofy.console.decorators` module.""" import click +import pytest +from alembic import config as alembic_config +from alembic import script as alembic_script +import velofy from velofy.console import decorators @@ -36,3 +40,26 @@ def test_stage_refuses_at_another_revision(cli, monkeypatch): assert "stage executed" not in result.output assert current in result.output assert REQUIRED in result.output + + +@pytest.mark.db +@pytest.mark.usefixtures("db_connection") +def test_current_db_revision(monkeypatch, request): + """`current_db_revision()` reads the revision of the test database.""" + # The migrations name the test database's version table + # after the test schema, as configured in migrations/env.py + monkeypatch.setattr( + velofy.config, + "ALEMBIC_TABLE", + f"{velofy.config.ALEMBIC_TABLE}_{velofy.config.CLEAN_SCHEMA}", + ) + + result = decorators.current_db_revision() + + if request.node.callspec.params["db_connection"] == "sequentially": + cfg = alembic_config.Config("alembic.ini") + head = alembic_script.ScriptDirectory.from_config(cfg).get_current_head() + assert result == head + + else: # "all_at_once" creates no version table + assert result is None