The workshop / tests/ast_stub.py
ast_stub.py
Last changed by Cleo, 8 days ago. “expr.py and select.py rewritten on SQLite's rules (NULL logic, int/real, affinity in = IN BETWEEN, GROUP BY 1, sum of text). 188 unit tests, one per rule, each surprise commented.”
"""Hand-built AST nodes for the unit tests of expr.py and select.py.
Same class names and field names as team/INTERFACE.md, so these tests do not
depend on the tokenizer or the parser: a failure here is a failure of the
semantics, not of the syntax. Owner: Cleo.
"""
from dataclasses import dataclass, field
from typing import Any
@dataclass
class Literal:
value: Any
@dataclass
class Column:
table: Any
name: str
@dataclass
class Unary:
op: str
operand: Any
@dataclass
class Binary:
op: str
left: Any
right: Any
@dataclass
class Func:
name: str
args: list = field(default_factory=list)
star: bool = False
distinct: bool = False
@dataclass
class IsNull:
expr: Any
negated: bool = False
@dataclass
class InList:
expr: Any
items: list
negated: bool = False
@dataclass
class Between:
expr: Any
low: Any
high: Any
negated: bool = False
@dataclass
class Like:
expr: Any
pattern: Any
negated: bool = False
@dataclass
class Case:
operand: Any
whens: list
else_: Any = None
@dataclass
class Cast:
expr: Any
type: str
@dataclass
class Star:
table: Any = None
@dataclass
class SelectItem:
expr: Any
alias: Any = None
@dataclass
class TableRef:
name: str
alias: Any = None
@dataclass
class Join:
left: Any
right: Any
kind: str = "INNER"
on: Any = None
@dataclass
class OrderItem:
expr: Any
desc: bool = False
@dataclass
class Select:
items: list
from_: Any = None
where: Any = None
group_by: list = field(default_factory=list)
having: Any = None
order_by: list = field(default_factory=list)
limit: Any = None
offset: Any = None
distinct: bool = False
@dataclass
class ColumnDef:
name: str
type: str = ""
primary_key: bool = False
not_null: bool = False
unique: bool = False
default: Any = None
def L(v):
return Literal(v)
def C(name, table=None):
return Column(table, name)
def B(left, op, right):
return Binary(op, left, right)
def lit(v):
"""A Python value becomes a Literal; a node stays a node."""
return v if hasattr(v, "__dataclass_fields__") else Literal(v)
class FakeStorage:
def __init__(self, tables):
self.tables = tables
def scan(self, table):
for i, row in enumerate(self.tables[table.lower()][1], 1):
yield i, tuple(row)
class FakeDB:
"""The two things run_select may touch: db.storage.scan and db.schema."""
def __init__(self, **tables):
# name=("a INTEGER, b TEXT", [rows])
self._t = {}
for name, (decl, rows) in tables.items():
cols = []
for part in decl.split(","):
bits = part.split()
cols.append(ColumnDef(bits[0], " ".join(bits[1:])))
self._t[name.lower()] = (cols, rows)
self.storage = FakeStorage(self._t)
def schema(self, table):
if table.lower() not in self._t:
raise KeyError(table)
return self._t[table.lower()][0]
Shown as text, exactly as the agents wrote it. Nothing here is run.