Files
leleka/scripts/e2e/codex/tasks/feature-query/reference/overlay/minidb/query.py
T

388 lines
12 KiB
Python

"""The textual ``where`` language described in SPEC.md.
``compile_where(text, columns)`` parses an expression once and returns a predicate for rows.
Evaluation uses three truth values: ``True``, ``False`` and ``None`` (UNKNOWN).
"""
from __future__ import annotations
import operator
import re
from functools import lru_cache
from typing import Any, Callable, Dict, Iterable, List, Mapping, NamedTuple, Optional, Tuple
from .errors import MiniDBError
Row = Mapping[str, Any]
Node = Callable[[Row], Optional[bool]]
Operand = Callable[[Row], Any]
class QueryError(MiniDBError):
"""Base class of errors in ``where`` expressions."""
class QuerySyntaxError(QueryError):
def __init__(self, message: str, position: int) -> None:
super().__init__("%s at position %d" % (message, position))
self.message = message
self.position = position
class QueryNameError(QueryError):
def __init__(self, name: str, position: int) -> None:
super().__init__("unknown column %s at position %d" % (name, position))
self.name = name
self.position = position
class QueryTypeError(QueryError):
"""Two values cannot be compared or used in this way."""
KEYWORDS = frozenset({"AND", "OR", "NOT", "IN", "BETWEEN", "LIKE", "ILIKE", "IS", "NULL", "TRUE", "FALSE"})
_LETTERS = frozenset("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_")
_DIGITS = frozenset("0123456789")
_NAME_CHARS = _LETTERS | _DIGITS
_COMPARE = {
"=": operator.eq,
"!=": operator.ne,
"<>": operator.ne,
"<": operator.lt,
"<=": operator.le,
">": operator.gt,
">=": operator.ge,
}
class Token(NamedTuple):
kind: str # NUMBER STRING IDENT KEYWORD OP LPAREN RPAREN COMMA EOF
value: Any
position: int
def tokenize(text: str) -> List[Token]:
tokens: List[Token] = []
i, n = 0, len(text)
while i < n:
ch = text[i]
if ch in " \t\r\n":
i += 1
elif ch == "'":
start = i
i += 1
chars: List[str] = []
while True:
if i >= n:
raise QuerySyntaxError("unterminated string", start)
if text[i] == "'":
if text[i + 1:i + 2] == "'":
chars.append("'")
i += 2
continue
i += 1
break
chars.append(text[i])
i += 1
tokens.append(Token("STRING", "".join(chars), start))
elif ch in _DIGITS or (ch in "+-" and text[i + 1:i + 2] in _DIGITS and i + 1 < n):
start = i
i += 1
while i < n and text[i] in _DIGITS:
i += 1
if i + 1 < n and text[i] == "." and text[i + 1] in _DIGITS:
i += 1
while i < n and text[i] in _DIGITS:
i += 1
tokens.append(Token("NUMBER", float(text[start:i]), start))
else:
tokens.append(Token("NUMBER", int(text[start:i]), start))
elif ch in _LETTERS:
start = i
while i < n and text[i] in _NAME_CHARS:
i += 1
word = text[start:i]
if word.upper() in KEYWORDS:
tokens.append(Token("KEYWORD", word.upper(), start))
else:
tokens.append(Token("IDENT", word, start))
elif text[i:i + 2] in ("<=", ">=", "<>", "!="):
tokens.append(Token("OP", text[i:i + 2], i))
i += 2
elif ch in "=<>":
tokens.append(Token("OP", ch, i))
i += 1
elif ch == "(":
tokens.append(Token("LPAREN", ch, i))
i += 1
elif ch == ")":
tokens.append(Token("RPAREN", ch, i))
i += 1
elif ch == ",":
tokens.append(Token("COMMA", ch, i))
i += 1
else:
raise QuerySyntaxError("invalid character %r" % ch, i)
tokens.append(Token("EOF", None, n))
return tokens
# -- evaluation helpers -------------------------------------------------------
def _is_number(value: Any) -> bool:
return isinstance(value, (int, float)) and not isinstance(value, bool)
def _compare(op: str, a: Any, b: Any) -> Optional[bool]:
if a is None or b is None:
return None
both_numbers = _is_number(a) and _is_number(b)
both_strings = isinstance(a, str) and isinstance(b, str)
both_bools = isinstance(a, bool) and isinstance(b, bool)
if not (both_numbers or both_strings or both_bools):
raise QueryTypeError("cannot compare %s with %s" % (type(a).__name__, type(b).__name__))
return _COMPARE[op](a, b)
@lru_cache(maxsize=256)
def _like_regex(pattern: str) -> "re.Pattern[str]":
parts = []
for ch in pattern:
parts.append(".*" if ch == "%" else "." if ch == "_" else re.escape(ch))
return re.compile("".join(parts), re.DOTALL)
def _like(a: Any, pattern: Any, ignore_case: bool) -> Optional[bool]:
if a is None or pattern is None:
return None
if not isinstance(a, str) or not isinstance(pattern, str):
raise QueryTypeError("LIKE needs strings, got %s and %s" % (type(a).__name__, type(pattern).__name__))
if ignore_case:
a, pattern = a.lower(), pattern.lower()
return _like_regex(pattern).fullmatch(a) is not None
def _and(left: Node, right: Node) -> Node:
def evaluate(row: Row) -> Optional[bool]:
a = left(row)
if a is False:
return False
b = right(row)
if b is False:
return False
return None if a is None or b is None else True
return evaluate
def _or(left: Node, right: Node) -> Node:
def evaluate(row: Row) -> Optional[bool]:
a = left(row)
if a is True:
return True
b = right(row)
if b is True:
return True
return None if a is None or b is None else False
return evaluate
def _not(inner: Node) -> Node:
def evaluate(row: Row) -> Optional[bool]:
value = inner(row)
return None if value is None else not value
return evaluate
def _constant(value: Any) -> Operand:
return lambda row: value
def _column(name: str) -> Operand:
return lambda row: row[name]
def _comparison(op: str, left: Operand, right: Operand) -> Node:
return lambda row: _compare(op, left(row), right(row))
def _in_list(operand: Operand, values: List[Any]) -> Node:
def evaluate(row: Row) -> Optional[bool]:
x = operand(row)
unknown = False
for value in values:
result = _compare("=", x, value)
if result is True:
return True
unknown = unknown or result is None
return None if unknown else False
return evaluate
def _bare(operand: Operand) -> Node:
def evaluate(row: Row) -> Optional[bool]:
value = operand(row)
if value is None or isinstance(value, bool):
return value
raise QueryTypeError("%s is not a boolean condition" % type(value).__name__)
return evaluate
def _is_null(operand: Operand) -> Node:
return lambda row: operand(row) is None
# -- parser -------------------------------------------------------------------
class _Parser:
def __init__(self, text: str) -> None:
self.text = text
self.tokens = tokenize(text)
self.index = 0
self.references: List[Tuple[str, int]] = []
@property
def current(self) -> Token:
return self.tokens[self.index]
def advance(self) -> Token:
token = self.tokens[self.index]
if token.kind != "EOF":
self.index += 1
return token
def at_keyword(self, *words: str) -> bool:
return self.current.kind == "KEYWORD" and self.current.value in words
def fail(self) -> QuerySyntaxError:
token = self.current
if token.kind == "EOF":
return QuerySyntaxError("unexpected end of input", len(self.text))
return QuerySyntaxError("unexpected token", token.position)
def expect_keyword(self, word: str) -> None:
if not self.at_keyword(word):
raise self.fail()
self.advance()
def parse(self) -> Node:
node = self.parse_or()
if self.current.kind != "EOF":
raise self.fail()
return node
def parse_or(self) -> Node:
node = self.parse_and()
while self.at_keyword("OR"):
self.advance()
node = _or(node, self.parse_and())
return node
def parse_and(self) -> Node:
node = self.parse_not()
while self.at_keyword("AND"):
self.advance()
node = _and(node, self.parse_not())
return node
def parse_not(self) -> Node:
if self.at_keyword("NOT"):
self.advance()
return _not(self.parse_not())
return self.parse_primary()
def parse_primary(self) -> Node:
if self.current.kind == "LPAREN":
self.advance()
node = self.parse_or()
if self.current.kind != "RPAREN":
raise self.fail()
self.advance()
return node
return self.parse_predicate()
def parse_predicate(self) -> Node:
left = self.parse_operand()
token = self.current
if token.kind == "OP":
self.advance()
return _comparison(token.value, left, self.parse_operand())
if self.at_keyword("IS"):
self.advance()
negate = self.at_keyword("NOT")
if negate:
self.advance()
self.expect_keyword("NULL")
node = _is_null(left)
return _not(node) if negate else node
negate = False
if self.at_keyword("NOT"):
self.advance()
negate = True
if not self.at_keyword("IN", "BETWEEN", "LIKE", "ILIKE"):
raise self.fail()
if self.at_keyword("IN"):
self.advance()
node = _in_list(left, self.parse_literal_list())
elif self.at_keyword("BETWEEN"):
self.advance()
low = self.parse_operand()
self.expect_keyword("AND")
high = self.parse_operand()
node = _and(_comparison(">=", left, low), _comparison("<=", left, high))
elif self.at_keyword("LIKE", "ILIKE"):
ignore_case = self.advance().value == "ILIKE"
pattern = self.parse_operand()
node = lambda row, p=pattern, ic=ignore_case: _like(left(row), p(row), ic)
else:
return _bare(left)
return _not(node) if negate else node
def parse_operand(self) -> Operand:
token = self.current
if token.kind == "IDENT":
self.advance()
self.references.append((token.value, token.position))
return _column(token.value)
return _constant(self.parse_literal())
def parse_literal(self) -> Any:
token = self.current
if token.kind in ("NUMBER", "STRING"):
self.advance()
return token.value
if self.at_keyword("TRUE", "FALSE", "NULL"):
self.advance()
return {"TRUE": True, "FALSE": False, "NULL": None}[token.value]
raise self.fail()
def parse_literal_list(self) -> List[Any]:
if self.current.kind != "LPAREN":
raise self.fail()
self.advance()
values = [self.parse_literal()]
while self.current.kind == "COMMA":
self.advance()
values.append(self.parse_literal())
if self.current.kind != "RPAREN":
raise self.fail()
self.advance()
return values
def compile_where(text: str, columns: Iterable[str]) -> Callable[[Row], bool]:
"""Parse ``text`` and return a predicate that is true for the rows the expression selects."""
known = set(columns)
parser = _Parser(text)
node = parser.parse()
for name, position in parser.references:
if name not in known:
raise QueryNameError(name, position)
return lambda row: node(row) is True