reorganization
This commit is contained in:
@@ -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]:
|
||||
|
||||
Reference in New Issue
Block a user