sqlprove 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sqlprove/__init__.py +28 -0
- sqlprove/algebra.py +1302 -0
- sqlprove/audit.py +347 -0
- sqlprove/cli.py +281 -0
- sqlprove/corpus.py +448 -0
- sqlprove/cost.py +92 -0
- sqlprove/dbt_manifest.py +582 -0
- sqlprove/fuzzer.py +312 -0
- sqlprove/prover.py +1568 -0
- sqlprove/rewrites.py +819 -0
- sqlprove/schema.py +430 -0
- sqlprove/targets.py +482 -0
- sqlprove-0.1.0.dist-info/LICENSE +21 -0
- sqlprove-0.1.0.dist-info/METADATA +99 -0
- sqlprove-0.1.0.dist-info/RECORD +18 -0
- sqlprove-0.1.0.dist-info/WHEEL +5 -0
- sqlprove-0.1.0.dist-info/entry_points.txt +2 -0
- sqlprove-0.1.0.dist-info/top_level.txt +1 -0
sqlprove/prover.py
ADDED
|
@@ -0,0 +1,1568 @@
|
|
|
1
|
+
"""Z3 SMT bounded bag-semantics + 3-valued NULL SQL equivalence checker.
|
|
2
|
+
|
|
3
|
+
Design principles:
|
|
4
|
+
- Fail closed: any unsupported SQL clause or non-deterministic construct raises UnsupportedSQLError.
|
|
5
|
+
- Exact SQL 3-valued Kleene logic for NULL predicates, comparisons, IN/NOT IN,
|
|
6
|
+
CASE WHEN, COALESCE, NULLIF, BETWEEN, IS TRUE/FALSE, and outer join null-extension.
|
|
7
|
+
- Exact bag (multiset) semantics for SELECT, INNER/LEFT/RIGHT/FULL/CROSS JOIN,
|
|
8
|
+
GROUP BY, HAVING, COUNT/COUNT(DISTINCT)/SUM/MIN/MAX, DISTINCT, UNION/UNION ALL,
|
|
9
|
+
VALUES, scalar aggregate subqueries, partition window aggregates, and tie-free ROW_NUMBER/QUALIFY.
|
|
10
|
+
- Full schema constraints: NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY (MATCH SIMPLE).
|
|
11
|
+
- Honest status reporting: ALGEBRAICALLY_PROVEN (unbounded) vs BOUNDED_VERIFIED(bound=k).
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
import datetime as dt
|
|
18
|
+
from enum import Enum
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
import sqlglot
|
|
22
|
+
from sqlglot import exp
|
|
23
|
+
import z3
|
|
24
|
+
|
|
25
|
+
from sqlprove.schema import Schema, TableSpec, normalize_dtype
|
|
26
|
+
|
|
27
|
+
_EPOCH_DATE = dt.date(1970, 1, 1)
|
|
28
|
+
_EPOCH_DT = dt.datetime(1970, 1, 1, 0, 0, 0)
|
|
29
|
+
_MIN_DATE_DAYS = (dt.date(1, 1, 1) - _EPOCH_DATE).days
|
|
30
|
+
_MAX_DATE_DAYS = (dt.date(9999, 12, 31) - _EPOCH_DATE).days
|
|
31
|
+
_MIN_TS_SECS = int((dt.datetime(1, 1, 1, 0, 0, 0) - _EPOCH_DT).total_seconds())
|
|
32
|
+
_MAX_TS_SECS = int((dt.datetime(9999, 12, 31, 23, 59, 59) - _EPOCH_DT).total_seconds())
|
|
33
|
+
_MAX_SYM_ROWS = 48
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class ProofStatus(str, Enum):
|
|
37
|
+
ALGEBRAICALLY_PROVEN = "ALGEBRAICALLY_PROVEN"
|
|
38
|
+
BOUNDED_VERIFIED = "BOUNDED_VERIFIED"
|
|
39
|
+
COUNTEREXAMPLE_FOUND = "COUNTEREXAMPLE_FOUND"
|
|
40
|
+
UNSUPPORTED = "UNSUPPORTED"
|
|
41
|
+
UNKNOWN = "UNKNOWN"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class UnsupportedSQLError(Exception):
|
|
45
|
+
"""Raised when a SQL construct is outside the sound verifier fragment."""
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(frozen=True)
|
|
49
|
+
class SymVal:
|
|
50
|
+
is_null: z3.BoolRef
|
|
51
|
+
val: z3.ArithRef
|
|
52
|
+
dtype: str = "INT"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(frozen=True)
|
|
56
|
+
class TriBool:
|
|
57
|
+
is_null: z3.BoolRef
|
|
58
|
+
val: z3.BoolRef
|
|
59
|
+
|
|
60
|
+
def is_true(self) -> z3.BoolRef:
|
|
61
|
+
return z3.And(z3.Not(self.is_null), self.val)
|
|
62
|
+
|
|
63
|
+
def is_false(self) -> z3.BoolRef:
|
|
64
|
+
return z3.And(z3.Not(self.is_null), z3.Not(self.val))
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@dataclass(frozen=True)
|
|
68
|
+
class SymRow:
|
|
69
|
+
present: z3.BoolRef
|
|
70
|
+
cols: tuple[tuple[str, str, SymVal], ...] # (qualifier, col_name, value)
|
|
71
|
+
|
|
72
|
+
def values(self) -> tuple[SymVal, ...]:
|
|
73
|
+
return tuple(v for _, _, v in self.cols)
|
|
74
|
+
|
|
75
|
+
def lookup(self, col_name: str, qualifier: str | None = None) -> SymVal:
|
|
76
|
+
col_l = col_name.lower()
|
|
77
|
+
if qualifier:
|
|
78
|
+
q_l = qualifier.lower()
|
|
79
|
+
matches = [v for q, c, v in self.cols if q == q_l and c == col_l]
|
|
80
|
+
if len(matches) == 1:
|
|
81
|
+
return matches[0]
|
|
82
|
+
if len(matches) > 1:
|
|
83
|
+
raise UnsupportedSQLError(f"Ambiguous column {qualifier}.{col_name}")
|
|
84
|
+
raise UnsupportedSQLError(f"Unknown column {qualifier}.{col_name}")
|
|
85
|
+
matches = [v for _, c, v in self.cols if c == col_l]
|
|
86
|
+
if len(matches) == 1:
|
|
87
|
+
return matches[0]
|
|
88
|
+
if len(matches) > 1:
|
|
89
|
+
raise UnsupportedSQLError(f"Ambiguous unqualified column '{col_name}'")
|
|
90
|
+
raise UnsupportedSQLError(f"Unknown column '{col_name}'")
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@dataclass(frozen=True)
|
|
94
|
+
class VerificationResult:
|
|
95
|
+
status: ProofStatus
|
|
96
|
+
bound: int | None = None
|
|
97
|
+
reason: str = ""
|
|
98
|
+
rule_name: str | None = None
|
|
99
|
+
counterexample: dict[str, list[dict[str, Any]]] | None = None
|
|
100
|
+
duckdb_confirmed: bool | None = None
|
|
101
|
+
duckdb_q1_rows: list[tuple[Any, ...]] | None = None
|
|
102
|
+
duckdb_q2_rows: list[tuple[Any, ...]] | None = None
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _sym_eq_sql_identity(a: SymVal, b: SymVal) -> z3.BoolRef:
|
|
106
|
+
"""Identity equality (used for DISTINCT, GROUP BY, IS NOT DISTINCT FROM, bag counts)."""
|
|
107
|
+
if a.dtype != b.dtype and a.dtype != "NULL" and b.dtype != "NULL":
|
|
108
|
+
if {a.dtype, b.dtype} == {"DATE", "TIMESTAMP"}:
|
|
109
|
+
av = a.val * 86400 if a.dtype == "DATE" else a.val
|
|
110
|
+
bv = b.val * 86400 if b.dtype == "DATE" else b.val
|
|
111
|
+
return z3.Or(
|
|
112
|
+
z3.And(a.is_null, b.is_null),
|
|
113
|
+
z3.And(z3.Not(a.is_null), z3.Not(b.is_null), av == bv),
|
|
114
|
+
)
|
|
115
|
+
raise UnsupportedSQLError(f"Incompatible types in identity comparison: {a.dtype} vs {b.dtype}")
|
|
116
|
+
return z3.Or(
|
|
117
|
+
z3.And(a.is_null, b.is_null),
|
|
118
|
+
z3.And(z3.Not(a.is_null), z3.Not(b.is_null), a.val == b.val),
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _tuple_eq(t1: tuple[SymVal, ...], t2: tuple[SymVal, ...]) -> z3.BoolRef:
|
|
123
|
+
if len(t1) != len(t2):
|
|
124
|
+
return z3.BoolVal(False)
|
|
125
|
+
if not t1:
|
|
126
|
+
return z3.BoolVal(True)
|
|
127
|
+
return z3.And(*(_sym_eq_sql_identity(a, b) for a, b in zip(t1, t2)))
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _tri_not(p: TriBool) -> TriBool:
|
|
131
|
+
return TriBool(is_null=p.is_null, val=z3.Not(p.val))
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _tri_and(p: TriBool, q: TriBool) -> TriBool:
|
|
135
|
+
definitely_false = z3.Or(p.is_false(), q.is_false())
|
|
136
|
+
definitely_true = z3.And(p.is_true(), q.is_true())
|
|
137
|
+
return TriBool(
|
|
138
|
+
is_null=z3.And(z3.Not(definitely_false), z3.Not(definitely_true)),
|
|
139
|
+
val=definitely_true,
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _tri_or(p: TriBool, q: TriBool) -> TriBool:
|
|
144
|
+
definitely_true = z3.Or(p.is_true(), q.is_true())
|
|
145
|
+
definitely_false = z3.And(p.is_false(), q.is_false())
|
|
146
|
+
return TriBool(
|
|
147
|
+
is_null=z3.And(z3.Not(definitely_true), z3.Not(definitely_false)),
|
|
148
|
+
val=definitely_true,
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _null_val(dtype: str = "NULL") -> SymVal:
|
|
153
|
+
return SymVal(is_null=z3.BoolVal(True), val=z3.IntVal(0), dtype=dtype)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _merge_dtypes(t1: str, t2: str) -> str:
|
|
157
|
+
if t1 == "NULL":
|
|
158
|
+
return t2
|
|
159
|
+
if t2 == "NULL":
|
|
160
|
+
return t1
|
|
161
|
+
if t1 == t2:
|
|
162
|
+
return t1
|
|
163
|
+
if {t1, t2} == {"DATE", "TIMESTAMP"}:
|
|
164
|
+
return "TIMESTAMP"
|
|
165
|
+
raise UnsupportedSQLError(f"Incompatible types: {t1} vs {t2}")
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _align_pair(a: SymVal, b: SymVal) -> tuple[SymVal, SymVal, str]:
|
|
169
|
+
dt_out = _merge_dtypes(a.dtype, b.dtype)
|
|
170
|
+
if a.dtype == "DATE" and dt_out == "TIMESTAMP":
|
|
171
|
+
a = SymVal(a.is_null, z3.If(a.is_null, 0, a.val * 86400), "TIMESTAMP")
|
|
172
|
+
if b.dtype == "DATE" and dt_out == "TIMESTAMP":
|
|
173
|
+
b = SymVal(b.is_null, z3.If(b.is_null, 0, b.val * 86400), "TIMESTAMP")
|
|
174
|
+
if a.dtype == "NULL" and dt_out != "NULL":
|
|
175
|
+
a = SymVal(a.is_null, a.val, dt_out)
|
|
176
|
+
if b.dtype == "NULL" and dt_out != "NULL":
|
|
177
|
+
b = SymVal(b.is_null, b.val, dt_out)
|
|
178
|
+
return a, b, dt_out
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _parse_iso_date_days(s: str) -> int:
|
|
182
|
+
try:
|
|
183
|
+
d = dt.date.fromisoformat(s.strip()[:10])
|
|
184
|
+
except ValueError as exc:
|
|
185
|
+
raise UnsupportedSQLError(f"Invalid DATE literal '{s}'") from exc
|
|
186
|
+
return (d - _EPOCH_DATE).days
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _parse_iso_timestamp_secs(s: str) -> int:
|
|
190
|
+
raw = s.strip().replace("T", " ")
|
|
191
|
+
if raw.endswith("Z"):
|
|
192
|
+
raw = raw[:-1]
|
|
193
|
+
elif raw.upper().endswith(" UTC"):
|
|
194
|
+
raw = raw[:-4]
|
|
195
|
+
try:
|
|
196
|
+
if len(raw) == 10:
|
|
197
|
+
parsed = dt.datetime.fromisoformat(raw + " 00:00:00")
|
|
198
|
+
else:
|
|
199
|
+
parsed = dt.datetime.fromisoformat(raw)
|
|
200
|
+
if parsed.microsecond != 0:
|
|
201
|
+
raise UnsupportedSQLError(f"Sub-second timestamp literal '{s}' is unsupported")
|
|
202
|
+
except ValueError as exc:
|
|
203
|
+
raise UnsupportedSQLError(f"Invalid TIMESTAMP literal '{s}'") from exc
|
|
204
|
+
return int((parsed - _EPOCH_DT).total_seconds())
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
class _SymbolicEvaluator:
|
|
208
|
+
def __init__(self, schema: Schema, bound: int, string_literals: list[str], dialect: str = "duckdb") -> None:
|
|
209
|
+
self.schema = schema
|
|
210
|
+
self.bound = bound
|
|
211
|
+
self.dialect = dialect.lower()
|
|
212
|
+
self.solver = z3.Solver()
|
|
213
|
+
self.base_tables: dict[str, list[SymRow]] = {}
|
|
214
|
+
self.str_to_id: dict[str, int] = {s: i for i, s in enumerate(string_literals)}
|
|
215
|
+
self.id_to_str: dict[int, str] = {i: s for i, s in enumerate(string_literals)}
|
|
216
|
+
self._build_base_tables()
|
|
217
|
+
|
|
218
|
+
def _encode_string(self, s: str) -> int:
|
|
219
|
+
if s not in self.str_to_id:
|
|
220
|
+
idx = len(self.str_to_id)
|
|
221
|
+
self.str_to_id[s] = idx
|
|
222
|
+
self.id_to_str[idx] = s
|
|
223
|
+
return self.str_to_id[s]
|
|
224
|
+
|
|
225
|
+
def _decode_string(self, code: int) -> str:
|
|
226
|
+
if code in self.id_to_str:
|
|
227
|
+
return self.id_to_str[code]
|
|
228
|
+
candidate = f"__s{code}"
|
|
229
|
+
while candidate in self.str_to_id:
|
|
230
|
+
candidate += "_"
|
|
231
|
+
return candidate
|
|
232
|
+
|
|
233
|
+
def _build_base_tables(self) -> None:
|
|
234
|
+
for tname, tspec in self.schema.tables.items():
|
|
235
|
+
rows: list[SymRow] = []
|
|
236
|
+
prev_present: z3.BoolRef | None = None
|
|
237
|
+
for idx in range(self.bound):
|
|
238
|
+
present = z3.Bool(f"{tname}__p_{idx}")
|
|
239
|
+
if prev_present is not None:
|
|
240
|
+
self.solver.add(z3.Implies(present, prev_present))
|
|
241
|
+
prev_present = present
|
|
242
|
+
|
|
243
|
+
col_entries: list[tuple[str, str, SymVal]] = []
|
|
244
|
+
for col in tspec.columns:
|
|
245
|
+
is_null = z3.Bool(f"{tname}__{col.name}_null_{idx}")
|
|
246
|
+
val = z3.Int(f"{tname}__{col.name}_val_{idx}")
|
|
247
|
+
cdtype = col.canonical_dtype
|
|
248
|
+
if not tspec.is_nullable(col.name):
|
|
249
|
+
self.solver.add(z3.Implies(present, z3.Not(is_null)))
|
|
250
|
+
# Canonicalize unused/null values to shrink solver search space.
|
|
251
|
+
self.solver.add(z3.Implies(z3.Or(z3.Not(present), is_null), val == 0))
|
|
252
|
+
# Domain constraints for BOOL, DATE, TIMESTAMP
|
|
253
|
+
active_non_null = z3.And(present, z3.Not(is_null))
|
|
254
|
+
if cdtype == "BOOL":
|
|
255
|
+
self.solver.add(z3.Implies(active_non_null, z3.Or(val == 0, val == 1)))
|
|
256
|
+
elif cdtype == "DATE":
|
|
257
|
+
self.solver.add(
|
|
258
|
+
z3.Implies(active_non_null, z3.And(val >= _MIN_DATE_DAYS, val <= _MAX_DATE_DAYS))
|
|
259
|
+
)
|
|
260
|
+
elif cdtype == "TIMESTAMP":
|
|
261
|
+
self.solver.add(
|
|
262
|
+
z3.Implies(active_non_null, z3.And(val >= _MIN_TS_SECS, val <= _MAX_TS_SECS))
|
|
263
|
+
)
|
|
264
|
+
col_entries.append((tname.lower(), col.name.lower(), SymVal(is_null, val, cdtype)))
|
|
265
|
+
rows.append(SymRow(present=present, cols=tuple(col_entries)))
|
|
266
|
+
|
|
267
|
+
self._add_uniqueness_constraints(tspec, rows)
|
|
268
|
+
self.base_tables[tname.lower()] = rows
|
|
269
|
+
|
|
270
|
+
# Add FOREIGN KEY constraints after all base tables are built.
|
|
271
|
+
for tname, tspec in self.schema.tables.items():
|
|
272
|
+
self._add_foreign_key_constraints(tspec, self.base_tables[tname.lower()])
|
|
273
|
+
|
|
274
|
+
def _add_uniqueness_constraints(self, tspec: TableSpec, rows: list[SymRow]) -> None:
|
|
275
|
+
for key_cols in tspec.all_unique_constraints():
|
|
276
|
+
for i in range(len(rows)):
|
|
277
|
+
for j in range(i + 1, len(rows)):
|
|
278
|
+
ri, rj = rows[i], rows[j]
|
|
279
|
+
vals_i = [ri.lookup(c) for c in key_cols]
|
|
280
|
+
vals_j = [rj.lookup(c) for c in key_cols]
|
|
281
|
+
all_non_null = z3.And(
|
|
282
|
+
*(z3.And(z3.Not(vi.is_null), z3.Not(vj.is_null)) for vi, vj in zip(vals_i, vals_j))
|
|
283
|
+
)
|
|
284
|
+
all_equal = z3.And(*(vi.val == vj.val for vi, vj in zip(vals_i, vals_j)))
|
|
285
|
+
self.solver.add(
|
|
286
|
+
z3.Implies(z3.And(ri.present, rj.present, all_non_null), z3.Not(all_equal))
|
|
287
|
+
)
|
|
288
|
+
|
|
289
|
+
def _add_foreign_key_constraints(self, tspec: TableSpec, rows: list[SymRow]) -> None:
|
|
290
|
+
for fk in tspec.foreign_keys:
|
|
291
|
+
ref_key = fk.ref_table.lower()
|
|
292
|
+
if ref_key not in self.base_tables:
|
|
293
|
+
raise UnsupportedSQLError(
|
|
294
|
+
f"Foreign key on '{tspec.name}' references undeclared table '{fk.ref_table}'"
|
|
295
|
+
)
|
|
296
|
+
ref_rows = self.base_tables[ref_key]
|
|
297
|
+
for row in rows:
|
|
298
|
+
fk_vals = [row.lookup(c) for c in fk.columns]
|
|
299
|
+
all_fk_non_null = z3.And(*(z3.Not(v.is_null) for v in fk_vals))
|
|
300
|
+
matches = []
|
|
301
|
+
for rr in ref_rows:
|
|
302
|
+
ref_vals = [rr.lookup(rc) for rc in fk.ref_columns]
|
|
303
|
+
matches.append(
|
|
304
|
+
z3.And(
|
|
305
|
+
rr.present,
|
|
306
|
+
*(z3.And(z3.Not(rv.is_null), lv.val == rv.val) for lv, rv in zip(fk_vals, ref_vals)),
|
|
307
|
+
)
|
|
308
|
+
)
|
|
309
|
+
exists_parent = z3.Or(*matches) if matches else z3.BoolVal(False)
|
|
310
|
+
self.solver.add(z3.Implies(z3.And(row.present, all_fk_non_null), exists_parent))
|
|
311
|
+
|
|
312
|
+
def eval_query(
|
|
313
|
+
self,
|
|
314
|
+
node: exp.Expression,
|
|
315
|
+
ctes: dict[str, list[SymRow]] | None = None,
|
|
316
|
+
outer_row: SymRow | None = None,
|
|
317
|
+
) -> list[SymRow]:
|
|
318
|
+
env_ctes = dict(ctes or {})
|
|
319
|
+
if isinstance(node, exp.Subquery):
|
|
320
|
+
return self.eval_query(node.this, env_ctes, outer_row)
|
|
321
|
+
|
|
322
|
+
# Evaluate WITH clause on either Union or Select root!
|
|
323
|
+
with_clause = node.args.get("with_") if isinstance(node, (exp.Select, exp.Union)) else None
|
|
324
|
+
if with_clause:
|
|
325
|
+
if with_clause.args.get("recursive"):
|
|
326
|
+
raise UnsupportedSQLError("WITH RECURSIVE is not supported")
|
|
327
|
+
for cte in with_clause.expressions:
|
|
328
|
+
alias = cte.alias.lower()
|
|
329
|
+
cte_rows = self.eval_query(cte.this, env_ctes, outer_row)
|
|
330
|
+
env_ctes[alias] = [
|
|
331
|
+
SymRow(present=r.present, cols=tuple((alias, c, v) for _, c, v in r.cols))
|
|
332
|
+
for r in cte_rows
|
|
333
|
+
]
|
|
334
|
+
|
|
335
|
+
if isinstance(node, exp.Union):
|
|
336
|
+
left_rows = self.eval_query(node.this, env_ctes, outer_row)
|
|
337
|
+
right_rows = self.eval_query(node.expression, env_ctes, outer_row)
|
|
338
|
+
if left_rows and right_rows and len(left_rows[0].cols) != len(right_rows[0].cols):
|
|
339
|
+
raise UnsupportedSQLError("UNION branches have mismatched column counts")
|
|
340
|
+
combined = self._align_union_rows(left_rows, right_rows)
|
|
341
|
+
if node.args.get("distinct", True):
|
|
342
|
+
return self._eval_distinct(combined)
|
|
343
|
+
return combined
|
|
344
|
+
if not isinstance(node, exp.Select):
|
|
345
|
+
raise UnsupportedSQLError(f"Unsupported query root: {type(node).__name__}")
|
|
346
|
+
|
|
347
|
+
# Reject unsupported clauses explicitly (fail closed).
|
|
348
|
+
for clause in ("order", "limit", "offset", "windows", "laterals"):
|
|
349
|
+
if node.args.get(clause):
|
|
350
|
+
raise UnsupportedSQLError(f"Clause '{clause.upper()}' is not supported yet")
|
|
351
|
+
|
|
352
|
+
rows = self._eval_from_and_joins(node, env_ctes, outer_row)
|
|
353
|
+
|
|
354
|
+
where = node.args.get("where")
|
|
355
|
+
if where is not None:
|
|
356
|
+
filtered: list[SymRow] = []
|
|
357
|
+
for row in rows:
|
|
358
|
+
cond = self._eval_pred(where.this, row, env_ctes, outer_row)
|
|
359
|
+
filtered.append(SymRow(present=z3.And(row.present, cond.is_true()), cols=row.cols))
|
|
360
|
+
rows = filtered
|
|
361
|
+
|
|
362
|
+
group = node.args.get("group")
|
|
363
|
+
having = node.args.get("having")
|
|
364
|
+
qualify = node.args.get("qualify")
|
|
365
|
+
has_agg = any(self._contains_agg_outside_window(e) for e in node.expressions) or (having is not None)
|
|
366
|
+
has_window = any(self._contains_window(e) for e in node.expressions) or (qualify is not None)
|
|
367
|
+
|
|
368
|
+
if group is not None or has_agg:
|
|
369
|
+
if has_window:
|
|
370
|
+
# Aggregate first (preserving group reps + agg values), then apply windows + qualify
|
|
371
|
+
rows = self._eval_group_by_with_optional_windows(node, rows, group, having, qualify, env_ctes, outer_row)
|
|
372
|
+
else:
|
|
373
|
+
rows = self._eval_group_by(node, rows, group, having, env_ctes, outer_row)
|
|
374
|
+
elif has_window:
|
|
375
|
+
rows = self._eval_projections_with_windows(node.expressions, qualify, rows, env_ctes, outer_row)
|
|
376
|
+
else:
|
|
377
|
+
rows = self._eval_projections(node.expressions, rows, env_ctes, outer_row)
|
|
378
|
+
|
|
379
|
+
if node.args.get("distinct"):
|
|
380
|
+
rows = self._eval_distinct(rows)
|
|
381
|
+
|
|
382
|
+
return rows
|
|
383
|
+
|
|
384
|
+
def _align_union_rows(self, left: list[SymRow], right: list[SymRow]) -> list[SymRow]:
|
|
385
|
+
if not left or not right:
|
|
386
|
+
return left + right
|
|
387
|
+
merged_types = [
|
|
388
|
+
_merge_dtypes(lc[2].dtype, rc[2].dtype)
|
|
389
|
+
for lc, rc in zip(left[0].cols, right[0].cols)
|
|
390
|
+
]
|
|
391
|
+
|
|
392
|
+
def cast_row(r: SymRow) -> SymRow:
|
|
393
|
+
new_cols = []
|
|
394
|
+
for (q, c, v), target_dt in zip(r.cols, merged_types):
|
|
395
|
+
if v.dtype == "DATE" and target_dt == "TIMESTAMP":
|
|
396
|
+
v = SymVal(v.is_null, z3.If(v.is_null, 0, v.val * 86400), "TIMESTAMP")
|
|
397
|
+
elif v.dtype == "NULL" and target_dt != "NULL":
|
|
398
|
+
v = SymVal(v.is_null, v.val, target_dt)
|
|
399
|
+
new_cols.append((q, c, v))
|
|
400
|
+
return SymRow(present=r.present, cols=tuple(new_cols))
|
|
401
|
+
|
|
402
|
+
return [cast_row(r) for r in left] + [cast_row(r) for r in right]
|
|
403
|
+
|
|
404
|
+
def _eval_from_and_joins(
|
|
405
|
+
self,
|
|
406
|
+
select: exp.Select,
|
|
407
|
+
ctes: dict[str, list[SymRow]],
|
|
408
|
+
outer_row: SymRow | None,
|
|
409
|
+
) -> list[SymRow]:
|
|
410
|
+
from_clause = select.args.get("from_")
|
|
411
|
+
if from_clause is None:
|
|
412
|
+
return [SymRow(present=z3.BoolVal(True), cols=())]
|
|
413
|
+
|
|
414
|
+
rows = self._eval_table_factor(from_clause.this, ctes, outer_row)
|
|
415
|
+
|
|
416
|
+
for join in select.args.get("joins") or []:
|
|
417
|
+
side = (join.side or "").upper()
|
|
418
|
+
kind = (join.kind or "").upper()
|
|
419
|
+
if side not in ("", "LEFT", "RIGHT", "FULL"):
|
|
420
|
+
raise UnsupportedSQLError(f"JOIN side '{side}' is not supported")
|
|
421
|
+
if kind not in ("", "INNER", "OUTER", "CROSS"):
|
|
422
|
+
raise UnsupportedSQLError(f"JOIN kind '{kind}' is not supported")
|
|
423
|
+
|
|
424
|
+
rhs_rows = self._eval_table_factor(join.this, ctes, outer_row)
|
|
425
|
+
on_expr = join.args.get("on")
|
|
426
|
+
using_cols = join.args.get("using") or []
|
|
427
|
+
|
|
428
|
+
if using_cols:
|
|
429
|
+
if on_expr is not None:
|
|
430
|
+
raise UnsupportedSQLError("JOIN cannot have both ON and USING")
|
|
431
|
+
rows = self._eval_join_using(rows, rhs_rows, [u.name.lower() for u in using_cols], side)
|
|
432
|
+
continue
|
|
433
|
+
|
|
434
|
+
if side in ("LEFT", "RIGHT", "FULL") and on_expr is None:
|
|
435
|
+
raise UnsupportedSQLError(f"{side} JOIN without ON predicate is unsupported")
|
|
436
|
+
|
|
437
|
+
rows = self._eval_join_on(rows, rhs_rows, on_expr, side, ctes, outer_row)
|
|
438
|
+
return rows
|
|
439
|
+
|
|
440
|
+
def _eval_join_on(
|
|
441
|
+
self,
|
|
442
|
+
lhs_rows: list[SymRow],
|
|
443
|
+
rhs_rows: list[SymRow],
|
|
444
|
+
on_expr: exp.Expression | None,
|
|
445
|
+
side: str,
|
|
446
|
+
ctes: dict[str, list[SymRow]],
|
|
447
|
+
outer_row: SymRow | None,
|
|
448
|
+
) -> list[SymRow]:
|
|
449
|
+
lhs_template = lhs_rows[0].cols if lhs_rows else ()
|
|
450
|
+
rhs_template = rhs_rows[0].cols if rhs_rows else ()
|
|
451
|
+
if len(lhs_rows) * (len(rhs_rows) + 1) > _MAX_SYM_ROWS:
|
|
452
|
+
raise UnsupportedSQLError(
|
|
453
|
+
f"Join symbolic row expansion ({len(lhs_rows)}x{len(rhs_rows)}) exceeds fail-closed budget ({_MAX_SYM_ROWS})"
|
|
454
|
+
)
|
|
455
|
+
null_lhs = tuple((q, c, _null_val(v.dtype)) for q, c, v in lhs_template)
|
|
456
|
+
null_rhs = tuple((q, c, _null_val(v.dtype)) for q, c, v in rhs_template)
|
|
457
|
+
|
|
458
|
+
joined: list[SymRow] = []
|
|
459
|
+
rhs_match_flags: list[list[z3.BoolRef]] = [[] for _ in rhs_rows]
|
|
460
|
+
|
|
461
|
+
for lrow in lhs_rows:
|
|
462
|
+
l_matches: list[z3.BoolRef] = []
|
|
463
|
+
for r_idx, rrow in enumerate(rhs_rows):
|
|
464
|
+
combined = SymRow(present=z3.And(lrow.present, rrow.present), cols=lrow.cols + rrow.cols)
|
|
465
|
+
if on_expr is not None:
|
|
466
|
+
cond = self._eval_pred(on_expr, combined, ctes, outer_row)
|
|
467
|
+
matched = z3.And(combined.present, cond.is_true())
|
|
468
|
+
else:
|
|
469
|
+
matched = combined.present
|
|
470
|
+
l_matches.append(matched)
|
|
471
|
+
rhs_match_flags[r_idx].append(matched)
|
|
472
|
+
joined.append(SymRow(present=matched, cols=combined.cols))
|
|
473
|
+
if side in ("LEFT", "FULL"):
|
|
474
|
+
no_match = z3.And(*(z3.Not(m) for m in l_matches)) if l_matches else z3.BoolVal(True)
|
|
475
|
+
joined.append(SymRow(present=z3.And(lrow.present, no_match), cols=lrow.cols + null_rhs))
|
|
476
|
+
|
|
477
|
+
if side in ("RIGHT", "FULL"):
|
|
478
|
+
for r_idx, rrow in enumerate(rhs_rows):
|
|
479
|
+
no_match = (
|
|
480
|
+
z3.And(*(z3.Not(m) for m in rhs_match_flags[r_idx]))
|
|
481
|
+
if rhs_match_flags[r_idx]
|
|
482
|
+
else z3.BoolVal(True)
|
|
483
|
+
)
|
|
484
|
+
joined.append(SymRow(present=z3.And(rrow.present, no_match), cols=null_lhs + rrow.cols))
|
|
485
|
+
return joined
|
|
486
|
+
|
|
487
|
+
def _eval_join_using(
|
|
488
|
+
self,
|
|
489
|
+
lhs_rows: list[SymRow],
|
|
490
|
+
rhs_rows: list[SymRow],
|
|
491
|
+
using_cols: list[str],
|
|
492
|
+
side: str,
|
|
493
|
+
) -> list[SymRow]:
|
|
494
|
+
"""Exact SQL JOIN USING semantics: equality on named cols + coalesced output columns."""
|
|
495
|
+
lhs_template = lhs_rows[0].cols if lhs_rows else ()
|
|
496
|
+
rhs_template = rhs_rows[0].cols if rhs_rows else ()
|
|
497
|
+
if len(lhs_rows) * (len(rhs_rows) + 1) > _MAX_SYM_ROWS:
|
|
498
|
+
raise UnsupportedSQLError(
|
|
499
|
+
f"Join symbolic row expansion ({len(lhs_rows)}x{len(rhs_rows)}) exceeds fail-closed budget ({_MAX_SYM_ROWS})"
|
|
500
|
+
)
|
|
501
|
+
null_lhs = tuple((q, c, _null_val(v.dtype)) for q, c, v in lhs_template)
|
|
502
|
+
null_rhs = tuple((q, c, _null_val(v.dtype)) for q, c, v in rhs_template)
|
|
503
|
+
using_set = set(using_cols)
|
|
504
|
+
|
|
505
|
+
def merge_cols(lcols: tuple[tuple[str, str, SymVal], ...], rcols: tuple[tuple[str, str, SymVal], ...]) -> tuple[tuple[str, str, SymVal], ...]:
|
|
506
|
+
# Keep qualified entries for both sides, plus omit duplicate unqualified ambiguity on USING cols
|
|
507
|
+
# by retaining LHS's entry (coalesced with RHS for RIGHT/FULL) and dropping RHS's duplicate USING col.
|
|
508
|
+
out: list[tuple[str, str, SymVal]] = []
|
|
509
|
+
r_by_col = {c: v for _, c, v in rcols}
|
|
510
|
+
for q, c, lv in lcols:
|
|
511
|
+
if c in using_set and c in r_by_col:
|
|
512
|
+
rv = r_by_col[c]
|
|
513
|
+
lv_a, rv_a, dt_out = _align_pair(lv, rv)
|
|
514
|
+
coalesced = SymVal(
|
|
515
|
+
is_null=z3.If(z3.Not(lv_a.is_null), z3.BoolVal(False), rv_a.is_null),
|
|
516
|
+
val=z3.If(z3.Not(lv_a.is_null), lv_a.val, rv_a.val),
|
|
517
|
+
dtype=dt_out,
|
|
518
|
+
)
|
|
519
|
+
out.append((q, c, coalesced))
|
|
520
|
+
else:
|
|
521
|
+
out.append((q, c, lv))
|
|
522
|
+
for q, c, rv in rcols:
|
|
523
|
+
if c not in using_set:
|
|
524
|
+
out.append((q, c, rv))
|
|
525
|
+
return tuple(out)
|
|
526
|
+
|
|
527
|
+
joined: list[SymRow] = []
|
|
528
|
+
rhs_match_flags: list[list[z3.BoolRef]] = [[] for _ in rhs_rows]
|
|
529
|
+
for lrow in lhs_rows:
|
|
530
|
+
l_matches: list[z3.BoolRef] = []
|
|
531
|
+
for r_idx, rrow in enumerate(rhs_rows):
|
|
532
|
+
eqs = []
|
|
533
|
+
for uc in using_cols:
|
|
534
|
+
lv = lrow.lookup(uc)
|
|
535
|
+
rv = rrow.lookup(uc)
|
|
536
|
+
lv, rv, _ = _align_pair(lv, rv)
|
|
537
|
+
eqs.append(z3.And(z3.Not(lv.is_null), z3.Not(rv.is_null), lv.val == rv.val))
|
|
538
|
+
matched = z3.And(lrow.present, rrow.present, *eqs)
|
|
539
|
+
l_matches.append(matched)
|
|
540
|
+
rhs_match_flags[r_idx].append(matched)
|
|
541
|
+
joined.append(SymRow(present=matched, cols=merge_cols(lrow.cols, rrow.cols)))
|
|
542
|
+
if side in ("LEFT", "FULL"):
|
|
543
|
+
no_match = z3.And(*(z3.Not(m) for m in l_matches)) if l_matches else z3.BoolVal(True)
|
|
544
|
+
joined.append(SymRow(present=z3.And(lrow.present, no_match), cols=merge_cols(lrow.cols, null_rhs)))
|
|
545
|
+
|
|
546
|
+
if side in ("RIGHT", "FULL"):
|
|
547
|
+
for r_idx, rrow in enumerate(rhs_rows):
|
|
548
|
+
no_match = (
|
|
549
|
+
z3.And(*(z3.Not(m) for m in rhs_match_flags[r_idx]))
|
|
550
|
+
if rhs_match_flags[r_idx]
|
|
551
|
+
else z3.BoolVal(True)
|
|
552
|
+
)
|
|
553
|
+
joined.append(SymRow(present=z3.And(rrow.present, no_match), cols=merge_cols(null_lhs, rrow.cols)))
|
|
554
|
+
return joined
|
|
555
|
+
|
|
556
|
+
def _eval_table_factor(
|
|
557
|
+
self,
|
|
558
|
+
factor: exp.Expression,
|
|
559
|
+
ctes: dict[str, list[SymRow]],
|
|
560
|
+
outer_row: SymRow | None,
|
|
561
|
+
) -> list[SymRow]:
|
|
562
|
+
if isinstance(factor, exp.Table):
|
|
563
|
+
tname = factor.name.lower()
|
|
564
|
+
alias = (factor.alias or factor.name).lower()
|
|
565
|
+
if tname in ctes:
|
|
566
|
+
src = ctes[tname]
|
|
567
|
+
elif tname in self.base_tables:
|
|
568
|
+
src = self.base_tables[tname]
|
|
569
|
+
else:
|
|
570
|
+
raise UnsupportedSQLError(f"Unknown table '{factor.name}' (declare it in Schema)")
|
|
571
|
+
return [
|
|
572
|
+
SymRow(present=r.present, cols=tuple((alias, c, v) for _, c, v in r.cols))
|
|
573
|
+
for r in src
|
|
574
|
+
]
|
|
575
|
+
if isinstance(factor, exp.Subquery):
|
|
576
|
+
alias = (factor.alias or "__sub").lower()
|
|
577
|
+
if isinstance(factor.this, exp.Values):
|
|
578
|
+
return self._eval_values(factor.this, alias, factor.args.get("alias"), ctes, outer_row)
|
|
579
|
+
sub_rows = self.eval_query(factor.this, ctes, outer_row)
|
|
580
|
+
col_aliases = []
|
|
581
|
+
tbl_alias = factor.args.get("alias")
|
|
582
|
+
if isinstance(tbl_alias, exp.TableAlias) and tbl_alias.columns:
|
|
583
|
+
col_aliases = [c.name.lower() for c in tbl_alias.columns]
|
|
584
|
+
out_rows: list[SymRow] = []
|
|
585
|
+
for r in sub_rows:
|
|
586
|
+
if col_aliases:
|
|
587
|
+
if len(col_aliases) != len(r.cols):
|
|
588
|
+
raise UnsupportedSQLError("Subquery column alias count mismatch")
|
|
589
|
+
new_cols = tuple((alias, ca, v) for ca, (_, _, v) in zip(col_aliases, r.cols))
|
|
590
|
+
else:
|
|
591
|
+
new_cols = tuple((alias, c, v) for _, c, v in r.cols)
|
|
592
|
+
out_rows.append(SymRow(present=r.present, cols=new_cols))
|
|
593
|
+
return out_rows
|
|
594
|
+
if isinstance(factor, exp.Values):
|
|
595
|
+
alias = (factor.alias or "__values").lower()
|
|
596
|
+
return self._eval_values(factor, alias, factor.args.get("alias"), ctes, outer_row)
|
|
597
|
+
raise UnsupportedSQLError(f"Unsupported FROM target: {type(factor).__name__}")
|
|
598
|
+
|
|
599
|
+
def _eval_values(
|
|
600
|
+
self,
|
|
601
|
+
values_node: exp.Values,
|
|
602
|
+
alias: str,
|
|
603
|
+
tbl_alias: exp.Expression | None,
|
|
604
|
+
ctes: dict[str, list[SymRow]],
|
|
605
|
+
outer_row: SymRow | None,
|
|
606
|
+
) -> list[SymRow]:
|
|
607
|
+
col_names: list[str] = []
|
|
608
|
+
if isinstance(tbl_alias, exp.TableAlias) and tbl_alias.columns:
|
|
609
|
+
col_names = [c.name.lower() for c in tbl_alias.columns]
|
|
610
|
+
empty_row = SymRow(present=z3.BoolVal(True), cols=())
|
|
611
|
+
out: list[SymRow] = []
|
|
612
|
+
for tup in values_node.expressions:
|
|
613
|
+
items = list(tup.expressions) if isinstance(tup, exp.Tuple) else [tup]
|
|
614
|
+
cols = []
|
|
615
|
+
for idx, item in enumerate(items):
|
|
616
|
+
cname = col_names[idx] if idx < len(col_names) else f"col{idx + 1}"
|
|
617
|
+
val = self._eval_scalar(item, empty_row, ctes, outer_row)
|
|
618
|
+
cols.append((alias, cname, val))
|
|
619
|
+
out.append(SymRow(present=z3.BoolVal(True), cols=tuple(cols)))
|
|
620
|
+
return out
|
|
621
|
+
|
|
622
|
+
def _eval_projections(
|
|
623
|
+
self,
|
|
624
|
+
projections: list[exp.Expression],
|
|
625
|
+
rows: list[SymRow],
|
|
626
|
+
ctes: dict[str, list[SymRow]],
|
|
627
|
+
outer_row: SymRow | None,
|
|
628
|
+
) -> list[SymRow]:
|
|
629
|
+
out: list[SymRow] = []
|
|
630
|
+
for row in rows:
|
|
631
|
+
proj_cols: list[tuple[str, str, SymVal]] = []
|
|
632
|
+
for idx, expr in enumerate(projections):
|
|
633
|
+
if isinstance(expr, exp.Star):
|
|
634
|
+
proj_cols.extend(row.cols)
|
|
635
|
+
elif isinstance(expr, exp.Column) and isinstance(expr.this, exp.Star):
|
|
636
|
+
q = expr.table.lower()
|
|
637
|
+
proj_cols.extend((rq, rc, rv) for rq, rc, rv in row.cols if rq == q)
|
|
638
|
+
elif isinstance(expr, exp.Alias):
|
|
639
|
+
val = self._eval_scalar(expr.this, row, ctes, outer_row)
|
|
640
|
+
proj_cols.append(("", expr.alias.lower(), val))
|
|
641
|
+
else:
|
|
642
|
+
val = self._eval_scalar(expr, row, ctes, outer_row)
|
|
643
|
+
col_name = expr.name.lower() if isinstance(expr, exp.Column) else f"__col{idx}"
|
|
644
|
+
proj_cols.append(("", col_name, val))
|
|
645
|
+
out.append(SymRow(present=row.present, cols=tuple(proj_cols)))
|
|
646
|
+
return out
|
|
647
|
+
|
|
648
|
+
def _contains_window(self, node: exp.Expression) -> bool:
|
|
649
|
+
return any(isinstance(n, exp.Window) for n in node.walk())
|
|
650
|
+
|
|
651
|
+
def _contains_agg_outside_window(self, node: exp.Expression) -> bool:
|
|
652
|
+
"""Return True if an AggFunc appears outside a Window (or inside a Window's arguments)."""
|
|
653
|
+
for n in node.walk():
|
|
654
|
+
if isinstance(n, exp.AggFunc):
|
|
655
|
+
if isinstance(n.parent, exp.Window) and n.parent.this is n:
|
|
656
|
+
continue
|
|
657
|
+
return True
|
|
658
|
+
return False
|
|
659
|
+
|
|
660
|
+
def _eval_window_expr(
|
|
661
|
+
self,
|
|
662
|
+
win: exp.Window,
|
|
663
|
+
rows: list[SymRow],
|
|
664
|
+
row_idx: int,
|
|
665
|
+
ctes: dict[str, list[SymRow]],
|
|
666
|
+
outer_row: SymRow | None,
|
|
667
|
+
all_part_keys: list[tuple[SymVal, ...]],
|
|
668
|
+
) -> SymVal:
|
|
669
|
+
"""Evaluate a supported window function for row `row_idx`."""
|
|
670
|
+
if win.args.get("spec") is not None:
|
|
671
|
+
raise UnsupportedSQLError("Explicit window frame specifications (ROWS/RANGE) are not supported yet")
|
|
672
|
+
|
|
673
|
+
cur = rows[row_idx]
|
|
674
|
+
cur_pk = all_part_keys[row_idx]
|
|
675
|
+
in_part = [
|
|
676
|
+
z3.And(rows[j].present, _tuple_eq(all_part_keys[j], cur_pk))
|
|
677
|
+
for j in range(len(rows))
|
|
678
|
+
]
|
|
679
|
+
fn = win.this
|
|
680
|
+
order = win.args.get("order")
|
|
681
|
+
|
|
682
|
+
if isinstance(fn, exp.RowNumber):
|
|
683
|
+
if order is None or not order.expressions:
|
|
684
|
+
raise UnsupportedSQLError("ROW_NUMBER() without ORDER BY is non-deterministic")
|
|
685
|
+
# Evaluate order tuples for all rows
|
|
686
|
+
order_specs: list[tuple[bool, bool, list[SymVal]]] = []
|
|
687
|
+
for ord_expr in order.expressions:
|
|
688
|
+
desc = bool(ord_expr.args.get("desc"))
|
|
689
|
+
nf_arg = ord_expr.args.get("nulls_first")
|
|
690
|
+
if nf_arg is None:
|
|
691
|
+
# DuckDB defaults to NULLS LAST for both ASC and DESC
|
|
692
|
+
nulls_first = False
|
|
693
|
+
else:
|
|
694
|
+
nulls_first = bool(nf_arg)
|
|
695
|
+
vals = [self._eval_scalar(ord_expr.this, r, ctes, outer_row) for r in rows]
|
|
696
|
+
if vals and vals[0].dtype == "STRING":
|
|
697
|
+
raise UnsupportedSQLError("ROW_NUMBER() ORDER BY on STRING column is not supported")
|
|
698
|
+
order_specs.append((desc, nulls_first, vals))
|
|
699
|
+
|
|
700
|
+
# Soundness guard: verify tie-freedom within each partition!
|
|
701
|
+
self._require_row_number_tie_free(rows, all_part_keys, order_specs)
|
|
702
|
+
|
|
703
|
+
# Strictly precedes relation between row j and row row_idx
|
|
704
|
+
precedes_terms = []
|
|
705
|
+
for j in range(len(rows)):
|
|
706
|
+
if j == row_idx:
|
|
707
|
+
continue
|
|
708
|
+
strict_before = self._order_strictly_before(j, row_idx, order_specs)
|
|
709
|
+
precedes_terms.append(z3.If(z3.And(in_part[j], strict_before), 1, 0))
|
|
710
|
+
rn = z3.IntVal(1) + (z3.Sum(precedes_terms) if precedes_terms else z3.IntVal(0))
|
|
711
|
+
return SymVal(is_null=z3.BoolVal(False), val=rn, dtype="INT")
|
|
712
|
+
|
|
713
|
+
if order is not None:
|
|
714
|
+
raise UnsupportedSQLError(f"Ordered window aggregate '{win.sql()}' is not supported yet")
|
|
715
|
+
|
|
716
|
+
# Unframed partition aggregate: MIN / MAX / SUM / COUNT over partition
|
|
717
|
+
return self._eval_agg_func(fn, rows, in_part, ctes, outer_row)
|
|
718
|
+
|
|
719
|
+
def _order_strictly_before(
|
|
720
|
+
self,
|
|
721
|
+
j: int,
|
|
722
|
+
i: int,
|
|
723
|
+
order_specs: list[tuple[bool, bool, list[SymVal]]],
|
|
724
|
+
) -> z3.BoolRef:
|
|
725
|
+
"""Return Z3 Bool: row j strictly precedes row i under lexicographic order_specs."""
|
|
726
|
+
clauses = []
|
|
727
|
+
prev_eqs: list[z3.BoolRef] = []
|
|
728
|
+
for desc, nulls_first, vals in order_specs:
|
|
729
|
+
vj, vi = vals[j], vals[i]
|
|
730
|
+
vj, vi, _ = _align_pair(vj, vi)
|
|
731
|
+
if nulls_first:
|
|
732
|
+
null_lt = z3.And(vj.is_null, z3.Not(vi.is_null))
|
|
733
|
+
else:
|
|
734
|
+
null_lt = z3.And(z3.Not(vj.is_null), vi.is_null)
|
|
735
|
+
val_lt = (vj.val > vi.val) if desc else (vj.val < vi.val)
|
|
736
|
+
strict_k = z3.Or(null_lt, z3.And(z3.Not(vj.is_null), z3.Not(vi.is_null), val_lt))
|
|
737
|
+
clauses.append(z3.And(*prev_eqs, strict_k))
|
|
738
|
+
prev_eqs.append(_sym_eq_sql_identity(vj, vi))
|
|
739
|
+
return z3.Or(*clauses) if clauses else z3.BoolVal(False)
|
|
740
|
+
|
|
741
|
+
def _require_row_number_tie_free(
|
|
742
|
+
self,
|
|
743
|
+
rows: list[SymRow],
|
|
744
|
+
part_keys: list[tuple[SymVal, ...]],
|
|
745
|
+
order_specs: list[tuple[bool, bool, list[SymVal]]],
|
|
746
|
+
) -> None:
|
|
747
|
+
"""Fail closed if two distinct present rows in the same partition can tie on ORDER BY."""
|
|
748
|
+
tie_clauses = []
|
|
749
|
+
for i in range(len(rows)):
|
|
750
|
+
for j in range(i + 1, len(rows)):
|
|
751
|
+
same_part = _tuple_eq(part_keys[i], part_keys[j])
|
|
752
|
+
same_ord = z3.And(
|
|
753
|
+
*(_sym_eq_sql_identity(vals[i], vals[j]) for _, _, vals in order_specs)
|
|
754
|
+
)
|
|
755
|
+
tie_clauses.append(z3.And(rows[i].present, rows[j].present, same_part, same_ord))
|
|
756
|
+
if not tie_clauses:
|
|
757
|
+
return
|
|
758
|
+
self.solver.push()
|
|
759
|
+
try:
|
|
760
|
+
self.solver.add(z3.Or(*tie_clauses))
|
|
761
|
+
res = self.solver.check()
|
|
762
|
+
if res != z3.unsat:
|
|
763
|
+
raise UnsupportedSQLError(
|
|
764
|
+
"ROW_NUMBER() ORDER BY is not provably tie-free under declared schema constraints"
|
|
765
|
+
)
|
|
766
|
+
finally:
|
|
767
|
+
self.solver.pop()
|
|
768
|
+
|
|
769
|
+
def _eval_scalar_with_windows(
|
|
770
|
+
self,
|
|
771
|
+
expr: exp.Expression,
|
|
772
|
+
rows: list[SymRow],
|
|
773
|
+
row_idx: int,
|
|
774
|
+
win_cache: dict[int, list[SymVal]],
|
|
775
|
+
ctes: dict[str, list[SymRow]],
|
|
776
|
+
outer_row: SymRow | None,
|
|
777
|
+
) -> SymVal:
|
|
778
|
+
if isinstance(expr, exp.Window):
|
|
779
|
+
return win_cache[id(expr)][row_idx]
|
|
780
|
+
if isinstance(expr, exp.Paren):
|
|
781
|
+
return self._eval_scalar_with_windows(expr.this, rows, row_idx, win_cache, ctes, outer_row)
|
|
782
|
+
if not self._contains_window(expr):
|
|
783
|
+
return self._eval_scalar(expr, rows[row_idx], ctes, outer_row)
|
|
784
|
+
if isinstance(expr, exp.Coalesce):
|
|
785
|
+
args = [expr.this, *expr.expressions]
|
|
786
|
+
vals = [self._eval_scalar_with_windows(a, rows, row_idx, win_cache, ctes, outer_row) for a in args]
|
|
787
|
+
return self._fold_coalesce(vals)
|
|
788
|
+
if isinstance(expr, (exp.Add, exp.Sub, exp.Mul)):
|
|
789
|
+
a = self._eval_scalar_with_windows(expr.this, rows, row_idx, win_cache, ctes, outer_row)
|
|
790
|
+
b = self._eval_scalar_with_windows(expr.expression, rows, row_idx, win_cache, ctes, outer_row)
|
|
791
|
+
return self._eval_arith(expr, a, b)
|
|
792
|
+
raise UnsupportedSQLError(f"Unsupported compound window expression: {expr.sql()}")
|
|
793
|
+
|
|
794
|
+
def _eval_pred_with_windows(
|
|
795
|
+
self,
|
|
796
|
+
expr: exp.Expression,
|
|
797
|
+
rows: list[SymRow],
|
|
798
|
+
row_idx: int,
|
|
799
|
+
win_cache: dict[int, list[SymVal]],
|
|
800
|
+
ctes: dict[str, list[SymRow]],
|
|
801
|
+
outer_row: SymRow | None,
|
|
802
|
+
) -> TriBool:
|
|
803
|
+
if isinstance(expr, exp.Paren):
|
|
804
|
+
return self._eval_pred_with_windows(expr.this, rows, row_idx, win_cache, ctes, outer_row)
|
|
805
|
+
if not self._contains_window(expr):
|
|
806
|
+
return self._eval_pred(expr, rows[row_idx], ctes, outer_row)
|
|
807
|
+
if isinstance(expr, exp.Not):
|
|
808
|
+
return _tri_not(self._eval_pred_with_windows(expr.this, rows, row_idx, win_cache, ctes, outer_row))
|
|
809
|
+
if isinstance(expr, exp.And):
|
|
810
|
+
return _tri_and(
|
|
811
|
+
self._eval_pred_with_windows(expr.this, rows, row_idx, win_cache, ctes, outer_row),
|
|
812
|
+
self._eval_pred_with_windows(expr.expression, rows, row_idx, win_cache, ctes, outer_row),
|
|
813
|
+
)
|
|
814
|
+
if isinstance(expr, exp.Or):
|
|
815
|
+
return _tri_or(
|
|
816
|
+
self._eval_pred_with_windows(expr.this, rows, row_idx, win_cache, ctes, outer_row),
|
|
817
|
+
self._eval_pred_with_windows(expr.expression, rows, row_idx, win_cache, ctes, outer_row),
|
|
818
|
+
)
|
|
819
|
+
if isinstance(expr, (exp.EQ, exp.NEQ, exp.LT, exp.LTE, exp.GT, exp.GTE)):
|
|
820
|
+
a = self._eval_scalar_with_windows(expr.this, rows, row_idx, win_cache, ctes, outer_row)
|
|
821
|
+
b = self._eval_scalar_with_windows(expr.expression, rows, row_idx, win_cache, ctes, outer_row)
|
|
822
|
+
return self._eval_comparison(expr, a, b)
|
|
823
|
+
raise UnsupportedSQLError(f"Unsupported QUALIFY/window predicate: {expr.sql()}")
|
|
824
|
+
|
|
825
|
+
def _build_window_cache(
|
|
826
|
+
self,
|
|
827
|
+
exprs: list[exp.Expression],
|
|
828
|
+
rows: list[SymRow],
|
|
829
|
+
ctes: dict[str, list[SymRow]],
|
|
830
|
+
outer_row: SymRow | None,
|
|
831
|
+
) -> dict[int, list[SymVal]]:
|
|
832
|
+
win_cache: dict[int, list[SymVal]] = {}
|
|
833
|
+
for e in exprs:
|
|
834
|
+
if e is None:
|
|
835
|
+
continue
|
|
836
|
+
for w in e.find_all(exp.Window):
|
|
837
|
+
if id(w) in win_cache:
|
|
838
|
+
continue
|
|
839
|
+
part_exprs = list(w.args.get("partition_by") or [])
|
|
840
|
+
all_pks = [
|
|
841
|
+
tuple(self._eval_scalar(p, r, ctes, outer_row) for p in part_exprs)
|
|
842
|
+
for r in rows
|
|
843
|
+
]
|
|
844
|
+
win_cache[id(w)] = [
|
|
845
|
+
self._eval_window_expr(w, rows, idx, ctes, outer_row, all_pks)
|
|
846
|
+
for idx in range(len(rows))
|
|
847
|
+
]
|
|
848
|
+
return win_cache
|
|
849
|
+
|
|
850
|
+
def _eval_projections_with_windows(
|
|
851
|
+
self,
|
|
852
|
+
projections: list[exp.Expression],
|
|
853
|
+
qualify: exp.Qualify | None,
|
|
854
|
+
rows: list[SymRow],
|
|
855
|
+
ctes: dict[str, list[SymRow]],
|
|
856
|
+
outer_row: SymRow | None,
|
|
857
|
+
) -> list[SymRow]:
|
|
858
|
+
win_cache = self._build_window_cache(
|
|
859
|
+
[*projections, qualify.this if qualify else None], rows, ctes, outer_row
|
|
860
|
+
)
|
|
861
|
+
out: list[SymRow] = []
|
|
862
|
+
for idx, row in enumerate(rows):
|
|
863
|
+
present = row.present
|
|
864
|
+
if qualify is not None:
|
|
865
|
+
q_cond = self._eval_pred_with_windows(qualify.this, rows, idx, win_cache, ctes, outer_row)
|
|
866
|
+
present = z3.And(present, q_cond.is_true())
|
|
867
|
+
proj_cols: list[tuple[str, str, SymVal]] = []
|
|
868
|
+
for col_i, expr in enumerate(projections):
|
|
869
|
+
if isinstance(expr, exp.Star):
|
|
870
|
+
proj_cols.extend(row.cols)
|
|
871
|
+
elif isinstance(expr, exp.Column) and isinstance(expr.this, exp.Star):
|
|
872
|
+
q = expr.table.lower()
|
|
873
|
+
proj_cols.extend((rq, rc, rv) for rq, rc, rv in row.cols if rq == q)
|
|
874
|
+
elif isinstance(expr, exp.Alias):
|
|
875
|
+
val = self._eval_scalar_with_windows(expr.this, rows, idx, win_cache, ctes, outer_row)
|
|
876
|
+
proj_cols.append(("", expr.alias.lower(), val))
|
|
877
|
+
else:
|
|
878
|
+
val = self._eval_scalar_with_windows(expr, rows, idx, win_cache, ctes, outer_row)
|
|
879
|
+
col_name = expr.name.lower() if isinstance(expr, exp.Column) else f"__col{col_i}"
|
|
880
|
+
proj_cols.append(("", col_name, val))
|
|
881
|
+
out.append(SymRow(present=present, cols=tuple(proj_cols)))
|
|
882
|
+
return out
|
|
883
|
+
|
|
884
|
+
def _eval_group_by_with_optional_windows(
|
|
885
|
+
self,
|
|
886
|
+
select: exp.Select,
|
|
887
|
+
rows: list[SymRow],
|
|
888
|
+
group: exp.Group | None,
|
|
889
|
+
having: exp.Having | None,
|
|
890
|
+
qualify: exp.Qualify | None,
|
|
891
|
+
ctes: dict[str, list[SymRow]],
|
|
892
|
+
outer_row: SymRow | None,
|
|
893
|
+
) -> list[SymRow]:
|
|
894
|
+
"""Support GROUP BY followed by window functions / QUALIFY (Snowplow consent_users pattern)."""
|
|
895
|
+
raise UnsupportedSQLError("Combined GROUP BY + Window in the same SELECT block is not supported yet")
|
|
896
|
+
|
|
897
|
+
def _eval_distinct(self, rows: list[SymRow]) -> list[SymRow]:
|
|
898
|
+
out: list[SymRow] = []
|
|
899
|
+
for i, row in enumerate(rows):
|
|
900
|
+
seen_before = [
|
|
901
|
+
z3.And(rows[j].present, _tuple_eq(rows[j].values(), row.values()))
|
|
902
|
+
for j in range(i)
|
|
903
|
+
]
|
|
904
|
+
first_occurrence = z3.And(*(z3.Not(s) for s in seen_before)) if seen_before else z3.BoolVal(True)
|
|
905
|
+
out.append(SymRow(present=z3.And(row.present, first_occurrence), cols=row.cols))
|
|
906
|
+
return out
|
|
907
|
+
|
|
908
|
+
def _resolve_group_key_exprs(self, select: exp.Select, group: exp.Group | None) -> list[exp.Expression]:
|
|
909
|
+
if group is None:
|
|
910
|
+
return []
|
|
911
|
+
alias_map: dict[str, exp.Expression] = {}
|
|
912
|
+
for e in select.expressions:
|
|
913
|
+
if isinstance(e, exp.Alias):
|
|
914
|
+
alias_map[e.alias.lower()] = e.this
|
|
915
|
+
|
|
916
|
+
resolved: list[exp.Expression] = []
|
|
917
|
+
for k in group.expressions:
|
|
918
|
+
if isinstance(k, exp.Literal) and k.is_int:
|
|
919
|
+
pos = int(k.this) - 1
|
|
920
|
+
if 0 <= pos < len(select.expressions):
|
|
921
|
+
target = select.expressions[pos]
|
|
922
|
+
resolved.append(target.this if isinstance(target, exp.Alias) else target)
|
|
923
|
+
continue
|
|
924
|
+
raise UnsupportedSQLError(f"GROUP BY position {pos + 1} out of range")
|
|
925
|
+
if isinstance(k, exp.Column) and not k.table and k.name.lower() in alias_map:
|
|
926
|
+
resolved.append(alias_map[k.name.lower()])
|
|
927
|
+
continue
|
|
928
|
+
resolved.append(k)
|
|
929
|
+
return resolved
|
|
930
|
+
|
|
931
|
+
def _eval_group_by(
|
|
932
|
+
self,
|
|
933
|
+
select: exp.Select,
|
|
934
|
+
rows: list[SymRow],
|
|
935
|
+
group: exp.Group | None,
|
|
936
|
+
having: exp.Having | None,
|
|
937
|
+
ctes: dict[str, list[SymRow]],
|
|
938
|
+
outer_row: SymRow | None,
|
|
939
|
+
) -> list[SymRow]:
|
|
940
|
+
key_exprs = self._resolve_group_key_exprs(select, group)
|
|
941
|
+
if not key_exprs:
|
|
942
|
+
# Global aggregation (1 row unless filtered out by HAVING).
|
|
943
|
+
in_group = [r.present for r in rows]
|
|
944
|
+
rep = rows[0] if rows else SymRow(present=z3.BoolVal(False), cols=())
|
|
945
|
+
present: z3.BoolRef = z3.BoolVal(True)
|
|
946
|
+
if having is not None:
|
|
947
|
+
h_cond = self._eval_agg_pred(having.this, rows, in_group, rep, ctes, outer_row)
|
|
948
|
+
present = h_cond.is_true()
|
|
949
|
+
cols = []
|
|
950
|
+
for idx, expr in enumerate(select.expressions):
|
|
951
|
+
target = expr.this if isinstance(expr, exp.Alias) else expr
|
|
952
|
+
name = expr.alias.lower() if isinstance(expr, exp.Alias) else f"__col{idx}"
|
|
953
|
+
val = self._eval_agg_scalar(target, rows, in_group, rep, ctes, outer_row)
|
|
954
|
+
cols.append(("", name, val))
|
|
955
|
+
return [SymRow(present=present, cols=tuple(cols))]
|
|
956
|
+
|
|
957
|
+
row_keys = [
|
|
958
|
+
tuple(self._eval_scalar(k, r, ctes, outer_row) for k in key_exprs)
|
|
959
|
+
for r in rows
|
|
960
|
+
]
|
|
961
|
+
|
|
962
|
+
out: list[SymRow] = []
|
|
963
|
+
for i, rep in enumerate(rows):
|
|
964
|
+
same_as_prev = [
|
|
965
|
+
z3.And(rows[j].present, _tuple_eq(row_keys[j], row_keys[i]))
|
|
966
|
+
for j in range(i)
|
|
967
|
+
]
|
|
968
|
+
is_group_rep = z3.And(rep.present, *(z3.Not(s) for s in same_as_prev))
|
|
969
|
+
in_group = [
|
|
970
|
+
z3.And(rows[j].present, _tuple_eq(row_keys[j], row_keys[i]))
|
|
971
|
+
for j in range(len(rows))
|
|
972
|
+
]
|
|
973
|
+
|
|
974
|
+
present = is_group_rep
|
|
975
|
+
if having is not None:
|
|
976
|
+
h_cond = self._eval_agg_pred(having.this, rows, in_group, rep, ctes, outer_row)
|
|
977
|
+
present = z3.And(is_group_rep, h_cond.is_true())
|
|
978
|
+
|
|
979
|
+
out_cols: list[tuple[str, str, SymVal]] = []
|
|
980
|
+
for idx, expr in enumerate(select.expressions):
|
|
981
|
+
target = expr.this if isinstance(expr, exp.Alias) else expr
|
|
982
|
+
name = (
|
|
983
|
+
expr.alias.lower()
|
|
984
|
+
if isinstance(expr, exp.Alias)
|
|
985
|
+
else (target.name.lower() if isinstance(target, exp.Column) else f"__col{idx}")
|
|
986
|
+
)
|
|
987
|
+
val = self._eval_agg_scalar(target, rows, in_group, rep, ctes, outer_row)
|
|
988
|
+
out_cols.append(("", name, val))
|
|
989
|
+
out.append(SymRow(present=present, cols=tuple(out_cols)))
|
|
990
|
+
return out
|
|
991
|
+
|
|
992
|
+
def _eval_agg_func(
|
|
993
|
+
self,
|
|
994
|
+
expr: exp.Expression,
|
|
995
|
+
rows: list[SymRow],
|
|
996
|
+
in_group: list[z3.BoolRef],
|
|
997
|
+
ctes: dict[str, list[SymRow]],
|
|
998
|
+
outer_row: SymRow | None,
|
|
999
|
+
) -> SymVal:
|
|
1000
|
+
if isinstance(expr, exp.Count):
|
|
1001
|
+
inner = expr.this
|
|
1002
|
+
if isinstance(inner, exp.Star):
|
|
1003
|
+
cnt = z3.Sum([z3.If(flag, 1, 0) for flag in in_group]) if in_group else z3.IntVal(0)
|
|
1004
|
+
return SymVal(is_null=z3.BoolVal(False), val=cnt, dtype="INT")
|
|
1005
|
+
if isinstance(inner, exp.Distinct):
|
|
1006
|
+
if len(inner.expressions) != 1:
|
|
1007
|
+
raise UnsupportedSQLError("Multi-column COUNT(DISTINCT a, b) is not supported yet")
|
|
1008
|
+
target = inner.expressions[0]
|
|
1009
|
+
vals = [self._eval_scalar(target, row, ctes, outer_row) for row in rows]
|
|
1010
|
+
terms = []
|
|
1011
|
+
for i, (vi, flag_i) in enumerate(zip(vals, in_group)):
|
|
1012
|
+
seen_prev = [
|
|
1013
|
+
z3.And(in_group[j], z3.Not(vals[j].is_null), vals[j].val == vi.val)
|
|
1014
|
+
for j in range(i)
|
|
1015
|
+
]
|
|
1016
|
+
first_non_null = z3.And(
|
|
1017
|
+
flag_i,
|
|
1018
|
+
z3.Not(vi.is_null),
|
|
1019
|
+
*(z3.Not(s) for s in seen_prev),
|
|
1020
|
+
)
|
|
1021
|
+
terms.append(z3.If(first_non_null, 1, 0))
|
|
1022
|
+
cnt = z3.Sum(terms) if terms else z3.IntVal(0)
|
|
1023
|
+
return SymVal(is_null=z3.BoolVal(False), val=cnt, dtype="INT")
|
|
1024
|
+
terms = []
|
|
1025
|
+
for row, flag in zip(rows, in_group):
|
|
1026
|
+
v = self._eval_scalar(inner, row, ctes, outer_row)
|
|
1027
|
+
terms.append(z3.If(z3.And(flag, z3.Not(v.is_null)), 1, 0))
|
|
1028
|
+
cnt = z3.Sum(terms) if terms else z3.IntVal(0)
|
|
1029
|
+
return SymVal(is_null=z3.BoolVal(False), val=cnt, dtype="INT")
|
|
1030
|
+
|
|
1031
|
+
if isinstance(expr, exp.Sum):
|
|
1032
|
+
terms = []
|
|
1033
|
+
non_null_flags = []
|
|
1034
|
+
for row, flag in zip(rows, in_group):
|
|
1035
|
+
v = self._eval_scalar(expr.this, row, ctes, outer_row)
|
|
1036
|
+
if v.dtype not in ("INT", "NULL"):
|
|
1037
|
+
raise UnsupportedSQLError(f"SUM over non-integer type '{v.dtype}' is unsupported")
|
|
1038
|
+
active = z3.And(flag, z3.Not(v.is_null))
|
|
1039
|
+
non_null_flags.append(active)
|
|
1040
|
+
terms.append(z3.If(active, v.val, 0))
|
|
1041
|
+
any_non_null = z3.Or(*non_null_flags) if non_null_flags else z3.BoolVal(False)
|
|
1042
|
+
total = z3.Sum(terms) if terms else z3.IntVal(0)
|
|
1043
|
+
return SymVal(is_null=z3.Not(any_non_null), val=z3.If(any_non_null, total, 0), dtype="INT")
|
|
1044
|
+
|
|
1045
|
+
if isinstance(expr, (exp.Min, exp.Max)):
|
|
1046
|
+
is_min = isinstance(expr, exp.Min)
|
|
1047
|
+
has_val: z3.BoolRef = z3.BoolVal(False)
|
|
1048
|
+
best_val: z3.ArithRef = z3.IntVal(0)
|
|
1049
|
+
res_dtype = "NULL"
|
|
1050
|
+
for row, flag in zip(rows, in_group):
|
|
1051
|
+
v = self._eval_scalar(expr.this, row, ctes, outer_row)
|
|
1052
|
+
if v.dtype == "STRING":
|
|
1053
|
+
raise UnsupportedSQLError(f"{type(expr).__name__} on STRING column is unsupported")
|
|
1054
|
+
res_dtype = _merge_dtypes(res_dtype, v.dtype)
|
|
1055
|
+
active = z3.And(flag, z3.Not(v.is_null))
|
|
1056
|
+
better = (v.val < best_val) if is_min else (v.val > best_val)
|
|
1057
|
+
best_val = z3.If(active, z3.If(has_val, z3.If(better, v.val, best_val), v.val), best_val)
|
|
1058
|
+
has_val = z3.Or(has_val, active)
|
|
1059
|
+
return SymVal(is_null=z3.Not(has_val), val=z3.If(has_val, best_val, 0), dtype=res_dtype or "INT")
|
|
1060
|
+
|
|
1061
|
+
raise UnsupportedSQLError(f"Unsupported aggregate expression: {expr.sql()}")
|
|
1062
|
+
|
|
1063
|
+
def _eval_agg_scalar(
|
|
1064
|
+
self,
|
|
1065
|
+
expr: exp.Expression,
|
|
1066
|
+
rows: list[SymRow],
|
|
1067
|
+
in_group: list[z3.BoolRef],
|
|
1068
|
+
rep: SymRow,
|
|
1069
|
+
ctes: dict[str, list[SymRow]],
|
|
1070
|
+
outer_row: SymRow | None,
|
|
1071
|
+
) -> SymVal:
|
|
1072
|
+
if isinstance(expr, exp.Paren):
|
|
1073
|
+
return self._eval_agg_scalar(expr.this, rows, in_group, rep, ctes, outer_row)
|
|
1074
|
+
if isinstance(expr, exp.AggFunc):
|
|
1075
|
+
return self._eval_agg_func(expr, rows, in_group, ctes, outer_row)
|
|
1076
|
+
if not self._contains_agg_outside_window(expr):
|
|
1077
|
+
return self._eval_scalar(expr, rep, ctes, outer_row)
|
|
1078
|
+
if isinstance(expr, exp.Neg):
|
|
1079
|
+
inner = self._eval_agg_scalar(expr.this, rows, in_group, rep, ctes, outer_row)
|
|
1080
|
+
return SymVal(inner.is_null, z3.If(inner.is_null, 0, -inner.val), inner.dtype)
|
|
1081
|
+
if isinstance(expr, (exp.Add, exp.Sub, exp.Mul)):
|
|
1082
|
+
a = self._eval_agg_scalar(expr.this, rows, in_group, rep, ctes, outer_row)
|
|
1083
|
+
b = self._eval_agg_scalar(expr.expression, rows, in_group, rep, ctes, outer_row)
|
|
1084
|
+
return self._eval_arith(expr, a, b)
|
|
1085
|
+
if isinstance(expr, exp.Coalesce):
|
|
1086
|
+
args = [expr.this, *expr.expressions]
|
|
1087
|
+
vals = [self._eval_agg_scalar(a, rows, in_group, rep, ctes, outer_row) for a in args]
|
|
1088
|
+
return self._fold_coalesce(vals)
|
|
1089
|
+
if isinstance(expr, exp.Case):
|
|
1090
|
+
return self._eval_case_generic(
|
|
1091
|
+
expr,
|
|
1092
|
+
eval_s=lambda e: self._eval_agg_scalar(e, rows, in_group, rep, ctes, outer_row),
|
|
1093
|
+
eval_p=lambda e: self._eval_agg_pred(e, rows, in_group, rep, ctes, outer_row),
|
|
1094
|
+
)
|
|
1095
|
+
raise UnsupportedSQLError(f"Unsupported aggregate scalar expression: {expr.sql()}")
|
|
1096
|
+
|
|
1097
|
+
def _eval_agg_pred(
|
|
1098
|
+
self,
|
|
1099
|
+
expr: exp.Expression,
|
|
1100
|
+
rows: list[SymRow],
|
|
1101
|
+
in_group: list[z3.BoolRef],
|
|
1102
|
+
rep: SymRow,
|
|
1103
|
+
ctes: dict[str, list[SymRow]],
|
|
1104
|
+
outer_row: SymRow | None,
|
|
1105
|
+
) -> TriBool:
|
|
1106
|
+
if isinstance(expr, exp.Paren):
|
|
1107
|
+
return self._eval_agg_pred(expr.this, rows, in_group, rep, ctes, outer_row)
|
|
1108
|
+
if not self._contains_agg_outside_window(expr):
|
|
1109
|
+
return self._eval_pred(expr, rep, ctes, outer_row)
|
|
1110
|
+
if isinstance(expr, exp.Not):
|
|
1111
|
+
return _tri_not(self._eval_agg_pred(expr.this, rows, in_group, rep, ctes, outer_row))
|
|
1112
|
+
if isinstance(expr, exp.And):
|
|
1113
|
+
return _tri_and(
|
|
1114
|
+
self._eval_agg_pred(expr.this, rows, in_group, rep, ctes, outer_row),
|
|
1115
|
+
self._eval_agg_pred(expr.expression, rows, in_group, rep, ctes, outer_row),
|
|
1116
|
+
)
|
|
1117
|
+
if isinstance(expr, exp.Or):
|
|
1118
|
+
return _tri_or(
|
|
1119
|
+
self._eval_agg_pred(expr.this, rows, in_group, rep, ctes, outer_row),
|
|
1120
|
+
self._eval_agg_pred(expr.expression, rows, in_group, rep, ctes, outer_row),
|
|
1121
|
+
)
|
|
1122
|
+
if isinstance(expr, exp.Is) and isinstance(expr.expression, exp.Null):
|
|
1123
|
+
lhs = self._eval_agg_scalar(expr.this, rows, in_group, rep, ctes, outer_row)
|
|
1124
|
+
return TriBool(is_null=z3.BoolVal(False), val=lhs.is_null)
|
|
1125
|
+
if isinstance(expr, (exp.EQ, exp.NEQ, exp.LT, exp.LTE, exp.GT, exp.GTE)):
|
|
1126
|
+
a = self._eval_agg_scalar(expr.this, rows, in_group, rep, ctes, outer_row)
|
|
1127
|
+
b = self._eval_agg_scalar(expr.expression, rows, in_group, rep, ctes, outer_row)
|
|
1128
|
+
return self._eval_comparison(expr, a, b)
|
|
1129
|
+
raise UnsupportedSQLError(f"Unsupported HAVING predicate: {expr.sql()}")
|
|
1130
|
+
|
|
1131
|
+
def _lookup_with_outer(self, col: exp.Column, row: SymRow, outer_row: SymRow | None) -> SymVal:
|
|
1132
|
+
qualifier = col.table or None
|
|
1133
|
+
try:
|
|
1134
|
+
return row.lookup(col.name, qualifier)
|
|
1135
|
+
except UnsupportedSQLError:
|
|
1136
|
+
if outer_row is not None:
|
|
1137
|
+
return outer_row.lookup(col.name, qualifier)
|
|
1138
|
+
raise
|
|
1139
|
+
|
|
1140
|
+
def _fold_coalesce(self, vals: list[SymVal]) -> SymVal:
|
|
1141
|
+
res_dt = "NULL"
|
|
1142
|
+
for v in vals:
|
|
1143
|
+
res_dt = _merge_dtypes(res_dt, v.dtype)
|
|
1144
|
+
acc = _null_val(res_dt)
|
|
1145
|
+
for v in reversed(vals):
|
|
1146
|
+
v_a, acc_a, dt_out = _align_pair(v, acc)
|
|
1147
|
+
acc = SymVal(
|
|
1148
|
+
is_null=z3.If(z3.Not(v_a.is_null), z3.BoolVal(False), acc_a.is_null),
|
|
1149
|
+
val=z3.If(z3.Not(v_a.is_null), v_a.val, acc_a.val),
|
|
1150
|
+
dtype=dt_out,
|
|
1151
|
+
)
|
|
1152
|
+
return acc
|
|
1153
|
+
|
|
1154
|
+
def _eval_arith(self, expr: exp.Expression, a: SymVal, b: SymVal) -> SymVal:
|
|
1155
|
+
if a.dtype not in ("INT", "NULL") or b.dtype not in ("INT", "NULL"):
|
|
1156
|
+
raise UnsupportedSQLError(f"Arithmetic only supported on INT (got {a.dtype}, {b.dtype})")
|
|
1157
|
+
null = z3.Or(a.is_null, b.is_null)
|
|
1158
|
+
if isinstance(expr, exp.Add):
|
|
1159
|
+
res = a.val + b.val
|
|
1160
|
+
elif isinstance(expr, exp.Sub):
|
|
1161
|
+
res = a.val - b.val
|
|
1162
|
+
elif isinstance(expr, exp.Mul):
|
|
1163
|
+
res = a.val * b.val
|
|
1164
|
+
else:
|
|
1165
|
+
raise UnsupportedSQLError(f"Unsupported arithmetic: {type(expr).__name__}")
|
|
1166
|
+
return SymVal(is_null=null, val=z3.If(null, 0, res), dtype="INT")
|
|
1167
|
+
|
|
1168
|
+
def _eval_case_generic(self, expr: exp.Case, eval_s, eval_p) -> SymVal:
|
|
1169
|
+
default = expr.args.get("default")
|
|
1170
|
+
acc = eval_s(default) if default is not None else _null_val("NULL")
|
|
1171
|
+
if expr.this is not None:
|
|
1172
|
+
# Simple CASE <base> WHEN <cand> THEN <then_v> ...
|
|
1173
|
+
base_v = eval_s(expr.this)
|
|
1174
|
+
for if_node in reversed(expr.args.get("ifs") or []):
|
|
1175
|
+
cand_v = eval_s(if_node.this)
|
|
1176
|
+
ba, ca, _ = _align_pair(base_v, cand_v)
|
|
1177
|
+
cond = z3.And(z3.Not(ba.is_null), z3.Not(ca.is_null), ba.val == ca.val)
|
|
1178
|
+
then_v = eval_s(if_node.args["true"])
|
|
1179
|
+
tv, acc_a, dt_out = _align_pair(then_v, acc)
|
|
1180
|
+
acc = SymVal(
|
|
1181
|
+
is_null=z3.If(cond, tv.is_null, acc_a.is_null),
|
|
1182
|
+
val=z3.If(cond, tv.val, acc_a.val),
|
|
1183
|
+
dtype=dt_out,
|
|
1184
|
+
)
|
|
1185
|
+
return acc
|
|
1186
|
+
for if_node in reversed(expr.args.get("ifs") or []):
|
|
1187
|
+
cond = eval_p(if_node.this).is_true()
|
|
1188
|
+
then_v = eval_s(if_node.args["true"])
|
|
1189
|
+
tv, acc_a, dt_out = _align_pair(then_v, acc)
|
|
1190
|
+
acc = SymVal(
|
|
1191
|
+
is_null=z3.If(cond, tv.is_null, acc_a.is_null),
|
|
1192
|
+
val=z3.If(cond, tv.val, acc_a.val),
|
|
1193
|
+
dtype=dt_out,
|
|
1194
|
+
)
|
|
1195
|
+
return acc
|
|
1196
|
+
|
|
1197
|
+
def _eval_comparison(self, expr: exp.Expression, a: SymVal, b: SymVal) -> TriBool:
|
|
1198
|
+
a, b, dt_out = _align_pair(a, b)
|
|
1199
|
+
if dt_out == "STRING" and isinstance(expr, (exp.LT, exp.LTE, exp.GT, exp.GTE)):
|
|
1200
|
+
raise UnsupportedSQLError(f"Ordering comparison '{type(expr).__name__}' on STRING is unsupported")
|
|
1201
|
+
if dt_out == "BOOL" and isinstance(expr, (exp.LT, exp.LTE, exp.GT, exp.GTE)):
|
|
1202
|
+
raise UnsupportedSQLError(f"Ordering comparison '{type(expr).__name__}' on BOOL is unsupported")
|
|
1203
|
+
null = z3.Or(a.is_null, b.is_null)
|
|
1204
|
+
if isinstance(expr, exp.EQ):
|
|
1205
|
+
cmp = a.val == b.val
|
|
1206
|
+
elif isinstance(expr, exp.NEQ):
|
|
1207
|
+
cmp = a.val != b.val
|
|
1208
|
+
elif isinstance(expr, exp.LT):
|
|
1209
|
+
cmp = a.val < b.val
|
|
1210
|
+
elif isinstance(expr, exp.LTE):
|
|
1211
|
+
cmp = a.val <= b.val
|
|
1212
|
+
elif isinstance(expr, exp.GT):
|
|
1213
|
+
cmp = a.val > b.val
|
|
1214
|
+
elif isinstance(expr, exp.GTE):
|
|
1215
|
+
cmp = a.val >= b.val
|
|
1216
|
+
else:
|
|
1217
|
+
raise UnsupportedSQLError(f"Unsupported comparison: {type(expr).__name__}")
|
|
1218
|
+
return TriBool(is_null=null, val=z3.And(z3.Not(null), cmp))
|
|
1219
|
+
|
|
1220
|
+
def _eval_scalar(
|
|
1221
|
+
self,
|
|
1222
|
+
expr: exp.Expression,
|
|
1223
|
+
row: SymRow,
|
|
1224
|
+
ctes: dict[str, list[SymRow]],
|
|
1225
|
+
outer_row: SymRow | None,
|
|
1226
|
+
) -> SymVal:
|
|
1227
|
+
if isinstance(expr, exp.Paren):
|
|
1228
|
+
return self._eval_scalar(expr.this, row, ctes, outer_row)
|
|
1229
|
+
if isinstance(expr, exp.Column):
|
|
1230
|
+
return self._lookup_with_outer(expr, row, outer_row)
|
|
1231
|
+
if isinstance(expr, exp.Null):
|
|
1232
|
+
return _null_val("NULL")
|
|
1233
|
+
if isinstance(expr, exp.Boolean):
|
|
1234
|
+
return SymVal(is_null=z3.BoolVal(False), val=z3.IntVal(1 if expr.this else 0), dtype="BOOL")
|
|
1235
|
+
if isinstance(expr, exp.Literal):
|
|
1236
|
+
if expr.is_int:
|
|
1237
|
+
return SymVal(is_null=z3.BoolVal(False), val=z3.IntVal(int(expr.this)), dtype="INT")
|
|
1238
|
+
if expr.is_string:
|
|
1239
|
+
code = self._encode_string(str(expr.this))
|
|
1240
|
+
return SymVal(is_null=z3.BoolVal(False), val=z3.IntVal(code), dtype="STRING")
|
|
1241
|
+
raise UnsupportedSQLError(f"Unsupported literal type: {expr.sql()}")
|
|
1242
|
+
if isinstance(expr, exp.Cast):
|
|
1243
|
+
target_dt = normalize_dtype(expr.to.sql())
|
|
1244
|
+
if isinstance(expr.this, exp.Literal) and expr.this.is_string:
|
|
1245
|
+
if target_dt == "DATE":
|
|
1246
|
+
return SymVal(z3.BoolVal(False), z3.IntVal(_parse_iso_date_days(str(expr.this.this))), "DATE")
|
|
1247
|
+
if target_dt == "TIMESTAMP":
|
|
1248
|
+
return SymVal(
|
|
1249
|
+
z3.BoolVal(False), z3.IntVal(_parse_iso_timestamp_secs(str(expr.this.this))), "TIMESTAMP"
|
|
1250
|
+
)
|
|
1251
|
+
if target_dt == "STRING":
|
|
1252
|
+
return self._eval_scalar(expr.this, row, ctes, outer_row)
|
|
1253
|
+
inner = self._eval_scalar(expr.this, row, ctes, outer_row)
|
|
1254
|
+
if inner.dtype == target_dt:
|
|
1255
|
+
return inner
|
|
1256
|
+
if inner.dtype == "TIMESTAMP" and target_dt == "DATE":
|
|
1257
|
+
return SymVal(inner.is_null, z3.If(inner.is_null, 0, inner.val / 86400), "DATE")
|
|
1258
|
+
if inner.dtype == "DATE" and target_dt == "TIMESTAMP":
|
|
1259
|
+
return SymVal(inner.is_null, z3.If(inner.is_null, 0, inner.val * 86400), "TIMESTAMP")
|
|
1260
|
+
if inner.dtype == "NULL":
|
|
1261
|
+
return _null_val(target_dt)
|
|
1262
|
+
raise UnsupportedSQLError(f"Unsupported CAST from {inner.dtype} to {target_dt}: {expr.sql()}")
|
|
1263
|
+
if isinstance(expr, (exp.TimestampTrunc, exp.DateTrunc)):
|
|
1264
|
+
inner = self._eval_scalar(expr.this, row, ctes, outer_row)
|
|
1265
|
+
unit_node = expr.args.get("unit")
|
|
1266
|
+
unit = (unit_node.name if unit_node is not None else "").upper()
|
|
1267
|
+
if inner.dtype == "TIMESTAMP" and unit == "DAY":
|
|
1268
|
+
trunc = (inner.val / 86400) * 86400
|
|
1269
|
+
return SymVal(inner.is_null, z3.If(inner.is_null, 0, trunc), "TIMESTAMP")
|
|
1270
|
+
if inner.dtype == "TIMESTAMP" and unit == "HOUR":
|
|
1271
|
+
trunc = (inner.val / 3600) * 3600
|
|
1272
|
+
return SymVal(inner.is_null, z3.If(inner.is_null, 0, trunc), "TIMESTAMP")
|
|
1273
|
+
if inner.dtype == "DATE" and unit == "DAY":
|
|
1274
|
+
return inner
|
|
1275
|
+
raise UnsupportedSQLError(f"Unsupported DATE_TRUNC/TIMESTAMP_TRUNC unit '{unit}' on {inner.dtype}")
|
|
1276
|
+
if isinstance(expr, exp.Neg):
|
|
1277
|
+
inner = self._eval_scalar(expr.this, row, ctes, outer_row)
|
|
1278
|
+
if inner.dtype not in ("INT", "NULL"):
|
|
1279
|
+
raise UnsupportedSQLError(f"Unary negation unsupported on {inner.dtype}")
|
|
1280
|
+
return SymVal(is_null=inner.is_null, val=z3.If(inner.is_null, 0, -inner.val), dtype="INT")
|
|
1281
|
+
if isinstance(expr, (exp.Add, exp.Sub, exp.Mul)):
|
|
1282
|
+
a = self._eval_scalar(expr.this, row, ctes, outer_row)
|
|
1283
|
+
b = self._eval_scalar(expr.expression, row, ctes, outer_row)
|
|
1284
|
+
return self._eval_arith(expr, a, b)
|
|
1285
|
+
if isinstance(expr, exp.Coalesce):
|
|
1286
|
+
args = [expr.this, *expr.expressions]
|
|
1287
|
+
vals = [self._eval_scalar(a, row, ctes, outer_row) for a in args]
|
|
1288
|
+
return self._fold_coalesce(vals)
|
|
1289
|
+
if isinstance(expr, exp.Nullif):
|
|
1290
|
+
a = self._eval_scalar(expr.this, row, ctes, outer_row)
|
|
1291
|
+
b = self._eval_scalar(expr.expression, row, ctes, outer_row)
|
|
1292
|
+
a, b, dt_out = _align_pair(a, b)
|
|
1293
|
+
eq = z3.And(z3.Not(a.is_null), z3.Not(b.is_null), a.val == b.val)
|
|
1294
|
+
return SymVal(is_null=z3.Or(a.is_null, eq), val=z3.If(z3.Or(a.is_null, eq), 0, a.val), dtype=dt_out)
|
|
1295
|
+
if isinstance(expr, exp.Case):
|
|
1296
|
+
return self._eval_case_generic(
|
|
1297
|
+
expr,
|
|
1298
|
+
eval_s=lambda e: self._eval_scalar(e, row, ctes, outer_row),
|
|
1299
|
+
eval_p=lambda e: self._eval_pred(e, row, ctes, outer_row),
|
|
1300
|
+
)
|
|
1301
|
+
if isinstance(expr, exp.Subquery):
|
|
1302
|
+
# Soundness: allow ONLY guaranteed-1-row global-aggregate scalar subqueries!
|
|
1303
|
+
inner_q = expr.this
|
|
1304
|
+
if (
|
|
1305
|
+
isinstance(inner_q, exp.Select)
|
|
1306
|
+
and inner_q.args.get("group") is None
|
|
1307
|
+
and inner_q.args.get("having") is None
|
|
1308
|
+
and len(inner_q.expressions) == 1
|
|
1309
|
+
and self._contains_agg_outside_window(inner_q.expressions[0])
|
|
1310
|
+
):
|
|
1311
|
+
sub_rows = self.eval_query(inner_q, ctes, outer_row=row)
|
|
1312
|
+
if len(sub_rows) == 1 and len(sub_rows[0].cols) == 1:
|
|
1313
|
+
r0 = sub_rows[0]
|
|
1314
|
+
v0 = r0.values()[0]
|
|
1315
|
+
return SymVal(
|
|
1316
|
+
is_null=z3.Or(z3.Not(r0.present), v0.is_null),
|
|
1317
|
+
val=z3.If(z3.And(r0.present, z3.Not(v0.is_null)), v0.val, 0),
|
|
1318
|
+
dtype=v0.dtype,
|
|
1319
|
+
)
|
|
1320
|
+
raise UnsupportedSQLError("Scalar subquery only supported for single-row global aggregates")
|
|
1321
|
+
# Predicate used in scalar position (e.g. SELECT x IS NOT NULL AS flag)
|
|
1322
|
+
if isinstance(expr, (exp.EQ, exp.NEQ, exp.LT, exp.LTE, exp.GT, exp.GTE, exp.Is, exp.Not, exp.And, exp.Or, exp.In, exp.Exists, exp.NullSafeEQ, exp.Between)):
|
|
1323
|
+
tb = self._eval_pred(expr, row, ctes, outer_row)
|
|
1324
|
+
return SymVal(is_null=tb.is_null, val=z3.If(tb.is_true(), 1, 0), dtype="BOOL")
|
|
1325
|
+
raise UnsupportedSQLError(f"Unsupported scalar expression: {type(expr).__name__} ({expr.sql()})")
|
|
1326
|
+
|
|
1327
|
+
def _eval_pred(
|
|
1328
|
+
self,
|
|
1329
|
+
expr: exp.Expression,
|
|
1330
|
+
row: SymRow,
|
|
1331
|
+
ctes: dict[str, list[SymRow]],
|
|
1332
|
+
outer_row: SymRow | None,
|
|
1333
|
+
) -> TriBool:
|
|
1334
|
+
if isinstance(expr, exp.Paren):
|
|
1335
|
+
return self._eval_pred(expr.this, row, ctes, outer_row)
|
|
1336
|
+
if isinstance(expr, exp.Boolean):
|
|
1337
|
+
return TriBool(is_null=z3.BoolVal(False), val=z3.BoolVal(bool(expr.this)))
|
|
1338
|
+
if isinstance(expr, exp.Not):
|
|
1339
|
+
return _tri_not(self._eval_pred(expr.this, row, ctes, outer_row))
|
|
1340
|
+
if isinstance(expr, exp.And):
|
|
1341
|
+
return _tri_and(
|
|
1342
|
+
self._eval_pred(expr.this, row, ctes, outer_row),
|
|
1343
|
+
self._eval_pred(expr.expression, row, ctes, outer_row),
|
|
1344
|
+
)
|
|
1345
|
+
if isinstance(expr, exp.Or):
|
|
1346
|
+
return _tri_or(
|
|
1347
|
+
self._eval_pred(expr.this, row, ctes, outer_row),
|
|
1348
|
+
self._eval_pred(expr.expression, row, ctes, outer_row),
|
|
1349
|
+
)
|
|
1350
|
+
if isinstance(expr, exp.Is):
|
|
1351
|
+
if isinstance(expr.expression, exp.Null):
|
|
1352
|
+
lhs = self._eval_scalar(expr.this, row, ctes, outer_row)
|
|
1353
|
+
return TriBool(is_null=z3.BoolVal(False), val=lhs.is_null)
|
|
1354
|
+
if isinstance(expr.expression, exp.Boolean):
|
|
1355
|
+
lhs_tb = self._eval_pred(expr.this, row, ctes, outer_row)
|
|
1356
|
+
want_true = bool(expr.expression.this)
|
|
1357
|
+
return TriBool(
|
|
1358
|
+
is_null=z3.BoolVal(False),
|
|
1359
|
+
val=lhs_tb.is_true() if want_true else lhs_tb.is_false(),
|
|
1360
|
+
)
|
|
1361
|
+
raise UnsupportedSQLError(f"Unsupported IS predicate: {expr.sql()}")
|
|
1362
|
+
if isinstance(expr, exp.NullSafeEQ):
|
|
1363
|
+
a = self._eval_scalar(expr.this, row, ctes, outer_row)
|
|
1364
|
+
b = self._eval_scalar(expr.expression, row, ctes, outer_row)
|
|
1365
|
+
return TriBool(is_null=z3.BoolVal(False), val=_sym_eq_sql_identity(a, b))
|
|
1366
|
+
if isinstance(expr, exp.Between):
|
|
1367
|
+
v = self._eval_scalar(expr.this, row, ctes, outer_row)
|
|
1368
|
+
lo = self._eval_scalar(expr.args["low"], row, ctes, outer_row)
|
|
1369
|
+
hi = self._eval_scalar(expr.args["high"], row, ctes, outer_row)
|
|
1370
|
+
return _tri_and(
|
|
1371
|
+
self._eval_comparison(exp.GTE(), v, lo),
|
|
1372
|
+
self._eval_comparison(exp.LTE(), v, hi),
|
|
1373
|
+
)
|
|
1374
|
+
if isinstance(expr, (exp.EQ, exp.NEQ, exp.LT, exp.LTE, exp.GT, exp.GTE)):
|
|
1375
|
+
a = self._eval_scalar(expr.this, row, ctes, outer_row)
|
|
1376
|
+
b = self._eval_scalar(expr.expression, row, ctes, outer_row)
|
|
1377
|
+
return self._eval_comparison(expr, a, b)
|
|
1378
|
+
if isinstance(expr, exp.Exists):
|
|
1379
|
+
sub_rows = self.eval_query(expr.this, ctes, outer_row=row)
|
|
1380
|
+
any_row = z3.Or(*(r.present for r in sub_rows)) if sub_rows else z3.BoolVal(False)
|
|
1381
|
+
return TriBool(is_null=z3.BoolVal(False), val=any_row)
|
|
1382
|
+
if isinstance(expr, exp.In):
|
|
1383
|
+
lhs = self._eval_scalar(expr.this, row, ctes, outer_row)
|
|
1384
|
+
sub_query = expr.args.get("query")
|
|
1385
|
+
if sub_query is not None:
|
|
1386
|
+
sub_rows = self.eval_query(sub_query, ctes, outer_row=row)
|
|
1387
|
+
if sub_rows and len(sub_rows[0].cols) != 1:
|
|
1388
|
+
raise UnsupportedSQLError("IN subquery must project exactly 1 column")
|
|
1389
|
+
cand_pairs = [(r.present, r.values()[0]) for r in sub_rows]
|
|
1390
|
+
else:
|
|
1391
|
+
cand_pairs = [
|
|
1392
|
+
(z3.BoolVal(True), self._eval_scalar(item, row, ctes, outer_row))
|
|
1393
|
+
for item in expr.expressions
|
|
1394
|
+
]
|
|
1395
|
+
if not cand_pairs:
|
|
1396
|
+
return TriBool(is_null=z3.BoolVal(False), val=z3.BoolVal(False))
|
|
1397
|
+
aligned_pairs = []
|
|
1398
|
+
for p, v in cand_pairs:
|
|
1399
|
+
la, va, _ = _align_pair(lhs, v)
|
|
1400
|
+
aligned_pairs.append((p, la, va))
|
|
1401
|
+
any_present = z3.Or(*(p for p, _, _ in aligned_pairs))
|
|
1402
|
+
any_true = z3.Or(
|
|
1403
|
+
*(z3.And(p, z3.Not(la.is_null), z3.Not(va.is_null), la.val == va.val) for p, la, va in aligned_pairs)
|
|
1404
|
+
)
|
|
1405
|
+
all_definite_neq = z3.And(
|
|
1406
|
+
z3.Not(lhs.is_null),
|
|
1407
|
+
*(z3.Implies(p, z3.And(z3.Not(va.is_null), la.val != va.val)) for p, la, va in aligned_pairs),
|
|
1408
|
+
)
|
|
1409
|
+
definitely_false = z3.Or(z3.Not(any_present), all_definite_neq)
|
|
1410
|
+
return TriBool(
|
|
1411
|
+
is_null=z3.And(z3.Not(any_true), z3.Not(definitely_false)),
|
|
1412
|
+
val=any_true,
|
|
1413
|
+
)
|
|
1414
|
+
# Bare boolean scalar expression in predicate position (e.g. WHERE is_default, WHERE COALESCE(is_deleted, FALSE))
|
|
1415
|
+
if isinstance(expr, (exp.Column, exp.Coalesce, exp.Case, exp.Nullif)):
|
|
1416
|
+
sv = self._eval_scalar(expr, row, ctes, outer_row)
|
|
1417
|
+
if sv.dtype == "BOOL":
|
|
1418
|
+
return TriBool(is_null=sv.is_null, val=sv.val != 0)
|
|
1419
|
+
raise UnsupportedSQLError(f"Non-boolean expression '{expr.sql()}' (type={sv.dtype}) used as predicate")
|
|
1420
|
+
raise UnsupportedSQLError(f"Unsupported predicate: {type(expr).__name__} ({expr.sql()})")
|
|
1421
|
+
|
|
1422
|
+
def extract_model(self, model: z3.ModelRef) -> dict[str, list[dict[str, Any]]]:
|
|
1423
|
+
extracted: dict[str, list[dict[str, Any]]] = {}
|
|
1424
|
+
for tname, tspec in self.schema.tables.items():
|
|
1425
|
+
table_rows: list[dict[str, Any]] = []
|
|
1426
|
+
for sym_row in self.base_tables[tname.lower()]:
|
|
1427
|
+
if not z3.is_true(model.eval(sym_row.present, model_completion=True)):
|
|
1428
|
+
continue
|
|
1429
|
+
rec: dict[str, Any] = {}
|
|
1430
|
+
for col in tspec.columns:
|
|
1431
|
+
sv = sym_row.lookup(col.name)
|
|
1432
|
+
if z3.is_true(model.eval(sv.is_null, model_completion=True)):
|
|
1433
|
+
rec[col.name] = None
|
|
1434
|
+
else:
|
|
1435
|
+
raw_int = model.eval(sv.val, model_completion=True).as_long()
|
|
1436
|
+
cdtype = col.canonical_dtype
|
|
1437
|
+
if cdtype == "BOOL":
|
|
1438
|
+
rec[col.name] = bool(raw_int)
|
|
1439
|
+
elif cdtype == "STRING":
|
|
1440
|
+
rec[col.name] = self._decode_string(raw_int)
|
|
1441
|
+
elif cdtype == "DATE":
|
|
1442
|
+
rec[col.name] = (_EPOCH_DATE + dt.timedelta(days=raw_int)).isoformat()
|
|
1443
|
+
elif cdtype == "TIMESTAMP":
|
|
1444
|
+
rec[col.name] = (_EPOCH_DT + dt.timedelta(seconds=raw_int)).isoformat(sep=" ")
|
|
1445
|
+
else:
|
|
1446
|
+
rec[col.name] = raw_int
|
|
1447
|
+
table_rows.append(rec)
|
|
1448
|
+
extracted[tname] = table_rows
|
|
1449
|
+
return extracted
|
|
1450
|
+
|
|
1451
|
+
|
|
1452
|
+
def _collect_string_literals(*asts: exp.Expression) -> list[str]:
|
|
1453
|
+
lits: set[str] = set()
|
|
1454
|
+
for a in asts:
|
|
1455
|
+
for lit in a.find_all(exp.Literal):
|
|
1456
|
+
if lit.is_string:
|
|
1457
|
+
lits.add(str(lit.this))
|
|
1458
|
+
return sorted(lits)
|
|
1459
|
+
|
|
1460
|
+
|
|
1461
|
+
def prove_equivalence(
|
|
1462
|
+
q1_sql: str,
|
|
1463
|
+
q2_sql: str,
|
|
1464
|
+
schema: Schema,
|
|
1465
|
+
*,
|
|
1466
|
+
dialect: str = "duckdb",
|
|
1467
|
+
bound: int = 3,
|
|
1468
|
+
timeout_ms: int = 10_000,
|
|
1469
|
+
confirm_in_duckdb: bool = True,
|
|
1470
|
+
use_algebraic: bool = True,
|
|
1471
|
+
) -> VerificationResult:
|
|
1472
|
+
"""Check bag-equivalence of q1 and q2 under 3-valued NULL logic and schema constraints.
|
|
1473
|
+
|
|
1474
|
+
Tier 1: Unbounded sound algebraic proof (ALGEBRAICALLY_PROVEN) when enabled and preconditions strictly hold.
|
|
1475
|
+
Tier 2: Bounded Z3 SMT bag-semantics verification up to `bound` rows/table (BOUNDED_VERIFIED / COUNTEREXAMPLE_FOUND).
|
|
1476
|
+
Fails closed (UNSUPPORTED / UNKNOWN) on any unsupported construct.
|
|
1477
|
+
"""
|
|
1478
|
+
try:
|
|
1479
|
+
ast1 = sqlglot.parse_one(q1_sql, read=dialect)
|
|
1480
|
+
ast2 = sqlglot.parse_one(q2_sql, read=dialect)
|
|
1481
|
+
except Exception as exc:
|
|
1482
|
+
return VerificationResult(status=ProofStatus.UNSUPPORTED, reason=f"Parse error: {exc}")
|
|
1483
|
+
|
|
1484
|
+
if use_algebraic:
|
|
1485
|
+
try:
|
|
1486
|
+
from sqlprove.algebra import try_algebraic_proof
|
|
1487
|
+
except ImportError:
|
|
1488
|
+
try_algebraic_proof = None
|
|
1489
|
+
if try_algebraic_proof is not None:
|
|
1490
|
+
alg_res = try_algebraic_proof(ast1, ast2, schema)
|
|
1491
|
+
if alg_res is not None:
|
|
1492
|
+
return alg_res
|
|
1493
|
+
|
|
1494
|
+
string_lits = _collect_string_literals(ast1, ast2)
|
|
1495
|
+
ev = _SymbolicEvaluator(schema=schema, bound=bound, string_literals=string_lits, dialect=dialect)
|
|
1496
|
+
ev.solver.set("timeout", timeout_ms)
|
|
1497
|
+
|
|
1498
|
+
try:
|
|
1499
|
+
rows1 = ev.eval_query(ast1)
|
|
1500
|
+
rows2 = ev.eval_query(ast2)
|
|
1501
|
+
except UnsupportedSQLError as exc:
|
|
1502
|
+
return VerificationResult(status=ProofStatus.UNSUPPORTED, reason=str(exc))
|
|
1503
|
+
|
|
1504
|
+
if len(rows1) > _MAX_SYM_ROWS or len(rows2) > _MAX_SYM_ROWS:
|
|
1505
|
+
return VerificationResult(
|
|
1506
|
+
status=ProofStatus.UNSUPPORTED,
|
|
1507
|
+
reason=f"Symbolic output row count ({len(rows1)}, {len(rows2)}) exceeds fail-closed budget ({_MAX_SYM_ROWS})",
|
|
1508
|
+
)
|
|
1509
|
+
|
|
1510
|
+
if rows1 and rows2 and len(rows1[0].cols) != len(rows2[0].cols):
|
|
1511
|
+
return VerificationResult(
|
|
1512
|
+
status=ProofStatus.COUNTEREXAMPLE_FOUND,
|
|
1513
|
+
bound=bound,
|
|
1514
|
+
reason=f"Output arity mismatch: {len(rows1[0].cols)} vs {len(rows2[0].cols)}",
|
|
1515
|
+
)
|
|
1516
|
+
|
|
1517
|
+
def _bag_count(rows: list[SymRow], target: tuple[SymVal, ...]) -> z3.ArithRef:
|
|
1518
|
+
if not rows:
|
|
1519
|
+
return z3.IntVal(0)
|
|
1520
|
+
return z3.Sum([z3.If(z3.And(r.present, _tuple_eq(r.values(), target)), 1, 0) for r in rows])
|
|
1521
|
+
|
|
1522
|
+
try:
|
|
1523
|
+
diff_clauses = [
|
|
1524
|
+
z3.And(r.present, _bag_count(rows1, r.values()) != _bag_count(rows2, r.values()))
|
|
1525
|
+
for r in (rows1 + rows2)
|
|
1526
|
+
]
|
|
1527
|
+
except UnsupportedSQLError as exc:
|
|
1528
|
+
return VerificationResult(status=ProofStatus.UNSUPPORTED, reason=str(exc))
|
|
1529
|
+
|
|
1530
|
+
if not diff_clauses:
|
|
1531
|
+
return VerificationResult(status=ProofStatus.BOUNDED_VERIFIED, bound=bound, reason="Both queries always empty")
|
|
1532
|
+
|
|
1533
|
+
ev.solver.add(z3.Or(*diff_clauses))
|
|
1534
|
+
check = ev.solver.check()
|
|
1535
|
+
|
|
1536
|
+
if check == z3.unsat:
|
|
1537
|
+
return VerificationResult(
|
|
1538
|
+
status=ProofStatus.BOUNDED_VERIFIED,
|
|
1539
|
+
bound=bound,
|
|
1540
|
+
reason=f"No counterexample exists for any database up to {bound} rows/table",
|
|
1541
|
+
)
|
|
1542
|
+
if check == z3.unknown:
|
|
1543
|
+
return VerificationResult(
|
|
1544
|
+
status=ProofStatus.UNKNOWN,
|
|
1545
|
+
bound=bound,
|
|
1546
|
+
reason=f"Z3 returned unknown ({ev.solver.reason_unknown()})",
|
|
1547
|
+
)
|
|
1548
|
+
|
|
1549
|
+
counterexample = ev.extract_model(ev.solver.model())
|
|
1550
|
+
confirmed = None
|
|
1551
|
+
out1 = None
|
|
1552
|
+
out2 = None
|
|
1553
|
+
if confirm_in_duckdb:
|
|
1554
|
+
from sqlprove.fuzzer import confirm_counterexample_in_duckdb
|
|
1555
|
+
|
|
1556
|
+
confirmed, out1, out2 = confirm_counterexample_in_duckdb(
|
|
1557
|
+
q1_sql, q2_sql, schema, counterexample, dialect=dialect
|
|
1558
|
+
)
|
|
1559
|
+
|
|
1560
|
+
return VerificationResult(
|
|
1561
|
+
status=ProofStatus.COUNTEREXAMPLE_FOUND,
|
|
1562
|
+
bound=bound,
|
|
1563
|
+
reason="Found concrete database where queries return different multisets",
|
|
1564
|
+
counterexample=counterexample,
|
|
1565
|
+
duckdb_confirmed=confirmed,
|
|
1566
|
+
duckdb_q1_rows=out1,
|
|
1567
|
+
duckdb_q2_rows=out2,
|
|
1568
|
+
)
|