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
+22 -34
View File
@@ -6,15 +6,14 @@ One file per build, `<data>/cohorts/<domain>/<cohort>/<armado_id>.parquet`, wher
domain's database and `COHORTS_DIR` replaces `<data>/cohorts`. Long format: one row per member and event, with
the member's index date on every row and the build's lineage in the file's metadata.
The timeline comes from the dbt model `<domain>_linea_de_tiempo`. dbt only compiles it to SQL, which runs here as
a subquery, so nothing is stored in the database and it can be opened read-only (on SQLite, dbt doesn't open it at
all). In a read-only folder, with nothing writing to the file, use
The timeline comes from dbt's view `<domain>_linea_de_tiempo`, which holds no rows and needs creating only when its
dbt model changes (`dbt run --select <domain>_linea_de_tiempo`). The script only reads, through the domain's
repository, so it needs neither dbt nor write access. In a read-only folder, with nothing writing to the file, use
`CACU_DATABASE_URL=sqlite:///file:/path/cacu.db?immutable=1&uri=true`; `mode=ro` isn't enough for a WAL database.
"""
import argparse
import os
import subprocess
import sys
import tempfile
from collections.abc import Callable, Iterable
@@ -28,14 +27,17 @@ import pyarrow.parquet as pq
from persistance.aristas.oro import CohortBuild, CohortMember
from persistance.aristas.plata import TIMELINE_COLUMNS, TimelineRepository
from persistance.settings import settings
from sqlalchemy import column, select, text
from sqlalchemy import column, select, table
from sqlalchemy.engine import make_url
from sqlalchemy.exc import DBAPIError
from models.io.cohorts import SCHEMA
ROW_ORDER = ["pac_id", "fecha", "clase", "tipo", "fuente_id"]
DBT_TARGETS = {"sqlite": "sqlite", "mssql": "sqlserver", "postgresql": "postgres", "mysql": "mysql", "mariadb": "mysql"}
DEFAULT_TRANSFORMATION = Path(__file__).resolve().parents[2] / "Transformation"
class TimelineViewError(RuntimeError):
"""dbt's timeline view can't be read."""
def cohorts_root(database_url: str) -> Path:
@@ -59,30 +61,15 @@ def lineage_of(path: Path) -> dict[str, str]:
return {k.decode(): v.decode() for k, v in metadata.items() if k not in (b"pandas", b"ARROW:schema")}
def compile_timeline(domain: str, database_url: str, transformation: Path) -> str:
"""The SQL of the domain's timeline model for this engine. On SQLite, dbt connects to an empty throwaway file."""
backend = make_url(database_url).get_backend_name()
model = f"{domain}_linea_de_tiempo"
with tempfile.TemporaryDirectory(prefix="dbt-compile-") as workdir:
work = Path(workdir)
(work / "schemas").mkdir()
env = {**os.environ, "DBT_SCHEMA_DIR": str(work / "schemas")}
if backend == "sqlite":
env[f"{domain.upper()}_DB_PATH"] = str(work / "empty.db")
subprocess.run(
["uv", "run", "--no-sync", "dbt", "--quiet", "compile", "--profiles-dir", ".", "--profile", domain,
"--target", DBT_TARGETS[backend], "--select", model, "--target-path", str(work / "target"),
"--log-path", str(work / "logs")],
cwd=transformation, env=env, check=True, capture_output=True, text=True)
compiled = next((work / "target" / "compiled").rglob(f"{model}.sql"))
return compiled.read_text().strip().rstrip(";")
def read_timeline(repository: TimelineRepository, sql: str) -> list[dict]:
"""Every event of the domain, with `sql` as a subquery. The cut-offs are applied in `build_table`."""
linea = text(sql.replace(":", r"\:")).columns(*(column(name) for name in TIMELINE_COLUMNS)).subquery("linea")
query = select(*(linea.c[name] for name in TIMELINE_COLUMNS))
return repository.with_query(lambda **_: query).read()
def read_timeline(repository: TimelineRepository, domain: str) -> list[dict]:
"""Every event of the domain, from dbt's view. The cut-offs are applied in `build_table`."""
name = f"{domain}_linea_de_tiempo"
view = table(name, *(column(c) for c in TIMELINE_COLUMNS))
try:
return repository.with_query(lambda **_: select(*(view.c[c] for c in TIMELINE_COLUMNS))).read()
except DBAPIError as error:
raise TimelineViewError(f"can't read {name} ({error.orig}): is it created? "
f"Run `dbt run --select {name}` in Transformation") from error
def build_table(rows: list[dict], members: Iterable[CohortMember], build: CohortBuild, *, domain: str,
@@ -153,11 +140,9 @@ def main(argv: list[str] | None = None) -> int:
return 1
database_url = getattr(settings, f"{args.domain}_database_url")
transformation = Path(os.environ.get("TRANSFORMATION_DIR", DEFAULT_TRANSFORMATION))
def make_table() -> pa.Table:
rows = read_timeline(timeline, compile_timeline(args.domain, database_url, transformation))
return build_table(rows, cohorts.members(build.armado_id), build, domain=args.domain,
return build_table(read_timeline(timeline, args.domain), cohorts.members(build.armado_id), build, domain=args.domain,
parametros=cohorts.get(build.armado_id).parametros)
try:
@@ -165,6 +150,9 @@ def main(argv: list[str] | None = None) -> int:
except PermissionError as error:
print(f"{error}: the data folder is read-only, set COHORTS_DIR", file=sys.stderr)
return 1
except TimelineViewError as error:
print(error, file=sys.stderr)
return 1
print(f"{outcome}: {path}")
return 0