diff --git a/aws_advanced_python_wrapper/encryption/metadata_manager.py b/aws_advanced_python_wrapper/encryption/metadata_manager.py index 1b2934988..693b08520 100644 --- a/aws_advanced_python_wrapper/encryption/metadata_manager.py +++ b/aws_advanced_python_wrapper/encryption/metadata_manager.py @@ -42,6 +42,7 @@ class _Snapshot(NamedTuple): + # Keyed by SqlDialect.metadata_key of the names. columns: Mapping[Tuple[str, str], ColumnEncryptionConfig] by_table: Mapping[str, Tuple[ColumnEncryptionConfig, ...]] loaded_at: float # time.monotonic() @@ -60,6 +61,12 @@ class MetadataManager: refresh is on. Before :meth:`start`, after :meth:`close`, or with the cache disabled, each lookup queries the database. + Lookups compare names the way the engine does + (:meth:`SqlDialect.metadata_key`): exactly on PostgreSQL, where names are + stored as the catalog has them (``users`` for an unquoted ``Users``), and + case-insensitively on MySQL. That matches what the uncached query's + ``WHERE`` does, given the default (case-insensitive) MySQL collations. + Call :meth:`close` when done. The refresh thread holds the manager only weakly, so a manager dropped without ``close`` still stops its thread once it is garbage-collected. @@ -162,7 +169,7 @@ def column_config(self, table_name: Optional[str], column_name: Optional[str]) - return None snapshot = self._usable_snapshot(table_name, column_name) if snapshot is not None: - return snapshot.columns.get((table_name, column_name)) + return snapshot.columns.get((self._sql.metadata_key(table_name), self._sql.metadata_key(column_name))) rows = self._query( f"{self._joined_sql()} WHERE em.table_name {self._sql.equals} %s AND em.column_name {self._sql.equals} %s", (table_name, column_name), table_name=table_name, column_name=column_name) @@ -174,7 +181,7 @@ def table_configs(self, table_name: Optional[str]) -> Sequence[ColumnEncryptionC return () snapshot = self._usable_snapshot(table_name) if snapshot is not None: - return snapshot.by_table.get(table_name, ()) + return snapshot.by_table.get(self._sql.metadata_key(table_name), ()) rows = self._query(f"{self._joined_sql()} WHERE em.table_name {self._sql.equals} %s", (table_name,), table_name=table_name) return tuple(self._to_column_config(row) for row in rows) @@ -213,11 +220,12 @@ def _load_snapshot(self, *, table_name: Optional[str] = None, column_name: Optio # returned. loaded_at = time.monotonic() columns = self._load_all(table_name=table_name, column_name=column_name) + key = self._sql.metadata_key by_table: Dict[str, List[ColumnEncryptionConfig]] = {} for config in columns.values(): - by_table.setdefault(config.table_name, []).append(config) + by_table.setdefault(key(config.table_name), []).append(config) snapshot = _Snapshot( - MappingProxyType(dict(columns)), + MappingProxyType({(key(c.table_name), key(c.column_name)): c for c in columns.values()}), MappingProxyType({t: tuple(c) for t, c in by_table.items()}), loaded_at) with self._lifecycle_lock: @@ -269,8 +277,8 @@ def _joined_sql(self) -> str: def _to_column_config(row: Mapping[str, Any]) -> ColumnEncryptionConfig: key_metadata = None if row.get(f"{_KS_PREFIX}id") is None else KeyMetadata.from_row(row, _KS_PREFIX) return ColumnEncryptionConfig( - table_name=row["table_name"], - column_name=row["column_name"], + table_name=MetadataManager._name(row, "table_name"), + column_name=MetadataManager._name(row, "column_name"), algorithm=row.get("encryption_algorithm") or EncryptionAlgorithm.DEFAULT, key_id=None if row.get("key_id") is None else int(row["key_id"]), key_metadata=key_metadata, @@ -278,6 +286,22 @@ def _to_column_config(row: Mapping[str, Any]) -> ColumnEncryptionConfig: updated_at=row.get("updated_at"), ) + @staticmethod + def _name(row: Mapping[str, Any], field: str) -> str: + # A driver can return text as bytes (psycopg on a SQL_ASCII database, + # Connector/Python with use_unicode=False). Such a name would never + # match the str names parsed from SQL, so an encrypted column would + # look like an ordinary one: decode it, and refuse anything else. + value = row[field] + if isinstance(value, str): + return value + if isinstance(value, (bytes, bytearray, memoryview)): + try: + return bytes(value).decode("utf-8") + except UnicodeDecodeError: + pass + raise MetadataError(Messages.get_formatted("MetadataManager.InvalidName", field, type(value).__name__)) + @staticmethod def _finalize(stop: Event, thread_holder: List[Optional[Thread]]) -> None: # Runs when an unclosed manager is collected. The collection can happen diff --git a/aws_advanced_python_wrapper/encryption/sql_analyzer.py b/aws_advanced_python_wrapper/encryption/sql_analyzer.py new file mode 100644 index 000000000..e4efb1608 --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/sql_analyzer.py @@ -0,0 +1,1448 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Works out which bind parameter of a statement fills or is compared with +which column, so values bound for an encrypted column can be encrypted. + +:func:`analyze` finds the placeholders the way the driver does +(:mod:`.sql_tokenizer`), parses the statement with ``sqlglot``, and pairs each +placeholder with a column by its position, which the normalized SQL carries in +the placeholder's name. It knows nothing about encryption metadata: the +plugin looks the reported columns up. + +The analysis is best effort, and reports where it fell short: +:attr:`StatementAnalysis.gap` is ``None`` only when every column the statement +itself writes (not one written by a routine, ``CALL`` or ``DO`` it runs) was +established, either as filled by a placeholder +(:attr:`~StatementAnalysis.assignments`) or by something else +(:attr:`~StatementAnalysis.unbound_writes`). A statement that could not be +parsed is never mistaken for one that writes nothing. +""" + +from __future__ import annotations + +import logging +import re +import threading +from contextlib import contextmanager +from dataclasses import dataclass, field +from enum import Enum +from functools import lru_cache +from typing import (TYPE_CHECKING, Any, Callable, Dict, Iterator, List, + Optional, Sequence, Set, Tuple) + +try: + import sqlglot + from sqlglot import exp +except ModuleNotFoundError as e: # pragma: no cover - exercised by the import-guard test + # Only a missing package gets the install hint; a broken install raises + # its own error. + if (e.name or "").partition(".")[0] != "sqlglot": + raise + raise ImportError( + "The KMS encryption plugin needs the 'sqlglot' package. " + "Install it with: pip install 'aws-advanced-python-wrapper[encryption]'") from e + +from aws_advanced_python_wrapper.encryption.sql_tokenizer import ( + ColumnRef, ParamStyle, Placeholder, TokenizedSql, normalized_ordinal, + tokenize) + +if TYPE_CHECKING: + from aws_advanced_python_wrapper.encryption.sql_dialect import SqlDialect + + +class StatementKind(Enum): + """What the (first) statement is.""" + + SELECT = "SELECT" + INSERT = "INSERT" # also MySQL REPLACE + UPDATE = "UPDATE" + DELETE = "DELETE" + MERGE = "MERGE" + COPY_FROM = "COPY_FROM" + COPY_TO = "COPY_TO" + #: Recognized but not one the analysis reads (DDL, SET, CALL...). + OTHER = "OTHER" + #: Not established: the statement could not be parsed, was not parsed + #: (see :attr:`StatementAnalysis.gap`), or its parse was not trusted. + UNKNOWN = "UNKNOWN" + + +class AnalysisGap(Enum): + """Why a statement's parameters or written columns could not all be + established. The values are fixed text, safe to log.""" + + #: The SQL could not be parsed (or ran out inside a quote or comment). + UNPARSEABLE = "the statement could not be parsed" + #: A placeholder sits inside a quoted literal, quoted identifier or + #: comment, where the driver still binds it. The tables the statement + #: names are still listed, but no placeholder's column is inferred. + HIDDEN_PLACEHOLDER = "a placeholder is inside a quoted literal, quoted identifier or comment" + #: The driver will reject the statement's placeholders. + DRIVER_ERROR = "the driver will reject the placeholders" + #: The parsed statement does not have exactly the placeholders the driver + #: binds, so the parse can't be trusted. + PLACEHOLDER_MISMATCH = "the parsed statement does not match its placeholders" + #: MySQL runs the body of a ``/*! ... */`` comment, which the analysis + #: can't read as SQL. + EXECUTABLE_COMMENT = "the statement has a MySQL executable comment" + #: The statement may write but is not a form the analysis reads + #: (``EXPLAIN ANALYZE INSERT``, ``EXECUTE``, ``LOAD DATA``, ...). + UNSUPPORTED_STATEMENT = "the statement is not a form the analysis reads" + #: A ``PREPARE``: its ``$n`` parameters are bound by a later ``EXECUTE``, + #: which the analysis does not see. + PREPARED_PARAMETERS = "the prepared statement's parameters arrive with a later EXECUTE" + #: An ``INSERT`` (or ``MERGE ... INSERT``, ``COPY ... FROM``) with no column + #: list, or ``DEFAULT VALUES``. + NO_COLUMN_LIST = "the statement does not name the columns it writes" + #: ``INSERT ... SELECT`` and similar: the rows come from a query, so which + #: value fills which column is not read. + VALUES_FROM_QUERY = "the values come from a query" + #: A ``VALUES`` row with more or fewer values than columns. + ROW_LENGTH_MISMATCH = "a VALUES row does not match the column list" + #: An ``UPDATE`` of several tables assigns a column whose table can't be + #: told. + AMBIGUOUS_TABLE = "an assignment's table can't be established" + + +@dataclass(frozen=True, slots=True) +class TableRef: + """A table a statement names.""" + + name: str + schema: Optional[str] = None + + def __str__(self) -> str: + return self.name if self.schema is None else f"{self.schema}.{self.name}" + + +@dataclass(frozen=True, slots=True) +class ParameterUse: + """A placeholder whose value fills, or is compared with, a column.""" + + placeholder: Placeholder + column: ColumnRef + #: Types the value is cast to, outermost first (``%s::text::bytea`` -> + #: ``("VARBINARY", "TEXT")``), as ``sqlglot`` names them. + casts: Tuple[str, ...] = () + #: Compared with ``= ANY(...)``, ``ALL(...)`` or ``SOME(...)``: the value + #: is a list. + array: bool = False + #: For a comparison: when it never matches, it can only remove rows from + #: what the statement reads or changes. Always true for an assignment or + #: an annotation. + safe: bool = True + + @property + def ordinal(self) -> int: + return self.placeholder.ordinal + + +@dataclass(frozen=True, slots=True) +class StatementAnalysis: + """What :func:`analyze` established about one SQL string.""" + + kind: StatementKind + #: The string stores values: an INSERT, UPDATE, MERGE, COPY ... FROM, a + #: data-modifying CTE, a PREPARE of one of those, or (when it could not + #: be read) a statement whose keywords say it may write. + writes: bool + placeholders: Tuple[Placeholder, ...] + #: Every table the string names, without duplicates and excluding CTE + #: names (outer queries first, not in text order). + tables: Tuple[TableRef, ...] = () + #: The tables it writes. + written_tables: Tuple[TableRef, ...] = () + #: Placeholders written into a column. + assignments: Tuple[ParameterUse, ...] = () + #: Placeholders compared with a column (``WHERE``, ``ON``, ``HAVING``...). + comparisons: Tuple[ParameterUse, ...] = () + #: Placeholders annotated with ``/*@encrypt:...*/``. These take precedence + #: over the rest. Once the statement is parsed and its placeholders + #: matched, a qualifier is resolved through the aliases in scope at the + #: placeholder, and a bare column gets a table only when the statement + #: says which: the table the value is written to, or else the only table + #: the query around it reads. Otherwise the annotation is kept as + #: written, only folded. + annotations: Tuple[ParameterUse, ...] = () + #: Columns written with something other than a placeholder (a literal, an + #: expression, ``DEFAULT``, another column, a ``COPY`` stream). ``NULL`` + #: and copying a conflicting row's own value for the same column + #: (``EXCLUDED.c`` / ``VALUES(c)`` / a row alias) are not listed. + unbound_writes: Tuple[ColumnRef, ...] = () + #: The source column of each result column, by position, when the result + #: is a plain select list or ``RETURNING`` list: an entry is ``None`` for an + #: expression, a column of a subquery or CTE, or one whose table can't be + #: told. ``None`` altogether when unknown (``*``, set operations, + #: ``VALUES``, ``PREPARE``, several statements, no result). + result_columns: Optional[Tuple[Optional[ColumnRef], ...]] = None + #: Why the analysis is incomplete: for a statement that writes, why its + #: written columns could not all be established; for any statement, a + #: placeholder or parse problem that makes its parameters untrustworthy. + #: ``None`` when complete. + gap: Optional[AnalysisGap] = None + #: ``/*@encrypt:...*/`` comments that annotate nothing or can't be read. + stray_annotations: Tuple[str, ...] = () + #: Diagnostic detail for :attr:`gap`, safe to log: it never quotes the SQL. + detail: Optional[str] = field(default=None, compare=False) + + @property + def complete(self) -> bool: + return self.gap is None + + def parameter_columns(self) -> Dict[int, ColumnRef]: + """The column each placeholder belongs to, by ordinal: comparisons, + then assignments, then annotations, each overriding the last.""" + result: Dict[int, ColumnRef] = {} + for use in (*self.comparisons, *self.assignments, *self.annotations): + result[use.ordinal] = use.column + return result + + +#: Only short statements with few ``%`` signs (an upper bound on their +#: placeholders) are cached, as psycopg does with its own query cache. Bulk +#: INSERTs differ in their row count and rarely repeat, so caching them would +#: only make the cache large. +CACHEABLE_SQL_LENGTH = 4096 +CACHEABLE_PERCENT_SIGNS = 64 + + +def analyze(sql: str, dialect: SqlDialect, params: Any = None) -> StatementAnalysis: + """Analyze ``sql`` as the driver for ``dialect`` runs it with ``params`` + (the second argument of ``execute``; for ``executemany``, one of its + parameter sets). Only the kind of ``params`` matters (none, a sequence, a + mapping, and on MySQL whether it is empty), not its values. The result is + immutable and may be shared. + + :raises TypeError: if ``sql`` is not a ``str``. + """ + style = ParamStyle.of(params, dialect) + if isinstance(sql, str) and len(sql) <= CACHEABLE_SQL_LENGTH and sql.count("%") <= CACHEABLE_PERCENT_SIGNS: + try: + return _cached_analysis(sql, dialect, style) + except _Uncacheable as e: + return e.analysis + return _analysis(sql, dialect, style) + + +class _Uncacheable(Exception): + """Carries an analysis that must not be cached (lru_cache does not cache + exceptions).""" + + def __init__(self, analysis: StatementAnalysis): + super().__init__() + self.analysis = analysis + + +@lru_cache(maxsize=1024) +def _cached_analysis(sql: str, dialect: SqlDialect, style: ParamStyle) -> StatementAnalysis: + result = _analysis(sql, dialect, style) + if result.detail == RecursionError.__name__: + # Depends on how deep the calling thread's stack already is; another + # caller may parse the same SQL. + raise _Uncacheable(result) + return result + + +# Leading words of the statements handed to the parser. Anything else is +# reported without parsing it: sqlglot falls back to an opaque "command" for +# what it doesn't support, and logs it. +_PARSED = { + "postgresql": frozenset({"SELECT", "WITH", "INSERT", "UPDATE", "DELETE", "MERGE", "COPY", "VALUES", "PREPARE"}), + "mysql": frozenset({"SELECT", "WITH", "INSERT", "REPLACE", "UPDATE", "DELETE", "VALUES"}), +} +_SQLGLOT_DIALECT = {"postgresql": "postgres", "mysql": "mysql"} +_WRITE_LEADING = frozenset({"INSERT", "UPDATE", "REPLACE", "MERGE", "UPSERT", "LOAD", "EXECUTE"}) +_WRITE_WORDS = frozenset({"INSERT", "UPDATE", "REPLACE", "MERGE", "UPSERT"}) +_KINDS = {"SELECT": StatementKind.SELECT, "WITH": StatementKind.SELECT, "VALUES": StatementKind.SELECT, + "TABLE": StatementKind.SELECT, "INSERT": StatementKind.INSERT, "REPLACE": StatementKind.INSERT, + "UPDATE": StatementKind.UPDATE, "DELETE": StatementKind.DELETE, "MERGE": StatementKind.MERGE} + +# Whitespace and comments, one character or one whole comment per repetition, +# with a line comment running through its newline. If the pattern could split +# the same text two ways, a failed match would backtrack exponentially. +_GAP = r"(?:\s|--[^\n]*(?:\n|\Z)|/\*[^*]*\*+(?:[^/*][^*]*\*+)*/)*" + +# PREPARE name [(type, ...)] AS , on the normalized SQL. +_PREPARE = re.compile(rf""" + \A{_GAP} + PREPARE{_GAP}(?:"(?:[^"]|"")+"|[^\W\d][\w$]*){_GAP} + (?:\((?:[^()]|\([^()]*\))*\){_GAP})? + AS\b +""", re.IGNORECASE | re.VERBOSE) + +# MySQL: sqlglot rejects a qualified INSERT column list ("INSERT INTO t (t.a)"); +# a qualifier there can only name the target (the server rejects any other). +_MYSQL_NAME = r"(?:`(?:[^`]|``)+`|[\w$]+)" +_MYSQL_INSERT_COLUMNS = re.compile(rf""" + \A(?P{_GAP}INSERT{_GAP}(?:INTO{_GAP})?{_MYSQL_NAME}(?:\s*\.\s*{_MYSQL_NAME})*\s*\() + (?P[^()]*)\) +""", re.IGNORECASE | re.VERBOSE) +# One name of the column list, and the dot after it when it is a qualifier. +# A back-quoted name is one token, dots and all. +_MYSQL_COLUMN_PART = re.compile(rf"(?P{_MYSQL_NAME})(?P\s*\.\s*)?") + + +class _QuietWhileAnalyzing(logging.Filter): + """Drops sqlglot's records while this module parses on the current thread. + sqlglot logs the statement text (literals included) when it falls back to + an opaque command or reports an unsupported construct; the application's + own sqlglot logging is untouched.""" + + def __init__(self) -> None: + super().__init__() + self._local = threading.local() + + def filter(self, record: logging.LogRecord) -> bool: + return not getattr(self._local, "active", False) + + @contextmanager + def active(self) -> Iterator[None]: + previous = getattr(self._local, "active", False) + self._local.active = True + try: + yield + finally: + self._local.active = previous + + +_QUIET = _QuietWhileAnalyzing() +logging.getLogger("sqlglot").addFilter(_QUIET) + + +def _analysis(sql: str, dialect: SqlDialect, style: ParamStyle) -> StatementAnalysis: + tokens = tokenize(sql, dialect, style) + annotations = tuple(ParameterUse(p, p.annotation) for p in tokens.placeholders if p.annotation is not None) + + def result(**kwargs: Any) -> StatementAnalysis: + kwargs.setdefault("annotations", annotations) + return StatementAnalysis(placeholders=tokens.placeholders, stray_annotations=tokens.stray_annotations, + **kwargs) + + early: Optional[AnalysisGap] = None + if tokens.unterminated: + early = AnalysisGap.UNPARSEABLE + elif tokens.driver_error: + early = AnalysisGap.DRIVER_ERROR + elif tokens.has_hidden_placeholders: + early = AnalysisGap.HIDDEN_PLACEHOLDER + elif tokens.executable_comment: + early = AnalysisGap.EXECUTABLE_COMMENT + if early is not None: + # The parser reads a hidden placeholder as literal or comment text, so + # the tables are still known, and a caller can refuse the statement + # when one of them has encrypted columns. + tables = _named_tables(tokens, dialect) if early is AnalysisGap.HIDDEN_PLACEHOLDER else () + return result(kind=StatementKind.UNKNOWN, writes=_may_write(tokens), gap=early, detail=tokens.driver_error, + tables=tables) + + if not tokens.leading_words: + return result(kind=StatementKind.OTHER, writes=False) + if any(w not in _PARSED[dialect.name] for w in tokens.leading_words): + writes = _may_write(tokens) + kind = _KINDS.get(tokens.leading_words[0], StatementKind.OTHER) if len(tokens.leading_words) == 1 \ + else StatementKind.OTHER + return result(kind=kind, writes=writes, gap=AnalysisGap.UNSUPPORTED_STATEMENT if writes else None) + + parsed = _parse_statement(tokens, dialect) + if parsed is None: + writes = _may_write(tokens) + return result(kind=StatementKind.OTHER, writes=writes, + gap=AnalysisGap.UNSUPPORTED_STATEMENT if writes else None) + trees, failure = parsed + if trees is None: + return result(kind=StatementKind.UNKNOWN, writes=_may_write(tokens), gap=AnalysisGap.UNPARSEABLE, + detail=failure) + + mismatch = _placeholder_mismatch(trees, tokens) + if mismatch is not None or not trees or any(isinstance(t, exp.Command) for t in trees): + return result(kind=StatementKind.UNKNOWN, writes=_may_write(tokens), + gap=AnalysisGap.PLACEHOLDER_MISMATCH if mismatch else AnalysisGap.UNPARSEABLE, detail=mismatch) + + walker = _Walker(dialect, tokens, prepared=tokens.leading_words == ("PREPARE",)) + for tree in trees: + walker.statement(tree) + return walker.result(trees, annotations, result) + + +def _parse(text: str, dialect: SqlDialect) -> Tuple[Optional[List[exp.Expression]], Optional[str]]: + try: + with _QUIET.active(): + parsed = sqlglot.parse(text, read=_SQLGLOT_DIALECT[dialect.name]) + except Exception as e: # sqlglot raises ParseError/TokenError, but must never break a statement + # sqlglot's tokenizer re-raises a RecursionError as a TokenError. + cause: Optional[BaseException] = e + seen: Set[int] = set() + while cause is not None and id(cause) not in seen: + if isinstance(cause, RecursionError): + return None, RecursionError.__name__ + seen.add(id(cause)) + cause = cause.__cause__ or cause.__context__ + return None, type(e).__name__ + return [t for t in parsed if isinstance(t, exp.Expression)], None + + +def _parse_statement(tokens: TokenizedSql, dialect: SqlDialect) -> Optional[Tuple[Optional[List[exp.Expression]], Optional[str]]]: + """Parses the normalized SQL the way the analysis reads it. A PostgreSQL + ``PREPARE name AS`` prefix is left out, and a MySQL INSERT or REPLACE + that doesn't parse is tried again without its column qualifiers. ``None`` + when a PREPARE has no such prefix.""" + text = tokens.normalized + if tokens.leading_words == ("PREPARE",): + m = _PREPARE.match(text) + if m is None: + return None + text = text[m.end():] + + trees, failure = _parse(text, dialect) + if trees is None and tokens.leading_words in (("INSERT",), ("REPLACE",)) and dialect.name == "mysql": + unqualified = _without_insert_column_qualifiers(text) + if unqualified is not None: + trees, failure = _parse(unqualified, dialect) + return trees, failure + + +def _named_tables(tokens: TokenizedSql, dialect: SqlDialect) -> Tuple[TableRef, ...]: + """The tables the statement names, read from the text the analysis + parses; none when it doesn't parse.""" + parsed = _parse_statement(tokens, dialect) + trees = parsed[0] if parsed is not None else None + if not trees: + return () + walker = _Walker(dialect, tokens) + for tree in trees: + walker.collect_tables(tree) + return walker.tables + + +def _without_insert_column_qualifiers(text: str) -> Optional[str]: + m = _MYSQL_INSERT_COLUMNS.match(text) + if m is None or "." not in m.group("columns"): + return None + columns = _MYSQL_COLUMN_PART.sub(lambda part: "" if part.group("dot") else part.group(0), m.group("columns")) + return f"{m.group('head')}{columns}){text[m.end():]}" + + +def _may_write(tokens: TokenizedSql) -> bool: + # Keywords only: what a statement that could not be read may be doing. + words = tokens.keywords + for leading in tokens.leading_words: + if leading in _WRITE_LEADING or (leading == "COPY" and "FROM" in words): + return True + if leading in ("WITH", "EXPLAIN", "PREPARE") and words & _WRITE_WORDS: + return True + if leading == "EXPLAIN" and "EXECUTE" in words: + return True # EXPLAIN ANALYZE EXECUTE runs the prepared statement + # A MySQL executable comment can turn any statement into a write. + return tokens.executable_comment and bool(words & (_WRITE_WORDS | _WRITE_LEADING)) + + +def _placeholder_mismatch(trees: List[exp.Expression], tokens: TokenizedSql) -> Optional[str]: + seen: Set[int] = set() + for tree in trees: + for node in tree.find_all(exp.Placeholder): + ordinal = normalized_ordinal(node.name) + if ordinal is None: + continue # a "?" or ":name" the driver does not bind + if ordinal in seen or ordinal >= len(tokens.placeholders): + return "a placeholder appears more than once" + seen.add(ordinal) + if len(seen) != len(tokens.placeholders): + return f"{len(tokens.placeholders) - len(seen)} placeholder(s) missing from the parse" + return None + + +# ---- the walk ---- + +def _by_ordinal(use: ParameterUse) -> int: + return use.ordinal + + +#: What an alias or table name in scope names: a table, or ``None`` for a +#: subquery, CTE or function. +_Source = Optional[TableRef] +#: Maps an assignment's qualifier (if any) to the table it writes. +_TableOf = Callable[[Optional[str]], Optional[str]] +#: For a same-row copy in an upsert: qualifier key -> {source column key -> +#: the insert column key it carries}; ``None`` maps a column to itself. +_SameRow = Dict[str, Optional[Dict[str, str]]] + +_COMPARISONS = (exp.EQ, exp.NEQ, exp.GT, exp.GTE, exp.LT, exp.LTE, exp.NullSafeEQ, exp.NullSafeNEQ, + exp.Like, exp.ILike) +# Operators under which a value that never matches leaves the comparison false, +# unless negated (sqlglot reads NOT LIKE as a negated Like, with no NOT node) +# or applied over ALL(...). +_SAFE_OPERATORS = (exp.EQ, exp.NullSafeEQ, exp.In, exp.Like, exp.ILike) +# Join kinds that keep only the rows that match. +_INNER_JOIN_KINDS = frozenset({"", "INNER", "CROSS", "STRAIGHT_JOIN"}) +# What makes a SELECT aggregate: an aggregate or window function, or a +# function sqlglot doesn't know, which may be an aggregate (PostgreSQL's +# jsonb_agg, MySQL's JSON_ARRAYAGG, any user-defined one). Each entry of a +# WINDOW clause is a Window, so any WINDOW clause matches. +_AGGREGATING = (exp.AggFunc, exp.Window, exp.Anonymous) +_QUERIES = (exp.Select, exp.Update, exp.Delete, exp.Merge, exp.Insert) +_ARRAY_FUNCTIONS = frozenset({"ALL", "SOME", "ANY"}) +_WRITES = (exp.Insert, exp.Update, exp.Merge) +# Operators that test a value rather than produce one. Most of them are +# Predicates only from sqlglot 30.16, and MATCH ... AGAINST is not one in any +# version, so they are listed by name as well. +_TESTS = (exp.Predicate, exp.RegexpLike, exp.RegexpILike, exp.RegexpFullMatch, exp.ArrayOverlaps, exp.ArrayContains, + exp.ArrayContainsAll, exp.ArrayContainedBy, exp.JSONBContains, exp.JSONBContainsAnyTopKeys, + exp.JSONBContainsAllTopKeys, exp.Overlaps, exp.Adjacent, exp.ExtendsLeft, exp.ExtendsRight, + exp.MatchAgainst) +# Slots of a query whose values are not written: conditions, grouping +# (including a window's PARTITION BY), sorting, limits and RETURNING. A value +# bound there feeds no column of the write above. +_NOT_WRITTEN_ARGS = frozenset({"where", "having", "on", "condition", "group", "partition_by", "order", "limit", + "offset", "qualify", "returning"}) +# Slots of a query that hold its sources (CTEs, FROM, JOIN, LATERAL, USING). A +# value bound in a source may feed the write, or may only be compared with +# another table's column, so the table it is written to can't be told. +_SOURCE_ARGS = frozenset({"with_", "from_", "joins", "laterals", "using"}) +# The Select args a "SELECT p0, p1 FROM (VALUES ...) AS v(p0, p1)" may set and +# still be read as plain rows (ORDER BY changes no row's values). +_PLAIN_SELECT_ARGS = frozenset({"expressions", "from_", "order"}) + +# How many derived tables or CTEs a result column is followed through. +_MAX_DEPTH = 8 + + +class _Walker: + """Collects what one or more parsed statements write, compare and read.""" + + def __init__(self, dialect: SqlDialect, tokens: TokenizedSql, prepared: bool = False): + self._dialect = dialect + self._tokens = tokens + # The body of a PREPARE: its $n parameters are bound later. + self._prepared = prepared + self._kind: Optional[StatementKind] = None + self._writes = False + self._tables: Dict[TableRef, None] = {} + self._written: Dict[TableRef, None] = {} + self._assignments: List[ParameterUse] = [] + self._comparisons: List[ParameterUse] = [] + self._unbound: List[ColumnRef] = [] + self._gap: Optional[AnalysisGap] = None + self._cte_names: Set[str] = set() + # Ids of the SET and ON CONFLICT assignments (EQ nodes), which are + # neither comparisons nor tests. + self._assignment_nodes: Set[int] = set() + self._scopes: Dict[int, Dict[str, _Source]] = {} + # Nearest enclosing query of a node, memoized so a long AND/OR chain + # is resolved in linear time. + self._nearest: Dict[int, Optional[exp.Expression]] = {} + # The query that decides whether a condition under a node (AND, OR, + # parentheses) is in a safe position, or None when it can't be (see + # _deciding_query), memoized so a long AND/OR chain is resolved in + # linear time; and whether each query's own position is safe. + self._deciders: Dict[int, Optional[exp.Expression]] = {} + self._safe: Dict[int, bool] = {} + # Per statement, its tables without a schema by name: where its CTEs + # are read. + self._tables_by_name: Dict[int, Dict[str, List[exp.Table]]] = {} + self._placeholder_nodes: Dict[int, exp.Expression] = {} + # Tables each write node (INSERT, UPDATE, MERGE) writes. + self._written_by: Dict[int, List[TableRef]] = {} + + # ---- entry ---- + + def statement(self, tree: exp.Expression) -> None: + self.collect_tables(tree) + for found in tree.find_all(exp.Placeholder): + ordinal = normalized_ordinal(found.name) + if ordinal is not None: + self._placeholder_nodes[ordinal] = found + + kind = self._statement_kind(tree) + if self._kind is None: + self._kind = kind + + # Every write, wherever it sits: the statement itself or a + # data-modifying CTE. MERGE's own WHEN ... INSERT/UPDATE are read by + # the MERGE. + for node in tree.walk(): + if isinstance(node, exp.Insert) and not isinstance(node.parent, exp.When): + self._insert(node) + elif isinstance(node, exp.Update) and not isinstance(node.parent, exp.When): + self._update(node) + elif isinstance(node, exp.Merge): + self._merge(node) + elif isinstance(node, exp.Copy): + self._copy(node) + self._collect_comparisons(tree) + + def collect_tables(self, tree: exp.Expression) -> None: + """Adds the tables ``tree`` names, leaving out its CTE names.""" + for cte in tree.find_all(exp.CTE): + alias = cte.args.get("alias") + if isinstance(alias, exp.TableAlias): + self._cte_names.add(self._key(alias.this)) + for table in tree.find_all(exp.Table): + ref = self._table_ref(table) + if ref is not None: + self._tables.setdefault(ref, None) + + @property + def tables(self) -> Tuple[TableRef, ...]: + return tuple(self._tables) + + def result(self, trees: List[exp.Expression], annotations: Tuple[ParameterUse, ...], + build: Callable[..., StatementAnalysis]) -> StatementAnalysis: + assignments = tuple(sorted(self._assignments, key=_by_ordinal)) + comparisons = tuple(sorted(self._comparisons, key=_by_ordinal)) + inferred = {use.ordinal: use.column for use in (*comparisons, *assignments)} + resolved = tuple(ParameterUse(a.placeholder, self._resolve_annotation(a.placeholder, a.column, inferred)) + for a in annotations) + if self._prepared: + self._note(AnalysisGap.PREPARED_PARAMETERS) + return build( + kind=self._kind or StatementKind.OTHER, + writes=self._writes, + tables=tuple(self._tables), + written_tables=tuple(self._written), + assignments=assignments, + comparisons=comparisons, + annotations=resolved, + unbound_writes=tuple(self._unbound), + result_columns=self._result_columns(trees[0]) if len(trees) == 1 and not self._prepared else None, + gap=self._gap if self._writes else None) + + # ---- statements ---- + + def _statement_kind(self, tree: exp.Expression) -> StatementKind: + if isinstance(tree, exp.Copy): + return StatementKind.COPY_FROM if tree.args.get("kind") else StatementKind.COPY_TO + for cls, kind in ((exp.Insert, StatementKind.INSERT), (exp.Update, StatementKind.UPDATE), + (exp.Delete, StatementKind.DELETE), (exp.Merge, StatementKind.MERGE), + (exp.Query, StatementKind.SELECT), (exp.Values, StatementKind.SELECT)): + if isinstance(tree, cls): + return kind + return StatementKind.OTHER + + def _insert(self, node: exp.Insert) -> None: + self._writes = True + target = node.this + columns: Optional[List[Optional[str]]] = None + if isinstance(target, exp.Schema): + table = target.this + columns = [self._identifier(i) for i in target.expressions] + else: + table = target + # sqlglot attaches the column list of "INSERT INTO t AS a (c)" to + # the alias. + alias = table.args.get("alias") if isinstance(table, exp.Table) else None + if alias is not None and alias.columns: + columns = [self._identifier(i) for i in alias.columns] + ref = self._written_table(table, node) + name = None if ref is None else ref.name + if ref is None: + self._note(AnalysisGap.UNSUPPORTED_STATEMENT) + if columns is not None and any(c is None for c in columns): + self._note(AnalysisGap.UNSUPPORTED_STATEMENT) + columns = None + + source = node.expression + if columns is None: + self._note(AnalysisGap.NO_COLUMN_LIST) + elif isinstance(source, exp.Values): + self._insert_rows(columns, name, source.expressions) + elif source is None: + self._note(AnalysisGap.NO_COLUMN_LIST) # DEFAULT VALUES + elif not self._insert_from_values(columns, name, source): + self._note(AnalysisGap.VALUES_FROM_QUERY) + + conflict = node.args.get("conflict") + if isinstance(conflict, exp.OnConflict): + self._upsert(conflict, name, columns, source) + + def _insert_rows(self, columns: List[Optional[str]], table: Optional[str], rows: List[exp.Expression], + positions: Optional[List[Tuple[int, Tuple[str, ...]]]] = None) -> None: + # positions: for each insert column, the position in the row that + # fills it and the casts on the way (default: the same position). + for row in rows: + values = self._row_values(row) + width = len(columns) if positions is None else max(p for p, _ in positions) + 1 + if values is None or (len(values) != width if positions is None else len(values) < width): + self._note(AnalysisGap.ROW_LENGTH_MISMATCH) + if values is None: + continue + for i, column in enumerate(columns): + position, casts = (i, ()) if positions is None else positions[i] + if position < len(values) and column is not None: + self._write(ColumnRef(column, table), values[position], casts) + + def _insert_from_values(self, columns: List[Optional[str]], table: Optional[str], + source: exp.Expression) -> bool: + """``INSERT INTO t (a, b) SELECT x, y FROM (VALUES (...), ...) AS v(x, y)``, + the form SQLAlchemy uses for a multi-row ORM insert. When each insert + column is filled by a different column of the VALUES list (possibly + cast), it is read like an ordinary multi-row VALUES. An ORDER BY is + allowed. A join, a filter, an expression other than a cast, or one + VALUES column filling two insert columns is not.""" + if not isinstance(source, exp.Select) or len(source.expressions) != len(columns): + return False + if any(value for key, value in source.args.items() if key not in _PLAIN_SELECT_ARGS): + return False # a join, a filter, a limit, ... (or an arg this code does not know) + from_ = source.args.get("from_") + values = from_.this if isinstance(from_, exp.From) else None + alias = values.args.get("alias") if isinstance(values, exp.Values) else None + if not isinstance(alias, exp.TableAlias) or not alias.columns: + return False + names = {self._key(c): i for i, c in enumerate(alias.columns)} + alias_key = self._key(alias.this) + positions: List[Tuple[int, Tuple[str, ...]]] = [] + for item in source.expressions: + inner, casts = self._unwrap_casts(item) + qualifier = inner.args.get("table") if isinstance(inner, exp.Column) else None + if not isinstance(inner, exp.Column) or not isinstance(inner.this, exp.Identifier) \ + or (qualifier is not None and self._key(qualifier) != alias_key) \ + or self._key(inner.this) not in names: + return False + positions.append((names[self._key(inner.this)], casts)) + if len({position for position, _ in positions}) != len(positions): + return False # one value would fill two columns + assert isinstance(values, exp.Values) + self._insert_rows(columns, table, values.expressions, positions) + return True + + def _upsert(self, conflict: exp.OnConflict, table: Optional[str], columns: Optional[List[Optional[str]]], + source: Optional[exp.Expression]) -> None: + same_row: _SameRow = {} + if self._dialect.name != "mysql": + same_row[self._key("excluded")] = None + row_alias = source.args.get("alias") if isinstance(source, exp.Values) else None + if isinstance(row_alias, exp.TableAlias): + renamed: Optional[Dict[str, str]] = None + if row_alias.columns: + # AS new(c1, c2) renames the inserted columns by position. + renamed = {} + for alias_column, column in zip(row_alias.columns, columns or ()): + if column is not None: + renamed[self._key(alias_column)] = self._dialect.metadata_key(column) + same_row[self._key(row_alias.this)] = renamed + for assignment in conflict.expressions: + self._assign(assignment, lambda _q: table, same_row=same_row) + + def _update(self, node: exp.Update) -> None: + self._writes = True + target = node.this + joins = (target.args.get("joins") or []) if isinstance(target, exp.Table) else [] + targets = [target] + [j.this for j in joins] + scope = self._scope(node) + ref = self._written_table(target, node) + if ref is None: + self._note(AnalysisGap.UNSUPPORTED_STATEMENT) + for extra in targets[1:]: + self._written_table(extra, node) + + def table_of(qualifier: Optional[str]) -> Optional[str]: + if len(targets) == 1: + # One table to write: a qualifier can only mean it. + # PostgreSQL's FROM adds tables to read, not to write. + return None if ref is None else ref.name + source = scope.get(self._dialect.metadata_key(qualifier)) if qualifier else None + if source is None: + self._note(AnalysisGap.AMBIGUOUS_TABLE) + return None + return source.name + + for assignment in node.expressions: + self._assign(assignment, table_of) + + def _merge(self, node: exp.Merge) -> None: + self._writes = True + ref = self._written_table(node.this, node) + name = None if ref is None else ref.name + whens = node.args.get("whens") + for when in (whens.expressions if whens is not None else ()): + then = when.args.get("then") + if isinstance(then, exp.Update): + for assignment in then.expressions: + self._assign(assignment, lambda _q: name) + elif isinstance(then, exp.Insert): + columns = [self._identifier(c) for c in then.this.expressions] \ + if isinstance(then.this, exp.Tuple) else None + if columns is None or any(c is None for c in columns): + self._note(AnalysisGap.NO_COLUMN_LIST if columns is None else AnalysisGap.UNSUPPORTED_STATEMENT) + continue + self._insert_rows(columns, name, [then.expression]) + + def _copy(self, node: exp.Copy) -> None: + if not node.args.get("kind"): + return # COPY ... TO reads + self._writes = True + target = node.this + table = target.this if isinstance(target, exp.Schema) else target + ref = self._written_table(table) + name = None if ref is None else ref.name + if not isinstance(target, exp.Schema) or not target.expressions: + self._note(AnalysisGap.NO_COLUMN_LIST) + return + # The rows arrive as a stream, never as bind parameters. + for identifier in target.expressions: + column = self._identifier(identifier) + if column is None: + self._note(AnalysisGap.UNSUPPORTED_STATEMENT) + else: + self._unbound.append(ColumnRef(column, name)) + + # ---- writes ---- + + def _assign(self, assignment: exp.Expression, table_of: _TableOf, same_row: Optional[_SameRow] = None) -> None: + self._assignment_nodes.add(id(assignment)) + if not isinstance(assignment, exp.EQ): + self._note(AnalysisGap.UNSUPPORTED_STATEMENT) + return + target, value = assignment.this, assignment.expression + if isinstance(target, exp.Tuple): + # SET (a, b) = (v1, v2) / ROW(v1, v2); a subquery fills them all. + values = self._row_values(value) + if values is None or len(values) != len(target.expressions): + for column in target.expressions: + name = self._identifier(column) if isinstance(column, exp.Column) else None + if name is None: + self._note(AnalysisGap.UNSUPPORTED_STATEMENT) + continue + self._unbound.append(ColumnRef(name, table_of(self._fold(column.args.get("table"))))) + return + pairs = list(zip(target.expressions, values)) + else: + pairs = [(target, value)] + for column, v in pairs: + name = self._identifier(column) if isinstance(column, exp.Column) else None + if name is None: + self._note(AnalysisGap.UNSUPPORTED_STATEMENT) + continue + if same_row is not None and self._copies_same_column(v, name, same_row): + continue + self._write(ColumnRef(name, table_of(self._fold(column.args.get("table")))), v) + + def _write(self, column: ColumnRef, value: exp.Expression, outer_casts: Tuple[str, ...] = ()) -> None: + param = self._param(value) + if param is not None: + ordinal, casts, _ = param + self._assignments.append(ParameterUse(self._tokens.placeholders[ordinal], column, outer_casts + casts)) + elif self._prepared and self._server_parameter(value): + pass # bound by a later EXECUTE; the statement's gap says so + elif not isinstance(value, exp.Null): + self._unbound.append(column) + + @staticmethod + def _server_parameter(value: exp.Expression) -> bool: + while isinstance(value, (exp.Paren, exp.Cast, exp.TryCast)): + value = value.this + return isinstance(value, exp.Parameter) + + def _copies_same_column(self, value: exp.Expression, column: str, same_row: _SameRow) -> bool: + # The incoming row's own value for this column, already encrypted (or + # refused) where the row was written: EXCLUDED.c, VALUES(c) on MySQL, + # or alias.c with a MySQL row alias (by position when the alias names + # its columns). + key = self._dialect.metadata_key(column) + qualifier = value.args.get("table") if isinstance(value, exp.Column) else None + if qualifier is not None: + qualifier_key = self._key(qualifier) + if qualifier_key not in same_row: + return False + renamed = same_row[qualifier_key] + source = self._key(value.this) + return (renamed.get(source) if renamed is not None else source) == key + if self._dialect.name == "mysql" and isinstance(value, exp.Anonymous) \ + and str(value.this).upper() == "VALUES" and len(value.expressions) == 1: + inner = value.expressions[0] + if isinstance(inner, exp.Column) and inner.args.get("table") is None: + inner = inner.this + return isinstance(inner, exp.Identifier) and self._key(inner) == key + return False + + def _row_values(self, row: Optional[exp.Expression]) -> Optional[List[exp.Expression]]: + if isinstance(row, exp.Paren): + return [row.this] + if isinstance(row, exp.Tuple): + items = list(row.expressions) + # MySQL's VALUES ROW(...) comes back as a one-item tuple. + if len(items) == 1 and self._is_row(items[0]): + return list(items[0].expressions) + return items + if row is not None and self._is_row(row): + return list(row.expressions) + return None + + @staticmethod + def _is_row(node: exp.Expression) -> bool: + return isinstance(node, exp.Anonymous) and str(node.this).upper() == "ROW" + + # ---- comparisons ---- + + def _collect_comparisons(self, tree: exp.Expression) -> None: + for node in tree.walk(): + if id(node) in self._assignment_nodes: + continue + if isinstance(node, _COMPARISONS): + self._compare(node, node.this, node.expression) + self._compare(node, node.expression, node.this) + elif isinstance(node, exp.In): + for item in node.expressions: + self._compare(node, node.this, item) + self._compare(node, node.args.get("query"), node.this) # %s IN (SELECT ssn FROM users) + elif isinstance(node, exp.Between): + self._compare(node, node.this, node.args.get("low")) + self._compare(node, node.this, node.args.get("high")) + + def _compare(self, node: exp.Expression, column: Optional[exp.Expression], + value: Optional[exp.Expression]) -> None: + column, every = self._compared_column(column) + if not isinstance(column, exp.Column) or not isinstance(column.this, exp.Identifier) or value is None: + return + param = self._param(value) + if param is None: + return + ordinal, casts, function = param + ref = self._column_ref(column, column) # a sub-select's column is resolved in the sub-select + if ref is not None: + safe = isinstance(node, _SAFE_OPERATORS) and not node.args.get("negate") and function != "ALL" and not every + if safe: + decider = self._deciding_query(node) + safe = decider is not None and self._query_safe(decider) + self._comparisons.append( + ParameterUse(self._tokens.placeholders[ordinal], ref, casts, function is not None, safe)) + + @staticmethod + def _compared_column(side: Optional[exp.Expression]) -> Tuple[Optional[exp.Expression], bool]: + """What one side of a comparison compares a value with, and whether + it does so under ALL. A column in parentheses is the column + (``(ssn) = %s``). A sub-select whose select list is one column, under + any alias, is that column, because its rows hold that column's + values: ``%s IN (SELECT ssn FROM users)``, ``%s = ANY (SELECT ...)``, + ``%s <> ALL (SELECT ...)`` and ``%s = (SELECT ...)``, in any number of + parentheses and with an ORDER BY or LIMIT between them + (``%s <> ALL ((SELECT ...) LIMIT 5)``). Any other side comes back with + the parentheses, aliases, ALL, SOME or ANY over a sub-select with its + ORDER BY or LIMIT, and one-item select list around it removed, for + the caller to reject.""" + every = False + if isinstance(side, (exp.Any, exp.All)) and isinstance(side.this, (exp.Subquery, exp.Select)): + # sqlglot reads ALL (SELECT ...) and SOME (SELECT ...) without a Subquery. + every, side = isinstance(side, exp.All), side.this + elif isinstance(side, exp.Anonymous) and str(side.this).upper() in _ARRAY_FUNCTIONS \ + and len(side.expressions) == 1: + # sqlglot reads ALL ((SELECT ...)) and SOME ((SELECT ...)) as functions, and an ORDER BY or LIMIT + # between the parentheses as a node over the Subquery. + query = side.expressions[0] + while isinstance(query, (exp.Order, exp.Limit)): + query = query.this + if isinstance(query, exp.Subquery): + every, side = str(side.this).upper() == "ALL", query + while True: + if isinstance(side, (exp.Paren, exp.Subquery, exp.Alias)): + side = side.this + elif isinstance(side, exp.Select) and len(side.expressions) == 1: + side = side.expressions[0] + else: + return side, every + + def _deciding_query(self, node: exp.Expression) -> Optional[exp.Expression]: + """The query whose own position (:meth:`_query_safe`) decides whether + a condition at ``node`` that never holds can only remove rows from + what the statement reads or changes; ``None`` when the condition's + place makes it unsafe in any query. The place is safe when AND, OR + and parentheses alone join the condition to the WHERE of a SELECT, + UPDATE or DELETE, the HAVING of a SELECT, or the ON of an inner join + in a query with no outer join. Anything else around it (NOT, IS, a + function, CASE, a select list, a SET value, a MERGE ...) is not.""" + path: List[int] = [] + child, parent = node, node.parent + while isinstance(parent, (exp.Paren, exp.And, exp.Or)) \ + or (isinstance(parent, exp.Escape) and child.arg_key == "this"): + if id(parent) in self._deciders: + decider = self._deciders[id(parent)] + break + path.append(id(parent)) + child, parent = parent, parent.parent + else: # reached without a memo hit: the clause the condition is in decides + query = parent.parent if parent is not None else None + if (isinstance(parent, exp.Where) and isinstance(query, (exp.Select, exp.Update, exp.Delete))) \ + or (isinstance(parent, exp.Having) and isinstance(query, exp.Select)): + decider = query + elif isinstance(parent, exp.Join) and child.arg_key == "on" and not parent.side \ + and parent.kind in _INNER_JOIN_KINDS: + decider = self._joining_query(parent) + else: + decider = None + for key in path: + self._deciders[key] = decider + return decider + + def _query_safe(self, query: exp.Expression) -> bool: + """Whether a condition of ``query`` that never holds can only remove + rows from what the statement reads or changes, memoized. Worked out + with a stack rather than by recursion, because a chain of CTEs is as + deep as it is long. A query counts as unsafe while it is worked out, + so a recursive CTE's reference to itself ends unsafe.""" + needs: Dict[int, List[exp.Expression]] = {} + todo = [query] + while todo: + top = todo[-1] + if id(top) in needs: + self._safe[id(top)] = all(self._safe[id(n)] for n in needs.pop(id(top))) + todo.pop() + elif id(top) in self._safe: + todo.pop() + else: + required = self._requirements(top) + self._safe[id(top)] = required == [] + if required: + needs[id(top)] = required + todo.extend(n for n in required if id(n) not in self._safe) + else: + todo.pop() + return self._safe[id(query)] + + def _requirements(self, query: exp.Expression) -> Optional[List[exp.Expression]]: + """The queries whose positions must all be safe for the position of + ``query`` to be, or ``None`` when it is unsafe whatever they are. What + reads its rows must only lose rows when it loses some: the statement + itself; a sub-select that doesn't group, aggregate or have a WINDOW + clause (an aggregate or window function in its select list, ORDER BY + or DISTINCT ON, where a function sqlglot doesn't know counts as an + aggregate), read (through either side of UNION or INTERSECT, the left + of EXCEPT, and an ORDER BY or LIMIT written after its parentheses) by + IN, EXISTS, a scalar ``=`` or ``= ANY`` in a safe position, or as a + FROM or JOIN source of a query with no outer join; a + CTE read only that way; or the rows of the statement's INSERT.""" + child, parent = query, query.parent + if parent is None: + return [] + if isinstance(query, exp.Select) and (query.args.get("group") or query.args.get("having") or any( + e.find(*_AGGREGATING) for e in (*query.expressions, *(query.args.get("windows") or ()), + query.args.get("order"), query.args.get("distinct")) if e)): + return None # it may return rows for no input row, such as a count of 0 + while isinstance(parent, (exp.Subquery, exp.Paren, exp.Union, exp.Intersect)) \ + or (isinstance(parent, (exp.Except, exp.Order, exp.Limit)) and child.arg_key == "this"): + child, parent = parent, parent.parent + if parent is None: + return [] # a set operation or a parenthesized query that is the statement + if isinstance(parent, exp.Insert): + # INSERT ... SELECT: a filter that never holds only inserts fewer rows. + return [] if child.arg_key == "expression" and parent.parent is None else None + if isinstance(parent, exp.CTE): + return self._cte_readers(parent) + decider: Optional[exp.Expression] = None + if isinstance(parent, exp.Exists) or (isinstance(parent, exp.In) and child.arg_key == "query") \ + or (isinstance(parent, exp.EQ) and isinstance(child, exp.Subquery)): + decider = self._deciding_query(parent) + elif (isinstance(parent, exp.Any) or (isinstance(parent, exp.Anonymous) and str(parent.this).upper() == "SOME")) \ + and isinstance(parent.parent, exp.EQ): + # sqlglot reads SOME ((SELECT ...)) as a function. + decider = self._deciding_query(parent.parent) + elif isinstance(parent, (exp.From, exp.Join)) and child.arg_key == "this": + decider = self._joining_query(parent) + return None if decider is None else [decider] + + def _cte_readers(self, cte: exp.Expression) -> Optional[List[exp.Expression]]: + """The queries that read ``cte``, each as a FROM or JOIN source with no + outer join, or ``None`` when something reads it otherwise. It is read + wherever a table without a schema has its name in the statement (as + :attr:`_cte_names` is scoped), its own body included.""" + root = cte.root() + named = self._tables_by_name.get(id(root)) + if named is None: + named = self._tables_by_name[id(root)] = {} + for table in root.find_all(exp.Table): + if table.args.get("db") is None and isinstance(table.this, exp.Identifier): + named.setdefault(self._key(table.this), []).append(table) + readers: List[exp.Expression] = [] + for table in named.get(self._key(cte.args["alias"].this), ()): + reader = self._joining_query(table.parent) \ + if isinstance(table.parent, (exp.From, exp.Join)) and table.arg_key == "this" else None + if reader is None: + return None + readers.append(reader) + return readers + + def _joining_query(self, node: exp.Expression) -> Optional[exp.Expression]: + """The query that owns ``node`` (a JOIN, or the FROM or JOIN of a + derived table or CTE) when it has no outer join, else ``None``. Joins + are evaluated left to right, so a later RIGHT or FULL join keeps the + rows of its side when an earlier one matches none.""" + owner = self._nearest_query(node) + return owner if owner is not None and not self._has_outer_join(owner) else None + + @staticmethod + def _has_outer_join(query: exp.Expression) -> bool: + """Whether ``query`` has a join with a side (LEFT, RIGHT, FULL), read + from its own joins and from the tables and ``Subquery`` nodes its FROM, + its USING and the table it writes start from, at any depth of + parentheses: sqlglot puts a multi-table UPDATE's or DELETE's joins + under a table, and the joins that follow a derived table or a + parenthesized join under its ``Subquery``. A derived table's joins are + its own query's.""" + using = query.args.get("using") + sources: List[Any] = [query.args.get("this"), query.args.get("from_"), *(query.args.get("joins") or ()), + *(using if isinstance(using, list) else [using])] + while sources: + source = sources.pop() + if isinstance(source, exp.Join): + if source.side: + return True + sources.append(source.this) + elif isinstance(source, (exp.From, exp.Subquery)): + # A Subquery around a Table is a parenthesized join. sqlglot + # hangs the joins that follow a derived table or a + # parenthesized join on its Subquery. + sources.append(source.this) + sources.extend(source.args.get("joins") or ()) + elif isinstance(source, exp.Table): + sources.extend(source.args.get("joins") or ()) + return False + + # ---- values ---- + + @staticmethod + def _unwrap_casts(value: exp.Expression) -> Tuple[exp.Expression, Tuple[str, ...]]: + casts: List[str] = [] + while True: + if isinstance(value, exp.Paren): + value = value.this + elif isinstance(value, (exp.Cast, exp.TryCast)): + to = value.args.get("to") + casts.append(to.this.name if isinstance(to, exp.DataType) else str(to)) + value = value.this + else: + return value, tuple(casts) + + def _param(self, value: exp.Expression) -> Optional[Tuple[int, Tuple[str, ...], Optional[str]]]: + """(ordinal, casts, array function) when ``value`` is a placeholder, + possibly in parentheses, casts, or ANY/ALL/SOME. The array function + is ``"ANY"``, ``"ALL"`` or ``"SOME"``, or ``None`` outside them.""" + value, casts = self._unwrap_casts(value) + function: Optional[str] = None + if isinstance(value, (exp.Any, exp.All)): + function, (value, more) = "ALL" if isinstance(value, exp.All) else "ANY", self._unwrap_casts(value.this) + casts += more + elif isinstance(value, exp.Anonymous) and str(value.this).upper() in _ARRAY_FUNCTIONS \ + and len(value.expressions) == 1: + # sqlglot reads PostgreSQL's ALL(...) and SOME(...) as functions. + function, (value, more) = str(value.this).upper(), self._unwrap_casts(value.expressions[0]) + casts += more + if isinstance(value, exp.Placeholder): + ordinal = normalized_ordinal(value.name) + if ordinal is not None: + return ordinal, casts, function + return None + + # ---- names and scopes ---- + + def _fold(self, name: Any) -> Optional[str]: + """The name an identifier resolves to, folded as the engine folds it; + ``None`` when ``name`` is not an identifier.""" + if isinstance(name, exp.Identifier): + return self._dialect.fold_identifier(name.this, quoted=bool(name.args.get("quoted"))) + if isinstance(name, str) and name: + return self._dialect.fold_identifier(name, quoted=False) + return None + + def _identifier(self, node: Any) -> Optional[str]: + """The column a node names, or ``None`` when it is not a plain name + (a subscript, a field of a composite, ...).""" + if isinstance(node, exp.Column): + node = node.this + return self._fold(node) if isinstance(node, exp.Identifier) else None + + def _key(self, name: Any) -> str: + """The form names are compared in (case-insensitive on MySQL).""" + return self._dialect.metadata_key(self._fold(name) or "") + + def _table_ref(self, table: exp.Table) -> Optional[TableRef]: + if not isinstance(table.this, exp.Identifier): + return None # a function or a subquery + name = self._fold(table.this) + assert name is not None + schema = self._fold(table.args.get("db")) + if schema is None and self._dialect.metadata_key(name) in self._cte_names: + return None + return TableRef(name, schema) + + def _written_table(self, table: Optional[exp.Expression], + write: Optional[exp.Expression] = None) -> Optional[TableRef]: + ref = self._table_ref(table) if isinstance(table, exp.Table) else None + if ref is not None: + self._written.setdefault(ref, None) + if write is not None: + self._written_by.setdefault(id(write), []).append(ref) + return ref + + def _write_targets(self, node: exp.Expression) -> Optional[Sequence[TableRef]]: + """The tables written by the INSERT, UPDATE or MERGE that the value at + ``node`` feeds. + + Returns ``None`` when the value is not written. That is the case when, + on the way up, it is compared or otherwise tested (:data:`_TESTS`), is + the condition or operand of a ``CASE`` or ``IF``, or sits in one of + :data:`_NOT_WRITTEN_ARGS`, and when it reaches no write at all. + + Returns an empty sequence when the table can't be told: the value + reaches the write through one of :data:`_SOURCE_ARGS` (a CTE, or a + ``FROM``, ``JOIN``, ``LATERAL`` or ``USING`` source), or the write's + target is not a plain table.""" + child: Any = node + parent: Any = node.parent + through_source = False + while parent is not None: + key = child.arg_key + if key in _NOT_WRITTEN_ARGS: + return None + # A SET or ON CONFLICT "c = value" is an assignment, not a test. + if isinstance(parent, _TESTS) and id(parent) not in self._assignment_nodes: + return None + if isinstance(parent, (exp.If, exp.Case)) and key == "this": + return None + through_source = through_source or key in _SOURCE_ARGS + # A MERGE's WHEN ... UPDATE / INSERT belongs to the MERGE. + if isinstance(parent, _WRITES) and not isinstance(parent.parent, exp.When): + return () if through_source else self._written_by.get(id(parent), ()) + child, parent = parent, parent.parent + return None + + def _scope(self, query: exp.Expression) -> Dict[str, _Source]: + """Alias or table name -> what it names, for the sources one query + reads directly.""" + cached = self._scopes.get(id(query)) + if cached is not None: + return cached + sources: Dict[str, _Source] = {} + + def add(node: Any) -> None: + if isinstance(node, list): + for item in node: + add(item) + return + if not isinstance(node, exp.Expression): + return # an absent arg can be None or False + if isinstance(node, (exp.From, exp.Join)): + add(node.this) + return + alias = node.args.get("alias") + alias_name = alias.this if isinstance(alias, exp.TableAlias) else None + ref = self._table_ref(node) if isinstance(node, exp.Table) else None + if alias_name is not None: + sources[self._key(alias_name)] = ref + if ref is not None: + sources.setdefault(self._dialect.metadata_key(ref.name), ref) + elif isinstance(node, exp.Table) and alias_name is None: + sources[self._key(node.this)] = None # a CTE named directly + if isinstance(node, exp.Table): + add(node.args.get("joins")) + + if isinstance(query, exp.Insert): + add(query.this.this if isinstance(query.this, exp.Schema) else query.this) + else: + if isinstance(query, (exp.Update, exp.Delete, exp.Merge)): + add(query.args.get("this")) + add(query.args.get("from_")) + add(query.args.get("joins")) + add(query.args.get("using")) # a list for DELETE ... USING + add(query.args.get("tables")) + self._scopes[id(query)] = sources + return sources + + def _nearest_query(self, node: exp.Expression) -> Optional[exp.Expression]: + """The innermost query around ``node`` (excluding ``node`` itself).""" + path: List[int] = [] + parent = node.parent + found: Optional[exp.Expression] = None + while parent is not None: + if id(parent) in self._nearest: + found = self._nearest[id(parent)] + break + if isinstance(parent, _QUERIES): + found = parent + break + path.append(id(parent)) + parent = parent.parent + for key in path: + self._nearest[key] = found + return found + + def _enclosing_queries(self, node: exp.Expression) -> Iterator[exp.Expression]: + query = self._nearest_query(node) + while query is not None: + yield query + query = self._nearest_query(query) + + def _column_ref(self, column: exp.Column, at: exp.Expression) -> Optional[ColumnRef]: + name = self._identifier(column) + if name is None: + return None + qualifier = self._fold(column.args.get("table")) + if qualifier is not None: + key = self._dialect.metadata_key(qualifier) + for query in self._enclosing_queries(at): + scope = self._scope(query) + if key in scope: + source = scope[key] + return ColumnRef(name, None if source is None else source.name) + # Not an alias in sight: taken as a table name. + return ColumnRef(name, qualifier) + nearest = self._nearest_query(at) + if nearest is not None: + sources = set(self._scope(nearest).values()) + if len(sources) == 1: + only = next(iter(sources)) + return ColumnRef(name, None if only is None else only.name) + return ColumnRef(name) + + def _resolve_annotation(self, placeholder: Placeholder, ref: ColumnRef, + inferred: Dict[int, ColumnRef]) -> ColumnRef: + """Resolve an annotation's qualifier through the aliases in scope at + its placeholder, nearest query first. A qualifier that names nothing + in scope, or names a subquery or CTE, is kept as a table name. + + A bare column gets a table only when the statement says which: + + 1. the table the analysis found for that placeholder, if it is the + same column; + 2. otherwise, for a written value (a VALUES row, a SET value, or the + select list of a query feeding an INSERT, UPDATE or MERGE; see + :meth:`_write_targets`), the table that write writes. With several + written tables, or when the value reaches the write through a CTE + or a FROM, JOIN, LATERAL or USING source, it stays bare; + 3. otherwise, for a compared or read value, the only table its + nearest query reads. + + In every other case it stays bare.""" + node = self._placeholder_nodes.get(placeholder.ordinal) + if ref.table is not None: + key = self._dialect.metadata_key(ref.table) + for query in (self._enclosing_queries(node) if node is not None else ()): + scope = self._scope(query) + if key in scope: + source = scope[key] + return ColumnRef(ref.column, ref.table if source is None else source.name) + return ref + found = inferred.get(placeholder.ordinal) + if found is not None and found.table is not None \ + and self._dialect.metadata_key(found.column) == self._dialect.metadata_key(ref.column): + return ColumnRef(ref.column, found.table) + if node is None: + return ref + targets = self._write_targets(node) + if targets is not None: + tables = {t.name: None for t in targets} + return ColumnRef(ref.column, next(iter(tables))) if len(tables) == 1 else ref + nearest = self._nearest_query(node) + if nearest is not None: + sources = set(self._scope(nearest).values()) + if len(sources) == 1: + only = next(iter(sources)) + if only is not None: + return ColumnRef(ref.column, only.name) + return ref + + # ---- results ---- + + def _result_columns(self, tree: exp.Expression) -> Optional[Tuple[Optional[ColumnRef], ...]]: + if isinstance(tree, exp.Select): + items = tree.expressions + else: + returning = tree.args.get("returning") if isinstance(tree, (exp.Insert, exp.Update, exp.Delete)) else None + if not isinstance(returning, exp.Returning): + return None + items = returning.expressions + result: List[Optional[ColumnRef]] = [] + for item in items: + inner = item.this if isinstance(item, exp.Alias) else item + if isinstance(inner, exp.Star) or (isinstance(inner, exp.Column) and isinstance(inner.this, exp.Star)): + return None + ref = self._column_ref(inner, inner) if isinstance(inner, exp.Column) else None + if (ref is None or ref.table is None) and isinstance(tree, exp.Select): + # Read through a derived table or CTE: follow it to its table. + ref = self._trace(inner, tree, 0) + result.append(ref if ref is not None and ref.table is not None else None) + return tuple(result) + + def _trace(self, node: exp.Expression, query: exp.Expression, depth: int) -> Optional[ColumnRef]: + """The table column a result column of ``query`` comes from, followed + through derived tables and CTEs; ``None`` past a set operation, ``*``, + an expression or :data:`_MAX_DEPTH` levels.""" + if depth > _MAX_DEPTH or not isinstance(node, exp.Column): + return None + ref = self._column_ref(node, node) + if ref is not None and ref.table is not None: + return ref + name = self._identifier(node) + if name is None: + return None + qualifier = self._fold(node.args.get("table")) + inner = self._derived_query(None if qualifier is None else self._dialect.metadata_key(qualifier), query) + if not isinstance(inner, exp.Select): + return None + key = self._dialect.metadata_key(name) + for item in inner.expressions: + # The alias is folded from its Identifier, so quoting counts. + out = self._fold(item.args.get("alias")) if isinstance(item, exp.Alias) else self._identifier(item) + if out is not None and self._dialect.metadata_key(out) == key: + return self._trace(item.this if isinstance(item, exp.Alias) else item, inner, depth + 1) + return None + + def _derived_query(self, qualifier: Optional[str], query: exp.Expression) -> Optional[exp.Expression]: + """The query behind the derived table or CTE that ``query`` reads as + ``qualifier``, or behind its only source when there is no qualifier. + A source whose alias lists column names is not followed: the list + renames the columns by position. A CTE sees only the CTEs written + before it, as the engines resolve a non-recursive ``WITH``. In a + ``RECURSIVE`` list, a source name no earlier CTE defines leaves the + column unknown.""" + nodes: List[exp.Expression] = [] + from_ = query.args.get("from_") + if from_ is not None: + nodes.append(from_.this) + nodes.extend(j.this for j in query.args.get("joins") or []) + if qualifier is None and len(nodes) != 1: + return None + for node in nodes: + alias = node.args.get("alias") + alias_name = self._fold(alias.this) if isinstance(alias, exp.TableAlias) else None + renamed = isinstance(alias, exp.TableAlias) and bool(alias.args.get("columns")) + if isinstance(node, exp.Subquery): + if qualifier is None or (alias_name is not None and self._dialect.metadata_key(alias_name) == qualifier): + return None if renamed else node.this + elif isinstance(node, exp.Table) and isinstance(node.this, exp.Identifier): + key = self._key(node.this) + seen = key if alias_name is None else self._dialect.metadata_key(alias_name) + if qualifier is not None and seen != qualifier: + continue + if renamed: + return None + outer: Optional[exp.Expression] = query + inside: Any = None + while outer is not None: + with_ = outer.args.get("with_") + recursive = with_ is not None and bool(with_.args.get("recursive")) + for cte in (with_.expressions if with_ is not None else ()): + if cte is inside: + if recursive: + return None # PostgreSQL lets a RECURSIVE list read later CTEs + break # a CTE sees only the CTEs before it + cte_alias = cte.args.get("alias") + if isinstance(cte_alias, exp.TableAlias) and self._key(cte_alias.this) == key: + return None if cte_alias.args.get("columns") else cte.this + inside = outer.parent + outer = self._nearest_query(outer) + return None + return None + + def _note(self, gap: AnalysisGap) -> None: + if self._gap is None: + self._gap = gap diff --git a/aws_advanced_python_wrapper/encryption/sql_dialect.py b/aws_advanced_python_wrapper/encryption/sql_dialect.py index 6b28721d8..9a8e8690f 100644 --- a/aws_advanced_python_wrapper/encryption/sql_dialect.py +++ b/aws_advanced_python_wrapper/encryption/sql_dialect.py @@ -23,6 +23,7 @@ from __future__ import annotations +import string from abc import ABC, abstractmethod from contextlib import closing from typing import TYPE_CHECKING, Any, Dict, List, Mapping, Sequence @@ -59,6 +60,22 @@ def insert_returning_id(self, conn: Any, sql: str, params: Sequence[Any]) -> int ``id``.""" ... + @abstractmethod + def fold_identifier(self, name: str, quoted: bool) -> str: + """The name the server resolves an identifier written in SQL to. + ``name`` is the identifier without its quotes (doubled quotes undone) + and ``quoted`` says whether it was quoted.""" + ... + + @abstractmethod + def metadata_key(self, name: str) -> str: + """The form a table or column name is compared in when looking it up + in ``encryption_metadata``. Names with the same key share encryption + metadata: usually because the engine treats them as the same object, + but on MySQL with ``lower_case_table_names=0`` table names that differ + only in case share a key too.""" + ... + @staticmethod def for_driver_dialect(driver_dialect: DriverDialect) -> SqlDialect: code = driver_dialect.dialect_code @@ -111,6 +128,17 @@ def insert_returning_id(self, conn: Any, sql: str, params: Sequence[Any]) -> int # A connection opened with a dict-like row factory returns a mapping. return int(next(iter(row.values())) if isinstance(row, Mapping) else row[0]) + def fold_identifier(self, name: str, quoted: bool) -> str: + # PostgreSQL folds an unquoted identifier to lower case, ASCII letters + # only in a multibyte (e.g. UTF-8) database; a quoted one keeps its + # case. The result is the name in the system catalog, apart from + # PostgreSQL's truncation of names longer than 63 bytes. + return name if quoted else name.translate(_ASCII_LOWER) + + def metadata_key(self, name: str) -> str: + # Catalog names are case-sensitive: "Users" and users are two tables. + return name + class MySqlSqlDialect(SqlDialect): name = "mysql" @@ -128,6 +156,24 @@ def insert_returning_id(self, conn: Any, sql: str, params: Sequence[Any]) -> int cursor.execute(sql, params) return int(cursor.lastrowid) + def fold_identifier(self, name: str, quoted: bool) -> str: + # MySQL keeps identifiers as written (quoting only allows reserved words + # and special characters). Whether it folds table names depends on + # lower_case_table_names, which metadata_key allows for by comparing + # case-insensitively. + return name + + def metadata_key(self, name: str) -> str: + # Column names are case-insensitive in MySQL, and table names are too + # unless lower_case_table_names=0 on a case-sensitive file system, where + # two tables differing only in case would share encryption metadata. + # This agrees with the uncached lookup under the default + # (case-insensitive) collations; metadata tables created with a _bin or + # _cs collation would compare case-sensitively there. + return name.lower() + + +_ASCII_LOWER = str.maketrans(string.ascii_uppercase, string.ascii_lowercase) PG = PgSqlDialect() MYSQL = MySqlSqlDialect() diff --git a/aws_advanced_python_wrapper/encryption/sql_tokenizer.py b/aws_advanced_python_wrapper/encryption/sql_tokenizer.py new file mode 100644 index 000000000..8f505129d --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/sql_tokenizer.py @@ -0,0 +1,581 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Finds a statement's bind parameters the way its driver does. + +Both supported drivers use the ``pyformat`` paramstyle, but they do not find +placeholders the same way, and neither skips quoted literals or comments: + +* psycopg, when given parameters (even an empty sequence), treats every ``%`` + as the start of a placeholder: ``%s``/``%b``/``%t``, ``%(name)s`` (or ``b`` + / ``t``), or ``%%`` for a literal percent sign. Anything else after a ``%`` + is a ``ProgrammingError``, and positional and named placeholders cannot be + mixed. Given ``None`` it substitutes nothing. +* MySQL Connector/Python, given a non-empty list or tuple, replaces every + ``%s`` substring and nothing else (``%%`` is left alone). Given a non-empty + dict, it replaces ``%(name)s`` and turns ``%(name)%`` into ``%``. Given an + empty value it substitutes nothing, and given any other type it raises + ``ProgrammingError``. + +So the n-th placeholder found here is the n-th value the driver binds, even +when it sits inside a quoted literal or a comment. Such a placeholder is +reported as hidden: the statement's structure says nothing about which column +it fills, and the statement is almost certainly broken anyway. + +The SQL is also lexed (quotes, comments, statement separators) for what the +driver doesn't need: spotting hidden placeholders, reading +``/*@encrypt:table.column*/`` annotations, and producing a copy of the SQL a +structural parser can read, with each placeholder replaced by a named +placeholder that carries its position. + +The lexer assumes server defaults: ``standard_conforming_strings=on`` on +PostgreSQL, and backslash escapes on and ``ANSI_QUOTES`` off on MySQL. Under +other settings a literal may end somewhere else on the server. MySQL runs the +body of an executable comment (``/*! ... */``), so a statement with one is +flagged (:attr:`TokenizedSql.executable_comment`) rather than read as if the +comment were not there. The database-side HMAC trigger, not this module, +guarantees an encrypted column never holds plaintext. + +The placeholder rules are the drivers' (psycopg, MySQL Connector/Python), not +the engines': another driver for the same engine needs its own. + +This module has no third-party dependencies. +""" + +from __future__ import annotations + +import re +from bisect import bisect_right +from collections.abc import Mapping +from dataclasses import dataclass, field, replace +from enum import Enum +from typing import TYPE_CHECKING, Any, FrozenSet, List, Optional, Tuple, Union + +if TYPE_CHECKING: + from aws_advanced_python_wrapper.encryption.sql_dialect import SqlDialect + +#: Prefix of the named placeholders written into :attr:`TokenizedSql.normalized`: +#: ``:_kms_p3`` stands for the placeholder whose ordinal is 3. +NORMALIZED_PLACEHOLDER_PREFIX = "_kms_p" + + +class ParamStyle(Enum): + """How a statement's parameters were passed, which decides what its driver + treats as a placeholder.""" + + #: No parameters, or (MySQL) a type the driver refuses: nothing is + #: substituted. + NONE = "none" + #: A sequence: ``%s`` placeholders, bound by position. + POSITIONAL = "positional" + #: A mapping: ``%(name)s`` placeholders, bound by name. + NAMED = "named" + + @classmethod + def of(cls, params: Any, dialect: SqlDialect) -> ParamStyle: + """The style the driver for ``dialect`` applies to ``params``, the + second argument of ``execute``.""" + if dialect.name == "mysql": + # Connector/Python substitutes only for a non-empty dict, list or + # tuple. + if not params: + return cls.NONE + if isinstance(params, dict): + return cls.NAMED + return cls.POSITIONAL if isinstance(params, (list, tuple)) else cls.NONE + if params is None: + return cls.NONE + return cls.NAMED if isinstance(params, Mapping) else cls.POSITIONAL + + +@dataclass(frozen=True, slots=True) +class ColumnRef: + """A column a statement names, with names folded the way the engine folds + them (see :meth:`SqlDialect.fold_identifier`).""" + + column: str + #: The table, without any schema; ``None`` when the statement does not say + #: which of its tables the column belongs to. + table: Optional[str] = None + + def __str__(self) -> str: + return self.column if self.table is None else f"{self.table}.{self.column}" + + +@dataclass(frozen=True, slots=True) +class Placeholder: + """One bind parameter, in the order the driver binds them.""" + + #: Position among the statement's placeholders, from 0. + ordinal: int + #: What the driver binds here: the index into the parameter sequence, or + #: the key in the parameter mapping. A key may be used more than once. + key: Union[int, str] + #: Span of the placeholder in the original SQL. + start: int + end: int + #: Overlaps a quoted literal (including a dollar-quoted one), a quoted + #: identifier, or a comment. + hidden: bool = False + #: The column a ``/*@encrypt:...*/`` annotation directly before it names, + #: folded like any identifier. Its qualifier is not resolved yet: see + #: :attr:`StatementAnalysis.annotations` for what the analyzer makes of it. + annotation: Optional[ColumnRef] = None + #: A MySQL charset introducer written directly before it (``_binary`` in + #: ``_binary %s``, as Django renders binary values), lower-cased. Anything + #: in between, an annotation included, hides the introducer. + introducer: Optional[str] = None + + +@dataclass(frozen=True) +class TokenizedSql: + """What :func:`tokenize` found.""" + + style: ParamStyle + placeholders: Tuple[Placeholder, ...] + #: The SQL with every placeholder replaced by ``:_kms_p``, the + #: driver's ``%`` escapes resolved, and on MySQL ``REPLACE`` read as + #: ``INSERT``, statement modifiers such as ``LOW_PRIORITY`` dropped, and + #: charset introducers before a placeholder removed (see + #: :attr:`Placeholder.introducer`). Only for a structural parser; never + #: sent to the database. + normalized: str + #: The first word of each statement, upper-cased. + leading_words: Tuple[str, ...] + #: Which of the keywords that matter for spotting a write (``INSERT``, + #: ``UPDATE``, ``REPLACE``, ``MERGE``, ``UPSERT``, ``COPY``, ``FROM``, + #: ``EXECUTE``, ``LOAD``) appear outside literals, comments and + #: placeholders, or inside a MySQL executable comment. + keywords: FrozenSet[str] + #: A quoted literal, quoted identifier, or comment runs to the end of the + #: text. + unterminated: bool = False + #: MySQL only: a ``/*! ... */`` (or MariaDB ``/*M! ... */``) comment, whose + #: body the server runs. + executable_comment: bool = False + #: Why the driver will reject the placeholders (an unknown ``%`` sequence, + #: positional and named placeholders mixed, or a style the parameters + #: don't have); ``None`` when it won't. + driver_error: Optional[str] = None + #: ``/*@encrypt:...*/`` comments that annotate no placeholder or can't be + #: read, as written. A caller may want to warn about them. + stray_annotations: Tuple[str, ...] = () + + @property + def has_hidden_placeholders(self) -> bool: + return any(p.hidden for p in self.placeholders) + + +_KEYWORDS = frozenset({"INSERT", "UPDATE", "REPLACE", "MERGE", "UPSERT", "COPY", "FROM", "EXECUTE", "LOAD"}) + +# MySQL statement modifiers between the keyword and the table. They change how +# a statement runs and leave what it writes alone. The structural parser reads +# "UPDATE LOW_PRIORITY users" as a table named LOW_PRIORITY aliased users, so +# they are dropped from the normalized copy. All are reserved words except +# QUICK, which can only follow DELETE. +_MYSQL_MODIFIERS = { + "INSERT": frozenset({"LOW_PRIORITY", "HIGH_PRIORITY", "DELAYED", "IGNORE"}), + "REPLACE": frozenset({"LOW_PRIORITY", "DELAYED"}), + "UPDATE": frozenset({"LOW_PRIORITY", "IGNORE"}), + "DELETE": frozenset({"LOW_PRIORITY", "QUICK", "IGNORE"}), +} + +# ---- lexers ---- +# +# Alternatives are tried in order at each token boundary. The ``*_end`` groups +# capture a closing quote, empty when the literal runs to the end of the text. + +_PG_TOKEN = re.compile(r""" + (?P--[^\n]*) + | (?P/\*) + | (?P[Ee]'(?:[^'\\]|\\.|'')*(?P'?)) + | (?P'(?:[^']|'')*(?P'?)) + | (?P"(?:[^"]|"")*(?P"?)) + | (?P\$\d+) + | (?P\$(?:[^\W\d]\w*)?\$) + | (?P[^\W\d][\w$]*) + | (?P\d[\w.]*) + | (?P;) + | (?P\s+) + | (?P[^\w\s'"$;/\-]+|.) +""", re.VERBOSE | re.DOTALL) + +_MYSQL_TOKEN = re.compile(r""" + (?P(?:\#|--(?=\s|\Z))[^\n]*) + | (?P/\*.*?(?P\*/|\Z)) + | (?P'(?:[^'\\]|\\.|'')*(?P'?)) + | (?P"(?:[^"\\]|\\.|"")*(?P"?)) + | (?P`(?:[^`]|``)*(?P`?)) + | (?P[^\W\d][\w$]*) + | (?P\d[\w.]*) + | (?P;) + | (?P\s+) + | (?P[^\w\s'"`;/\-\#]+|.) +""", re.VERBOSE | re.DOTALL) + +_QUOTED_KINDS = frozenset({"estring", "string", "dqstring", "ident"}) + +# A block comment that is an annotation: /*@encrypt:*/, with no space +# after the opening delimiter. is dot-separated parts, table.column or a +# bare column; leading parts (a schema) are ignored. A part is word characters, +# or a name quoted with the engine's identifier quote. Every [\w.]+ reference +# that ends in a column is accepted, empty parts included: ".c" is the bare +# column c and "t..c" is t.c. A reference that ends in "." names no column and +# is reported as stray. +_ANNOTATION = re.compile(r"/\*@encrypt:(?P.*?)\*/\Z", re.DOTALL) +_PG_REF_PART = re.compile(r'(?P\w+)|"(?P(?:[^"]|"")+)"') +_MYSQL_REF_PART = re.compile(r"(?P\w+)|`(?P(?:[^`]|``)+)`") + +# A MySQL charset introducer (_binary, _utf8mb4, ...) and the space after it, +# directly before a placeholder. +_INTRODUCER = re.compile(r"(?[A-Za-z0-9]+)\s*\Z") +_MYSQL_CHARSETS = frozenset({ + "armscii8", "ascii", "big5", "binary", "cp1250", "cp1251", "cp1256", "cp1257", "cp850", "cp852", "cp866", + "cp932", "dec8", "eucjpms", "euckr", "gb18030", "gb2312", "gbk", "geostd8", "greek", "hebrew", "hp8", + "keybcs2", "koi8r", "koi8u", "latin1", "latin2", "latin5", "latin7", "macce", "macroman", "sjis", "swe7", + "tis620", "ucs2", "ujis", "utf16", "utf16le", "utf32", "utf8", "utf8mb3", "utf8mb4", +}) +_WORD = re.compile(r"[^\W\d][\w$]*") +_COMMENT_DELIMITER = re.compile(r"/\*|\*/") + +# The drivers' own placeholder patterns. +_PSYCOPG_PLACEHOLDER = re.compile(r"%(?:\(([^)]+)\).|.)") # no DOTALL, as in psycopg +_MYSQL_POSITIONAL = re.compile(r"%s") +_MYSQL_NAMED = re.compile(r"%\((?P[^)]+)\)(?P[diouxXeEfFgGcrs%])") + +_Edit = Tuple[int, int, str] +_FAR = 1 << 62 # past any string offset + + +@dataclass +class _Lexed: + hidden_spans: List[Tuple[int, int]] # literals, quoted identifiers, comments; sorted + block_comments: List[Tuple[int, int]] + # (UPPER word, start, end); "" stands for any other significant token, so + # that two words with something between them are not taken as adjacent. + words: List[Tuple[str, int, int]] + separators: List[int] # offsets of the ";" between statements + unterminated: bool = False + executable_comment: bool = False + # Words inside MySQL executable comments, which the server runs. + executable_words: List[str] = field(default_factory=list) + + +def tokenize(sql: str, dialect: SqlDialect, style: ParamStyle) -> TokenizedSql: + """Find the placeholders in ``sql`` as the driver for ``dialect`` does when + given parameters of ``style``. + + :raises TypeError: if ``sql`` is not a ``str``. + """ + if not isinstance(sql, str): + raise TypeError(f"sql must be a str, not {type(sql).__name__}") + mysql = dialect.name == "mysql" + lexed = _lex(sql, _MYSQL_TOKEN if mysql else _PG_TOKEN, mysql=mysql) + + edits: List[_Edit] = [] + if mysql: + placeholders, driver_error = _mysql_placeholders(sql, style, lexed, edits) + placeholders = _attach_introducers(sql, lexed, placeholders, edits) + else: + placeholders, driver_error = _psycopg_placeholders(sql, style, lexed, edits) + + stray: List[str] = [] + if "@encrypt:" in sql: + placeholders = _attach_annotations(sql, dialect, lexed, placeholders, stray) + + # A word inside a placeholder (the s of %s, a %(name)s key) is not SQL. + words = _outside(lexed.words, placeholders) + bounds = _statement_bounds(words, lexed.separators) + if mysql: + edits.extend(_mysql_rewrites(words, bounds)) + + keywords = {w for w, _, _ in words if w in _KEYWORDS} + keywords.update(w for w in lexed.executable_words if w in _KEYWORDS) + return TokenizedSql( + style=style, + placeholders=tuple(placeholders), + normalized=_apply(sql, edits), + leading_words=_leading_words(words, bounds), + keywords=frozenset(keywords), + unterminated=lexed.unterminated, + executable_comment=lexed.executable_comment, + driver_error=driver_error, + stray_annotations=tuple(stray), + ) + + +def normalized_ordinal(name: Optional[str]) -> Optional[int]: + """The ordinal of a placeholder in the normalized SQL, from the name a + parser reports for it (``_kms_p3`` -> 3); ``None`` for any other name.""" + if not name or not name.startswith(NORMALIZED_PLACEHOLDER_PREFIX): + return None + digits = name[len(NORMALIZED_PLACEHOLDER_PREFIX):] + return int(digits) if digits.isascii() and digits.isdigit() else None + + +# ---- driver placeholders ---- +# +# The error texts never quote the SQL: a rejected "%(...)x" sequence can sit +# inside a literal holding a value. + +def _psycopg_placeholders(sql: str, style: ParamStyle, lexed: _Lexed, + edits: List[_Edit]) -> Tuple[List[Placeholder], Optional[str]]: + if style is ParamStyle.NONE: + return [], None + found: List[Placeholder] = [] + error: Optional[str] = None + named = positional = False + for m in _PSYCOPG_PLACEHOLDER.finditer(sql): + text = m.group(0) + if text == "%%": + edits.append((m.start(), m.end(), "%")) + continue + if text == "%(" or text[-1] not in "sbt": + error = error or f"psycopg rejects the % sequence at offset {m.start()}" + continue + name = m.group(1) + named, positional = named or name is not None, positional or name is None + ordinal = len(found) + found.append(_placeholder(ordinal, ordinal if name is None else name, m, lexed)) + edits.append(_placeholder_edit(ordinal, m)) + if named and positional: + error = error or "positional and named placeholders are mixed" + elif (named or positional) and named != (style is ParamStyle.NAMED): + error = error or f"the placeholders don't match {style.value} parameters" + return found, error + + +def _mysql_placeholders(sql: str, style: ParamStyle, lexed: _Lexed, + edits: List[_Edit]) -> Tuple[List[Placeholder], Optional[str]]: + found: List[Placeholder] = [] + error: Optional[str] = None + if style is ParamStyle.POSITIONAL: + for m in _MYSQL_POSITIONAL.finditer(sql): + ordinal = len(found) + found.append(_placeholder(ordinal, ordinal, m, lexed)) + edits.append(_placeholder_edit(ordinal, m)) + elif style is ParamStyle.NAMED: + for m in _MYSQL_NAMED.finditer(sql): + conv = m.group("conv") + if conv == "%": + edits.append((m.start(), m.end(), "%")) + elif conv != "s": + error = error or f"MySQL Connector/Python rejects the %(...) conversion at offset {m.start()}" + else: + ordinal = len(found) + found.append(_placeholder(ordinal, m.group("key"), m, lexed)) + edits.append(_placeholder_edit(ordinal, m)) + return found, error + + +def _placeholder(ordinal: int, key: Union[int, str], m: re.Match, lexed: _Lexed) -> Placeholder: + return Placeholder(ordinal=ordinal, key=key, start=m.start(), end=m.end(), + hidden=_overlaps(lexed.hidden_spans, m.start(), m.end())) + + +def _placeholder_edit(ordinal: int, m: re.Match) -> _Edit: + # Padded so the placeholder cannot fuse with a neighboring token. + return m.start(), m.end(), f" :{NORMALIZED_PLACEHOLDER_PREFIX}{ordinal} " + + +def _overlaps(spans: List[Tuple[int, int]], start: int, end: int) -> bool: + i = bisect_right(spans, (start, _FAR)) - 1 + if i >= 0 and spans[i][1] > start: + return True + return i + 1 < len(spans) and spans[i + 1][0] < end + + +def _attach_introducers(sql: str, lexed: _Lexed, placeholders: List[Placeholder], + edits: List[_Edit]) -> List[Placeholder]: + # "_binary %s" binds the value as a binary string, which is what a + # ciphertext is. The parser misreads the pair (as an alias, or not at all), + # so the introducer is recorded on the placeholder and removed from the + # normalized copy. Only whitespace may separate the two. + if "_" not in sql: + return placeholders + result = list(placeholders) + for i, p in enumerate(placeholders): + if p.hidden: + continue + m = _INTRODUCER.search(sql, max(0, p.start - 64), p.start) + if m is None or m.group("charset").lower() not in _MYSQL_CHARSETS \ + or _overlaps(lexed.hidden_spans, m.start(), m.end()): + continue + result[i] = replace(p, introducer=f"_{m.group('charset').lower()}") + edits.append((m.start(), m.end(), " ")) + return result + + +# ---- annotations ---- + +def _attach_annotations(sql: str, dialect: SqlDialect, lexed: _Lexed, + placeholders: List[Placeholder], stray: List[str]) -> List[Placeholder]: + by_start = {p.start: i for i, p in enumerate(placeholders)} + result = list(placeholders) + for start, end in lexed.block_comments: + if not sql.startswith("/*@encrypt:", start): + continue + m = _ANNOTATION.match(sql, start, end) + ref = None if m is None else _annotation_ref(m.group("ref"), dialect) + nxt = end + while nxt < len(sql) and sql[nxt].isspace(): + nxt += 1 + index = by_start.get(nxt) + if ref is None or index is None or result[index].hidden: + stray.append(sql[start:end]) + else: + result[index] = replace(result[index], annotation=ref) + return result + + +def _annotation_ref(text: str, dialect: SqlDialect) -> Optional[ColumnRef]: + mysql = dialect.name == "mysql" + part_re, quote = (_MYSQL_REF_PART, "`") if mysql else (_PG_REF_PART, '"') + parts: List[str] = [] + pos = 0 + while pos <= len(text): + if text.startswith(".", pos) or pos == len(text): + parts.append("") # an empty part, as in ".c" or "t..c" + else: + m = part_re.match(text, pos) + if m is None: + return None + if m.group("word") is not None: + parts.append(dialect.fold_identifier(m.group("word"), quoted=False)) + else: + parts.append(dialect.fold_identifier(m.group("quoted").replace(quote * 2, quote), quoted=True)) + pos = m.end() + if pos < len(text) and text[pos] != ".": + return None + pos += 1 + if not parts[-1]: + return None # no column ("t.") + # The metadata has no schema: the table is the nearest named part before + # the column, and anything before that is ignored. + table = next((part for part in reversed(parts[:-1]) if part), None) + return ColumnRef(column=parts[-1], table=table) + + +# ---- lexing ---- + +def _lex(sql: str, token_re: re.Pattern, mysql: bool) -> _Lexed: + lexed = _Lexed([], [], [], []) + pos, n = 0, len(sql) + while pos < n: + m = token_re.match(sql, pos) + assert m is not None # "other" matches any character + kind, end = m.lastgroup, m.end() + if kind == "block_comment": + if not mysql: + end = _nested_comment_end(sql, pos) + elif not m.group("block_comment_end"): + lexed.unterminated = True + if end < 0: + end, lexed.unterminated = n, True + if mysql and (sql.startswith("/*!", pos) or sql.startswith("/*M!", pos)): + lexed.executable_comment = True + lexed.executable_words.extend(w.upper() for w in _WORD.findall(sql, pos, end)) + lexed.block_comments.append((pos, end)) + lexed.hidden_spans.append((pos, end)) + elif kind == "dollar": + close = sql.find(m.group(0), end) + if close < 0: + end, lexed.unterminated = n, True + else: + end = close + len(m.group(0)) + lexed.hidden_spans.append((pos, end)) + elif kind in _QUOTED_KINDS: + if not m.group(f"{kind}_end"): + lexed.unterminated = True + lexed.hidden_spans.append((pos, end)) + elif kind == "line_comment": + lexed.hidden_spans.append((pos, end)) + elif kind == "word": + lexed.words.append((m.group(0).upper(), pos, end)) + elif kind == "semicolon": + lexed.separators.append(pos) + elif kind != "space": + lexed.words.append(("", pos, end)) + pos = end + return lexed + + +def _nested_comment_end(sql: str, start: int) -> int: + # PostgreSQL block comments nest. Returns -1 when unterminated. One pass + # over the delimiters, so deep nesting stays linear. + depth = 0 + for m in _COMMENT_DELIMITER.finditer(sql, start): + depth += 1 if m.group(0) == "/*" else -1 + if depth == 0: + return m.end() + return -1 + + +def _outside(words: List[Tuple[str, int, int]], placeholders: List[Placeholder]) -> List[Tuple[str, int, int]]: + if not placeholders: + return words + spans = [(p.start, p.end) for p in placeholders] + return [w for w in words if not _overlaps(spans, w[1], w[2])] + + +def _statement_bounds(words: List[Tuple[str, int, int]], separators: List[int]) -> List[Tuple[int, int]]: + """(begin, end) indexes into ``words`` of each non-empty statement.""" + bounds: List[Tuple[int, int]] = [] + begin = 0 + for separator in separators + [_FAR]: + end = begin + while end < len(words) and words[end][1] < separator: + end += 1 + if end > begin: + bounds.append((begin, end)) + begin = end + return bounds + + +def _leading_words(words: List[Tuple[str, int, int]], bounds: List[Tuple[int, int]]) -> Tuple[str, ...]: + # A statement's first word, skipping leading punctuation such as "("; "" + # when it has no word at all. + return tuple(next((w for w, _, _ in words[begin:end] if w), "") for begin, end in bounds) + + +def _mysql_rewrites(words: List[Tuple[str, int, int]], bounds: List[Tuple[int, int]]) -> List[_Edit]: + leading = {begin for begin, _ in bounds} + edits: List[_Edit] = [] + for i, (word, start, end) in enumerate(words): + modifiers = _MYSQL_MODIFIERS.get(word) + if modifiers is None: + continue + if word == "REPLACE": + # Only the statement keyword, not the REPLACE() string function. + if i not in leading: + continue + edits.append((start, end, "INSERT")) + j = i + 1 + while j < len(words) and words[j][0] in modifiers: + edits.append((words[j][1], words[j][2], " ")) + j += 1 + return edits + + +def _apply(sql: str, edits: List[_Edit]) -> str: + if not edits: + return sql + out: List[str] = [] + pos = 0 + for start, end, text in sorted(edits): + out.append(sql[pos:start]) + out.append(text) + pos = end + out.append(sql[pos:]) + return "".join(out) diff --git a/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties b/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties index a30656b4c..a56e4a847 100644 --- a/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties +++ b/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties @@ -575,6 +575,7 @@ KeyManager.StoreKeyMetadataFailed=[KeyManager] Failed to store key metadata ({}) KeyManager.TouchKeyFailed=[KeyManager] Failed to update last_used_at for key {}: {} KeyManager.UnauthorizedMasterKey=[KeyManager] Master key {} is not listed in {}; refusing to use it. KeyManager.WrongDataKeyLength=[KeyManager] KMS returned a {}-byte data key for key spec {}, which {} cannot use. +MetadataManager.InvalidName=[MetadataManager] encryption_metadata.{} must be UTF-8 text; the driver returned a value of type {} that is not. MetadataManager.LoadFailed=[MetadataManager] Failed to read the kms_encryption metadata: {} MetadataManager.RefreshFailed=[MetadataManager] Failed to refresh the kms_encryption metadata cache: {} MetadataManager.Refreshed=[MetadataManager] Refreshed the kms_encryption metadata cache with {} column configuration(s). diff --git a/poetry.lock b/poetry.lock index ab2f45c8c..026a64875 100644 --- a/poetry.lock +++ b/poetry.lock @@ -3328,6 +3328,24 @@ postgresql-psycopgbinary = ["psycopg[binary] (>=3.0.7)"] pymysql = ["pymysql"] sqlcipher = ["sqlcipher3_binary"] +[[package]] +name = "sqlglot" +version = "30.25.0" +description = "An easily customizable SQL parser and transpiler" +optional = false +python-versions = ">=3.9" +groups = ["main", "dev"] +files = [ + {file = "sqlglot-30.25.0-py3-none-any.whl", hash = "sha256:7d5a292d5f61b7fc860e65a8fa41083c726db0e27fb6efb224cca63c3a5980f7"}, + {file = "sqlglot-30.25.0.tar.gz", hash = "sha256:d2d6e4d4865a210b1e33a801b105a6782ef12280cc2b6d0969bdc2634aef427a"}, +] +markers = {main = "extra == \"encryption\""} + +[package.extras] +c = ["sqlglotc (==30.25.0) ; python_version >= \"3.10\""] +dev = ["duckdb (>=0.6)", "mypy (>=2.4.0) ; python_version >= \"3.10\"", "mypy ; python_version < \"3.10\"", "pandas", "pandas-stubs", "pdoc", "pre-commit", "pyperf", "python-dateutil", "pytz", "ruff (==0.15.6)", "setuptools_scm", "types-python-dateutil", "types-pytz", "typing_extensions"] +rs = ["sqlglotc (==30.25.0) ; python_version >= \"3.10\"", "sqlglotrs (==0.13.0)"] + [[package]] name = "sqlparse" version = "0.6.0" @@ -4183,9 +4201,9 @@ multidict = ">=4.0" propcache = ">=0.2.1" [extras] -encryption = ["cryptography"] +encryption = ["cryptography", "sqlglot"] [metadata] lock-version = "2.1" python-versions = "^3.10.0" -content-hash = "7cd044243bd145b872f30416b3db964cb7cfe39d37c44ad1a3df05b1abe9a88e" +content-hash = "511c6be5d88dd7b486441f4c4099f84b00bfdb3cbb91dec4e064c60182ac5e16" diff --git a/pyproject.toml b/pyproject.toml index 48ad28a84..03d70d7ad 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -52,10 +52,16 @@ requests = "^2.33.1" # pip install "aws-advanced-python-wrapper[encryption]" # The import is lazy as well: nothing on the core import path imports it. cryptography = { version = ">=42.0.0", optional = true } +# The plugin's SQL analysis (which bind parameter fills which column) parses +# statements with this pure-Python parser. Also only in the `encryption` extra +# and imported lazily. Capped below the next major: its expression tree changes +# shape between majors, and the analysis walks that tree. The floor is the +# oldest release the analysis tests pass on. +sqlglot = { version = ">=30.14.0,<31.0.0", optional = true } [tool.poetry.extras] # `pip install "aws-advanced-python-wrapper[encryption]"` to use the KMS Encryption plugin. -encryption = ["cryptography"] +encryption = ["cryptography", "sqlglot"] [tool.poetry.group.dev.dependencies] mypy = "^1.20.2" @@ -76,6 +82,7 @@ types_aws_xray_sdk = "^2.13.0" # Non-optional in the dev group so the encryption unit tests run without needing # to install the `encryption` extra explicitly. cryptography = ">=42.0.0" +sqlglot = ">=30.14.0,<31.0.0" [tool.poetry.group.test.dependencies] boto3 = "^1.42.95" diff --git a/tests/unit/test_encryption_import_guard.py b/tests/unit/test_encryption_import_guard.py index 666917176..5a8119599 100644 --- a/tests/unit/test_encryption_import_guard.py +++ b/tests/unit/test_encryption_import_guard.py @@ -12,11 +12,13 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""``cryptography`` is an optional extra (``encryption``). The wrapper must -import without it, and only the module that encrypts may need it. +"""``cryptography`` and ``sqlglot`` are installed only with the optional +``encryption`` extra. The wrapper must import without them; only the module +that encrypts needs ``cryptography`` and only the SQL analyzer needs +``sqlglot``. -Each check runs in a fresh interpreter, most with ``cryptography`` blocked, -since the test environment always has it installed.""" +Each check runs in a fresh interpreter, most with both packages blocked, +since the test environment always has them installed.""" import subprocess import sys @@ -29,7 +31,7 @@ class _Block: def find_spec(self, name, path=None, target=None): - if name == "cryptography" or name.startswith("cryptography."): + if name.partition(".")[0] in ("cryptography", "sqlglot"): raise ModuleNotFoundError(f"No module named {name!r}", name=name) return None @@ -63,11 +65,14 @@ def _run(code: str, block: bool = True) -> subprocess.CompletedProcess: "aws_advanced_python_wrapper.encryption.key_manager", "aws_advanced_python_wrapper.encryption.metadata_manager", "aws_advanced_python_wrapper.encryption.key_management_utility", + # Placeholder scanning is dependency-free; only the structural parse + # needs sqlglot. + "aws_advanced_python_wrapper.encryption.sql_tokenizer", ] @pytest.mark.parametrize("module", _CORE_MODULES + _KEY_LAYER_MODULES) -def test_imports_without_cryptography(module): +def test_imports_without_cryptography_or_sqlglot(module): result = _run(f""" import importlib importlib.import_module({module!r}) @@ -76,13 +81,14 @@ def test_imports_without_cryptography(module): @pytest.mark.parametrize("module", _CORE_MODULES + _KEY_LAYER_MODULES) -def test_does_not_load_cryptography_even_when_installed(module): - # With cryptography available, importing these must still not load it, - # so users who never encrypt don't pay its import cost. +def test_does_not_load_the_extra_even_when_installed(module): + # With the packages available, importing these must still not load them, + # so users who never encrypt don't pay their import cost. result = _run(f""" import importlib importlib.import_module({module!r}) assert "cryptography" not in sys.modules, "cryptography was imported" + assert "sqlglot" not in sys.modules, "sqlglot was imported" """, block=False) assert result.returncode == 0, result.stderr @@ -100,6 +106,20 @@ def test_encryption_service_names_the_extra_when_cryptography_is_missing(): assert "aws-advanced-python-wrapper[encryption]" in result.stdout +def test_sql_analyzer_names_the_extra_when_sqlglot_is_missing(): + result = _run(""" + try: + import aws_advanced_python_wrapper.encryption.sql_analyzer + except ImportError as e: + print(e) + else: + raise SystemExit("imported without sqlglot") + """) + assert result.returncode == 0, result.stderr + assert "'sqlglot'" in result.stdout + assert "aws-advanced-python-wrapper[encryption]" in result.stdout + + _BROKEN = textwrap.dedent(""" import sys @@ -130,3 +150,17 @@ def test_a_broken_cryptography_is_not_reported_as_missing(error): assert result.returncode == 0, result.stderr assert "aws-advanced-python-wrapper[encryption]" not in result.stdout assert ("DLL load failed" in result.stdout) or ("_cffi_backend" in result.stdout) + + +def test_a_broken_sqlglot_is_not_reported_as_missing(): + code = _BROKEN.replace('"cryptography"', '"sqlglot"').format( + error='ModuleNotFoundError("No module named \'sqlglotc\'", name="sqlglotc")') + textwrap.dedent(""" + try: + import aws_advanced_python_wrapper.encryption.sql_analyzer + except ImportError as e: + print(e) + """) + result = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, timeout=120) + assert result.returncode == 0, result.stderr + assert "aws-advanced-python-wrapper[encryption]" not in result.stdout + assert "sqlglotc" in result.stdout diff --git a/tests/unit/test_metadata_manager.py b/tests/unit/test_metadata_manager.py index 70a53b99d..768a516a1 100644 --- a/tests/unit/test_metadata_manager.py +++ b/tests/unit/test_metadata_manager.py @@ -515,3 +515,63 @@ def test_failed_reload_names_the_lookup(clock): with pytest.raises(MetadataError) as err: mm.column_config("users", "ssn") assert (err.value.table_name, err.value.column_name) == ("users", "ssn") + + +# ---- name matching ---- + +def test_postgresql_lookups_are_exact(clock): + # Names are stored as the catalog has them; "Users" and users differ. + db = FakeDb([row("users", "ssn"), row("Users", "SSN", 2)]) + mm = MetadataManager(db, PG, config()) + mm.start() + assert mm.column_config("users", "ssn").key_id == 1 + assert mm.column_config("Users", "SSN").key_id == 2 + assert mm.column_config("USERS", "ssn") is None + assert [c.key_id for c in mm.table_configs("Users")] == [2] + + +def test_mysql_lookups_ignore_case(clock): + # MySQL compares these names case-insensitively, as the uncached query's + # WHERE does under the metadata table's collation. + db = FakeDb([row("Users", "SSN")]) + mm = MetadataManager(db, MYSQL, config()) + mm.start() + found = mm.column_config("users", "ssn") + assert found is not None and (found.table_name, found.column_name) == ("Users", "SSN") + assert mm.is_column_encrypted("USERS", "Ssn") + assert [c.column_name for c in mm.table_configs("users")] == ["SSN"] + assert [c.column_name for c in mm.table_configs("USERS")] == ["SSN"] + assert db.opened == 1 # all from the cache + + +def test_load_metadata_keeps_the_stored_names(): + db = FakeDb([row("Users", "SSN")]) + assert list(MetadataManager(db, MYSQL, config()).load_metadata()) == [("Users", "SSN")] + + +@pytest.mark.parametrize("raw", [b"users", bytearray(b"users"), memoryview(b"users")]) +def test_bytes_names_are_decoded(clock, raw): + # psycopg on a SQL_ASCII database, or Connector/Python with + # use_unicode=False, returns text as bytes. Undecoded, the snapshot would + # be keyed by bytes and no str lookup would find the encrypted column. + db = FakeDb([row(raw, b"ssn")]) + mm = MetadataManager(db, PG, config()) + mm.start() + assert mm.is_column_encrypted("users", "ssn") + assert mm.column_config("users", "ssn").table_name == "users" + + +@pytest.mark.parametrize("raw", [b"\xff\xfe", 42, None]) +def test_names_that_are_not_text_are_refused(clock, raw): + db = FakeDb([row(raw, "ssn")]) + mm = MetadataManager(db, PG, config()) + with pytest.raises(MetadataError, match="table_name") as info: + mm.start() + assert info.value.__context__ is None + + +def test_names_that_are_not_text_are_refused_on_an_uncached_lookup(): + db = FakeDb([row("users", 7)]) + mm = MetadataManager(db, PG, config(metadata_cache_enabled=False)) + with pytest.raises(MetadataError, match="column_name"): + mm.column_config("users", 7) # type: ignore[arg-type] diff --git a/tests/unit/test_sql_analyzer.py b/tests/unit/test_sql_analyzer.py new file mode 100644 index 000000000..89250d59d --- /dev/null +++ b/tests/unit/test_sql_analyzer.py @@ -0,0 +1,1815 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import dataclasses +import logging +import sys +import threading + +import pytest +import sqlglot +from sqlglot import exp + +from aws_advanced_python_wrapper.encryption import sql_analyzer +from aws_advanced_python_wrapper.encryption.sql_analyzer import (AnalysisGap, + StatementKind, + TableRef, + analyze) +from aws_advanced_python_wrapper.encryption.sql_dialect import MYSQL, PG +from aws_advanced_python_wrapper.encryption.sql_tokenizer import (ColumnRef, + ParamStyle, + tokenize) + + +@pytest.fixture(autouse=True) +def _fresh_cache(): + # The analysis cache is process-wide: without this a test can pass on an + # earlier test's cached result instead of the code path it names. + sql_analyzer._cached_analysis.cache_clear() + yield + sql_analyzer._cached_analysis.cache_clear() + + +BOTH = pytest.mark.parametrize("dialect", [PG, MYSQL], ids=["pg", "mysql"]) +P = (1,) # positional parameters +N = {"x": 1} # named parameters + + +def assigned(a): + return [(u.ordinal, str(u.column)) for u in a.assignments] + + +def compared(a): + return [(u.ordinal, str(u.column)) for u in a.comparisons] + + +def unbound(a): + return [str(c) for c in a.unbound_writes] + + +def names(tables): + return [str(t) for t in tables] + + +def safety(sql, dialect): + return [u.safe for u in analyze(sql, dialect, P).comparisons] + + +def on(both=(), pg=(), mysql=()): + """Parametrizes ``dialect, sql``: each of ``both`` on PostgreSQL and on + MySQL, then each of ``pg`` and ``mysql`` on its own dialect.""" + cases = [(d, s) for s in both for d in (PG, MYSQL)] + [(PG, s) for s in pg] + [(MYSQL, s) for s in mysql] + return pytest.mark.parametrize("dialect, sql", cases, ids=[f"{d.name}: {s}" for d, s in cases]) + + +class TestInsert: + @BOTH + def test_columns_pair_with_their_placeholders(self, dialect): + a = analyze("INSERT INTO users (name, ssn) VALUES (%s, %s)", dialect, P) + assert a.kind is StatementKind.INSERT and a.writes and a.complete + assert assigned(a) == [(0, "users.name"), (1, "users.ssn")] + assert names(a.written_tables) == ["users"] + assert a.parameter_columns() == {0: ColumnRef("name", "users"), 1: ColumnRef("ssn", "users")} + + @BOTH + def test_multi_row_values(self, dialect): + a = analyze("INSERT INTO users (name, ssn) VALUES (%s, %s), (%s, %s)", dialect, P) + assert assigned(a) == [(0, "users.name"), (1, "users.ssn"), (2, "users.name"), (3, "users.ssn")] + + @BOTH + def test_named_placeholders(self, dialect): + a = analyze("INSERT INTO users (name, ssn) VALUES (%(n)s, %(s)s)", dialect, N) + pairs = [(u.placeholder.key, str(u.column)) for u in a.assignments] + assert pairs == [("n", "users.name"), ("s", "users.ssn")] + + @BOTH + def test_expression_literal_and_default_are_unbound(self, dialect): + a = analyze("INSERT INTO users (a, b, c, d) VALUES (lower(%s), 'x', DEFAULT, %s)", dialect, P) + assert assigned(a) == [(1, "users.d")] + assert unbound(a) == ["users.a", "users.b", "users.c"] + assert a.complete + + @BOTH + def test_null_needs_no_encryption(self, dialect): + a = analyze("INSERT INTO users (a, b) VALUES (%s, NULL)", dialect, P) + assert assigned(a) == [(0, "users.a")] + assert unbound(a) == [] + + @BOTH + def test_casts_are_reported(self, dialect): + sql = ("INSERT INTO users (a, b) VALUES (%s::VARCHAR, CAST(%s AS BINARY))" if dialect is PG + else "INSERT INTO users (a, b) VALUES (CAST(%s AS CHAR), CAST(%s AS BINARY))") + a = analyze(sql, dialect, P) + assert assigned(a) == [(0, "users.a"), (1, "users.b")] + assert all(u.casts for u in a.assignments) + + def test_casts_are_outermost_first(self): + a = analyze("INSERT INTO users (a) VALUES (CAST(%s::text AS bytea))", PG, P) + assert a.assignments[0].casts == ("VARBINARY", "TEXT") + + @BOTH + def test_no_column_list(self, dialect): + a = analyze("INSERT INTO users VALUES (%s, %s)", dialect, P) + assert a.writes and a.gap is AnalysisGap.NO_COLUMN_LIST + assert assigned(a) == [] + + def test_default_values(self): + assert analyze("INSERT INTO users DEFAULT VALUES", PG).gap is AnalysisGap.NO_COLUMN_LIST + + @BOTH + def test_insert_select(self, dialect): + a = analyze("INSERT INTO users (name, ssn) SELECT name, ssn FROM staging WHERE id = %s", dialect, P) + assert a.gap is AnalysisGap.VALUES_FROM_QUERY + assert assigned(a) == [] + assert compared(a) == [(0, "staging.id")] + assert names(a.tables) == ["users", "staging"] and names(a.written_tables) == ["users"] + + @BOTH + def test_row_length_mismatch(self, dialect): + assert analyze("INSERT INTO users (a, b) VALUES (%s)", dialect, P).gap is AnalysisGap.ROW_LENGTH_MISMATCH + + def test_schema_qualified_table(self): + a = analyze("INSERT INTO app.users (ssn) VALUES (%s)", PG, P) + assert a.written_tables == (TableRef("users", "app"),) + assert assigned(a) == [(0, "users.ssn")] + + def test_alias_with_column_list(self): + a = analyze("INSERT INTO users AS u (ssn) VALUES (%s)", PG, P) + assert assigned(a) == [(0, "users.ssn")] + + def test_returning_columns(self): + a = analyze("INSERT INTO users (ssn) VALUES (%s) RETURNING id, ssn AS s, 1", PG, P) + assert a.result_columns == (ColumnRef("id", "users"), ColumnRef("ssn", "users"), None) + + +class TestUpsert: + def test_on_conflict_assignments(self): + a = analyze("INSERT INTO users (name, ssn) VALUES (%s, %s) " + "ON CONFLICT (id) DO UPDATE SET ssn = %s, note = 'x' WHERE users.age > %s", PG, P) + assert assigned(a) == [(0, "users.name"), (1, "users.ssn"), (2, "users.ssn")] + assert unbound(a) == ["users.note"] + assert compared(a) == [(3, "users.age")] + + def test_excluded_copy_of_the_same_column_is_not_a_write(self): + a = analyze("INSERT INTO users (ssn) VALUES (%s) ON CONFLICT (id) DO UPDATE SET ssn = EXCLUDED.ssn", + PG, P) + assert unbound(a) == [] + + def test_excluded_copy_of_another_column_is(self): + a = analyze("INSERT INTO users (name, ssn) VALUES (%s, %s) " + "ON CONFLICT (id) DO UPDATE SET ssn = EXCLUDED.name", PG, P) + assert unbound(a) == ["users.ssn"] + + def test_on_conflict_do_nothing(self): + a = analyze("INSERT INTO users (ssn) VALUES (%s) ON CONFLICT DO NOTHING", PG, P) + assert assigned(a) == [(0, "users.ssn")] and a.complete + + def test_on_duplicate_key_update(self): + a = analyze("INSERT INTO users (name, ssn) VALUES (%s, %s) " + "ON DUPLICATE KEY UPDATE ssn = %s, name = VALUES(name), note = VALUES(ssn)", MYSQL, P) + assert assigned(a) == [(0, "users.name"), (1, "users.ssn"), (2, "users.ssn")] + assert unbound(a) == ["users.note"] + + def test_on_duplicate_key_update_with_row_alias(self): + a = analyze("INSERT INTO users (name, ssn) VALUES (%s, %s) AS new " + "ON DUPLICATE KEY UPDATE ssn = new.ssn, name = new.ssn", MYSQL, P) + assert unbound(a) == ["users.name"] + + def test_replace(self): + a = analyze("REPLACE INTO users (name, ssn) VALUES (%s, %s)", MYSQL, P) + assert a.kind is StatementKind.INSERT + assert assigned(a) == [(0, "users.name"), (1, "users.ssn")] + + def test_insert_set_form(self): + a = analyze("INSERT IGNORE INTO users SET name = %s, ssn = %s, note = NULL", MYSQL, P) + assert assigned(a) == [(0, "users.name"), (1, "users.ssn")] + + @pytest.mark.parametrize("sql", [ + "INSERT LOW_PRIORITY INTO users (ssn) VALUES (%s)", + "INSERT HIGH_PRIORITY IGNORE INTO users (ssn) VALUES (%s)", + "INSERT DELAYED INTO users (ssn) VALUES (%s)", + "REPLACE LOW_PRIORITY INTO users (ssn) VALUES (%s)", + "REPLACE users SET ssn = %s", + ]) + def test_mysql_modifiers(self, sql): + assert assigned(analyze(sql, MYSQL, P)) == [(0, "users.ssn")] + + def test_values_row(self): + a = analyze("INSERT INTO users (a, b) VALUES ROW(%s, %s), ROW(%s, NULL)", MYSQL, P) + assert assigned(a) == [(0, "users.a"), (1, "users.b"), (2, "users.a")] + + +class TestUpdate: + @BOTH + def test_set_and_where(self, dialect): + a = analyze("UPDATE users SET ssn = %s, name = 'x' WHERE id = %s", dialect, P) + assert a.kind is StatementKind.UPDATE and a.writes and a.complete + assert assigned(a) == [(0, "users.ssn")] + assert unbound(a) == ["users.name"] + assert compared(a) == [(1, "users.id")] + + @BOTH + def test_alias_and_qualified_assignment(self, dialect): + a = analyze("UPDATE users u SET u.ssn = %s WHERE u.id = %s", dialect, P) + assert assigned(a) == [(0, "users.ssn")] + assert compared(a) == [(1, "users.id")] + + @pytest.mark.parametrize("sql", ["UPDATE LOW_PRIORITY users SET ssn = %s", + "UPDATE IGNORE users SET ssn = %s", + "UPDATE LOW_PRIORITY IGNORE users SET ssn = %s"]) + def test_mysql_modifiers(self, sql): + # Unhandled, the parser reads LOW_PRIORITY as the table. + a = analyze(sql, MYSQL, P) + assert names(a.written_tables) == ["users"] + assert assigned(a) == [(0, "users.ssn")] + + def test_mysql_multi_table_qualified(self): + a = analyze("UPDATE users u JOIN orders o ON o.uid = u.id SET u.ssn = %s, o.total = %s WHERE o.id = %s", + MYSQL, P) + assert a.complete + assert assigned(a) == [(0, "users.ssn"), (1, "orders.total")] + assert compared(a) == [(2, "orders.id")] + assert names(a.written_tables) == ["users", "orders"] + + def test_mysql_multi_table_comma(self): + a = analyze("UPDATE users, orders SET users.ssn = %s WHERE users.id = orders.uid", MYSQL, P) + assert assigned(a) == [(0, "users.ssn")] and a.complete + + def test_mysql_multi_table_unqualified_is_ambiguous(self): + a = analyze("UPDATE users u JOIN orders o ON o.uid = u.id SET ssn = %s", MYSQL, P) + assert a.gap is AnalysisGap.AMBIGUOUS_TABLE + assert assigned(a) == [(0, "ssn")] + + def test_postgresql_from_does_not_add_a_written_table(self): + a = analyze("UPDATE users SET ssn = %s FROM other o WHERE o.id = users.id AND o.ssn = %s", PG, P) + assert names(a.written_tables) == ["users"] + assert assigned(a) == [(0, "users.ssn")] + assert compared(a) == [(1, "other.ssn")] + + def test_multi_column_assignment(self): + a = analyze("UPDATE users SET (a, b) = (%s, %s), (c, d) = ROW(%s, 'x'), (e, f) = (SELECT 1, 2)", PG, P) + assert assigned(a) == [(0, "users.a"), (1, "users.b"), (2, "users.c")] + assert unbound(a) == ["users.d", "users.e", "users.f"] + + def test_set_default(self): + assert unbound(analyze("UPDATE users SET ssn = DEFAULT", PG)) == ["users.ssn"] + + def test_returning(self): + a = analyze("UPDATE users SET ssn = %s RETURNING ssn", PG, P) + assert a.result_columns == (ColumnRef("ssn", "users"),) + + +class TestOtherWrites: + def test_merge(self): + a = analyze("MERGE INTO users u USING src s ON u.id = s.id " + "WHEN MATCHED AND s.flag = %s THEN UPDATE SET ssn = %s " + "WHEN MATCHED THEN DELETE " + "WHEN NOT MATCHED THEN INSERT (id, ssn) VALUES (%s, s.ssn)", PG, P) + assert a.kind is StatementKind.MERGE and a.writes and a.complete + assert assigned(a) == [(1, "users.ssn"), (2, "users.id")] + assert unbound(a) == ["users.ssn"] + assert compared(a) == [(0, "src.flag")] + assert names(a.written_tables) == ["users"] + + def test_merge_insert_without_columns(self): + a = analyze("MERGE INTO users u USING src s ON u.id = s.id " + "WHEN NOT MATCHED THEN INSERT VALUES (%s, %s)", PG, P) + assert a.gap is AnalysisGap.NO_COLUMN_LIST + + def test_merge_that_only_deletes(self): + a = analyze("MERGE INTO users u USING src s ON u.id = s.id WHEN MATCHED THEN DELETE", PG) + assert a.writes and a.complete and assigned(a) == [] and unbound(a) == [] + + def test_data_modifying_cte(self): + a = analyze("WITH w AS (INSERT INTO users (ssn) VALUES (%s) RETURNING id) SELECT * FROM w", PG, P) + assert a.kind is StatementKind.SELECT and a.writes + assert assigned(a) == [(0, "users.ssn")] + assert names(a.tables) == ["users"] # w is a CTE, not a table + + def test_update_cte(self): + a = analyze("WITH w AS (UPDATE users SET ssn = %s WHERE id = %s RETURNING id) SELECT id FROM w", PG, P) + assert assigned(a) == [(0, "users.ssn")] and compared(a) == [(1, "users.id")] + + def test_read_only_cte_is_a_read(self): + a = analyze("WITH w AS (SELECT ssn FROM users) SELECT ssn FROM w WHERE ssn = %s", PG, P) + assert not a.writes + assert names(a.tables) == ["users"] + assert compared(a) == [(0, "ssn")] # a CTE column has no table + assert a.result_columns == (ColumnRef("ssn", "users"),) + + def test_cte_insert_select(self): + a = analyze("WITH a AS (SELECT %s AS v) INSERT INTO users (ssn) SELECT v FROM a", PG, P) + assert a.gap is AnalysisGap.VALUES_FROM_QUERY + + def test_copy_from_names_unbound_columns(self): + a = analyze("COPY users (name, ssn) FROM STDIN", PG) + assert a.kind is StatementKind.COPY_FROM and a.writes and a.complete + assert unbound(a) == ["users.name", "users.ssn"] + + def test_copy_from_without_columns(self): + assert analyze("COPY users FROM STDIN WITH (FORMAT csv)", PG).gap is AnalysisGap.NO_COLUMN_LIST + + def test_copy_to_is_a_read(self): + a = analyze("COPY users TO STDOUT", PG) + assert a.kind is StatementKind.COPY_TO and not a.writes + assert names(a.tables) == ["users"] + + def test_copy_query_to(self): + a = analyze("COPY (SELECT ssn FROM users) TO STDOUT", PG) + assert not a.writes and names(a.tables) == ["users"] + + def test_several_statements_are_all_read(self): + # The ordinals run across the whole string, so each statement's + # placeholders still map to the right parameters. + a = analyze("UPDATE t SET a = %s; INSERT INTO users (name, ssn) VALUES (%s, %s)", MYSQL, P) + assert a.kind is StatementKind.UPDATE and a.writes and a.complete + assert assigned(a) == [(0, "t.a"), (1, "users.name"), (2, "users.ssn")] + assert a.result_columns is None + + @BOTH + def test_delete(self, dialect): + a = analyze("DELETE FROM users WHERE ssn = %s", dialect, P) + assert a.kind is StatementKind.DELETE and not a.writes + assert compared(a) == [(0, "users.ssn")] + + def test_mysql_multi_table_delete(self): + a = analyze("DELETE t FROM t JOIN u ON u.id = t.id WHERE u.a = %s", MYSQL, P) + assert compared(a) == [(0, "u.a")] + + +class TestComparisons: + def test_operators(self): + a = analyze("SELECT * FROM t WHERE a = %s AND b <> %s AND c < %s AND d >= %s AND e LIKE %s " + "AND f ILIKE %s AND g IS NOT DISTINCT FROM %s AND %s = h", PG, P) + assert compared(a) == [(i, f"t.{c}") for i, c in enumerate("abcdefgh")] + + @BOTH + def test_a_parenthesized_column_is_paired_with_its_value(self, dialect): + a = analyze("SELECT * FROM users u WHERE (ssn) = %s AND ((u.dob)) IN (%s, %s) AND %s <> (ssn) " + "AND (ssn) BETWEEN %s AND %s", dialect, P) + assert sorted(compared(a)) == [(0, "users.ssn"), (1, "users.dob"), (2, "users.dob"), (3, "users.ssn"), + (4, "users.ssn"), (5, "users.ssn")] + + @BOTH + def test_a_sub_selects_only_column_is_paired_with_the_value(self, dialect): + # The sub-select's rows hold that column's values, and its column is resolved in the sub-select, not in t. + a = analyze("SELECT name FROM t WHERE %s IN (SELECT ssn FROM users) AND %s = ANY (SELECT u.dob FROM users u) " + "AND %s = SOME (SELECT ssn AS s FROM users) AND %s <> ALL (SELECT ((ssn)) FROM users) " + "AND %s = (SELECT ssn FROM users LIMIT 1) AND (SELECT ssn FROM users LIMIT 1) = %s " + "AND %s IN ((SELECT ssn FROM users))", dialect, P) + assert sorted(compared(a)) == [(0, "users.ssn"), (1, "users.dob"), (2, "users.ssn"), (3, "users.ssn"), + (4, "users.ssn"), (5, "users.ssn"), (6, "users.ssn")] + assert not any(u.array for u in a.comparisons) + + @BOTH + def test_a_sub_select_with_more_than_its_column_is_not_paired(self, dialect): + a = analyze("SELECT name FROM t WHERE %s IN (SELECT ssn FROM users UNION SELECT ssn FROM archive) " + "AND %s IN (SELECT lower(ssn) FROM users) AND %s IN (SELECT * FROM users) " + "AND (%s, %s) IN (SELECT ssn, dob FROM users) AND ssn IN (SELECT %s) " + "AND %s IN (SELECT ssn, dob FROM users)", dialect, P) + assert compared(a) == [] + + @BOTH + def test_a_sub_select_in_doubled_parentheses_under_all_or_some_is_paired(self, dialect): + # sqlglot reads ALL ((SELECT ...)) and SOME ((SELECT ...)) as functions; both servers read a sub-select. + a = analyze("SELECT name FROM t WHERE %s <> ALL ((SELECT ssn FROM users)) " + "AND %s = SOME (((SELECT u.ssn AS s FROM users u))) AND %s = some ((select dob from users))", + dialect, P) + assert sorted(compared(a)) == [(0, "users.ssn"), (1, "users.ssn"), (2, "users.dob")] + assert not any(u.array for u in a.comparisons) + + @BOTH + def test_all_or_some_over_anything_but_a_sub_select_of_the_column_is_not_paired(self, dialect): + # The last two compare the value with the elements of an array column, not with the column. + a = analyze("SELECT name FROM t WHERE %s <> ALL ((SELECT ssn FROM users UNION SELECT ssn FROM archive)) " + "AND %s = SOME ((SELECT lower(ssn) FROM users)) " + "AND %s = SOME ((SELECT ssn FROM users), (SELECT dob FROM users)) " + "AND %s = foo((SELECT ssn FROM users)) AND %s = SOME ((ssn) ORDER BY 1) " + "AND %s = ALL (tags) AND %s = SOME (tags)", + dialect, P) + assert compared(a) == [] + + @BOTH + def test_a_sub_select_with_order_by_or_limit_after_its_parentheses_is_paired(self, dialect): + # sqlglot puts an ORDER BY or LIMIT between the parentheses of ALL ((...)) or SOME ((...)) over the Subquery. + a = analyze("SELECT name FROM t WHERE %s = SOME ((SELECT ssn FROM users) ORDER BY 1) " + "AND %s <> ALL ((SELECT dob FROM users) LIMIT 5) " + "AND %s = some ((select u.ssn as s from users u) order by 1 limit 5)", dialect, P) + assert sorted(compared(a)) == [(0, "users.ssn"), (1, "users.dob"), (2, "users.ssn")] + assert not any(u.array for u in a.comparisons) + + def test_in_between_and_any(self): + a = analyze("SELECT * FROM t WHERE a IN (%s, %s) AND b BETWEEN %s AND %s AND c = ANY(%s)", PG, P) + assert compared(a) == [(0, "t.a"), (1, "t.a"), (2, "t.b"), (3, "t.b"), (4, "t.c")] + assert [u.array for u in a.comparisons] == [False] * 4 + [True] + + def test_mysql_null_safe_equals(self): + assert compared(analyze("SELECT * FROM t WHERE a <=> %s", MYSQL, P)) == [(0, "t.a")] + + def test_join_resolves_aliases_and_leaves_unqualified_columns_open(self): + a = analyze("SELECT u.ssn FROM users u JOIN orders o ON o.uid = u.id " + "WHERE u.name = %s AND o.id = %s AND total = %s", PG, P) + assert compared(a) == [(0, "users.name"), (1, "orders.id"), (2, "total")] + + def test_subquery_scope(self): + a = analyze("SELECT * FROM users WHERE id IN (SELECT uid FROM orders WHERE total = %s) AND ssn = %s", + PG, P) + assert compared(a) == [(0, "orders.total"), (1, "users.ssn")] + + def test_correlated_qualifier_from_an_outer_query(self): + a = analyze("SELECT * FROM users u WHERE EXISTS (SELECT 1 FROM orders o WHERE o.uid = u.id AND u.ssn = %s)", + PG, P) + assert compared(a) == [(0, "users.ssn")] + + def test_column_against_column_is_not_a_parameter(self): + assert compared(analyze("SELECT * FROM t WHERE a = b", PG)) == [] + + def test_jsonb_question_mark_operator(self): + # "?" is an operator on PostgreSQL, not a placeholder. + a = analyze("SELECT ssn FROM users WHERE data ? 'k' AND id = %s", PG, P) + assert a.complete and compared(a) == [(0, "users.id")] + + def test_unknown_qualifier_is_taken_as_a_table(self): + assert compared(analyze("SELECT * FROM users WHERE other.ssn = %s", PG, P)) == [(0, "other.ssn")] + + +class TestComparisonSafety: + """``ParameterUse.safe``: whether a comparison that never matches can only + remove rows from what the statement reads or changes.""" + + @on(both=["SELECT id FROM users WHERE ssn = %s", + "SELECT id FROM users WHERE %s = ssn", + "SELECT id FROM users WHERE ssn IN (%s, %s)", + "SELECT id FROM users WHERE ssn LIKE %s", + "SELECT id FROM users WHERE ssn LIKE %s ESCAPE '!'"], + pg=["SELECT id FROM users WHERE ssn = ANY(%s)", + "SELECT id FROM users WHERE ssn = SOME(%s)", + "SELECT id FROM users WHERE ssn ILIKE %s", + "SELECT id FROM users WHERE ssn IS NOT DISTINCT FROM %s", + "SELECT id FROM users WHERE ssn LIKE ANY(%s)", + "SELECT id FROM users WHERE ssn LIKE SOME(%s)", + "SELECT id FROM users WHERE ssn ILIKE ANY(%s)"], + mysql=["SELECT id FROM users WHERE ssn LIKE BINARY %s", + "SELECT id FROM users WHERE ssn <=> %s"]) + def test_safe_operators(self, dialect, sql): + flags = safety(sql, dialect) + assert flags and all(flags) + + @on(both=["SELECT id FROM users WHERE ssn <> %s", + "SELECT id FROM users WHERE %s <> ssn", + "SELECT id FROM users WHERE ssn != %s", + "SELECT id FROM users WHERE ssn < %s", + "SELECT id FROM users WHERE ssn <= %s", + "SELECT id FROM users WHERE ssn > %s", + "SELECT id FROM users WHERE ssn >= %s", + "SELECT id FROM users WHERE ssn BETWEEN %s AND %s", + "SELECT id FROM users WHERE ssn NOT BETWEEN %s AND %s", + "SELECT id FROM users WHERE ssn NOT IN (%s, %s)", + "SELECT id FROM users WHERE ssn NOT LIKE %s", + "SELECT id FROM users WHERE ssn NOT LIKE %s ESCAPE '!'"], + pg=["SELECT id FROM users WHERE ssn IS DISTINCT FROM %s", + "SELECT id FROM users WHERE ssn NOT ILIKE %s", + "SELECT id FROM users WHERE ssn <> ALL(%s)", + "SELECT id FROM users WHERE ssn <> ANY(%s)", + "SELECT id FROM users WHERE ssn = ALL(%s)", + "SELECT id FROM users WHERE ssn LIKE ALL(%s)", + "SELECT id FROM users WHERE ssn NOT LIKE ANY(%s)"]) + def test_unsafe_operators(self, dialect, sql): + flags = safety(sql, dialect) + assert flags and not any(flags) + + @BOTH + def test_a_parenthesized_column_is_judged_like_the_column(self, dialect): + # sqlglot keeps the parentheses as a Paren node around the column. + assert safety("SELECT id FROM users WHERE (ssn) = %s OR ((ssn)) LIKE %s", dialect) == [True, True] + assert safety("DELETE FROM users WHERE (ssn) <> %s", dialect) == [False] + assert safety("DELETE FROM users WHERE %s <> (ssn) OR ((ssn)) NOT LIKE %s", dialect) == [False, False] + + @BOTH + def test_a_sub_selects_only_column_is_judged_like_the_column(self, dialect): + assert safety("SELECT id FROM t WHERE %s IN (SELECT ssn FROM users) OR %s = ANY (SELECT ssn FROM users) " + "OR %s = (SELECT ssn FROM users LIMIT 1)", dialect) == [True] * 3 + # = ALL over no rows is true, so only ALL itself makes it unsafe. + unsafe = ["%s NOT IN (SELECT ssn FROM users)", "%s <> ALL (SELECT ssn FROM users)", + "%s = ALL (SELECT ssn FROM users)", "%s <> ANY (SELECT ssn FROM users)", + "%s <> (SELECT ssn FROM users LIMIT 1)", "%s > (SELECT ssn FROM users LIMIT 1)"] + assert [safety(f"DELETE FROM t WHERE {c}", dialect) for c in unsafe] == [[False]] * len(unsafe) + assert safety("SELECT %s IN (SELECT ssn FROM users) FROM t", dialect) == [False] + + @BOTH + def test_a_sub_select_in_doubled_parentheses_under_all_or_some_is_judged_like_the_column(self, dialect): + assert safety("SELECT id FROM t WHERE %s = SOME ((SELECT ssn FROM users)) " + "OR %s = some (((select ssn from users)))", dialect) == [True, True] + unsafe = ["%s <> ALL ((SELECT ssn FROM users))", "%s = ALL ((SELECT ssn FROM users))", + "%s = all (((select ssn from users)))", "%s <> SOME ((SELECT ssn FROM users))"] + assert [safety(f"DELETE FROM t WHERE {c}", dialect) for c in unsafe] == [[False]] * len(unsafe) + + @BOTH + def test_a_sub_select_read_by_some_in_doubled_parentheses_is_judged_like_any(self, dialect): + assert safety("DELETE FROM orders WHERE uid = SOME ((SELECT id FROM users WHERE ssn = %s)) " + "OR uid = some (((select id from users where dob = %s)))", dialect) == [True, True] + # ALL over a sub-select whose filter never holds is true for every row. + assert safety("DELETE FROM orders WHERE uid = ALL ((SELECT id FROM users WHERE ssn = %s))", dialect) == [False] + # As under <> ANY (SELECT ...), only = reads the sub-select. + assert safety("DELETE FROM orders WHERE uid <> SOME ((SELECT id FROM users WHERE ssn = %s))", dialect) == [False] + + @BOTH + def test_a_sub_select_with_order_by_or_limit_after_its_parentheses_is_judged_like_the_column(self, dialect): + assert safety("SELECT id FROM t WHERE %s = SOME ((SELECT ssn FROM users) LIMIT 5)", dialect) == [True] + unsafe = ["%s <> ALL ((SELECT ssn FROM users) ORDER BY 1)", "%s <> ALL ((SELECT ssn FROM users) LIMIT 5)", + "%s = all ((select ssn from users) order by 1 limit 5)"] + assert [safety(f"DELETE FROM t WHERE {c}", dialect) for c in unsafe] == [[False]] * len(unsafe) + + @BOTH + def test_a_read_sub_select_with_order_by_or_limit_after_its_parentheses_is_judged_by_its_reader(self, dialect): + assert safety("DELETE FROM orders WHERE uid = SOME ((SELECT id FROM users WHERE ssn = %s) LIMIT 5) " + "OR uid = SOME ((SELECT id FROM users WHERE dob = %s) ORDER BY 1) " + "OR EXISTS ((SELECT 1 FROM users WHERE name = %s) ORDER BY 1 LIMIT 1)", dialect) == [True] * 3 + # ALL over a sub-select whose filter never holds is true for every row, and a LIMIT count taken from such a + # sub-select is NULL, which PostgreSQL reads as no limit. + unsafe = ["uid = ALL ((SELECT id FROM users WHERE ssn = %s) LIMIT 5)", + "uid = SOME ((SELECT id FROM t2) LIMIT (SELECT id FROM users WHERE ssn = %s))"] + assert [safety(f"DELETE FROM orders WHERE {c}", dialect) for c in unsafe] == [[False]] * len(unsafe) + + @BOTH + def test_not_like_is_unsafe_without_a_not_node(self, dialect): + sql = "SELECT id FROM users WHERE ssn NOT LIKE %s" + trees, _ = sql_analyzer._parse(tokenize(sql, dialect, ParamStyle.of(P, dialect)).normalized, dialect) + # sqlglot sets the LIKE's negate flag rather than adding a NOT node, + # so only the operator check can see the negation. + assert trees and trees[0].find(exp.Not) is None and trees[0].find(exp.Like).args.get("negate") + assert safety(sql, dialect) == [False] + + @on(both=["SELECT id FROM users WHERE (ssn = %s)", + "SELECT id FROM users WHERE id > 0 AND (name = 'a' OR (ssn = %s))", + "SELECT id FROM users WHERE ((ssn = %s) OR (id > 0 AND ssn = %s))", + "SELECT id FROM users u, orders o WHERE o.uid = u.id AND u.ssn = %s", + "SELECT name FROM users GROUP BY name, ssn HAVING ssn = %s", + "SELECT name, COUNT(*) FROM users GROUP BY name, ssn HAVING ssn = %s", + "SELECT a.name FROM users a JOIN users b ON a.id = b.id AND b.ssn = %s", + "SELECT a.id FROM users a JOIN users b ON b.ssn = %s AND a.id = b.id", + "SELECT u.id FROM users u INNER JOIN orders o ON o.uid = u.id AND u.ssn = %s", + "SELECT name FROM users WHERE id IN (SELECT id FROM users WHERE ssn = %s)", + "SELECT id FROM users WHERE id IN ((SELECT id FROM users WHERE ssn = %s))", + "SELECT id FROM users WHERE id IN (SELECT id FROM users WHERE ssn = %s UNION SELECT id FROM users)", + "SELECT id FROM users u WHERE EXISTS (SELECT 1 FROM users v WHERE v.id = u.id AND v.ssn = %s)", + "SELECT id FROM orders WHERE EXISTS (SELECT id FROM users WHERE ssn = %s AND my_fn(id))", + "DELETE FROM orders WHERE uid = (SELECT id FROM users WHERE ssn = %s)", + "UPDATE orders SET note = 'x' WHERE (SELECT id FROM users WHERE ssn = %s) = uid", + "DELETE FROM orders WHERE uid = ANY(SELECT id FROM users WHERE ssn = %s)", + "DELETE FROM orders WHERE uid = SOME(SELECT id FROM users WHERE ssn = %s)", + "SELECT u.id FROM (SELECT id FROM users WHERE ssn = %s) u", + "SELECT u.id FROM (SELECT id FROM users WHERE ssn = %s) u JOIN orders o ON o.uid = u.id", + "SELECT u.id FROM orders o JOIN (SELECT id FROM users WHERE ssn = %s) u ON o.uid = u.id", + "UPDATE orders SET note = 'x' WHERE uid IN (SELECT id FROM (SELECT id FROM users WHERE ssn = %s) d)", + "WITH w AS (SELECT id FROM users WHERE ssn = %s) SELECT id FROM w", + "WITH c AS (SELECT id, ssn FROM users WHERE ssn = %s) SELECT id FROM c", + "WITH c AS (SELECT id, ssn FROM users) SELECT id FROM c WHERE ssn = %s", + "WITH a AS (SELECT id FROM users WHERE ssn = %s), b AS (SELECT id FROM a) SELECT id FROM b", + "WITH a AS (SELECT id FROM users WHERE ssn = %s) SELECT id FROM users WHERE id IN (SELECT id FROM a)", + "WITH w AS (SELECT id FROM users WHERE ssn = %s) SELECT u.id FROM users u JOIN w ON w.id = u.id", + "SELECT id FROM users WHERE ssn = %s UNION SELECT id FROM users", + "SELECT id FROM users UNION ALL SELECT id FROM users WHERE ssn = %s", + "SELECT id FROM users WHERE ssn = %s INTERSECT SELECT id FROM users", + "SELECT id FROM users INTERSECT SELECT id FROM users WHERE ssn = %s", + "SELECT id FROM users WHERE ssn = %s EXCEPT SELECT id FROM users", + "(SELECT id FROM users WHERE ssn = %s)", + "((SELECT id FROM users WHERE ssn = %s) UNION (SELECT id FROM users))", + "SELECT id FROM users WHERE ssn = %s ORDER BY id LIMIT 1", + "UPDATE users SET note = 'x' WHERE ssn = %s", + "DELETE FROM users WHERE ssn = %s", + "INSERT INTO audit (uid) SELECT id FROM users WHERE ssn = %s", + "SELECT id FROM users WHERE ssn = %s; DELETE FROM users WHERE ssn = %s"], + pg=["UPDATE users SET note = 'x' WHERE ssn = %s RETURNING id", + "DELETE FROM users WHERE ssn = %s RETURNING id", + "UPDATE users SET name = 'x' FROM users v WHERE v.id = users.id AND v.ssn = %s", + "DELETE FROM users USING users v WHERE v.id = users.id AND v.ssn = %s", + "WITH d AS (DELETE FROM users WHERE ssn = %s RETURNING id) SELECT id FROM d", + "WITH users AS (SELECT id FROM public.users WHERE ssn = %s) SELECT id FROM users"], + mysql=["UPDATE users u JOIN orders o ON o.uid = u.id AND u.ssn = %s SET o.note = 'x'", + "UPDATE users u JOIN orders o ON o.uid = u.id SET o.note = 'x' WHERE u.ssn = %s", + "DELETE u FROM users u JOIN orders o ON o.uid = u.id AND u.ssn = %s", + "DELETE t FROM t JOIN u ON u.id = t.id WHERE u.ssn = %s", + "SELECT u.id FROM users u STRAIGHT_JOIN orders o ON o.uid = u.id AND u.ssn = %s", + "SELECT u.id FROM users u CROSS JOIN orders o ON o.uid = u.id AND u.ssn = %s", + "WITH users AS (SELECT id FROM mydb.users WHERE ssn = %s) SELECT id FROM users"]) + def test_safe_positions(self, dialect, sql): + flags = safety(sql, dialect) + assert flags and all(flags) + + @on(both=["SELECT id FROM users WHERE NOT ssn = %s", + "SELECT id FROM users WHERE NOT (ssn = %s OR id = 1)", + "SELECT id FROM users WHERE (ssn = %s) IS TRUE", + "SELECT id FROM users WHERE (ssn = %s) IS NOT TRUE", + "SELECT id FROM users WHERE (ssn = %s) IS FALSE", + "SELECT id FROM users WHERE (ssn = %s) = FALSE", + "SELECT id FROM users WHERE CASE WHEN ssn = %s THEN FALSE ELSE TRUE END", + "SELECT id FROM users WHERE COALESCE(ssn = %s, FALSE)", + "SELECT ssn = %s FROM users", + "SELECT (SELECT 1 FROM users WHERE ssn = %s) FROM orders", + "SELECT id FROM users ORDER BY ssn = %s", + "SELECT COUNT(*) FROM users GROUP BY ssn = %s", + "UPDATE users SET flag = (ssn = %s)", + "UPDATE users SET note = (SELECT note FROM orders WHERE orders.ssn = %s)", + "INSERT INTO audit (uid) VALUES ((SELECT id FROM users WHERE ssn = %s))", + "SELECT u.id FROM users u LEFT JOIN users v ON v.id = u.id AND v.ssn = %s", + "SELECT u.id FROM users u LEFT JOIN users v ON v.id = u.id AND u.ssn = %s", + "SELECT u.id FROM users u LEFT OUTER JOIN users v ON v.id = u.id AND v.ssn = %s", + "SELECT u.id FROM users u RIGHT JOIN users v ON v.id = u.id AND v.ssn = %s", + "SELECT u.id FROM users u RIGHT JOIN users v ON v.id = u.id AND u.ssn = %s", + "DELETE FROM orders WHERE uid NOT IN (SELECT id FROM users WHERE ssn = %s)", + "DELETE FROM orders WHERE NOT EXISTS (SELECT 1 FROM users WHERE users.id = orders.uid AND users.ssn = %s)", + "DELETE FROM orders WHERE uid <> ALL (SELECT id FROM users WHERE ssn = %s)", + "DELETE FROM orders WHERE uid > ALL (SELECT id FROM users WHERE ssn = %s)", + "DELETE FROM orders WHERE uid = ALL (SELECT id FROM users WHERE ssn = %s)", + "DELETE FROM orders WHERE uid <> ANY (SELECT id FROM users WHERE ssn = %s)", + "DELETE FROM orders WHERE uid <> (SELECT id FROM users WHERE ssn = %s)", + "SELECT id FROM users EXCEPT SELECT id FROM users WHERE ssn = %s", + "SELECT id FROM orders WHERE uid IN (SELECT id FROM users EXCEPT SELECT id FROM users WHERE ssn = %s)", + "WITH w AS (SELECT id FROM users WHERE ssn = %s) DELETE FROM orders WHERE uid NOT IN (SELECT id FROM w)", + "WITH w AS (SELECT id FROM users WHERE ssn = %s) SELECT u.id FROM users u LEFT JOIN w ON w.id = u.id", + "WITH w AS (SELECT id FROM users WHERE ssn = %s) SELECT id FROM w UNION SELECT id FROM orders " + "WHERE uid NOT IN (SELECT id FROM w)", + "SELECT v.id FROM users v LEFT JOIN (SELECT id FROM users WHERE ssn = %s) u ON v.id = u.id", + "SELECT u.id FROM (SELECT id FROM users WHERE ssn = %s) u LEFT JOIN users v ON v.id = u.id", + "SELECT u.id FROM (SELECT id FROM users WHERE ssn = %s) u JOIN orders o ON o.uid = u.id " + "RIGHT JOIN items i ON i.oid = o.id", + "SELECT id FROM orders WHERE (SELECT id FROM users WHERE ssn = %s) IN (1, 2)", + "SELECT u.id FROM users u JOIN orders o ON (SELECT TRUE FROM users v WHERE v.ssn = %s)"], + pg=["UPDATE users SET note = 'x' RETURNING ssn = %s", + "WITH x AS (INSERT INTO audit (uid) SELECT id FROM users WHERE ssn = %s RETURNING uid) SELECT uid FROM x", + "WITH w AS (SELECT id FROM users WHERE ssn = %s) INSERT INTO w (id) VALUES (1)", + "SELECT u.id FROM users u ANTI JOIN orders o ON o.uid = u.id AND u.ssn = %s", + "DELETE FROM orders WHERE uid IS DISTINCT FROM (SELECT id FROM users WHERE ssn = %s)", + "MERGE INTO users t USING src s ON t.ssn = %s WHEN MATCHED THEN DELETE", + "MERGE INTO users t USING src s ON t.id = s.id WHEN MATCHED AND t.ssn = %s THEN DELETE", + "MERGE INTO orders t USING (SELECT id FROM users WHERE ssn = %s) s ON t.uid = s.id WHEN MATCHED THEN DELETE", + "INSERT INTO users (id, ssn) VALUES (%s, %s) ON CONFLICT (id) DO UPDATE SET note = 'x' WHERE users.ssn = %s", + "SELECT u.id FROM users u FULL JOIN users v ON v.id = u.id AND v.ssn = %s", + "SELECT id FROM orders o, LATERAL (SELECT 1 FROM users v WHERE v.ssn = %s) x", + "SELECT id FROM orders o CROSS JOIN LATERAL (SELECT 1 FROM users v WHERE v.ssn = %s) x"], + mysql=["SELECT id FROM users WHERE ssn = %s XOR TRUE", + "SELECT id FROM users WHERE IF(ssn = %s, 0, 1) = 1", + "DELETE FROM orders WHERE uid <=> (SELECT id FROM users WHERE ssn = %s)", + "DELETE u FROM users u LEFT JOIN orders o ON o.uid = u.id AND u.ssn = %s WHERE o.uid IS NULL", + "UPDATE users u LEFT JOIN orders o ON o.uid = u.id AND u.ssn = %s SET u.note = 'x' WHERE o.uid IS NULL"]) + def test_unsafe_positions(self, dialect, sql): + flags = safety(sql, dialect) + assert flags and not any(flags) + + @pytest.mark.parametrize("dialect, sql, column", [ + (PG, "SELECT i.id FROM users u JOIN orders o ON o.uid = u.id{on} RIGHT JOIN items i ON i.oid = o.id{where}", + "u.ssn"), + (MYSQL, "DELETE i FROM users u JOIN orders o ON o.uid = u.id{on} RIGHT JOIN items i ON i.oid = o.id{where}", + "u.ssn"), + (PG, "SELECT o.id FROM users u JOIN orders o ON o.uid = u.id{on} LEFT JOIN items i ON i.oid = o.id{where}", + "u.ssn"), + (MYSQL, "SELECT o.id FROM users u JOIN orders o ON o.uid = u.id{on} LEFT JOIN items i ON i.oid = o.id{where}", + "u.ssn"), + (PG, "SELECT u.id FROM users u LEFT JOIN (orders o JOIN items i ON i.oid = o.id{on}) ON o.uid = u.id{where}", + "o.ssn"), + (MYSQL, "SELECT u.id FROM users u LEFT JOIN (orders o JOIN items i ON i.oid = o.id{on}) ON o.uid = u.id{where}", + "o.ssn"), + (PG, "SELECT i.id FROM (users u JOIN orders o ON o.uid = u.id{on} RIGHT JOIN items i ON i.oid = o.id){where}", + "u.ssn"), + (PG, "SELECT r.id FROM users u CROSS JOIN (orders o JOIN items i ON i.oid = o.id{on} RIGHT JOIN refs r " + "ON r.iid = i.id){where}", "o.ssn"), + (MYSQL, "SELECT r.id FROM users u CROSS JOIN (orders o JOIN items i ON i.oid = o.id{on} RIGHT JOIN refs r " + "ON r.iid = i.id){where}", "o.ssn"), + (PG, "UPDATE users SET note = 'x' FROM orders o JOIN items i ON i.oid = o.id{on} RIGHT JOIN refs r " + "ON r.iid = i.id{where}", "o.ssn"), + (PG, "DELETE FROM users USING orders o JOIN items i ON i.oid = o.id{on} RIGHT JOIN refs r ON r.iid = i.id{where}", + "o.ssn"), + (MYSQL, "UPDATE users u JOIN orders o ON o.uid = u.id{on} LEFT JOIN items i ON i.oid = o.id SET u.note = 'x'{where}", + "u.ssn"), + (MYSQL, "DELETE FROM i USING users u JOIN orders o ON o.uid = u.id{on} RIGHT JOIN items i ON i.oid = o.id{where}", + "u.ssn"), + (PG, "SELECT r.id FROM ((orders JOIN items ON items.oid = orders.id{on}) RIGHT JOIN refs r ON r.iid = items.id){where}", + "orders.ssn"), + (MYSQL, "DELETE u FROM users u CROSS JOIN ((orders JOIN items ON items.oid = orders.id{on}) RIGHT JOIN refs r " + "ON r.iid = items.id){where}", "orders.ssn"), + ], ids=["pg-right", "mysql-delete-right", "pg-later-left", "mysql-later-left", "pg-parenthesized-under-left", + "mysql-parenthesized-under-left", "pg-right-inside-parentheses", "pg-right-inside-a-joined-parenthesis", + "mysql-right-inside-a-joined-parenthesis", "pg-update-from", "pg-delete-using", "mysql-update", + "mysql-delete-using", "pg-right-around-nested-parentheses", "mysql-delete-right-around-nested-parentheses"]) + def test_inner_join_in_a_query_with_an_outer_join_is_unsafe(self, dialect, sql, column): + # A later RIGHT or FULL join keeps every row of its side when the + # earlier join matches nothing, and so does a LEFT join around a + # parenthesized join. A WHERE filters the joined rows. + assert safety(sql.format(on=f" AND {column} = %s", where=""), dialect) == [False] + assert safety(sql.format(on="", where=f" WHERE {column} = %s"), dialect) == [True] + + @pytest.mark.parametrize("dialect, sql", [ + (PG, "UPDATE users SET note = 'x' FROM (SELECT id FROM orders) o " + "LEFT JOIN (SELECT id FROM users WHERE ssn = %s) d ON d.id = o.id WHERE d.id IS NULL AND o.id = users.id"), + (PG, "DELETE FROM users USING (SELECT id FROM orders) o " + "LEFT JOIN (SELECT id FROM users WHERE ssn = %s) d ON d.id = o.id WHERE d.id IS NULL AND o.id = users.id"), + (MYSQL, "UPDATE (SELECT id FROM orders) o JOIN users u ON u.id = o.id " + "LEFT JOIN (SELECT id FROM users WHERE ssn = %s) d ON d.id = u.id SET u.note = 'x' WHERE d.id IS NULL"), + (PG, "SELECT r.id FROM users u CROSS JOIN (((SELECT id FROM users WHERE ssn = %s) d JOIN items ON items.oid = d.id) " + "RIGHT JOIN refs r ON r.iid = items.id)"), + ], ids=["pg-update-from-derived-table", "pg-delete-using-derived-table", "mysql-update-derived-table", + "pg-derived-table-in-nested-parentheses"]) + def test_outer_join_after_a_parenthesized_source_is_seen(self, dialect, sql): + # sqlglot hangs the joins that follow a derived table or a + # parenthesized join on its Subquery. When the derived table d matches + # nothing, the sided join there still keeps every row of its other side. + assert safety(sql, dialect) == [False] + + @pytest.mark.parametrize("sql, safe", [ + ("SELECT id FROM users WHERE (SELECT COUNT(*) FROM users WHERE ssn = %s) = 0", False), + ("DELETE FROM orders WHERE (SELECT COUNT(*) FROM users v WHERE v.id = orders.uid AND v.ssn = %s) = 0", False), + ("SELECT id FROM users WHERE EXISTS (SELECT COUNT(*) FROM users WHERE ssn = %s)", False), + ("SELECT id FROM orders WHERE uid = (SELECT MAX(id) FROM users WHERE ssn = %s)", False), + ("SELECT id FROM users WHERE id IN (SELECT uid FROM orders WHERE ssn = %s GROUP BY uid HAVING COUNT(*) < 2)", + False), + ("SELECT id FROM users WHERE id IN (SELECT uid FROM orders WHERE ssn = %s GROUP BY uid)", False), + ("SELECT id FROM orders WHERE EXISTS (SELECT 1 FROM users WHERE ssn = %s HAVING COUNT(*) < 2)", False), + ("SELECT d.id FROM (SELECT id, ROW_NUMBER() OVER (ORDER BY id) AS rn FROM users WHERE ssn = %s) d", False), + ("WITH c AS (SELECT COUNT(*) AS n FROM users WHERE ssn = %s) SELECT n FROM c", False), + ("SELECT COUNT(*) FROM users WHERE ssn = %s", True), + ], ids=["count-equals-zero", "correlated-count", "exists-count", "max", "group-having", "group", "having", + "window", "cte", "the-statement"]) + @BOTH + def test_aggregating_sub_select_is_unsafe(self, dialect, sql, safe): + assert safety(sql, dialect) == [safe] + + @pytest.mark.parametrize("dialect, sql", [ + (PG, "DELETE FROM orders WHERE EXISTS (SELECT jsonb_agg(id) FROM users WHERE ssn = %s)"), + (MYSQL, "DELETE FROM orders WHERE EXISTS (SELECT JSON_ARRAYAGG(id) FROM users WHERE ssn = %s)"), + (PG, "DELETE FROM orders WHERE EXISTS (SELECT my_agg(id) FROM users WHERE ssn = %s)"), + (MYSQL, "DELETE FROM orders WHERE EXISTS (SELECT my_agg(id) FROM users WHERE ssn = %s)"), + (PG, "DELETE FROM orders WHERE EXISTS (SELECT 1 FROM users WHERE ssn = %s ORDER BY COUNT(*))"), + (MYSQL, "DELETE FROM orders WHERE EXISTS (SELECT 1 FROM users WHERE ssn = %s ORDER BY COUNT(*))"), + (PG, "DELETE FROM orders WHERE EXISTS (SELECT DISTINCT ON (COUNT(*)) 1 FROM users WHERE ssn = %s)"), + (PG, "DELETE FROM orders WHERE EXISTS (SELECT 1 FROM users WHERE ssn = %s WINDOW w AS (ORDER BY COUNT(*)))"), + ], ids=["pg-jsonb-agg", "mysql-json-arrayagg", "pg-user-defined", "mysql-user-defined", "pg-order-by", + "mysql-order-by", "pg-distinct-on", "pg-window-clause"]) + def test_possible_aggregate_in_a_sub_select_is_unsafe(self, dialect, sql): + # An aggregate without GROUP BY returns a row for no input row, so the + # EXISTS holds and every order is deleted. sqlglot reads some built-in + # aggregates and every user-defined one as a function it doesn't know, + # and a query's own aggregate can also sit in ORDER BY, DISTINCT ON or + # WINDOW. + assert safety(sql, dialect) == [False] + + @pytest.mark.parametrize("sql", [ + "WITH RECURSIVE r AS (SELECT id FROM users WHERE ssn = %s " + "UNION ALL SELECT u.id FROM users u JOIN r ON u.id = r.id + 1) SELECT id FROM r", + "WITH RECURSIVE r AS (SELECT id FROM users " + "UNION ALL SELECT u.id FROM users u JOIN r ON u.id = r.id + 1 WHERE u.ssn = %s) SELECT id FROM r", + ], ids=["anchor", "recursive-part"]) + @BOTH + def test_recursive_cte_reference_is_unsafe(self, dialect, sql): + assert safety(sql, dialect) == [False] + + @pytest.mark.timeout(5) + @BOTH + def test_long_cte_chain_is_followed_without_recursion(self, dialect): + # Each CTE reads the one before it, so the statement, 2000 queries + # out, decides the comparison's position. + ctes = ["c0 AS (SELECT id FROM users WHERE ssn = %s)"] + [f"c{i} AS (SELECT id FROM c{i - 1})" for i in range(1, 2000)] + assert safety("WITH " + ", ".join(ctes) + " SELECT id FROM c1999", dialect) == [True] + + @BOTH + def test_assignments_and_annotations_keep_the_default(self, dialect): + a = analyze("UPDATE users SET ssn = %s WHERE id <> /*@encrypt:users.ssn*/ %s", dialect, P) + assert [(u.ordinal, u.safe) for u in a.assignments] == [(0, True)] + assert [(u.ordinal, u.safe) for u in a.annotations] == [(1, True)] + assert [(u.ordinal, u.safe) for u in a.comparisons] == [(1, False)] + assert [u.safe for u in analyze("INSERT INTO users (id, ssn) VALUES (%s, %s)", dialect, P).assignments] \ + == [True, True] + + @pytest.mark.timeout(10) + def test_comparison_safety_is_time_bounded_in_a_long_or_chain(self): + # Without the memo, each comparison climbs the rest of the chain: far + # past the timeout at this length. + sql = "SELECT id FROM users WHERE " + " OR ".join(["ssn = %s"] * 40000) + flags = safety(sql, PG) + assert len(flags) == 40000 and all(flags) + + +class TestReads: + @BOTH + def test_tables_and_result_columns(self, dialect): + a = analyze("SELECT u.ssn AS s, o.ssn, name, 1 FROM users u JOIN orders o ON o.uid = u.id", dialect) + assert a.kind is StatementKind.SELECT and not a.writes + assert names(a.tables) == ["users", "orders"] + assert a.result_columns == (ColumnRef("ssn", "users"), ColumnRef("ssn", "orders"), None, None) + + def test_single_table_unqualified(self): + a = analyze("SELECT ssn, name FROM users WHERE id = %s", PG, P) + assert a.result_columns == (ColumnRef("ssn", "users"), ColumnRef("name", "users")) + + @pytest.mark.parametrize("sql", ["SELECT * FROM users", "SELECT u.* FROM users u", + "SELECT ssn FROM users UNION SELECT ssn FROM archive"]) + def test_result_columns_unknown(self, sql): + assert analyze(sql, PG).result_columns is None + + def test_subquery_column_is_traced_to_its_table(self): + a = analyze("SELECT s.ssn FROM (SELECT ssn FROM users) s", PG) + assert a.result_columns == (ColumnRef("ssn", "users"),) + assert names(a.tables) == ["users"] + + @BOTH + @pytest.mark.parametrize("sql, params, expected", [ + ("SELECT x.ssn FROM (SELECT ssn FROM users) AS x", None, (ColumnRef("ssn", "users"),)), + ("SELECT ssn FROM (SELECT ssn FROM users) x", None, (ColumnRef("ssn", "users"),)), + ("WITH c AS (SELECT ssn FROM users) SELECT c.ssn FROM c", None, (ColumnRef("ssn", "users"),)), + ("SELECT y.ssn FROM (SELECT x.ssn FROM (SELECT ssn FROM users) x) y", None, (ColumnRef("ssn", "users"),)), + ("SELECT x.s FROM (SELECT ssn AS s FROM users) x", None, (ColumnRef("ssn", "users"),)), + ("WITH c AS (SELECT ssn FROM users) SELECT x.ssn FROM (SELECT ssn FROM c) x", None, + (ColumnRef("ssn", "users"),)), + ("SELECT u.name, d.ssn FROM users u JOIN (SELECT id, ssn FROM archive) d ON d.id = u.id", None, + (ColumnRef("name", "users"), ColumnRef("ssn", "archive"))), + ("WITH a AS (SELECT id FROM archive), c AS (SELECT ssn FROM users) SELECT c.ssn FROM c", None, + (ColumnRef("ssn", "users"),)), + ("SELECT y.ssn FROM (SELECT id FROM archive) x JOIN (SELECT id, ssn FROM users) y ON x.id = y.id", None, + (ColumnRef("ssn", "users"),)), + # SQLAlchemy's legacy Query.first() over a model with a joined eager load. + ("SELECT anon_1.users_id AS anon_1_users_id, anon_1.users_ssn AS anon_1_users_ssn, addresses_1.id AS addresses_1_id " + "FROM (SELECT users.id AS users_id, users.ssn AS users_ssn FROM users LIMIT %s) AS anon_1 " + "LEFT OUTER JOIN addresses AS addresses_1 ON anon_1.users_id = addresses_1.user_id", P, + (ColumnRef("id", "users"), ColumnRef("ssn", "users"), ColumnRef("id", "addresses"))), + ], ids=["derived", "only_source", "cte", "nested", "relabelled", "cte_behind_derived", "joined", "two_ctes", + "second_derived", "orm_first"]) + def test_derived_and_cte_columns_trace_to_their_table(self, dialect, sql, params, expected): + assert analyze(sql, dialect, params).result_columns == expected + + @BOTH + @pytest.mark.parametrize("sql", [ + "SELECT x.ssn FROM (SELECT ssn FROM users UNION SELECT ssn FROM archive) x", + "SELECT x.ssn FROM (SELECT * FROM users) x", + "SELECT x.s FROM (SELECT upper(ssn) AS s FROM users) x", + "SELECT ssn FROM (SELECT ssn FROM users) x, (SELECT ssn FROM archive) y", + "SELECT g.ssn FROM (SELECT ssn FROM users) y CROSS JOIN generate_series(1, 2) AS g", + ], ids=["set_operation", "star", "expression", "two_sources", "function_source"]) + def test_untraceable_derived_columns_stay_unknown(self, dialect, sql): + assert analyze(sql, dialect).result_columns == (None,) + + @BOTH + def test_self_shadowing_cte_stays_unknown(self, dialect): + # The inner users is the table, but every unqualified users reads as + # the CTE, and a CTE doesn't see itself, so the trace stops there. + assert analyze("WITH users AS (SELECT ssn FROM users) SELECT ssn FROM users", dialect).result_columns == (None,) + + @BOTH + @pytest.mark.parametrize("sql, expected", [ + # Inside c, users is the table: a later CTE of that name isn't seen. + ("WITH c AS (SELECT ssn FROM users), users AS (SELECT name AS ssn FROM people) SELECT ssn FROM c", (None,)), + ("WITH c AS (SELECT u.ssn FROM users u), users AS (SELECT name AS ssn FROM people) SELECT c.ssn FROM c", (None,)), + ("WITH c AS (SELECT x.ssn FROM (SELECT ssn FROM users) x), users AS (SELECT name AS ssn FROM people) " + "SELECT ssn FROM c", (None,)), + ("WITH users AS (SELECT name AS ssn FROM people), c AS (SELECT ssn FROM users) SELECT ssn FROM c", + (ColumnRef("name", "people"),)), + # Past c, the trace takes the outer users; under RECURSIVE, PostgreSQL + # reads the later inner one instead, so the column stays unknown. + ("WITH users AS (SELECT addr AS ssn FROM homes) SELECT z.ssn FROM (WITH c AS (SELECT ssn FROM users), " + "users AS (SELECT name AS ssn FROM people) SELECT ssn FROM c) z", (ColumnRef("addr", "homes"),)), + ("WITH users AS (SELECT addr AS ssn FROM homes) SELECT z.ssn FROM (WITH RECURSIVE c AS (SELECT ssn FROM users), " + "users AS (SELECT name AS ssn FROM people) SELECT ssn FROM c) z", (None,)), + ], ids=["forward", "forward_qualified", "forward_in_derived", "backward", "nested_outer", "nested_outer_recursive"]) + def test_a_cte_sees_only_the_ctes_before_it(self, dialect, sql, expected): + assert analyze(sql, dialect).result_columns == expected + + @BOTH + @pytest.mark.parametrize("sql", [ + "WITH c(ssn, name) AS (SELECT name, ssn FROM users) SELECT c.ssn, c.name FROM c", + "SELECT x.ssn, x.name FROM (SELECT name, ssn FROM users) AS x(ssn, name)", + ], ids=["cte", "derived"]) + def test_a_source_with_a_column_list_stays_unknown(self, dialect, sql): + # The list renames the columns by position (here c.ssn is users.name), + # which the trace doesn't follow. + assert analyze(sql, dialect).result_columns == (None, None) + + @pytest.mark.parametrize("sql, expected", [ + ("WITH c AS (SELECT name, ssn FROM users) SELECT x.ssn FROM c AS x(ssn, name)", (None,)), + ("SELECT d.ssn FROM users AS u(a, b) JOIN (SELECT id, ssn FROM archive) d ON d.id = u.a", + (ColumnRef("ssn", "archive"),)), + ], ids=["cte_renamed_where_read", "other_source_renamed"]) + def test_only_a_column_list_on_the_traced_source_matters(self, sql, expected): + assert analyze(sql, PG).result_columns == expected + + def test_returning_list_is_not_traced(self): + a = analyze("UPDATE users SET name = %s FROM (SELECT id, ssn FROM archive) x WHERE users.id = x.id " + "RETURNING x.ssn", PG, P) + assert a.result_columns == (None,) + + def test_trace_stops_after_eight_levels(self): + def nested(levels): + sql = "SELECT ssn FROM users" + for i in range(levels): + sql = f"SELECT t{i}.ssn FROM ({sql}) t{i}" + return sql + + assert analyze(nested(8), PG).result_columns == (ColumnRef("ssn", "users"),) + assert analyze(nested(9), PG).result_columns == (None,) + + @pytest.mark.parametrize("sql, expected", [ + ('SELECT x."S" FROM (SELECT ssn AS "S" FROM users) x', (ColumnRef("ssn", "users"),)), + ('SELECT x.s FROM (SELECT ssn AS "S" FROM users) x', (None,)), + ], ids=["quoted", "unquoted"]) + def test_quoted_alias_matches_as_quoted(self, sql, expected): + assert analyze(sql, PG).result_columns == expected + + @pytest.mark.parametrize("sql", [ + "SELECT x.s FROM (SELECT ssn AS `S` FROM users) x", + "SELECT X.SSN FROM (SELECT ssn FROM users) x", + ], ids=["alias", "qualifier"]) + def test_mysql_traces_names_without_case(self, sql): + assert analyze(sql, MYSQL).result_columns == (ColumnRef("ssn", "users"),) + + def test_union_tables(self): + assert names(analyze("SELECT ssn FROM users UNION ALL SELECT ssn FROM archive", PG).tables) == [ + "users", "archive"] + + def test_for_update_is_not_a_write(self): + assert not analyze("SELECT * FROM users WHERE id = %s FOR UPDATE", PG, P).writes + + +class TestIdentifiers: + def test_postgresql_folds_ascii_letters_only(self): + # As PostgreSQL does in a multibyte (UTF-8) database. + assert PG.fold_identifier("ƄBc", quoted=False) == "Ƅbc" + assert PG.fold_identifier("ƄBc", quoted=True) == "ƄBc" + assert MYSQL.fold_identifier("ƄBc", quoted=False) == "ƄBc" + assert (PG.metadata_key("Users"), MYSQL.metadata_key("Users")) == ("Users", "users") + + def test_postgresql_folds_unquoted_names(self): + a = analyze('INSERT INTO Users (Name, "SSN") VALUES (%s, %s)', PG, P) + assert assigned(a) == [(0, "users.name"), (1, "users.SSN")] + + def test_postgresql_quoted_table(self): + a = analyze('UPDATE "Users" SET ssn = %s', PG, P) + assert names(a.written_tables) == ["Users"] + + def test_mysql_keeps_case_and_strips_backticks(self): + a = analyze("INSERT INTO `Users` (`Name`, SSN) VALUES (%s, %s)", MYSQL, P) + assert assigned(a) == [(0, "Users.Name"), (1, "Users.SSN")] + + def test_mysql_alias_match_is_case_insensitive(self): + a = analyze("UPDATE users U SET u.ssn = %s WHERE U.id = %s", MYSQL, P) + assert assigned(a) == [(0, "users.ssn")] and compared(a) == [(1, "users.id")] + + def test_quoted_alias(self): + a = analyze('SELECT "U".ssn FROM users "U" WHERE "U".id = %s', PG, P) + assert compared(a) == [(0, "users.id")] + + +class TestAnnotations: + def test_annotation_overrides_inference(self): + a = analyze("INSERT INTO t (a, b) VALUES (/*@encrypt:users.ssn*/ %s, %s)", PG, P) + assert [(u.ordinal, str(u.column)) for u in a.annotations] == [(0, "users.ssn")] + assert a.parameter_columns() == {0: ColumnRef("ssn", "users"), 1: ColumnRef("b", "t")} + + def test_alias_qualifier_is_resolved(self): + a = analyze("UPDATE users u SET note = /*@encrypt:u.ssn*/ %s", PG, P) + assert [str(u.column) for u in a.annotations] == ["users.ssn"] + + def test_annotations_survive_an_unparseable_statement(self): + a = analyze("INSERT INTO t OVERRIDING SYSTEM VALUE VALUES (/*@encrypt:t.ssn*/ %s)", PG, P) + assert a.gap is AnalysisGap.UNPARSEABLE + assert [str(u.column) for u in a.annotations] == ["t.ssn"] + + def test_annotations_survive_an_unsupported_statement(self): + a = analyze("EXPLAIN ANALYZE INSERT INTO t (a) VALUES (/*@encrypt:t.a*/ %s)", PG, P) + assert [str(u.column) for u in a.annotations] == ["t.a"] + + def test_stray_annotations_are_reported(self): + a = analyze("INSERT INTO t (a) VALUES (%s) /*@encrypt:t.a*/", PG, P) + assert a.stray_annotations == ("/*@encrypt:t.a*/",) + + +class TestNotEstablished: + @pytest.mark.parametrize("dialect, sql, params, gap", [ + (PG, "INSERT INTO t (a) VALUES ('%s')", P, AnalysisGap.HIDDEN_PLACEHOLDER), + (MYSQL, "INSERT INTO t (a) VALUES (%s) -- %s", P, AnalysisGap.HIDDEN_PLACEHOLDER), + (PG, "INSERT INTO t (a) VALUES (%s, %(x)s)", P, AnalysisGap.DRIVER_ERROR), + (PG, "INSERT INTO t (a) VALUES (%s) WHERE 1 % 2", P, AnalysisGap.DRIVER_ERROR), + (PG, "INSERT INTO t (a) VALUES ('abc", P, AnalysisGap.UNPARSEABLE), + (PG, "INSERT INTO t (a VALUES (%s)", P, AnalysisGap.UNPARSEABLE), + (PG, "INSERT INTO t (a) OVERRIDING SYSTEM VALUE VALUES (%s)", P, AnalysisGap.UNPARSEABLE), + (PG, "EXPLAIN ANALYZE INSERT INTO t (a) VALUES (%s)", P, AnalysisGap.UNSUPPORTED_STATEMENT), + (PG, "EXECUTE p (%s)", P, AnalysisGap.UNSUPPORTED_STATEMENT), + (MYSQL, "LOAD DATA INFILE 'x' INTO TABLE t", None, AnalysisGap.UNSUPPORTED_STATEMENT), + (PG, "SET search_path TO app; INSERT INTO t (a) VALUES (%s)", P, AnalysisGap.UNSUPPORTED_STATEMENT), + ]) + def test_writes_not_established(self, dialect, sql, params, gap): + a = analyze(sql, dialect, params) + assert a.writes and a.gap is gap and not a.complete + assert a.assignments == () and a.unbound_writes == () + + @pytest.mark.parametrize("dialect, sql, tables", [ + (PG, "INSERT INTO t (a, b) VALUES (%s, 'x%s')", (TableRef("t"),)), + (PG, 'SELECT a AS "x%s" FROM t WHERE b = %s', (TableRef("t"),)), + (PG, "UPDATE app.t SET a = %s /* %s */ WHERE id = %s", (TableRef("t", "app"),)), + (PG, "SELECT t.a FROM t JOIN u ON u.id = t.id WHERE t.b = %s AND t.c = 'x%s'", (TableRef("t"), TableRef("u"))), + (PG, "WITH c AS (SELECT a FROM t) SELECT a FROM c WHERE a = %s -- %s", (TableRef("t"),)), + (PG, "PREPARE p AS INSERT INTO t (a, b) VALUES ($1, 'x%s')", (TableRef("t"),)), + (MYSQL, "INSERT INTO t (a, b) VALUES (%s, 'x%s')", (TableRef("t"),)), + (MYSQL, "SELECT a AS `x%s` FROM t WHERE b = %s", (TableRef("t"),)), + (MYSQL, "UPDATE app.t SET a = %s WHERE id = %s -- %s", (TableRef("t", "app"),)), + (MYSQL, "INSERT INTO t (a, `b%s`) VALUES (%s, %s)", (TableRef("t"),)), + (MYSQL, "SELECT t.a FROM t JOIN u ON u.id = t.id WHERE t.b = %s # %s", (TableRef("t"), TableRef("u"))), + (MYSQL, "INSERT INTO t (t.a, t.b) VALUES (%s, 'x%s')", (TableRef("t"),)), + # The main path doesn't analyze these statements, but their tables + # must still be listed, or a caller would let them reach a table with + # encrypted columns. + (PG, "SET search_path TO app; INSERT INTO t (a, b) VALUES (%s, 'x%s')", (TableRef("t"),)), + (PG, "CREATE TABLE u AS SELECT a FROM t WHERE b = %s AND c = 'x%s'", (TableRef("u"), TableRef("t"))), + (MYSQL, "EXPLAIN INSERT INTO t (a, b) VALUES (%s, 'x%s')", (TableRef("t"),)), + (MYSQL, "DESCRIBE SELECT a FROM t WHERE b = %s AND c = 'x%s'", (TableRef("t"),)), + ], ids=["pg_literal", "pg_identifier_select", "pg_comment", "pg_join", "pg_cte", "pg_prepare", "mysql_literal", + "mysql_identifier_select", "mysql_comment", "mysql_identifier", "mysql_join", "mysql_qualified_columns", + "pg_set_then_insert", "pg_create_table_as", "mysql_explain_insert", "mysql_describe_select"]) + def test_hidden_placeholder_gap_still_lists_the_tables(self, dialect, sql, tables): + # The tables are what lets a caller refuse such a statement when one + # of them has encrypted columns; the placeholders still can't be + # paired with columns, so nothing else is reported. + a = analyze(sql, dialect, P) + assert a.gap is AnalysisGap.HIDDEN_PLACEHOLDER and a.kind is StatementKind.UNKNOWN + assert a.tables == tables + assert a.assignments == () and a.comparisons == () and a.annotations == () and a.result_columns is None + + def test_unparseable_read_is_not_a_write(self): + a = analyze("SELECT FROM WHERE %s", PG, P) + assert a.kind is StatementKind.UNKNOWN and not a.writes + + @pytest.mark.parametrize("sql", ["CREATE TABLE t (a int)", "BEGIN", "CALL p(1)", "", " -- just a comment"]) + def test_statements_that_write_no_column(self, sql): + a = analyze(sql, PG) + assert not a.writes and a.complete + + def test_placeholder_text_in_the_sql_is_a_mismatch(self): + # Something that looks like a normalized placeholder must not be + # taken for one. + a = analyze("INSERT INTO t (a, b) VALUES (%s, :_kms_p0)", PG, P) + assert a.gap is AnalysisGap.PLACEHOLDER_MISMATCH + + def test_parser_failure_of_any_kind_is_unparseable(self, monkeypatch): + def boom(*_args, **_kwargs): + raise RecursionError("too deep") + monkeypatch.setattr(sql_analyzer.sqlglot, "parse", boom) + a = sql_analyzer._analysis("INSERT INTO t (a) VALUES (%s)", PG, sql_analyzer.ParamStyle.POSITIONAL) + assert a.gap is AnalysisGap.UNPARSEABLE and a.detail == "RecursionError" + + def test_mysql_without_params_leaves_percent_s(self): + # Connector/Python sends %s as written when there are no parameters. + a = analyze("INSERT INTO t (a) VALUES (%s)", MYSQL, ()) + assert a.placeholders == () and a.gap is AnalysisGap.UNPARSEABLE + + +class TestApi: + def test_cached_and_immutable(self): + a = analyze("SELECT * FROM t WHERE a = %s", PG, P) + assert analyze("SELECT * FROM t WHERE a = %s", PG, [2]) is a + with pytest.raises(AttributeError): + a.writes = True # type: ignore[misc] + + def test_cache_is_per_dialect_and_style(self): + sql = "SELECT * FROM t WHERE a = %s" + assert analyze(sql, PG, P) is not analyze(sql, MYSQL, P) + assert analyze(sql, PG, P) is not analyze(sql, PG, None) + + def test_long_sql_is_not_cached(self): + rows = ", ".join(["(%s, %s)"] * 2000) + sql = f"INSERT INTO users (name, ssn) VALUES {rows}" + assert len(sql) > sql_analyzer.CACHEABLE_SQL_LENGTH + a = analyze(sql, MYSQL, P) + assert len(a.assignments) == 4000 and a.assignments[-1].ordinal == 3999 + assert analyze(sql, MYSQL, P) is not a + + def test_short_sql_with_many_placeholders_is_not_cached(self): + # A bulk INSERT under the length limit still holds an object per + # placeholder; caching every row count would grow without need. + sql = "INSERT INTO t (a) VALUES " + ",".join(["(%s)"] * (sql_analyzer.CACHEABLE_PERCENT_SIGNS + 1)) + assert len(sql) <= sql_analyzer.CACHEABLE_SQL_LENGTH + assert analyze(sql, PG, P) is not analyze(sql, PG, P) + + def test_nested_results_are_frozen(self): + a = analyze("INSERT INTO users (ssn) VALUES (%s)", PG, P) + with pytest.raises(dataclasses.FrozenInstanceError): + a.assignments[0].column = ColumnRef("x") # type: ignore[misc] + with pytest.raises(dataclasses.FrozenInstanceError): + a.assignments[0].column.table = "x" # type: ignore[misc] + with pytest.raises(dataclasses.FrozenInstanceError): + a.placeholders[0].key = 5 # type: ignore[misc] + + def test_recursion_error_is_not_cached(self, monkeypatch): + # How deep sqlglot can recurse depends on the caller's stack, so a + # failure for one caller must not be served to the next. + real = sqlglot.parse + calls = [] + + def flaky(sql, read): + calls.append(sql) + if len(calls) == 1: + raise RecursionError("too deep") + return real(sql, read=read) + + monkeypatch.setattr(sql_analyzer.sqlglot, "parse", flaky) + sql = "UPDATE users SET ssn = %s" + assert analyze(sql, PG, P).gap is AnalysisGap.UNPARSEABLE + assert analyze(sql, PG, P).gap is None + + def test_deep_nesting_from_a_deep_stack_is_a_gap(self): + sql = "UPDATE users SET ssn = " + "(" * 40 + "%s" + ")" * 40 + result = [] + + def deep(n): + if n: + return deep(n - 1) + result.append(analyze(sql, PG, P)) + + thread = threading.Thread(target=deep, args=(sys.getrecursionlimit() - 200,)) + thread.start() + thread.join() + assert result and result[0].gap is AnalysisGap.UNPARSEABLE + + def test_type_error_for_non_str(self): + with pytest.raises(TypeError): + analyze(b"SELECT 1", PG) # type: ignore[arg-type] + + @pytest.mark.parametrize("dialect, sql, params", [ + (MYSQL, "CALL p(%s)", P), + (PG, "EXPLAIN ANALYZE INSERT INTO t (a) VALUES (%s)", P), + # Parsed, but sqlglot falls back to a command (and would log the + # statement, literal included). + (PG, "COPY users (ssn) FROM STDIN WITH (FORMAT text) WHERE ssn <> '123-45-6789'", None), + (MYSQL, "SELECT JSON_EXTRACT(doc, '$[last]') FROM t WHERE ssn = '123-45-6789'", None), + ]) + def test_the_parser_never_logs_statement_text(self, caplog, dialect, sql, params): + with caplog.at_level(logging.DEBUG, logger="sqlglot"): + analyze(sql, dialect, params) + assert caplog.records == [] + + def test_the_applications_own_sqlglot_logging_is_untouched(self, caplog): + with caplog.at_level(logging.WARNING, logger="sqlglot"): + sqlglot.parse("CALL p(1)", read="mysql") + assert caplog.records + + @pytest.mark.parametrize("dialect, sql, params", [ + (PG, "INSERT INTO t (c, d) VALUES ('100%(card 4111-1111-1111-1111)x', %s)", P), + (PG, "INSERT INTO t (c, d) VALUES ('4111-1111-1111-1111 %d', %s)", P), + (MYSQL, "INSERT INTO t (c) VALUES (%(ssn 123-45-6789)d)", {"a": 1}), + (PG, "INSERT INTO t (secret_col) VALUES ('top secret', %s", P), + ]) + def test_detail_never_quotes_the_sql(self, dialect, sql, params): + a = analyze(sql, dialect, params) + assert a.gap is not None + assert a.detail is not None or a.gap is AnalysisGap.UNPARSEABLE + for secret in ("4111", "123-45", "secret"): + assert secret not in (a.detail or "") + + +class TestReviewRegressions: + """Regression tests for statements the analysis once got wrong: annotation + scopes, MySQL syntax, ORM-rendered SQL and statement kinds.""" + + # ---- annotations resolve in the placeholder's own scope ---- + + @pytest.mark.parametrize("dialect, sql, expected", [ + (MYSQL, "UPDATE accounts u SET x = %s WHERE id = 1; UPDATE users u SET ssn = /*@encrypt:u.ssn*/ %s", + {0: "accounts.x", 1: "users.ssn"}), + (PG, "WITH w AS (UPDATE users u SET ssn = /*@encrypt:u.ssn*/ %s RETURNING u.id) SELECT * FROM w", + {0: "users.ssn"}), + (PG, "WITH w AS (INSERT INTO users AS u (ssn) VALUES (/*@encrypt:u.ssn*/ %s) RETURNING id) SELECT * FROM w", + {0: "users.ssn"}), + (PG, "UPDATE users u SET name = %s WHERE id IN " + "(SELECT uid FROM accounts u WHERE u.secret = /*@encrypt:u.secret*/ %s)", + {0: "users.name", 1: "accounts.secret"}), + (PG, "SELECT 1 FROM accounts u UNION SELECT 1 FROM users u WHERE u.ssn = /*@encrypt:u.ssn*/ %s", + {0: "users.ssn"}), + ]) + def test_annotation_alias_is_resolved_where_the_placeholder_is(self, dialect, sql, expected): + a = analyze(sql, dialect, P) + assert {k: str(v) for k, v in a.parameter_columns().items()} == expected + + def test_bare_annotation_keeps_the_table_the_analysis_found(self): + a = analyze("UPDATE users SET ssn = /*@encrypt:ssn*/ %s", PG, P) + assert a.parameter_columns() == {0: ColumnRef("ssn", "users")} + + def test_bare_annotation_naming_another_column_takes_the_only_table(self): + a = analyze("INSERT INTO users (note) VALUES (/*@encrypt:ssn*/ %s)", PG, P) + assert a.parameter_columns() == {0: ColumnRef("ssn", "users")} + + def test_mysql_annotation_alias_is_case_insensitive(self): + a = analyze("UPDATE users u SET note = /*@encrypt:U.ssn*/ %s", MYSQL, P) + assert [str(u.column) for u in a.annotations] == ["users.ssn"] + + @pytest.mark.parametrize("sql", [ + "INSERT INTO t (a, b) VALUES (/*@encrypt:t.a*/ %s, '%s')", # hidden placeholder + "INSERT INTO t (a, b) VALUES (/*@encrypt:t.a*/ %s, :_kms_p0)", # placeholder mismatch + ]) + def test_annotations_survive_every_gap(self, sql): + a = analyze(sql, PG, P) + assert a.gap is not None + assert [str(u.column) for u in a.annotations] == ["t.a"] + + # ---- MySQL executable comments run on the server ---- + + @pytest.mark.parametrize("sql", [ + "INSERT INTO users (/*!80000 ssn, */ name) VALUES (%s /*!80000 , DEFAULT*/)", + "INSERT INTO users (name, ssn) VALUES (%s, %s) /*! ON DUPLICATE KEY UPDATE ssn = 'plain' */", + "UPDATE users SET name = %s /*!, ssn = 'plain' */ WHERE id = %s", + "SELECT 1 /*M! , 2 */", + ]) + def test_executable_comment_is_not_established(self, sql): + a = analyze(sql, MYSQL, P) + assert a.gap is AnalysisGap.EXECUTABLE_COMMENT + assert a.assignments == () + + def test_executable_comment_write_keyword_counts(self): + assert analyze("SELECT 1 /*! ; INSERT INTO t (a) VALUES (1) */", MYSQL).writes + + def test_optimizer_hint_is_an_ordinary_comment(self): + a = analyze("UPDATE /*+ NO_INDEX_MERGE(users) */ users SET ssn = %s", MYSQL, P) + assert a.complete and assigned(a) == [(0, "users.ssn")] + + # ---- MySQL charset introducers (Django renders binary values as _binary %s) ---- + + def test_binary_introducer_in_insert(self): + a = analyze("INSERT INTO `Person` (`name`, `ssn`, `note`) VALUES (%s, _binary %s, %s), (%s, _binary %s, %s)", + MYSQL, P) + assert a.complete and unbound(a) == [] + assert assigned(a) == [(0, "Person.name"), (1, "Person.ssn"), (2, "Person.note"), + (3, "Person.name"), (4, "Person.ssn"), (5, "Person.note")] + assert [p.introducer for p in a.placeholders] == [None, "_binary", None] * 2 + + def test_binary_introducer_in_update_and_upsert(self): + a = analyze("UPDATE `Person` SET `ssn` = _binary %s, `name` = %s WHERE `Person`.`id` = %s", MYSQL, P) + assert a.complete and assigned(a) == [(0, "Person.ssn"), (1, "Person.name")] + a = analyze("INSERT INTO `Person` (`ssn`) VALUES (_binary %s) AS new ON DUPLICATE KEY UPDATE `ssn` = new.`ssn`", + MYSQL, P) + assert a.complete and unbound(a) == [] + + def test_introducer_needs_a_known_charset(self): + # "_x %s" is not an introducer, so the statement reads as written. + a = analyze("SELECT _x %s", MYSQL, P) + assert [p.introducer for p in a.placeholders] == [None] + + def test_introducer_only_on_mysql(self): + assert analyze("SELECT _binary %s", PG, P).placeholders[0].introducer is None + + # ---- MySQL row alias with a column list renames by position ---- + + def test_row_alias_columns_copy_by_position(self): + a = analyze("INSERT INTO users (name, ssn) VALUES (%s, %s) AS new(n, s) ON DUPLICATE KEY UPDATE ssn = new.s", + MYSQL, P) + assert unbound(a) == [] + + def test_row_alias_column_naming_another_insert_column_is_unbound(self): + # new.ssn is the incoming *name*: alias columns rename by position. + a = analyze("INSERT INTO users (name, ssn) VALUES (%s, %s) AS new(ssn, name) " + "ON DUPLICATE KEY UPDATE ssn = new.ssn", MYSQL, P) + assert unbound(a) == ["users.ssn"] + + # ---- copies from another table ---- + + @pytest.mark.parametrize("dialect, sql", [ + (MYSQL, "UPDATE users u JOIN orders o ON o.uid = u.id SET u.ssn = o.ssn"), + (PG, "UPDATE users SET ssn = o.ssn FROM other o WHERE o.id = users.id"), + ]) + def test_copy_of_another_tables_column_of_the_same_name_is_unbound(self, dialect, sql): + assert unbound(analyze(sql, dialect)) == ["users.ssn"] + + # ---- SQLAlchemy's multi-row ORM insert on PostgreSQL ---- + + def test_insert_select_from_values_list(self): + sql = ("INSERT INTO users (name, ssn) SELECT p0::VARCHAR, p1::BYTEA FROM " + "(VALUES (%(name__0)s::VARCHAR, %(ssn__0)s, 0), (%(name__1)s::VARCHAR, %(ssn__1)s, 1)) " + "AS imp_sen(p0, p1, sen_counter) ORDER BY sen_counter RETURNING users.id, users.id AS id__1") + a = analyze(sql, PG, N) + assert a.complete + assert [(u.placeholder.key, str(u.column)) for u in a.assignments] == [ + ("name__0", "users.name"), ("ssn__0", "users.ssn"), ("name__1", "users.name"), ("ssn__1", "users.ssn")] + assert a.assignments[1].casts == ("VARBINARY",) + + @pytest.mark.parametrize("sql", [ + "INSERT INTO users (ssn) SELECT v.p0 FROM (VALUES (%s)) AS v(p0) WHERE v.p0 IS NOT NULL", + "INSERT INTO users (ssn) SELECT upper(p0) FROM (VALUES (%s)) AS v(p0)", + "INSERT INTO users (ssn) SELECT p0 FROM (VALUES (%s)) AS v(p0) JOIN x ON true", + "INSERT INTO users (ssn) SELECT q FROM (VALUES (%s)) AS v(p0)", + "INSERT INTO users (name, ssn) SELECT %s, %s", + ]) + def test_other_insert_selects_are_values_from_query(self, sql): + assert analyze(sql, PG, P).gap is AnalysisGap.VALUES_FROM_QUERY + + # ---- statements that run a stored statement ---- + + def test_execute_may_write(self): + a = analyze("EXECUTE ins_user(%s, %s)", PG, P) + assert a.writes and a.gap is AnalysisGap.UNSUPPORTED_STATEMENT + + def test_prepare_body_is_read(self): + a = analyze("PREPARE ins (text, text) AS INSERT INTO users (name, ssn) VALUES ($1, '123-45-6789')", PG) + assert a.kind is StatementKind.INSERT and a.writes + assert a.gap is AnalysisGap.PREPARED_PARAMETERS + # The literal is reported as an unbound write; $1 is bound by a later + # EXECUTE. + assert unbound(a) == ["users.ssn"] + + def test_prepare_of_a_read(self): + a = analyze('PREPARE "q" AS SELECT ssn FROM users WHERE id = $1', PG) + assert a.kind is StatementKind.SELECT and not a.writes and a.complete + + # ---- DELETE ... USING ---- + + def test_delete_using_aliases_are_in_scope(self): + a = analyze("DELETE FROM users USING accounts a WHERE a.uid = users.id AND a.secret = %s RETURNING a.secret", + PG, P) + assert compared(a) == [(0, "accounts.secret")] + assert a.result_columns == (ColumnRef("secret", "accounts"),) + + # ---- ALL / SOME ---- + + @pytest.mark.parametrize("sql", ["SELECT * FROM t WHERE c <> ALL(%s)", "SELECT * FROM t WHERE c = SOME(%s)", + "SELECT * FROM t WHERE c = ANY(%s::text[])"]) + def test_all_some_and_any_are_array_comparisons(self, sql): + a = analyze(sql, PG, P) + assert [(u.ordinal, str(u.column), u.array) for u in a.comparisons] == [(0, "t.c", True)] + + # ---- MySQL qualified INSERT column lists ---- + + @pytest.mark.parametrize("sql, expected", [ + ("INSERT INTO users (users.name, users.ssn) VALUES (%s, %s)", [(0, "users.name"), (1, "users.ssn")]), + ("INSERT INTO mydb.users (mydb.users.ssn) VALUES (%s)", [(0, "users.ssn")]), + ("INSERT INTO `users` (`users`.`ssn`) VALUES (%s)", [(0, "users.ssn")]), + ]) + def test_mysql_qualified_insert_columns(self, sql, expected): + a = analyze(sql, MYSQL, P) + assert a.complete and assigned(a) == expected + + # ---- names that are not plain identifiers ---- + + def test_subscripted_column_is_not_a_column_name(self): + a = analyze("MERGE INTO t USING s ON 1=1 WHEN NOT MATCHED THEN INSERT (ssn[1]) VALUES (%s)", PG, P) + assert a.gap is AnalysisGap.UNSUPPORTED_STATEMENT + assert assigned(a) == [] + + # ---- keyword fallback ---- + + @pytest.mark.parametrize("sql", [ + "SET search_path TO app; WITH w AS (INSERT INTO users (ssn) VALUES (%s) RETURNING id) SELECT * FROM w", + "SET search_path TO app; COPY users (ssn) FROM STDIN", + ]) + def test_unparsed_statement_before_a_write_is_not_complete(self, sql): + a = analyze(sql, PG, P) + assert a.writes and a.gap is AnalysisGap.UNSUPPORTED_STATEMENT + + # ---- parse-trust guards ---- + + def test_placeholder_missing_from_the_parse_is_a_mismatch(self, monkeypatch): + real = sqlglot.parse + monkeypatch.setattr(sql_analyzer.sqlglot, "parse", + lambda _sql, read: real("INSERT INTO users (name, ssn) VALUES (:_kms_p0, 'x')", read=read)) + a = sql_analyzer._analysis("INSERT INTO users (name, ssn) VALUES (%s, %s)", PG, ParamStyle.POSITIONAL) + assert a.gap is AnalysisGap.PLACEHOLDER_MISMATCH and a.assignments == () + + def test_command_fallback_is_unparseable(self, monkeypatch): + monkeypatch.setattr(sql_analyzer.sqlglot, "parse", lambda _sql, read: [exp.Command(this="INSERT")]) + a = sql_analyzer._analysis("INSERT INTO users (ssn) VALUES ('x')", PG, ParamStyle.NONE) + assert a.writes and a.gap is AnalysisGap.UNPARSEABLE + + def test_unterminated_is_unparseable_even_if_the_parser_accepts_it(self, monkeypatch): + real = sqlglot.parse + monkeypatch.setattr(sql_analyzer.sqlglot, "parse", + lambda _sql, read: real("INSERT INTO users (ssn) VALUES (:_kms_p0)", read=read)) + a = sql_analyzer._analysis("INSERT INTO users (ssn) VALUES (%s) /* a /* b */", PG, ParamStyle.POSITIONAL) + assert a.writes and a.gap is AnalysisGap.UNPARSEABLE and a.assignments == () + + # ---- row lengths ---- + + @pytest.mark.parametrize("sql", [ + "INSERT INTO users (a) VALUES (%s, %s)", + "MERGE INTO users u USING src s ON u.id = s.id WHEN NOT MATCHED THEN INSERT (id, ssn) VALUES (%s)", + "MERGE INTO users u USING src s ON u.id = s.id WHEN NOT MATCHED THEN INSERT (id) VALUES (%s, %s)", + ]) + def test_row_length_mismatch_both_ways(self, sql): + assert analyze(sql, PG, P).gap is AnalysisGap.ROW_LENGTH_MISMATCH + + def test_several_selects_have_no_result_columns(self): + assert analyze("SELECT ssn FROM users; SELECT name FROM accounts", PG).result_columns is None + + # ---- performance ---- + + def test_long_boolean_chain_is_linear(self): + sql = "SELECT ssn FROM users WHERE " + " OR ".join(["(id = %s AND ssn = %s)"] * 3000) + a = analyze(sql, PG, P) + assert len(a.comparisons) == 6000 and a.comparisons[-1].column == ColumnRef("ssn", "users") + + +class TestReviewRegressionsRound2: + """Regression tests: annotations across tables, SQLAlchemy's multi-row + insert, regex cost, caching and the logging filter.""" + + # ---- annotations ---- + + @pytest.mark.parametrize("sql, expected", [ + ("UPDATE users u SET name = %s WHERE id IN (SELECT uid FROM accounts a WHERE a.x = /*@encrypt:u.ssn*/ %s)", + {0: "users.name", 1: "users.ssn"}), + ("SELECT * FROM users u WHERE EXISTS " + "(SELECT 1 FROM accounts a WHERE a.uid = u.id AND a.x = /*@encrypt:u.ssn*/ %s)", + {0: "users.ssn"}), + ]) + def test_annotation_qualifier_resolves_through_outer_queries(self, sql, expected): + assert {k: str(v) for k, v in analyze(sql, PG, P).parameter_columns().items()} == expected + + @pytest.mark.parametrize("dialect, sql, expected", [ + (PG, "UPDATE users SET ssn = /*@encrypt:ssn*/ %s FROM accounts a WHERE a.id = users.id", + ColumnRef("ssn", "users")), + (MYSQL, "UPDATE users u JOIN accounts a ON a.uid = u.id SET u.SSN = /*@encrypt:ssn*/ %s", + ColumnRef("ssn", "users")), + # A column other than the one assigned: the single written table. + (PG, "UPDATE users SET note = /*@encrypt:ssn*/ %s FROM accounts a WHERE a.id = users.id", + ColumnRef("ssn", "users")), + # Several written tables and another column: the table can't be told. + (MYSQL, "UPDATE users u JOIN accounts a ON a.uid = u.id SET u.note = /*@encrypt:ssn*/ %s, a.x = 1", + ColumnRef("ssn")), + ]) + def test_bare_annotation_with_several_tables(self, dialect, sql, expected): + assert analyze(sql, dialect, P).parameter_columns() == {0: expected} + + @pytest.mark.parametrize("dialect, sql, expected", [ + (PG, "INSERT INTO orders (user_id, payment_info) SELECT id, /*@encrypt:payment_info*/ %s FROM temp", + ColumnRef("payment_info", "orders")), + (MYSQL, "INSERT INTO orders (payment_info) SELECT /*@encrypt:payment_info*/ %s FROM DUAL", + ColumnRef("payment_info", "orders")), + (PG, "INSERT INTO users (name, ssn) SELECT name, /*@encrypt:ssn*/ %s FROM accounts", ColumnRef("ssn", "users")), + (PG, "UPDATE users SET ssn = (SELECT /*@encrypt:ssn*/ %s FROM accounts)", ColumnRef("ssn", "users")), + ]) + def test_bare_annotation_in_a_query_feeding_a_write_names_the_written_table(self, dialect, sql, expected): + # The value goes to the write's target, even though the subquery reads another table. + assert analyze(sql, dialect, P).parameter_columns()[0] == expected + + # ---- SQLAlchemy's multi-row insert ---- + + def test_insert_select_from_values_maps_select_items_by_name(self): + a = analyze("INSERT INTO users (name, ssn) SELECT p1, p0 FROM (VALUES (%s, %s)) AS v(p0, p1)", PG, P) + assert a.complete + assert assigned(a) == [(0, "users.ssn"), (1, "users.name")] + + @pytest.mark.parametrize("sql", [ + "INSERT INTO users (ssn, note) SELECT p0, p0 FROM (VALUES (%s)) AS v(p0)", + "INSERT INTO users (name, ssn) SELECT v.p0, p0::text FROM (VALUES (%s, %s)) AS v(p0, p1)", + ]) + def test_insert_select_from_values_using_a_column_twice_is_not_read(self, sql): + # One value would fill two columns, and could be encrypted for only one. + a = analyze(sql, PG, P) + assert a.gap is AnalysisGap.VALUES_FROM_QUERY and a.assignments == () + + @pytest.mark.parametrize("sql, gap", [ + ("INSERT INTO users (name, ssn) SELECT p0 FROM (VALUES (%s, %s)) AS v(p0, p1)", AnalysisGap.VALUES_FROM_QUERY), + ("INSERT INTO users (name, ssn) SELECT p0, p1 FROM (VALUES (%s, %s), (%s)) AS v(p0, p1)", + AnalysisGap.ROW_LENGTH_MISMATCH), + ("INSERT INTO users (ssn) SELECT p0 FROM (VALUES (%s)) AS v(p0) FETCH FIRST 1 ROWS ONLY", + AnalysisGap.VALUES_FROM_QUERY), + ]) + def test_insert_select_from_values_widths_and_extras(self, sql, gap): + assert analyze(sql, PG, P).gap is gap + + # ---- regex cost on indented SQL ---- + + @pytest.mark.timeout(10) + @pytest.mark.parametrize("dialect, sql", [ + (MYSQL, "\n" + " " * 60 + "\n" + " " * 60 + "UPDATE users SET ssn = %s WHERE id = %s AND (name = 'x'"), + (MYSQL, " " * 60 + "SELECT a FROM t WHERE b = %s INTO OUTFILE '/tmp/x'"), + (MYSQL, " " * 60 + "INSERT INTO users (users.ssn) VALUE (%s"), + (PG, "\n" + " " * 60 + "PREPARE p (int) /* c */ AS INSERT INTO users (ssn) VALUES ($1)"), + (PG, "/* a */" * 60 + " PREPARE p (int) /* c */ AS INSERT INTO users (ssn) VALUES ($1)"), + ]) + def test_leading_whitespace_and_comments_do_not_backtrack(self, dialect, sql): + assert analyze(sql, dialect, P).gap is not None + + def test_indented_prepare_and_qualified_insert_are_still_read(self): + a = analyze("\n PREPARE p (int) /* c */ AS INSERT INTO users (ssn) VALUES ('x')", PG) + assert a.gap is AnalysisGap.PREPARED_PARAMETERS and unbound(a) == ["users.ssn"] + a = analyze("\n INSERT INTO users (users.ssn) VALUES (%s)", MYSQL, P) + assert a.complete and assigned(a) == [(0, "users.ssn")] + + # ---- MySQL qualified INSERT columns with dotted back-quoted names ---- + + @pytest.mark.parametrize("sql, expected", [ + ("INSERT INTO users (users.name, `x.ssn`) VALUES (%s, %s)", [(0, "users.name"), (1, "users.x.ssn")]), + ("INSERT INTO users (users.name, `ssn.v2`) VALUES (%s, %s)", [(0, "users.name"), (1, "users.ssn.v2")]), + ("INSERT INTO users (`users`.`ssn`, name) VALUES (%s, %s)", [(0, "users.ssn"), (1, "users.name")]), + ]) + def test_back_quoted_name_with_a_dot_is_one_name(self, sql, expected): + a = analyze(sql, MYSQL, P) + assert a.complete and assigned(a) == expected + + def test_qualifier_retry_only_for_inserts(self, monkeypatch): + calls = [] + real = sql_analyzer._without_insert_column_qualifiers + monkeypatch.setattr(sql_analyzer, "_without_insert_column_qualifiers", + lambda text: calls.append(text) or real(text)) + analyze("UPDATE users SET ssn = %s WHERE (", MYSQL, P) + assert calls == [] + + # ---- keyword fallback ---- + + @pytest.mark.parametrize("dialect, sql", [ + (PG, "SET search_path TO app; PREPARE p AS INSERT INTO users (ssn) VALUES ('123-45-6789')"), + (PG, "EXPLAIN ANALYZE EXECUTE p(%s)"), + (MYSQL, "SELECT 1 /*!LOAD DATA INFILE 'x' INTO TABLE users */"), + ]) + def test_more_statements_that_may_write(self, dialect, sql): + a = analyze(sql, dialect, P) + assert a.writes and a.gap is not None + + # ---- names that are not plain identifiers ---- + + def test_subscripted_update_target_is_unsupported(self): + a = analyze("UPDATE users SET ssn[1] = %s", PG, P) + assert a.writes and a.gap is AnalysisGap.UNSUPPORTED_STATEMENT and a.assignments == () + + # ---- TABLE is not parsed (sqlglot reads it as an alias) ---- + + def test_table_statement_is_not_parsed(self): + a = analyze("TABLE users", PG) + assert a.kind is StatementKind.SELECT and not a.writes and a.tables == () + + # ---- scopes ---- + + def test_nearest_query_memo_does_not_cross_queries(self): + a = analyze("SELECT * FROM users u WHERE EXISTS " + "(SELECT 1 FROM accounts WHERE u.name = %s GROUP BY secret HAVING secret = %s)", PG, P) + assert compared(a) == [(0, "users.name"), (1, "accounts.secret")] + + @pytest.mark.timeout(10) + def test_long_boolean_chain_is_time_bounded(self): + sql = "SELECT ssn FROM users WHERE " + " OR ".join(["(id = %s AND ssn = %s)"] * 12000) + assert len(analyze(sql, PG, P).comparisons) == 24000 + + # ---- caching ---- + + def test_long_sql_with_few_placeholders_is_not_cached(self): + sql = "UPDATE users SET ssn = %s WHERE note = '" + "x" * sql_analyzer.CACHEABLE_SQL_LENGTH + "'" + assert sql.count("%") <= sql_analyzer.CACHEABLE_PERCENT_SIGNS + assert analyze(sql, PG, P) is not analyze(sql, PG, P) + + def test_recursion_error_wrapped_by_the_tokenizer_is_not_cached(self, monkeypatch): + real = sqlglot.parse + calls = [] + + def flaky(sql, read): + calls.append(sql) + if len(calls) == 1: + try: + raise RecursionError("too deep") + except RecursionError as e: + raise sqlglot.errors.TokenError("wrapped") from e + return real(sql, read=read) + + monkeypatch.setattr(sql_analyzer.sqlglot, "parse", flaky) + sql = "SELECT a FROM users WHERE ssn = %s" + first = analyze(sql, PG, P) + assert first.gap is AnalysisGap.UNPARSEABLE and first.detail == "RecursionError" + assert analyze(sql, PG, P).gap is None + + # ---- the logging filter is per thread ---- + + def test_quiet_filter_does_not_silence_other_threads(self, caplog): + entered, release = threading.Event(), threading.Event() + + def parse_elsewhere(): + with sql_analyzer._QUIET.active(): + entered.set() + release.wait(5) + + thread = threading.Thread(target=parse_elsewhere) + thread.start() + try: + assert entered.wait(5) + with caplog.at_level(logging.WARNING, logger="sqlglot"): + logging.getLogger("sqlglot").warning("application record") + assert [r.getMessage() for r in caplog.records] == ["application record"] + finally: + release.set() + thread.join() + + +class TestReviewRegressionsRound3: + """Regression tests: regexes that fail after a long gap, and which table a + bare annotation gets.""" + + # ---- regexes that fail after a long run of whitespace or comments ---- + + _BAD_PREPARE = "PREPARE p (int AS INSERT INTO users (ssn) VALUES ($1)" # unbalanced header + _PARTITION = "INSERT INTO users PARTITION (p0) (users.ssn) VALUES (%s)" # valid MySQL neither read can parse + + @pytest.mark.timeout(10) + @pytest.mark.parametrize("dialect, sql, gap", [ + (PG, " " * 60 + _BAD_PREPARE, AnalysisGap.UNSUPPORTED_STATEMENT), + (PG, "/* a */ " * 60 + _BAD_PREPARE, AnalysisGap.UNSUPPORTED_STATEMENT), + (PG, "-- " + "-" * 60 + "\n" + _BAD_PREPARE, AnalysisGap.UNSUPPORTED_STATEMENT), + (PG, "-- " * 60 + "\n" + _BAD_PREPARE, AnalysisGap.UNSUPPORTED_STATEMENT), + (PG, "-- header line\r\n" * 40 + _BAD_PREPARE, AnalysisGap.UNSUPPORTED_STATEMENT), + (PG, "PREPARE p" + "-- c\r\n" * 40 + "INSERT INTO users (ssn) VALUES ($1)", AnalysisGap.UNSUPPORTED_STATEMENT), + (MYSQL, " " * 60 + _PARTITION, AnalysisGap.UNPARSEABLE), + (MYSQL, "/* a */ " * 60 + _PARTITION, AnalysisGap.UNPARSEABLE), + (MYSQL, "-- " + "-" * 60 + "\n" + _PARTITION, AnalysisGap.UNPARSEABLE), + (MYSQL, "-- " + " -- ".join("abcdefghijklmnopqrstuvwxyz") + "\n" + _PARTITION, AnalysisGap.UNPARSEABLE), + (MYSQL, "-- c \n" * 40 + "INSERT INTO users SET ssn = %s, note = 'a' 'b' garbage(", AnalysisGap.UNPARSEABLE), + ], ids=["pg-spaces", "pg-comments", "pg-dash-banner", "pg-dashes", "pg-crlf", "pg-crlf-header", "my-spaces", + "my-comments", "my-dash-banner", "my-dashed-prose", "my-trailing-space"]) + def test_a_regex_that_fails_after_a_long_gap_fails_fast(self, dialect, sql, gap): + assert analyze(sql, dialect, P).gap is gap + + def test_line_comments_in_a_prepare_header(self): + a = analyze("-- c\r\n PREPARE -- x\r\n p (int) -- y \r\n AS INSERT INTO users (ssn) VALUES ('x')", PG) + assert a.gap is AnalysisGap.PREPARED_PARAMETERS and unbound(a) == ["users.ssn"] + + # ---- bare annotations: written vs compared values ---- + + @pytest.mark.parametrize("dialect, sql, ordinal, expected", [ + # A filter value gets the table it is compared in, even in a statement that writes. + (PG, "UPDATE users SET note = %s WHERE id IN " + "(SELECT user_id FROM cards WHERE lower(pan) = /*@encrypt:pan*/ %s)", 1, ColumnRef("pan", "cards")), + (PG, "INSERT INTO audit (note) SELECT note FROM users WHERE coalesce(ssn, '') = /*@encrypt:ssn*/ %s", + 0, ColumnRef("ssn", "users")), + (PG, "WITH c AS (SELECT user_id FROM cards WHERE lower(pan) = /*@encrypt:pan*/ %s) " + "UPDATE users SET flag = true WHERE id IN (SELECT user_id FROM c)", 0, ColumnRef("pan", "cards")), + # Another statement's write doesn't count. + (MYSQL, "UPDATE a SET x = %s; SELECT * FROM cards WHERE lower(pan) = /*@encrypt:pan*/ %s", + 1, ColumnRef("pan", "cards")), + (MYSQL, "SELECT * FROM users u WHERE u.tax = /*@encrypt:ssn*/ %s; UPDATE audit SET n = n + 1", + 0, ColumnRef("ssn", "users")), + (PG, "INSERT INTO logs (msg) VALUES (%s); SELECT id FROM users WHERE ssn || '' = /*@encrypt:ssn*/ %s", + 1, ColumnRef("ssn", "users")), + # Values that flow into the write: the written table. + (PG, "INSERT INTO users (ssn) SELECT /*@encrypt:ssn*/ %s FROM temp", 0, ColumnRef("ssn", "users")), + (PG, "UPDATE users SET note = (SELECT /*@encrypt:ssn*/ %s FROM temp LIMIT 1)", 0, ColumnRef("ssn", "users")), + # Values bound in a source of the write may feed it or only be compared + # with another table's column: the table can't be told. + (PG, "MERGE INTO users t USING (SELECT /*@encrypt:ssn*/ %s AS v) s ON t.id = 1 " + "WHEN NOT MATCHED THEN INSERT (id, ssn) VALUES (1, s.v)", 0, ColumnRef("ssn")), + (PG, "WITH s AS (SELECT /*@encrypt:ssn*/ %s AS v) INSERT INTO users (ssn) SELECT v FROM s", + 0, ColumnRef("ssn")), + # Several written tables: the table can't be told. + (MYSQL, "UPDATE users u JOIN accounts a ON a.uid = u.id " + "SET u.note = (SELECT /*@encrypt:ssn*/ %s FROM temp), a.x = 1", 0, ColumnRef("ssn")), + ]) + def test_bare_annotation_by_where_the_value_goes(self, dialect, sql, ordinal, expected): + assert analyze(sql, dialect, P).parameter_columns()[ordinal] == expected + + @pytest.mark.parametrize("dialect, sql, expected", [ + # A value compared or tested inside a written expression is not written. + (PG, "INSERT INTO audit (note) SELECT CASE WHEN lower(ssn) = /*@encrypt:ssn*/ %s THEN 'm' END FROM users", + ColumnRef("ssn", "users")), + (PG, "INSERT INTO audit (flag) SELECT lower(ssn) = /*@encrypt:ssn*/ %s FROM users", ColumnRef("ssn", "users")), + (MYSQL, "INSERT INTO audit (note) SELECT IF(lower(ssn) = /*@encrypt:ssn*/ %s, 'm', 'n') FROM users", + ColumnRef("ssn", "users")), + (PG, "INSERT INTO audit (note) SELECT CASE lower(ssn) WHEN /*@encrypt:ssn*/ %s THEN 'm' END FROM users", + ColumnRef("ssn", "users")), + (PG, "UPDATE users SET flag = (SELECT lower(pan) = /*@encrypt:pan*/ %s FROM cards LIMIT 1)", + ColumnRef("pan", "cards")), + (PG, "UPDATE users SET note = CASE WHEN lower(a.tax) = /*@encrypt:tax*/ %s THEN 'x' END " + "FROM accounts a WHERE a.uid = users.id", ColumnRef("tax")), + # The THEN value is written. + (PG, "UPDATE users SET note = CASE WHEN flag THEN /*@encrypt:ssn*/ %s END", ColumnRef("ssn", "users")), + # A parameter CTE or derived table compared with another table's column. + (PG, "WITH params AS (SELECT /*@encrypt:ssn*/ %s::text AS ssn) UPDATE orders o SET status = 'flagged' " + "FROM customers c, params p WHERE o.customer_id = c.id AND c.ssn = p.ssn", ColumnRef("ssn")), + (PG, "WITH params AS (SELECT /*@encrypt:ssn*/ %s AS ssn) INSERT INTO audit (customer_id) " + "SELECT c.id FROM customers c JOIN params p ON c.ssn = p.ssn", ColumnRef("ssn")), + (MYSQL, "INSERT INTO audit (customer_id) WITH params AS (SELECT /*@encrypt:ssn*/ %s AS ssn) " + "SELECT c.id FROM customers c JOIN params p ON c.ssn = p.ssn", ColumnRef("ssn")), + # A value fed to the write through a source: bare as well. + (PG, "INSERT INTO t (a) SELECT j.v FROM src JOIN (SELECT /*@encrypt:ssn*/ %s AS v) j ON true", + ColumnRef("ssn")), + (PG, "INSERT INTO t (a) SELECT s.v FROM (SELECT /*@encrypt:ssn*/ %s AS v) s", ColumnRef("ssn")), + ], ids=["case-when", "boolean-item", "mysql-if", "simple-case", "set-subquery-item", "set-case-two-sources", + "case-then", "param-cte-update", "param-cte-insert", "mysql-param-cte", "join-source", "from-source"]) + def test_bare_annotation_on_a_compared_or_source_value(self, dialect, sql, expected): + assert analyze(sql, dialect, P).parameter_columns()[0] == expected + + @pytest.mark.parametrize("dialect, sql, expected", [ + # THEN, ELSE and IF() results in an INSERT ... SELECT reading another table are written. + (PG, "INSERT INTO audit (note) SELECT CASE WHEN flag THEN /*@encrypt:ssn*/ %s END FROM users", + ColumnRef("ssn", "audit")), + (PG, "INSERT INTO audit (note) SELECT CASE WHEN flag THEN 'a' ELSE /*@encrypt:ssn*/ %s END FROM users", + ColumnRef("ssn", "audit")), + (MYSQL, "INSERT INTO audit (note) SELECT IF(flag, /*@encrypt:ssn*/ %s, 'n') FROM users", + ColumnRef("ssn", "audit")), + # Tests other than the plain comparisons. + (PG, "INSERT INTO audit (flag) SELECT lower(ssn) IN (/*@encrypt:ssn*/ %s) FROM users", ColumnRef("ssn", "users")), + (PG, "INSERT INTO audit (flag) SELECT lower(ssn) BETWEEN /*@encrypt:ssn*/ %s AND 'z' FROM users", + ColumnRef("ssn", "users")), + (PG, "INSERT INTO audit (flag) SELECT ssn ~ /*@encrypt:ssn*/ %s FROM users", ColumnRef("ssn", "users")), + (PG, "INSERT INTO audit (flag) SELECT doc @> /*@encrypt:ssn*/ %s::jsonb FROM users", ColumnRef("ssn", "users")), + (MYSQL, "INSERT INTO audit (flag) SELECT ssn REGEXP /*@encrypt:ssn*/ %s FROM users", ColumnRef("ssn", "users")), + (MYSQL, "INSERT INTO audit (flag) SELECT MATCH (ssn) AGAINST (/*@encrypt:ssn*/ %s) FROM users", + ColumnRef("ssn", "users")), + # The operand of a simple CASE. + (PG, "INSERT INTO audit (note) SELECT CASE /*@encrypt:ssn*/ %s WHEN lower(ssn) THEN 'm' END FROM users", + ColumnRef("ssn", "users")), + # A window's PARTITION BY is not written. + (PG, "INSERT INTO audit (n) SELECT row_number() OVER (PARTITION BY /*@encrypt:ssn*/ %s) FROM users", + ColumnRef("ssn", "users")), + # Sources that read a table: bare, not that table. + (PG, "INSERT INTO t (a) SELECT j.v FROM src JOIN (SELECT /*@encrypt:ssn*/ %s AS v FROM cards) j ON true", + ColumnRef("ssn")), + (PG, "INSERT INTO t (a) SELECT s.v FROM (SELECT /*@encrypt:ssn*/ %s AS v FROM cards) s", ColumnRef("ssn")), + (PG, "WITH s AS (SELECT /*@encrypt:ssn*/ %s AS v FROM cards) INSERT INTO users (note) SELECT v FROM s", + ColumnRef("ssn")), + (PG, "MERGE INTO users t USING (SELECT /*@encrypt:ssn*/ %s AS v FROM cards) s ON t.id = 1 " + "WHEN NOT MATCHED THEN INSERT (id, note) VALUES (1, s.v)", ColumnRef("ssn")), + (PG, "INSERT INTO t (a) SELECT l.v FROM src CROSS JOIN LATERAL (SELECT /*@encrypt:ssn*/ %s AS v FROM cards) l", + ColumnRef("ssn")), + (PG, "INSERT INTO t (a) SELECT l.v FROM src, LATERAL (SELECT /*@encrypt:ssn*/ %s AS v FROM cards) l", + ColumnRef("ssn")), + # A SET value in an UPDATE that also reads another table: the assignment is not a test. + (PG, "UPDATE users SET note = /*@encrypt:ssn*/ %s FROM cards c WHERE c.uid = users.id", + ColumnRef("ssn", "users")), + ], ids=["then", "else", "mysql-if-true", "in", "between", "regex", "jsonb-contains", "mysql-regexp", + "mysql-match", "simple-case-operand", "partition-by", "join-source-reads", "from-source-reads", + "cte-reads", "merge-using-reads", "cross-join-lateral-reads", "comma-lateral-reads", "set-with-from"]) + def test_bare_annotation_written_tested_or_from_a_source(self, dialect, sql, expected): + assert analyze(sql, dialect, P).parameter_columns()[0] == expected + + # A value tested by any of these operators resolves to the table it is tested against on + # every supported sqlglot, though the operators are Predicates only from 30.16. + @pytest.mark.parametrize("op", ["~*", "!~*", "<@", "&&", "?", "?|", "?&", "-|-", "&<", "&>"]) + def test_bare_annotation_tested_by_an_operator(self, op): + sql = f"UPDATE audit SET flag = (SELECT ssn {op} /*@encrypt:ssn*/ %s FROM users LIMIT 1)" + assert analyze(sql, PG, P).parameter_columns()[0] == ColumnRef("ssn", "users") + + def test_bare_annotation_tested_by_overlaps(self): + sql = "UPDATE audit SET flag = (SELECT (d1, ssn) OVERLAPS (d2, /*@encrypt:ssn*/ %s) FROM users LIMIT 1)" + assert analyze(sql, PG, P).parameter_columns()[0] == ColumnRef("ssn", "users") + + # A condition with no test operator around the value (a function sqlglot + # does not model as one): only the slot keeps the value out of the write. + @pytest.mark.parametrize("dialect, sql, expected", [ + (PG, "INSERT INTO audit (uid) SELECT id FROM users WHERE starts_with(ssn, /*@encrypt:ssn*/ %s)", + ColumnRef("ssn", "users")), + (MYSQL, "INSERT INTO audit (uid) SELECT id FROM users WHERE LOCATE(/*@encrypt:ssn*/ %s, ssn)", + ColumnRef("ssn", "users")), + (PG, "INSERT INTO audit (n) SELECT count(*) FROM users GROUP BY note " + "HAVING bool_or(starts_with(ssn, /*@encrypt:ssn*/ %s))", ColumnRef("ssn", "users")), + (PG, "UPDATE users SET flag = true FROM cards c " + "WHERE c.uid = users.id AND starts_with(c.pan, /*@encrypt:pan*/ %s)", ColumnRef("pan")), + (PG, "MERGE INTO users t USING cards c ON t.id = c.uid AND starts_with(c.pan, /*@encrypt:pan*/ %s) " + "WHEN MATCHED THEN UPDATE SET flag = true", ColumnRef("pan")), + (PG, "MERGE INTO users t USING cards c ON t.id = c.uid " + "WHEN MATCHED AND starts_with(c.pan, /*@encrypt:pan*/ %s) THEN UPDATE SET flag = true", ColumnRef("pan")), + ], ids=["where", "mysql-where", "having", "update-from-where", "merge-on", "merge-when-condition"]) + def test_bare_annotation_in_a_condition_slot(self, dialect, sql, expected): + assert analyze(sql, dialect, P).parameter_columns()[0] == expected + + @pytest.mark.parametrize("sql, ordinal, expected", [ + ("INSERT INTO audit (n) SELECT count(*) FROM users GROUP BY note HAVING max(lower(ssn)) = /*@encrypt:ssn*/ %s", + 0, ColumnRef("ssn", "users")), + ("MERGE INTO users t USING cards c ON t.id = c.uid AND lower(c.pan) = /*@encrypt:pan*/ %s " + "WHEN MATCHED THEN UPDATE SET flag = true", 0, ColumnRef("pan")), + ("MERGE INTO users t USING cards c ON t.id = c.uid " + "WHEN MATCHED AND lower(c.pan) = /*@encrypt:pan*/ %s THEN UPDATE SET flag = true", 0, ColumnRef("pan")), + ("UPDATE users SET flag = true FROM cards c WHERE c.uid = users.id AND lower(c.pan) = /*@encrypt:pan*/ %s", + 0, ColumnRef("pan")), + ("MERGE INTO users t USING cards c ON t.id = c.uid " + "WHEN NOT MATCHED THEN INSERT (id, note) VALUES (c.uid, /*@encrypt:ssn*/ %s)", 0, ColumnRef("ssn", "users")), + ("MERGE INTO users t USING cards c ON t.id = c.uid " + "WHEN MATCHED THEN UPDATE SET note = /*@encrypt:ssn*/ %s", 0, ColumnRef("ssn", "users")), + ("INSERT INTO logs (msg) VALUES (%s); UPDATE users SET note = /*@encrypt:ssn*/ %s", 1, ColumnRef("ssn", "users")), + ("INSERT INTO t (a) VALUES (1) ON CONFLICT (a) DO UPDATE SET note = /*@encrypt:ssn*/ %s", + 0, ColumnRef("ssn", "t")), + ], ids=["having", "merge-on", "merge-when-condition", "update-from-where", "merge-when-insert", "merge-when-update", + "two-writes", "on-conflict-set"]) + def test_bare_annotation_slots(self, sql, ordinal, expected): + assert analyze(sql, PG, P).parameter_columns()[ordinal] == expected + + # ---- one-dialect gaps ---- + + def test_replace_with_qualified_columns_is_read(self): + a = analyze("REPLACE INTO users (users.ssn) VALUES (%s)", MYSQL, P) + assert a.complete and assigned(a) == [(0, "users.ssn")] + + @BOTH + def test_table_statement_is_not_parsed_on_either_dialect(self, dialect): + a = analyze("TABLE users", dialect) + assert a.kind is StatementKind.SELECT and not a.writes and a.tables == () + + # ---- a cyclic exception chain ends ---- + + @pytest.mark.timeout(10) + def test_cyclic_exception_chain_does_not_hang(self, monkeypatch): + def cyclic(sql, read): + error = sqlglot.errors.ParseError("x") + error.__cause__ = error + raise error + + monkeypatch.setattr(sql_analyzer.sqlglot, "parse", cyclic) + a = sql_analyzer._analysis("SELECT 1", PG, ParamStyle.NONE) + assert a.gap is AnalysisGap.UNPARSEABLE and a.detail == "ParseError" diff --git a/tests/unit/test_sql_tokenizer.py b/tests/unit/test_sql_tokenizer.py new file mode 100644 index 000000000..032217c2c --- /dev/null +++ b/tests/unit/test_sql_tokenizer.py @@ -0,0 +1,415 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import re +from types import MappingProxyType + +import pytest + +from aws_advanced_python_wrapper.encryption.sql_dialect import MYSQL, PG +from aws_advanced_python_wrapper.encryption.sql_tokenizer import ( + ColumnRef, ParamStyle, normalized_ordinal, tokenize) + +POS, NAMED, NONE = ParamStyle.POSITIONAL, ParamStyle.NAMED, ParamStyle.NONE + + +def keys(tokens): + return [p.key for p in tokens.placeholders] + + +def hidden(tokens): + return [p.hidden for p in tokens.placeholders] + + +class TestParamStyle: + @pytest.mark.parametrize("params, expected", [ + (None, NONE), ((), POS), ([], POS), ((1,), POS), ([1], POS), + ({}, NAMED), ({"a": 1}, NAMED), (MappingProxyType({"a": 1}), NAMED), + ]) + def test_psycopg(self, params, expected): + # psycopg splits the query whenever params is not None, even if empty. + assert ParamStyle.of(params, PG) is expected + + @pytest.mark.parametrize("params, expected", [ + (None, NONE), ((), NONE), ([], NONE), ({}, NONE), ((1,), POS), ([1], POS), ({"a": 1}, NAMED), + # Connector/Python only accepts a dict, list or tuple. + (MappingProxyType({"a": 1}), NONE), ("abc", NONE), + ]) + def test_mysql_connector(self, params, expected): + # Connector/Python substitutes only for a non-empty dict, list or tuple. + assert ParamStyle.of(params, MYSQL) is expected + + +class TestPsycopgPlaceholders: + def test_positional_in_order(self): + t = tokenize("INSERT INTO t (a, b) VALUES (%s, %s)", PG, POS) + assert keys(t) == [0, 1] + assert [p.ordinal for p in t.placeholders] == [0, 1] + + def test_binary_and_text_formats_are_placeholders(self): + assert keys(tokenize("VALUES (%s, %b, %t)", PG, POS)) == [0, 1, 2] + + def test_named_may_repeat(self): + t = tokenize("UPDATE t SET a = %(v)s, b = %(v)s WHERE id = %(id)b", PG, NAMED) + assert keys(t) == ["v", "v", "id"] + assert [p.ordinal for p in t.placeholders] == [0, 1, 2] + + def test_double_percent_is_a_percent_sign(self): + t = tokenize("SELECT 7 %% 2, a FROM t WHERE b LIKE 'x%%' AND c = %s", PG, POS) + assert keys(t) == [0] + assert "7 % 2" in t.normalized and "'x%'" in t.normalized + + def test_placeholders_inside_literals_and_comments_are_still_bound(self): + # psycopg does not skip quotes or comments, so neither may we: the + # second %s is the second parameter even though it's in a string. + sql = "SELECT %s, '%s', \"%s\", $$%s$$, $tag$%s$tag$, E'\\'%s', /* %s */ -- %s\n %s" + t = tokenize(sql, PG, POS) + assert keys(t) == list(range(9)) + assert hidden(t) == [False, True, True, True, True, True, True, True, False] + assert t.has_hidden_placeholders + + def test_nested_block_comments(self): + t = tokenize("/* a /* b */ %s */ SELECT %s", PG, POS) + assert hidden(t) == [True, False] + + @pytest.mark.timeout(10) + def test_deeply_nested_comments_stay_linear(self): + depth = 100_000 + t = tokenize("SELECT /*" + " /*" * depth + " */" * (depth + 1) + " %s", PG, POS) + assert hidden(t) == [False] + + def test_dollar_number_is_not_a_dollar_quote(self): + t = tokenize("SELECT $1, %s", PG, POS) + assert hidden(t) == [False] + + def test_identifier_with_dollar_is_not_a_dollar_quote(self): + t = tokenize("SELECT a$b$, %s", PG, POS) + assert hidden(t) == [False] + + def test_standard_strings_do_not_escape_backslash(self): + # standard_conforming_strings=on: 'a\' is a whole literal. + t = tokenize("SELECT 'a\\', %s", PG, POS) + assert hidden(t) == [False] + + def test_escape_strings_do(self): + t = tokenize("SELECT E'a\\', %s'", PG, POS) + assert hidden(t) == [True] + + def test_doubled_quotes(self): + t = tokenize("SELECT 'it''s', \"a\"\"b\", %s", PG, POS) + assert hidden(t) == [False] + + @pytest.mark.parametrize("sql, rejected", [ + ("SELECT 1 % 2", True), ("SELECT '100%'", True), ("SELECT %d", True), ("SELECT %()s", True), + # A lone % at the very end is not matched by psycopg's pattern either. + ("SELECT %", False), + ]) + def test_driver_rejects_other_percent_sequences(self, sql, rejected): + assert (tokenize(sql, PG, POS).driver_error is not None) is rejected + + @pytest.mark.parametrize("sql, style", [ + ("SELECT '%(card 4111-1111-1111-1111)x', %s", POS), + ("SELECT '4111-1111-1111-1111 %d'", POS), + ("VALUES (%s, %(4111-1111)s)", NAMED), + ]) + def test_driver_error_never_quotes_the_sql(self, sql, style): + error = tokenize(sql, PG, style).driver_error + assert error is not None and "4111" not in error + + def test_percent_before_newline_is_left_alone(self): + # psycopg's pattern does not match a newline after %. + assert tokenize("SELECT 1 %\n2", PG, POS).driver_error is None + + @pytest.mark.parametrize("style", [POS, NAMED]) + def test_mixed_styles_are_a_driver_error(self, style): + assert tokenize("VALUES (%s, %(a)s)", PG, style).driver_error is not None + + @pytest.mark.parametrize("sql, style", [("VALUES (%s)", NAMED), ("VALUES (%(a)s)", POS)]) + def test_style_mismatch_is_a_driver_error(self, sql, style): + assert tokenize(sql, PG, style).driver_error is not None + + def test_no_params_means_no_placeholders(self): + t = tokenize("SELECT '%s', %s, 1 %% 2", PG, NONE) + assert t.placeholders == () + assert t.driver_error is None + assert t.normalized == "SELECT '%s', %s, 1 %% 2" + + def test_spans(self): + sql = "SELECT %(name)s" + p = tokenize(sql, PG, NAMED).placeholders[0] + assert sql[p.start:p.end] == "%(name)s" + + +class TestMySqlPlaceholders: + def test_positional(self): + assert keys(tokenize("INSERT INTO t (a, b) VALUES (%s, %s)", MYSQL, POS)) == [0, 1] + + def test_double_percent_is_not_an_escape(self): + # Connector/Python replaces every "%s" substring, including in "%%s". + t = tokenize("SELECT 5 %% 2, %%s", MYSQL, POS) + assert keys(t) == [0] + assert t.driver_error is None + + def test_any_other_percent_sequence_is_left_alone(self): + t = tokenize("SELECT a FROM t WHERE b LIKE 'x%' AND c = %d AND d = %s", MYSQL, POS) + assert keys(t) == [0] + assert t.driver_error is None + + def test_named_only_with_a_dict(self): + assert keys(tokenize("VALUES (%(a)s, %s)", MYSQL, NAMED)) == ["a"] + assert keys(tokenize("VALUES (%(a)s, %s)", MYSQL, POS)) == [0] + + def test_named_percent_conversion_is_a_percent_sign(self): + t = tokenize("SELECT %(a)s, 5 %(x)% 2", MYSQL, NAMED) + assert keys(t) == ["a"] + assert "5 % 2" in t.normalized + + def test_named_other_conversion_is_a_driver_error(self): + error = tokenize("SELECT '%(123-45-6789)d'", MYSQL, NAMED).driver_error + assert error is not None and "123-45" not in error + + def test_no_params_means_no_placeholders(self): + assert tokenize("SELECT %s", MYSQL, NONE).placeholders == () + + def test_placeholders_inside_literals_and_comments_are_still_bound(self): + sql = "SELECT %s, '%s', \"%s\", `%s`, /* %s */, # %s\n -- %s\n %s" + t = tokenize(sql, MYSQL, POS) + assert hidden(t) == [False, True, True, True, True, True, True, False] + + def test_backslash_escapes_in_strings(self): + t = tokenize("SELECT 'a\\'b', \"c\\\"d\", %s", MYSQL, POS) + assert hidden(t) == [False] + + def test_double_dash_needs_whitespace_to_start_a_comment(self): + t = tokenize("SELECT 1--%s", MYSQL, POS) + assert hidden(t) == [False] + assert hidden(tokenize("SELECT 1-- %s", MYSQL, POS)) == [True] + + def test_block_comments_do_not_nest(self): + t = tokenize("/* a /* b */ %s */", MYSQL, POS) + assert hidden(t) == [False] + + @pytest.mark.parametrize("sql, executable", [ + ("SELECT /*!40001 SQL_NO_CACHE */ 1", True), + ("SELECT /*! 1 */", True), + ("SELECT /*M!100000 1 */", True), + ("SELECT /*+ hint */ 1", False), + ("SELECT '/*! x */'", False), + ]) + def test_executable_comments(self, sql, executable): + assert tokenize(sql, MYSQL, NONE).executable_comment is executable + + def test_executable_comment_is_only_a_mysql_notion(self): + assert not tokenize("SELECT /*! 1 */", PG, NONE).executable_comment + + def test_executable_comment_keywords(self): + assert "INSERT" in tokenize("SELECT 1 /*! ; INSERT INTO t VALUES (1) */", MYSQL, NONE).keywords + + @pytest.mark.parametrize("sql, introducers", [ + ("VALUES (_binary %s, _utf8mb4'x', %s)", ["_binary", None]), + ("VALUES (_BINARY %s)", ["_binary"]), + ("VALUES (_x %s, a_binary %s)", [None, None]), + ("VALUES ('_binary' %s)", [None]), + ("VALUES (_binary '%s')", [None]), + ]) + def test_charset_introducers(self, sql, introducers): + t = tokenize(sql, MYSQL, POS) + assert [p.introducer for p in t.placeholders] == introducers + if introducers[0]: + assert "_binary" not in t.normalized.lower() + + def test_introducer_inside_a_comment_is_ignored(self): + t = tokenize("VALUES (-- _binary\n%s)", MYSQL, POS) + assert [p.introducer for p in t.placeholders] == [None] + assert "_binary" in t.normalized + + +class TestLexing: + @pytest.mark.parametrize("dialect, sql", [ + (PG, "SELECT 'abc"), (PG, "SELECT \"abc"), (PG, "SELECT $$abc"), (PG, "SELECT /* /* */"), + (PG, "SELECT 'it''"), (MYSQL, "SELECT 'abc\\'"), (MYSQL, "SELECT `a"), (MYSQL, "SELECT /* a"), + ]) + def test_unterminated(self, dialect, sql): + assert tokenize(sql, dialect, POS).unterminated + + def test_leading_words_per_statement(self): + t = tokenize("/* hint */ insert INTO t VALUES (1); -- c\n (SELECT 1); ; UPDATE t SET a = 1;", PG, NONE) + assert t.leading_words == ("INSERT", "SELECT", "UPDATE") + + def test_semicolon_in_literal_does_not_split(self): + assert tokenize("SELECT ';' ; SELECT 2", PG, NONE).leading_words == ("SELECT", "SELECT") + assert tokenize("SELECT ';'", MYSQL, NONE).leading_words == ("SELECT",) + + def test_keywords_ignore_literals_comments_and_placeholder_names(self): + t = tokenize("SELECT 'INSERT' /* UPDATE */ FROM t WHERE a = %(merge)s", PG, NAMED) + assert t.keywords == {"FROM"} + + def test_type_error_for_non_str(self): + with pytest.raises(TypeError): + tokenize(b"SELECT 1", PG, NONE) # type: ignore[arg-type] + + +class TestNormalized: + def test_placeholders_carry_their_ordinal(self): + t = tokenize("VALUES (%s, %s)", PG, POS) + names = re.findall(r":(\w+)", t.normalized) + assert [normalized_ordinal(n) for n in names] == [0, 1] + + def test_cast_after_placeholder_stays_readable(self): + assert ":_kms_p0 ::bytea" in tokenize("VALUES (%s::bytea)", PG, POS).normalized + + @pytest.mark.parametrize("name, expected", [ + ("_kms_p0", 0), ("_kms_p12", 12), ("_kms_p", None), ("_kms_px", None), ("other", None), (None, None), + ("_kms_pŁ£", None), # a non-ASCII digit + ]) + def test_normalized_ordinal(self, name, expected): + assert normalized_ordinal(name) == expected + + @pytest.mark.parametrize("sql, expected", [ + ("REPLACE INTO t (a) VALUES (%s)", "INSERT INTO t (a) VALUES"), + ("REPLACE LOW_PRIORITY INTO t (a) VALUES (%s)", "INSERT INTO t"), + ("INSERT HIGH_PRIORITY IGNORE INTO t (a) VALUES (%s)", "INSERT INTO t"), + ("INSERT DELAYED INTO t (a) VALUES (%s)", "INSERT INTO t"), + ("UPDATE LOW_PRIORITY IGNORE t SET a = %s", "UPDATE t SET"), + ("DELETE LOW_PRIORITY QUICK IGNORE FROM t WHERE a = %s", "DELETE FROM t"), + ("/* x */ replace t SET a = %s", "/* x */ INSERT t SET"), + ]) + def test_mysql_statement_modifiers_and_replace(self, sql, expected): + assert expected in " ".join(tokenize(sql, MYSQL, POS).normalized.split()) + + def test_replace_function_is_left_alone(self): + t = tokenize("SELECT REPLACE(a, 'x', 'y') FROM t; UPDATE t SET a = REPLACE(a, 'x', %s)", MYSQL, POS) + assert t.normalized.count("REPLACE(") == 2 + + def test_modifier_words_elsewhere_are_left_alone(self): + # QUICK is not reserved and can name a table. + t = tokenize("UPDATE quick SET a = %s", MYSQL, POS) + assert "UPDATE quick" in t.normalized + + def test_postgresql_keeps_modifier_words(self): + assert "UPDATE ignore" in tokenize("UPDATE ignore SET a = %s", PG, POS).normalized + + +class TestAnnotations: + def test_annotation_before_a_placeholder(self): + t = tokenize("INSERT INTO t (a, b) VALUES (%s, /*@encrypt:users.ssn*/ %s)", PG, POS) + assert [p.annotation for p in t.placeholders] == [None, ColumnRef("ssn", "users")] + assert t.stray_annotations == () + + def test_named_placeholder(self): + t = tokenize("UPDATE t SET b = /*@encrypt:ssn*/%(ssn)s", PG, NAMED) + assert t.placeholders[0].annotation == ColumnRef("ssn") + + def test_schema_is_dropped(self): + t = tokenize("VALUES (/*@encrypt:app.users.ssn*/ %s)", PG, POS) + assert t.placeholders[0].annotation == ColumnRef("ssn", "users") + + @pytest.mark.parametrize("ref, expected", [ + # References the shared [\w.]+ grammar allows: empty and extra parts. + (".ssn", ColumnRef("ssn")), + ("t..ssn", ColumnRef("ssn", "t")), + ("a.b.t.ssn", ColumnRef("ssn", "t")), + ("9t.1a", ColumnRef("1a", "9t")), + ]) + def test_empty_and_extra_parts(self, ref, expected): + t = tokenize(f"VALUES (/*@encrypt:{ref}*/ %s)", PG, POS) + assert t.placeholders[0].annotation == expected + + def test_doubled_quote_in_a_quoted_part(self): + t = tokenize('VALUES (/*@encrypt:"a""b".ssn*/ %s)', PG, POS) + assert t.placeholders[0].annotation == ColumnRef("ssn", 'a"b') + + def test_postgresql_folds_unquoted_parts_and_keeps_quoted_ones(self): + t = tokenize('VALUES (/*@encrypt:Users."SSN"*/ %s)', PG, POS) + assert t.placeholders[0].annotation == ColumnRef("SSN", "users") + + def test_mysql_backtick_parts(self): + t = tokenize("VALUES (/*@encrypt:`My Table`.SSN*/ %s)", MYSQL, POS) + assert t.placeholders[0].annotation == ColumnRef("SSN", "My Table") + + @pytest.mark.parametrize("sql", [ + "VALUES (%s /*@encrypt:users.ssn*/)", # after, not before + "VALUES (/*@encrypt:users.ssn*/ 'x', %s)", # not followed by a placeholder + "VALUES (/*@encrypt:users.*/ %s)", # no column + "VALUES (/*@encrypt:users ssn*/ %s)", + "VALUES (/*@encrypt:users.ssn*/ '%s')", # a literal, not a placeholder, follows + ]) + def test_stray_annotations(self, sql): + t = tokenize(sql, PG, POS) + assert all(p.annotation is None for p in t.placeholders) + assert len(t.stray_annotations) == 1 + + def test_annotation_before_a_hidden_placeholder_is_stray(self): + # psycopg reads %("x")s as one placeholder that starts outside a + # quoted identifier and ends inside it. + t = tokenize('VALUES (/*@encrypt:t.a*/ %("x")s)', PG, NAMED) + assert hidden(t) == [True] + assert t.placeholders[0].annotation is None and len(t.stray_annotations) == 1 + + def test_space_after_comment_opener_is_not_an_annotation(self): + t = tokenize("VALUES (/* @encrypt:users.ssn*/ %s)", PG, POS) + assert t.placeholders[0].annotation is None + assert t.stray_annotations == () + + def test_annotation_inside_a_literal_is_text(self): + t = tokenize("VALUES ('/*@encrypt:users.ssn*/', %s)", PG, POS) + assert t.placeholders[0].annotation is None + + +# ---- the drivers themselves as the oracle ---- +# +# These call the drivers' own placeholder scanning, so a driver upgrade that +# changes what it binds fails here rather than silently shifting which value +# the plugin encrypts. + +_ORACLE_SQL = [ + "INSERT INTO t (a, b) VALUES (%s, %s)", + "SELECT %s, '%s', \"%s\" -- %s\n, %s", + "SELECT 7 %% 2, %s, '%%s', /* %s */ %s", + "UPDATE t SET a = %s WHERE b LIKE 'x%%' AND c IN (%s, %s)", + "SELECT $$ %s $$, E'\\'%s', %s", + "SELECT %%s, %s%s", +] + +_NAMED_ORACLE_SQL = [ + "INSERT INTO t (a, b) VALUES (%(a)s, %(b)s)", + "UPDATE t SET a = %(v)s, b = %(v)s WHERE c = '%(w)s' -- %(x)s", + "SELECT %(a)s, 5 %% 2, %(b)s", +] + + +@pytest.mark.parametrize("sql", _ORACLE_SQL + _NAMED_ORACLE_SQL) +def test_matches_psycopg(sql): + queries = pytest.importorskip("psycopg._queries") + named = "%(" in sql + parts = queries._split_query(sql.encode()) + expected = [part.item for part in parts[:-1]] + t = tokenize(sql, PG, NAMED if named else POS) + assert keys(t) == expected + assert t.driver_error is None # psycopg accepted it + + +@pytest.mark.parametrize("sql", _ORACLE_SQL) +def test_matches_mysql_connector_positional(sql): + cursor = pytest.importorskip("mysql.connector.cursor") + expected = list(range(len(cursor.RE_PY_PARAM.findall(sql.encode())))) + assert keys(tokenize(sql, MYSQL, POS)) == expected + + +@pytest.mark.parametrize("sql", _NAMED_ORACLE_SQL) +def test_matches_mysql_connector_named(sql): + cursor = pytest.importorskip("mysql.connector.cursor") + expected = [m.group("mapping_key").decode() for m in cursor.RE_PY_MAPPING_PARAM.finditer(sql.encode()) + if m.group("conversion_type") == b"s"] + assert keys(tokenize(sql, MYSQL, NAMED)) == expected