sqlassert 0.1.2__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.
Files changed (50) hide show
  1. sqlassert/__init__.py +34 -9
  2. sqlassert/__main__.py +9 -0
  3. sqlassert/check.py +451 -0
  4. sqlassert/diagnostics.py +70 -0
  5. sqlassert/dialects.py +258 -0
  6. sqlassert/discovery/__init__.py +30 -0
  7. sqlassert/discovery/bigquery.py +71 -0
  8. sqlassert/discovery/databricks.py +18 -0
  9. sqlassert/discovery/duckdb.py +159 -0
  10. sqlassert/discovery/fetcher.py +418 -0
  11. sqlassert/discovery/information_schema.py +327 -0
  12. sqlassert/discovery/mysql.py +70 -0
  13. sqlassert/discovery/postgres.py +142 -0
  14. sqlassert/discovery/redshift.py +36 -0
  15. sqlassert/discovery/snowflake.py +63 -0
  16. sqlassert/discovery/trino.py +37 -0
  17. sqlassert/edits.py +240 -0
  18. sqlassert/hazards.py +574 -0
  19. sqlassert/ir/__init__.py +58 -0
  20. sqlassert/ir/convert.py +3509 -0
  21. sqlassert/ir/model.py +779 -0
  22. sqlassert/main.py +51 -0
  23. sqlassert/properties.py +121 -0
  24. sqlassert/provenance.py +73 -0
  25. sqlassert/python_engine.py +356 -0
  26. sqlassert/reporting.py +105 -0
  27. sqlassert/rewrites.py +1541 -0
  28. sqlassert/rules/STYLEGUIDE.md +19 -0
  29. sqlassert/rules/__init__.py +11 -0
  30. sqlassert/rules/column_set.py +34 -0
  31. sqlassert/rules/domain.py +472 -0
  32. sqlassert/rules/equality.py +442 -0
  33. sqlassert/rules/exactly_one.py +114 -0
  34. sqlassert/rules/foreign_key.py +319 -0
  35. sqlassert/rules/join_cardinality.py +116 -0
  36. sqlassert/rules/nullability.py +627 -0
  37. sqlassert/rules/uniqueness.py +904 -0
  38. sqlassert/sql_parse.py +1081 -0
  39. sqlassert/suggest.py +418 -0
  40. sqlassert-0.3.3.dist-info/METADATA +807 -0
  41. sqlassert-0.3.3.dist-info/RECORD +46 -0
  42. {sqlassert-0.1.2.dist-info → sqlassert-0.3.3.dist-info}/WHEEL +1 -1
  43. sqlassert-0.3.3.dist-info/entry_points.txt +2 -0
  44. sqlassert-0.3.3.dist-info/licenses/LICENSE +21 -0
  45. sqlassert-0.3.3.dist-info/top_level.txt +2 -0
  46. sqlassert_cli.py +130 -0
  47. sqlassert/unique.py +0 -605
  48. sqlassert-0.1.2.dist-info/METADATA +0 -173
  49. sqlassert-0.1.2.dist-info/RECORD +0 -6
  50. sqlassert-0.1.2.dist-info/top_level.txt +0 -1
@@ -0,0 +1,442 @@
1
+ """Equality groups: the output columns of a relation that carry one value.
2
+
3
+ A strict equality -- a `WHERE` or inner-join `ON` conjunct `a = b` -- keeps
4
+ only rows on which `a` and `b` are non-null and equal; `a IS NOT DISTINCT
5
+ FROM b` those on which they are equal or both NULL. Equality groups are a
6
+ union-find over those equalities, per relation, over its output columns: an
7
+ input's groups pass through every column that passes an input column through,
8
+ then the relation's own strict equalities merge them. On every row a group's
9
+ members are equal, or all NULL (an outer join padded them, padding nulling a
10
+ whole side, or IS NOT DISTINCT FROM equated NULLs): where one is non-null,
11
+ every one equals it. A semi join's ON merges through the columns of the
12
+ matched right row, which no output carries. An outer join's ON merges columns on the side it pads together. Cross-side
13
+ equalities become strict when a filter excludes the padding.
14
+
15
+ A functional dependency `a ↔ b` also holds for an injective `a = f(b)`, whose
16
+ values differ; a group says the values are the same. Facts about values read
17
+ it (Enumerated Domains, Foreign Keys through an equality join); uniqueness
18
+ never does.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ from dataclasses import dataclass
24
+ from itertools import combinations
25
+ from collections.abc import Callable, Iterable, Mapping
26
+ from typing import assert_never
27
+ import re
28
+
29
+ from sqlassert import ir
30
+ from sqlassert.python_engine import Result, Stratum, analysis, current_arena
31
+
32
+ type _Group = tuple[ir.OutputColumn, ...]
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class EqualityGroups:
37
+ """A partition of `relation`'s output columns into value-equal groups.
38
+
39
+ Each group lists its columns in output order, and groups are ordered by
40
+ their first column; a column no equality reaches is a group of its own.
41
+ """
42
+
43
+ relation: ir.RelationExpr
44
+ groups: tuple[_Group, ...]
45
+
46
+
47
+ @analysis(Stratum.EQUALITY_GROUP)
48
+ def _equal_columns(column: ir.OutputColumn) -> Result[frozenset[ir.OutputColumn]]:
49
+ """Every column of `column`'s relation that carries its value, itself included."""
50
+ groups = _equality_groups(column.get_relation(current_arena().program))
51
+ group, = (group for group in groups.value.groups if column in group)
52
+ return Result(frozenset(group), "Equal columns", (column,), [groups.members[group]])
53
+
54
+
55
+ @analysis(Stratum.EQUALITY_GROUP)
56
+ def _equality_groups(relation: ir.RelationExpr) -> Result[EqualityGroups]:
57
+ """`relation`'s equality groups; each group's member cites the equalities that merged it."""
58
+ roots = {column: column for column in relation.output_columns}
59
+ evidence: dict[ir.OutputColumn, list[Result[bool]]] = {column: [] for column in relation.output_columns}
60
+
61
+ def find(column: ir.OutputColumn) -> ir.OutputColumn:
62
+ while roots[column] is not column:
63
+ column = roots[column]
64
+ return column
65
+
66
+ def merge(columns: list[ir.OutputColumn], reason: Result[bool]) -> None:
67
+ found = list(dict.fromkeys(find(column) for column in columns))
68
+ if len(found) < 2:
69
+ return # Already one group: the first justification suffices.
70
+ root, *others = found
71
+ for other in others:
72
+ roots[other] = root
73
+ evidence[root].extend(evidence.pop(other))
74
+ evidence[root].append(reason)
75
+
76
+ outputs: dict[ir.OutputColumn, list[ir.OutputColumn]] = {}
77
+ for source in _inputs(relation):
78
+ passed = _pass_through(relation, source)
79
+ outputs.update(passed)
80
+ groups = _equality_groups(source)
81
+ for group in groups.value.groups:
82
+ own = [column for upstream in group for column in passed.get(upstream, ())]
83
+ merge(own, Result(True, "Equal in the input", (), [groups.members[group]]))
84
+
85
+ if isinstance(relation, ir.Join) and relation.kind == "semi":
86
+ # The matched right row's columns carry values too, though no output
87
+ # does: two left columns equal to one right column are equal.
88
+ right = relation.right
89
+ for column in right.output_columns:
90
+ roots[column], evidence[column], outputs[column] = column, [], [column]
91
+ groups = _equality_groups(right)
92
+ for group in groups.value.groups:
93
+ merge(list(group), Result(True, "Equal in the matched right row", (), [groups.members[group]]))
94
+
95
+ conjuncts, clause = _strict_conjuncts(relation)
96
+ for (first, second), reason in _predicate_equalities(conjuncts).items():
97
+ if first in outputs and second in outputs:
98
+ merge([*outputs[first], *outputs[second]], Result(True, f"{clause} equality", (reason,)))
99
+
100
+ if isinstance(relation, ir.Join) and relation.kind in {"left", "right"}:
101
+ padded = relation.right if relation.kind == "left" else relation.left
102
+ for (first, second), reason in _predicate_equalities(relation.conjuncts).items():
103
+ if first in padded.output_columns and second in padded.output_columns:
104
+ merge([*outputs[first], *outputs[second]], Result(True, "ON equality within the padded side", (reason,)))
105
+
106
+ if isinstance(relation, ir.Filter):
107
+ from sqlassert.rules.nullability import non_null_column
108
+
109
+ for (first, second), reason in _lax_equalities(relation).value.items():
110
+ definite = non_null_column(first)
111
+ if definite.value:
112
+ merge([first, second], Result(True, "The ON equality holds without padding", (reason,), [definite]))
113
+
114
+ if isinstance(relation, ir.SetOperation) and relation.operator == "union":
115
+ typed = {column: arms for column in relation.output_columns if (arms := _typed_arms(relation, column)) is not None}
116
+ for first, second in combinations(typed, 2):
117
+ arm_groups = [_equal_columns(arm) for arm in typed[first]]
118
+ if all(other in group.value for other, group in zip(typed[second], arm_groups)):
119
+ merge([first, second], Result(True, "Equal in both UNION inputs", (relation,), arm_groups))
120
+
121
+ grouped: dict[ir.OutputColumn, list[ir.OutputColumn]] = {}
122
+ for column in relation.output_columns:
123
+ grouped.setdefault(find(column), []).append(column)
124
+ members: dict[_Group, Result[bool]] = {}
125
+ for root, columns in grouped.items():
126
+ group = tuple(columns)
127
+ members[group] = (
128
+ Result(True, "Equal columns", group, evidence[root]) if evidence[root]
129
+ else Result(True, "A column equals itself", group)
130
+ )
131
+ value = EqualityGroups(relation, tuple(members))
132
+ return Result(value, "Equality groups", (relation,), list(members.values()), members=members)
133
+
134
+
135
+ # Ordered pairs of columns an equality relates, each with the conjunct that
136
+ # relates them.
137
+ type Equalities = dict[tuple[ir.OutputColumn, ir.OutputColumn], ir.ScalarExpr]
138
+
139
+
140
+ def _in_every_branch[Key](disjunction: ir.Or, facts: Callable[[tuple[ir.ScalarExpr, ...]], Mapping[Key, object]]) -> list[Key]:
141
+ """The facts every branch of an OR establishes: one of them holds on each row."""
142
+ first, *rest = (facts(ir.conjuncts(part)) for part in disjunction.parts)
143
+ return [key for key in first if all(key in branch for branch in rest)]
144
+
145
+
146
+ def _predicate_equalities(conjuncts: tuple[ir.ScalarExpr, ...]) -> Equalities:
147
+ """The column equalities every row satisfying `conjuncts` meets."""
148
+ pairs: Equalities = {}
149
+ for conjunct in conjuncts:
150
+ match conjunct:
151
+ case ir.Or():
152
+ pairs.update(dict.fromkeys(_in_every_branch(conjunct, _predicate_equalities), conjunct))
153
+ case (
154
+ ir.Equality(left=ir.ColumnRef(column=first), right=ir.ColumnRef(column=second))
155
+ | ir.NullSafeEquality(left=ir.ColumnRef(column=first), right=ir.ColumnRef(column=second))
156
+ ) if _same_type(first, second):
157
+ pairs[first, second] = pairs[second, first] = conjunct
158
+ return pairs
159
+
160
+
161
+ @analysis(Stratum.COMPARISON)
162
+ def _lax_equalities(relation: ir.RelationExpr) -> Result[Equalities]:
163
+ """Directed pairs: where the first is non-null, it equals the second."""
164
+ pairs: Equalities = {}
165
+ for source in _inputs(relation):
166
+ passed = _pass_through(relation, source)
167
+ for (first, second), reason in _lax_equalities(source).value.items():
168
+ for own in passed.get(first, ()):
169
+ for other in passed.get(second, ()):
170
+ pairs[own, other] = reason
171
+ if isinstance(relation, ir.Join) and relation.kind in {"left", "right"}:
172
+ padded, preserved = (relation.right, relation.left) if relation.kind == "left" else (relation.left, relation.right)
173
+ padded_outputs = _pass_through(relation, padded)
174
+ preserved_outputs = _pass_through(relation, preserved)
175
+ for (first, second), reason in _predicate_equalities(relation.conjuncts).items():
176
+ for own in padded_outputs.get(first, ()):
177
+ for other in preserved_outputs.get(second, ()):
178
+ pairs[own, other] = reason
179
+ return Result(pairs, "Lax equalities", (relation,))
180
+
181
+
182
+ def _predicate_constants(conjuncts: tuple[ir.ScalarExpr, ...]) -> dict[ir.OutputColumn, tuple[ir.LiteralValue | None, ir.ScalarExpr]]:
183
+ """The constant (SQL NULL included) each column has on every row
184
+ satisfying `conjuncts`, with the conjunct that fixes it."""
185
+ return {column: (value, conjunct) for (column, value), conjunct in _pinned_values(conjuncts).items()}
186
+
187
+
188
+ def _pinned_values(conjuncts: tuple[ir.ScalarExpr, ...]) -> dict[tuple[ir.OutputColumn, ir.LiteralValue | None], ir.ScalarExpr]:
189
+ pinned: dict[tuple[ir.OutputColumn, ir.LiteralValue | None], ir.ScalarExpr] = {}
190
+ for conjunct in conjuncts:
191
+ match conjunct:
192
+ case ir.Or():
193
+ pinned.update(dict.fromkeys(_in_every_branch(conjunct, _pinned_values), conjunct))
194
+ case ir.Equality(left=left, right=right) | ir.NullSafeEquality(left=left, right=right):
195
+ for column, literal in ((left, right), (right, left)):
196
+ if isinstance(column, ir.ColumnRef) and isinstance(literal, ir.Constant) and literal.value is not None:
197
+ if _pins(column.column, literal):
198
+ pinned[column.column, literal.value] = conjunct
199
+ case ir.IsNull(operand=ir.ColumnRef(column=column)):
200
+ pinned[column, None] = conjunct
201
+ return pinned
202
+
203
+
204
+ @analysis(Stratum.COMPARISON)
205
+ def _constant_value(column: ir.OutputColumn) -> Result[tuple[ir.LiteralValue | None] | None]:
206
+ """An exact constant, including SQL NULL, on every row carrying this column."""
207
+ relation = column.get_relation(current_arena().program).closed
208
+ unknown_value: Result[tuple[ir.LiteralValue | None] | None] = Result(None, "No exact constant is known", (column,))
209
+ match relation:
210
+ case ir.SetOperation(operator="union"):
211
+ if (arms := _typed_arms(relation, column)) is None:
212
+ return unknown_value
213
+ left, right = (_constant_value(arm) for arm in arms)
214
+ if left.value is not None and left.value == right.value:
215
+ return Result(left.value, "The same constant in both UNION inputs", (column,), [left, right])
216
+ return unknown_value
217
+ case ir.Filter(conjuncts=conjuncts):
218
+ match column.scalar_expr:
219
+ case ir.ColumnRef(column=source) if (constant := _predicate_constants(conjuncts).get(source)) is not None:
220
+ value, conjunct = constant
221
+ return Result((value,), "The WHERE clause fixes the value", (conjunct,))
222
+ case ir.ColumnRef(column=source):
223
+ return _constant_value(source)
224
+ case _:
225
+ return unknown_value
226
+ case ir.Project() | ir.Alias() | ir.NamedRelation() | ir.Distinct() | ir.Limit() | ir.QualifyByPartition():
227
+ match column.scalar_expr:
228
+ case ir.ColumnRef(column=source):
229
+ return _constant_value(source)
230
+ case ir.Constant(value=ir.LiteralValue() as literal):
231
+ return Result((literal,), "A literal is constant", (column,))
232
+ case ir.NullLiteral():
233
+ return Result((None,), "A NULL literal is constant", (column,))
234
+ case _:
235
+ return unknown_value
236
+ case ir.Join() | ir.Aggregate() | ir.SetOperation() | ir.OpaqueRelation():
237
+ # Padding, grouping, and the other set operations are not followed.
238
+ return unknown_value
239
+ case _:
240
+ assert_never(relation)
241
+
242
+
243
+ def _same_type(first: ir.OutputColumn, second: ir.OutputColumn) -> bool:
244
+ """Equalities are value identities only for known, matching comparison types."""
245
+ first_type = _comparison_type(first).value
246
+ return first is second or first_type is not None and first_type == _comparison_type(second).value
247
+
248
+
249
+ @analysis(Stratum.COMPARISON)
250
+ def _comparison_type(column: ir.OutputColumn) -> Result[str | None]:
251
+ relation = column.get_relation(current_arena().program)
252
+ if isinstance(relation, ir.SetOperation) and (arms := relation.arms(column)) is not None:
253
+ # Both inputs of one type: the output is that type.
254
+ left, right = (_comparison_type(arm) for arm in arms)
255
+ if left.value is not None and left.value == right.value:
256
+ return Result(left.value, "Both inputs of the set operation share the comparison type", (column,), [left, right])
257
+ match column.scalar_expr:
258
+ case ir.ColumnRef(column=source) | ir.AnyAggregate(input=ir.ColumnRef(column=source)) if not isinstance(relation, ir.SetOperation):
259
+ return _comparison_type(source)
260
+ case ir.Constant(value=ir.LiteralValue(type="numeric", text=text)) if _small_integer(text):
261
+ return Result("INT", "Integer literal", (column,))
262
+ case _:
263
+ return Result(column.comparison_type, "Declared comparison type", (column,))
264
+
265
+
266
+ @analysis(Stratum.COMPARISON)
267
+ def _identity_comparison(column: ir.OutputColumn) -> Result[bool]:
268
+ """Whether equal values of `column` are identical, from its declared type."""
269
+ relation = column.get_relation(current_arena().program)
270
+ if (both := _both_inputs(column, relation, _identity_comparison)) is not None:
271
+ return both
272
+ match column.scalar_expr:
273
+ case ir.ColumnRef(column=source) | ir.AnyAggregate(input=ir.ColumnRef(column=source)) if not isinstance(relation, ir.SetOperation):
274
+ # A picked value (min, max, any_value) is a value of its column.
275
+ return _identity_comparison(source)
276
+ case _:
277
+ return Result(column.identity_comparison, "Declared type compares by identity", (column,))
278
+
279
+
280
+ def _both_inputs(
281
+ column: ir.OutputColumn, relation: ir.RelationExpr | None, fact: Callable[[ir.OutputColumn], Result[bool]]
282
+ ) -> Result[bool] | None:
283
+ """A set operation's column has a type fact when both its input columns
284
+ have one comparison type and the fact: its type is theirs, not widened.
285
+ None when that is not shown, and the column's own declaration decides."""
286
+ if not isinstance(relation, ir.SetOperation) or (arms := relation.arms(column)) is None or not _same_type(*arms):
287
+ return None
288
+ left, right = (fact(arm) for arm in arms)
289
+ if not (left.value and right.value):
290
+ return None
291
+ return Result(True, "Both inputs of the set operation have it", (column,), [left, right])
292
+
293
+
294
+ def _pins(column: ir.OutputColumn, value: ir.ScalarExpr) -> bool:
295
+ """Whether equality can pin the column without a lossy coercion."""
296
+ if _binary_text(column).value:
297
+ match value:
298
+ case ir.Constant(value=ir.LiteralValue(type="string")):
299
+ return True
300
+ case ir.ColumnRef(column=other):
301
+ return _binary_text(other).value
302
+ case _:
303
+ return False
304
+ if not (_identity_comparison(column).value or _signed_integer(column)):
305
+ return False
306
+ match value:
307
+ case ir.ColumnRef(column=other):
308
+ return _same_type(column, other) or (
309
+ _signed_integer(column) and _signed_integer(other)
310
+ )
311
+ case ir.Constant(value=ir.LiteralValue(type="numeric", text=text)):
312
+ return "e" not in text.lower() and (exact_numeric(column).value or _exact_arithmetic(column))
313
+ case ir.Constant(value=ir.LiteralValue(type="boolean")):
314
+ return _comparison_type(column).value == "BOOLEAN"
315
+ case _:
316
+ return False
317
+
318
+
319
+ _SIGNED_INTEGERS = {"TINYINT", "SMALLINT", "INT", "INTEGER", "BIGINT", "HUGEINT", "INT128"}
320
+
321
+
322
+ def _small_integer(text: str) -> bool:
323
+ return re.fullmatch(r"-?[0-9]{1,10}", text) is not None and -(2**31) <= int(text) < 2**31
324
+
325
+
326
+ def _signed_integer(column: ir.OutputColumn) -> bool:
327
+ if _comparison_type(column).value in _SIGNED_INTEGERS:
328
+ return True
329
+ program = current_arena().program
330
+ while isinstance(column.scalar_expr, ir.ColumnRef) and not isinstance(column.get_relation(program), ir.SetOperation):
331
+ column = column.scalar_expr.column
332
+ if isinstance(column.scalar_expr, ir.Count):
333
+ return True
334
+ if not isinstance(column.scalar_expr, ir.Call):
335
+ return False
336
+ argument = column.scalar_expr.injective_argument
337
+ return isinstance(argument, ir.ColumnRef) and _comparison_type(argument.column).value in _SIGNED_INTEGERS and all(
338
+ node is argument or isinstance(node, ir.Constant) and node.value is not None
339
+ and node.value.type == "numeric" and _small_integer(node.value.text)
340
+ for node in column.scalar_expr.arguments
341
+ )
342
+
343
+
344
+ def _same_set_types(operation: ir.SetOperation, columns: Iterable[ir.OutputColumn]) -> bool:
345
+ """Whether set output columns retain the same types as their inputs."""
346
+ return all(_typed_arms(operation, column) is not None for column in columns)
347
+
348
+
349
+ def _typed_arms(operation: ir.SetOperation, column: ir.OutputColumn) -> tuple[ir.OutputColumn, ir.OutputColumn] | None:
350
+ """`column`'s input columns, when it keeps their type: its values are theirs."""
351
+ arms = operation.arms(column)
352
+ return arms if arms is not None and _same_type(*arms) else None
353
+
354
+
355
+ def _exact_arithmetic(column: ir.OutputColumn) -> bool:
356
+ """Whether `column` is an integer or decimal it computes: a `count`, or
357
+ exact arithmetic over an integer or decimal (`id + 7`)."""
358
+ program = current_arena().program
359
+ while isinstance(column.scalar_expr, ir.ColumnRef) and not isinstance(column.get_relation(program), ir.SetOperation):
360
+ column = column.scalar_expr.column
361
+ if isinstance(column.scalar_expr, ir.Count):
362
+ return True
363
+ if not isinstance(column.scalar_expr, ir.Call):
364
+ return False
365
+ source = ir.injective_input(column.scalar_expr)
366
+ return source is not None and exact_numeric(source).value
367
+
368
+
369
+ @analysis(Stratum.COMPARISON)
370
+ def _binary_text(column: ir.OutputColumn) -> Result[bool]:
371
+ """Whether `column` is text compared by identity, from its declared type."""
372
+ relation = column.get_relation(current_arena().program)
373
+ if (both := _both_inputs(column, relation, _binary_text)) is not None:
374
+ return both
375
+ match column.scalar_expr:
376
+ case ir.ColumnRef(column=source) if not isinstance(relation, ir.SetOperation):
377
+ return _binary_text(source)
378
+ case _:
379
+ return Result(column.binary_text, "Declared as text compared by identity", (column,))
380
+
381
+
382
+ @analysis(Stratum.COMPARISON)
383
+ def exact_numeric(column: ir.OutputColumn) -> Result[bool]:
384
+ """Whether `column` is an integer or decimal, from its declared type."""
385
+ relation = column.get_relation(current_arena().program)
386
+ if (both := _both_inputs(column, relation, exact_numeric)) is not None:
387
+ return both
388
+ match column.scalar_expr:
389
+ case ir.ColumnRef(column=source) | ir.AnyAggregate(input=ir.ColumnRef(column=source)) if not isinstance(relation, ir.SetOperation):
390
+ return exact_numeric(source)
391
+ case _:
392
+ return Result(column.exact_numeric, "Declared an integer or decimal", (column,))
393
+
394
+
395
+ def _inputs(relation: ir.RelationExpr) -> tuple[ir.RelationExpr, ...]:
396
+ """The inputs whose groups hold on `relation`'s pass-through columns.
397
+
398
+ Each output row of these takes its pass-through values from one row of
399
+ each listed input (or, for a padded side, NULL in every column).
400
+ """
401
+ relation = relation.closed
402
+ match relation:
403
+ case ir.Alias(source=source) | ir.NamedRelation(body=ir.RelationExpr() as source) | ir.Filter(input=source) | ir.Project(input=source) | ir.Limit(input=source) | ir.Aggregate(input=source) | ir.Distinct(input=source) | ir.QualifyByPartition(input=source):
404
+ return (source,)
405
+ case ir.Join(kind="inner" | "cross" | "left" | "right" | "full", left=left, right=right):
406
+ return (left, right)
407
+ case ir.Join(left=left):
408
+ # A semi or anti join keeps left rows; its right columns have no row.
409
+ return (left,)
410
+ case ir.SetOperation(operator="intersect" | "except", left=left) if _same_set_types(relation, relation.output_columns):
411
+ # Every output row equals some row of the left input.
412
+ return (left,)
413
+ case ir.SetOperation() | ir.NamedRelation() | ir.OpaqueRelation():
414
+ # A UNION row may come from either branch; the right one is not tracked.
415
+ return ()
416
+ case _:
417
+ assert_never(relation)
418
+
419
+
420
+ def _strict_conjuncts(relation: ir.RelationExpr) -> tuple[tuple[ir.ScalarExpr, ...], str]:
421
+ """The conjuncts true on every row of `relation`, and the clause they come from."""
422
+ match relation:
423
+ case ir.Filter(conjuncts=conjuncts):
424
+ return conjuncts, "WHERE"
425
+ case ir.Join(kind="inner" | "cross" | "semi", conjuncts=conjuncts):
426
+ # A semi join's on each output row with its matched right row.
427
+ return conjuncts, "ON"
428
+ case _:
429
+ # An outer join's ON holds on matched rows only; an anti join's on no output row.
430
+ return (), ""
431
+
432
+
433
+ def _pass_through(relation: ir.RelationExpr, source: ir.RelationExpr) -> dict[ir.OutputColumn, list[ir.OutputColumn]]:
434
+ """Each column of `source` that `relation` passes through, with the columns passing it."""
435
+ passed: dict[ir.OutputColumn, list[ir.OutputColumn]] = {}
436
+ for column in relation.output_columns:
437
+ match column.scalar_expr:
438
+ case ir.ColumnRef(column=upstream) if upstream in source.output_columns:
439
+ passed.setdefault(upstream, []).append(column)
440
+ case _:
441
+ pass # A computed column starts its own group.
442
+ return passed
@@ -0,0 +1,114 @@
1
+ """Exactly One Joins: every left row matches exactly one right row.
2
+
3
+ Three halves, each reported. At most one match is a Many To One Join, which further
4
+ conjuncts only strengthen. At least one match needs every conjunct to be an
5
+ equality between a left and a right column, and Referential Coverage of the
6
+ left columns, as one tuple, onto the right columns they are paired with: a
7
+ row of the right input carrying every left value then satisfies the whole ON.
8
+ Coverage of each column separately does not give a row matching all of them.
9
+ Any other conjunct may reject the covering row, so matching stays unknown.
10
+ `IS NOT DISTINCT FROM` pairs columns too: with the left columns non-null it
11
+ is `=`, and a NULL left value would match every right row whose column is
12
+ NULL (UNIQUE allows many), so non-null left columns stay required.
13
+ An ON that is always TRUE (none, for a CROSS JOIN) matches every right row,
14
+ so a right input that always has a row (a scalar aggregate) is matched.
15
+ Non-null left columns: a null equals nothing, and `MATCH SIMPLE` exempts a
16
+ row with any null referencing component. The input relations may be derived:
17
+ coverage, uniqueness and nullability each follow their own propagation, and
18
+ coverage onto a narrowed right input must hold on its own.
19
+ """
20
+
21
+ from typing import assert_never
22
+
23
+ from sqlassert import ir
24
+ from sqlassert.python_engine import Result, Stratum, analysis, all_of, unknown
25
+ from sqlassert.rules.foreign_key import referential_coverage
26
+ from sqlassert.rules.nullability import non_null_columns
27
+ from sqlassert.rules.join_cardinality import many_to_one_join
28
+
29
+
30
+ @analysis(Stratum.UNIQUE_JOIN)
31
+ def exactly_one_join(join: ir.Join) -> Result[bool]:
32
+ # As for a Many To One Join, the left row's matches decide it, except that an
33
+ # anti join drops every matched row.
34
+ if join.kind == "anti":
35
+ return unknown("An anti join drops the rows it matches", join)
36
+ at_most_one = _half("At most one match: the right predicate columns cover a Unique Set", (join,), many_to_one_join(join))
37
+ if all(_is_true(conjunct) for conjunct in join.conjuncts):
38
+ return at_most_one & _half(
39
+ "At least one match: ON is always TRUE, and the right input has a row", (join,), _has_a_row(join.right),
40
+ )
41
+ pairs, others = _cross_equalities(join)
42
+ if not pairs:
43
+ return at_most_one & unknown(
44
+ "At least one match needs an equality between a left and a right column", join
45
+ )
46
+ lefts = tuple(left for left, _ in pairs)
47
+ rights = tuple(right for _, right in pairs)
48
+ coverage = referential_coverage(lefts, rights)
49
+ if others:
50
+ coverage = all_of((coverage, *(
51
+ unknown("Only column-to-column equalities between the inputs are known to keep a covering row", conjunct)
52
+ for conjunct in others
53
+ )))
54
+ return all_of((
55
+ at_most_one,
56
+ _half("At least one match: the left columns reference the right predicate columns", (*lefts, *rights), coverage),
57
+ _half(
58
+ "Non-null left columns: a null left value matches no row", lefts, non_null_columns(frozenset(lefts))
59
+ ),
60
+ ))
61
+
62
+
63
+ def _is_true(conjunct: ir.ScalarExpr) -> bool:
64
+ return isinstance(conjunct, ir.Constant) and conjunct.value == ir.LiteralValue(type="boolean", text="TRUE")
65
+
66
+
67
+ def _has_a_row(relation: ir.RelationExpr) -> Result[bool]:
68
+ """Whether `relation` has at least one row on every instance: an
69
+ aggregate grouped by nothing has one even over no input rows, and an
70
+ Alias, Project or DISTINCT keeps it. HAVING (a Filter) may drop it."""
71
+ relation = relation.closed
72
+ match relation:
73
+ case ir.Aggregate(grouping_outputs=()):
74
+ return Result(True, "An aggregate grouped by nothing has one row, even over no input rows", (relation,))
75
+ case ir.Alias(source=source) | ir.NamedRelation(body=ir.RelationExpr() as source) | ir.Project(input=source) | ir.Distinct(input=source):
76
+ return _has_a_row(source)
77
+ case (
78
+ ir.Aggregate() | ir.NamedRelation() | ir.Join() | ir.Filter() | ir.Limit() | ir.SetOperation()
79
+ | ir.QualifyByPartition() | ir.OpaqueRelation() | ir.RecursiveRelation()
80
+ ):
81
+ return unknown("The right input may have no rows", relation)
82
+ case _:
83
+ assert_never(relation)
84
+
85
+
86
+ def _half(reason: str, subjects: tuple[object, ...], evidence: Result[bool]) -> Result[bool]:
87
+ return Result(evidence.value, reason, subjects, [evidence], kind="all")
88
+
89
+
90
+ def _cross_equalities(
91
+ join: ir.Join,
92
+ ) -> tuple[list[tuple[ir.OutputColumn, ir.OutputColumn]], list[ir.ScalarExpr]]:
93
+ """The (left, right) column pairs of ON's cross-input equalities, and every other conjunct."""
94
+ pairs: list[tuple[ir.OutputColumn, ir.OutputColumn]] = []
95
+ others: list[ir.ScalarExpr] = []
96
+ for conjunct in join.conjuncts:
97
+ match conjunct:
98
+ # IS NOT DISTINCT FROM matches NULL to NULL, but the left columns
99
+ # must be non-null anyway, and then it is `=`.
100
+ case (
101
+ ir.Equality(left=ir.ColumnRef(column=first), right=ir.ColumnRef(column=second))
102
+ | ir.NullSafeEquality(left=ir.ColumnRef(column=first), right=ir.ColumnRef(column=second))
103
+ ):
104
+ pair = next((
105
+ (left, right) for left, right in ((first, second), (second, first))
106
+ if left in join.left.output_columns and right in join.right.output_columns
107
+ ), None)
108
+ if pair is None:
109
+ others.append(conjunct) # Both columns on one side: a filter.
110
+ elif pair not in pairs:
111
+ pairs.append(pair)
112
+ case _:
113
+ others.append(conjunct) # A constant, expression, or opaque operand fixes no column pairing.
114
+ return pairs, others