import datetime as _dt import importlib.util import re from contextlib import contextmanager from dataclasses import dataclass from typing import Any, ClassVar, Iterator import pandas as pd import sqlalchemy as sa import sqlglot from sqlalchemy.pool import NullPool from webapi.imports.connectors.base import Connector, PreviewResult, SourceColumn from webapi.imports.connectors.errors import ConnectorError from webapi.imports.connectors.registry import register_connector from webapi.imports.connectors.sql_policy import SQLGLOT_DIALECTS, SqlSourcePolicy from webapi.imports.connectors.tabular import infer_type @dataclass(frozen=True) class SqlEngine: """A database server the connection form offers. Supporting another server is one entry in `SqlConnector.ENGINES` plus its driver package.""" id: str label: str drivername: str default_port: int driver_module: str description: str = "" default_schema: str | None = None supports_instance_name: bool = False @property def available(self) -> bool: return importlib.util.find_spec(self.driver_module) is not None def describe(self) -> dict[str, Any]: return { "id": self.id, "label": self.label, "description": self.description, "default_port": self.default_port, "default_schema": self.default_schema, "available": self.available, } @register_connector class SqlConnector(Connector): """Reads a table or a SELECT from a client's database server. Browsing (`list_schemas`/`list_tables`/`list_columns`) lives here only; the import pipeline uses the `Connector` methods once `select_table` or `select_query` has been called. Rows come straight from SQLAlchemy, so they keep the driver's types, previews fetch only `limit` rows and `read_rows` streams. Connections are read-only (see `_reading`) and unpooled, since every request builds its own connector. """ kind = "sql" label = "Base de datos" description = "Tabla o consulta de un servidor SQL" category = "database" icon = "storage" ENGINES: ClassVar[dict[str, SqlEngine]] = { engine.id: engine for engine in ( 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", supports_instance_name=True, ), ) } @classmethod def describe(cls) -> dict[str, Any]: return {**super().describe(), "engines": [engine.describe() for engine in cls.ENGINES.values()]} @classmethod def from_payload(cls, payload: dict[str, Any]) -> "SqlConnector": connector = cls.connect(payload) if payload.get("query"): return connector.select_query(payload["query"]) return connector.select_table(payload["table"], schema=payload.get("schema")) @classmethod def connect(cls, payload: dict[str, Any]) -> "SqlConnector": """A connector without a table selected yet, for browsing. Takes either `server` (engine, host, port, database, user, password) or a raw SQLAlchemy `connection_string`.""" if payload.get("server"): return cls(cls.server_url(payload["server"])) if payload.get("connection_string"): return cls(payload["connection_string"]) raise ConnectorError("falta server o connection_string") @classmethod def server_url(cls, server: dict[str, Any]) -> sa.engine.URL: engine = cls.ENGINES.get(server.get("engine", "")) if engine is None: raise ConnectorError(f"motor desconocido {server.get('engine')!r} (disponibles: {', '.join(cls.ENGINES)})") if not engine.available: 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(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=host, port=port, database=server["database"], ) def __init__(self, connection: str | sa.engine.URL, *, policy: SqlSourcePolicy | None = None): self._policy = policy or SqlSourcePolicy.from_env() url = self._policy.check_url(connection) try: self._engine = sa.create_engine(url, poolclass=NullPool) except Exception as exc: raise ConnectorError(f"cadena de conexión inválida: {exc}") from exc self._table: sa.Table | None = None self._query: str | None = None # -- browsing --------------------------------------------------------- def test_connection(self) -> None: try: with self._reading() as conn: conn.execute(sa.text("SELECT 1")) except ConnectorError: raise except Exception as exc: raise ConnectorError(f"no se pudo conectar: {exc}") from exc def get_dialect(self) -> str: return self._engine.dialect.name def list_schemas(self) -> list[str]: try: return sa.inspect(self._engine).get_schema_names() except Exception as exc: raise ConnectorError(f"no se pudieron listar los esquemas: {exc}") from exc def list_tables(self, *, schema: str | None = None) -> list[str]: try: inspector = sa.inspect(self._engine) return inspector.get_table_names(schema=schema) + inspector.get_view_names(schema=schema) except Exception as exc: raise ConnectorError(f"no se pudieron listar las tablas: {exc}") from exc def list_columns(self, table_name: str, *, schema: str | None = None) -> list[SourceColumn]: try: columns = sa.inspect(self._engine).get_columns(table_name, schema=schema) except Exception as exc: raise ConnectorError(f"no se pudieron listar las columnas: {exc}") from exc return [SourceColumn(name=c["name"], inferred_type=_sa_type_to_kind(c["type"])) for c in columns] def select_table(self, table_name: str, *, schema: str | None = None) -> "SqlConnector": try: self._table = sa.Table(table_name, sa.MetaData(), schema=schema, autoload_with=self._engine) except Exception as exc: raise ConnectorError(f"no se pudo abrir la tabla {table_name!r}: {exc}") from exc self._query = None return self def select_query(self, query: str) -> "SqlConnector": self._query, self._table = self._policy.check_query(query, dialect=self.get_dialect()), None return self # -- Connector ---------------------------------------------------------- def preview(self, *, limit: int = 20) -> PreviewResult: statement = self._selectable() try: with self._reading() as conn: result = conn.execute(sa.select(statement).limit(limit)) names = list(result.keys()) rows = [dict(row) for row in result.mappings()] total = conn.execute(sa.select(sa.func.count()).select_from(statement)).scalar_one() except ConnectorError: raise except Exception as exc: raise ConnectorError(f"no se pudieron leer las filas: {exc}") from exc return PreviewResult(columns=self._columns(names, rows), sample_rows=rows, total_rows=total) def read_rows(self, column_mapping: dict[str, str]) -> Iterator[dict[str, Any]]: statement = sa.select(self._selectable()) try: with self._reading() as conn: result = conn.execution_options(stream_results=True, yield_per=1000).execute(statement) for row in result.mappings(): yield {target: row.get(source) for source, target in column_mapping.items()} except ConnectorError: raise except Exception as exc: raise ConnectorError(f"no se pudieron leer las filas: {exc}") from exc # -- internals ---------------------------------------------------------- def _selectable(self) -> sa.Subquery: if self._table is not None: return sa.select(self._table).subquery("source") if self._query: return _text_subquery(self._query, self.get_dialect()) raise ConnectorError("no hay tabla ni consulta seleccionada") def _columns(self, names: list[str], rows: list[dict[str, Any]]) -> list[SourceColumn]: if self._table is not None: by_name = {c.name: c for c in self._table.columns} return [SourceColumn(n, _sa_type_to_kind(by_name[n].type) if n in by_name else "string") for n in names] return [SourceColumn(n, infer_type(pd.Series([r.get(n) for r in rows], dtype=object))) for n in names] @contextmanager def _reading(self): """A connection that can't write: read-only mode where the dialect has one, and an unconditional rollback, so not even a SELECT calling a side-effecting function can commit anything. SQL Server has no read-only session mode; the rollback and `SqlSourcePolicy`'s single-SELECT rule cover it.""" with self._engine.connect() as conn: dialect = conn.dialect.name if dialect in ("mysql", "mariadb"): conn.exec_driver_sql("SET SESSION TRANSACTION READ ONLY") elif dialect == "postgresql": conn.exec_driver_sql("SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY") elif dialect == "sqlite": conn.exec_driver_sql("PRAGMA query_only = ON") try: yield conn finally: 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 a SQL client, 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 SQL Server's `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, dialect: str | None = None) -> sa.Subquery: """Wraps policy-checked SELECT text as a derived table, so SQLAlchemy composes LIMIT/TOP and COUNT(*) for whichever dialect the source speaks.""" query = _without_trailing_order_by(query, dialect) return sa.select(sa.literal_column("*")).select_from(sa.text(f"({query}) AS source_query")).subquery("source") _ORDER_BY = re.compile(r"\bORDER\s+BY\b", re.I) def _without_trailing_order_by(query: str, dialect: str | None) -> str: """Drops a top-level `ORDER BY` that nothing limits: SQL Server refuses one inside a derived table, and row order means nothing to an import. Kept when TOP, LIMIT or OFFSET makes it choose the rows.""" try: [root] = sqlglot.parse(query, read=SQLGLOT_DIALECTS.get(dialect, dialect)) except Exception: return query if root is None or not root.args.get("order") or root.args.get("limit") or root.args.get("offset"): return query depth, quote, cut = 0, None, None for position, char in enumerate(query): if quote: quote = None if char == quote else quote elif char in "'\"[`": quote = "]" if char == "[" else char elif char == "(": depth += 1 elif char == ")": depth -= 1 elif depth == 0 and _ORDER_BY.match(query, position): cut = position return query[:cut].rstrip() if cut is not None else query def _sa_type_to_kind(sa_type: sa.types.TypeEngine) -> str: try: python_type = sa_type.python_type except (NotImplementedError, AttributeError): return "string" if python_type is bool: return "boolean" if python_type is int: return "integer" if python_type is float: return "float" if python_type is _dt.datetime: return "datetime" if python_type is _dt.date: return "date" return "string"