Files
ISSSTELEON/Persistance/persistance/aristas/plata/timeline.py
T

68 lines
2.8 KiB
Python

"""Silver: each patient's timeline of procedures and observations, under a fixed column contract.
The query is injected. Each domain module binds dbt's view (`persistance.aristas.dbt`); another query, such as
the indicator kit's `linea_de_tiempo_plata`, can still be bound with `with_query`. Readers keep the same columns and
filters.
"""
from collections.abc import Callable, Iterable
from datetime import date, datetime
from typing import Protocol
from sqlalchemy import Select
from persistance.materializador import SesionDeLectura
from persistance.repository import Repository
TIMELINE_COLUMNS = (
"pac_id", "fecha", "conocida_en", "clase", "tipo", "codigo", "valor_codigo", "valor_numerico",
"fuente_tabla", "fuente_id",
)
class TimelineQuery(Protocol):
def __call__(self, *, patients: Iterable[int] | None, until: date | None,
known_until: datetime | None) -> Select: ...
class TimelineContractError(ValueError):
"""The injected query returned columns other than `TIMELINE_COLUMNS`."""
class TimelineQueryMissing(RuntimeError):
"""`read` was called on a repository that has no query yet (see `with_query`)."""
class TimelineRepository(Repository):
"""Reads the timeline of some patients, or of everyone, cut at a date and at what was loaded by then.
Created with a query, or without one and bound later with `with_query`, so neither side names what it
can't import.
"""
def __init__(self, session_factory: Callable, query: TimelineQuery | None = None):
super().__init__(session_factory, None)
self._query = query
def with_query(self, query: TimelineQuery) -> "TimelineRepository":
"""The same repository, reading through `query`."""
return TimelineRepository(self._session_factory, query)
def read(self, *, patients: Iterable[int] | None = None, until: date | None = None,
known_until: datetime | None = None) -> list[dict]:
"""One dict per event, keyed by `TIMELINE_COLUMNS`, in the query's order.
`until` keeps events up to that clinical date; `known_until` keeps rows already loaded at that
moment. The query runs on a read-only session.
"""
if self._query is None:
raise TimelineQueryMissing("bind a timeline query with `with_query` before reading")
query = self._query(patients=None if patients is None else list(patients), until=until,
known_until=known_until)
with self._session_factory() as session:
result = SesionDeLectura(session).execute(query)
columns = tuple(result.keys())
if columns != TIMELINE_COLUMNS:
raise TimelineContractError(f"expected columns {TIMELINE_COLUMNS}, got {columns}")
return [dict(zip(columns, row)) for row in result]