Files
ISSSTELEON/Persistance/persistance/edges/dbt.py
T

88 lines
4.2 KiB
Python

"""What dbt owns in a domain's database and Python reads: the timeline view and the queries dbt compiled.
dbt creates and changes these relations, so there's no ORM class and no Alembic migration for them. Both repositories
read on a `ReadSession`. That refuses ORM writes and `insert`/`update`/`delete` statements, but not one spelled as
text, so a compiled query is trusted to be the `select` dbt wrote; a database account that can only read is what
guarantees it.
"""
from collections.abc import Callable, Iterable
from datetime import date, datetime
from core.indicadores.tipos import FechaHoraUTC
from sqlalchemy import Date, Select, bindparam, column, select, table, text
from sqlalchemy.exc import DBAPIError
from persistance.edges.silver.timeline import TIMELINE_COLUMNS, TimelineRepository
from persistance.materializer import ReadSession
from persistance.repository import Repository
class DbtRelationError(RuntimeError):
"""A relation dbt should have created can't be read."""
def timeline_view(domain: str) -> str:
return f"{domain}_linea_de_tiempo"
class DbtTimelineRepository(TimelineRepository):
"""The domain's timeline, read from dbt's view `<domain>_linea_de_tiempo`.
`fecha` comes back as a date and `conocida_en` as an aware UTC datetime on every engine. The filters run in the database; `patients` becomes one bound
parameter per patient, so a long list can exceed an engine's limit (SQL Server's is 2,100): read without it and join.
"""
def __init__(self, session_factory: Callable, domain: str):
self.view = timeline_view(domain)
super().__init__(session_factory, self._query)
def _query(self, *, patients: Iterable[int] | None, until: date | None, known_until: datetime | None):
types = {"fecha": Date, "conocida_en": FechaHoraUTC}
view = table(self.view, *(column(name, types.get(name)) for name in TIMELINE_COLUMNS))
query = select(*(view.c[name] for name in TIMELINE_COLUMNS))
if patients is not None:
query = query.where(view.c.pac_id.in_(list(patients)))
if until is not None:
query = query.where(view.c.fecha <= until)
if known_until is not None:
query = query.where(view.c.conocida_en <= known_until)
return query.order_by(view.c.pac_id, view.c.fecha, view.c.fuente_tabla, view.c.fuente_id)
def read(self, *, patients: Iterable[int] | None = None, until: date | None = None,
known_until: datetime | None = None) -> list[dict]:
try:
return super().read(patients=patients, until=until, known_until=known_until)
except DBAPIError as error:
raise DbtRelationError(f"can't read {self.view} ({error.orig}): is it created? "
f"Run `dbt run --select {self.view}` in Transformation") from error
class DbtQueryRepository(Repository):
"""Runs a query dbt compiled (a model's `compiled_code` in `manifest.json`); one dict per row.
A query compiled with `--vars '{bind: true}'` has placeholders (`:periodo_inicio`) instead of values: `parameters`
gives them, and a list or tuple fills an `in :name`. The database does the work; only what the query selects
comes back.
"""
def __init__(self, session_factory: Callable):
super().__init__(session_factory, None)
def read(self, sql: str, parameters: dict | None = None) -> list[dict]:
columns, rows = self.rows(sql, parameters)
return [dict(zip(columns, row)) for row in rows]
def rows(self, sql: str | Select, parameters: dict | None = None) -> tuple[list[str], list[tuple]]:
"""The column names and the rows; the names come back even when there are no rows.
`sql` can also be a `select` built over dbt's relations, which carries its own bound values.
"""
parameters = parameters or {}
query = sql if isinstance(sql, Select) else text(sql).bindparams(*(
bindparam(name, value, expanding=isinstance(value, (list, tuple))) for name, value in parameters.items()
))
with self._session_factory() as session:
result = ReadSession(session).execute(query)
return list(result.keys()), [tuple(row) for row in result]