94 lines
5.3 KiB
Python
94 lines
5.3 KiB
Python
"""Oro: measures asked for on request, each answer kept once under the full key of the question.
|
|
|
|
A question is a measure and its definition's version, a period, the event cut-off (`fecha`), the knowledge cut-off
|
|
(`conocida_en`) and the values of its rules. Its answer is a `measure_report` whose `parametros` is that key and
|
|
whose `parametros_sha` is the key's hash, with its units in `measure_report_unidad` and their strata in
|
|
`measure_report_unidad_estrato`, so the publication views read it as any other report. The database writes those
|
|
rows (`INSERT … SELECT`): they never pass through Python. A stratum value not yet in `cat_estrato_valor` is added
|
|
there first, labelled with itself, so the foreign key from `measure_report_unidad_estrato` holds.
|
|
|
|
Asking a stored key again reads it and writes nothing; what was answered can't drift when later loads change silver.
|
|
"""
|
|
|
|
from collections.abc import Callable, Iterable
|
|
|
|
from sqlalchemy import Select, and_, distinct, exists, func, insert, literal, select
|
|
from sqlmodel import SQLModel
|
|
|
|
from persistance.repository import Repository
|
|
|
|
|
|
class MeasureHistoryRepository(Repository):
|
|
"""The reports of a domain's measures asked for on request. `unit_model` and `stratum_model` are the domain's
|
|
`measure_report_unidad` and `measure_report_unidad_estrato`; `value_model`, its `cat_estrato_valor`."""
|
|
|
|
def __init__(self, session_factory, model, *, unit_model, stratum_model, value_model):
|
|
super().__init__(session_factory, model)
|
|
self.unit_model, self.stratum_model, self.value_model = unit_model, stratum_model, value_model
|
|
|
|
def counts(self, report_id: int) -> dict[tuple[str, str, str, str | None], int]:
|
|
"""A stored answer's units counted from its rows: `{(stratum, value, resultado_id, valor_id): units}`, the
|
|
total as `("total", "total", …)`. No view is needed to read what was answered."""
|
|
u, e = self.unit_model, self.stratum_model
|
|
units = func.count(distinct(u.unidad_id))
|
|
with self._session_factory() as session:
|
|
total = session.execute(select(u.resultado_id, u.valor_id, units).where(u.report_id == report_id)
|
|
.group_by(u.resultado_id, u.valor_id)).all()
|
|
by_stratum = session.execute(
|
|
select(e.estrato_id, e.estrato_valor, u.resultado_id, u.valor_id, units)
|
|
.join(e, (e.report_id == u.report_id) & (e.unidad_id == u.unidad_id))
|
|
.where(u.report_id == report_id)
|
|
.group_by(e.estrato_id, e.estrato_valor, u.resultado_id, u.valor_id)).all()
|
|
return {**{("total", "total", r, v): n for r, v, n in total},
|
|
**{(s, sv, r, v): n for s, sv, r, v, n in by_stratum}}
|
|
|
|
def group_counts(self, report_id: int) -> dict[tuple[str, str], int]:
|
|
"""A stored answer's units per group and population: `{(grupo, resultado_id): units}`. For a measure with
|
|
several groups, whose units repeat in each one."""
|
|
u = self.unit_model
|
|
with self._session_factory() as session:
|
|
rows = session.execute(select(u.grupo, u.resultado_id, func.count(distinct(u.unidad_id)))
|
|
.where(u.report_id == report_id).group_by(u.grupo, u.resultado_id)).all()
|
|
return {(g, r): n for g, r, n in rows}
|
|
|
|
def find(self, measure_url: str, key_sha: str) -> int | None:
|
|
"""The report already answering this key, if it was asked before."""
|
|
report = self.model
|
|
with self._session_factory() as session:
|
|
return session.execute(
|
|
select(report.report_id)
|
|
.where(report.measure_url == measure_url, report.parametros_sha == key_sha)
|
|
.order_by(report.report_id)
|
|
.limit(1)
|
|
).scalar()
|
|
|
|
def record(self, report: SQLModel, rows: Callable[[int], Iterable[tuple[type[SQLModel], Select]]]) -> int:
|
|
"""Saves the report and, in the same transaction, what each `(model, select)` of `rows(report_id)` gives.
|
|
|
|
Each select names its columns as the model's table does. All or nothing. Returns the `report_id`.
|
|
"""
|
|
with self._session_factory() as session:
|
|
try:
|
|
session.add(report)
|
|
session.flush()
|
|
report_id = report.report_id
|
|
for model, query in rows(report_id):
|
|
table = model.__table__
|
|
if model is self.stratum_model:
|
|
session.execute(self._new_values(query))
|
|
session.execute(insert(table).from_select([table.c[c.name] for c in query.selected_columns], query))
|
|
session.commit()
|
|
except Exception:
|
|
session.rollback()
|
|
raise
|
|
return report_id
|
|
|
|
def _new_values(self, strata: Select):
|
|
"""`INSERT … SELECT` of the stratum values `strata` gives that `cat_estrato_valor` doesn't have yet."""
|
|
catalog, given = self.value_model.__table__, strata.subquery()
|
|
new = (select(given.c.estrato_id, given.c.estrato_valor, given.c.estrato_valor, literal(0))
|
|
.where(~exists().where(and_(catalog.c.estrato_id == given.c.estrato_id,
|
|
catalog.c.valor_id == given.c.estrato_valor)))
|
|
.distinct())
|
|
return insert(catalog).from_select(["estrato_id", "valor_id", "etiqueta", "orden"], new)
|