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/rewrites.py ADDED
@@ -0,0 +1,819 @@
1
+ """Verified SQL rewrite candidates. Every rewrite fails closed through Algebra + Z3 + DuckDB."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ import datetime as dt
7
+
8
+ import duckdb
9
+ import sqlglot
10
+ from sqlglot import exp
11
+
12
+ from sqlprove.algebra import (
13
+ _is_bool_lit,
14
+ _is_non_null_literal,
15
+ _negated_atomic_cmp,
16
+ _norm_sql,
17
+ _parse_date_extractor_window,
18
+ _split_conjuncts,
19
+ _strip_parens,
20
+ )
21
+ from sqlprove.cost import CostMeasurement, measure_duckdb_query
22
+ from sqlprove.prover import ProofStatus, VerificationResult, prove_equivalence
23
+ from sqlprove.schema import Schema
24
+ from sqlprove.targets import TargetDecision, TargetRuleAdvice, WarehouseTarget, evaluate_rule_for_target
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class RewriteCandidate:
29
+ rule: str
30
+ rewritten_sql: str
31
+ verification: VerificationResult
32
+ orig_cost: CostMeasurement | None = None
33
+ rew_cost: CostMeasurement | None = None
34
+ target_advice: TargetRuleAdvice | None = None
35
+
36
+
37
+ def _join_conjuncts(conjs: list[exp.Expression]) -> exp.Expression:
38
+ acc = conjs[0].copy()
39
+ for c in conjs[1:]:
40
+ acc = exp.And(this=acc, expression=c.copy())
41
+ return acc
42
+
43
+
44
+ def _cleanup_unused_ctes(sel: exp.Select) -> None:
45
+ if not sel.args.get("with_"):
46
+ return
47
+ # Iteratively prune CTEs not referenced by outer query or kept CTEs
48
+ ctes = list(sel.args["with_"].expressions)
49
+ body = sel.copy()
50
+ body.set("with_", None)
51
+ needed = {t.name.lower() for t in body.find_all(exp.Table) if t.name}
52
+ changed = True
53
+ while changed:
54
+ changed = False
55
+ for c in ctes:
56
+ if c.alias.lower() in needed:
57
+ for t in c.this.find_all(exp.Table):
58
+ if t.name and t.name.lower() not in needed:
59
+ needed.add(t.name.lower())
60
+ changed = True
61
+ kept = [c for c in ctes if c.alias.lower() in needed]
62
+ if kept:
63
+ sel.args["with_"].set("expressions", kept)
64
+ else:
65
+ sel.set("with_", None)
66
+
67
+
68
+ def _propose_dead_joins(ast: exp.Select, dialect: str) -> list[tuple[str, str]]:
69
+ out: list[tuple[str, str]] = []
70
+ joins = list(ast.args.get("joins") or [])
71
+ if not joins:
72
+ return out
73
+ has_star = any(
74
+ isinstance(e, exp.Star) or (isinstance(e, exp.Column) and isinstance(e.this, exp.Star))
75
+ for e in ast.expressions
76
+ )
77
+ if has_star:
78
+ return out
79
+
80
+ non_join_parts = [
81
+ *ast.expressions,
82
+ ast.args.get("where"),
83
+ ast.args.get("group"),
84
+ ast.args.get("having"),
85
+ ast.args.get("qualify"),
86
+ ]
87
+ referenced = {
88
+ c.table.lower()
89
+ for part in non_join_parts
90
+ if part is not None
91
+ for c in part.find_all(exp.Column)
92
+ if c.table
93
+ }
94
+
95
+ for idx, join in enumerate(joins):
96
+ side = (join.side or "").upper()
97
+ kind = (join.kind or "").upper()
98
+ if side not in ("", "LEFT") or kind not in ("", "INNER", "OUTER"):
99
+ continue
100
+ rhs = join.this
101
+ rhs_alias = (rhs.alias or rhs.name).lower() if isinstance(rhs, exp.Table) else (rhs.alias.lower() if hasattr(rhs, "alias") and rhs.alias else "")
102
+ if not rhs_alias:
103
+ continue
104
+ other_join_refs = {
105
+ c.table.lower()
106
+ for j_i, oj in enumerate(joins)
107
+ if j_i != idx and oj.args.get("on") is not None
108
+ for c in oj.args["on"].find_all(exp.Column)
109
+ if c.table
110
+ }
111
+ if rhs_alias not in (referenced | other_join_refs):
112
+ cloned = ast.copy()
113
+ new_joins = [j for j_idx, j in enumerate(cloned.args["joins"]) if j_idx != idx]
114
+ cloned.set("joins", new_joins or None)
115
+ _cleanup_unused_ctes(cloned)
116
+ rule = f"eliminate_unused_left_join:{rhs_alias}" if side == "LEFT" else f"eliminate_unused_inner_join_fk:{rhs_alias}"
117
+ out.append((rule, cloned.sql(dialect=dialect)))
118
+ return out
119
+
120
+
121
+ def _propose_tides_view_distinct_collapse(ast: exp.Select, dialect: str) -> list[tuple[str, str]]:
122
+ """Collapse `WITH feed_days AS (SELECT DISTINCT ... FROM base), ..., v AS (... LEFT JOIN ...) SELECT DISTINCT ... FROM v`."""
123
+ if not ast.args.get("distinct") or not ast.args.get("with_") or (ast.args.get("joins") or []):
124
+ return []
125
+ fc = ast.args.get("from_")
126
+ if fc is None or not isinstance(fc.this, exp.Table):
127
+ return []
128
+ ctes = {c.alias.lower(): c for c in ast.args["with_"].expressions if c.alias}
129
+ vname = fc.this.name.lower()
130
+ if vname not in ctes:
131
+ return []
132
+ vsel = ctes[vname].this
133
+ if not isinstance(vsel, exp.Select) or not vsel.args.get("from_"):
134
+ return []
135
+ v_lhs = vsel.args["from_"].this
136
+ if not isinstance(v_lhs, exp.Table):
137
+ return []
138
+ inner_name = v_lhs.name.lower()
139
+ if inner_name not in ctes:
140
+ return []
141
+ inner_sel = ctes[inner_name].this
142
+ if isinstance(inner_sel, exp.Select) and inner_sel.args.get("distinct") and inner_sel.args.get("from_"):
143
+ base_tbl = inner_sel.args["from_"].this
144
+ if isinstance(base_tbl, exp.Table) and base_tbl.name.lower() not in ctes:
145
+ cloned = ast.copy()
146
+ cloned.set("with_", None)
147
+ repl_tbl = base_tbl.copy()
148
+ if fc.this.args.get("alias"):
149
+ repl_tbl.set("alias", fc.this.args["alias"].copy())
150
+ else:
151
+ repl_tbl.set("alias", None)
152
+ cloned.set("from_", exp.From(this=repl_tbl))
153
+ return [("collapse_view_dead_left_join_and_nested_distinct", cloned.sql(dialect=dialect))]
154
+ return []
155
+
156
+
157
+ def _propose_coalesce_unwraps(ast: exp.Select, dialect: str) -> list[tuple[str, str]]:
158
+ where = ast.args.get("where")
159
+ if where is None:
160
+ return []
161
+ conjs = _split_conjuncts(where.this)
162
+ out: list[tuple[str, str]] = []
163
+ for idx, raw_c in enumerate(conjs):
164
+ c = _strip_parens(raw_c)
165
+ replacements: list[tuple[str, exp.Expression]] = []
166
+
167
+ # COALESCE(col, FALSE) / COALESCE(col, FALSE) = TRUE -> col = TRUE
168
+ co = c if isinstance(c, exp.Coalesce) else (c.this if isinstance(c, exp.EQ) and isinstance(c.this, exp.Coalesce) and _is_bool_lit(c.expression, True) else None)
169
+ if co is not None and len(co.expressions) == 1 and isinstance(co.this, exp.Column) and _is_bool_lit(co.expressions[0], False):
170
+ replacements.append(("unwrap_coalesce_bool_true", exp.EQ(this=co.this.copy(), expression=exp.Boolean(this=True))))
171
+
172
+ # COALESCE(col, lit) <> lit -> col <> lit
173
+ if isinstance(c, exp.NEQ) and isinstance(c.this, exp.Coalesce) and len(c.this.expressions) == 1:
174
+ col, default = c.this.this, c.this.expressions[0]
175
+ if isinstance(col, exp.Column) and _is_non_null_literal(default) and _norm_sql(default) == _norm_sql(c.expression):
176
+ replacements.append(("unwrap_coalesce_neq_sentinel", exp.NEQ(this=col.copy(), expression=c.expression.copy())))
177
+
178
+ # NOT COALESCE(col, FALSE) -> col = FALSE (iff NOT NULL) or (col = FALSE OR col IS NULL)
179
+ if isinstance(c, exp.Not) and isinstance(_strip_parens(c.this), exp.Coalesce):
180
+ nco = _strip_parens(c.this)
181
+ if len(nco.expressions) == 1 and isinstance(nco.this, exp.Column) and _is_bool_lit(nco.expressions[0], False):
182
+ col = nco.this
183
+ replacements.append(("unwrap_not_coalesce_not_null", exp.EQ(this=col.copy(), expression=exp.Boolean(this=False))))
184
+ replacements.append(
185
+ (
186
+ "unwrap_not_coalesce_null_safe",
187
+ exp.Paren(
188
+ this=exp.Or(
189
+ this=exp.EQ(this=col.copy(), expression=exp.Boolean(this=False)),
190
+ expression=exp.Is(this=col.copy(), expression=exp.Null()),
191
+ )
192
+ ),
193
+ )
194
+ )
195
+
196
+ # COALESCE(col, lit) = lit -> col = lit (iff NOT NULL) or (col = lit OR col IS NULL)
197
+ if isinstance(c, exp.EQ) and isinstance(c.this, exp.Coalesce) and len(c.this.expressions) == 1:
198
+ col, default = c.this.this, c.this.expressions[0]
199
+ if isinstance(col, exp.Column) and _is_non_null_literal(default) and _norm_sql(default) == _norm_sql(c.expression):
200
+ replacements.append(("unwrap_coalesce_eq_not_null", exp.EQ(this=col.copy(), expression=c.expression.copy())))
201
+ replacements.append(
202
+ (
203
+ "unwrap_coalesce_eq_null_safe",
204
+ exp.Paren(
205
+ this=exp.Or(
206
+ this=exp.EQ(this=col.copy(), expression=c.expression.copy()),
207
+ expression=exp.Is(this=col.copy(), expression=exp.Null()),
208
+ )
209
+ ),
210
+ )
211
+ )
212
+
213
+ for rule_name, repl in replacements:
214
+ new_conjs = [repl if i == idx else old.copy() for i, old in enumerate(conjs)]
215
+ cloned = ast.copy()
216
+ cloned.set("where", exp.Where(this=_join_conjuncts(new_conjs)))
217
+ out.append((rule_name, cloned.sql(dialect=dialect)))
218
+ return out
219
+
220
+
221
+ def _propose_or_to_union_all(ast: exp.Select, dialect: str) -> list[tuple[str, str]]:
222
+ if ast.args.get("distinct") or ast.args.get("group") or ast.args.get("having") or ast.args.get("qualify"):
223
+ return []
224
+ if any(isinstance(n, (exp.AggFunc, exp.Window)) for n in ast.walk()):
225
+ return []
226
+ where = ast.args.get("where")
227
+ if where is None:
228
+ return []
229
+ w = _strip_parens(where.this)
230
+ if not isinstance(w, exp.Or):
231
+ return []
232
+ p_expr, q_expr = _strip_parens(w.this), _strip_parens(w.expression)
233
+ neg_info = _negated_atomic_cmp(p_expr)
234
+ if neg_info is None:
235
+ return []
236
+ p_col, neg_p = neg_info
237
+ # Only split OR when Q references a different column than P (splitting same-column `x <> 'a' OR x IS NULL` hurts scan cost!)
238
+ q_cols = {c.name.lower() for c in q_expr.find_all(exp.Column) if c.name}
239
+ if not q_cols or q_cols == {p_col.name.lower()}:
240
+ return []
241
+
242
+ out: list[tuple[str, str]] = []
243
+ # Candidate 1: null-safe guard (neg_p OR p_col IS NULL)
244
+ b1 = ast.copy()
245
+ b1.set("where", exp.Where(this=p_expr.copy()))
246
+ b2_safe = ast.copy()
247
+ guard_safe = exp.Paren(this=exp.Or(this=neg_p.copy(), expression=exp.Is(this=p_col.copy(), expression=exp.Null())))
248
+ b2_safe.set("where", exp.Where(this=exp.And(this=q_expr.copy(), expression=guard_safe)))
249
+ out.append(
250
+ ("split_or_to_disjoint_union_all_null_safe", exp.Union(this=b1, expression=b2_safe, distinct=False).sql(dialect=dialect))
251
+ )
252
+
253
+ # Candidate 2: tighter guard (neg_p) — only passes prover if p_col is NOT NULL!
254
+ b2_nn = ast.copy()
255
+ b2_nn.set("where", exp.Where(this=exp.And(this=q_expr.copy(), expression=neg_p.copy())))
256
+ out.append(
257
+ ("split_or_to_disjoint_union_all_not_null", exp.Union(this=b1.copy(), expression=b2_nn, distinct=False).sql(dialect=dialect))
258
+ )
259
+ return out
260
+
261
+
262
+ def _ts_cast_node(ts: dt.datetime) -> exp.Cast:
263
+ return exp.Cast(
264
+ this=exp.Literal.string(ts.isoformat(sep=" ")),
265
+ to=exp.DataType.build("TIMESTAMP"),
266
+ )
267
+
268
+
269
+ def _propose_date_extractor_to_range(ast: exp.Select, dialect: str) -> list[tuple[str, str]]:
270
+ where = ast.args.get("where")
271
+ if where is None:
272
+ return []
273
+ conjs = _split_conjuncts(where.this)
274
+ # Partition conjuncts into date-extractor conjuncts vs remaining conjuncts
275
+ date_conjs: list[exp.Expression] = []
276
+ other_conjs: list[exp.Expression] = []
277
+ for c in conjs:
278
+ if any(isinstance(n, (exp.Extract, exp.TimeToStr, exp.TimestampTrunc, exp.DateTrunc)) for n in c.walk()) or (
279
+ isinstance(c, exp.EQ) and isinstance(c.this, exp.Anonymous) and c.this.name.upper() in ("STRFTIME", "FORMAT_TIMESTAMP", "FORMAT_DATE")
280
+ ):
281
+ date_conjs.append(c)
282
+ else:
283
+ other_conjs.append(c)
284
+ if not date_conjs:
285
+ return []
286
+ parsed = _parse_date_extractor_window(date_conjs)
287
+ if parsed is None:
288
+ return []
289
+ col_s, lo, hi, _ = parsed
290
+ # Recover original column node
291
+ col_node = next((c.copy() for dc in date_conjs for c in dc.find_all(exp.Column) if _norm_sql(c) == col_s), None)
292
+ if col_node is None:
293
+ return []
294
+ range_conjs: list[exp.Expression] = []
295
+ if lo is not None:
296
+ range_conjs.append(exp.GTE(this=col_node.copy(), expression=_ts_cast_node(lo)))
297
+ if hi is not None:
298
+ range_conjs.append(exp.LT(this=col_node.copy(), expression=_ts_cast_node(hi)))
299
+ if not range_conjs:
300
+ return []
301
+ cloned = ast.copy()
302
+ cloned.set("where", exp.Where(this=_join_conjuncts([*other_conjs, *range_conjs])))
303
+ return [("rewrite_date_extractor_to_range", cloned.sql(dialect=dialect))]
304
+
305
+
306
+ def _propose_repeated_cte_union_all_collapse(ast: exp.Union, dialect: str) -> list[tuple[str, str]]:
307
+ """Collapse `SELECT e1 FROM src UNION ALL SELECT e2 FROM src` (top-level or inside CTE) into single scan + CROSS JOIN VALUES."""
308
+ if ast.args.get("distinct", True):
309
+ return []
310
+ b1, b2 = ast.this, ast.expression
311
+ if not isinstance(b1, exp.Select) or not isinstance(b2, exp.Select):
312
+ return []
313
+ if b1.args.get("joins") or b2.args.get("joins") or b1.args.get("where") or b2.args.get("where") or b1.args.get("group") or b2.args.get("group") or b1.args.get("distinct") or b2.args.get("distinct"):
314
+ return []
315
+ f1, f2 = b1.args.get("from_"), b2.args.get("from_")
316
+ if not (f1 and f2 and isinstance(f1.this, exp.Table) and isinstance(f2.this, exp.Table)):
317
+ return []
318
+ if f1.this.name.lower() != f2.this.name.lower():
319
+ return []
320
+ if len(b1.expressions) != len(b2.expressions) or not b1.expressions:
321
+ return []
322
+ # Skip trivial SELECT *
323
+ if any(isinstance(e, exp.Star) for e in [*b1.expressions, *b2.expressions]):
324
+ return []
325
+
326
+ # Build combined projections: identical expressions stay as-is, differing ones become CASE WHEN _branch = 0 THEN e1 ELSE e2 END
327
+ dl = dialect.lower()
328
+ branch_col = (
329
+ exp.Column(this=exp.to_identifier("_branch"))
330
+ if dl == "bigquery"
331
+ else exp.Column(this=exp.to_identifier("_branch"), table=exp.to_identifier("_s"))
332
+ )
333
+ proj_exprs: list[exp.Expression] = []
334
+ for e1, e2 in zip(b1.expressions, b2.expressions):
335
+ t1 = e1.this if isinstance(e1, exp.Alias) else e1
336
+ t2 = e2.this if isinstance(e2, exp.Alias) else e2
337
+ alias = e1.alias if isinstance(e1, exp.Alias) else (t1.name if isinstance(t1, exp.Column) else None)
338
+ if _norm_sql(t1) == _norm_sql(t2):
339
+ expr = t1.copy()
340
+ else:
341
+ expr = exp.Case(
342
+ ifs=[
343
+ exp.If(
344
+ this=exp.EQ(
345
+ this=branch_col.copy(),
346
+ expression=exp.Literal.number(0),
347
+ ),
348
+ true=t1.copy(),
349
+ )
350
+ ],
351
+ default=t2.copy(),
352
+ )
353
+ proj_exprs.append(exp.Alias(this=expr, alias=exp.to_identifier(alias)) if alias else expr)
354
+
355
+ if dl == "bigquery":
356
+ join_rhs: exp.Expression = exp.Unnest(
357
+ expressions=[exp.Array(expressions=[exp.Literal.number(0), exp.Literal.number(1)])],
358
+ alias=exp.TableAlias(columns=[exp.to_identifier("_branch")]),
359
+ )
360
+ elif dl == "snowflake":
361
+ sf_vals = exp.Values(
362
+ expressions=[
363
+ exp.Tuple(expressions=[exp.Literal.number(0)]),
364
+ exp.Tuple(expressions=[exp.Literal.number(1)]),
365
+ ]
366
+ )
367
+ sf_sub = exp.Select(
368
+ expressions=[exp.Alias(this=exp.Column(this=exp.to_identifier("column1")), alias=exp.to_identifier("_branch"))],
369
+ from_=exp.From(this=sf_vals),
370
+ )
371
+ join_rhs = exp.Subquery(this=sf_sub, alias=exp.TableAlias(this=exp.to_identifier("_s")))
372
+ else:
373
+ join_rhs = exp.Values(
374
+ expressions=[
375
+ exp.Tuple(expressions=[exp.Literal.number(0)]),
376
+ exp.Tuple(expressions=[exp.Literal.number(1)]),
377
+ ],
378
+ alias=exp.TableAlias(this=exp.to_identifier("_s"), columns=[exp.to_identifier("_branch")]),
379
+ )
380
+ new_sel = exp.Select(
381
+ expressions=proj_exprs,
382
+ from_=exp.From(this=f1.this.copy()),
383
+ joins=[exp.Join(this=join_rhs, kind="CROSS")],
384
+ )
385
+ if ast.args.get("with_"):
386
+ new_sel.set("with_", ast.args["with_"].copy())
387
+ return [("collapse_repeated_cte_union_all", new_sel.sql(dialect=dialect))]
388
+
389
+
390
+ def _propose_disjoint_union_all_group_by_collapse(ast: exp.Union, dialect: str) -> list[tuple[str, str]]:
391
+ """Collapse M-branch UNION ALL over same table with disjoint `col = lit_i` filters + GROUP BY into single scan."""
392
+ from sqlprove.algebra import _flatten_union_all
393
+
394
+ branches = _flatten_union_all(ast)
395
+ if branches is None or len(branches) < 2 or ast.args.get("with_"):
396
+ return []
397
+ first = branches[0]
398
+ f0 = first.args.get("from_")
399
+ if not (f0 and isinstance(f0.this, exp.Table) and first.args.get("group") and first.args.get("where")):
400
+ return []
401
+ base_tbl = f0.this.name.lower()
402
+ base_gb = [_norm_sql(g) for g in first.args["group"].expressions]
403
+ for br in branches:
404
+ bf = br.args.get("from_")
405
+ if br.args.get("joins") or br.args.get("having") or br.args.get("distinct") or br.args.get("qualify"):
406
+ return []
407
+ if not (bf and isinstance(bf.this, exp.Table) and bf.this.name.lower() == base_tbl):
408
+ return []
409
+ if br.args.get("group") is None or br.args.get("where") is None:
410
+ return []
411
+ if [_norm_sql(g) for g in br.args["group"].expressions] != base_gb or len(br.expressions) != len(first.expressions):
412
+ return []
413
+
414
+ all_conjs = [_split_conjuncts(br.args["where"].this) for br in branches]
415
+ cand_cols = [
416
+ c.this
417
+ for c in all_conjs[0]
418
+ if isinstance(c, exp.EQ) and isinstance(c.this, exp.Column) and _is_non_null_literal(c.expression)
419
+ ]
420
+ for col_node in cand_cols:
421
+ cc = _norm_sql(col_node)
422
+ lits: list[exp.Expression] = []
423
+ extras_norm: list[list[str]] = []
424
+ extras_nodes: list[exp.Expression] = []
425
+ ok = True
426
+ for b_idx, conjs in enumerate(all_conjs):
427
+ m_lit = None
428
+ ext_n: list[str] = []
429
+ for c in conjs:
430
+ if isinstance(c, exp.EQ) and isinstance(c.this, exp.Column) and _norm_sql(c.this) == cc and _is_non_null_literal(c.expression) and m_lit is None:
431
+ m_lit = c.expression
432
+ else:
433
+ ext_n.append(_norm_sql(c))
434
+ if b_idx == 0:
435
+ extras_nodes.append(c)
436
+ if m_lit is None:
437
+ ok = False
438
+ break
439
+ lits.append(m_lit)
440
+ extras_norm.append(sorted(ext_n))
441
+ lit_norms = [_norm_sql(x) for x in lits]
442
+ if not (ok and len(set(lit_norms)) == len(lit_norms) and all(e == extras_norm[0] for e in extras_norm)):
443
+ continue
444
+
445
+ # Build single-pass projections
446
+ new_projs: list[exp.Expression] = []
447
+ proj_ok = True
448
+ for ci in range(len(first.expressions)):
449
+ e0 = first.expressions[ci]
450
+ alias = e0.alias if isinstance(e0, exp.Alias) else None
451
+ br_t = [br.expressions[ci].this if isinstance(br.expressions[ci], exp.Alias) else br.expressions[ci] for br in branches]
452
+ br_n = [_norm_sql(x) for x in br_t]
453
+ if len(set(br_n)) == 1:
454
+ expr = br_t[0].copy()
455
+ elif all(_is_non_null_literal(x) for x in br_t):
456
+ expr = exp.Case(
457
+ this=col_node.copy(),
458
+ ifs=[exp.If(this=lit.copy(), true=tv.copy()) for lit, tv in zip(lits, br_t)],
459
+ )
460
+ else:
461
+ proj_ok = False
462
+ break
463
+ new_projs.append(exp.Alias(this=expr, alias=exp.to_identifier(alias)) if alias else expr)
464
+ if not proj_ok:
465
+ continue
466
+
467
+ in_pred = exp.In(this=col_node.copy(), expressions=[x.copy() for x in lits])
468
+ where_expr = _join_conjuncts([in_pred, *extras_nodes])
469
+ new_gb = [*[g.copy() for g in first.args["group"].expressions], col_node.copy()]
470
+ rew = exp.Select(
471
+ expressions=new_projs,
472
+ from_=exp.From(this=f0.this.copy()),
473
+ where=exp.Where(this=where_expr),
474
+ group=exp.Group(expressions=new_gb),
475
+ )
476
+ return [("collapse_disjoint_union_all_group_by", rew.sql(dialect=dialect))]
477
+ return []
478
+
479
+
480
+ def _propose_multi_cte_filtered_agg_collapse(ast: exp.Select, dialect: str) -> list[tuple[str, str]]:
481
+ """Collapse `WITH a AS (SELECT k, SUM(x) AS s1 FROM T WHERE c1 GROUP BY k), b AS (SELECT k, SUM(y) AS s2 FROM T WHERE c2 GROUP BY k) SELECT a.k, a.s1, b.s2 FROM a LEFT JOIN b ON a.k = b.k` into single-pass conditional agg + HAVING."""
482
+ if not ast.args.get("with_"):
483
+ return []
484
+ joins = list(ast.args.get("joins") or [])
485
+ if len(joins) != 1 or (joins[0].side or "").upper() != "LEFT":
486
+ return []
487
+ fc = ast.args.get("from_")
488
+ if fc is None or not isinstance(fc.this, exp.Table) or not isinstance(joins[0].this, exp.Table):
489
+ return []
490
+ ctes = {c.alias.lower(): c for c in ast.args["with_"].expressions if c.alias}
491
+ a_name, b_name = fc.this.name.lower(), joins[0].this.name.lower()
492
+ if a_name not in ctes or b_name not in ctes:
493
+ return []
494
+ a_sel, b_sel = ctes[a_name].this, ctes[b_name].this
495
+ if not (isinstance(a_sel, exp.Select) and isinstance(b_sel, exp.Select)):
496
+ return []
497
+ if not (a_sel.args.get("group") and b_sel.args.get("group") and a_sel.args.get("where") and b_sel.args.get("where")):
498
+ return []
499
+ if a_sel.args.get("joins") or b_sel.args.get("joins") or a_sel.args.get("having") or b_sel.args.get("having"):
500
+ return []
501
+ af, bf = a_sel.args.get("from_"), b_sel.args.get("from_")
502
+ if not (af and bf and isinstance(af.this, exp.Table) and isinstance(bf.this, exp.Table)):
503
+ return []
504
+ if af.this.name.lower() != bf.this.name.lower():
505
+ return []
506
+ # Require single group-by column matching identically
507
+ if len(a_sel.args["group"].expressions) != 1 or len(b_sel.args["group"].expressions) != 1:
508
+ return []
509
+ gk_a, gk_b = a_sel.args["group"].expressions[0], b_sel.args["group"].expressions[0]
510
+ if not (isinstance(gk_a, exp.Column) and isinstance(gk_b, exp.Column) and gk_a.name.lower() == gk_b.name.lower()):
511
+ return []
512
+
513
+ a_alias = (fc.this.alias or fc.this.name).lower()
514
+ b_alias = (joins[0].this.alias or joins[0].this.name).lower()
515
+ # Map CTE output aliases -> conditional aggregate expression
516
+ cond_a = a_sel.args["where"].this
517
+ cond_b = b_sel.args["where"].this
518
+
519
+ def wrap_agg(expr: exp.Expression, cond: exp.Expression) -> exp.Expression | None:
520
+ if isinstance(expr, exp.Sum):
521
+ return exp.Sum(this=exp.Case(ifs=[exp.If(this=cond.copy(), true=expr.this.copy())]))
522
+ if isinstance(expr, exp.Count):
523
+ if isinstance(expr.this, exp.Star):
524
+ return exp.Count(this=exp.Case(ifs=[exp.If(this=cond.copy(), true=exp.Literal.number(1))]))
525
+ return exp.Count(this=exp.Case(ifs=[exp.If(this=cond.copy(), true=expr.this.copy())]))
526
+ if isinstance(expr, exp.Min):
527
+ return exp.Min(this=exp.Case(ifs=[exp.If(this=cond.copy(), true=expr.this.copy())]))
528
+ if isinstance(expr, exp.Max):
529
+ return exp.Max(this=exp.Case(ifs=[exp.If(this=cond.copy(), true=expr.this.copy())]))
530
+ return None
531
+
532
+ col_rewrites: dict[tuple[str, str], exp.Expression] = {}
533
+ col_rewrites[(a_alias, gk_a.name.lower())] = gk_a.copy()
534
+ for cte_al, c_sel, cond in ((a_alias, a_sel, cond_a), (b_alias, b_sel, cond_b)):
535
+ for e in c_sel.expressions:
536
+ if isinstance(e, exp.Alias):
537
+ wrapped = wrap_agg(e.this, cond)
538
+ if wrapped is not None:
539
+ col_rewrites[(cte_al, e.alias.lower())] = wrapped
540
+
541
+ new_projs: list[exp.Expression] = []
542
+ for e in ast.expressions:
543
+ target = e.this if isinstance(e, exp.Alias) else e
544
+ if not isinstance(target, exp.Column) or not target.table:
545
+ return []
546
+ key = (target.table.lower(), target.name.lower())
547
+ if key not in col_rewrites:
548
+ return []
549
+ alias_name = e.alias if isinstance(e, exp.Alias) else target.name
550
+ new_expr = col_rewrites[key].copy()
551
+ new_projs.append(
552
+ exp.Alias(this=new_expr, alias=exp.to_identifier(alias_name))
553
+ if not (isinstance(new_expr, exp.Column) and new_expr.name.lower() == alias_name.lower())
554
+ else new_expr
555
+ )
556
+
557
+ having_expr = exp.GT(
558
+ this=exp.Count(this=exp.Case(ifs=[exp.If(this=cond_a.copy(), true=exp.Literal.number(1))])),
559
+ expression=exp.Literal.number(0),
560
+ )
561
+ combined_where = exp.Or(this=exp.Paren(this=cond_a.copy()), expression=exp.Paren(this=cond_b.copy()))
562
+ rew = exp.Select(
563
+ expressions=new_projs,
564
+ from_=exp.From(this=af.this.copy()),
565
+ where=exp.Where(this=combined_where),
566
+ group=exp.Group(expressions=[gk_a.copy()]),
567
+ having=exp.Having(this=having_expr),
568
+ )
569
+ return [("collapse_multi_cte_filtered_agg", rew.sql(dialect=dialect))]
570
+
571
+
572
+ def propose_rewrites(sql: str, *, dialect: str = "duckdb") -> list[tuple[str, str]]:
573
+ """Generate candidate cost-saving rewrites before formal verification."""
574
+ ast = sqlglot.parse_one(sql, read=dialect)
575
+ candidates: list[tuple[str, str]] = []
576
+
577
+ if isinstance(ast, exp.Select):
578
+ # 1. Drop DISTINCT (both with GROUP BY and over potential UNIQUE+NOT NULL PK — prover enforces!)
579
+ if ast.args.get("distinct"):
580
+ cloned = ast.copy()
581
+ cloned.set("distinct", None)
582
+ rule = "drop_redundant_distinct_with_group_by" if ast.args.get("group") else "drop_redundant_distinct_on_unique_key"
583
+ candidates.append((rule, cloned.sql(dialect=dialect)))
584
+
585
+ # 2. Eliminate unused LEFT JOIN (or INNER JOIN w/ FK)
586
+ candidates.extend(_propose_dead_joins(ast, dialect))
587
+
588
+ # 3. Cal-ITP TIDES view dead LEFT JOIN + nested DISTINCT collapse
589
+ candidates.extend(_propose_tides_view_distinct_collapse(ast, dialect))
590
+
591
+ # 4. Unwrap COALESCE in WHERE
592
+ candidates.extend(_propose_coalesce_unwraps(ast, dialect))
593
+
594
+ # 5. Split disjunctive OR -> disjoint UNION ALL
595
+ candidates.extend(_propose_or_to_union_all(ast, dialect))
596
+
597
+ # 6. Date/timestamp extractors -> half-open range bounds
598
+ candidates.extend(_propose_date_extractor_to_range(ast, dialect))
599
+
600
+ # 7. Multi-CTE filtered agg LEFT JOIN -> single-pass conditional agg + HAVING
601
+ candidates.extend(_propose_multi_cte_filtered_agg_collapse(ast, dialect))
602
+
603
+ elif isinstance(ast, exp.Union):
604
+ # 8. QuickBooks 2x repeated CTE UNION ALL -> CROSS JOIN VALUES
605
+ candidates.extend(_propose_repeated_cte_union_all_collapse(ast, dialect))
606
+ # 9. Cal-ITP M-branch disjoint UNION ALL GROUP BY -> single pass
607
+ candidates.extend(_propose_disjoint_union_all_group_by_collapse(ast, dialect))
608
+
609
+ # Deduplicate candidate SQL strings while preserving order
610
+ seen: set[str] = set()
611
+ deduped: list[tuple[str, str]] = []
612
+ for rule, rew_sql in candidates:
613
+ if rew_sql not in seen:
614
+ seen.add(rew_sql)
615
+ deduped.append((rule, rew_sql))
616
+ return deduped
617
+
618
+
619
+ def verify_rewrites(
620
+ sql: str,
621
+ schema: Schema,
622
+ *,
623
+ dialect: str = "duckdb",
624
+ target: WarehouseTarget | str = WarehouseTarget.ALL,
625
+ bound: int = 3,
626
+ timeout_ms: int = 10_000,
627
+ confirm_in_duckdb: bool = True,
628
+ con: duckdb.DuckDBPyConnection | None = None,
629
+ ) -> list[RewriteCandidate]:
630
+ """Generate, formally verify, target-gate, and optionally cost-measure every candidate rewrite."""
631
+ results: list[RewriteCandidate] = []
632
+ orig_cost: CostMeasurement | None = None
633
+ if con is not None:
634
+ orig_cost = measure_duckdb_query(con, sql, dialect=dialect)
635
+
636
+ for rule, rewritten in propose_rewrites(sql, dialect=dialect):
637
+ ver = prove_equivalence(
638
+ sql,
639
+ rewritten,
640
+ schema,
641
+ dialect=dialect,
642
+ bound=bound,
643
+ timeout_ms=timeout_ms,
644
+ confirm_in_duckdb=confirm_in_duckdb,
645
+ )
646
+ rew_cost: CostMeasurement | None = None
647
+ if con is not None and ver.status in (ProofStatus.ALGEBRAICALLY_PROVEN, ProofStatus.BOUNDED_VERIFIED):
648
+ rew_cost = measure_duckdb_query(con, rewritten, dialect=dialect)
649
+ results.append(
650
+ RewriteCandidate(
651
+ rule=rule,
652
+ rewritten_sql=rewritten,
653
+ verification=ver,
654
+ orig_cost=orig_cost,
655
+ rew_cost=rew_cost,
656
+ target_advice=evaluate_rule_for_target(rule, target),
657
+ )
658
+ )
659
+ return results
660
+
661
+
662
+ def _build_local_cte_schema(
663
+ cte_node: exp.CTE,
664
+ prior_ctes: list[exp.CTE],
665
+ base_schema: Schema,
666
+ ) -> Schema:
667
+ """Build a sound conservative local Schema for verifying a single CTE in isolation.
668
+
669
+ Earlier CTEs are modeled as unconstrained relations (all columns nullable, no unique keys),
670
+ EXCEPT single-table non-joining CTEs projecting unmodified NOT NULL/UNIQUE columns directly
671
+ from a base table in `base_schema` (row-preserving projection/filtering/windowing).
672
+ """
673
+ from sqlprove.schema import ColumnSpec, TableSpec
674
+
675
+ tables = dict(base_schema.tables)
676
+ prior_map = {c.alias.lower(): c for c in prior_ctes if c.alias}
677
+
678
+ # Resolve single-table non-fanout CTE inheritance in definition order
679
+ for prev in prior_ctes:
680
+ pname = prev.alias.lower()
681
+ body = prev.this
682
+ inferred_cols: dict[str, ColumnSpec] = {}
683
+ inherited_uks: list[tuple[str, ...]] = []
684
+ if (
685
+ isinstance(body, exp.Select)
686
+ and not (body.args.get("joins") or [])
687
+ and body.args.get("group") is None
688
+ and not list(body.find_all(exp.Unnest))
689
+ ):
690
+ fc = body.args.get("from_")
691
+ if fc is not None and isinstance(fc.this, exp.Table):
692
+ src_name = fc.this.name.lower()
693
+ src_spec = tables.get(src_name) or next((v for k, v in tables.items() if k.lower() == src_name), None)
694
+ if src_spec is not None:
695
+ # Map directly projected unmodified columns
696
+ direct_map: dict[str, str] = {} # orig_col_l -> out_col_name
697
+ has_star = any(isinstance(e, exp.Star) or (isinstance(e, exp.Column) and isinstance(e.this, exp.Star)) for e in body.expressions)
698
+ if has_star:
699
+ for c in src_spec.columns:
700
+ inferred_cols[c.name.lower()] = c
701
+ direct_map[c.name.lower()] = c.name
702
+ for e in body.expressions:
703
+ if isinstance(e, exp.Star) or (isinstance(e, exp.Column) and isinstance(e.this, exp.Star)):
704
+ continue
705
+ target = e.this if isinstance(e, exp.Alias) else e
706
+ out_name = e.alias if isinstance(e, exp.Alias) else (target.name if isinstance(target, exp.Column) else None)
707
+ if not out_name:
708
+ continue
709
+ if isinstance(target, exp.Column) and src_spec.has_column(target.name):
710
+ sc = src_spec.get_column(target.name)
711
+ inferred_cols[out_name.lower()] = ColumnSpec(out_name, sc.dtype, src_spec.is_nullable(sc.name))
712
+ direct_map[sc.name.lower()] = out_name
713
+ else:
714
+ inferred_cols[out_name.lower()] = ColumnSpec(out_name, "INT", True)
715
+ for uk in src_spec.all_unique_constraints():
716
+ if uk and all(c.lower() in direct_map for c in uk):
717
+ inherited_uks.append(tuple(direct_map[c.lower()] for c in uk))
718
+
719
+ # Ensure any column referenced on `pname` inside `cte_node` exists as nullable
720
+ for col in cte_node.this.find_all(exp.Column):
721
+ if col.name and col.name.lower() not in inferred_cols:
722
+ inferred_cols[col.name.lower()] = ColumnSpec(col.name, "INT", True)
723
+
724
+ if inferred_cols:
725
+ tables[pname] = TableSpec(
726
+ name=pname,
727
+ columns=tuple(inferred_cols.values()),
728
+ unique_keys=tuple(inherited_uks),
729
+ )
730
+ return Schema(tables=tables)
731
+
732
+
733
+ def verify_rewrites_with_ctes(
734
+ sql: str,
735
+ schema: Schema,
736
+ *,
737
+ dialect: str = "duckdb",
738
+ target: WarehouseTarget | str = WarehouseTarget.ALL,
739
+ bound: int = 2,
740
+ timeout_ms: int = 5_000,
741
+ confirm_in_duckdb: bool = True,
742
+ ) -> list[RewriteCandidate]:
743
+ """Verify both top-level rewrites and sound CTE-level rewrites (by relational bag congruence)."""
744
+ results = verify_rewrites(
745
+ sql,
746
+ schema,
747
+ dialect=dialect,
748
+ target=target,
749
+ bound=bound,
750
+ timeout_ms=timeout_ms,
751
+ confirm_in_duckdb=confirm_in_duckdb,
752
+ )
753
+ ast = sqlglot.parse_one(sql, read=dialect)
754
+ with_clause = ast.args.get("with_") if isinstance(ast, (exp.Select, exp.Union)) else None
755
+ if not with_clause:
756
+ return results
757
+
758
+ ctes = list(with_clause.expressions)
759
+ for idx, cte in enumerate(ctes):
760
+ cte_sql = cte.this.sql(dialect=dialect)
761
+ cte_cands = propose_rewrites(cte_sql, dialect=dialect)
762
+ if not cte_cands:
763
+ continue
764
+ local_schema = _build_local_cte_schema(cte, ctes[:idx], schema)
765
+ for rule, rew_cte_sql in cte_cands:
766
+ ver = prove_equivalence(
767
+ cte_sql,
768
+ rew_cte_sql,
769
+ local_schema,
770
+ dialect=dialect,
771
+ bound=bound,
772
+ timeout_ms=timeout_ms,
773
+ confirm_in_duckdb=confirm_in_duckdb,
774
+ )
775
+ spliced = ast.copy()
776
+ spliced.args["with_"].expressions[idx].set("this", sqlglot.parse_one(rew_cte_sql, read=dialect))
777
+ full_rule = f"cte[{cte.alias}]:{rule}"
778
+ results.append(
779
+ RewriteCandidate(
780
+ rule=full_rule,
781
+ rewritten_sql=spliced.sql(dialect=dialect),
782
+ verification=ver,
783
+ target_advice=evaluate_rule_for_target(full_rule, target),
784
+ )
785
+ )
786
+ return results
787
+
788
+
789
+ def only_verified(candidates: list[RewriteCandidate]) -> list[RewriteCandidate]:
790
+ return [
791
+ c
792
+ for c in candidates
793
+ if c.verification.status in (ProofStatus.ALGEBRAICALLY_PROVEN, ProofStatus.BOUNDED_VERIFIED)
794
+ ]
795
+
796
+
797
+ def only_recommended(candidates: list[RewriteCandidate]) -> list[RewriteCandidate]:
798
+ """Keep only formally verified rewrites whose target warehouse advice is RECOMMENDED (never BLOCKED/NEUTRAL)."""
799
+ return [
800
+ c
801
+ for c in only_verified(candidates)
802
+ if c.target_advice is None or c.target_advice.decision == TargetDecision.RECOMMENDED
803
+ ]
804
+
805
+
806
+ def only_verified_and_cheaper(candidates: list[RewriteCandidate]) -> list[RewriteCandidate]:
807
+ """Keep only formally verified rewrites that measurably reduce DuckDB time, bytes read, or intermediate bytes."""
808
+ kept: list[RewriteCandidate] = []
809
+ for c in only_verified(candidates):
810
+ if c.orig_cost is None or c.rew_cost is None:
811
+ kept.append(c)
812
+ continue
813
+ faster = c.rew_cost.elapsed_ms < c.orig_cost.elapsed_ms
814
+ fewer_bytes = c.orig_cost.bytes_read > 0 and c.rew_cost.bytes_read < c.orig_cost.bytes_read
815
+ fewer_rows = c.orig_cost.rows_scanned > 0 and c.rew_cost.rows_scanned < c.orig_cost.rows_scanned
816
+ smaller_inter = c.orig_cost.intermediate_bytes > 0 and c.rew_cost.intermediate_bytes < c.orig_cost.intermediate_bytes
817
+ if faster or fewer_bytes or fewer_rows or smaller_inter:
818
+ kept.append(c)
819
+ return kept