Parse pasted server addresses and carry SQL columns as document fields

This commit is contained in:
Roberto Treviño Cervantes
2026-11-12 01:13:34 -06:00
parent edd12df144
commit 59fe94ad97
4 changed files with 309 additions and 15 deletions
+112
View File
@@ -57,6 +57,118 @@ def _sql_payload(url: str, **overrides) -> dict:
return {"connection_string": url, "table": "estudios", "column": "reporte", "key_column": "estudio_id", **overrides}
@pytest.fixture
def sqlite_archivos_uni_table(tmp_path):
"""Shaped exactly like the hospital's own `ArchivosUni` table (`Id`,
`PacienteId`, `OrdenServicioId`, `Archivo`): no column prints a
recognizable "Expediente" label anywhere, and two rows (the same
order's cover page and its result) share one `PacienteId`, the way the
source's own export does. Proves a table with no text-parseable key at
all can still be read correctly through `sql.fields`."""
db_path = tmp_path / "archivos_uni.db"
url = f"sqlite:///{db_path}"
engine = create_engine(url)
with engine.begin() as conn:
conn.execute(text("CREATE TABLE ArchivosUni (Id INTEGER, PacienteId INTEGER, OrdenServicioId INTEGER, Archivo BLOB)"))
rows = [
(1, 115220, 297914, "VPH alto riesgo: POSITIVO"),
(2, 115220, 297914, "Genotipo 18: DETECTADO"),
(3, 209622, 298182, "VPH alto riesgo: NEGATIVO"),
]
for id_, paciente_id, orden_id, archivo in rows:
conn.execute(
text("INSERT INTO ArchivosUni (Id, PacienteId, OrdenServicioId, Archivo) VALUES (:id, :pid, :oid, :archivo)"),
{"id": id_, "pid": paciente_id, "oid": orden_id, "archivo": archivo},
)
return url
def _archivos_uni_payload(url: str, **overrides) -> dict:
return {
"connection_string": url,
"table": "ArchivosUni",
"column": "Archivo",
"key_column": "Id",
"fields": {"pac_id_hospital": "PacienteId"},
**overrides,
}
def test_rows_with_no_text_label_are_keyed_from_a_structured_column(client, sqlite_archivos_uni_table):
"""Neither row prints "Expediente" anywhere; `sql.fields` is the only
way these rows can be keyed at all. Fails if `fields` stops reaching
the key computation through `DocumentConnector.source_fields`."""
body = client.post(
"/imports/sources/document/extract",
json={"sql": _archivos_uni_payload(sqlite_archivos_uni_table), "target": "cacu.CitologiaCervical"},
).get_json()
by_key = {r["key"]: r for r in body["records"]}
assert set(by_key) == {"115220", "209622"}
assert by_key["115220"]["fields"]["cit_vph_resultado"]["value"] == "POSITIVO"
def test_rows_sharing_a_patient_id_merge_into_one_record(client, sqlite_archivos_uni_table):
"""Rows 1 and 2 are two blob parts of the same order (same
`PacienteId` and `OrdenServicioId`, the way the hospital stores a
split report) and must land on a single record, not two. Fails if
`fields` stops being enough to merge documents that share no text in
common at all."""
body = client.post(
"/imports/sources/document/extract",
json={"sql": _archivos_uni_payload(sqlite_archivos_uni_table), "target": "cacu.CitologiaCervical"},
).get_json()
[record] = [r for r in body["records"] if r["key"] == "115220"]
assert record["fields"]["pac_id_hospital"]["value"] == "115220"
assert record["fields"]["cit_vph_resultado"]["value"] == "POSITIVO"
assert record["fields"]["cit_vph_genotipo_18"]["value"] == 1
assert {s["document"] for s in record["sources"]} == {"1", "2"}
def test_sql_fields_value_wins_over_a_conflicting_text_label(client, sqlite_archivos_uni_table):
"""If a row's own text happens to print a different "Expediente" than
its `PacienteId`, the structured column must still be trusted — it is
the hospital's real join key. Fails if a text-derived reading is ever
allowed to outrank `sql.fields`."""
engine = create_engine(sqlite_archivos_uni_table)
with engine.begin() as conn:
conn.execute(
text("INSERT INTO ArchivosUni (Id, PacienteId, OrdenServicioId, Archivo) VALUES (4, 300000, 400000, :archivo)"),
{"archivo": "Expediente: WRONG-LABEL\nVPH alto riesgo: NEGATIVO"},
)
body = client.post(
"/imports/sources/document/extract",
json={"sql": _archivos_uni_payload(sqlite_archivos_uni_table), "target": "cacu.CitologiaCervical"},
).get_json()
[record] = [r for r in body["records"] if r["key"] == "300000"]
assert record["fields"]["pac_id_hospital"]["value"] == "300000"
def test_an_unknown_sql_field_is_a_bad_request(client, sqlite_archivos_uni_table):
payload = _archivos_uni_payload(sqlite_archivos_uni_table, fields={"campo_inexistente": "PacienteId"})
response = client.post(
"/imports/sources/document/extract", json={"sql": payload, "target": "cacu.CitologiaCervical"}
)
assert response.status_code == 400 and "campo_inexistente" in response.get_json()["error"]
def test_sql_fields_source_commits_like_a_text_derived_key(client, sqlite_archivos_uni_table):
source = {
"source_type": "document",
"target": "cacu.CitologiaCervical",
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "cit_vph_resultado": "cit_vph_resultado"},
"payload": {"sql": _archivos_uni_payload(sqlite_archivos_uni_table)},
"label": "archivos_uni",
}
result = client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0]
assert result["created"] == 2, result
from persistance.cacu import citologia_cervical_repository
rows = {r.pac_id_hospital: r for r in citologia_cervical_repository.list(limit=100) if r.pac_id_hospital in ("115220", "209622")}
assert rows["115220"].cit_vph_resultado == "POSITIVO"
assert rows["209622"].cit_vph_resultado == "NEGATIVO"
def test_a_pdf_column_is_read_like_an_uploaded_pdf(client, sqlite_studies_table):
body = client.post(
"/imports/sources/document/extract",
+86
View File
@@ -9,6 +9,7 @@ import sqlalchemy as sa
from sqlalchemy.dialects import mssql
from extraction.testing import edf_file, scanned_pdf, text_pdf
from webapi.imports.connectors.errors import ConnectorError
@pytest.fixture(scope="module")
@@ -61,6 +62,91 @@ def test_sql_server_url_is_built_from_form_fields():
assert url.password == "p@ss:/w"
@pytest.mark.parametrize(
"raw,expected",
[
# bare host, nothing to pull apart
("10.56.0.45", ("10.56.0.45", None, None)),
(" 10.56.0.45 ", ("10.56.0.45", None, None)),
# SQL Server named instance, as the hospital's IT contact pasted it
("10.56.0.45\\SQLMAIN", ("10.56.0.45", "SQLMAIN", None)),
# the SSMS "Connect to Database Engine" convention: comma before the port
("10.56.0.45,1433", ("10.56.0.45", None, 1433)),
("10.56.0.45\\SQLMAIN,1433", ("10.56.0.45", "SQLMAIN", 1433)),
# a colon is also tolerated, as long as it isn't an IPv6 literal
("10.56.0.45:1433", ("10.56.0.45", None, 1433)),
# a copied connection string: scheme prefix and a trailing database/property list
("jdbc:sqlserver://10.56.0.45\\SQLMAIN;databaseName=Pruebas", ("10.56.0.45", "SQLMAIN", None)),
("tcp:10.56.0.45,1433", ("10.56.0.45", None, 1433)),
("postgresql://10.56.0.45:5432/Pruebas", ("10.56.0.45", None, 5432)),
# an IPv6 literal has more than one colon: left alone rather than mis-split
("fe80::1", ("fe80::1", None, None)),
],
)
def test_parse_server_address_tolerates_pasted_formats(raw, expected):
"""Pins the address parser against every way Erick (the hospital's IT
contact) is known to paste a server address — plain host, a SQL Server
named instance, the SSMS `host,port` convention and a copied JDBC/URI
string — plus an IPv6 literal that must NOT be mistaken for a
`host:port` pair. Fails if a future change stops stripping one of these
shapes, or starts mangling an IPv6 address."""
from webapi.imports.connectors.sql import _parse_server_address
assert _parse_server_address(raw) == expected
def test_sql_server_named_instance_leaves_port_unset_for_browser_resolution():
"""A named instance with no port given anywhere must reach pymssql as
`host\\instance` with no port appended, so FreeTDS can resolve the
instance's real port through SQL Server Browser (UDP 1434) instead of
being forced onto the wrong default port. Fails if `server_url` goes
back to always filling in `engine.default_port`."""
from webapi.imports.connectors.sql import SqlConnector
url = SqlConnector.server_url({"engine": "mssql", "host": "10.56.0.45\\SQLMAIN", "database": "Pruebas", "user": "enlace", "password": "Enlace"})
assert url.host == "10.56.0.45\\SQLMAIN"
assert url.port is None
def test_sql_server_named_instance_with_explicit_port_is_appended_after_the_backslash():
"""When the instance's real static port IS known (typed in Puerto, or
pasted as `host\\instance,port`), it must still reach the driver
attached to the instance name, not silently dropped. Fails if the
explicit-port path stops composing `host\\instance` before handing off
to SQLAlchemy."""
from webapi.imports.connectors.sql import SqlConnector
url = SqlConnector.server_url(
{"engine": "mssql", "host": "10.56.0.45\\SQLMAIN", "port": "52001", "database": "Pruebas", "user": "enlace", "password": "Enlace"}
)
assert url.host == "10.56.0.45\\SQLMAIN"
assert url.port == 52001
def test_mysql_tolerates_an_embedded_port_with_no_explicit_port_field():
"""Any engine, not just SQL Server, benefits from the same parser: a
host pasted as `host:port` must still work when the Puerto field is
left blank. Fails if the fix regresses to engine-specific handling that
only covers mssql."""
from webapi.imports.connectors.sql import SqlConnector
url = SqlConnector.server_url({"engine": "mysql", "host": "10.56.0.45:3307", "database": "hospital_legacy"})
assert url.host == "10.56.0.45"
assert url.port == 3307
def test_mysql_rejects_a_named_instance_it_cannot_speak():
"""MySQL/MariaDB/PostgreSQL have no concept of a named instance; a
backslash in the host for one of them is a mistake (e.g. the address
was meant for a different engine), and must be reported rather than
sent on as a garbled hostname. Fails if `server_url` stops validating
`supports_instance_name` per engine."""
from webapi.imports.connectors.sql import SqlConnector
with pytest.raises(ConnectorError, match="instancia"):
SqlConnector.server_url({"engine": "mysql", "host": "10.56.0.45\\SQLMAIN", "database": "hospital_legacy"})
def test_sql_server_preview_compiles_to_top(monkeypatch):
from webapi.imports.connectors.sql import _text_subquery
+45 -12
View File
@@ -49,12 +49,18 @@ class _ResultCache:
_CACHE = _ResultCache()
def _files_from_sql(sql: dict[str, Any]) -> list[tuple[str, bytes]]:
def _files_from_sql(sql: dict[str, Any]) -> tuple[list[tuple[str, bytes]], dict[str, dict[str, Any]]]:
"""One `(name, bytes)` per row of a SQL source (connected the same way
`SqlConnector` is): `column` is the field bundle (a `varbinary(max)`
PDF, or already a plain string — `read_document` reads either), and
`key_column` names the row (a patient or study id) for tracing. Any
column type `SqlConnector` can read works; it's not limited to PDFs."""
PDF, or already a plain string — `read_document` reads either),
`key_column` names the row (a patient or study id) for tracing, and the
optional `fields` (`{target_field: sql_column}`) carries other columns
through as that row's authoritative values — a source's own patient or
study id, trusted over whatever the document's text happens to say.
Any column type `SqlConnector` can read works; it's not limited to PDFs.
Returns the files alongside, per row name, the `fields` values read for
it (`DocumentExtractor.extract`'s `source_fields`)."""
column = sql.get("column")
if not column:
raise ConnectorError("falta column")
@@ -63,18 +69,29 @@ def _files_from_sql(sql: dict[str, Any]) -> list[tuple[str, bytes]]:
key_column = sql.get("key_column") or column
if key_column == column:
raise ConnectorError("key_column debe ser distinta de column")
fields: dict[str, str] = sql.get("fields") or {}
mapping = {column: "contenido", key_column: "clave"}
for field_name, sql_column in fields.items():
if sql_column in mapping:
raise ConnectorError(f"la columna {sql_column!r} ya está asignada a otro papel en fields/column/key_column")
mapping[sql_column] = field_name
connector = SqlConnector.connect(sql)
connector = (
connector.select_query(sql["query"]) if sql.get("query") else connector.select_table(sql["table"], schema=sql.get("schema"))
)
files = []
for row in connector.read_rows({column: "contenido", key_column: "clave"}):
source_fields: dict[str, dict[str, Any]] = {}
for row in connector.read_rows(mapping):
raw = row.get("contenido")
if raw is None:
continue
name = str(row.get("clave", len(files) + 1))
files.append((name, raw if isinstance(raw, bytes) else str(raw).encode("utf-8")))
return files
if fields:
source_fields[name] = {field_name: row.get(field_name) for field_name in fields if row.get(field_name) is not None}
return files, source_fields
@register_connector
@@ -93,8 +110,14 @@ class DocumentConnector(DataFrameConnector):
Each row also carries the record's pages as a PDF (`documento`),
mappable to the entity's file column, when the source produced one.
Corrections made while reviewing travel in `overrides`
(`{"<row>": {"field": value}}`) and win over the extracted value.
A SQL source's `sql.fields` (`{target_field: sql_column}`) carries other
columns of the same row straight through as that row's values for those
fields, overriding whatever the document's own text parses to — a
source's own patient or study id is a structured join key, not a guess,
so it wins even over a page that prints nothing recognizable, or
prints something else entirely. Corrections made while reviewing
travel in `overrides` (`{"<row>": {"field": value}}`) and win over
both.
"""
kind = "document"
@@ -114,6 +137,7 @@ class DocumentConnector(DataFrameConnector):
ocr_mode: str = "auto",
key_pattern: str | None = None,
overrides: dict[str, dict[str, Any]] | None = None,
source_fields: dict[str, dict[str, Any]] | None = None,
):
if not files:
raise ConnectorError("no se recibieron documentos")
@@ -133,16 +157,22 @@ class DocumentConnector(DataFrameConnector):
self.ocr_mode = ocr_mode
self.key_pattern = key_pattern
self.overrides = {str(k): v for k, v in (overrides or {}).items()}
self.source_fields = {str(k): v for k, v in (source_fields or {}).items()}
known = {spec.name for spec in self.specs}
unknown = sorted({name for values in self.source_fields.values() for name in values} - known)
if unknown:
raise ConnectorError(f"fields desconocidos para {target}: {', '.join(unknown)}")
self._df: pd.DataFrame | None = None
@classmethod
def from_payload(cls, payload: dict[str, Any]) -> "DocumentConnector":
if payload.get("sql"):
files = _files_from_sql(payload["sql"])
files, source_fields = _files_from_sql(payload["sql"])
else:
files = [
(f.get("name") or f"documento_{i}", decode_file(f)) for i, f in enumerate(payload.get("files") or [], 1)
]
source_fields = {}
return cls(
files,
target=payload["target"],
@@ -151,6 +181,7 @@ class DocumentConnector(DataFrameConnector):
ocr_mode=payload.get("ocr_mode", "auto"),
key_pattern=payload.get("key_pattern") or None,
overrides=payload.get("overrides"),
source_fields=source_fields,
)
@classmethod
@@ -174,15 +205,17 @@ class DocumentConnector(DataFrameConnector):
key=next((s for s in self.specs if s.name == self.key_field), None),
pages_per_record=self.pages_per_record,
)
return DocumentExtractor(self.specs, key_field=self.key_field, segmenter=segmenter).extract(documents)
return DocumentExtractor(self.specs, key_field=self.key_field, segmenter=segmenter).extract(
documents, source_fields=self.source_fields
)
def _cache_key(self) -> str:
digest = hashlib.sha256()
for name, raw in self.files:
digest.update(name.encode())
digest.update(hashlib.sha256(raw).digest())
config = [self.target, self.segmentation, self.pages_per_record, self.ocr_mode, self.key_pattern]
digest.update(json.dumps(config).encode())
config = [self.target, self.segmentation, self.pages_per_record, self.ocr_mode, self.key_pattern, self.source_fields]
digest.update(json.dumps(config, sort_keys=True, default=str).encode())
return digest.hexdigest()
# -- rows -----------------------------------------------------------------
+66 -3
View File
@@ -1,5 +1,6 @@
import datetime as _dt
import importlib.util
import re
from contextlib import contextmanager
from dataclasses import dataclass
from typing import Any, ClassVar, Iterator
@@ -27,6 +28,7 @@ class SqlEngine:
driver_module: str
description: str = ""
default_schema: str | None = None
supports_instance_name: bool = False
@property
def available(self) -> bool:
@@ -67,7 +69,10 @@ class SqlConnector(Connector):
SqlEngine("mysql", "MySQL", "mysql+pymysql", 3306, "pymysql", "Servidor MySQL 5.7+ / 8"),
SqlEngine("mariadb", "MariaDB", "mariadb+pymysql", 3306, "pymysql", "Servidor MariaDB"),
SqlEngine("postgresql", "PostgreSQL", "postgresql+psycopg2", 5432, "psycopg2", "Servidor PostgreSQL", "public"),
SqlEngine("mssql", "SQL Server", "mssql+pymssql", 1433, "pymssql", "Microsoft SQL Server 2017+ / Azure SQL", "dbo"),
SqlEngine(
"mssql", "SQL Server", "mssql+pymssql", 1433, "pymssql",
"Microsoft SQL Server 2017+ / Azure SQL", "dbo", supports_instance_name=True,
),
)
}
@@ -102,15 +107,27 @@ class SqlConnector(Connector):
raise ConnectorError(f"el controlador de {engine.label} ({engine.driver_module}) no está instalado en el servidor")
if not server.get("host") or not server.get("database"):
raise ConnectorError("se requieren el servidor (host) y la base de datos")
host, instance, embedded_port = _parse_server_address(str(server["host"]))
if instance and not engine.supports_instance_name:
raise ConnectorError(f"{engine.label} no admite una instancia con nombre ({server['host']!r}); indique solo el host y, si aplica, el puerto")
explicit_port = server.get("port")
try:
port = int(server.get("port") or engine.default_port)
port = int(explicit_port) if explicit_port not in (None, "") else embedded_port
except (TypeError, ValueError) as exc:
raise ConnectorError("el puerto debe ser un número") from exc
if instance:
host = f"{host}\\{instance}"
elif port is None:
port = engine.default_port
return sa.engine.URL.create(
engine.drivername,
username=server.get("user") or None,
password=server.get("password") or None,
host=server["host"],
host=host,
port=port,
database=server["database"],
)
@@ -235,6 +252,52 @@ class SqlConnector(Connector):
conn.rollback()
_ADDRESS_SCHEME_RE = re.compile(r"^[a-zA-Z][a-zA-Z0-9+.\-:]*?://")
_ADDRESS_PORT_SEPARATORS = (",", ":")
def _parse_server_address(raw: str) -> tuple[str, str | None, int | None]:
"""Tolerates the ways a server address arrives typed or pasted from
SSMS, a JDBC string or a connection URI instead of a bare host: a
leading scheme (`jdbc:sqlserver://`, `postgresql://`, `tcp:`), a
trailing path/query/property list, surrounding whitespace, a SQL
Server named instance (`host\\instance`), and a port given as
`host:port` or the SSMS convention `host,port` / `host\\instance,port`.
Returns `(host, instance, port)`, with `instance` and `port` `None`
when absent, so the caller can leave the port unset for a named
instance instead of forcing the engine's default one.
"""
address = _ADDRESS_SCHEME_RE.sub("", raw.strip(), count=1)
if address.lower().startswith("tcp:"):
address = address[len("tcp:") :]
for cut in ("/", "?", ";"):
address = address.split(cut, 1)[0]
address = address.strip()
instance: str | None = None
if "\\" in address:
host, instance = (part.strip() for part in address.split("\\", 1))
else:
host = address
tail = instance or host
port: int | None = None
for sep in _ADDRESS_PORT_SEPARATORS:
if tail.count(sep) == 1:
prefix, suffix = (part.strip() for part in tail.split(sep))
if suffix.isdigit():
tail, port = prefix, int(suffix)
break
if instance:
instance = tail or None
else:
host = tail
return host, (instance or None), port
def _text_subquery(query: str) -> sa.Subquery:
"""Wraps policy-checked SELECT text as a derived table, so SQLAlchemy
composes LIMIT/TOP and COUNT(*) for whichever dialect the source speaks."""