Parse pasted server addresses and carry SQL columns as document fields
This commit is contained in:
@@ -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."""
|
||||
|
||||
Reference in New Issue
Block a user