Persistance: TimelineRepository with an injected query (#21)
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
"""Plata: los catálogos, la carga del staging directo, `v_persona`, el periodo de observación y la verificación."""
|
||||
"""Plata: los catálogos, la carga del staging directo, `v_persona`, el periodo de observación, la verificación y la línea de tiempo."""
|
||||
|
||||
from persistance.aristas.plata.carga import (
|
||||
CargaRepository,
|
||||
@@ -9,6 +9,12 @@ from persistance.aristas.plata.carga import (
|
||||
from persistance.aristas.plata.catalogos import CatalogoRepository
|
||||
from persistance.aristas.plata.observacion import ObservacionRepository
|
||||
from persistance.aristas.plata.procedimientos import guardar_plata_en
|
||||
from persistance.aristas.plata.timeline import (
|
||||
TIMELINE_COLUMNS,
|
||||
TimelineContractError,
|
||||
TimelineQuery,
|
||||
TimelineRepository,
|
||||
)
|
||||
from persistance.aristas.plata.vinculos import VinculosRepository
|
||||
from persistance.aristas.plata.vistas import VistasRepository
|
||||
|
||||
@@ -16,6 +22,10 @@ __all__ = [
|
||||
"CargaRepository",
|
||||
"CatalogoRepository",
|
||||
"ObservacionRepository",
|
||||
"TIMELINE_COLUMNS",
|
||||
"TimelineContractError",
|
||||
"TimelineQuery",
|
||||
"TimelineRepository",
|
||||
"VinculosRepository",
|
||||
"VistasRepository",
|
||||
"abrir_carga",
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Silver: each patient's timeline of procedures and observations, under a fixed column contract.
|
||||
|
||||
The query is injected. The code that builds it today, the indicator kit's `linea_de_tiempo_plata`,
|
||||
depends on this package and can't be imported from here, so it's wired where the repositories are
|
||||
assembled. When the timeline moves to dbt, only the injected query changes; 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 TimelineRepository(Repository):
|
||||
"""Reads the timeline of some patients, or of everyone, cut at a date and at what was loaded by then."""
|
||||
|
||||
def __init__(self, session_factory: Callable, query: TimelineQuery):
|
||||
super().__init__(session_factory, None)
|
||||
self._query = 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.
|
||||
"""
|
||||
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]
|
||||
@@ -0,0 +1,81 @@
|
||||
from datetime import date, datetime
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import Column, Date, DateTime, Float, Integer, MetaData, String, Table, create_engine, insert, select
|
||||
from sqlalchemy.pool import StaticPool
|
||||
from sqlmodel import Session
|
||||
|
||||
from persistance.aristas.plata import TIMELINE_COLUMNS, TimelineContractError, TimelineRepository
|
||||
from persistance.materializador import SoloLectura
|
||||
|
||||
metadata = MetaData()
|
||||
events = Table(
|
||||
"timeline_events", metadata,
|
||||
Column("pac_id", Integer), Column("fecha", Date), Column("conocida_en", DateTime),
|
||||
Column("clase", String), Column("tipo", String), Column("codigo", String),
|
||||
Column("valor_codigo", String), Column("valor_numerico", Float),
|
||||
Column("fuente_tabla", String), Column("fuente_id", String),
|
||||
)
|
||||
|
||||
ROWS = [
|
||||
{"pac_id": 1, "fecha": date(2025, 1, 5), "conocida_en": datetime(2025, 1, 6), "clase": "procedimiento",
|
||||
"tipo": "citologia", "codigo": "citologia_cervical", "valor_codigo": "SATISFACTORIA", "valor_numerico": None,
|
||||
"fuente_tabla": "citologiacervical", "fuente_id": "1"},
|
||||
{"pac_id": 1, "fecha": date(2025, 3, 1), "conocida_en": datetime(2025, 3, 2), "clase": "medicion",
|
||||
"tipo": "biopsia", "codigo": "cin", "valor_codigo": "LIEAG", "valor_numerico": None,
|
||||
"fuente_tabla": "biopsiacervical", "fuente_id": "7"},
|
||||
{"pac_id": 2, "fecha": date(2025, 2, 1), "conocida_en": datetime(2025, 6, 1), "clase": "procedimiento",
|
||||
"tipo": "citologia", "codigo": "citologia_cervical", "valor_codigo": None, "valor_numerico": None,
|
||||
"fuente_tabla": "citologiacervical", "fuente_id": "3"},
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def session_factory():
|
||||
engine = create_engine("sqlite://", poolclass=StaticPool, connect_args={"check_same_thread": False})
|
||||
metadata.create_all(engine)
|
||||
with engine.begin() as connection:
|
||||
connection.execute(insert(events), ROWS)
|
||||
return lambda: Session(engine)
|
||||
|
||||
|
||||
def timeline_query(*, patients, until, known_until):
|
||||
"""Stands in for the injected query: same columns and filters, over a plain table."""
|
||||
query = select(*(events.c[name] for name in TIMELINE_COLUMNS))
|
||||
if patients is not None:
|
||||
query = query.where(events.c.pac_id.in_(patients))
|
||||
if until is not None:
|
||||
query = query.where(events.c.fecha <= until)
|
||||
if known_until is not None:
|
||||
query = query.where(events.c.conocida_en <= known_until)
|
||||
return query.order_by(events.c.pac_id, events.c.fecha)
|
||||
|
||||
|
||||
def test_reads_every_event_with_the_contract_columns(session_factory):
|
||||
rows = TimelineRepository(session_factory, timeline_query).read()
|
||||
assert [tuple(row) for row in rows] == [TIMELINE_COLUMNS] * 3
|
||||
assert [(row["pac_id"], row["tipo"]) for row in rows] == [(1, "citologia"), (1, "biopsia"), (2, "citologia")]
|
||||
|
||||
|
||||
def test_filters_reach_the_query(session_factory):
|
||||
repository = TimelineRepository(session_factory, timeline_query)
|
||||
assert [row["fuente_id"] for row in repository.read(patients=[1])] == ["1", "7"]
|
||||
assert [row["fuente_id"] for row in repository.read(until=date(2025, 2, 1))] == ["1", "3"]
|
||||
assert [row["fuente_id"] for row in repository.read(known_until=datetime(2025, 5, 1))] == ["1", "7"]
|
||||
assert repository.read(patients=iter([2]), until=date(2025, 1, 31)) == []
|
||||
|
||||
|
||||
def test_a_query_with_other_columns_breaks_the_contract(session_factory):
|
||||
def short_query(*, patients, until, known_until):
|
||||
return select(events.c.pac_id, events.c.fecha)
|
||||
|
||||
with pytest.raises(TimelineContractError, match="expected columns"):
|
||||
TimelineRepository(session_factory, short_query).read()
|
||||
|
||||
|
||||
def test_the_query_runs_on_a_read_only_session(session_factory):
|
||||
def writing_query(*, patients, until, known_until):
|
||||
return insert(events).values(pac_id=9)
|
||||
|
||||
with pytest.raises(SoloLectura):
|
||||
TimelineRepository(session_factory, writing_query).read()
|
||||
Reference in New Issue
Block a user