sqlassert 0.3.1__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.
Files changed (73) hide show
  1. sqlassert/__init__.py +1 -2
  2. sqlassert/__main__.py +2 -131
  3. sqlassert/check.py +98 -16
  4. sqlassert/diagnostics.py +31 -7
  5. sqlassert/dialects.py +504 -27
  6. sqlassert/discovery/bigquery.py +3 -1
  7. sqlassert/discovery/databricks.py +25 -2
  8. sqlassert/discovery/duckdb.py +61 -23
  9. sqlassert/discovery/fetcher.py +170 -45
  10. sqlassert/discovery/information_schema.py +34 -5
  11. sqlassert/discovery/mysql.py +22 -1
  12. sqlassert/discovery/postgres.py +28 -12
  13. sqlassert/discovery/redshift.py +3 -2
  14. sqlassert/discovery/snowflake.py +3 -0
  15. sqlassert/discovery/trino.py +2 -2
  16. sqlassert/edits.py +240 -0
  17. sqlassert/hazards.py +735 -0
  18. sqlassert/ir/__init__.py +6 -1
  19. sqlassert/ir/convert/__init__.py +13 -0
  20. sqlassert/ir/convert/aggregation.py +439 -0
  21. sqlassert/ir/convert/builtins.py +140 -0
  22. sqlassert/ir/convert/expressions.py +572 -0
  23. sqlassert/ir/convert/joins.py +264 -0
  24. sqlassert/ir/convert/markers.py +249 -0
  25. sqlassert/ir/convert/parser.py +253 -0
  26. sqlassert/ir/convert/queries.py +259 -0
  27. sqlassert/ir/convert/schema.py +606 -0
  28. sqlassert/ir/convert/scopes.py +205 -0
  29. sqlassert/ir/convert/selects.py +337 -0
  30. sqlassert/ir/convert/shared.py +429 -0
  31. sqlassert/ir/convert/sources.py +432 -0
  32. sqlassert/ir/convert/subqueries.py +364 -0
  33. sqlassert/ir/convert/value_types.py +223 -0
  34. sqlassert/ir/convert/windows.py +275 -0
  35. sqlassert/ir/model.py +247 -66
  36. sqlassert/ir/names.py +63 -0
  37. sqlassert/main.py +3 -9
  38. sqlassert/properties.py +12 -1
  39. sqlassert/provenance.py +5 -1
  40. sqlassert/python_engine.py +167 -50
  41. sqlassert/reporting.py +36 -32
  42. sqlassert/rewrites.py +1591 -0
  43. sqlassert/rules/STYLEGUIDE.md +3 -2
  44. sqlassert/rules/causes/__init__.py +41 -0
  45. sqlassert/rules/causes/coverage.py +113 -0
  46. sqlassert/rules/causes/domain.py +123 -0
  47. sqlassert/rules/causes/joins.py +73 -0
  48. sqlassert/rules/causes/nulls.py +154 -0
  49. sqlassert/rules/causes/unique.py +523 -0
  50. sqlassert/rules/domain.py +123 -26
  51. sqlassert/rules/equality.py +153 -85
  52. sqlassert/rules/exactly_one.py +42 -2
  53. sqlassert/rules/foreign_key.py +15 -13
  54. sqlassert/rules/join_cardinality.py +302 -39
  55. sqlassert/rules/nullability.py +244 -35
  56. sqlassert/rules/uniqueness.py +513 -86
  57. sqlassert/rules/value_typing.py +337 -0
  58. sqlassert/sql_parse.py +224 -90
  59. sqlassert/suggest.py +132 -57
  60. sqlassert-0.4.1.dist-info/METADATA +235 -0
  61. sqlassert-0.4.1.dist-info/RECORD +69 -0
  62. sqlassert-0.4.1.dist-info/entry_points.txt +2 -0
  63. sqlassert-0.4.1.dist-info/top_level.txt +2 -0
  64. sqlassert_cli.py +130 -0
  65. sqlassert/improvements.py +0 -528
  66. sqlassert/ir/convert.py +0 -2377
  67. sqlassert/smells.py +0 -306
  68. sqlassert-0.3.1.dist-info/METADATA +0 -725
  69. sqlassert-0.3.1.dist-info/RECORD +0 -44
  70. sqlassert-0.3.1.dist-info/entry_points.txt +0 -2
  71. sqlassert-0.3.1.dist-info/top_level.txt +0 -1
  72. {sqlassert-0.3.1.dist-info → sqlassert-0.4.1.dist-info}/WHEEL +0 -0
  73. {sqlassert-0.3.1.dist-info → sqlassert-0.4.1.dist-info}/licenses/LICENSE +0 -0
sqlassert/hazards.py ADDED
@@ -0,0 +1,735 @@
1
+ """Hazard suggestions: results the SQL leaves unspecified, from the Kossmann et al. 2022 triage (issue 15).
2
+
3
+ A Hazard is not a rewrite: the SQL may be what its author meant. It names a
4
+ place where the result depends on something the SQL does not pin down, and
5
+ the proof that would have pinned it, which failed:
6
+
7
+ - `LIMIT` or `OFFSET` whose `ORDER BY` does not strictly determine every
8
+ selected column (or that has no `ORDER BY`): rows tied on the sort keys come
9
+ in an arbitrary order, so which rows are kept may change from run to run
10
+ (Kossmann's "unstable sorting", read the other way round).
11
+ - An aggregate over a join that can repeat the rows its argument comes from
12
+ (issue 41): a fan trap when the join is many to many, a chasm trap when it
13
+ is one to many and the argument is on the side with one row per key. Every
14
+ aggregate counts, `min` and `max` included: the join is wrong either way.
15
+ `count(*)` has no argument, so only a many-to-many join is a trap for it.
16
+ Silent when the input whose rows are repeated has no known Unique Set.
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.
32
+ - A scalar subquery not proved to return at most one row (issue 38): more
33
+ than one is a runtime error. Uncorrelated, its body must have at most one
34
+ row; correlated, the columns its WHERE binds must reach its Row Identity.
35
+ - A query that can never return a row: a `NOT EXISTS` every row has a match
36
+ for (a foreign key's orphan check), a `WHERE x IS NULL` on a column proved
37
+ non-null (the `LEFT JOIN ... IS NULL` form of it), an `EXCEPT` whose left
38
+ rows all appear on the right. Whether the key is enforced is not asked:
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.
44
+ - A GROUP BY key the Select does not return, when the keys it returns do not
45
+ determine it: output rows told apart only by a value not shown look like
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.
69
+
70
+ A hazard is reported only when sqlassert sees the whole Select Expression; an
71
+ `ORDER BY` key it cannot map to a selected column keeps it silent.
72
+ """
73
+
74
+ from __future__ import annotations
75
+
76
+ from collections import Counter
77
+ from collections.abc import Callable, Iterable
78
+ from dataclasses import dataclass, replace
79
+ from enum import Enum
80
+ from typing import ClassVar
81
+
82
+ from sqlglot import exp
83
+
84
+ from sqlassert.diagnostics import quoted, quoted_all
85
+ from sqlassert import ir
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
91
+ from sqlassert.provenance import AttachmentSite
92
+ from sqlassert.python_engine import Arena, Result
93
+ from sqlassert.rules.value_typing import _identity_comparison, exact_comparison, scalar_typing
94
+ from sqlassert.rules.join_cardinality import _at_most_one_match, many_to_one_join, one_to_many_join, unique_join
95
+ from sqlassert.properties import NonNullColumn, NonNullColumns, ReferentialCoverage
96
+ from sqlassert.rules.exactly_one import _cross_equalities
97
+ from sqlassert.rules.uniqueness import _closure, _reaches_row_identity, minimal_keys
98
+ from sqlassert.sql_parse import assertion_span
99
+
100
+
101
+ class Concern(Enum):
102
+ ARBITRARY_LIMIT = "Arbitrary LIMIT"
103
+ FAN_TRAP = "Fan trap"
104
+ CHASM_TRAP = "Chasm trap"
105
+ SCALAR_SUBQUERY = "Scalar subquery"
106
+ LOSSY_COMPARISON = "Lossy comparison"
107
+ ALWAYS_EMPTY = "Always empty"
108
+ MANY_TO_MANY = "Many-to-many join"
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"
115
+
116
+
117
+ @dataclass(frozen=True)
118
+ class Hazard:
119
+ """A place whose result the SQL leaves unspecified, with the failed proof."""
120
+
121
+ site: AttachmentSite
122
+ concern: Concern
123
+ message: str
124
+ evidence: Result
125
+ suggest_type: ClassVar[SuggestType] = SuggestType.HAZARD
126
+
127
+
128
+ def hazards(
129
+ conversion: IrConversionResult, arena: Arena, wanted: Callable[[AttachmentSite], bool] = lambda site: True,
130
+ ) -> list[Hazard]:
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.
134
+ reachable = set(program.nodes())
135
+ found: list[Hazard] = []
136
+ join_labels = {relation: site.label for site, relation in program.attachment_sites if isinstance(relation, ir.Join)}
137
+ deduplicated = _deduplicated_joins(program)
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
+
157
+ for site, relation in program.attachment_sites:
158
+ if not wanted(site):
159
+ continue
160
+ node = syntax.get(site)
161
+ aggregate = relation.input if isinstance(relation, ir.Limit) else relation
162
+ if isinstance(relation, ir.Limit) and relation in reachable and isinstance(node, exp.Select):
163
+ found.extend(_arbitrary_limit(site, relation, conversion.sort_keys.get(site)))
164
+ if isinstance(relation, ir.Join) and relation in reachable and not site.trailing:
165
+ found.extend(_lossy_comparisons(site, relation.conjuncts, compared))
166
+ if isinstance(node, exp.Join) and assertion_span(node) is None and relation not in deduplicated:
167
+ found.extend(_many_to_many(site, relation))
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:
177
+ if operation in reachable and wanted(site) and operation.operator == "except":
178
+ found.extend(_empty_except(site, operation, arena))
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:
184
+ if join in reachable and wanted(site):
185
+ found.extend(_scalar_subquery(site, join))
186
+ return sorted(found, key=lambda item: item.site.offset)
187
+
188
+
189
+ def _grouped(relation: ir.RelationExpr | ir.SimpleCase) -> ir.Aggregate | None:
190
+ """The Aggregate of a grouped Select, under its HAVING (a Filter) and the
191
+ Project that drops grouping keys it does not select."""
192
+ if isinstance(relation, ir.Project) and isinstance(relation.input, ir.Aggregate | ir.Filter):
193
+ relation = relation.input
194
+ if isinstance(relation, ir.Filter) and isinstance(relation.input, ir.Aggregate):
195
+ relation = relation.input
196
+ return relation if isinstance(relation, ir.Aggregate) else None
197
+
198
+
199
+ def _rows_are_read(select: exp.Select) -> bool:
200
+ """Whether `select`'s rows are a result, read as rows: not the values of
201
+ an IN, EXISTS or scalar subquery, where equal rows are no surprise."""
202
+ if select.find_ancestor(exp.In, exp.Exists) is not None:
203
+ return False
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.
207
+ return subquery is None or isinstance(subquery.parent, exp.From | exp.Join)
208
+
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
+
303
+ def _unselected_grouping(site: AttachmentSite, aggregate: ir.Aggregate) -> list[Hazard]:
304
+ """GROUP BY keys the Select does not return, when the keys it returns do
305
+ not determine them: two output rows may then be equal, told apart only by
306
+ a value not shown. Rarely what the author meant."""
307
+ hidden = [column for column in aggregate.grouping_outputs if column.name.startswith(HIDDEN_GROUPING)]
308
+ if not hidden:
309
+ return []
310
+ shown = frozenset(column for column in aggregate.grouping_outputs if column not in hidden)
311
+ if _reaches_row_identity(_closure(aggregate, shown, frozenset())).value:
312
+ return []
313
+ names = quoted_all(column.scalar_expr.origin.detail for column in hidden)
314
+ terms, verb, pronoun = ("term", "does", "it") if len(hidden) == 1 else ("terms", "do", "them")
315
+ message = (
316
+ f"GROUP BY {terms} {names} {verb} not appear in SELECT. This is probably a mistake: "
317
+ f"select {pronoun}, or drop {pronoun} from GROUP BY"
318
+ )
319
+ return [Hazard(site, Concern.UNSELECTED_GROUPING, message, Result(True, "a grouping key is not selected", tuple(hidden)))]
320
+
321
+
322
+ def _always_empty(site: AttachmentSite, relation: ir.RelationExpr, arena: Arena) -> list[Hazard]:
323
+ """A filter of this Select that keeps no row: an anti join every row
324
+ matches, or `x IS NULL` on a non-null x. A scalar aggregate still returns
325
+ its one row, so the walk stops there."""
326
+ while True:
327
+ match relation:
328
+ case ir.Aggregate(grouping_outputs=()):
329
+ return []
330
+ case ir.Project(input=source) | ir.Aggregate(input=source) | ir.Distinct(input=source) | ir.QualifyByPartition(input=source) | ir.Join(kind="semi", left=source):
331
+ relation = source
332
+ case ir.Join(kind="anti", left=source):
333
+ proof = _every_row_matches(relation, arena)
334
+ if proof.value:
335
+ message = (
336
+ "every row has a match in its NOT EXISTS subquery, which therefore removes every row: this "
337
+ "query never returns one (an orphan check a foreign key already guarantees)"
338
+ )
339
+ return [Hazard(site, Concern.ALWAYS_EMPTY, message, proof)]
340
+ relation = source
341
+ case ir.Filter(input=source):
342
+ for conjunct in relation.conjuncts:
343
+ match conjunct:
344
+ case ir.IsNull(operand=ir.ColumnRef(column=column)):
345
+ proof = arena.prove(NonNullColumn(column=column))
346
+ if proof.value:
347
+ message = f"{conjunct.origin.detail} is never TRUE ({quoted(column.name)} is never NULL), so this query never returns a row"
348
+ return [Hazard(site, Concern.ALWAYS_EMPTY, message, proof)]
349
+ case _:
350
+ pass
351
+ relation = source
352
+ case _:
353
+ return []
354
+
355
+
356
+ def _every_row_matches(join: ir.Join, arena: Arena) -> Result[bool]:
357
+ """Every left row of `join` has a right row its ON holds on: ON is only
358
+ equalities between the inputs, the left columns are non-null and covered
359
+ by the right ones (the at-least-one half of an Exactly One Join)."""
360
+ pairs, others = _cross_equalities(join)
361
+ if not pairs or others:
362
+ return Result(False, "Only an ON of equalities between the inputs is known to match", (join,), kind="unknown")
363
+ lefts, rights = tuple(left for left, _ in pairs), tuple(right for _, right in pairs)
364
+ return arena.prove(ReferentialCoverage(columns=lefts, referenced_columns=rights)) & arena.prove(NonNullColumns(columns=frozenset(lefts)))
365
+
366
+
367
+ def _empty_except(site: AttachmentSite, operation: ir.SetOperation, arena: Arena) -> list[Hazard]:
368
+ """`A EXCEPT B` where every row of A, non-null, appears in B."""
369
+ left, right = operation.left.output_columns, operation.right.output_columns
370
+ if not operation.distinct or operation.unpaired or len(left) != len(right):
371
+ return []
372
+ proof = arena.prove(ReferentialCoverage(columns=left, referenced_columns=right)) & arena.prove(NonNullColumns(columns=frozenset(left)))
373
+ if not proof.value:
374
+ return []
375
+ message = "every row of the left input appears in the right one, so this EXCEPT never returns a row"
376
+ return [Hazard(site, Concern.ALWAYS_EMPTY, message, proof)]
377
+
378
+
379
+ def _many_to_many(site: AttachmentSite, join: ir.Join) -> list[Hazard]:
380
+ """A join with no marker that is not proved to repeat rows of at most one
381
+ input, both of whose inputs have a known Unique Set: it may repeat rows of
382
+ both. A many-to-many join is rare on purpose; an explicit CROSS JOIN is
383
+ one, so it is left alone, and a marker leaves the cardinality to `check`."""
384
+ if join.kind in ("semi", "anti", "cross"):
385
+ return []
386
+ proof = unique_join(join)
387
+ if proof.value or not (_has_unique_set(join.left) and _has_unique_set(join.right)):
388
+ return []
389
+ if _equates_a_key(join, join.left, join.right) or _equates_a_key(join, join.right, join.left):
390
+ return [] # A join on a key whose column types are unknown: a missing fact, not a hazard.
391
+ message = (
392
+ "this join is not proved to repeat rows of only one input: it may be many to many, repeating rows of both. "
393
+ "Join on a key of one input, or write the join marker you expect (/**ASSERT MANY TO ONE**/, ...) for check to prove"
394
+ )
395
+ return [Hazard(site, Concern.MANY_TO_MANY, message, proof)]
396
+
397
+
398
+ def _deduplicated_joins(program: ir.Program) -> set[ir.Join]:
399
+ """The joins in the FROM of a Select whose DISTINCT or GROUP BY merges
400
+ the rows they repeat: repeats never reach its result, and what they do to
401
+ an aggregate is a trap of its own."""
402
+ found: set[ir.Join] = set()
403
+ for site, relation in program.attachment_sites:
404
+ stage = relation.input if isinstance(relation, ir.Limit) else relation
405
+ if not site.trailing or not isinstance(stage, ir.Distinct | ir.Aggregate):
406
+ continue
407
+ pending = [stage.input]
408
+ while pending:
409
+ match pending.pop():
410
+ case ir.Join(left=left, right=right) as join:
411
+ found.add(join)
412
+ pending += [left, right]
413
+ case ir.Filter(input=source):
414
+ pending.append(source)
415
+ case _:
416
+ pass
417
+ return found
418
+
419
+
420
+ def _equates_a_key(join: ir.Join, side: ir.RelationExpr, other: ir.RelationExpr) -> bool:
421
+ """Whether ON equates every column of a known key of `side` with a value
422
+ of the other input's row (a column, an expression of its columns such as
423
+ a FULL JOIN chain's `coalesce(a.k, b.k)`, or a constant), whatever their
424
+ types: the join is on that key, and only an unknown type or an
425
+ expression kept the proof from binding it."""
426
+ equated: set[ir.OutputColumn] = set()
427
+ for conjunct in join.conjuncts:
428
+ if not isinstance(conjunct, ir.Equality):
429
+ continue
430
+ for mine, theirs in ((conjunct.left, conjunct.right), (conjunct.right, conjunct.left)):
431
+ inputs = ir.determinants(theirs)
432
+ if isinstance(mine, ir.ColumnRef) and mine.column in side.output_columns and inputs is not None and (
433
+ set(inputs) <= set(other.output_columns)
434
+ ):
435
+ equated.add(mine.column)
436
+ return any(set(key) <= equated for key in minimal_keys(side))
437
+
438
+
439
+ def _filter_conjuncts(relation: ir.RelationExpr) -> list[ir.ScalarExpr]:
440
+ """The conjuncts of a Select's WHERE and HAVING, and of the semi and anti
441
+ joins its IN and EXISTS subqueries are, from its result down to its FROM."""
442
+ found: list[ir.ScalarExpr] = []
443
+ while True:
444
+ match relation:
445
+ case ir.Project(input=source) | ir.Aggregate(input=source) | ir.Distinct(input=source) | ir.QualifyByPartition(input=source):
446
+ relation = source
447
+ case ir.Filter(input=source):
448
+ found.extend(relation.conjuncts)
449
+ relation = source
450
+ case ir.Join(kind="semi" | "anti", left=source):
451
+ found.extend(relation.conjuncts)
452
+ relation = source
453
+ case _:
454
+ return found
455
+
456
+
457
+ # Call names that compare for equality, as their operands' values.
458
+ _EQUALITY_CALLS = {"<>", "IS DISTINCT FROM"}
459
+
460
+
461
+ def _lossy_comparisons(site: AttachmentSite, conjuncts: Iterable[ir.ScalarExpr], compared: set[ir.ScalarExpr]) -> list[Hazard]:
462
+ """Each equality in `conjuncts`, at any depth (`x = 1 OR y = 2` is two),
463
+ that compares typed operands lossily (`_lossy_pair`); an IN list compares
464
+ its operand with each value."""
465
+ found = []
466
+ pending = list(conjuncts)
467
+ while pending:
468
+ node = pending.pop(0)
469
+ if node in compared:
470
+ continue
471
+ compared.add(node)
472
+ match node:
473
+ case ir.Equality(left=left, right=right) | ir.NullSafeEquality(left=left, right=right):
474
+ pairs = [(left, right)]
475
+ case ir.Call(function=function, arguments=(left, right)) if function.name in _EQUALITY_CALLS:
476
+ pairs = [(left, right)]
477
+ case ir.InList(operand=operand, values=values):
478
+ pairs = [(operand, value) for value in values]
479
+ case _:
480
+ pending.extend(child for child in ir.children(node) if isinstance(child, ir.ScalarExpr))
481
+ continue
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.
492
+ return found
493
+
494
+
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:
502
+ return None
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
534
+
535
+
536
+ def _scalar_subquery(site: AttachmentSite, join: ir.Join) -> list[Hazard]:
537
+ """A scalar subquery that may return more than one row.
538
+
539
+ Its join is many to one by construction (more rows fail the query), so
540
+ the question is asked of its body: uncorrelated, under the implied LIMIT
541
+ 1, whether the body has at most one row (the empty set is a Unique Set);
542
+ correlated, whether the columns ON binds reach the body's Row Identity."""
543
+ match join.right:
544
+ case ir.Limit(input=body) if join.predicate is None:
545
+ proof = _reaches_row_identity(_closure(body, frozenset(), frozenset()))
546
+ reason = "it is not proved to have at most one row"
547
+ case _:
548
+ proof = _at_most_one_match(join, "right")
549
+ reason = "the columns its WHERE binds to the outer row are not proved to be a Unique Set"
550
+ if proof.value:
551
+ return []
552
+ message = f"this scalar subquery may return more than one row, a runtime error: {reason}"
553
+ return [Hazard(site, Concern.SCALAR_SUBQUERY, message, proof)]
554
+
555
+
556
+ # Join traps ------------------------------------------------------------------
557
+
558
+
559
+ def _traps(site: AttachmentSite, aggregate: ir.Aggregate, join_labels: dict[ir.Join, str]) -> list[Hazard]:
560
+ """Each aggregate call whose input rows a join may repeat."""
561
+ found: list[Hazard] = []
562
+ for call in aggregate.calls:
563
+ inputs = [ir.determinants(argument) for argument in call.arguments]
564
+ if any(columns is None for columns in inputs):
565
+ continue # An argument whose columns are unknown.
566
+ columns = frozenset(column for columns in inputs if columns is not None for column in columns)
567
+ if not columns:
568
+ # `count(*)`, or a constant: it counts the input's rows.
569
+ for join, path, proof in _many_to_many_joins(aggregate.input, []):
570
+ if _unrepeated(aggregate.input, join.left, path) or _unrepeated(aggregate.input, join.right, path):
571
+ continue
572
+ message = (
573
+ f"{call.description} counts the rows of {_label(join, join_labels)}, which is not proved "
574
+ "to repeat rows of only one input (a fan trap): rows may be counted more than once"
575
+ )
576
+ found.append(Hazard(site, Concern.FAN_TRAP, message, proof))
577
+ continue
578
+ repeated = _repeating_join(aggregate.input, columns)
579
+ if repeated is None:
580
+ continue
581
+ join, side, path, proof = repeated
582
+ if _unrepeated(aggregate.input, side, path):
583
+ continue # A filter keeps one row per key after all (`WHERE o.id = 1`).
584
+ if unique_join(join).value:
585
+ concern, why = Concern.CHASM_TRAP, "is one to many, and the argument is on the side with one row per key"
586
+ else:
587
+ concern, why = Concern.FAN_TRAP, "is not proved to repeat rows of only one input"
588
+ message = (
589
+ f"{call.description} reads rows that {_label(join, join_labels)} may repeat: the join {why} "
590
+ f"({concern.value.lower()}), so a value may be counted more than once"
591
+ )
592
+ found.append(Hazard(site, concern, message, proof))
593
+ return found
594
+
595
+
596
+ def _repeating_join(
597
+ relation: ir.RelationExpr, columns: frozenset[ir.OutputColumn]
598
+ ) -> tuple[ir.Join, ir.RelationExpr, list[ir.RelationExpr], Result] | None:
599
+ """The first join, from `relation` down to the input `columns` come from,
600
+ not proved to keep that input's rows unrepeated: the join, that input,
601
+ the stages from `relation` down to the join, and the failed proof. None
602
+ when every join on the way is proved, or the columns cannot be traced to
603
+ one input of a join."""
604
+ path: list[ir.RelationExpr] = []
605
+ while True:
606
+ path.append(relation)
607
+ upstream = _upstream(relation, columns)
608
+ if upstream is None:
609
+ return None
610
+ match relation:
611
+ case ir.Join(kind="semi" | "anti"):
612
+ side = relation.left # It never repeats a row.
613
+ case ir.Join():
614
+ if upstream <= set(relation.left.output_columns):
615
+ side, proof = relation.left, many_to_one_join(relation)
616
+ elif upstream <= set(relation.right.output_columns):
617
+ side, proof = relation.right, one_to_many_join(relation)
618
+ else:
619
+ return None # The argument reads both inputs.
620
+ if not proof.value and _has_unique_set(side):
621
+ return relation, side, path, proof
622
+ case ir.Filter(input=side) | ir.Alias(source=side) | ir.Project(input=side) | ir.Limit(input=side):
623
+ pass
624
+ case ir.NamedRelation(body=ir.RelationExpr() as side):
625
+ pass
626
+ case _:
627
+ return None # A base table, or a stage that drops or merges rows.
628
+ if not upstream <= set(side.output_columns):
629
+ return None
630
+ relation, columns = side, upstream
631
+
632
+
633
+ def _many_to_many_joins(relation: ir.RelationExpr, path: list[ir.RelationExpr]):
634
+ """Each join under `relation` not proved to repeat rows of at most one
635
+ input, both of whose inputs have a known Unique Set, with the stages down
636
+ to it and the failed proof."""
637
+ path = [*path, relation]
638
+ match relation:
639
+ case ir.Join(kind="semi" | "anti", left=left):
640
+ yield from _many_to_many_joins(left, path)
641
+ case ir.Join(left=left, right=right):
642
+ proof = unique_join(relation)
643
+ if not proof.value and _has_unique_set(left) and _has_unique_set(right):
644
+ yield relation, path, proof
645
+ yield from _many_to_many_joins(left, path)
646
+ yield from _many_to_many_joins(right, path)
647
+ case ir.Filter(input=source) | ir.Alias(source=source) | ir.Project(input=source) | ir.Limit(input=source):
648
+ yield from _many_to_many_joins(source, path)
649
+ case ir.NamedRelation(body=ir.RelationExpr() as source):
650
+ yield from _many_to_many_joins(source, path)
651
+ case _:
652
+ pass
653
+
654
+
655
+ def _unrepeated(top: ir.RelationExpr, side: ir.RelationExpr, path: list[ir.RelationExpr]) -> bool:
656
+ """Whether a Unique Set of `side`, carried up `path` (the stages from
657
+ `top` down to the join `side` is an input of), is a Unique Set of `top`:
658
+ `side`'s rows are not repeated there after all."""
659
+ for key in minimal_keys(side):
660
+ lifted: list[ir.OutputColumn] = list(key)
661
+ for stage in reversed(path):
662
+ passed = {
663
+ output.scalar_expr.column: output for output in stage.output_columns if isinstance(output.scalar_expr, ir.ColumnRef)
664
+ }
665
+ if not all(column in passed for column in lifted):
666
+ break
667
+ lifted = [passed[column] for column in lifted]
668
+ else:
669
+ members = frozenset(lifted)
670
+ if _reaches_row_identity(_closure(top, members, members)).value:
671
+ return True
672
+ return False
673
+
674
+
675
+ def _upstream(relation: ir.RelationExpr, columns: frozenset[ir.OutputColumn]) -> frozenset[ir.OutputColumn] | None:
676
+ """The input columns `columns` of `relation` are computed from, if known."""
677
+ found: set[ir.OutputColumn] = set()
678
+ for column in columns:
679
+ inputs = ir.determinants(column.scalar_expr)
680
+ if inputs is None:
681
+ return None
682
+ found.update(inputs)
683
+ return frozenset(found)
684
+
685
+
686
+ def _has_unique_set(relation: ir.RelationExpr) -> bool:
687
+ """Some set of `relation`'s columns is a Unique Set: its rows are distinct."""
688
+ columns = frozenset(relation.output_columns)
689
+ return bool(columns) and _reaches_row_identity(_closure(relation, columns, columns)).value
690
+
691
+
692
+ def _label(join: ir.Join, join_labels: dict[ir.Join, str]) -> str:
693
+ return join_labels.get(join, "a join")
694
+
695
+
696
+ # Arbitrary LIMIT -------------------------------------------------------------
697
+
698
+
699
+ def _arbitrary_limit(site: AttachmentSite, limit: ir.Limit, keys: tuple[ir.OutputColumn, ...] | None) -> list[Hazard]:
700
+ """A LIMIT whose sort keys leave two different rows tied.
701
+
702
+ Rows that agree on every selected column are interchangeable, so the keys
703
+ need only strictly determine the selected columns (NULL equal to NULL, as
704
+ ORDER BY ties them), not a row of the input. Under a projection the keys
705
+ are input columns it may not select, so the question is asked there. A
706
+ key that does not compare by identity (a collation, a float) ties
707
+ different values, so it determines nothing here.
708
+ """
709
+ if limit.count == 0 or keys is None:
710
+ return []
711
+ relation = limit.input
712
+ if isinstance(relation, ir.Project):
713
+ scope, needed = relation.input, {column: _needed(column) for column in relation.output_columns}
714
+ else:
715
+ scope, needed = relation, {column: frozenset({column}) for column in relation.output_columns}
716
+ exact = tuple(key for key in keys if _ties_identical(key))
717
+ closure = _closure(scope, frozenset(exact), frozenset())
718
+ loose = [column for column, inputs in needed.items() if inputs is None or not inputs <= closure.value.columns]
719
+ if not loose:
720
+ return []
721
+ names = quoted_all(column.name for column in loose)
722
+ reason = f"the ORDER BY does not determine ({names}), so rows tied on it" if keys else "with no ORDER BY, rows"
723
+ message = f"{reason} come in an arbitrary order and LIMIT may keep different rows on each run: order by a key as well"
724
+ return [Hazard(site, Concern.ARBITRARY_LIMIT, message, closure)]
725
+
726
+
727
+ def _ties_identical(column: ir.OutputColumn) -> bool:
728
+ """Whether rows ORDER BY ties on `column` hold identical values of it."""
729
+ return _identity_comparison(column).value
730
+
731
+
732
+ def _needed(column: ir.OutputColumn) -> frozenset[ir.OutputColumn] | None:
733
+ """The input columns a projected column's value is a function of, if known."""
734
+ inputs = ir.determinants(column.scalar_expr)
735
+ return None if inputs is None else frozenset(inputs)