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/hazards.py ADDED
@@ -0,0 +1,574 @@
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 join equality between text and another declared type: the text is cast,
18
+ so different strings may match one value (`'01'` and `'1'` both equal 1),
19
+ and no cardinality is proved across it. Write the cast explicitly.
20
+ - A Float Equality: an equality (`=`, `<>`, `IS [NOT] DISTINCT FROM`, an
21
+ IN list or subquery) with an operand of a known floating type (REAL,
22
+ FLOAT, DOUBLE in any spelling), against another float, an integer, a
23
+ decimal or a literal. Floats round, so exact equality is wrong; which
24
+ values a float holds exactly is no rule to rely on. In a join's ON, a
25
+ WHERE or HAVING, and the correlation of an IN or EXISTS subquery (its
26
+ semi or anti join). Silent for an ordering (`<`, `>`) and an operand
27
+ whose type is unknown: a literal's type is the dialect's, never guessed.
28
+ - A scalar subquery not proved to return at most one row (issue 38): more
29
+ than one is a runtime error. Uncorrelated, its body must have at most one
30
+ row; correlated, the columns its WHERE binds must reach its Row Identity.
31
+ - A query that can never return a row: a `NOT EXISTS` every row has a match
32
+ for (a foreign key's orphan check), a `WHERE x IS NULL` on a column proved
33
+ non-null (the `LEFT JOIN ... IS NULL` form of it), an `EXCEPT` whose left
34
+ rows all appear on the right. Whether the key is enforced is not asked:
35
+ sqlassert trusts every key the SQL states.
36
+ - A GROUP BY key the Select does not return, when the keys it returns do not
37
+ determine it: output rows told apart only by a value not shown look like
38
+ duplicates. Silent for the values of an IN, EXISTS or scalar subquery.
39
+
40
+ A hazard is reported only when sqlassert sees the whole Select Expression; an
41
+ `ORDER BY` key it cannot map to a selected column keeps it silent.
42
+ """
43
+
44
+ from __future__ import annotations
45
+
46
+ from collections.abc import Callable, Iterable
47
+ from dataclasses import dataclass
48
+ from enum import Enum
49
+ from typing import ClassVar
50
+
51
+ from sqlglot import exp
52
+
53
+ from sqlassert.diagnostics import quoted, quoted_all
54
+ from sqlassert import ir
55
+ from sqlassert.ir.convert import HIDDEN_GROUPING
56
+ from sqlassert.rewrites import SuggestType, _syntax_at_sites
57
+ from sqlassert.provenance import AttachmentSite
58
+ from sqlassert.python_engine import Arena, Result
59
+ from sqlassert.rules.equality import _binary_text, _comparison_type, _exact_arithmetic, _identity_comparison
60
+ from sqlassert.rules.join_cardinality import _at_most_one_match, many_to_one_join, one_to_many_join, unique_join
61
+ from sqlassert.properties import NonNullColumn, NonNullColumns, ReferentialCoverage
62
+ from sqlassert.rules.exactly_one import _cross_equalities
63
+ from sqlassert.rules.uniqueness import _closure, _reaches_row_identity, minimal_keys
64
+ from sqlassert.sql_parse import ParsedProgram, assertion_span
65
+
66
+
67
+ class Concern(Enum):
68
+ ARBITRARY_LIMIT = "Arbitrary LIMIT"
69
+ FAN_TRAP = "Fan trap"
70
+ CHASM_TRAP = "Chasm trap"
71
+ SCALAR_SUBQUERY = "Scalar subquery"
72
+ IMPLICIT_CAST = "Implicit cast"
73
+ FLOAT_EQUALITY = "Float equality"
74
+ ALWAYS_EMPTY = "Always empty"
75
+ MANY_TO_MANY = "Many-to-many join"
76
+ UNSELECTED_GROUPING = "Grouping key not selected"
77
+
78
+
79
+ @dataclass(frozen=True)
80
+ class Hazard:
81
+ """A place whose result the SQL leaves unspecified, with the failed proof."""
82
+
83
+ site: AttachmentSite
84
+ concern: Concern
85
+ message: str
86
+ evidence: Result
87
+ suggest_type: ClassVar[SuggestType] = SuggestType.HAZARD
88
+
89
+
90
+ def hazards(
91
+ ast: ParsedProgram, program: ir.Program, arena: Arena, dialect: str,
92
+ wanted: Callable[[AttachmentSite], bool] = lambda site: True,
93
+ ) -> list[Hazard]:
94
+ """Every Hazard in `program` at a site `wanted` accepts, in source order. `arena` must be active."""
95
+ syntax = _syntax_at_sites(ast)
96
+ compared: set[ir.ScalarExpr] = set() # Comparisons already checked for a float equality.
97
+ reachable = set(program.nodes())
98
+ found: list[Hazard] = []
99
+ join_labels = {relation: site.label for site, relation in program.attachment_sites if isinstance(relation, ir.Join)}
100
+ deduplicated = _deduplicated_joins(program)
101
+ sort_keys = dict(program.sort_keys)
102
+ for site, relation in program.attachment_sites:
103
+ if not wanted(site):
104
+ continue
105
+ node = syntax.get((site.offset, site.trailing))
106
+ 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)))
108
+ if isinstance(relation, ir.Join) and relation in reachable and not site.trailing:
109
+ found.extend(_implicit_casts(site, relation))
110
+ found.extend(_float_equalities(site, relation.conjuncts, compared, dialect))
111
+ if isinstance(node, exp.Join) and assertion_span(node) is None and relation not in deduplicated:
112
+ found.extend(_many_to_many(site, relation))
113
+ aggregate = relation.input if isinstance(relation, ir.Limit) else relation
114
+ grouped = _grouped(aggregate)
115
+ if grouped is not None and grouped in reachable:
116
+ found.extend(_traps(site, grouped, join_labels))
117
+ if site.trailing and isinstance(node, exp.Select) and _rows_are_read(node):
118
+ found.extend(_unselected_grouping(site, grouped))
119
+ if site.trailing and aggregate in reachable and not isinstance(aggregate, ir.SimpleCase):
120
+ found.extend(_always_empty(site, aggregate, arena))
121
+ found.extend(_float_equalities(site, _filter_conjuncts(aggregate), compared, dialect))
122
+ for site, operation in program.set_operations:
123
+ if operation in reachable and wanted(site) and operation.operator == "except":
124
+ found.extend(_empty_except(site, operation, arena))
125
+ for site, join in program.scalar_subqueries:
126
+ if join in reachable and wanted(site):
127
+ found.extend(_scalar_subquery(site, join))
128
+ return sorted(found, key=lambda item: item.site.offset)
129
+
130
+
131
+ def _grouped(relation: ir.RelationExpr | ir.SimpleCase) -> ir.Aggregate | None:
132
+ """The Aggregate of a grouped Select, under its HAVING (a Filter) and the
133
+ Project that drops grouping keys it does not select."""
134
+ if isinstance(relation, ir.Project) and isinstance(relation.input, ir.Aggregate | ir.Filter):
135
+ relation = relation.input
136
+ if isinstance(relation, ir.Filter) and isinstance(relation.input, ir.Aggregate):
137
+ relation = relation.input
138
+ return relation if isinstance(relation, ir.Aggregate) else None
139
+
140
+
141
+ def _rows_are_read(select: exp.Select) -> bool:
142
+ """Whether `select`'s rows are a result, read as rows: not the values of
143
+ an IN, EXISTS or scalar subquery, where equal rows are no surprise."""
144
+ if select.find_ancestor(exp.In, exp.Exists) is not None:
145
+ return False
146
+ subquery = select.find_ancestor(exp.Subquery)
147
+ return subquery is None or isinstance(subquery.parent, exp.From | exp.Join)
148
+
149
+
150
+ def _unselected_grouping(site: AttachmentSite, aggregate: ir.Aggregate) -> list[Hazard]:
151
+ """GROUP BY keys the Select does not return, when the keys it returns do
152
+ not determine them: two output rows may then be equal, told apart only by
153
+ a value not shown. Rarely what the author meant."""
154
+ hidden = [column for column in aggregate.grouping_outputs if column.name.startswith(HIDDEN_GROUPING)]
155
+ if not hidden:
156
+ return []
157
+ shown = frozenset(column for column in aggregate.grouping_outputs if column not in hidden)
158
+ if _reaches_row_identity(_closure(aggregate, shown, frozenset())).value:
159
+ return []
160
+ names = quoted_all(column.scalar_expr.origin.detail for column in hidden)
161
+ terms, verb, pronoun = ("term", "does", "it") if len(hidden) == 1 else ("terms", "do", "them")
162
+ message = (
163
+ f"GROUP BY {terms} {names} {verb} not appear in SELECT. This is probably a mistake: "
164
+ f"select {pronoun}, or drop {pronoun} from GROUP BY"
165
+ )
166
+ return [Hazard(site, Concern.UNSELECTED_GROUPING, message, Result(True, "a grouping key is not selected", tuple(hidden)))]
167
+
168
+
169
+ def _always_empty(site: AttachmentSite, relation: ir.RelationExpr, arena: Arena) -> list[Hazard]:
170
+ """A filter of this Select that keeps no row: an anti join every row
171
+ matches, or `x IS NULL` on a non-null x. A scalar aggregate still returns
172
+ its one row, so the walk stops there."""
173
+ while True:
174
+ match relation:
175
+ case ir.Aggregate(grouping_outputs=()):
176
+ return []
177
+ case ir.Project(input=source) | ir.Aggregate(input=source) | ir.Distinct(input=source) | ir.QualifyByPartition(input=source) | ir.Join(kind="semi", left=source):
178
+ relation = source
179
+ case ir.Join(kind="anti", left=source):
180
+ proof = _every_row_matches(relation, arena)
181
+ if proof.value:
182
+ message = (
183
+ "every row has a match in its NOT EXISTS subquery, which therefore removes every row: this "
184
+ "query never returns one (an orphan check a foreign key already guarantees)"
185
+ )
186
+ return [Hazard(site, Concern.ALWAYS_EMPTY, message, proof)]
187
+ relation = source
188
+ case ir.Filter(input=source):
189
+ for conjunct in relation.conjuncts:
190
+ match conjunct:
191
+ case ir.IsNull(operand=ir.ColumnRef(column=column)):
192
+ proof = arena.prove(NonNullColumn(column=column))
193
+ if proof.value:
194
+ message = f"{conjunct.origin.detail} is never TRUE ({quoted(column.name)} is never NULL), so this query never returns a row"
195
+ return [Hazard(site, Concern.ALWAYS_EMPTY, message, proof)]
196
+ case _:
197
+ pass
198
+ relation = source
199
+ case _:
200
+ return []
201
+
202
+
203
+ def _every_row_matches(join: ir.Join, arena: Arena) -> Result[bool]:
204
+ """Every left row of `join` has a right row its ON holds on: ON is only
205
+ equalities between the inputs, the left columns are non-null and covered
206
+ by the right ones (the at-least-one half of an Exactly One Join)."""
207
+ pairs, others = _cross_equalities(join)
208
+ if not pairs or others:
209
+ return Result(False, "Only an ON of equalities between the inputs is known to match", (join,), kind="unknown")
210
+ lefts, rights = tuple(left for left, _ in pairs), tuple(right for _, right in pairs)
211
+ return arena.prove(ReferentialCoverage(columns=lefts, referenced_columns=rights)) & arena.prove(NonNullColumns(columns=frozenset(lefts)))
212
+
213
+
214
+ def _empty_except(site: AttachmentSite, operation: ir.SetOperation, arena: Arena) -> list[Hazard]:
215
+ """`A EXCEPT B` where every row of A, non-null, appears in B."""
216
+ left, right = operation.left.output_columns, operation.right.output_columns
217
+ if not operation.distinct or operation.by_name or len(left) != len(right):
218
+ return []
219
+ proof = arena.prove(ReferentialCoverage(columns=left, referenced_columns=right)) & arena.prove(NonNullColumns(columns=frozenset(left)))
220
+ if not proof.value:
221
+ return []
222
+ message = "every row of the left input appears in the right one, so this EXCEPT never returns a row"
223
+ return [Hazard(site, Concern.ALWAYS_EMPTY, message, proof)]
224
+
225
+
226
+ def _many_to_many(site: AttachmentSite, join: ir.Join) -> list[Hazard]:
227
+ """A join with no marker that is not proved to repeat rows of at most one
228
+ input, both of whose inputs have a known Unique Set: it may repeat rows of
229
+ both. A many-to-many join is rare on purpose; an explicit CROSS JOIN is
230
+ one, so it is left alone, and a marker leaves the cardinality to `check`."""
231
+ if join.kind in ("semi", "anti", "cross"):
232
+ return []
233
+ proof = unique_join(join)
234
+ if proof.value or not (_has_unique_set(join.left) and _has_unique_set(join.right)):
235
+ return []
236
+ if _equates_a_key(join, join.left, join.right) or _equates_a_key(join, join.right, join.left):
237
+ return [] # A join on a key whose column types are unknown: a missing fact, not a hazard.
238
+ message = (
239
+ "this join is not proved to repeat rows of only one input: it may be many to many, repeating rows of both. "
240
+ "Join on a key of one input, or write the join marker you expect (/**ASSERT MANY TO ONE**/, ...) for check to prove"
241
+ )
242
+ return [Hazard(site, Concern.MANY_TO_MANY, message, proof)]
243
+
244
+
245
+ def _deduplicated_joins(program: ir.Program) -> set[ir.Join]:
246
+ """The joins in the FROM of a Select whose DISTINCT or GROUP BY merges
247
+ the rows they repeat: repeats never reach its result, and what they do to
248
+ an aggregate is a trap of its own."""
249
+ found: set[ir.Join] = set()
250
+ for site, relation in program.attachment_sites:
251
+ stage = relation.input if isinstance(relation, ir.Limit) else relation
252
+ if not site.trailing or not isinstance(stage, ir.Distinct | ir.Aggregate):
253
+ continue
254
+ pending = [stage.input]
255
+ while pending:
256
+ match pending.pop():
257
+ case ir.Join(left=left, right=right) as join:
258
+ found.add(join)
259
+ pending += [left, right]
260
+ case ir.Filter(input=source):
261
+ pending.append(source)
262
+ case _:
263
+ pass
264
+ return found
265
+
266
+
267
+ def _equates_a_key(join: ir.Join, side: ir.RelationExpr, other: ir.RelationExpr) -> bool:
268
+ """Whether ON equates every column of a known key of `side` with a value
269
+ of the other input's row (a column, an expression of its columns such as
270
+ a FULL JOIN chain's `coalesce(a.k, b.k)`, or a constant), whatever their
271
+ types: the join is on that key, and only an unknown type or an
272
+ expression kept the proof from binding it."""
273
+ equated: set[ir.OutputColumn] = set()
274
+ for conjunct in join.conjuncts:
275
+ if not isinstance(conjunct, ir.Equality):
276
+ continue
277
+ for mine, theirs in ((conjunct.left, conjunct.right), (conjunct.right, conjunct.left)):
278
+ inputs = ir.determinants(theirs)
279
+ if isinstance(mine, ir.ColumnRef) and mine.column in side.output_columns and inputs is not None and (
280
+ set(inputs) <= set(other.output_columns)
281
+ ):
282
+ equated.add(mine.column)
283
+ return any(set(key) <= equated for key in minimal_keys(side))
284
+
285
+
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
+ def _filter_conjuncts(relation: ir.RelationExpr) -> list[ir.ScalarExpr]:
307
+ """The conjuncts of a Select's WHERE and HAVING, and of the semi and anti
308
+ joins its IN and EXISTS subqueries are, from its result down to its FROM."""
309
+ found: list[ir.ScalarExpr] = []
310
+ while True:
311
+ match relation:
312
+ case ir.Project(input=source) | ir.Aggregate(input=source) | ir.Distinct(input=source) | ir.QualifyByPartition(input=source):
313
+ relation = source
314
+ case ir.Filter(input=source):
315
+ found.extend(relation.conjuncts)
316
+ relation = source
317
+ case ir.Join(kind="semi" | "anti", left=source):
318
+ found.extend(relation.conjuncts)
319
+ relation = source
320
+ case _:
321
+ return found
322
+
323
+
324
+ _FLOATS = {exp.DataType.Type.FLOAT, exp.DataType.Type.DOUBLE, exp.DataType.Type.UDOUBLE}
325
+
326
+ # Call names that compare for equality, as their operands' values.
327
+ _EQUALITY_CALLS = {"<>", "IS DISTINCT FROM"}
328
+
329
+
330
+ def _float_equalities(
331
+ site: AttachmentSite, conjuncts: Iterable[ir.ScalarExpr], compared: set[ir.ScalarExpr], dialect: str,
332
+ ) -> list[Hazard]:
333
+ """Each equality in `conjuncts`, at any depth (`x = 1 OR y = 2` is two),
334
+ with an operand column of a known floating type."""
335
+ found = []
336
+ pending = list(conjuncts)
337
+ while pending:
338
+ node = pending.pop(0)
339
+ if node in compared:
340
+ continue
341
+ compared.add(node)
342
+ match node:
343
+ case ir.Equality(left=left, right=right) | ir.NullSafeEquality(left=left, right=right):
344
+ operands: tuple[ir.ScalarExpr, ...] = (left, right)
345
+ case ir.Call(function=function, arguments=(left, right)) if function.name in _EQUALITY_CALLS:
346
+ operands = (left, right)
347
+ case ir.InList(operand=operand, values=values):
348
+ operands = (operand, *values)
349
+ case _:
350
+ pending.extend(child for child in ir.children(node) if isinstance(child, ir.ScalarExpr))
351
+ continue
352
+ floats = [(operand.column, kind) for operand in operands if isinstance(operand, ir.ColumnRef) and (kind := _float_type(operand.column, dialect)) is not None]
353
+ if not floats:
354
+ continue
355
+ written = node.origin.detail
356
+ for operand in operands:
357
+ if isinstance(operand, ir.ColumnRef) and operand.origin.detail.startswith("__having."):
358
+ written = written.replace(operand.origin.detail, operand.column.name) # HAVING reads the grouped columns.
359
+ message = f"{written} compares a floating-point value for exact equality; compare within a tolerance or use an exact type"
360
+ column, kind = floats[0]
361
+ evidence = Result(False, f"{quoted(column.name)} is {kind}, a floating-point type, compared for exact equality", (node,))
362
+ found.append(Hazard(site, Concern.FLOAT_EQUALITY, message, evidence))
363
+ return found
364
+
365
+
366
+ def _float_type(column: ir.OutputColumn, dialect: str) -> str | None:
367
+ """`column`'s declared floating type, or None when its type is not a
368
+ float or not known."""
369
+ declared = _comparison_type(column).value
370
+ if declared is None or exp.DataType.build(declared, dialect=dialect).this not in _FLOATS:
371
+ return None
372
+ return declared
373
+
374
+
375
+ def _scalar_subquery(site: AttachmentSite, join: ir.Join) -> list[Hazard]:
376
+ """A scalar subquery that may return more than one row.
377
+
378
+ Its join is many to one by construction (more rows fail the query), so
379
+ the question is asked of its body: uncorrelated, under the implied LIMIT
380
+ 1, whether the body has at most one row (the empty set is a Unique Set);
381
+ correlated, whether the columns ON binds reach the body's Row Identity."""
382
+ match join.right:
383
+ case ir.Limit(input=body) if join.predicate is None:
384
+ proof = _reaches_row_identity(_closure(body, frozenset(), frozenset()))
385
+ reason = "it is not proved to have at most one row"
386
+ case _:
387
+ proof = _at_most_one_match(join, "right")
388
+ reason = "the columns its WHERE binds to the outer row are not proved to be a Unique Set"
389
+ if proof.value:
390
+ return []
391
+ message = f"this scalar subquery may return more than one row, a runtime error: {reason}"
392
+ return [Hazard(site, Concern.SCALAR_SUBQUERY, message, proof)]
393
+
394
+
395
+ # Join traps ------------------------------------------------------------------
396
+
397
+
398
+ def _traps(site: AttachmentSite, aggregate: ir.Aggregate, join_labels: dict[ir.Join, str]) -> list[Hazard]:
399
+ """Each aggregate call whose input rows a join may repeat."""
400
+ found: list[Hazard] = []
401
+ for call in aggregate.calls:
402
+ inputs = [ir.determinants(argument) for argument in call.arguments]
403
+ if any(columns is None for columns in inputs):
404
+ continue # An argument whose columns are unknown.
405
+ columns = frozenset(column for columns in inputs if columns is not None for column in columns)
406
+ if not columns:
407
+ # `count(*)`, or a constant: it counts the input's rows.
408
+ for join, path, proof in _many_to_many_joins(aggregate.input, []):
409
+ if _unrepeated(aggregate.input, join.left, path) or _unrepeated(aggregate.input, join.right, path):
410
+ continue
411
+ message = (
412
+ f"{call.description} counts the rows of {_label(join, join_labels)}, which is not proved "
413
+ "to repeat rows of only one input (a fan trap): rows may be counted more than once"
414
+ )
415
+ found.append(Hazard(site, Concern.FAN_TRAP, message, proof))
416
+ continue
417
+ repeated = _repeating_join(aggregate.input, columns)
418
+ if repeated is None:
419
+ continue
420
+ join, side, path, proof = repeated
421
+ if _unrepeated(aggregate.input, side, path):
422
+ continue # A filter keeps one row per key after all (`WHERE o.id = 1`).
423
+ if unique_join(join).value:
424
+ concern, why = Concern.CHASM_TRAP, "is one to many, and the argument is on the side with one row per key"
425
+ else:
426
+ concern, why = Concern.FAN_TRAP, "is not proved to repeat rows of only one input"
427
+ message = (
428
+ f"{call.description} reads rows that {_label(join, join_labels)} may repeat: the join {why} "
429
+ f"({concern.value.lower()}), so a value may be counted more than once"
430
+ )
431
+ found.append(Hazard(site, concern, message, proof))
432
+ return found
433
+
434
+
435
+ def _repeating_join(
436
+ relation: ir.RelationExpr, columns: frozenset[ir.OutputColumn]
437
+ ) -> tuple[ir.Join, ir.RelationExpr, list[ir.RelationExpr], Result] | None:
438
+ """The first join, from `relation` down to the input `columns` come from,
439
+ not proved to keep that input's rows unrepeated: the join, that input,
440
+ the stages from `relation` down to the join, and the failed proof. None
441
+ when every join on the way is proved, or the columns cannot be traced to
442
+ one input of a join."""
443
+ path: list[ir.RelationExpr] = []
444
+ while True:
445
+ path.append(relation)
446
+ upstream = _upstream(relation, columns)
447
+ if upstream is None:
448
+ return None
449
+ match relation:
450
+ case ir.Join(kind="semi" | "anti"):
451
+ side = relation.left # It never repeats a row.
452
+ case ir.Join():
453
+ if upstream <= set(relation.left.output_columns):
454
+ side, proof = relation.left, many_to_one_join(relation)
455
+ elif upstream <= set(relation.right.output_columns):
456
+ side, proof = relation.right, one_to_many_join(relation)
457
+ else:
458
+ return None # The argument reads both inputs.
459
+ if not proof.value and _has_unique_set(side):
460
+ return relation, side, path, proof
461
+ case ir.Filter(input=side) | ir.Alias(source=side) | ir.Project(input=side) | ir.Limit(input=side):
462
+ pass
463
+ case ir.NamedRelation(body=ir.RelationExpr() as side):
464
+ pass
465
+ case _:
466
+ return None # A base table, or a stage that drops or merges rows.
467
+ if not upstream <= set(side.output_columns):
468
+ return None
469
+ relation, columns = side, upstream
470
+
471
+
472
+ def _many_to_many_joins(relation: ir.RelationExpr, path: list[ir.RelationExpr]):
473
+ """Each join under `relation` not proved to repeat rows of at most one
474
+ input, both of whose inputs have a known Unique Set, with the stages down
475
+ to it and the failed proof."""
476
+ path = [*path, relation]
477
+ match relation:
478
+ case ir.Join(kind="semi" | "anti", left=left):
479
+ yield from _many_to_many_joins(left, path)
480
+ case ir.Join(left=left, right=right):
481
+ proof = unique_join(relation)
482
+ if not proof.value and _has_unique_set(left) and _has_unique_set(right):
483
+ yield relation, path, proof
484
+ yield from _many_to_many_joins(left, path)
485
+ yield from _many_to_many_joins(right, path)
486
+ case ir.Filter(input=source) | ir.Alias(source=source) | ir.Project(input=source) | ir.Limit(input=source):
487
+ yield from _many_to_many_joins(source, path)
488
+ case ir.NamedRelation(body=ir.RelationExpr() as source):
489
+ yield from _many_to_many_joins(source, path)
490
+ case _:
491
+ pass
492
+
493
+
494
+ def _unrepeated(top: ir.RelationExpr, side: ir.RelationExpr, path: list[ir.RelationExpr]) -> bool:
495
+ """Whether a Unique Set of `side`, carried up `path` (the stages from
496
+ `top` down to the join `side` is an input of), is a Unique Set of `top`:
497
+ `side`'s rows are not repeated there after all."""
498
+ for key in minimal_keys(side):
499
+ lifted: list[ir.OutputColumn] = list(key)
500
+ for stage in reversed(path):
501
+ passed = {
502
+ output.scalar_expr.column: output for output in stage.output_columns if isinstance(output.scalar_expr, ir.ColumnRef)
503
+ }
504
+ if not all(column in passed for column in lifted):
505
+ break
506
+ lifted = [passed[column] for column in lifted]
507
+ else:
508
+ members = frozenset(lifted)
509
+ if _reaches_row_identity(_closure(top, members, members)).value:
510
+ return True
511
+ return False
512
+
513
+
514
+ def _upstream(relation: ir.RelationExpr, columns: frozenset[ir.OutputColumn]) -> frozenset[ir.OutputColumn] | None:
515
+ """The input columns `columns` of `relation` are computed from, if known."""
516
+ found: set[ir.OutputColumn] = set()
517
+ for column in columns:
518
+ inputs = ir.determinants(column.scalar_expr)
519
+ if inputs is None:
520
+ return None
521
+ found.update(inputs)
522
+ return frozenset(found)
523
+
524
+
525
+ def _has_unique_set(relation: ir.RelationExpr) -> bool:
526
+ """Some set of `relation`'s columns is a Unique Set: its rows are distinct."""
527
+ columns = frozenset(relation.output_columns)
528
+ return bool(columns) and _reaches_row_identity(_closure(relation, columns, columns)).value
529
+
530
+
531
+ def _label(join: ir.Join, join_labels: dict[ir.Join, str]) -> str:
532
+ return join_labels.get(join, "a join")
533
+
534
+
535
+ # Arbitrary LIMIT -------------------------------------------------------------
536
+
537
+
538
+ def _arbitrary_limit(site: AttachmentSite, limit: ir.Limit, keys: tuple[ir.OutputColumn, ...] | None) -> list[Hazard]:
539
+ """A LIMIT whose sort keys leave two different rows tied.
540
+
541
+ Rows that agree on every selected column are interchangeable, so the keys
542
+ need only strictly determine the selected columns (NULL equal to NULL, as
543
+ ORDER BY ties them), not a row of the input. Under a projection the keys
544
+ are input columns it may not select, so the question is asked there. A
545
+ key that does not compare by identity (a collation, a float) ties
546
+ different values, so it determines nothing here.
547
+ """
548
+ if limit.count == 0 or keys is None:
549
+ return []
550
+ relation = limit.input
551
+ if isinstance(relation, ir.Project):
552
+ scope, needed = relation.input, {column: _needed(column) for column in relation.output_columns}
553
+ else:
554
+ scope, needed = relation, {column: frozenset({column}) for column in relation.output_columns}
555
+ exact = tuple(key for key in keys if _ties_identical(key))
556
+ closure = _closure(scope, frozenset(exact), frozenset())
557
+ loose = [column for column, inputs in needed.items() if inputs is None or not inputs <= closure.value.columns]
558
+ if not loose:
559
+ return []
560
+ names = quoted_all(column.name for column in loose)
561
+ reason = f"the ORDER BY does not determine ({names}), so rows tied on it" if keys else "with no ORDER BY, rows"
562
+ message = f"{reason} come in an arbitrary order and LIMIT may keep different rows on each run: order by a key as well"
563
+ return [Hazard(site, Concern.ARBITRARY_LIMIT, message, closure)]
564
+
565
+
566
+ def _ties_identical(column: ir.OutputColumn) -> bool:
567
+ """Whether rows ORDER BY ties on `column` hold identical values of it."""
568
+ return _identity_comparison(column).value or _exact_arithmetic(column)
569
+
570
+
571
+ def _needed(column: ir.OutputColumn) -> frozenset[ir.OutputColumn] | None:
572
+ """The input columns a projected column's value is a function of, if known."""
573
+ inputs = ir.determinants(column.scalar_expr)
574
+ return None if inputs is None else frozenset(inputs)
sqlassert/ir/__init__.py CHANGED
@@ -1,8 +1,9 @@
1
1
  """Relational intermediate representation."""
2
2
 
3
- from sqlassert.ir.model import 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, 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, 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
4
4
 
5
5
  __all__ = [
6
+ "Accumulation",
6
7
  "Aggregate",
7
8
  "AggregateCall",
8
9
  "Alias",
@@ -32,6 +33,7 @@ __all__ = [
32
33
  "NamedRelation",
33
34
  "Node",
34
35
  "NullLiteral",
36
+ "NullSafeEquality",
35
37
  "OpaqueExpression",
36
38
  "OpaquePureFunction",
37
39
  "OpaqueRelation",