sqlassert 0.3.1__py3-none-any.whl → 0.3.3__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.
- sqlassert/__main__.py +2 -131
- sqlassert/check.py +10 -3
- sqlassert/diagnostics.py +19 -6
- sqlassert/dialects.py +69 -22
- sqlassert/discovery/duckdb.py +12 -16
- sqlassert/discovery/fetcher.py +45 -29
- sqlassert/discovery/information_schema.py +4 -3
- sqlassert/discovery/postgres.py +6 -7
- sqlassert/edits.py +240 -0
- sqlassert/hazards.py +574 -0
- sqlassert/ir/__init__.py +3 -1
- sqlassert/ir/convert.py +1315 -183
- sqlassert/ir/model.py +128 -25
- sqlassert/main.py +3 -9
- sqlassert/python_engine.py +63 -6
- sqlassert/reporting.py +3 -0
- sqlassert/rewrites.py +1541 -0
- sqlassert/rules/domain.py +117 -21
- sqlassert/rules/equality.py +238 -29
- sqlassert/rules/exactly_one.py +40 -1
- sqlassert/rules/foreign_key.py +7 -4
- sqlassert/rules/join_cardinality.py +33 -11
- sqlassert/rules/nullability.py +239 -30
- sqlassert/rules/uniqueness.py +355 -52
- sqlassert/sql_parse.py +196 -89
- sqlassert/suggest.py +127 -48
- {sqlassert-0.3.1.dist-info → sqlassert-0.3.3.dist-info}/METADATA +121 -39
- sqlassert-0.3.3.dist-info/RECORD +46 -0
- sqlassert-0.3.3.dist-info/entry_points.txt +2 -0
- sqlassert-0.3.3.dist-info/top_level.txt +2 -0
- sqlassert_cli.py +130 -0
- sqlassert/improvements.py +0 -528
- sqlassert/smells.py +0 -306
- sqlassert-0.3.1.dist-info/RECORD +0 -44
- sqlassert-0.3.1.dist-info/entry_points.txt +0 -2
- sqlassert-0.3.1.dist-info/top_level.txt +0 -1
- {sqlassert-0.3.1.dist-info → sqlassert-0.3.3.dist-info}/WHEEL +0 -0
- {sqlassert-0.3.1.dist-info → sqlassert-0.3.3.dist-info}/licenses/LICENSE +0 -0
sqlassert/rewrites.py
ADDED
|
@@ -0,0 +1,1541 @@
|
|
|
1
|
+
"""Rewrite suggestions: changes to the SQL justified by a proof.
|
|
2
|
+
|
|
3
|
+
Each Rewrite names a change that leaves the program's result unchanged,
|
|
4
|
+
as a multiset, and the evidence that it does:
|
|
5
|
+
|
|
6
|
+
- An outer join that never keeps a padded row is an inner join: it matches
|
|
7
|
+
exactly one row, or a null-rejecting conjunct later in the same FROM and
|
|
8
|
+
WHERE removes every row it pads (padding promotion), directly or through a
|
|
9
|
+
later LEFT or FULL JOIN that then pads the same rows.
|
|
10
|
+
- A join none of whose columns is used outside its own ON is redundant when
|
|
11
|
+
it keeps every left row once (a unique LEFT JOIN, an Exactly One JOIN), and
|
|
12
|
+
only filters when it is a unique inner join (a `WHERE EXISTS`).
|
|
13
|
+
- A `DISTINCT` over rows that already differ, NULL equal to NULL, on the
|
|
14
|
+
selected columns; a `GROUP BY` column the remaining grouping columns
|
|
15
|
+
strictly determine.
|
|
16
|
+
- A CTE nothing references.
|
|
17
|
+
- A `WHERE EXISTS` or `IN` subquery (or a SEMI JOIN) every row passes: its
|
|
18
|
+
semi join is proved Exactly One, so it keeps every row once.
|
|
19
|
+
- A `GROUP BY` whose grouping columns are a key of its input, NULL equal to
|
|
20
|
+
NULL: each group is one row, so it is a projection. A Rewrite with
|
|
21
|
+
Caveat when an aggregate's one-row value has another type or precision
|
|
22
|
+
(`sum(x)` is x's type, not sum's; `sum(x) + 1` may overflow as `x + 1`).
|
|
23
|
+
- An `EXCEPT` whose left input, or an `INTERSECT` either of whose inputs,
|
|
24
|
+
has no two rows alike: `EXCEPT ALL` and `INTERSECT ALL` give the same rows
|
|
25
|
+
without removing duplicates, where the dialect has them.
|
|
26
|
+
|
|
27
|
+
Proofs come from the rules' internals (null sources, strict closure) as well
|
|
28
|
+
as `Arena.prove`, since none of these facts is a Property. Whether a column
|
|
29
|
+
is used is read from the syntax: the IR keeps neither ORDER BY nor the
|
|
30
|
+
columns inside opaque expressions. Anything the checks cannot see whole --
|
|
31
|
+
a padded row leaving its own Select Expression, a join whose right side's
|
|
32
|
+
columns are unknown -- is left alone.
|
|
33
|
+
|
|
34
|
+
Each Rewrite carries the exact edits that make it (`edits.py`), placed from
|
|
35
|
+
the SQL's tokens; one whose syntax they cannot place is not offered.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
from __future__ import annotations
|
|
39
|
+
|
|
40
|
+
from collections.abc import Callable, Iterator
|
|
41
|
+
from dataclasses import dataclass, replace
|
|
42
|
+
from enum import Enum
|
|
43
|
+
from typing import Literal, assert_never
|
|
44
|
+
|
|
45
|
+
import sqlglot
|
|
46
|
+
from sqlglot import Expr, exp
|
|
47
|
+
from sqlglot.tokens import TokenType
|
|
48
|
+
|
|
49
|
+
from sqlassert.diagnostics import quoted, quoted_all
|
|
50
|
+
from sqlassert.edits import Edit, Source, apply_edits, unified_diff
|
|
51
|
+
from sqlassert import ir
|
|
52
|
+
from sqlassert.dialects import semantics
|
|
53
|
+
from sqlassert.properties import ExactlyOneJoin, ManyToOneJoin, NonNullColumn, NonNullColumns, NonNullUniqueSet
|
|
54
|
+
from sqlassert.rules.domain import _domain
|
|
55
|
+
from sqlassert.rules.equality import _comparison_type, _identity_comparison, _pins, _same_set_types, _same_type
|
|
56
|
+
from sqlassert.rules.exactly_one import _cross_equalities
|
|
57
|
+
from sqlassert.provenance import AttachmentSite
|
|
58
|
+
from sqlassert.python_engine import Arena, Result
|
|
59
|
+
from sqlassert.rules.column_set import RowIdentity
|
|
60
|
+
from sqlassert.rules.nullability import (
|
|
61
|
+
Padding, _null_rejected, _null_sources, _on_rejected, _on_rejected_paddings, _rejected_paddings,
|
|
62
|
+
)
|
|
63
|
+
from sqlassert.rules.uniqueness import _closure, _reaches_row_identity
|
|
64
|
+
from sqlassert.sql_parse import ParsedProgram, grouping, marker_position, span, written_sql
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class SuggestType(Enum):
|
|
68
|
+
"""What a suggestion is, listed in this order: a rewrite of the SQL that
|
|
69
|
+
keeps its rows and every column's type and adds no error; a rewrite with
|
|
70
|
+
caveat, which keeps its rows but may change a column's type or precision,
|
|
71
|
+
or overflow, as its message says; a marker to paste; a hazard in its
|
|
72
|
+
result."""
|
|
73
|
+
|
|
74
|
+
REWRITE = "rewrite"
|
|
75
|
+
REWRITE_WITH_CAVEAT = "rewrite with caveat"
|
|
76
|
+
MARKER = "marker"
|
|
77
|
+
HAZARD = "hazard"
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class RewriteKind(Enum):
|
|
81
|
+
INNER_JOIN = "INNER JOIN"
|
|
82
|
+
REDUNDANT_JOIN = "Redundant Join"
|
|
83
|
+
FILTER_JOIN = "Filter-Only Join"
|
|
84
|
+
REDUNDANT_DISTINCT = "Redundant DISTINCT"
|
|
85
|
+
REDUNDANT_GROUPING = "Redundant GROUP BY"
|
|
86
|
+
GROUPING_PROJECTION = "GROUP BY of one row per group"
|
|
87
|
+
REDUNDANT_SORT_KEY = "Redundant ORDER BY key"
|
|
88
|
+
REDUNDANT_FILTER = "Redundant EXISTS"
|
|
89
|
+
SET_OPERATION_ALL = "EXCEPT ALL or INTERSECT ALL"
|
|
90
|
+
ONE_ROW = "LIMIT or ORDER BY on one row"
|
|
91
|
+
SELF_JOIN = "Self-join on a key"
|
|
92
|
+
IMPLIED_CONDITION = "Implied condition"
|
|
93
|
+
UNUSED_CTE = "Unused CTE"
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
@dataclass(frozen=True)
|
|
97
|
+
class Rewrite:
|
|
98
|
+
"""A result-preserving rewrite of the SQL at one site, with its proof.
|
|
99
|
+
`edits` make it, on the SQL it was found in (one is offered only with
|
|
100
|
+
them: where its syntax cannot be placed from the tokens, there is none);
|
|
101
|
+
`message` says why, and what to do in a word. Its `suggest_type` is REWRITE_WITH_CAVEAT when a
|
|
102
|
+
column's type or precision may change, which the message names;
|
|
103
|
+
sqlassert has no result-type model per dialect, so such a change is
|
|
104
|
+
caveated."""
|
|
105
|
+
|
|
106
|
+
site: AttachmentSite
|
|
107
|
+
kind: RewriteKind
|
|
108
|
+
message: str
|
|
109
|
+
edits: tuple[Edit, ...]
|
|
110
|
+
evidence: Result[bool]
|
|
111
|
+
suggest_type: SuggestType = SuggestType.REWRITE
|
|
112
|
+
|
|
113
|
+
def __post_init__(self) -> None:
|
|
114
|
+
if not self.edits:
|
|
115
|
+
raise ValueError(f"a {self.kind.value} Rewrite without edits")
|
|
116
|
+
|
|
117
|
+
def rewritten(self, sql: str) -> str:
|
|
118
|
+
"""`sql`, the SQL this Rewrite was found in, rewritten."""
|
|
119
|
+
return apply_edits(sql, self.edits)
|
|
120
|
+
|
|
121
|
+
def diff(self, sql: str, *, name: str = "original", context: int = 2) -> str:
|
|
122
|
+
"""The unified diff from `sql`, the SQL this Rewrite was found in, to
|
|
123
|
+
its rewrite; `name` labels it."""
|
|
124
|
+
return unified_diff(sql, self.edits, name=name, context=context)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def rewrites(
|
|
128
|
+
ast: ParsedProgram, program: ir.Program, arena: Arena, dialect: str,
|
|
129
|
+
wanted: Callable[[AttachmentSite], bool] = lambda site: True,
|
|
130
|
+
) -> list[Rewrite]:
|
|
131
|
+
"""Every Rewrite for `program` at a site `wanted` accepts, in source
|
|
132
|
+
order. `arena` must be active."""
|
|
133
|
+
syntax = _syntax_at_sites(ast)
|
|
134
|
+
source = Source(ast.sql, ast.tokens)
|
|
135
|
+
parents: dict[ir.RelationExpr, list[ir.RelationExpr]] = {}
|
|
136
|
+
for relation in program.relations():
|
|
137
|
+
for child in ir.children(relation):
|
|
138
|
+
if isinstance(child, ir.RelationExpr):
|
|
139
|
+
parents.setdefault(child, []).append(relation)
|
|
140
|
+
found: list[Rewrite] = []
|
|
141
|
+
sort_keys = dict(program.sort_keys)
|
|
142
|
+
for site, relation in program.attachment_sites:
|
|
143
|
+
if isinstance(relation, ir.SimpleCase) or not wanted(site):
|
|
144
|
+
continue # A CASE has nothing to rewrite yet.
|
|
145
|
+
if relation not in parents and relation is not program.root:
|
|
146
|
+
# Unreachable: lowered inside a Select that is opaque as a whole.
|
|
147
|
+
# (Every reachable relation but the root is some relation's input.)
|
|
148
|
+
continue
|
|
149
|
+
node = syntax.get((site.offset, site.trailing))
|
|
150
|
+
limit = relation if isinstance(relation, ir.Limit) else None
|
|
151
|
+
if isinstance(relation, ir.Limit):
|
|
152
|
+
relation = relation.input
|
|
153
|
+
if site.trailing and isinstance(node, exp.Select):
|
|
154
|
+
found.extend(_redundant_subquery_filters(arena, site, relation, node, source, dialect))
|
|
155
|
+
found.extend(_implied_where(arena, site, relation, program, node, source, dialect))
|
|
156
|
+
if site.trailing and isinstance(node, exp.Select):
|
|
157
|
+
one_row = _one_row_tail(site, relation, limit, node, source)
|
|
158
|
+
found.extend(one_row or _redundant_sort_keys(site, relation, node, sort_keys.get(site), dialect, source))
|
|
159
|
+
match relation:
|
|
160
|
+
case ir.Join() if isinstance(node, exp.Join):
|
|
161
|
+
same = _self_join(arena, site, relation, node, program, dialect, source)
|
|
162
|
+
removed = None if same else _redundant_join(arena, site, relation, node, dialect, source)
|
|
163
|
+
inner = None if removed or same else _inner_join(arena, site, relation, parents, node, source)
|
|
164
|
+
found.extend(item for item in (removed, same, inner) if item is not None)
|
|
165
|
+
written, _ = _on_conjuncts(node, source)
|
|
166
|
+
found.extend(_implied_conjuncts(arena, site, relation, program, "ON", written, None, source, dialect))
|
|
167
|
+
case ir.Distinct() if isinstance(node, exp.Select):
|
|
168
|
+
found.extend(_redundant_distinct(site, relation, node, source))
|
|
169
|
+
case ir.Aggregate() | ir.Project() | ir.Filter() if isinstance(node, exp.Select) and (aggregate := _grouped(relation, node)) is not None:
|
|
170
|
+
projection = _grouping_is_projection(site, aggregate, node, dialect, source)
|
|
171
|
+
found.extend([projection] if projection else _redundant_grouping(site, relation, aggregate, node, dialect, source))
|
|
172
|
+
case _:
|
|
173
|
+
pass # Other Select Expressions have nothing to rewrite yet.
|
|
174
|
+
found.extend(item for item in _unused_ctes(ast, source) if wanted(item.site))
|
|
175
|
+
if semantics(dialect).set_operations_all:
|
|
176
|
+
found.extend(
|
|
177
|
+
item for site, operation in program.set_operations
|
|
178
|
+
if wanted(site) and (item := _set_operation_all(site, operation, source)) is not None
|
|
179
|
+
)
|
|
180
|
+
return sorted(found, key=lambda item: item.site.offset)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _grouped(relation: ir.RelationExpr, node: exp.Select) -> ir.Aggregate | None:
|
|
184
|
+
"""The Aggregate of a grouped Select's relation: under the Project that
|
|
185
|
+
drops its hidden outputs and computes the items over aggregates
|
|
186
|
+
(`_lower_aggregate`), and the Filter that is its HAVING, all under the
|
|
187
|
+
Filter of a DISTINCT ON, which keeps one group per key."""
|
|
188
|
+
distinct = node.args.get("distinct")
|
|
189
|
+
if isinstance(relation, ir.Filter) and distinct is not None and distinct.args.get("on") is not None:
|
|
190
|
+
relation = relation.input
|
|
191
|
+
if isinstance(relation, ir.Project):
|
|
192
|
+
relation = relation.input
|
|
193
|
+
if isinstance(relation, ir.Filter) and node.args.get("having") is not None and node.args.get("qualify") is None:
|
|
194
|
+
relation = relation.input
|
|
195
|
+
return relation if isinstance(relation, ir.Aggregate) else None
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _redundant_subquery_filters(
|
|
199
|
+
arena: Arena, site: AttachmentSite, relation: ir.RelationExpr, node: exp.Select, source: Source, dialect: str,
|
|
200
|
+
) -> list[Rewrite]:
|
|
201
|
+
"""The semi joins of this Select (its WHERE subqueries, issue 23, or an
|
|
202
|
+
explicit SEMI JOIN) that match every row exactly once, so filter nothing.
|
|
203
|
+
The edit deletes the WHERE conjunct (`_deleted_conjunct`) or the join."""
|
|
204
|
+
found: list[Rewrite] = []
|
|
205
|
+
while True:
|
|
206
|
+
match relation:
|
|
207
|
+
case ir.Project(input=input_) | ir.Aggregate(input=input_) | ir.Distinct(input=input_) | ir.QualifyByPartition(input=input_) | ir.Filter(input=input_):
|
|
208
|
+
relation = input_
|
|
209
|
+
case ir.Join(kind="semi" | "anti", left=input_):
|
|
210
|
+
if relation.kind == "semi":
|
|
211
|
+
proof = arena.prove(ExactlyOneJoin(join=relation))
|
|
212
|
+
edits = _semi_join_edits(relation, node, source, dialect)
|
|
213
|
+
if proof.value and edits:
|
|
214
|
+
message = f"every row matches exactly one row, so {relation.origin.detail} filters nothing: delete it"
|
|
215
|
+
found.append(Rewrite(site, RewriteKind.REDUNDANT_FILTER, message, edits, proof))
|
|
216
|
+
relation = input_
|
|
217
|
+
case _:
|
|
218
|
+
return found
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _semi_join_edits(join: ir.Join, node: exp.Select, source: Source, dialect: str) -> tuple[Edit, ...]:
|
|
222
|
+
"""Deleting the WHERE subquery or SEMI JOIN of `node` that `join` lowers."""
|
|
223
|
+
where = node.args.get("where")
|
|
224
|
+
conjuncts = _where_conjuncts(where, source) if where is not None else None
|
|
225
|
+
for index, (conjunct, _, _) in enumerate(conjuncts or ()):
|
|
226
|
+
if written_sql(conjunct, dialect) == join.origin.detail:
|
|
227
|
+
assert conjuncts is not None and where is not None
|
|
228
|
+
return _deleted_conjunct(source, conjuncts, index, source.tokens_of(span(where)))
|
|
229
|
+
for other in node.args.get("joins") or ():
|
|
230
|
+
tokens = source.tokens_of(span(other))
|
|
231
|
+
if tokens is not None and written_sql(other, dialect) == join.origin.detail:
|
|
232
|
+
return source.deletions([tokens])
|
|
233
|
+
return ()
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
# Conjuncts of a WHERE or ON, as written ----------------------------------------------
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _where_conjuncts(where: exp.Where, source: Source) -> list[tuple[Expr, int, int]] | None:
|
|
240
|
+
clause = source.tokens_of(span(where))
|
|
241
|
+
return None if clause is None else _conjunct_tokens(where.this, clause[0] + 1, clause[1], source)
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _on_conjuncts(node: exp.Join, source: Source) -> tuple[list[tuple[Expr, int, int]] | None, tuple[int, int] | None]:
|
|
245
|
+
"""The ON conjuncts of a join, and the tokens of its condition."""
|
|
246
|
+
tokens, on = source.tokens_of(span(node)), node.args.get("on")
|
|
247
|
+
keyword = next(iter(source.top_level(tokens[0], tokens[1], TokenType.ON)), None) if tokens is not None else None
|
|
248
|
+
if on is None or keyword is None or tokens is None:
|
|
249
|
+
return None, None
|
|
250
|
+
return _conjunct_tokens(on, keyword + 1, tokens[1], source), (keyword + 1, tokens[1])
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _conjunct_tokens(condition: Expr, first: int, last: int, source: Source) -> list[tuple[Expr, int, int]] | None:
|
|
254
|
+
"""Each conjunct of `condition`, written from token `first` to `last`,
|
|
255
|
+
as the IR reads them (`ir.convert._conjuncts`: top-level ANDs, parentheses
|
|
256
|
+
removed), with its first and last token, parentheses around it included.
|
|
257
|
+
None when the tokens do not line up with the AST."""
|
|
258
|
+
found: list[tuple[Expr, int, int]] = []
|
|
259
|
+
|
|
260
|
+
def walk(node: Expr, first: int, last: int) -> bool:
|
|
261
|
+
inner, start, end = node, first, last
|
|
262
|
+
while isinstance(inner, exp.Paren):
|
|
263
|
+
if not source.is_(start, TokenType.L_PAREN) or source.closing(start) != end:
|
|
264
|
+
return False
|
|
265
|
+
inner, start, end = inner.this, start + 1, end - 1
|
|
266
|
+
if isinstance(inner, exp.And):
|
|
267
|
+
ands = source.top_level(start, end, TokenType.AND)
|
|
268
|
+
# AND is left-associative: the last one at this level splits it.
|
|
269
|
+
return bool(ands) and walk(inner.this, start, ands[-1] - 1) and walk(inner.expression, ands[-1] + 1, end)
|
|
270
|
+
found.append((inner, first, last))
|
|
271
|
+
return first <= last
|
|
272
|
+
|
|
273
|
+
return found if walk(condition, first, last) else None
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _deleted_conjunct(
|
|
277
|
+
source: Source, conjuncts: list[tuple[Expr, int, int]], index: int, clause: tuple[int, int] | None,
|
|
278
|
+
) -> tuple[Edit, ...]:
|
|
279
|
+
"""Conjunct `index` deleted with the AND joining it to the others; the
|
|
280
|
+
whole `clause` (a WHERE) when it is the only one, or, with no clause (an
|
|
281
|
+
ON), the condition written as TRUE."""
|
|
282
|
+
_, first, last = conjuncts[index]
|
|
283
|
+
if len(conjuncts) == 1:
|
|
284
|
+
return source.deletions([clause]) if clause is not None else (source.replace(first, last, "TRUE"),)
|
|
285
|
+
if index == 0:
|
|
286
|
+
following = next(token for token in range(last + 1, conjuncts[1][1]) if source.is_(token, TokenType.AND))
|
|
287
|
+
return source.deletions([(first, following)])
|
|
288
|
+
preceding = next(token for token in range(first - 1, conjuncts[index - 1][2], -1) if source.is_(token, TokenType.AND))
|
|
289
|
+
return source.deletions([(preceding, last)])
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _syntax_at_sites(ast: ParsedProgram) -> dict[tuple[int, bool], exp.Join | exp.Select]:
|
|
293
|
+
"""Each Join and Select by its Attachment Site's (offset, trailing)."""
|
|
294
|
+
index: dict[tuple[int, bool], exp.Join | exp.Select] = {}
|
|
295
|
+
for node in _nodes(ast, exp.Join, exp.Select):
|
|
296
|
+
position = marker_position(node)
|
|
297
|
+
if position is not None:
|
|
298
|
+
index[(position[0], isinstance(node, exp.Select))] = node
|
|
299
|
+
return index
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _join_start(node: exp.Join, source: Source) -> int | None:
|
|
303
|
+
"""The join's first token."""
|
|
304
|
+
position = marker_position(node)
|
|
305
|
+
return None if position is None else source.at(position[0])
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _nodes(ast: ParsedProgram, *types: type[Expr]) -> Iterator:
|
|
309
|
+
for statement in (*ast.create_statements, ast.root_select):
|
|
310
|
+
if statement is not None:
|
|
311
|
+
yield from statement.find_all(*types)
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
# Outer joins that cannot pad ------------------------------------------------------
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def _inner_join(
|
|
318
|
+
arena: Arena, site: AttachmentSite, join: ir.Join, parents: dict[ir.RelationExpr, list[ir.RelationExpr]],
|
|
319
|
+
node: exp.Join, source: Source,
|
|
320
|
+
) -> Rewrite | None:
|
|
321
|
+
"""An outer join none of whose padded rows reaches the result. Its edit
|
|
322
|
+
deletes the LEFT or RIGHT keyword, and OUTER.
|
|
323
|
+
|
|
324
|
+
Only the joins above it in the same FROM and its own WHERE are searched:
|
|
325
|
+
within one Select Expression nothing between them looks at a row as a
|
|
326
|
+
whole, while past it a LIMIT, window, or aggregate may.
|
|
327
|
+
"""
|
|
328
|
+
if join.kind not in {"left", "right"}:
|
|
329
|
+
return None
|
|
330
|
+
side = _join_start(node, source)
|
|
331
|
+
if not source.is_(side, TokenType.LEFT, TokenType.RIGHT):
|
|
332
|
+
return None
|
|
333
|
+
assert side is not None
|
|
334
|
+
last = side + 1 if source.is_(side + 1, TokenType.OUTER) else side
|
|
335
|
+
if not source.is_(last + 1, TokenType.JOIN):
|
|
336
|
+
return None
|
|
337
|
+
edits = (source.delete(side, last),)
|
|
338
|
+
keyword = f"{join.kind.upper()} JOIN"
|
|
339
|
+
if join.kind == "left":
|
|
340
|
+
exactly_one = arena.prove(ExactlyOneJoin(join=join))
|
|
341
|
+
if exactly_one.value:
|
|
342
|
+
message = f"every left row matches exactly one right row, so the {keyword} pads nothing: write JOIN"
|
|
343
|
+
return Rewrite(site, RewriteKind.INNER_JOIN, message, edits, exactly_one)
|
|
344
|
+
# Joins that pad every row this one pads, each with why (issue 33): a
|
|
345
|
+
# later LEFT or FULL JOIN whose ON rejects NULL in a column one of them
|
|
346
|
+
# pads finds no match for those rows, so it pads them too.
|
|
347
|
+
# Keyed by join and the side it pads: a FULL JOIN pads each side on different rows.
|
|
348
|
+
chained: dict[tuple[ir.Join, bool], list[Result[bool]]] = {(join, join.kind == "right"): []}
|
|
349
|
+
|
|
350
|
+
def padded_by(column: ir.OutputColumn) -> tuple[ir.Join, bool] | None:
|
|
351
|
+
return next((
|
|
352
|
+
(source.join, source.left) for source in _null_sources(column).value
|
|
353
|
+
if isinstance(source, Padding) and (source.join, source.left) in chained
|
|
354
|
+
), None)
|
|
355
|
+
|
|
356
|
+
relation: ir.RelationExpr = join
|
|
357
|
+
while len(parents.get(relation, ())) == 1:
|
|
358
|
+
parent, = parents[relation]
|
|
359
|
+
match parent:
|
|
360
|
+
case ir.Join(kind="anti"):
|
|
361
|
+
rejected, paddings, clause = {}, {}, ""
|
|
362
|
+
case ir.Join(kind=kind):
|
|
363
|
+
# A semi join (a WHERE EXISTS or IN) keeps only rows its ON holds on.
|
|
364
|
+
described = "WHERE EXISTS or IN subquery" if kind == "semi" else f"later {kind.upper()} JOIN"
|
|
365
|
+
rejected, paddings, clause = _on_rejected(parent), _on_rejected_paddings(parent), f"the ON condition of a {described}"
|
|
366
|
+
case ir.Filter():
|
|
367
|
+
rejected, paddings, clause = _null_rejected(parent.conjuncts), _rejected_paddings(parent.conjuncts), "the WHERE clause"
|
|
368
|
+
case _:
|
|
369
|
+
return None
|
|
370
|
+
for column, conjunct in rejected.items():
|
|
371
|
+
via = padded_by(column)
|
|
372
|
+
if via is not None:
|
|
373
|
+
how = f"is padded by the {keyword}" if via[0] is join else f"is NULL on every row the {keyword} pads"
|
|
374
|
+
padded = Result(True, f"{quoted(column.name)} {how}", (join, column), chained[via])
|
|
375
|
+
evidence = Result(
|
|
376
|
+
True, f"{clause} rejects NULL in {quoted(column.name)}, so every row the {keyword} pads is removed",
|
|
377
|
+
(conjunct, column), [padded],
|
|
378
|
+
)
|
|
379
|
+
message = f"{clause} rejects NULL in {quoted(column.name)}, so no padded row survives: write JOIN"
|
|
380
|
+
return Rewrite(site, RewriteKind.INNER_JOIN, message, edits, evidence)
|
|
381
|
+
for padding, conjunct in paddings.items():
|
|
382
|
+
# Not TRUE on a row padded as a whole (`a.x > 0 OR a.y > 0`).
|
|
383
|
+
via = (padding.join, padding.left)
|
|
384
|
+
if via in chained:
|
|
385
|
+
how = f"The {keyword}'s padding" if padding.join is join else f"A later join's padding, which every row the {keyword} pads gets"
|
|
386
|
+
padded = Result(True, how, (join, padding.join), chained[via])
|
|
387
|
+
evidence = Result(
|
|
388
|
+
True, f"{clause} is never TRUE on a padded row, so every row the {keyword} pads is removed",
|
|
389
|
+
(conjunct, padding.join), [padded],
|
|
390
|
+
)
|
|
391
|
+
message = f"{clause} is never TRUE on a row the {keyword} pads, so no padded row survives: write JOIN"
|
|
392
|
+
return Rewrite(site, RewriteKind.INNER_JOIN, message, edits, evidence)
|
|
393
|
+
if isinstance(parent, ir.Join) and parent.kind in {"left", "full"}:
|
|
394
|
+
for column, conjunct in _null_rejected(parent.conjuncts).items():
|
|
395
|
+
via = padded_by(column)
|
|
396
|
+
# The left rows it cannot match keep a padded right side.
|
|
397
|
+
if via is not None and column in parent.left.output_columns and (parent, False) not in chained:
|
|
398
|
+
reason = f"its ON rejects NULL in {quoted(column.name)}, so the later {parent.kind.upper()} JOIN pads every row the {keyword} pads"
|
|
399
|
+
chained[(parent, False)] = [*chained[via], Result(True, reason, (conjunct, column))]
|
|
400
|
+
if isinstance(parent, ir.Filter):
|
|
401
|
+
return None
|
|
402
|
+
relation = parent
|
|
403
|
+
return None
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
# Redundant ORDER BY keys -----------------------------------------------------------
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def _redundant_sort_keys(
|
|
410
|
+
site: AttachmentSite, relation: ir.RelationExpr, select: exp.Select, keys: tuple[ir.OutputColumn, ...] | None, dialect: str,
|
|
411
|
+
source: Source,
|
|
412
|
+
) -> list[Rewrite]:
|
|
413
|
+
"""Each ORDER BY key the keys before it determine, NULL equal to NULL
|
|
414
|
+
(Paulley §3, reducing the sort list): rows tied on the earlier keys agree
|
|
415
|
+
on it, so it never breaks a tie. Only while the earlier keys compare by
|
|
416
|
+
identity: a collation or a float ties values its equality tells apart.
|
|
417
|
+
Silent when a key is an expression or a name that does not resolve to one
|
|
418
|
+
column, and for DISTINCT ON, whose ORDER BY picks the rows it keeps. Its
|
|
419
|
+
edit deletes the key and the comma before it."""
|
|
420
|
+
from sqlassert.hazards import _ties_identical
|
|
421
|
+
|
|
422
|
+
if not keys:
|
|
423
|
+
return []
|
|
424
|
+
items = select.args["order"].expressions
|
|
425
|
+
clause = source.tokens_of(span(select.args["order"]))
|
|
426
|
+
parts = source.split(clause[0] + 1, clause[1], TokenType.COMMA) if clause is not None else []
|
|
427
|
+
if len(parts) != len(items):
|
|
428
|
+
return []
|
|
429
|
+
scope = relation.input if isinstance(relation, ir.Project) else relation
|
|
430
|
+
found = []
|
|
431
|
+
for position in range(1, len(keys)):
|
|
432
|
+
if not all(_ties_identical(key) for key in keys[:position]):
|
|
433
|
+
break
|
|
434
|
+
closure = _closure(scope, frozenset(keys[:position]), frozenset())
|
|
435
|
+
key = keys[position]
|
|
436
|
+
if key not in closure.value.columns:
|
|
437
|
+
continue
|
|
438
|
+
written = [written_sql(item.this if isinstance(item, exp.Ordered) else item, dialect) for item in items]
|
|
439
|
+
message = f"({quoted_all(written[:position])}) determine {quoted(written[position])}, NULL equal to NULL, so it never breaks a tie: drop it from ORDER BY"
|
|
440
|
+
evidence = Result(True, "The earlier ORDER BY keys determine this one", (key,), [closure.members[key]])
|
|
441
|
+
found.append(Rewrite(site, RewriteKind.REDUNDANT_SORT_KEY, message, source.deletions([(parts[position][0] - 1, parts[position][1])]), evidence))
|
|
442
|
+
return found
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
# Redundant joins ------------------------------------------------------------------
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def _redundant_join(arena: Arena, site: AttachmentSite, join: ir.Join, node: exp.Join, dialect: str, source: Source) -> Rewrite | None:
|
|
449
|
+
"""A join that keeps every left row once, none of whose columns is used
|
|
450
|
+
outside its ON: its edit deletes it. One that only filters moves into a
|
|
451
|
+
WHERE EXISTS."""
|
|
452
|
+
if join.kind not in {"inner", "left"} or _right_side_used(join, node):
|
|
453
|
+
return None
|
|
454
|
+
tokens = source.tokens_of(span(node))
|
|
455
|
+
if tokens is None:
|
|
456
|
+
return None
|
|
457
|
+
right = written_sql(node.this, dialect)
|
|
458
|
+
unused = f"no column of {right} is used outside its ON"
|
|
459
|
+
if join.kind == "left":
|
|
460
|
+
unique = arena.prove(ManyToOneJoin(join=join))
|
|
461
|
+
if unique.value:
|
|
462
|
+
message = f"at most one match per row and {unused}: delete the join"
|
|
463
|
+
return Rewrite(site, RewriteKind.REDUNDANT_JOIN, message, source.deletions([tokens]), unique)
|
|
464
|
+
return None
|
|
465
|
+
exactly_one = arena.prove(ExactlyOneJoin(join=join))
|
|
466
|
+
if exactly_one.value:
|
|
467
|
+
message = f"exactly one match per row and {unused}: delete the join"
|
|
468
|
+
return Rewrite(site, RewriteKind.REDUNDANT_JOIN, message, source.deletions([tokens]), exactly_one)
|
|
469
|
+
unique = arena.prove(ManyToOneJoin(join=join))
|
|
470
|
+
if not unique.value or _right_or_full_join_follows(node):
|
|
471
|
+
# A filter moved to WHERE would act after a later RIGHT or FULL JOIN,
|
|
472
|
+
# which then no longer pads the rows this join used to drop first.
|
|
473
|
+
return None
|
|
474
|
+
edits = _filter_join_edits(node, source)
|
|
475
|
+
if edits is None:
|
|
476
|
+
return None
|
|
477
|
+
message = f"at most one match per row and {unused}, so it only filters: move it into a WHERE EXISTS"
|
|
478
|
+
return Rewrite(site, RewriteKind.FILTER_JOIN, message, edits, unique)
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def _filter_join_edits(node: exp.Join, source: Source) -> tuple[Edit, ...] | None:
|
|
482
|
+
"""The join deleted and `EXISTS (SELECT 1 FROM <its relation> WHERE <its
|
|
483
|
+
ON>)`, both as written, ANDed into its Select's WHERE (`_anded_into_where`)."""
|
|
484
|
+
select = node.parent
|
|
485
|
+
tokens = source.tokens_of(span(node))
|
|
486
|
+
if not isinstance(select, exp.Select) or tokens is None:
|
|
487
|
+
return None
|
|
488
|
+
keyword = next(iter(source.top_level(tokens[0], tokens[1], TokenType.JOIN)), None)
|
|
489
|
+
_, condition = _on_conjuncts(node, source)
|
|
490
|
+
if keyword is None or condition is None and node.args.get("on") is not None:
|
|
491
|
+
return None
|
|
492
|
+
relation = (keyword + 1, condition[0] - 2 if condition is not None else tokens[1])
|
|
493
|
+
where = f" WHERE {source.text(*condition)}" if condition is not None else ""
|
|
494
|
+
exists = f"EXISTS (SELECT 1 FROM {source.text(*relation)}{where})"
|
|
495
|
+
return _anded_into_where(select, source, exists, tokens, [relation] + ([condition] if condition is not None else []))
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
def _anded_into_where(
|
|
499
|
+
select: exp.Select, source: Source, condition: str, deleted: tuple[int, int], moved: list[tuple[int, int]],
|
|
500
|
+
) -> tuple[Edit, ...] | None:
|
|
501
|
+
"""`condition` ANDed to the end of `select`'s WHERE (the WHERE's own
|
|
502
|
+
condition parenthesized when it is an OR), or written as a new WHERE
|
|
503
|
+
after its FROM, and the `deleted` join deleted, but for the text it
|
|
504
|
+
`moved` into `condition`."""
|
|
505
|
+
where = select.args.get("where")
|
|
506
|
+
if where is not None:
|
|
507
|
+
added = _anded_to_where(where, source, condition)
|
|
508
|
+
return None if added is None else (source.delete(*deleted, moved), *added)
|
|
509
|
+
last = _from_end(select, source)
|
|
510
|
+
if last is None:
|
|
511
|
+
return None
|
|
512
|
+
if last == deleted[1]:
|
|
513
|
+
return (source.replace(*deleted, f"WHERE {condition}", moved),)
|
|
514
|
+
return (source.delete(*deleted, moved), source.insert_after(last, f" WHERE {condition}"))
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
def _anded_to_where(where: exp.Where, source: Source, condition: str) -> tuple[Edit, ...] | None:
|
|
518
|
+
"""`condition` ANDed to the end of `where`, whose own condition is
|
|
519
|
+
parenthesized when it is an OR."""
|
|
520
|
+
tokens = source.tokens_of(span(where))
|
|
521
|
+
if tokens is None:
|
|
522
|
+
return None
|
|
523
|
+
if isinstance(where.this, exp.Or | exp.Xor):
|
|
524
|
+
return (source.insert_before(tokens[0] + 1, "("), source.insert_after(tokens[1], f") AND {condition}"))
|
|
525
|
+
return (source.insert_after(tokens[1], f" AND {condition}"),)
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
def _from_end(select: exp.Select, source: Source) -> int | None:
|
|
529
|
+
"""The last token of `select`'s FROM clause, where a new WHERE goes: past
|
|
530
|
+
its joins (a `, LATERAL` or `JOIN LATERAL` among them), before the first
|
|
531
|
+
clause after them (GROUP BY,
|
|
532
|
+
HAVING, WINDOW, QUALIFY, ORDER BY, LIMIT, ...)."""
|
|
533
|
+
end = marker_position(select)
|
|
534
|
+
clauses = [
|
|
535
|
+
position[0] for key, value in select.args.items()
|
|
536
|
+
if key != "distinct" and isinstance(value, Expr) and (position := span(value)) is not None
|
|
537
|
+
]
|
|
538
|
+
# A WINDOW clause is a list, which records no span: its keyword is found.
|
|
539
|
+
if select.args.get("windows"):
|
|
540
|
+
position = span(select)
|
|
541
|
+
first = source.at(position[0]) if position is not None else None
|
|
542
|
+
last = source.before(end[0]) if end is not None else None
|
|
543
|
+
if first is None or last is None:
|
|
544
|
+
return None
|
|
545
|
+
clauses.extend(source.start(index) for index in source.top_level(first, last, TokenType.WINDOW))
|
|
546
|
+
boundary = min(clauses, default=end[0] if end is not None else None)
|
|
547
|
+
return source.before(boundary) if boundary is not None else None
|
|
548
|
+
|
|
549
|
+
|
|
550
|
+
def _right_side_used(join: ir.Join, node: exp.Join) -> bool:
|
|
551
|
+
"""Whether anything in the join's Select Expression but its own ON may
|
|
552
|
+
read a column of its right side. Unknown counts as used."""
|
|
553
|
+
select = node.parent
|
|
554
|
+
name = node.this.alias_or_name.lower()
|
|
555
|
+
if not isinstance(select, exp.Select) or not name or not join.right.is_schema_complete or node.args.get("using"):
|
|
556
|
+
return True
|
|
557
|
+
if node.args.get("method"):
|
|
558
|
+
return True # NATURAL: the condition is implicit.
|
|
559
|
+
columns = {column.name.lower() for column in join.right.output_columns}
|
|
560
|
+
if any(isinstance(item, exp.Star) for item in select.expressions):
|
|
561
|
+
return True
|
|
562
|
+
on = node.args.get("on")
|
|
563
|
+
for column in select.find_all(exp.Column):
|
|
564
|
+
if on is not None and _within(column, on):
|
|
565
|
+
continue
|
|
566
|
+
if column.table.lower() == name if column.table else column.name.lower() in columns:
|
|
567
|
+
return True
|
|
568
|
+
return any(
|
|
569
|
+
identifier.name.lower() in columns
|
|
570
|
+
for other in select.args.get("joins") or ()
|
|
571
|
+
for identifier in other.args.get("using") or ()
|
|
572
|
+
)
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
def _right_or_full_join_follows(node: exp.Join) -> bool:
|
|
576
|
+
joins = list(node.parent.args.get("joins") or ()) if node.parent is not None else []
|
|
577
|
+
later = joins[next(index for index, other in enumerate(joins) if other is node) + 1:]
|
|
578
|
+
return any((other.side or "").upper() in {"RIGHT", "FULL"} for other in later)
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
def _within(node: Expr | None, ancestor: Expr) -> bool:
|
|
582
|
+
current: Expr | None = node
|
|
583
|
+
while current is not None:
|
|
584
|
+
if current is ancestor:
|
|
585
|
+
return True
|
|
586
|
+
current = current.parent
|
|
587
|
+
return False
|
|
588
|
+
|
|
589
|
+
|
|
590
|
+
# DISTINCT and GROUP BY ------------------------------------------------------------
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
def _redundant_distinct(site: AttachmentSite, distinct: ir.Distinct, node: exp.Select, source: Source) -> list[Rewrite]:
|
|
594
|
+
"""DISTINCT over input rows no two of which agree on the selected
|
|
595
|
+
columns, NULL equal to NULL: a strict key of the input. Its edit deletes
|
|
596
|
+
the keyword."""
|
|
597
|
+
keyword = node.args.get("distinct")
|
|
598
|
+
tokens = source.tokens_of(span(keyword)) if keyword is not None else None
|
|
599
|
+
if tokens is None:
|
|
600
|
+
return []
|
|
601
|
+
selected = {
|
|
602
|
+
column.scalar_expr.column: column.name
|
|
603
|
+
for column in distinct.output_columns if isinstance(column.scalar_expr, ir.ColumnRef)
|
|
604
|
+
}
|
|
605
|
+
key = _strict_key(distinct.input, tuple(selected))
|
|
606
|
+
if key is None:
|
|
607
|
+
return []
|
|
608
|
+
evidence = _reaches_row_identity(_closure(distinct.input, frozenset(key), frozenset()))
|
|
609
|
+
names = quoted_all(selected[column] for column in key)
|
|
610
|
+
message = f"no two rows agree on ({names}), NULL equal to NULL, so DISTINCT removes nothing: delete DISTINCT"
|
|
611
|
+
return [Rewrite(site, RewriteKind.REDUNDANT_DISTINCT, message, source.deletions([tokens]), evidence)]
|
|
612
|
+
|
|
613
|
+
|
|
614
|
+
def _strict_key(relation: ir.RelationExpr, columns: tuple[ir.OutputColumn, ...]) -> tuple[ir.OutputColumn, ...] | None:
|
|
615
|
+
"""A minimal subset of `columns` that strictly determines a row of `relation`, if any."""
|
|
616
|
+
|
|
617
|
+
def reaches(members: tuple[ir.OutputColumn, ...]) -> bool:
|
|
618
|
+
return RowIdentity(relation) in _closure(relation, frozenset(members), frozenset()).value.columns
|
|
619
|
+
|
|
620
|
+
if not columns or not reaches(columns):
|
|
621
|
+
return None
|
|
622
|
+
for column in columns:
|
|
623
|
+
rest = tuple(other for other in columns if other is not column)
|
|
624
|
+
if rest and reaches(rest):
|
|
625
|
+
return _strict_key(relation, rest)
|
|
626
|
+
return columns
|
|
627
|
+
|
|
628
|
+
|
|
629
|
+
def _grouping_is_projection(
|
|
630
|
+
site: AttachmentSite, aggregate: ir.Aggregate, node: exp.Select, dialect: str, source: Source,
|
|
631
|
+
) -> Rewrite | None:
|
|
632
|
+
"""A GROUP BY whose grouping columns no two input rows agree on, NULL
|
|
633
|
+
equal to NULL (GROUP BY puts NULLs in one group): every group is one row,
|
|
634
|
+
so the query is a projection, each aggregate its value over that row.
|
|
635
|
+
An empty input gives no rows either way. Silent when a grouping
|
|
636
|
+
expression is not a column, or an aggregate has no one-row form here
|
|
637
|
+
(`_one_row`), or is read outside the select list and HAVING (ORDER BY,
|
|
638
|
+
QUALIFY, a window over it), or HAVING reads a select item by its name,
|
|
639
|
+
which WHERE cannot. A rewrite with caveat when an item's type or
|
|
640
|
+
precision may change (`_one_row`), or HAVING's arithmetic may overflow.
|
|
641
|
+
The edits delete GROUP BY and replace each aggregate call by its one-row
|
|
642
|
+
value (`_one_row_edit`); a HAVING, its calls replaced so, is deleted and
|
|
643
|
+
its condition ANDed into WHERE (each parenthesized when an OR), or
|
|
644
|
+
written as a WHERE in GROUP BY's place."""
|
|
645
|
+
expressions = grouping(node) or []
|
|
646
|
+
outputs = aggregate.grouping_outputs
|
|
647
|
+
if not outputs or len(expressions) != len(outputs) or not all(isinstance(column.scalar_expr, ir.ColumnRef) for column in outputs):
|
|
648
|
+
return None
|
|
649
|
+
having = node.args.get("having")
|
|
650
|
+
parts = [*node.expressions, *([having] if having is not None else [])]
|
|
651
|
+
if any(
|
|
652
|
+
call.find_ancestor(exp.Select) is node and not any(_within(call, part) for part in parts)
|
|
653
|
+
for call in node.find_all(exp.AggFunc)
|
|
654
|
+
) or node.args.get("qualify") is not None or any(item.find(exp.Window) for item in node.expressions):
|
|
655
|
+
return None
|
|
656
|
+
aliases = {item.alias.lower() for item in node.expressions if isinstance(item, exp.Alias)}
|
|
657
|
+
if having is not None and any(not column.table and column.name.lower() in aliases for column in having.find_all(exp.Column)):
|
|
658
|
+
return None
|
|
659
|
+
if any(part.find(exp.Anonymous, exp.AnonymousAggFunc) for part in parts):
|
|
660
|
+
# A call SQLGlot does not know may be an aggregate the analysis does
|
|
661
|
+
# not model (DuckDB's mean, arbitrary, count_star): with GROUP BY
|
|
662
|
+
# gone, it would aggregate the whole input.
|
|
663
|
+
return None
|
|
664
|
+
keys = frozenset(column.scalar_expr.column for column in outputs if isinstance(column.scalar_expr, ir.ColumnRef))
|
|
665
|
+
evidence = _reaches_row_identity(_closure(aggregate.input, keys, frozenset()))
|
|
666
|
+
if not evidence.value:
|
|
667
|
+
return None
|
|
668
|
+
types = {
|
|
669
|
+
call.description: _comparison_type(argument.column).value
|
|
670
|
+
for call in aggregate.calls
|
|
671
|
+
if len(call.arguments) == 1 and isinstance(argument := call.arguments[0], ir.ColumnRef)
|
|
672
|
+
}
|
|
673
|
+
clause = source.tokens_of(span(node.args["group"])) if node.args.get("group") is not None else None
|
|
674
|
+
if clause is None:
|
|
675
|
+
return None
|
|
676
|
+
caveats: list[_Caveat] = []
|
|
677
|
+
if having is None:
|
|
678
|
+
edits = list(source.deletions([clause]))
|
|
679
|
+
else:
|
|
680
|
+
moved = _having_into_where(node, having, clause, source, dialect, types)
|
|
681
|
+
if moved is None:
|
|
682
|
+
return None
|
|
683
|
+
having_edits, having_caveats = moved
|
|
684
|
+
edits = list(having_edits)
|
|
685
|
+
caveats.extend(having_caveats)
|
|
686
|
+
for item in node.expressions:
|
|
687
|
+
name = quoted(item.alias if isinstance(item, exp.Alias) else written_sql(item, dialect))
|
|
688
|
+
rewritten = _one_row(item, name, dialect, types)
|
|
689
|
+
if rewritten is None:
|
|
690
|
+
return None
|
|
691
|
+
replacements, item_caveats = rewritten
|
|
692
|
+
for replacement in replacements:
|
|
693
|
+
edit = _one_row_edit(replacement, source, dialect)
|
|
694
|
+
if edit is None:
|
|
695
|
+
return None
|
|
696
|
+
edits.append(edit)
|
|
697
|
+
caveats.extend(item_caveats)
|
|
698
|
+
names = quoted_all(written_sql(expression, dialect) for expression in expressions)
|
|
699
|
+
message = (
|
|
700
|
+
f"no two rows agree on ({names}), NULL equal to NULL, so every group is one row: "
|
|
701
|
+
"drop GROUP BY and write each aggregate as its value over that row"
|
|
702
|
+
) + (", and move HAVING into WHERE" if having is not None else "")
|
|
703
|
+
if not caveats:
|
|
704
|
+
return Rewrite(site, RewriteKind.GROUPING_PROJECTION, message, tuple(edits), evidence)
|
|
705
|
+
message += f". Caveat: {'; '.join(caveat.text for caveat in caveats)}"
|
|
706
|
+
castable = len({caveat.column for caveat in caveats if caveat.castable})
|
|
707
|
+
if castable:
|
|
708
|
+
message += "; cast it if later arithmetic needs the wider type" if castable == 1 else "; cast them if later arithmetic needs the wider types"
|
|
709
|
+
return Rewrite(site, RewriteKind.GROUPING_PROJECTION, message, tuple(edits), evidence, SuggestType.REWRITE_WITH_CAVEAT)
|
|
710
|
+
|
|
711
|
+
|
|
712
|
+
def _having_into_where(
|
|
713
|
+
node: exp.Select, having: exp.Having, group: tuple[int, int], source: Source, dialect: str, types: dict[str, str | None],
|
|
714
|
+
) -> tuple[tuple[Edit, ...], list[_Caveat]] | None:
|
|
715
|
+
"""GROUP BY (tokens `group`) and HAVING deleted, HAVING's condition, each
|
|
716
|
+
aggregate call in it written as its one-row value as an item's is,
|
|
717
|
+
ANDed into WHERE or written as a WHERE in GROUP BY's place; and what the
|
|
718
|
+
replacements may change, as for an item (no column to cast)."""
|
|
719
|
+
clause = source.tokens_of(span(having))
|
|
720
|
+
rewritten = _one_row(having.this, "HAVING", dialect, types)
|
|
721
|
+
if clause is None or rewritten is None or clause[0] + 1 > clause[1]:
|
|
722
|
+
return None
|
|
723
|
+
replacements, caveats = rewritten
|
|
724
|
+
first, last = clause[0] + 1, clause[1]
|
|
725
|
+
start = source.start(first)
|
|
726
|
+
inner = []
|
|
727
|
+
for replacement in replacements:
|
|
728
|
+
edit = _one_row_edit(replacement, source, dialect)
|
|
729
|
+
if edit is None:
|
|
730
|
+
return None
|
|
731
|
+
inner.append(Edit(edit.start - start, edit.end - start, edit.replacement))
|
|
732
|
+
condition = apply_edits(source.sql[start:source.end(last)], inner)
|
|
733
|
+
caveats = [replace(caveat, castable=False) for caveat in caveats]
|
|
734
|
+
moved = [(first, last)]
|
|
735
|
+
where = node.args.get("where")
|
|
736
|
+
adjacent = clause[0] == group[1] + 1
|
|
737
|
+
if where is None:
|
|
738
|
+
if adjacent:
|
|
739
|
+
return (source.replace(group[0], clause[1], f"WHERE {condition}", moved),), caveats
|
|
740
|
+
return (source.replace(*group, f"WHERE {condition}"), source.delete(*clause, moved)), caveats
|
|
741
|
+
anded = _anded_to_where(where, source, f"({condition})" if isinstance(having.this, exp.Or | exp.Xor) else condition)
|
|
742
|
+
if anded is None:
|
|
743
|
+
return None
|
|
744
|
+
deleted = (source.delete(group[0], clause[1], moved),) if adjacent else (*source.deletions([group]), source.delete(*clause, moved))
|
|
745
|
+
return (*deleted, *anded), caveats
|
|
746
|
+
|
|
747
|
+
|
|
748
|
+
@dataclass(frozen=True)
|
|
749
|
+
class _OneRowValue:
|
|
750
|
+
"""An aggregate call's value over one row: `target`, the call or the
|
|
751
|
+
IGNORE or RESPECT NULLS around it, is written as 1 (`count(*)`), as
|
|
752
|
+
`CASE WHEN x IS NULL THEN 0 ELSE 1 END` (`count(x)`), or as its argument
|
|
753
|
+
`argument` (none for `count(*)`). `whole`: the call is its select item's
|
|
754
|
+
whole expression."""
|
|
755
|
+
|
|
756
|
+
target: Expr
|
|
757
|
+
call: exp.AggFunc
|
|
758
|
+
form: Literal["one", "case", "argument"]
|
|
759
|
+
whole: bool
|
|
760
|
+
argument: Expr | None
|
|
761
|
+
|
|
762
|
+
|
|
763
|
+
def _one_row_edit(value: _OneRowValue, source: Source, dialect: str) -> Edit | None:
|
|
764
|
+
"""The call written as its one-row value: its argument's text, verbatim,
|
|
765
|
+
in parentheses inside an expression unless it is a column, literal, call
|
|
766
|
+
or CASE. The call is written `name(...)` or, as an ODBC escape, `{fn
|
|
767
|
+
name(...)}`; its argument without DISTINCT or ALL before it, nor IGNORE
|
|
768
|
+
or RESPECT NULLS or BigQuery's HAVING MAX or MIN after it. None when the
|
|
769
|
+
text left does not parse back to the argument."""
|
|
770
|
+
tokens = source.tokens_of(span(value.target) or span(value.call))
|
|
771
|
+
if tokens is None:
|
|
772
|
+
return None
|
|
773
|
+
first, last = tokens
|
|
774
|
+
name, end = first, last
|
|
775
|
+
if source.is_(first, TokenType.L_BRACE) and source.tokens[first + 1].text.lower() == "fn":
|
|
776
|
+
if not source.is_(last, TokenType.R_BRACE):
|
|
777
|
+
return None
|
|
778
|
+
name, end = first + 2, last - 1
|
|
779
|
+
closing = source.closing(name + 1) if source.is_(name + 1, TokenType.L_PAREN) else None
|
|
780
|
+
if closing is None or closing > end:
|
|
781
|
+
return None
|
|
782
|
+
if value.form == "one":
|
|
783
|
+
return source.replace(first, last, "1")
|
|
784
|
+
argument_first, argument_last = name + 2, closing - 1
|
|
785
|
+
if source.is_(argument_first, TokenType.DISTINCT, TokenType.ALL):
|
|
786
|
+
argument_first += 1
|
|
787
|
+
if (
|
|
788
|
+
argument_last - 1 > argument_first and source.tokens[argument_last].text.upper() == "NULLS"
|
|
789
|
+
and source.tokens[argument_last - 1].text.upper() in {"IGNORE", "RESPECT"}
|
|
790
|
+
):
|
|
791
|
+
argument_last -= 2
|
|
792
|
+
having = source.top_level(argument_first, argument_last, TokenType.HAVING)
|
|
793
|
+
if having:
|
|
794
|
+
argument_last = having[0] - 1
|
|
795
|
+
if argument_last < argument_first or value.argument is None:
|
|
796
|
+
return None
|
|
797
|
+
argument = source.text(argument_first, argument_last)
|
|
798
|
+
try:
|
|
799
|
+
parsed = sqlglot.parse_one(argument, read=dialect)
|
|
800
|
+
except sqlglot.errors.ParseError:
|
|
801
|
+
return None
|
|
802
|
+
if parsed.sql(dialect=dialect) != value.argument.sql(dialect=dialect):
|
|
803
|
+
return None
|
|
804
|
+
moved = [(argument_first, argument_last)]
|
|
805
|
+
if value.form == "case":
|
|
806
|
+
return source.replace(first, last, f"CASE WHEN {argument} IS NULL THEN 0 ELSE 1 END", moved)
|
|
807
|
+
atomic = isinstance(value.argument, exp.Column | exp.Literal | exp.Paren | exp.Func | exp.Case | exp.Null | exp.Boolean)
|
|
808
|
+
return source.replace(first, last, argument if value.whole or atomic else f"({argument})", moved)
|
|
809
|
+
|
|
810
|
+
|
|
811
|
+
@dataclass(frozen=True)
|
|
812
|
+
class _Caveat:
|
|
813
|
+
"""What a one-row replacement may change in `column`, a quoted output
|
|
814
|
+
name: its type or overflow (`castable`: a cast to the aggregate's wider
|
|
815
|
+
type restores it), or avg's precision."""
|
|
816
|
+
|
|
817
|
+
column: str
|
|
818
|
+
text: str
|
|
819
|
+
castable: bool
|
|
820
|
+
|
|
821
|
+
|
|
822
|
+
# Argument types whose sum and average over one row are the argument's value,
|
|
823
|
+
# and whose average, a DOUBLE in some dialects, holds it exactly (at most
|
|
824
|
+
# 32-bit integers and floats): a BIGINT, HUGEINT, UBIGINT or DECIMAL average
|
|
825
|
+
# may round, which the rewrite caveats.
|
|
826
|
+
_SUMMABLE = (exp.DataType.INTEGER_TYPES | exp.DataType.REAL_TYPES) - {
|
|
827
|
+
exp.DataType.Type.BIT, exp.DataType.Type.MONEY, exp.DataType.Type.SMALLMONEY,
|
|
828
|
+
}
|
|
829
|
+
_FLOATS = {exp.DataType.Type.FLOAT, exp.DataType.Type.DOUBLE, exp.DataType.Type.UDOUBLE}
|
|
830
|
+
_AVERAGED_EXACTLY = {
|
|
831
|
+
exp.DataType.Type.TINYINT, exp.DataType.Type.SMALLINT, exp.DataType.Type.MEDIUMINT, exp.DataType.Type.INT,
|
|
832
|
+
exp.DataType.Type.UTINYINT, exp.DataType.Type.USMALLINT, exp.DataType.Type.UMEDIUMINT, exp.DataType.Type.UINT,
|
|
833
|
+
exp.DataType.Type.FLOAT, exp.DataType.Type.DOUBLE,
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
|
|
837
|
+
def _one_row(item: Expr, name: str, dialect: str, types: dict[str, str | None]) -> tuple[list[_OneRowValue], list[_Caveat]] | None:
|
|
838
|
+
"""Each aggregate call in `item`, output as `name`, and its value over
|
|
839
|
+
one row, and what each replacement may change in its type, overflow or
|
|
840
|
+
precision; None when an aggregate has no such form here.
|
|
841
|
+
|
|
842
|
+
count(*) is 1 and count(x) is 1 unless x is NULL, an integer literal's
|
|
843
|
+
type rather than count's; sum(x) and avg(x) are x for a numeric x, of
|
|
844
|
+
x's type unless x is a DOUBLE; min, max, any_value, and bool_and or
|
|
845
|
+
bool_or of a BOOLEAN are x, of x's type. Precision and type are caveats,
|
|
846
|
+
never a refusal:
|
|
847
|
+
- a whole item changes type (`sum(x)` is x's type, not sum's);
|
|
848
|
+
- inside an expression, the arithmetic runs in the narrower type and
|
|
849
|
+
may overflow, or for a float round, where the aggregate's did not
|
|
850
|
+
(`sum(x) + 1`);
|
|
851
|
+
- avg of a type a DOUBLE does not hold exactly (`_AVERAGED_EXACTLY`) is
|
|
852
|
+
x, the exact average, where avg's DOUBLE may round it.
|
|
853
|
+
A value change is a refusal: sum of a BOOLEAN counts it, and avg of an
|
|
854
|
+
integer inside an expression may divide as an integer (`avg(x) / 2` is
|
|
855
|
+
x / 2, which truncates in PostgreSQL). So is an argument whose type is
|
|
856
|
+
unknown. With or without DISTINCT, IGNORE or RESPECT NULLS; never with
|
|
857
|
+
FILTER, nor a count of several values. None too when an aggregate sits
|
|
858
|
+
in a subquery: it may be the subquery's own or, reading only outer
|
|
859
|
+
columns, the outer query's."""
|
|
860
|
+
if any(_within(call.find_ancestor(exp.Select), item) for call in item.find_all(exp.AggFunc)):
|
|
861
|
+
return None
|
|
862
|
+
caveats: list[_Caveat] = []
|
|
863
|
+
values: list[_OneRowValue] = []
|
|
864
|
+
for call in list(item.find_all(exp.AggFunc)):
|
|
865
|
+
target: Expr = call
|
|
866
|
+
while isinstance(target.parent, exp.IgnoreNulls | exp.RespectNulls):
|
|
867
|
+
target = target.parent
|
|
868
|
+
if isinstance(target.parent, exp.Filter | exp.WithinGroup) or any(value for key, value in call.args.items() if key not in {"this", "big_int"}):
|
|
869
|
+
return None
|
|
870
|
+
argument = call.this
|
|
871
|
+
if isinstance(argument, exp.Distinct):
|
|
872
|
+
if len(argument.expressions) != 1:
|
|
873
|
+
return None
|
|
874
|
+
argument = argument.expressions[0]
|
|
875
|
+
if isinstance(argument, exp.HavingMax):
|
|
876
|
+
argument = argument.this # BigQuery's ANY_VALUE(x HAVING MAX y): x, over one row.
|
|
877
|
+
if isinstance(argument, exp.Column) and isinstance(argument.this, exp.Star):
|
|
878
|
+
return None # count(t.*) counts rows.
|
|
879
|
+
declared = types.get(call.sql(dialect=dialect))
|
|
880
|
+
kind = exp.DataType.build(declared, dialect=dialect).this if declared is not None else None
|
|
881
|
+
whole = target is item or (isinstance(item, exp.Alias) and target is item.this)
|
|
882
|
+
narrowed_to = None
|
|
883
|
+
form: Literal["one", "case", "argument"] = "argument"
|
|
884
|
+
match call:
|
|
885
|
+
case exp.Count() if argument is None or isinstance(argument, exp.Star):
|
|
886
|
+
form = "one"
|
|
887
|
+
narrowed_to = "an integer literal's type"
|
|
888
|
+
case exp.Count() if isinstance(argument, exp.Column) and declared is None:
|
|
889
|
+
return None # Maybe a whole row (`count(t)`), NULL in PostgreSQL when all its columns are.
|
|
890
|
+
case exp.Count():
|
|
891
|
+
form = "case"
|
|
892
|
+
narrowed_to = "an integer literal's type"
|
|
893
|
+
case exp.Sum() | exp.Avg() if isinstance(argument, Expr) and not isinstance(argument, exp.Star | exp.Order) and kind in _SUMMABLE:
|
|
894
|
+
if isinstance(call, exp.Avg) and not whole and kind in exp.DataType.INTEGER_TYPES:
|
|
895
|
+
return None
|
|
896
|
+
written = written_sql(argument, dialect)
|
|
897
|
+
if isinstance(call, exp.Avg) and kind not in _AVERAGED_EXACTLY:
|
|
898
|
+
caveats.append(_Caveat(name, (
|
|
899
|
+
f"{name} takes {written}'s exact value and type, where avg converts to DOUBLE in some dialects "
|
|
900
|
+
"and may lose precision (avg(9007199254740993) is 9007199254740992.0)"
|
|
901
|
+
), castable=False))
|
|
902
|
+
if whole:
|
|
903
|
+
narrowed_to = ""
|
|
904
|
+
if kind is not exp.DataType.Type.DOUBLE and narrowed_to is None:
|
|
905
|
+
narrowed_to = f"the type of {written}"
|
|
906
|
+
case exp.LogicalAnd() | exp.LogicalOr() if isinstance(argument, Expr) and kind is exp.DataType.Type.BOOLEAN:
|
|
907
|
+
pass
|
|
908
|
+
case exp.Min() | exp.Max() | exp.AnyValue() if isinstance(argument, Expr) and not isinstance(argument, exp.Star | exp.Order):
|
|
909
|
+
pass
|
|
910
|
+
case _:
|
|
911
|
+
return None
|
|
912
|
+
aggregate = "count" if isinstance(call, exp.Count) else "sum" if isinstance(call, exp.Sum) else "avg"
|
|
913
|
+
if narrowed_to and whole:
|
|
914
|
+
caveats.append(_Caveat(name, f"{name} changes from {aggregate}'s result type to {narrowed_to}", castable=True))
|
|
915
|
+
elif narrowed_to:
|
|
916
|
+
risk = "lose precision" if kind in _FLOATS else "overflow"
|
|
917
|
+
caveats.append(_Caveat(name, (
|
|
918
|
+
f"{name} runs its arithmetic in {narrowed_to}, not {aggregate}'s result type, "
|
|
919
|
+
f"and may {risk} where the aggregate's did not"
|
|
920
|
+
), castable=True))
|
|
921
|
+
values.append(_OneRowValue(target, call, form, whole, argument if form != "one" else None))
|
|
922
|
+
return values, caveats
|
|
923
|
+
|
|
924
|
+
|
|
925
|
+
def _redundant_grouping(
|
|
926
|
+
site: AttachmentSite, selected: ir.RelationExpr, aggregate: ir.Aggregate, node: exp.Select, dialect: str, source: Source,
|
|
927
|
+
) -> list[Rewrite]:
|
|
928
|
+
"""Each grouping column the grouping columns kept so far strictly determine.
|
|
929
|
+
`selected` is the relation whose output columns are `node`'s items: the
|
|
930
|
+
Aggregate, or a Project over it. The edits delete it from GROUP BY, with
|
|
931
|
+
a comma, and wrap its select item, if any, in any_value, named as before.
|
|
932
|
+
|
|
933
|
+
One column always stays: grouping by nothing turns an empty input into one row.
|
|
934
|
+
"""
|
|
935
|
+
expressions = grouping(node) or []
|
|
936
|
+
group = node.args.get("group")
|
|
937
|
+
if len(expressions) != len(aggregate.grouping_outputs) or not isinstance(group, exp.Group):
|
|
938
|
+
return []
|
|
939
|
+
clause = source.tokens_of(span(group))
|
|
940
|
+
written_items = source.split(clause[0] + 1, clause[1], TokenType.COMMA) if clause is not None else []
|
|
941
|
+
items = _select_items(node, source)
|
|
942
|
+
if len(written_items) != len(group.expressions) or items is None:
|
|
943
|
+
return []
|
|
944
|
+
# Grouping outputs are lowered in GROUP BY order.
|
|
945
|
+
written = {column: written_sql(expression, dialect) for column, expression in zip(aggregate.grouping_outputs, expressions)}
|
|
946
|
+
kept = list(aggregate.grouping_outputs)
|
|
947
|
+
found = []
|
|
948
|
+
for grouped in aggregate.grouping_outputs:
|
|
949
|
+
others = [other for other in kept if other is not grouped]
|
|
950
|
+
if not others or not isinstance(grouped.scalar_expr, ir.ColumnRef):
|
|
951
|
+
continue
|
|
952
|
+
determinant = frozenset(other.scalar_expr.column for other in others if isinstance(other.scalar_expr, ir.ColumnRef))
|
|
953
|
+
closure = _closure(aggregate.input, determinant, frozenset())
|
|
954
|
+
source_column = grouped.scalar_expr.column
|
|
955
|
+
expression = expressions[aggregate.grouping_outputs.index(grouped)]
|
|
956
|
+
if source_column not in closure.value.columns or _read_past_select_list(node, expression):
|
|
957
|
+
continue
|
|
958
|
+
kept.remove(grouped)
|
|
959
|
+
names = quoted_all(written[other] for other in others)
|
|
960
|
+
alias = exp.to_identifier(grouped.name).sql(dialect=dialect)
|
|
961
|
+
position = next((
|
|
962
|
+
index for index, column in enumerate(selected.output_columns)
|
|
963
|
+
if column is grouped or isinstance(column.scalar_expr, ir.ColumnRef) and column.scalar_expr.column is grouped
|
|
964
|
+
), None)
|
|
965
|
+
drop = f"({names}) determine {quoted(written[grouped])}, NULL equal to NULL: drop {quoted(written[grouped])} from GROUP BY"
|
|
966
|
+
index = next(index for index, expression in enumerate(group.expressions) if expression is expressions[aggregate.grouping_outputs.index(grouped)])
|
|
967
|
+
first, last = written_items[index]
|
|
968
|
+
edits = list(source.deletions([(first - 1, last) if index else (first, last + 1)]))
|
|
969
|
+
if position is None:
|
|
970
|
+
message = drop # Not selected.
|
|
971
|
+
else:
|
|
972
|
+
item = node.expressions[position]
|
|
973
|
+
expression = item.this if isinstance(item, exp.Alias) else item
|
|
974
|
+
message = f"{drop} and select any_value({written_sql(expression, dialect)}) AS {alias}"
|
|
975
|
+
start, end = items[position][1]
|
|
976
|
+
edits += [
|
|
977
|
+
source.insert_before(start, "any_value("),
|
|
978
|
+
source.insert_after(end, ")" if isinstance(item, exp.Alias) else f") AS {alias}"),
|
|
979
|
+
]
|
|
980
|
+
found.append(Rewrite(site, RewriteKind.REDUNDANT_GROUPING, message, tuple(edits), closure.members[source_column]))
|
|
981
|
+
return found
|
|
982
|
+
|
|
983
|
+
|
|
984
|
+
def _read_past_select_list(node: exp.Select, expression: Expr) -> bool:
|
|
985
|
+
"""Whether a column `expression` reads may be read in DISTINCT ON, HAVING,
|
|
986
|
+
QUALIFY or ORDER BY of `node`, where it must stay grouped: any column of
|
|
987
|
+
the same name, but, in DISTINCT ON and ORDER BY, an unqualified one that
|
|
988
|
+
names a select item, which they read instead."""
|
|
989
|
+
names = {column.name.lower() for column in expression.find_all(exp.Column)}
|
|
990
|
+
outputs = {item.alias_or_name.lower() for item in node.expressions}
|
|
991
|
+
distinct = node.args.get("distinct")
|
|
992
|
+
for key, clause in (("on", distinct.args.get("on") if distinct is not None else None), *(
|
|
993
|
+
(key, node.args.get(key)) for key in ("having", "qualify", "order")
|
|
994
|
+
)):
|
|
995
|
+
for column in clause.find_all(exp.Column) if clause is not None else ():
|
|
996
|
+
name = column.name.lower()
|
|
997
|
+
if name in names and not (key in {"on", "order"} and not column.table and name in outputs):
|
|
998
|
+
return True
|
|
999
|
+
return False
|
|
1000
|
+
|
|
1001
|
+
|
|
1002
|
+
def _select_items(node: exp.Select, source: Source) -> list[tuple[tuple[int, int], tuple[int, int]]] | None:
|
|
1003
|
+
"""The tokens of each item of `node`'s select list, whole and without
|
|
1004
|
+
its alias; None where they cannot be told apart."""
|
|
1005
|
+
position = span(node)
|
|
1006
|
+
end = marker_position(node)
|
|
1007
|
+
start = source.at(position[0]) if position is not None else None
|
|
1008
|
+
last = source.before(end[0]) if end is not None else None
|
|
1009
|
+
# Its SELECT keyword: after the FROM of a DuckDB FROM-first Select, and
|
|
1010
|
+
# none in a bare `FROM t`, whose `*` is implied.
|
|
1011
|
+
keyword = next(iter(source.top_level(start, last, TokenType.SELECT)), None) if start is not None and last is not None else None
|
|
1012
|
+
if keyword is None or last is None:
|
|
1013
|
+
return None
|
|
1014
|
+
first = keyword + 1
|
|
1015
|
+
distinct = node.args.get("distinct")
|
|
1016
|
+
if distinct is not None:
|
|
1017
|
+
if not source.is_(first, TokenType.DISTINCT):
|
|
1018
|
+
return None
|
|
1019
|
+
first += 1
|
|
1020
|
+
if distinct.args.get("on") is not None:
|
|
1021
|
+
# DISTINCT ON (...): the list starts past its parenthesized keys.
|
|
1022
|
+
closing = source.closing(first + 1) if source.is_(first, TokenType.ON) and source.is_(first + 1, TokenType.L_PAREN) else None
|
|
1023
|
+
if closing is None:
|
|
1024
|
+
return None
|
|
1025
|
+
first = closing + 1
|
|
1026
|
+
elif source.is_(first, TokenType.ALL):
|
|
1027
|
+
first += 1
|
|
1028
|
+
# The list ends at FROM, or at the first clause after it.
|
|
1029
|
+
ends = [index for index in source.top_level(first, last, *_AFTER_SELECT_LIST)]
|
|
1030
|
+
parts = source.split(first, (ends[0] - 1) if ends else last, TokenType.COMMA)
|
|
1031
|
+
if len(parts) != len(node.expressions):
|
|
1032
|
+
return None
|
|
1033
|
+
items = []
|
|
1034
|
+
for (item_first, item_last), item in zip(parts, node.expressions):
|
|
1035
|
+
expression_last = item_last
|
|
1036
|
+
if isinstance(item, exp.Alias):
|
|
1037
|
+
identifier = item.args.get("alias")
|
|
1038
|
+
alias = source.at(identifier.meta["start"]) if isinstance(identifier, exp.Identifier) and "start" in identifier.meta else None
|
|
1039
|
+
if alias is None or not item_first < alias <= item_last:
|
|
1040
|
+
return None
|
|
1041
|
+
expression_last = alias - 2 if source.is_(alias - 1, TokenType.ALIAS) else alias - 1
|
|
1042
|
+
items.append(((item_first, item_last), (item_first, expression_last)))
|
|
1043
|
+
return items
|
|
1044
|
+
|
|
1045
|
+
|
|
1046
|
+
# Tokens that end a select list.
|
|
1047
|
+
_AFTER_SELECT_LIST = (
|
|
1048
|
+
TokenType.FROM, TokenType.WHERE, TokenType.GROUP_BY, TokenType.HAVING, TokenType.QUALIFY, TokenType.WINDOW,
|
|
1049
|
+
TokenType.ORDER_BY, TokenType.LIMIT, TokenType.OFFSET, TokenType.FETCH, TokenType.INTO,
|
|
1050
|
+
TokenType.UNION, TokenType.EXCEPT, TokenType.INTERSECT,
|
|
1051
|
+
)
|
|
1052
|
+
|
|
1053
|
+
|
|
1054
|
+
# LIMIT and ORDER BY on at most one row ----------------------------------------------
|
|
1055
|
+
|
|
1056
|
+
|
|
1057
|
+
def _one_row_tail(
|
|
1058
|
+
site: AttachmentSite, relation: ir.RelationExpr, limit: ir.Limit | None, select: exp.Select, source: Source,
|
|
1059
|
+
) -> list[Rewrite]:
|
|
1060
|
+
"""A Select proved to return at most one row (the empty set is a strict
|
|
1061
|
+
key of it, Kossmann's early abort) needs no ORDER BY, and no LIMIT of at
|
|
1062
|
+
least one row. Not with OFFSET, which may skip that row, nor a LIMIT whose
|
|
1063
|
+
count is unknown or zero. Its edits delete the clauses."""
|
|
1064
|
+
sorted_ = select.args.get("order") is not None
|
|
1065
|
+
limited = select.args.get("limit") is not None and select.args.get("offset") is None and limit is not None and (limit.count or 0) >= 1
|
|
1066
|
+
if not sorted_ and not limited:
|
|
1067
|
+
return []
|
|
1068
|
+
clauses = [source.tokens_of(span(select.args[key])) for key, present in (("order", sorted_), ("limit", limited)) if present]
|
|
1069
|
+
if any(tokens is None for tokens in clauses):
|
|
1070
|
+
return []
|
|
1071
|
+
evidence = _reaches_row_identity(_closure(relation, frozenset(), frozenset()))
|
|
1072
|
+
if not evidence.value:
|
|
1073
|
+
return []
|
|
1074
|
+
dropped = " and ".join(clause for clause, present in (("ORDER BY", sorted_), ("LIMIT", limited)) if present)
|
|
1075
|
+
message = f"this Select returns at most one row, so {dropped} {'change' if sorted_ and limited else 'changes'} nothing: drop {'them' if sorted_ and limited else 'it'}"
|
|
1076
|
+
return [Rewrite(site, RewriteKind.ONE_ROW, message, source.deletions(tokens for tokens in clauses if tokens is not None), evidence)]
|
|
1077
|
+
|
|
1078
|
+
|
|
1079
|
+
# Self-joins on a key -----------------------------------------------------------------
|
|
1080
|
+
|
|
1081
|
+
|
|
1082
|
+
@dataclass(frozen=True)
|
|
1083
|
+
class _Copy:
|
|
1084
|
+
"""A column read from one reference (`alias`) to a relation, and the relation's own column."""
|
|
1085
|
+
|
|
1086
|
+
alias: ir.Alias
|
|
1087
|
+
column: ir.OutputColumn
|
|
1088
|
+
|
|
1089
|
+
|
|
1090
|
+
def _copy(column: ir.OutputColumn, program: ir.Program) -> _Copy | None:
|
|
1091
|
+
"""Where `column` comes from, followed through pass-through columns of
|
|
1092
|
+
joins and filters down to the alias that reads its relation."""
|
|
1093
|
+
while True:
|
|
1094
|
+
relation = column.get_relation(program)
|
|
1095
|
+
match relation, column.scalar_expr:
|
|
1096
|
+
case ir.Alias(), ir.ColumnRef(column=source):
|
|
1097
|
+
return _Copy(relation, source)
|
|
1098
|
+
case ir.Join() | ir.Filter(), ir.ColumnRef(column=source):
|
|
1099
|
+
column = source
|
|
1100
|
+
case _:
|
|
1101
|
+
return None
|
|
1102
|
+
|
|
1103
|
+
|
|
1104
|
+
def _self_join(
|
|
1105
|
+
arena: Arena, site: AttachmentSite, join: ir.Join, node: exp.Join, program: ir.Program, dialect: str, source: Source,
|
|
1106
|
+
) -> Rewrite | None:
|
|
1107
|
+
"""`a JOIN t b ON a.k = b.k`, where `a` reads the same relation `t` and
|
|
1108
|
+
`k` is a non-null key of it: each row of `a` matches itself, so every
|
|
1109
|
+
`b.x` is `a.x` and the join goes. Other ON conjuncts move to WHERE (an
|
|
1110
|
+
inner join; not ahead of a RIGHT or FULL JOIN, which would then pad
|
|
1111
|
+
differently) or, for a LEFT JOIN, guard each column read from `b`:
|
|
1112
|
+
`CASE WHEN cond THEN a.x END`, NULL where the join padded. The relation
|
|
1113
|
+
is a table, or a view or CTE whose rows are the same each time it is read
|
|
1114
|
+
(`_same_rows`) and whose columns read through `b` are pure (`_pure`).
|
|
1115
|
+
The edits delete the join, qualify each `b.x` with `a`, and write the
|
|
1116
|
+
other conjuncts, as written but for `b`, in WHERE or each guard."""
|
|
1117
|
+
if join.kind not in {"inner", "left"} or not isinstance(join.right, ir.Alias) or node.args.get("using") or node.args.get("method"):
|
|
1118
|
+
return None
|
|
1119
|
+
select = node.parent
|
|
1120
|
+
if not isinstance(select, exp.Select) or any(isinstance(item, exp.Star) for item in select.expressions):
|
|
1121
|
+
return None
|
|
1122
|
+
pairs, _ = _cross_equalities(join)
|
|
1123
|
+
keys: dict[ir.OutputColumn, ir.OutputColumn] = {} # The relation's key column, by the left column equal to it.
|
|
1124
|
+
alias: ir.Alias | None = None
|
|
1125
|
+
for left, right in pairs:
|
|
1126
|
+
mine, theirs = _copy(left, program), _copy(right, program)
|
|
1127
|
+
if mine is None or theirs is None or theirs.alias is not join.right or mine.column is not theirs.column:
|
|
1128
|
+
continue
|
|
1129
|
+
if alias is not None and mine.alias is not alias:
|
|
1130
|
+
return None
|
|
1131
|
+
alias = mine.alias
|
|
1132
|
+
keys[left] = mine.column
|
|
1133
|
+
if alias is None or alias.source is not join.right.source:
|
|
1134
|
+
return None
|
|
1135
|
+
relation = join.right.source
|
|
1136
|
+
keys = {left: column for left, column in keys.items() if arena.prove(NonNullColumn(column=column)).value}
|
|
1137
|
+
key = arena.prove(NonNullUniqueSet(columns=frozenset(keys.values())))
|
|
1138
|
+
if not key.value or not _same_rows(relation, program):
|
|
1139
|
+
return None
|
|
1140
|
+
if join.kind == "inner":
|
|
1141
|
+
present = arena.prove(NonNullColumns(columns=frozenset(keys)))
|
|
1142
|
+
if not present.value:
|
|
1143
|
+
return None # A padded or NULL key matches nothing, so the join drops its row.
|
|
1144
|
+
key = key & present
|
|
1145
|
+
mine, theirs = alias.name, node.this.alias_or_name
|
|
1146
|
+
names = {column.name.lower() for column in keys.values()}
|
|
1147
|
+
written, _ = _on_conjuncts(node, source)
|
|
1148
|
+
tokens = source.tokens_of(span(node))
|
|
1149
|
+
if written is None or tokens is None:
|
|
1150
|
+
return None
|
|
1151
|
+
columns = {column.name.lower(): column for column in relation.output_columns}
|
|
1152
|
+
extra = [(conjunct, first, last) for conjunct, first, last in written if not _key_equality(conjunct, mine, theirs, names)]
|
|
1153
|
+
if extra and join.kind == "inner" and _right_or_full_join_follows(node):
|
|
1154
|
+
return None
|
|
1155
|
+
if extra and join.kind == "left" and join.predicate is not None and ir.determinants(join.predicate) is None:
|
|
1156
|
+
return None # A volatile condition repeated per column would draw again.
|
|
1157
|
+
reader = exp.to_identifier(mine).sql(dialect=dialect)
|
|
1158
|
+
parts = [_requalified(source, conjunct, first, last, theirs, reader, mine, dialect) for conjunct, first, last in extra]
|
|
1159
|
+
if any(part is None for part in parts):
|
|
1160
|
+
return None
|
|
1161
|
+
guard = " AND ".join(part for part in parts if part is not None) or None
|
|
1162
|
+
edits: list[Edit] = []
|
|
1163
|
+
for column in select.find_all(exp.Column):
|
|
1164
|
+
if _within(column, node):
|
|
1165
|
+
continue
|
|
1166
|
+
if column.find_ancestor(exp.Select) is not select:
|
|
1167
|
+
if column.table.lower() == theirs.lower():
|
|
1168
|
+
return None # Read in a nested query, which this rewrite does not reach.
|
|
1169
|
+
continue
|
|
1170
|
+
if not column.table:
|
|
1171
|
+
if column.name.lower() in columns:
|
|
1172
|
+
return None # Unqualified: it may be read through either reference.
|
|
1173
|
+
continue
|
|
1174
|
+
if column.table.lower() != theirs.lower():
|
|
1175
|
+
continue
|
|
1176
|
+
read = columns.get(column.name.lower())
|
|
1177
|
+
qualifier, name = _identifier_token(column.args.get("table"), source), _identifier_token(column.this, source)
|
|
1178
|
+
if read is None or not _pure(read, program) or qualifier is None or name is None:
|
|
1179
|
+
return None
|
|
1180
|
+
if guard is not None and join.kind == "left":
|
|
1181
|
+
written_name = source.text(name, name)
|
|
1182
|
+
value = f"CASE WHEN {guard} THEN {reader}.{written_name} END"
|
|
1183
|
+
edits.append(source.replace(qualifier, name, value + (f" AS {written_name}" if column.parent is select else "")))
|
|
1184
|
+
else:
|
|
1185
|
+
edits.append(source.replace(qualifier, qualifier, reader))
|
|
1186
|
+
moved = [(first, last) for _, first, last in extra]
|
|
1187
|
+
if guard is not None and join.kind == "inner":
|
|
1188
|
+
anded = _anded_into_where(select, source, guard, tokens, moved)
|
|
1189
|
+
if anded is None:
|
|
1190
|
+
return None
|
|
1191
|
+
edits.extend(anded)
|
|
1192
|
+
else:
|
|
1193
|
+
# A LEFT JOIN's guard may be copied into no column: its comments stay.
|
|
1194
|
+
edits.append(source.delete(*tokens))
|
|
1195
|
+
message = (
|
|
1196
|
+
f"each {mine} row matches itself on the key ({quoted_all(sorted(column.name for column in keys.values()))}), "
|
|
1197
|
+
f"so {theirs} is {mine}: delete the join and read {mine}'s columns"
|
|
1198
|
+
)
|
|
1199
|
+
return Rewrite(site, RewriteKind.SELF_JOIN, message, tuple(edits), key)
|
|
1200
|
+
|
|
1201
|
+
|
|
1202
|
+
def _identifier_token(identifier: Expr | None, source: Source) -> int | None:
|
|
1203
|
+
return source.at(identifier.meta["start"]) if isinstance(identifier, exp.Identifier) and "start" in identifier.meta else None
|
|
1204
|
+
|
|
1205
|
+
|
|
1206
|
+
def _requalified(source: Source, conjunct: Expr, first: int, last: int, old: str, new: str, new_name: str, dialect: str) -> str | None:
|
|
1207
|
+
"""The conjunct, written from token `first` to `last`, reading `new`
|
|
1208
|
+
(written as `new`, named `new_name`) where it read `old`; `new.x =
|
|
1209
|
+
old.x` becomes `new.x IS NOT NULL`, all it still checks once both are
|
|
1210
|
+
one row."""
|
|
1211
|
+
if isinstance(conjunct, exp.EQ) and _key_equality(conjunct, new_name, old, {conjunct.this.name.lower()}):
|
|
1212
|
+
return written_sql(exp.Is(this=exp.column(conjunct.this.name, table=new_name), expression=exp.null(), negate=True), dialect)
|
|
1213
|
+
qualifiers = [
|
|
1214
|
+
_identifier_token(column.args.get("table"), source)
|
|
1215
|
+
for column in conjunct.find_all(exp.Column) if column.table.lower() == old.lower()
|
|
1216
|
+
]
|
|
1217
|
+
text, cursor = "", source.start(first)
|
|
1218
|
+
for index in sorted(index if index is not None else -1 for index in qualifiers):
|
|
1219
|
+
if index < 0:
|
|
1220
|
+
return None
|
|
1221
|
+
text += source.sql[cursor:source.start(index)] + new
|
|
1222
|
+
cursor = source.end(index)
|
|
1223
|
+
return text + source.sql[cursor:source.end(last)]
|
|
1224
|
+
|
|
1225
|
+
|
|
1226
|
+
def _key_equality(conjunct: Expr, mine: str, theirs: str, names: set[str]) -> bool:
|
|
1227
|
+
"""`mine.k = theirs.k` (either way round) for a key column `k`."""
|
|
1228
|
+
if not isinstance(conjunct, exp.EQ) or not isinstance(conjunct.this, exp.Column) or not isinstance(conjunct.expression, exp.Column):
|
|
1229
|
+
return False
|
|
1230
|
+
first, second = conjunct.this, conjunct.expression
|
|
1231
|
+
tables = {first.table.lower(), second.table.lower()}
|
|
1232
|
+
return first.name.lower() == second.name.lower() and first.name.lower() in names and tables == {mine.lower(), theirs.lower()}
|
|
1233
|
+
|
|
1234
|
+
|
|
1235
|
+
def _same_rows(relation: ir.RelationExpr, program: ir.Program) -> bool:
|
|
1236
|
+
"""Whether reading `relation` twice gives the same rows: a table, or a body
|
|
1237
|
+
with no LIMIT, QUALIFY or opaque part, no volatile condition, and no
|
|
1238
|
+
volatile column among those that decide which rows there are (DISTINCT,
|
|
1239
|
+
a set operation's, GROUP BY's). Other columns are checked where read."""
|
|
1240
|
+
relation = relation.closed
|
|
1241
|
+
match relation:
|
|
1242
|
+
case ir.NamedRelation(role=role, body=body):
|
|
1243
|
+
return role is ir.RelationRole.TABLE or (body is not None and _same_rows(body, program))
|
|
1244
|
+
case ir.Limit() | ir.QualifyByPartition() | ir.OpaqueRelation() | ir.RecursiveRelation():
|
|
1245
|
+
return False
|
|
1246
|
+
case ir.Filter(input=source, predicate=predicate):
|
|
1247
|
+
return (predicate is None or _pure_expression(predicate, program)) and _same_rows(source, program)
|
|
1248
|
+
case ir.Join(left=left, right=right, predicate=predicate):
|
|
1249
|
+
return (predicate is None or _pure_expression(predicate, program)) and _same_rows(left, program) and _same_rows(right, program)
|
|
1250
|
+
case ir.Distinct(input=source) | ir.Aggregate(input=source):
|
|
1251
|
+
deciding = relation.grouping_outputs if isinstance(relation, ir.Aggregate) else relation.output_columns
|
|
1252
|
+
return all(_pure(column, program) for column in deciding) and _same_rows(source, program)
|
|
1253
|
+
case ir.SetOperation(left=left, right=right):
|
|
1254
|
+
return (not relation.distinct or all(_pure(column, program) for column in (*left.output_columns, *right.output_columns))) and _same_rows(left, program) and _same_rows(right, program)
|
|
1255
|
+
case ir.Project(input=source) | ir.Alias(source=source):
|
|
1256
|
+
return _same_rows(source, program)
|
|
1257
|
+
case _:
|
|
1258
|
+
assert_never(relation)
|
|
1259
|
+
|
|
1260
|
+
|
|
1261
|
+
def _pure(column: ir.OutputColumn, program: ir.Program) -> bool:
|
|
1262
|
+
"""Whether `column` has the same value each time its row is read: a table
|
|
1263
|
+
column, or a pure function of such columns."""
|
|
1264
|
+
relation = column.get_relation(program)
|
|
1265
|
+
if isinstance(relation, ir.NamedRelation) and relation.role is ir.RelationRole.TABLE:
|
|
1266
|
+
return True
|
|
1267
|
+
return _pure_expression(column.scalar_expr, program)
|
|
1268
|
+
|
|
1269
|
+
|
|
1270
|
+
def _pure_expression(expression: ir.ScalarExpr, program: ir.Program) -> bool:
|
|
1271
|
+
inputs = ir.determinants(expression)
|
|
1272
|
+
return inputs is not None and all(_pure(column, program) for column in inputs)
|
|
1273
|
+
|
|
1274
|
+
|
|
1275
|
+
# Conditions the others imply ---------------------------------------------------------
|
|
1276
|
+
|
|
1277
|
+
|
|
1278
|
+
def _implied_where(
|
|
1279
|
+
arena: Arena, site: AttachmentSite, relation: ir.RelationExpr, program: ir.Program, node: exp.Select, source: Source, dialect: str,
|
|
1280
|
+
) -> list[Rewrite]:
|
|
1281
|
+
"""The WHERE of the Select whose relation is `relation`."""
|
|
1282
|
+
while True:
|
|
1283
|
+
match relation:
|
|
1284
|
+
case ir.Project(input=input_) | ir.Aggregate(input=input_) | ir.Distinct(input=input_) | ir.QualifyByPartition(input=input_) | ir.Join(kind="semi" | "anti", left=input_):
|
|
1285
|
+
relation = input_
|
|
1286
|
+
case ir.Filter():
|
|
1287
|
+
where = node.args.get("where")
|
|
1288
|
+
if where is None:
|
|
1289
|
+
return []
|
|
1290
|
+
clause = source.tokens_of(span(where))
|
|
1291
|
+
return _implied_conjuncts(arena, site, relation, program, "WHERE", _where_conjuncts(where, source), clause, source, dialect)
|
|
1292
|
+
case _:
|
|
1293
|
+
return []
|
|
1294
|
+
|
|
1295
|
+
|
|
1296
|
+
def _implied_conjuncts(
|
|
1297
|
+
arena: Arena, site: AttachmentSite, relation: ir.Filter | ir.Join, program: ir.Program, clause: str,
|
|
1298
|
+
written_conjuncts: list[tuple[Expr, int, int]] | None, clause_tokens: tuple[int, int] | None, source: Source, dialect: str,
|
|
1299
|
+
) -> list[Rewrite]:
|
|
1300
|
+
"""Each conjunct TRUE on every row whose columns it reads are non-null,
|
|
1301
|
+
given the other conjuncts and what is known of the input: an equality
|
|
1302
|
+
two other equalities chain (`a = b AND b = c` give `a = c`), or both of
|
|
1303
|
+
whose sides are pinned to one value; a self-join's copies of one column
|
|
1304
|
+
(`_self_join`'s rows are the same row); `x = v` or `x IN (...)` whose
|
|
1305
|
+
listed values hold every value x can take (its Enumerated Domain);
|
|
1306
|
+
`x IS NOT NULL` where x is never NULL. It is
|
|
1307
|
+
deleted when those columns are non-null, else it only removes rows where
|
|
1308
|
+
one is NULL: write `x IS NOT NULL` instead. The edit deletes it
|
|
1309
|
+
(`_deleted_conjunct`: of an ON, its only conjunct becomes TRUE) or
|
|
1310
|
+
writes the IS NOT NULL in its place. `written_conjuncts` are the
|
|
1311
|
+
clause's conjuncts as written (`_conjunct_tokens`), `clause_tokens` the
|
|
1312
|
+
WHERE's tokens, None for an ON."""
|
|
1313
|
+
if isinstance(relation, ir.Join) and relation.kind not in {"inner", "left", "semi"}:
|
|
1314
|
+
return []
|
|
1315
|
+
found = []
|
|
1316
|
+
conjuncts = relation.conjuncts
|
|
1317
|
+
kept = list(conjuncts)
|
|
1318
|
+
for conjunct in conjuncts:
|
|
1319
|
+
others = [other for other in kept if other is not conjunct]
|
|
1320
|
+
implied = _implication(arena, relation, conjunct, others, program)
|
|
1321
|
+
if implied is None:
|
|
1322
|
+
continue
|
|
1323
|
+
reason, one_value = implied
|
|
1324
|
+
kept.remove(conjunct) # One of several that imply each other stays.
|
|
1325
|
+
columns = ir.strict_inputs(conjunct)[:1] if one_value else ir.strict_inputs(conjunct)
|
|
1326
|
+
rejected = {column for other in others for column in ir.strict_inputs(other)}
|
|
1327
|
+
open_ = [column for column in columns if column not in rejected and not arena.prove(NonNullColumn(column=column)).value]
|
|
1328
|
+
written = conjunct.origin.detail
|
|
1329
|
+
index = next((
|
|
1330
|
+
index for index, (node, _, _) in enumerate(written_conjuncts or ()) if written_sql(node, dialect) == written
|
|
1331
|
+
), None)
|
|
1332
|
+
if index is None or written_conjuncts is None:
|
|
1333
|
+
continue
|
|
1334
|
+
if open_:
|
|
1335
|
+
written_columns = _written_columns(conjunct)
|
|
1336
|
+
check = " AND ".join(f"{written_columns.get(column, column.name)} IS NOT NULL" for column in open_)
|
|
1337
|
+
message = f"{written} is TRUE whenever its columns are non-null ({reason}), so it only removes NULLs: write {check} in {clause}"
|
|
1338
|
+
_, first, last = written_conjuncts[index]
|
|
1339
|
+
edits: tuple[Edit, ...] = (source.replace(first, last, check),)
|
|
1340
|
+
else:
|
|
1341
|
+
message = f"{written} is always TRUE here ({reason}): delete it from {clause}"
|
|
1342
|
+
edits = _deleted_conjunct(source, written_conjuncts, index, clause_tokens)
|
|
1343
|
+
found.append(Rewrite(site, RewriteKind.IMPLIED_CONDITION, message, edits, Result(True, reason, (conjunct,))))
|
|
1344
|
+
return found
|
|
1345
|
+
|
|
1346
|
+
|
|
1347
|
+
def _written_columns(conjunct: ir.ScalarExpr) -> dict[ir.OutputColumn, str]:
|
|
1348
|
+
"""Each column `conjunct` reads, as the SQL wrote it."""
|
|
1349
|
+
found: dict[ir.OutputColumn, str] = {}
|
|
1350
|
+
pending: list[ir.Node] = [conjunct]
|
|
1351
|
+
while pending:
|
|
1352
|
+
node = pending.pop()
|
|
1353
|
+
if isinstance(node, ir.ColumnRef):
|
|
1354
|
+
found.setdefault(node.column, node.origin.detail)
|
|
1355
|
+
elif isinstance(node, ir.ScalarExpr):
|
|
1356
|
+
pending.extend(ir.children(node))
|
|
1357
|
+
return found
|
|
1358
|
+
|
|
1359
|
+
|
|
1360
|
+
def _implication(
|
|
1361
|
+
arena: Arena, relation: ir.Filter | ir.Join, conjunct: ir.ScalarExpr, others: list[ir.ScalarExpr], program: ir.Program,
|
|
1362
|
+
) -> tuple[str, bool] | None:
|
|
1363
|
+
"""Why `conjunct` holds wherever its columns are non-null, and whether
|
|
1364
|
+
its columns are NULL together (one IS NOT NULL then checks both)."""
|
|
1365
|
+
match conjunct:
|
|
1366
|
+
case ir.IsNotNull(operand=ir.ColumnRef(column=column)):
|
|
1367
|
+
return (f"{quoted(column.name)} is never NULL", False) if arena.prove(NonNullColumn(column=column)).value else None
|
|
1368
|
+
case ir.Equality(left=ir.ColumnRef(column=first), right=ir.ColumnRef(column=second)):
|
|
1369
|
+
if _chained(first, second, others):
|
|
1370
|
+
return "the other equalities chain its sides", False
|
|
1371
|
+
pinned = _pinned(first, others), _pinned(second, others)
|
|
1372
|
+
comparable = _same_type(first, second) and _identity_comparison(first).value and _identity_comparison(second).value
|
|
1373
|
+
if comparable and pinned[0] is not None and pinned[0] == pinned[1]:
|
|
1374
|
+
return f"both sides are {pinned[0].text}", False
|
|
1375
|
+
if isinstance(relation, ir.Join) and _same_row_column(first, second, others, relation, program, arena):
|
|
1376
|
+
return "both sides read one row's column through a self-join on its key", True
|
|
1377
|
+
return None
|
|
1378
|
+
case ir.Equality(left=ir.ColumnRef(column=column), right=ir.Constant(value=ir.LiteralValue() as value)) | ir.Equality(left=ir.Constant(value=ir.LiteralValue() as value), right=ir.ColumnRef(column=column)):
|
|
1379
|
+
listed = frozenset({value})
|
|
1380
|
+
case ir.InList(operand=ir.ColumnRef(column=column), values=values) if all(isinstance(item, ir.Constant) and item.value is not None for item in values):
|
|
1381
|
+
listed = frozenset(item.value for item in values if isinstance(item, ir.Constant) and item.value is not None)
|
|
1382
|
+
case _:
|
|
1383
|
+
return None
|
|
1384
|
+
domain = _domain(column).value
|
|
1385
|
+
if domain is None or not domain or not domain <= listed:
|
|
1386
|
+
return None
|
|
1387
|
+
return f"{quoted(column.name)} is always one of the listed values", False
|
|
1388
|
+
|
|
1389
|
+
|
|
1390
|
+
def _chained(first: ir.OutputColumn, second: ir.OutputColumn, others: list[ir.ScalarExpr]) -> bool:
|
|
1391
|
+
"""Whether column-to-column equalities among `others`, over columns of
|
|
1392
|
+
one comparison type compared by identity, connect `first` to `second`."""
|
|
1393
|
+
edges = []
|
|
1394
|
+
for other in others:
|
|
1395
|
+
match other:
|
|
1396
|
+
case ir.Equality(left=ir.ColumnRef(column=left), right=ir.ColumnRef(column=right)) if (
|
|
1397
|
+
_same_type(left, right) and _identity_comparison(left).value and _identity_comparison(right).value
|
|
1398
|
+
):
|
|
1399
|
+
edges.append((left, right))
|
|
1400
|
+
case _:
|
|
1401
|
+
pass
|
|
1402
|
+
reached, pending = {first}, [first]
|
|
1403
|
+
while pending:
|
|
1404
|
+
current = pending.pop()
|
|
1405
|
+
for left, right in edges:
|
|
1406
|
+
for here, there in ((left, right), (right, left)):
|
|
1407
|
+
if here is current and there not in reached:
|
|
1408
|
+
reached.add(there)
|
|
1409
|
+
pending.append(there)
|
|
1410
|
+
return second in reached and first is not second
|
|
1411
|
+
|
|
1412
|
+
|
|
1413
|
+
def _pinned(column: ir.OutputColumn, others: list[ir.ScalarExpr]) -> ir.LiteralValue | None:
|
|
1414
|
+
"""The one value another conjunct, or the column's domain, holds it to."""
|
|
1415
|
+
for other in others:
|
|
1416
|
+
match other:
|
|
1417
|
+
case ir.Equality(left=ir.ColumnRef(column=pinned), right=ir.Constant(value=value) as literal) | ir.Equality(left=ir.Constant(value=value) as literal, right=ir.ColumnRef(column=pinned)) if pinned is column and value is not None and _pins(column, literal):
|
|
1418
|
+
return value
|
|
1419
|
+
case _:
|
|
1420
|
+
pass
|
|
1421
|
+
domain = _domain(column).value
|
|
1422
|
+
return next(iter(domain)) if domain is not None and len(domain) == 1 else None
|
|
1423
|
+
|
|
1424
|
+
|
|
1425
|
+
def _same_row_column(
|
|
1426
|
+
first: ir.OutputColumn, second: ir.OutputColumn, others: list[ir.ScalarExpr], join: ir.Join, program: ir.Program, arena: Arena,
|
|
1427
|
+
) -> bool:
|
|
1428
|
+
"""Whether `first` and `second` are one column of the one row a
|
|
1429
|
+
self-join on a non-null key of its relation, equated by `others`, pairs
|
|
1430
|
+
each row with."""
|
|
1431
|
+
mine, theirs = _copy(first, program), _copy(second, program)
|
|
1432
|
+
if mine is None or theirs is None or mine.column is not theirs.column or mine.alias is theirs.alias:
|
|
1433
|
+
return False
|
|
1434
|
+
if mine.alias.source is not theirs.alias.source or not _same_rows(mine.alias.source, program) or not _pure(mine.column, program):
|
|
1435
|
+
return False
|
|
1436
|
+
pairs = [
|
|
1437
|
+
(other.left.column, other.right.column) for other in others
|
|
1438
|
+
if isinstance(other, ir.Equality) and isinstance(other.left, ir.ColumnRef) and isinstance(other.right, ir.ColumnRef)
|
|
1439
|
+
]
|
|
1440
|
+
keys = set()
|
|
1441
|
+
for left, right in pairs:
|
|
1442
|
+
a, b = _copy(left, program), _copy(right, program)
|
|
1443
|
+
if a is not None and b is not None and a.column is b.column and {a.alias, b.alias} == {mine.alias, theirs.alias}:
|
|
1444
|
+
keys.add(a.column)
|
|
1445
|
+
return bool(keys) and arena.prove(NonNullUniqueSet(columns=frozenset(keys))).value
|
|
1446
|
+
|
|
1447
|
+
|
|
1448
|
+
# EXCEPT and INTERSECT over inputs without duplicates --------------------------------
|
|
1449
|
+
|
|
1450
|
+
|
|
1451
|
+
def _set_operation_all(site: AttachmentSite, operation: ir.SetOperation, source: Source) -> Rewrite | None:
|
|
1452
|
+
"""`A EXCEPT B` keeps each distinct row of A that B lacks; `EXCEPT ALL`
|
|
1453
|
+
keeps it as often as A has it more than B. When A has no two rows alike,
|
|
1454
|
+
NULL equal to NULL as a set operation compares them, both keep each such
|
|
1455
|
+
row once. `INTERSECT ALL` keeps a row as often as the input with fewer of
|
|
1456
|
+
it, so a duplicate-free input on either side suffices. Its edit writes
|
|
1457
|
+
ALL after the operator, or in place of DISTINCT."""
|
|
1458
|
+
if not operation.distinct or operation.operator == "union" or not _same_set_types(operation, operation.output_columns):
|
|
1459
|
+
return None
|
|
1460
|
+
# The site follows the left input's last Select; the operator comes next.
|
|
1461
|
+
operator = source.after(site.offset)
|
|
1462
|
+
while operator is not None and source.is_(operator, TokenType.R_PAREN):
|
|
1463
|
+
operator += 1
|
|
1464
|
+
if operator is None or not source.is_(operator, TokenType.EXCEPT, TokenType.INTERSECT):
|
|
1465
|
+
return None
|
|
1466
|
+
if source.is_(operator + 1, TokenType.DISTINCT):
|
|
1467
|
+
edits = (source.replace(operator + 1, operator + 1, "ALL"),)
|
|
1468
|
+
else:
|
|
1469
|
+
edits = (source.insert_after(operator, " ALL"),)
|
|
1470
|
+
keyword = operation.operator.upper()
|
|
1471
|
+
sides = [("left", operation.left)] + ([("right", operation.right)] if operation.operator == "intersect" else [])
|
|
1472
|
+
for side, relation in sides:
|
|
1473
|
+
evidence = _reaches_row_identity(_closure(relation, frozenset(relation.output_columns), frozenset()))
|
|
1474
|
+
if evidence.value:
|
|
1475
|
+
message = f"no two rows of the {side} input are alike, NULL equal to NULL, so {keyword} removes no duplicates: write {keyword} ALL"
|
|
1476
|
+
return Rewrite(site, RewriteKind.SET_OPERATION_ALL, message, edits, evidence)
|
|
1477
|
+
return None
|
|
1478
|
+
|
|
1479
|
+
|
|
1480
|
+
# Unused CTEs ----------------------------------------------------------------------
|
|
1481
|
+
|
|
1482
|
+
|
|
1483
|
+
def _unused_ctes(ast: ParsedProgram, source: Source) -> list[Rewrite]:
|
|
1484
|
+
"""CTEs no query of their WITH reaches, directly or through a used CTE.
|
|
1485
|
+
Each one's edit deletes it (`_cte_tokens`); each is a Rewrite of its own,
|
|
1486
|
+
so a dead CTE another dead one reads is deleted without it.
|
|
1487
|
+
|
|
1488
|
+
A name is matched wherever it appears as a table, shadowed or not, so a
|
|
1489
|
+
CTE is only ever kept by mistake.
|
|
1490
|
+
"""
|
|
1491
|
+
found = []
|
|
1492
|
+
for with_ in _nodes(ast, exp.With):
|
|
1493
|
+
query = with_.parent
|
|
1494
|
+
ctes = {cte.alias_or_name.lower(): cte for cte in with_.expressions}
|
|
1495
|
+
live = {name for name in _table_names(query, skip=with_) if name in ctes}
|
|
1496
|
+
pending = list(live)
|
|
1497
|
+
while pending:
|
|
1498
|
+
for name in _table_names(ctes[pending.pop()].this):
|
|
1499
|
+
if name in ctes and name not in live:
|
|
1500
|
+
live.add(name)
|
|
1501
|
+
pending.append(name)
|
|
1502
|
+
for name, cte in ctes.items():
|
|
1503
|
+
body = cte.this.find(exp.Select)
|
|
1504
|
+
position = marker_position(body) if body is not None else None
|
|
1505
|
+
tokens = _cte_tokens(source, with_, cte)
|
|
1506
|
+
if name in live or position is None or tokens is None:
|
|
1507
|
+
continue
|
|
1508
|
+
offset, line = position
|
|
1509
|
+
site = AttachmentSite(f"CTE {cte.alias_or_name}", line, offset, True)
|
|
1510
|
+
evidence = Result(True, f"No query of its WITH clause references CTE {cte.alias_or_name}")
|
|
1511
|
+
message = f"CTE {cte.alias_or_name} is never referenced, so it never runs and its markers go unchecked: delete it"
|
|
1512
|
+
found.append(Rewrite(site, RewriteKind.UNUSED_CTE, message, source.deletions([tokens]), evidence))
|
|
1513
|
+
return found
|
|
1514
|
+
|
|
1515
|
+
|
|
1516
|
+
def _cte_tokens(source: Source, with_: exp.With, cte: exp.CTE) -> tuple[int, int] | None:
|
|
1517
|
+
"""The tokens deleting `cte` deletes: `name AS (...)` and the comma
|
|
1518
|
+
after it (before it, for the last), or the whole WITH for its only CTE."""
|
|
1519
|
+
alias = cte.args.get("alias")
|
|
1520
|
+
identifier = alias.this if isinstance(alias, exp.TableAlias) else None
|
|
1521
|
+
name = source.at(identifier.meta["start"]) if isinstance(identifier, exp.Identifier) and "start" in identifier.meta else None
|
|
1522
|
+
if name is None:
|
|
1523
|
+
return None
|
|
1524
|
+
keyword = next(iter(source.top_level(name, len(source.tokens) - 1, TokenType.ALIAS)), None)
|
|
1525
|
+
opening = None if keyword is None else next(
|
|
1526
|
+
(index for index in range(keyword + 1, len(source.tokens)) if source.is_(index, TokenType.L_PAREN)), None
|
|
1527
|
+
)
|
|
1528
|
+
closing = source.closing(opening) if opening is not None else None
|
|
1529
|
+
if closing is None:
|
|
1530
|
+
return None
|
|
1531
|
+
ctes = list(with_.expressions)
|
|
1532
|
+
if len(ctes) == 1:
|
|
1533
|
+
first = name - 1 if source.is_(name - 1, TokenType.RECURSIVE) else name
|
|
1534
|
+
return (first - 1, closing) if source.is_(first - 1, TokenType.WITH) else None
|
|
1535
|
+
if ctes[0] is cte:
|
|
1536
|
+
return (name, closing + 1) if source.is_(closing + 1, TokenType.COMMA) else None
|
|
1537
|
+
return (name - 1, closing) if source.is_(name - 1, TokenType.COMMA) else None
|
|
1538
|
+
|
|
1539
|
+
|
|
1540
|
+
def _table_names(node: Expr, skip: Expr | None = None) -> set[str]:
|
|
1541
|
+
return {table.name.lower() for table in node.find_all(exp.Table) if skip is None or not _within(table, skip)}
|