Export reads the timeline from dbt's view

This commit is contained in:
2026-11-04 20:39:53 -06:00
parent 27e29804aa
commit 122f71105a
3 changed files with 40 additions and 59 deletions
+17 -24
View File
@@ -1,13 +1,12 @@
"""What this module covers: `scripts/export_cohort.py`, the standalone export of a kit cohort build: where the file
goes, what it holds, that it's written once, and that reading the timeline stores nothing in the database.
goes, what it holds, that it's written once, and that the timeline is read from dbt's view without changing the database.
Fixtures: `script`, the module loaded from its path, since `scripts/` isn't part of the package; `build`, a build
cut at 2025-12-31 with two members; `events`, one kept event per member plus one event each cut-off must drop and
one of a patient outside the build; `timeline_db`, a SQLite file with a `eventos` table and its repository.
one of a patient outside the build; `timeline_db`, a SQLite file with a `cacu_linea_de_tiempo` view and its repository.
"""
import importlib.util
import shutil
import sqlite3
from datetime import date, datetime, timezone
from pathlib import Path
@@ -19,7 +18,6 @@ from persistance.aristas.plata import TIMELINE_COLUMNS, TimelineRepository
from sqlmodel import Session, create_engine
ROOT = Path(__file__).resolve().parents[1]
TRANSFORMATION = ROOT.parent / "Transformation"
MEMBERS = [CohortMember(20, date(2025, 2, 1), "citologiacervical", "b"),
CohortMember(10, date(2025, 1, 1), "citologiacervical", "a")]
@@ -152,40 +150,35 @@ def test_server_engine_needs_cohorts_dir(script, monkeypatch):
@pytest.fixture
def timeline_db(tmp_path):
"""A SQLite file with an `eventos` table, and a repository over it."""
"""A SQLite file with one event behind a `cacu_linea_de_tiempo` view, and a repository over it."""
path = tmp_path / "cacu.db"
connection = sqlite3.connect(path)
connection.execute(f"create table eventos ({', '.join(TIMELINE_COLUMNS)})")
connection.execute("insert into eventos values (10, '2025-02-01', '2025-02-02', 'medicion', 'vph', 'vph', 'a:b', null, 't', '1')")
connection.execute("create view cacu_linea_de_tiempo as select * from eventos")
connection.execute("insert into eventos values (10, '2025-02-01', '2025-02-02', 'medicion', 'vph', 'vph', 'a', null, 't', '1')")
connection.commit()
connection.close()
engine = create_engine(f"sqlite:///{path}")
return path, TimelineRepository(lambda: Session(engine))
def test_read_timeline_stores_nothing(script, timeline_db):
"""Pins down: the timeline runs as a subquery, with the column contract, and adds no object to the database.
Fails if the read creates a view, or if a colon in the SQL is taken for a bind parameter."""
def test_read_timeline_reads_the_view_and_changes_nothing(script, timeline_db):
"""Pins down: the rows come from the domain's view, with the column contract, and the read adds no object. Fails
if the script reads another relation, or starts creating objects in the database."""
path, repository = timeline_db
sql = "select pac_id, fecha, conocida_en, clase, tipo, codigo, valor_codigo || ':x' as valor_codigo, valor_numerico, fuente_tabla, fuente_id from eventos"
rows = script.read_timeline(repository, sql)
rows = script.read_timeline(repository, "cacu")
assert rows[0]["pac_id"] == 10 and rows[0]["valor_codigo"] == "a:b:x"
assert [(row["pac_id"], row["valor_codigo"]) for row in rows] == [(10, "a")]
connection = sqlite3.connect(path)
assert connection.execute("select name from sqlite_master").fetchall() == [("eventos",)]
assert connection.execute("select name from sqlite_master order by name").fetchall() == [("cacu_linea_de_tiempo",), ("eventos",)]
connection.close()
@pytest.mark.skipif(not (TRANSFORMATION / ".venv").exists() or shutil.which("uv") is None,
reason="needs the Transformation environment")
def test_compile_never_opens_the_domains_database(script, monkeypatch, tmp_path):
"""Pins down: dbt compiles the timeline without touching the domain's SQLite file. Fails if the compile uses the
caller's database path or stops producing SQL over `procedimiento`."""
database = tmp_path / "cacu.db"
monkeypatch.setenv("CACU_DB_PATH", str(database))
def test_missing_view_says_how_to_create_it(script, timeline_db):
"""Pins down: without the view the error names the dbt command to run. Fails if the driver's error reaches the
user unexplained, or if the message stops naming the domain's model."""
_, repository = timeline_db
sql = script.compile_timeline("cacu", f"sqlite:///{database}", TRANSFORMATION)
assert '"procedimiento"' in sql and not sql.endswith(";")
assert not database.exists()
with pytest.raises(script.TimelineViewError, match="dbt run --select cama_linea_de_tiempo"):
script.read_timeline(repository, "cama")