import datetime as _dt import importlib.util from contextlib import contextmanager from dataclasses import dataclass from typing import Any, ClassVar, Iterator import pandas as pd import sqlalchemy as sa 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 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 @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"), ) } @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") try: port = int(server.get("port") or engine.default_port) except (TypeError, ValueError) as exc: raise ConnectorError("el puerto debe ser un número") from exc return sa.engine.URL.create( engine.drivername, username=server.get("user") or None, password=server.get("password") or None, host=server["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) 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() 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.""" return sa.select(sa.literal_column("*")).select_from(sa.text(f"({query}) AS source_query")).subquery("source") 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"