Files
WebApi/webapi/imports/services/link_resolver.py
T

89 lines
3.6 KiB
Python

"""Fills a child row's foreign keys from the natural keys it carries, as
Core's column descriptions specify (e.g. `NotaMedica.pac_id` is looked up by
`pac_id_hospital`). This links rows that came from unrelated sources in the
same batch.
Links are derived from Core's columns: an entity with both `pac_id` and
`pac_id_hospital` links to its domain's `Paciente`, and one with both
`ord_id` and `ord_numero_hospital` links to its `OrdenesEstudio`. TEA's child
tables carry the source's patient id itself (`*_pac_id`), so it needs none.
"""
from dataclasses import dataclass
from functools import cache
from typing import Any
from sqlmodel import Session, select
from webapi.imports.schemas.registry import ENTITY_REGISTRY
@dataclass(frozen=True)
class ForeignKeyLink:
fk_field: str # on the child, e.g. "pac_id"
via_field: str # natural key on the child, e.g. "pac_id_hospital"
parent: str # registry key, e.g. "cacu.Paciente"
parent_key: str # natural key on the parent
parent_pk: str # primary key on the parent
# (fk column, natural-key column, parent entity name, parent primary key)
_CONVENTIONS = (
("pac_id", "pac_id_hospital", "Paciente", "pac_id"),
("ord_id", "ord_numero_hospital", "OrdenesEstudio", "ord_id"),
)
@cache
def links_for(target_key: str) -> tuple[ForeignKeyLink, ...]:
domain, _, name = target_key.partition(".")
columns = set(ENTITY_REGISTRY[target_key].model.__table__.columns.keys())
links = []
for fk_field, via_field, parent_name, parent_pk in _CONVENTIONS:
parent = f"{domain}.{parent_name}"
if name != parent_name and parent in ENTITY_REGISTRY and {fk_field, via_field} <= columns:
links.append(ForeignKeyLink(fk_field, via_field, parent, via_field, parent_pk))
return tuple(links)
@cache
def dependency_rank(target_key: str) -> int:
"""Write order within a batch: parents rank lower than their children, so
a child's lookup finds a parent written earlier in the same batch."""
return max((dependency_rank(link.parent) + 1 for link in links_for(target_key)), default=0)
class LinkResolver:
"""Looks up parent primary keys by natural key within the batch's session,
so parents written earlier in the same uncommitted transaction are found.
The natural key wins over an id the source sent: a hospital table carries
the hospital's internal ids, which only match ours when the parent was
loaded with its own id. An id is kept as sent only when there is no
natural key or its parent isn't loaded; a missing parent leaves the FK
null, which Core allows."""
def __init__(self, session: Session):
self._session = session
self._cache: dict[tuple[str, Any], Any] = {}
def resolve(self, target_key: str, row: dict[str, Any]) -> list[str]:
linked = []
for link in links_for(target_key):
value = row.get(link.via_field)
if value is None:
continue
pk = self._lookup(link, value)
if pk is not None:
if row.get(link.fk_field) != pk:
linked.append(link.fk_field)
row[link.fk_field] = pk
return linked
def _lookup(self, link: ForeignKeyLink, value: Any) -> Any:
cache_key = (link.parent, value)
if cache_key not in self._cache:
parent = ENTITY_REGISTRY[link.parent].model
statement = select(getattr(parent, link.parent_pk)).where(getattr(parent, link.parent_key) == value)
self._cache[cache_key] = self._session.exec(statement).first()
return self._cache[cache_key]