sqlassert 0.3.3__py3-none-any.whl → 0.4.1__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/__init__.py +1 -2
- sqlassert/check.py +88 -13
- sqlassert/diagnostics.py +17 -6
- sqlassert/dialects.py +437 -7
- sqlassert/discovery/bigquery.py +3 -1
- sqlassert/discovery/databricks.py +25 -2
- sqlassert/discovery/duckdb.py +49 -7
- sqlassert/discovery/fetcher.py +130 -21
- sqlassert/discovery/information_schema.py +30 -2
- sqlassert/discovery/mysql.py +22 -1
- sqlassert/discovery/postgres.py +22 -5
- sqlassert/discovery/redshift.py +3 -2
- sqlassert/discovery/snowflake.py +3 -0
- sqlassert/discovery/trino.py +2 -2
- sqlassert/hazards.py +248 -87
- sqlassert/ir/__init__.py +4 -1
- sqlassert/ir/convert/__init__.py +13 -0
- sqlassert/ir/convert/aggregation.py +439 -0
- sqlassert/ir/convert/builtins.py +140 -0
- sqlassert/ir/convert/expressions.py +572 -0
- sqlassert/ir/convert/joins.py +264 -0
- sqlassert/ir/convert/markers.py +249 -0
- sqlassert/ir/convert/parser.py +253 -0
- sqlassert/ir/convert/queries.py +259 -0
- sqlassert/ir/convert/schema.py +606 -0
- sqlassert/ir/convert/scopes.py +205 -0
- sqlassert/ir/convert/selects.py +337 -0
- sqlassert/ir/convert/shared.py +429 -0
- sqlassert/ir/convert/sources.py +432 -0
- sqlassert/ir/convert/subqueries.py +364 -0
- sqlassert/ir/convert/value_types.py +223 -0
- sqlassert/ir/convert/windows.py +275 -0
- sqlassert/ir/model.py +125 -47
- sqlassert/ir/names.py +63 -0
- sqlassert/properties.py +12 -1
- sqlassert/provenance.py +5 -1
- sqlassert/python_engine.py +104 -44
- sqlassert/reporting.py +33 -32
- sqlassert/rewrites.py +111 -61
- sqlassert/rules/STYLEGUIDE.md +3 -2
- sqlassert/rules/causes/__init__.py +41 -0
- sqlassert/rules/causes/coverage.py +113 -0
- sqlassert/rules/causes/domain.py +123 -0
- sqlassert/rules/causes/joins.py +73 -0
- sqlassert/rules/causes/nulls.py +154 -0
- sqlassert/rules/causes/unique.py +523 -0
- sqlassert/rules/domain.py +8 -7
- sqlassert/rules/equality.py +6 -147
- sqlassert/rules/exactly_one.py +2 -1
- sqlassert/rules/foreign_key.py +8 -9
- sqlassert/rules/join_cardinality.py +282 -41
- sqlassert/rules/nullability.py +5 -5
- sqlassert/rules/uniqueness.py +171 -47
- sqlassert/rules/value_typing.py +337 -0
- sqlassert/sql_parse.py +28 -1
- sqlassert/suggest.py +11 -15
- sqlassert-0.4.1.dist-info/METADATA +235 -0
- sqlassert-0.4.1.dist-info/RECORD +69 -0
- sqlassert/ir/convert.py +0 -3509
- sqlassert-0.3.3.dist-info/METADATA +0 -807
- sqlassert-0.3.3.dist-info/RECORD +0 -46
- {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/WHEEL +0 -0
- {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/entry_points.txt +0 -0
- {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/licenses/LICENSE +0 -0
- {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/top_level.txt +0 -0
sqlassert/hazards.py
CHANGED
|
@@ -14,17 +14,21 @@ the proof that would have pinned it, which failed:
|
|
|
14
14
|
aggregate counts, `min` and `max` included: the join is wrong either way.
|
|
15
15
|
`count(*)` has no argument, so only a many-to-many join is a trap for it.
|
|
16
16
|
Silent when the input whose rows are repeated has no known Unique Set.
|
|
17
|
-
- A
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
17
|
+
- A Lossy Comparison: an equality (`=`, `<>`, `IS [NOT] DISTINCT FROM`, an
|
|
18
|
+
IN list or subquery) that is not an `exact_comparison`
|
|
19
|
+
(`rules/value_typing.py`), because a float is on either side, whatever the
|
|
20
|
+
other side is (a column, an expression or a literal: floats round, and a
|
|
21
|
+
BIGINT beside a DOUBLE rounds too, so exact equality is wrong; which values
|
|
22
|
+
a float holds exactly is no rule to rely on), or because text, a string
|
|
23
|
+
literal included, is compared with a number or, for text that is not a
|
|
24
|
+
literal, with any other known type: the text is cast, so different strings
|
|
25
|
+
may match one value (`'01'` and `'1'` both equal 1), and no cardinality is
|
|
26
|
+
proved across it. Write the cast explicitly. The same in every dialect
|
|
27
|
+
(ADR 0007): where the engine raises on the cast instead, the SQL is wrong
|
|
28
|
+
either way. In a join's ON, a WHERE or HAVING, and the correlation of an IN
|
|
29
|
+
or EXISTS subquery (its semi or anti join). Silent for an ordering (`<`,
|
|
30
|
+
`>`), text against an operand whose type is unknown, and a string literal
|
|
31
|
+
beside a date, time or timestamp, which SQL has no other way to write.
|
|
28
32
|
- A scalar subquery not proved to return at most one row (issue 38): more
|
|
29
33
|
than one is a runtime error. Uncorrelated, its body must have at most one
|
|
30
34
|
row; correlated, the columns its WHERE binds must reach its Row Identity.
|
|
@@ -33,9 +37,35 @@ the proof that would have pinned it, which failed:
|
|
|
33
37
|
non-null (the `LEFT JOIN ... IS NULL` form of it), an `EXCEPT` whose left
|
|
34
38
|
rows all appear on the right. Whether the key is enforced is not asked:
|
|
35
39
|
sqlassert trusts every key the SQL states.
|
|
40
|
+
- A CASE (or IF) whose results have different declared types: the engine
|
|
41
|
+
casts them to a common type, and the cast may lose what told values apart
|
|
42
|
+
(`'01'` and `'1'` both become 1). Integer types only widen. A result whose
|
|
43
|
+
type is not known (a numeric literal, an expression) is left out.
|
|
36
44
|
- A GROUP BY key the Select does not return, when the keys it returns do not
|
|
37
45
|
determine it: output rows told apart only by a value not shown look like
|
|
38
46
|
duplicates. Silent for the values of an IN, EXISTS or scalar subquery.
|
|
47
|
+
- A strange construct, one the SQL standard rejects or that no author means,
|
|
48
|
+
which sqlassert lowers opaque or as a row subset: a star in a GROUP BY
|
|
49
|
+
select (the star selects columns that are neither grouped nor aggregated;
|
|
50
|
+
whatever the star selects and DuckDB's `GROUP BY ALL` included), a QUALIFY
|
|
51
|
+
beside an aggregate without GROUP BY (it keeps or drops the one result
|
|
52
|
+
row), and a constant PARTITION BY key in any window of the Select, in its
|
|
53
|
+
list, QUALIFY or ORDER BY (a literal is one partition). Read from the
|
|
54
|
+
syntax, so they are reported wherever the Select is, with no proof to fail.
|
|
55
|
+
- A name a Select outputs more than once (`SELECT *, 1 AS w` over a table
|
|
56
|
+
with a column `w`), when its output columns are all known: a reference by
|
|
57
|
+
the name reads only the first, and the engine renames the others (DuckDB's
|
|
58
|
+
`w_1`) or rejects them. Read from the lowered output columns, for every
|
|
59
|
+
reachable Select whose rows are read (not an IN, EXISTS or scalar
|
|
60
|
+
subquery's): the root's names reach its consumer, a derived table's are
|
|
61
|
+
renamed. A star that cannot be expanded leaves the names unknown, and the
|
|
62
|
+
Select is left alone.
|
|
63
|
+
|
|
64
|
+
The last operand of a set operation ends where the whole query does, so it has
|
|
65
|
+
no Attachment Site of its own: its select-level Hazards (all of the above that
|
|
66
|
+
are read from one Select) are reported at the query's site, with the message
|
|
67
|
+
starting "in the last operand of UNION ALL:" (its operator). A parenthesised
|
|
68
|
+
operand has a site and reports there.
|
|
39
69
|
|
|
40
70
|
A hazard is reported only when sqlassert sees the whole Select Expression; an
|
|
41
71
|
`ORDER BY` key it cannot map to a selected column keeps it silent.
|
|
@@ -43,8 +73,9 @@ A hazard is reported only when sqlassert sees the whole Select Expression; an
|
|
|
43
73
|
|
|
44
74
|
from __future__ import annotations
|
|
45
75
|
|
|
76
|
+
from collections import Counter
|
|
46
77
|
from collections.abc import Callable, Iterable
|
|
47
|
-
from dataclasses import dataclass
|
|
78
|
+
from dataclasses import dataclass, replace
|
|
48
79
|
from enum import Enum
|
|
49
80
|
from typing import ClassVar
|
|
50
81
|
|
|
@@ -52,16 +83,19 @@ from sqlglot import exp
|
|
|
52
83
|
|
|
53
84
|
from sqlassert.diagnostics import quoted, quoted_all
|
|
54
85
|
from sqlassert import ir
|
|
55
|
-
from sqlassert.ir.convert import
|
|
56
|
-
from sqlassert.
|
|
86
|
+
from sqlassert.ir.convert import IrConversionResult
|
|
87
|
+
from sqlassert.ir.convert.aggregation import HIDDEN_GROUPING
|
|
88
|
+
from sqlassert.ir.convert.shared import _projection_star
|
|
89
|
+
from sqlassert.ir.convert.windows import _aggregates, _constant_partition_keys
|
|
90
|
+
from sqlassert.rewrites import SuggestType
|
|
57
91
|
from sqlassert.provenance import AttachmentSite
|
|
58
92
|
from sqlassert.python_engine import Arena, Result
|
|
59
|
-
from sqlassert.rules.
|
|
93
|
+
from sqlassert.rules.value_typing import _identity_comparison, exact_comparison, scalar_typing
|
|
60
94
|
from sqlassert.rules.join_cardinality import _at_most_one_match, many_to_one_join, one_to_many_join, unique_join
|
|
61
95
|
from sqlassert.properties import NonNullColumn, NonNullColumns, ReferentialCoverage
|
|
62
96
|
from sqlassert.rules.exactly_one import _cross_equalities
|
|
63
97
|
from sqlassert.rules.uniqueness import _closure, _reaches_row_identity, minimal_keys
|
|
64
|
-
from sqlassert.sql_parse import
|
|
98
|
+
from sqlassert.sql_parse import assertion_span
|
|
65
99
|
|
|
66
100
|
|
|
67
101
|
class Concern(Enum):
|
|
@@ -69,11 +103,15 @@ class Concern(Enum):
|
|
|
69
103
|
FAN_TRAP = "Fan trap"
|
|
70
104
|
CHASM_TRAP = "Chasm trap"
|
|
71
105
|
SCALAR_SUBQUERY = "Scalar subquery"
|
|
72
|
-
|
|
73
|
-
FLOAT_EQUALITY = "Float equality"
|
|
106
|
+
LOSSY_COMPARISON = "Lossy comparison"
|
|
74
107
|
ALWAYS_EMPTY = "Always empty"
|
|
75
108
|
MANY_TO_MANY = "Many-to-many join"
|
|
76
109
|
UNSELECTED_GROUPING = "Grouping key not selected"
|
|
110
|
+
MIXED_CASE = "Mixed CASE types"
|
|
111
|
+
STAR_IN_GROUPING = "Star with GROUP BY"
|
|
112
|
+
QUALIFY_BESIDE_AGGREGATE = "QUALIFY beside an aggregate"
|
|
113
|
+
CONSTANT_PARTITION = "Constant partition key"
|
|
114
|
+
DUPLICATE_OUTPUT_NAME = "Duplicate output name"
|
|
77
115
|
|
|
78
116
|
|
|
79
117
|
@dataclass(frozen=True)
|
|
@@ -88,41 +126,61 @@ class Hazard:
|
|
|
88
126
|
|
|
89
127
|
|
|
90
128
|
def hazards(
|
|
91
|
-
|
|
92
|
-
wanted: Callable[[AttachmentSite], bool] = lambda site: True,
|
|
129
|
+
conversion: IrConversionResult, arena: Arena, wanted: Callable[[AttachmentSite], bool] = lambda site: True,
|
|
93
130
|
) -> list[Hazard]:
|
|
94
|
-
"""Every Hazard in `
|
|
95
|
-
syntax =
|
|
96
|
-
compared: set[ir.ScalarExpr] = set() # Comparisons already checked for a
|
|
131
|
+
"""Every Hazard in `conversion`'s Program at a site `wanted` accepts, in source order. `arena` must be active."""
|
|
132
|
+
program, syntax = conversion.program, conversion.syntax
|
|
133
|
+
compared: set[ir.ScalarExpr] = set() # Comparisons already checked for a lossy comparison.
|
|
97
134
|
reachable = set(program.nodes())
|
|
98
135
|
found: list[Hazard] = []
|
|
99
136
|
join_labels = {relation: site.label for site, relation in program.attachment_sites if isinstance(relation, ir.Join)}
|
|
100
137
|
deduplicated = _deduplicated_joins(program)
|
|
101
|
-
|
|
138
|
+
|
|
139
|
+
def select_hazards(site: AttachmentSite, relation: ir.RelationExpr | ir.SimpleCase, node: exp.Join | exp.Select | None) -> list[Hazard]:
|
|
140
|
+
"""The Hazards of the Select `node`, whose relation is `relation` and whose site is `site`."""
|
|
141
|
+
found: list[Hazard] = []
|
|
142
|
+
aggregate = relation.input if isinstance(relation, ir.Limit) else relation
|
|
143
|
+
grouped = _grouped(aggregate)
|
|
144
|
+
if grouped is not None and grouped in reachable:
|
|
145
|
+
found.extend(_traps(site, grouped, join_labels))
|
|
146
|
+
if site.trailing and isinstance(node, exp.Select) and _rows_are_read(node) and not _has_star(node):
|
|
147
|
+
found.extend(_unselected_grouping(site, grouped)) # A star may select the key.
|
|
148
|
+
if site.trailing and aggregate in reachable and isinstance(node, exp.Select):
|
|
149
|
+
found.extend(_strange_constructs(site, node))
|
|
150
|
+
if not isinstance(aggregate, ir.SimpleCase) and _rows_are_read(node):
|
|
151
|
+
found.extend(_duplicate_output_names(site, aggregate, node, program))
|
|
152
|
+
if site.trailing and aggregate in reachable and not isinstance(aggregate, ir.SimpleCase):
|
|
153
|
+
found.extend(_always_empty(site, aggregate, arena))
|
|
154
|
+
found.extend(_lossy_comparisons(site, _filter_conjuncts(aggregate), compared))
|
|
155
|
+
return found
|
|
156
|
+
|
|
102
157
|
for site, relation in program.attachment_sites:
|
|
103
158
|
if not wanted(site):
|
|
104
159
|
continue
|
|
105
|
-
node = syntax.get(
|
|
160
|
+
node = syntax.get(site)
|
|
161
|
+
aggregate = relation.input if isinstance(relation, ir.Limit) else relation
|
|
106
162
|
if isinstance(relation, ir.Limit) and relation in reachable and isinstance(node, exp.Select):
|
|
107
|
-
found.extend(_arbitrary_limit(site, relation, sort_keys.get(site)))
|
|
163
|
+
found.extend(_arbitrary_limit(site, relation, conversion.sort_keys.get(site)))
|
|
108
164
|
if isinstance(relation, ir.Join) and relation in reachable and not site.trailing:
|
|
109
|
-
found.extend(
|
|
110
|
-
found.extend(_float_equalities(site, relation.conjuncts, compared, dialect))
|
|
165
|
+
found.extend(_lossy_comparisons(site, relation.conjuncts, compared))
|
|
111
166
|
if isinstance(node, exp.Join) and assertion_span(node) is None and relation not in deduplicated:
|
|
112
167
|
found.extend(_many_to_many(site, relation))
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
for site, operation in program.set_operations:
|
|
168
|
+
if not isinstance(aggregate, ir.SetOperation): # The Select at a set operation's end is its last operand: below.
|
|
169
|
+
found.extend(select_hazards(site, relation, node))
|
|
170
|
+
for site, operand, operator in conversion.last_operands:
|
|
171
|
+
if wanted(site):
|
|
172
|
+
found.extend(
|
|
173
|
+
replace(hazard, message=f"in the last operand of {operator}: {hazard.message}")
|
|
174
|
+
for hazard in select_hazards(site, operand, syntax.get(site))
|
|
175
|
+
)
|
|
176
|
+
for site, operation in conversion.set_operations:
|
|
123
177
|
if operation in reachable and wanted(site) and operation.operator == "except":
|
|
124
178
|
found.extend(_empty_except(site, operation, arena))
|
|
125
|
-
for site,
|
|
179
|
+
for site, mixed in conversion.mixed_cases:
|
|
180
|
+
if wanted(site):
|
|
181
|
+
message = f"{mixed}: the engine casts the results to a common type, which may lose what told values apart; cast each result explicitly"
|
|
182
|
+
found.append(Hazard(site, Concern.MIXED_CASE, message, Result(False, "The results of a CASE have different types")))
|
|
183
|
+
for site, join in conversion.scalar_subqueries:
|
|
126
184
|
if join in reachable and wanted(site):
|
|
127
185
|
found.extend(_scalar_subquery(site, join))
|
|
128
186
|
return sorted(found, key=lambda item: item.site.offset)
|
|
@@ -144,9 +202,104 @@ def _rows_are_read(select: exp.Select) -> bool:
|
|
|
144
202
|
if select.find_ancestor(exp.In, exp.Exists) is not None:
|
|
145
203
|
return False
|
|
146
204
|
subquery = select.find_ancestor(exp.Subquery)
|
|
205
|
+
while subquery is not None and isinstance(subquery.parent, exp.SetOperation):
|
|
206
|
+
subquery = subquery.find_ancestor(exp.Subquery) # A parenthesised operand: its rows are the set operation's.
|
|
147
207
|
return subquery is None or isinstance(subquery.parent, exp.From | exp.Join)
|
|
148
208
|
|
|
149
209
|
|
|
210
|
+
def _has_star(select: exp.Select) -> bool:
|
|
211
|
+
return any(_projection_star(item) is not None for item in select.expressions)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _strange_constructs(site: AttachmentSite, select: exp.Select) -> list[Hazard]:
|
|
215
|
+
"""The constructs `select` is written with that are odd whatever the
|
|
216
|
+
schema: a star beside GROUP BY, a QUALIFY beside an aggregate without
|
|
217
|
+
GROUP BY, and a constant PARTITION BY key in a window of any clause.
|
|
218
|
+
Each is read from the syntax."""
|
|
219
|
+
found: list[Hazard] = []
|
|
220
|
+
group, qualify = select.args.get("group"), select.args.get("qualify")
|
|
221
|
+
if isinstance(group, exp.Group) and _has_star(select):
|
|
222
|
+
message = (
|
|
223
|
+
"SELECT * with GROUP BY selects every column, and the SQL standard rejects any that is neither grouped nor aggregated. "
|
|
224
|
+
"This is probably a mistake: list the grouped columns and the aggregates instead of the star"
|
|
225
|
+
)
|
|
226
|
+
found.append(Hazard(site, Concern.STAR_IN_GROUPING, message, Result(True, "a star is selected beside GROUP BY")))
|
|
227
|
+
if isinstance(qualify, exp.Qualify) and group is None and _aggregates(select):
|
|
228
|
+
message = (
|
|
229
|
+
"QUALIFY beside an aggregate without GROUP BY filters the one row the aggregate returns, keeping it or dropping it. "
|
|
230
|
+
"This is probably a mistake: filter it with HAVING, or GROUP BY a key to rank the groups"
|
|
231
|
+
)
|
|
232
|
+
found.append(Hazard(site, Concern.QUALIFY_BESIDE_AGGREGATE, message, Result(True, "QUALIFY filters the one row of a scalar aggregate")))
|
|
233
|
+
for key in _constant_partition_keys(select, select):
|
|
234
|
+
message = (
|
|
235
|
+
f"PARTITION BY {key.sql()} is a constant, so every row is in one partition and the window partitions nothing. "
|
|
236
|
+
"This is probably a mistake: partition by a column, or drop PARTITION BY"
|
|
237
|
+
)
|
|
238
|
+
found.append(Hazard(site, Concern.CONSTANT_PARTITION, message, Result(True, "a window partitions by a constant")))
|
|
239
|
+
return found
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _duplicate_output_names(site: AttachmentSite, relation: ir.RelationExpr, select: exp.Select, program: ir.Program) -> list[Hazard]:
|
|
243
|
+
"""The names `select` outputs more than once, when its output columns are
|
|
244
|
+
all known: a star left as one `*` column (its input's columns are unknown,
|
|
245
|
+
or it is beside GROUP BY) leaves them unknown, and no name is reported.
|
|
246
|
+
A later reference by that name reads only the first, best effort, as the
|
|
247
|
+
engine's renamed repeats do (DuckDB's `w_1`; `ir/names.py`). A repeat
|
|
248
|
+
that a star only carries on from a relation that already repeats the
|
|
249
|
+
name was reported there, so a name is reported only where some column of
|
|
250
|
+
it is new. `*` is no name: it is the
|
|
251
|
+
column a star or `count(*)` is written as, and the engine names it itself."""
|
|
252
|
+
if not relation.is_schema_complete or (_has_star(select) and any(column.name == "*" for column in relation.output_columns)):
|
|
253
|
+
return []
|
|
254
|
+
if isinstance(relation, ir.Alias):
|
|
255
|
+
return [] # A bare star over a derived table outputs its names: a repeat is its select's to report.
|
|
256
|
+
if not _names_read(select):
|
|
257
|
+
return []
|
|
258
|
+
named = [column for column in relation.output_columns if column.name and column.name != "*"]
|
|
259
|
+
counts = Counter(column.name.lower() for column in named)
|
|
260
|
+
repeated = tuple(column for column in named if counts[column.name.lower()] > 1)
|
|
261
|
+
new = {column.name.lower() for column in repeated if not _carried_repeat(column, program)}
|
|
262
|
+
repeated = tuple(column for column in repeated if column.name.lower() in new)
|
|
263
|
+
names = list({column.name.lower(): column.name for column in reversed(repeated)}.values())[::-1] # Each once, as first written.
|
|
264
|
+
if not names:
|
|
265
|
+
return []
|
|
266
|
+
subject = f"name {quoted(names[0])}" if len(names) == 1 else f"names {quoted_all(names)}"
|
|
267
|
+
message = (
|
|
268
|
+
f"this SELECT outputs {subject} more than once: a reference by {'that name' if len(names) == 1 else 'those names'} reads only the first, "
|
|
269
|
+
"and the engine renames the others (DuckDB appends _1, _2, ...) or rejects them. Alias each output column with a name of its own"
|
|
270
|
+
)
|
|
271
|
+
return [Hazard(site, Concern.DUPLICATE_OUTPUT_NAME, message, Result(True, "an output name repeats", repeated))]
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _carried_repeat(column: ir.OutputColumn, program: ir.Program) -> bool:
|
|
275
|
+
"""Whether `column` passes on, under its name and through pass-through
|
|
276
|
+
stages, a column of a derived table that repeats that name."""
|
|
277
|
+
name = column.name.lower()
|
|
278
|
+
while isinstance(reference := column.scalar_expr, ir.ColumnRef) and reference.column.name.lower() == name:
|
|
279
|
+
column = reference.column
|
|
280
|
+
parent = program.column_to_parent_relation_index.get(column)
|
|
281
|
+
if isinstance(parent, ir.Alias):
|
|
282
|
+
return sum(other.name.lower() == name for other in parent.output_columns) > 1
|
|
283
|
+
return False
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def _names_read(select: exp.Select) -> bool:
|
|
287
|
+
"""Whether anything reads `select`'s output names. A positional set
|
|
288
|
+
operation (UNION, EXCEPT, INTERSECT) takes its names from its first
|
|
289
|
+
operand and pairs the others by position, so a later operand's names are
|
|
290
|
+
never read; `BY NAME` pairs them by name, so every operand's are."""
|
|
291
|
+
node: exp.Expr = select
|
|
292
|
+
while True:
|
|
293
|
+
parent = node.parent
|
|
294
|
+
while isinstance(parent, exp.Subquery | exp.Paren):
|
|
295
|
+
node, parent = parent, parent.parent
|
|
296
|
+
if not isinstance(parent, exp.SetOperation):
|
|
297
|
+
return True
|
|
298
|
+
if parent.expression is node and not parent.args.get("by_name"):
|
|
299
|
+
return False
|
|
300
|
+
node = parent
|
|
301
|
+
|
|
302
|
+
|
|
150
303
|
def _unselected_grouping(site: AttachmentSite, aggregate: ir.Aggregate) -> list[Hazard]:
|
|
151
304
|
"""GROUP BY keys the Select does not return, when the keys it returns do
|
|
152
305
|
not determine them: two output rows may then be equal, told apart only by
|
|
@@ -214,7 +367,7 @@ def _every_row_matches(join: ir.Join, arena: Arena) -> Result[bool]:
|
|
|
214
367
|
def _empty_except(site: AttachmentSite, operation: ir.SetOperation, arena: Arena) -> list[Hazard]:
|
|
215
368
|
"""`A EXCEPT B` where every row of A, non-null, appears in B."""
|
|
216
369
|
left, right = operation.left.output_columns, operation.right.output_columns
|
|
217
|
-
if not operation.distinct or operation.
|
|
370
|
+
if not operation.distinct or operation.unpaired or len(left) != len(right):
|
|
218
371
|
return []
|
|
219
372
|
proof = arena.prove(ReferentialCoverage(columns=left, referenced_columns=right)) & arena.prove(NonNullColumns(columns=frozenset(left)))
|
|
220
373
|
if not proof.value:
|
|
@@ -283,26 +436,6 @@ def _equates_a_key(join: ir.Join, side: ir.RelationExpr, other: ir.RelationExpr)
|
|
|
283
436
|
return any(set(key) <= equated for key in minimal_keys(side))
|
|
284
437
|
|
|
285
438
|
|
|
286
|
-
def _implicit_casts(site: AttachmentSite, join: ir.Join) -> list[Hazard]:
|
|
287
|
-
"""Each ON equality between a text column and a column of another known type."""
|
|
288
|
-
found = []
|
|
289
|
-
for conjunct in join.conjuncts:
|
|
290
|
-
match conjunct:
|
|
291
|
-
case ir.Equality(left=ir.ColumnRef(column=first), right=ir.ColumnRef(column=second)):
|
|
292
|
-
types = (_comparison_type(first).value, _comparison_type(second).value)
|
|
293
|
-
if None in types or _binary_text(first).value == _binary_text(second).value:
|
|
294
|
-
continue
|
|
295
|
-
message = (
|
|
296
|
-
f"{quoted(first.name)} ({types[0]}) = {quoted(second.name)} ({types[1]}) compares text with another type: the text is cast, "
|
|
297
|
-
"so different strings may match one value ('01' and '1' both equal 1): cast explicitly"
|
|
298
|
-
)
|
|
299
|
-
evidence = Result(False, "The comparison casts text", (conjunct,))
|
|
300
|
-
found.append(Hazard(site, Concern.IMPLICIT_CAST, message, evidence))
|
|
301
|
-
case _:
|
|
302
|
-
pass
|
|
303
|
-
return found
|
|
304
|
-
|
|
305
|
-
|
|
306
439
|
def _filter_conjuncts(relation: ir.RelationExpr) -> list[ir.ScalarExpr]:
|
|
307
440
|
"""The conjuncts of a Select's WHERE and HAVING, and of the semi and anti
|
|
308
441
|
joins its IN and EXISTS subqueries are, from its result down to its FROM."""
|
|
@@ -321,17 +454,14 @@ def _filter_conjuncts(relation: ir.RelationExpr) -> list[ir.ScalarExpr]:
|
|
|
321
454
|
return found
|
|
322
455
|
|
|
323
456
|
|
|
324
|
-
_FLOATS = {exp.DataType.Type.FLOAT, exp.DataType.Type.DOUBLE, exp.DataType.Type.UDOUBLE}
|
|
325
|
-
|
|
326
457
|
# Call names that compare for equality, as their operands' values.
|
|
327
458
|
_EQUALITY_CALLS = {"<>", "IS DISTINCT FROM"}
|
|
328
459
|
|
|
329
460
|
|
|
330
|
-
def
|
|
331
|
-
site: AttachmentSite, conjuncts: Iterable[ir.ScalarExpr], compared: set[ir.ScalarExpr], dialect: str,
|
|
332
|
-
) -> list[Hazard]:
|
|
461
|
+
def _lossy_comparisons(site: AttachmentSite, conjuncts: Iterable[ir.ScalarExpr], compared: set[ir.ScalarExpr]) -> list[Hazard]:
|
|
333
462
|
"""Each equality in `conjuncts`, at any depth (`x = 1 OR y = 2` is two),
|
|
334
|
-
|
|
463
|
+
that compares typed operands lossily (`_lossy_pair`); an IN list compares
|
|
464
|
+
its operand with each value."""
|
|
335
465
|
found = []
|
|
336
466
|
pending = list(conjuncts)
|
|
337
467
|
while pending:
|
|
@@ -341,35 +471,66 @@ def _float_equalities(
|
|
|
341
471
|
compared.add(node)
|
|
342
472
|
match node:
|
|
343
473
|
case ir.Equality(left=left, right=right) | ir.NullSafeEquality(left=left, right=right):
|
|
344
|
-
|
|
474
|
+
pairs = [(left, right)]
|
|
345
475
|
case ir.Call(function=function, arguments=(left, right)) if function.name in _EQUALITY_CALLS:
|
|
346
|
-
|
|
476
|
+
pairs = [(left, right)]
|
|
347
477
|
case ir.InList(operand=operand, values=values):
|
|
348
|
-
|
|
478
|
+
pairs = [(operand, value) for value in values]
|
|
349
479
|
case _:
|
|
350
480
|
pending.extend(child for child in ir.children(node) if isinstance(child, ir.ScalarExpr))
|
|
351
481
|
continue
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
found.append(Hazard(site, Concern.FLOAT_EQUALITY, message, evidence))
|
|
482
|
+
for left, right in pairs:
|
|
483
|
+
if (reason := _lossy_pair(left, right)) is None:
|
|
484
|
+
continue
|
|
485
|
+
written = node.origin.detail
|
|
486
|
+
for operand in (left, right):
|
|
487
|
+
if isinstance(operand, ir.ColumnRef) and operand.origin.detail.startswith("__having."):
|
|
488
|
+
written = written.replace(operand.origin.detail, operand.column.name) # HAVING reads the grouped columns.
|
|
489
|
+
message, why = reason
|
|
490
|
+
found.append(Hazard(site, Concern.LOSSY_COMPARISON, f"{written} is a lossy comparison: {message}", why))
|
|
491
|
+
break # One Hazard for the comparison.
|
|
363
492
|
return found
|
|
364
493
|
|
|
365
494
|
|
|
366
|
-
def
|
|
367
|
-
"""`
|
|
368
|
-
float or
|
|
369
|
-
|
|
370
|
-
|
|
495
|
+
def _lossy_pair(left: ir.ScalarExpr, right: ir.ScalarExpr) -> tuple[str, Result] | None:
|
|
496
|
+
"""Why `left = right` is lossy, with the failed `exact_comparison`: a
|
|
497
|
+
float on a side, whatever the other; or text against a number, or text
|
|
498
|
+
that is not a string literal against any other known type."""
|
|
499
|
+
first, second = scalar_typing(left).value, scalar_typing(right).value
|
|
500
|
+
exact = exact_comparison(left, right)
|
|
501
|
+
if exact.value:
|
|
371
502
|
return None
|
|
372
|
-
|
|
503
|
+
for operand, typing in ((left, first), (right, second)):
|
|
504
|
+
if typing is not None and typing.floating:
|
|
505
|
+
side = _described(operand)
|
|
506
|
+
return (
|
|
507
|
+
f"{side} is {typing.comparison_type}, a floating-point type, so values that differ may compare equal; "
|
|
508
|
+
"compare within a tolerance or use an exact type",
|
|
509
|
+
Result(False, f"{side} is {typing.comparison_type}, a floating-point type, compared for exact equality", (left, right), [exact]),
|
|
510
|
+
)
|
|
511
|
+
if first is None or second is None or first.text == second.text:
|
|
512
|
+
return None
|
|
513
|
+
(text, _), (other, other_typing) = ((left, first), (right, second)) if first.text else ((right, second), (left, first))
|
|
514
|
+
if _string_literal(text) and not other_typing.exact_numeric:
|
|
515
|
+
return None # A string literal beside a date, a boolean, a UUID: read as that type.
|
|
516
|
+
return (
|
|
517
|
+
f"{_described(text)} is text and {_described(other)} is {other_typing.comparison_type}: the text is cast, so different "
|
|
518
|
+
"strings may match one value ('01' and '1' both equal 1); cast explicitly",
|
|
519
|
+
Result(False, f"{_described(text)} is text compared with {other_typing.comparison_type}, which casts the text", (left, right), [exact]),
|
|
520
|
+
)
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
def _string_literal(operand: ir.ScalarExpr) -> bool:
|
|
524
|
+
return isinstance(operand, ir.Constant) and operand.value is not None and operand.value.type == "string"
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
def _described(operand: ir.ScalarExpr) -> str:
|
|
528
|
+
"""`operand` for a message: a column by name, else as written."""
|
|
529
|
+
match operand:
|
|
530
|
+
case ir.ColumnRef(column=column):
|
|
531
|
+
return quoted(column.name)
|
|
532
|
+
case _:
|
|
533
|
+
return operand.origin.detail
|
|
373
534
|
|
|
374
535
|
|
|
375
536
|
def _scalar_subquery(site: AttachmentSite, join: ir.Join) -> list[Hazard]:
|
|
@@ -565,7 +726,7 @@ def _arbitrary_limit(site: AttachmentSite, limit: ir.Limit, keys: tuple[ir.Outpu
|
|
|
565
726
|
|
|
566
727
|
def _ties_identical(column: ir.OutputColumn) -> bool:
|
|
567
728
|
"""Whether rows ORDER BY ties on `column` hold identical values of it."""
|
|
568
|
-
return _identity_comparison(column).value
|
|
729
|
+
return _identity_comparison(column).value
|
|
569
730
|
|
|
570
731
|
|
|
571
732
|
def _needed(column: ir.OutputColumn) -> frozenset[ir.OutputColumn] | None:
|
sqlassert/ir/__init__.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"""Relational intermediate representation."""
|
|
2
2
|
|
|
3
|
-
from sqlassert.ir.model import Accumulation, Aggregate, AggregateCall, Alias, And, AnyAggregate, AnyRelation, AnyScalar, Assertion, Builtin, BuiltinVariadic, Call, Coalesce, ColumnRef, Constant, Count, Distinct, Elements, Equality, Filter, InList, IsNotNull, IsNull, Join, JoinKind, Limit, NamedRelation, Node, NullLiteral, NullSafeEquality, OpaqueExpression, OpaquePureFunction, OpaqueRelation, Or, OutputColumn, Program, Project, QualifyByPartition, RecursiveRelation, RelationExpr, RelationRole, ScalarExpr, SetOperation, SimpleCase, LiteralValue, SetOperator, children, conjuncts, determinants, injective_input, strict_inputs, total
|
|
3
|
+
from sqlassert.ir.model import Accumulation, Aggregate, AggregateCall, Alias, And, AnyAggregate, AnyRelation, AnyScalar, ArgumentTyping, Assertion, Builtin, BuiltinVariadic, Call, Coalesce, ColumnRef, Constant, Count, Distinct, Elements, Equality, Filter, InList, IsNotNull, IsNull, Join, JoinKind, Limit, NamedRelation, Node, NullLiteral, NullSafeEquality, OpaqueExpression, OpaquePureFunction, OpaqueRelation, Or, OutputColumn, Program, Project, QualifyByPartition, RecursiveRelation, RelationExpr, RelationRole, ScalarExpr, SetOperation, SimpleCase, ValuesList, ValueTyping, LiteralValue, SetOperator, children, conjuncts, determinants, injective_input, strict_inputs, total
|
|
4
4
|
|
|
5
5
|
__all__ = [
|
|
6
6
|
"Accumulation",
|
|
@@ -48,6 +48,9 @@ __all__ = [
|
|
|
48
48
|
"ScalarExpr",
|
|
49
49
|
"SetOperation",
|
|
50
50
|
"SetOperator",
|
|
51
|
+
"ValuesList",
|
|
52
|
+
"ValueTyping",
|
|
53
|
+
"ArgumentTyping",
|
|
51
54
|
"SimpleCase",
|
|
52
55
|
"children",
|
|
53
56
|
"conjuncts",
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""Link a parsed SQL program into the framework-independent relational IR.
|
|
2
|
+
|
|
3
|
+
Declaration and scope discovery happens before lowering. This gives table,
|
|
4
|
+
view, and CTE references compiler-like symbol resolution: every occurrence is
|
|
5
|
+
a fresh Alias, while all occurrences share one memoized NamedRelation.
|
|
6
|
+
|
|
7
|
+
The package lowers by responsibility: `parser.IrParser` is the driver, and
|
|
8
|
+
each mixin it inherits lowers one part of the SQL.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from sqlassert.ir.convert.parser import IrConversionResult, IrParser
|
|
12
|
+
|
|
13
|
+
__all__ = ["IrConversionResult", "IrParser"]
|