Files

87 lines
5.2 KiB
Python

"""What the cycle takes from dbt's manifest: the event models to create and the catalog the reports point to.
The measures are defined in dbt's semantic layer (`webapi.metrics`, `webapi.compositions`). Their event models have
to exist in the database for a measure to be asked; `event_views` gives the DDL that creates them from dbt's compiled
SQL, as `dbt run` would for a view. The publication catalog (`cat_measure*`, `cat_estrato`) is what the reports'
units point to; `catalog_layers` builds it from the same definitions, parents before children.
"""
import json
from importlib import import_module
from pathlib import Path
from sqlalchemy import text
from webapi.compositions import composition_definitions
from webapi.durations import OBSERVATION, duration_definitions
from webapi.kpis import scoring_of
from webapi.metrics import measure_definitions
CONTRACTS = {"proportion": "C1", "composition": "C2", "continuous-variable": "C3r"} # the publication views
STRATUM_LABELS = {"grupo_edad": "Grupo de edad"} # unless the stratum's `etiqueta` says otherwise
def event_views(manifest: Path, project: str) -> list:
"""`drop view if exists` and `create view … as <compiled SQL>` for every model the project's measures read,
parents first.
Those are the project's models semantic models count over (`models/<project>/…`), the timelines its strata
read (`meta.estratos.*.linea`) and the views the WebApi reads (`meta.lee_la_webapi`), with the non-ephemeral
models they're built on; an ephemeral one is already inlined
in its child's compiled SQL. Another domain's models aren't created: their tables may not exist here.
"""
m = json.loads(manifest.read_text(encoding="utf-8"))
nodes = {n["unique_id"]: n for n in m["nodes"].values()}
by_name = {n["name"]: uid for uid, n in nodes.items() if n["resource_type"] == "model"}
roots = {uid for uid in (s["depends_on"]["nodes"][0] for s in m["semantic_models"].values())
if nodes[uid]["fqn"][1] == project}
roots |= {by_name[spec["linea"]] for metric in m["metrics"].values()
if metric["config"].get("meta", {}).get("measure_url", "").startswith(f"{project}/")
for spec in metric["config"]["meta"].get("estratos", {}).values() if "linea" in spec}
# The views the WebApi reads directly (a follow-up list, a patient summary).
roots |= {uid for uid, n in nodes.items() if n["resource_type"] == "model" and n["fqn"][1] == project
and n["config"].get("meta", {}).get("lee_la_webapi")}
ordered: list[str] = []
def visit(uid: str) -> None:
if uid in ordered or uid not in nodes:
return
for parent in nodes[uid]["depends_on"]["nodes"]:
visit(parent)
if nodes[uid]["config"]["materialized"] != "ephemeral":
ordered.append(uid)
for uid in sorted(roots):
visit(uid)
ddl = [text(f"drop view if exists {nodes[uid]['alias']}") for uid in reversed(ordered)]
return ddl + [text(f"create view {nodes[uid]['alias']} as {nodes[uid]['compiled_code']}") for uid in ordered]
def catalog_layers(project: str, manifest: Path) -> list[list]:
"""The catalog rows of every measure the manifest defines for the project, in layers: parents first."""
t = import_module(f"core.{project}.indicadores.models")
# The title on screen: `meta.titulo` when the label had to differ (dbt wants labels unique in the project).
labels = {n["name"]: n["config"].get("meta", {}).get("titulo") or n["label"]
for n in json.loads(manifest.read_text(encoding="utf-8"))["metrics"].values()}
definitions = [d for d in (*measure_definitions(manifest).values(), *composition_definitions(manifest).values(),
*duration_definitions(manifest).values()) if d.url.startswith(f"{project}/")]
labels_of = {s.name: s.spec.get("etiqueta") or STRATUM_LABELS.get(s.name, s.name)
for d in definitions for s in d.strata}
strata = sorted(labels_of)
measures, children = [], []
for d in definitions:
contract = CONTRACTS[scoring_of(d)]
measures.append(t.CatMeasure(measure_id=d.measure_id, url=d.url, version=d.version, titulo=labels[d.metric],
contrato=contract, unidad=d.basis))
exclusion = getattr(d, "exclusion", None)
codes = dict.fromkeys((*d.denominator.codes, *d.numerator.codes, *((OBSERVATION,) if contract == "C3r" else ()),
*(exclusion.codes if exclusion else ())))
children += [t.CatMeasureResultado(resultado_id=f"{d.measure_id}.{c}", measure_id=d.measure_id, poblacion=c,
etiqueta=c) for c in codes]
children.append(t.CatMeasureGrupo(measure_id=d.measure_id, grupo=d.group, etiqueta=d.group, orden=0))
children += [t.CatMeasureGrupo(measure_id=d.measure_id, grupo=g.name, etiqueta=g.label, orden=i)
for i, g in enumerate(getattr(d, "groups", ()), 1)]
children += [t.CatMeasureEstrato(measure_id=d.measure_id, estrato_id=s.name) for s in d.strata]
stratum_rows = [t.CatEstrato(estrato_id=s, etiqueta=labels_of[s], unidad="paciente") for s in strata]
return [stratum_rows + measures, children]