Source code for ds_common_placeholder_py_lib.sql

"""
**File:** ``sql.py``
**Region:** ``ds-common-placeholder-py-lib``

Description
-----------
Placeholders in SQL text become SQL literals, never raw text (contract §8.3).
The lexer knows DuckDB's quoting: ``'…'``, ``E'…'``, ``"…"``, ``$tag$…$tag$``,
``--`` and nested ``/* */`` comments.
"""

from __future__ import annotations

import json
import math
import re
from collections.abc import Mapping
from collections.abc import Set as AbstractSet
from typing import TYPE_CHECKING, Any

from .context import secret_forms
from .errors import ErrorCode, PlaceholderError
from .grammar import Placeholder, Reference, Segment, Text, calls, namespaces, reference_text
from .resolve import parse_at

if TYPE_CHECKING:
    from .resolve import _Resolver

# Tags follow the Postgres lexer DuckDB uses: non-ASCII characters are allowed.
_DOLLAR_TAG = re.compile("\\$(?:[A-Za-z_\u0080-\U0010ffff][A-Za-z0-9_\u0080-\U0010ffff]*)?\\$")


_SECRET_CALLS = frozenset({"get_secret", "secret"})


def _resolve_sql(sql: str, resolver: _Resolver, path: str) -> str:
    """The SQL text *sql*, at *path* in the context, with each placeholder
    a SQL literal. An error names *path* unless it names a place of its own."""
    try:
        return _sql_literals(sql, resolver, path)
    except PlaceholderError as err:
        if not err.path:
            err.path = path
        raise


[docs] def refuse_secrets_in_sql(sql: str, path: str) -> list[Segment]: """Check the SQL text at *path* before anything is read. Returns: ``parse(sql)``. Raises: PlaceholderError: ``syntax``, ``sql_position``, or ``sql_secret`` for a ``get_secret`` or ``secret`` call at any depth, with *path*. """ segments = parse_at(sql, path) errors = position_errors(sql, segments) if errors: errors[0].path = errors[0].path or path raise errors[0] for segment in segments: if isinstance(segment, Placeholder) and any(call.name in _SECRET_CALLS for call in calls(segment.expr)): err = _sql_secret(segment) err.path = path raise err return segments
[docs] def sql_errors(sql: str) -> list[PlaceholderError]: """Every error of the SQL text that its text alone shows, for :func:`~ds_common_placeholder_py_lib.validate.validate`: ``sql_position`` for each misplaced placeholder, ``sql_secret`` for each one with a ``get_secret`` or ``secret`` call at any depth. Raises: PlaceholderError: ``syntax``, if *sql* does not parse. """ segments = parse_at(sql, "") errors = position_errors(sql, segments) errors.extend( _sql_secret(segment) for segment in segments if isinstance(segment, Placeholder) and any(call.name in _SECRET_CALLS for call in calls(segment.expr)) ) return errors
def _sql_literals(sql: str, resolver: _Resolver, path: str) -> str: segments = refuse_secrets_in_sql(sql, path) out: list[str] = [] for segment in segments: if isinstance(segment, Text): out.append(segment.value) continue value = resolver.placeholder(segment, path) try: # A secret can also arrive through a value: a namespace the service # filled from a resolved get_secret (a variable), or str_join over one. if _contains_secret(value, resolver.ctx._secrets): raise _sql_secret(segment) out.append(literal(value, segment)) except PlaceholderError as err: if isinstance(segment.expr, Reference): err.reference = reference_text(segment.expr) err.namespaces = namespaces(segment.expr) | err.namespaces raise return "".join(out) def _contains_secret(value: Any, secrets: AbstractSet[str]) -> bool: if isinstance(value, str): # Also JSON-escaped: dataframe_to_json_array or a service function # may have written one into a JSON text. return any(form in value for secret in secrets for form in secret_forms(secret)) if isinstance(value, Mapping): return any(_contains_secret(key, secrets) or _contains_secret(item, secrets) for key, item in value.items()) if isinstance(value, list): return any(_contains_secret(item, secrets) for item in value) return False
[docs] def literal(value: Any, placeholder: Placeholder) -> str: """Render a JSON value as a SQL literal. Raises: PlaceholderError: ``type`` for anything but a string, number, or boolean. """ if isinstance(value, bool): return "TRUE" if value else "FALSE" if isinstance(value, str): return "'" + value.replace("'", "''") + "'" if isinstance(value, int | float) and math.isfinite(value): text = str(value) if isinstance(value, int) else json.dumps(value) # Parenthesise negatives so "x -@{n}" cannot become a "--" comment. return f"({text})" if text.startswith("-") else text raise PlaceholderError(ErrorCode.TYPE, "only strings, numbers, and booleans can be SQL literals", placeholder=placeholder.raw)
[docs] def position_errors(sql: str, segments: list[Segment]) -> list[PlaceholderError]: """Find placeholders inside quotes or comments, or glued to other tokens. Args: sql: The statement. segments: ``parse(sql)``. Returns: One ``sql_position`` error per misplaced placeholder. """ placeholders = [s for s in segments if isinstance(s, Placeholder)] by_start = {p.start: p for p in placeholders} bad: dict[int, str] = {} i, n = 0, len(sql) while i < n: if i in by_start: p = by_start[i] if _glued(sql, p, by_start): bad.setdefault(p.start, "a placeholder must stand alone where a SQL literal can stand") i = p.end continue end = _region_end(sql, i) if end is None: i += 1 continue for p in placeholders: if i <= p.start < end: bad.setdefault(p.start, "a placeholder must not be inside a quoted string, quoted identifier, or comment") i = max([end, *(p.end for p in placeholders if i <= p.start < end)]) return [ PlaceholderError(ErrorCode.SQL_POSITION, message, placeholder=by_start[start].raw) for start, message in sorted(bad.items()) ]
def _word(ch: str) -> bool: """Identifier character other than a digit. Any non-ASCII character counts, as in the Postgres lexer, so every implementation agrees.""" return ("a" <= ch.lower() <= "z") or ch in "_$" or ord(ch) >= 0x80 def _ident(ch: str) -> bool: return _word(ch) or "0" <= ch <= "9" def _glued(sql: str, p: Placeholder, by_start: dict[int, Placeholder]) -> bool: ends = {q.end for q in by_start.values()} before = sql[p.start - 1] if p.start > 0 else " " after = sql[p.end] if p.end < len(sql) else " " return _ident(before) or before in "'\"&." or p.start in ends or _ident(after) or after in "'\"." or p.end in by_start def _region_end(sql: str, i: int) -> int | None: """If a quoted string, quoted identifier, or comment starts at *i*, return the offset after it (or ``len(sql)`` if unterminated).""" ch = sql[i] if ch == "'": word = _word_before(sql, i) if _is_number(word[:-1]) and word[-1:] in ("e", "E"): return _quoted_end(sql, i, "'", True) # E'…' (possibly after a number) if word[-1:] in ("e", "E") and not _is_identifier(word): return len(sql) # can't tell E'…' from '…': treat the rest as quoted return _quoted_end(sql, i, "'", False) if ch == '"': return _quoted_end(sql, i, '"', False) if sql.startswith("--", i): newline = sql.find("\n", i) return len(sql) if newline == -1 else newline + 1 if sql.startswith("/*", i): return _block_comment_end(sql, i) if ch == "$": match = _DOLLAR_TAG.match(sql, i) if not match: return None word = _word_before(sql, i) if _is_identifier(word): return None # "a1$$" is one identifier if not _is_number(word): return len(sql) # e.g. "$1$$": ambiguous, treat the rest as quoted close = sql.find(match.group(), match.end()) return len(sql) if close == -1 else close + len(match.group()) return None def _word_before(sql: str, i: int) -> str: """The run of identifier characters that ends just before *i*.""" j = i while j > 0 and _ident(sql[j - 1]): j -= 1 return sql[j:i] def _is_identifier(word: str) -> bool: return bool(word) and _word(word[0]) and word[0] != "$" def _is_number(word: str) -> bool: """Empty, or ASCII digits only: what may precede a quote that DuckDB lexes as a separate token.""" return all("0" <= ch <= "9" for ch in word) def _quoted_end(sql: str, i: int, quote: str, escapes: bool) -> int: j, n = i + 1, len(sql) while j < n: if escapes and sql[j] == "\\": j += 2 elif sql[j] == quote: if sql.startswith(quote, j + 1): j += 2 else: return j + 1 else: j += 1 return n def _block_comment_end(sql: str, i: int) -> int: depth, j, n = 0, i, len(sql) while j < n: if sql.startswith("/*", j): depth += 1 j += 2 elif sql.startswith("*/", j): depth -= 1 j += 2 if depth == 0: return j else: j += 1 return n def _sql_secret(placeholder: Placeholder) -> PlaceholderError: return PlaceholderError(ErrorCode.SQL_SECRET, "secrets must not be used in SQL", placeholder=placeholder.raw)