reorganization

This commit is contained in:
Roberto Treviño Cervantes
2026-10-31 12:47:59 -06:00
parent ae1ee4633f
commit fce6ccd40a
9 changed files with 185 additions and 23 deletions
+1 -1
View File
@@ -168,7 +168,7 @@ class SqlConnector(Connector):
return self
def select_query(self, query: str) -> "SqlConnector":
self._query, self._table = self._policy.check_query(query), None
self._query, self._table = self._policy.check_query(query, dialect=self.get_dialect()), None
return self
# -- Connector ----------------------------------------------------------
+30 -9
View File
@@ -10,9 +10,10 @@ to, so:
read-only connection, not instead of it).
"""
import os
import re
from dataclasses import dataclass
import sqlglot
from sqlglot import exp
from sqlalchemy.engine import URL, make_url
from sqlalchemy.exc import ArgumentError
@@ -20,7 +21,13 @@ from webapi.imports.connectors.errors import ConnectorError
_DEFAULT_DIALECTS = "mysql,mariadb,postgresql,mssql"
_DEFAULT_PORTS = {"mysql": 3306, "mariadb": 3306, "postgresql": 5432, "mssql": 1433}
_LEADING_COMMENTS = re.compile(r"^\s*((--[^\n]*\n)|(/\*.*?\*/)|\s)*", re.S)
# SQLAlchemy dialect name -> sqlglot's name for it, where they differ.
_SQLGLOT_DIALECTS = {"postgresql": "postgres", "mssql": "tsql", "mariadb": "mysql"}
# Anything that writes, wherever it sits in the tree: a top-level
# `SELECT ... INTO table`/`INTO OUTFILE`, or a writable CTE
# (`WITH t AS (DELETE FROM x RETURNING *) SELECT * FROM t` still parses as a
# top-level SELECT, so checking only the root node's type is not enough).
_WRITE_NODES = (exp.Into, exp.Insert, exp.Update, exp.Delete)
@dataclass(frozen=True)
@@ -54,15 +61,29 @@ class SqlSourcePolicy:
return url
@staticmethod
def check_query(query: str) -> str:
statement = query.strip().rstrip(";").strip()
if ";" in statement:
def check_query(query: str, *, dialect: str | None = None) -> str:
"""Parses the query with `sqlglot` (in the source's own SQL dialect,
when known) and inspects the resulting syntax tree, rather than
matching keywords on the raw text — a string check can't tell a
read-only `SELECT` from one hiding a write, e.g. MySQL's
`SELECT ... INTO OUTFILE` (writes a file to the server) or a
PostgreSQL CTE performing the write (`WITH t AS (DELETE FROM x
RETURNING *) SELECT * FROM t` is a syntactic SELECT at the top)."""
statement = query.strip()
if not statement:
raise ConnectorError("la consulta no puede estar vacía")
try:
parsed = [node for node in sqlglot.parse(statement, read=_SQLGLOT_DIALECTS.get(dialect, dialect)) if node is not None]
except sqlglot.errors.ParseError as exc:
raise ConnectorError(f"la consulta no es SQL válido: {exc}") from exc
if len(parsed) != 1:
raise ConnectorError("la consulta debe ser una sola instrucción")
body = _LEADING_COMMENTS.sub("", statement, count=1)
first_word = body.split(None, 1)[0].upper() if body else ""
if first_word not in ("SELECT", "WITH"):
root = parsed[0]
if not isinstance(root, (exp.Select, exp.Union, exp.Intersect, exp.Except)):
raise ConnectorError("la consulta debe ser un SELECT (o WITH ... SELECT)")
return statement
if root.find(*_WRITE_NODES) is not None:
raise ConnectorError("la consulta no puede escribir en el servidor de origen")
return statement.rstrip(";").strip()
def _own_database_urls() -> list[URL]:
+5 -4
View File
@@ -1,10 +1,11 @@
"""Auto-match suggestions for the column-mapping UI, based on stdlib `difflib`."""
"""Auto-match suggestions for the column-mapping UI, based on `rapidfuzz`."""
import difflib
import re
import unicodedata
from dataclasses import dataclass
from rapidfuzz import fuzz
# Keys are target fields; values are normalized source-column names (see
# `_normalize`: lowercase, no accents, spaces/dashes/dots -> "_").
SYNONYMS: dict[str, set[str]] = {
@@ -75,7 +76,7 @@ def _word_score(source_words: list[str], target_words: list[str]) -> float:
return 0.0
total = 0.0
for word in source_words:
best = max(difflib.SequenceMatcher(None, word, other).ratio() for other in target_words)
best = max(fuzz.ratio(word, other) / 100.0 for other in target_words)
if best >= _NEAR_WORD:
total += best
return total / max(len(source_words), len(target_words))
@@ -150,6 +151,6 @@ def _score_one(source: str, target: str) -> tuple[float, str] | None:
if words >= _WORD_FLOOR:
# 0.5..0.7 by word overlap, plus a tiny whole-string tiebreak so
# "fecha_reporte" prefers bx_fecha_reporte over another one-word overlap.
ratio = difflib.SequenceMatcher(None, normalized_source, unprefixed_target).ratio()
ratio = fuzz.ratio(normalized_source, unprefixed_target) / 100.0
return min(0.5 + (words - _WORD_FLOOR) * 0.36 + ratio * 0.02, _FUZZY_CAP), "fuzzy"
return None
+1 -1
View File
@@ -1,6 +1,6 @@
"""Los repositorios que recibe un paso (`ctx.repos`), agrupados por capa: bronce, plata y oro.
Las subclases viven en `persistance/aristas/<capa>/` (`arquitectura_grafo_etl.md` §6) y se
Las subclases viven en `persistance/aristas/<capa>/` y se
instancian en `persistance/<proyecto>/__init__.py` con la fábrica de sesión del
dominio. Aquí solo se juntan: la orquestación no nombra ninguna conexión.
"""
+1 -1
View File
@@ -5,7 +5,7 @@
Es dato por paciente: **solo se registra en DEV** (con `DEV_REVISION`, que define el despliegue de
`deploy/dev`) y con datos simulados; toda respuesta lleva `simulado: true`. Fuera de DEV la ruta no
existe (404). La lista la arma el kit (`indicadores_kit.serving.seguimiento`); aquí solo se valida,
se abre la sesión y se traducen los errores. El contrato: `_docs/contratos/cacu_seguimiento_y_estratos.md` §2.
se abre la sesión y se traducen los errores.
"""
import json