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,904 @@
1
+ """Functional dependencies, their closure, and the Unique Sets closure proves.
2
+
3
+ Every relation has a Row Identity that tells its rows apart. A key is a
4
+ functional dependency onto it, an equality is a pair of dependencies, and a
5
+ constant is a dependency from the empty set, so one question decides
6
+ uniqueness: does the closure of a column set reach the Row Identity?
7
+
8
+ `_functional_dependencies(relation)` holds only the dependencies a relation
9
+ introduces itself, over its own output columns and Row Identities. The
10
+ dependencies of its inputs are not copied up: `_closure` maps the columns it
11
+ has reached into each input, takes the input's closure there, and maps the
12
+ result back. Columns an operation drops therefore still take part ("hide,
13
+ don't delete"), and each Alias reasons about its own rows even when two
14
+ Aliases share one Named Relation.
15
+
16
+ A strict dependency holds on every pair of rows, NULL agreeing with NULL; a
17
+ lax one only where its determinant is non-null. Closure steps through a lax
18
+ dependency only when every determinant column is definite: requested as
19
+ non-null by the caller, or proved non-null.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from collections.abc import Callable, Iterator
25
+ from dataclasses import dataclass, field
26
+ from itertools import combinations
27
+ from typing import assert_never
28
+
29
+ from sqlassert.diagnostics import quoted
30
+ from sqlassert import ir
31
+ from sqlassert.python_engine import Result, Stratum, all_of, analysis, any_of, current_arena, unknown
32
+ from sqlassert.rules.column_set import Attribute, Closure, RowIdentity
33
+ from sqlassert.rules.equality import _binary_text, _constant_value, _equal_columns, _identity_comparison, _pins, _predicate_constants, _predicate_equalities, _same_set_types, _signed_integer, _typed_arms, exact_numeric
34
+ from sqlassert.rules.nullability import Padding, _null_sources, _padded_sides, non_null_column, non_null_columns
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class Dependency:
39
+ """`determinant → dependent`; an empty determinant makes the dependent constant."""
40
+
41
+ determinant: frozenset[Attribute]
42
+ dependent: Attribute
43
+ strict: bool
44
+
45
+
46
+ type Dependencies = dict[Dependency, Result[bool]]
47
+
48
+
49
+ # Public analyses ---------------------------------------------------------------
50
+
51
+
52
+ @analysis(Stratum.UNIQUE_SET)
53
+ def unique_set(columns: frozenset[ir.OutputColumn]) -> Result[bool]:
54
+ relation = current_arena().program.relation_of(columns)
55
+ if relation is None:
56
+ return unknown("A unique set must have columns belonging to one relation", *columns)
57
+ return _reaches_row_identity(_closure(relation, frozenset(columns), frozenset(columns)))
58
+
59
+
60
+ @analysis(Stratum.UNIQUE_SET)
61
+ def non_null_unique_set(columns: frozenset[ir.OutputColumn]) -> Result[bool]:
62
+ return unique_set(columns) & non_null_columns(columns)
63
+
64
+
65
+ @analysis(Stratum.CLOSURE)
66
+ def functional_dependency(determinant: frozenset[ir.OutputColumn], dependent: frozenset[ir.OutputColumn]) -> Result[bool]:
67
+ relation = current_arena().program.relation_of(determinant | dependent)
68
+ if relation is None:
69
+ return unknown("A functional dependency must have columns belonging to one relation", *determinant, *dependent)
70
+ closure = _closure(relation, frozenset(determinant), frozenset(determinant))
71
+ ordered = [column for column in relation.output_columns if column in dependent]
72
+ return all_of(
73
+ closure.members[column] if column in closure.value.columns
74
+ else unknown(f"{quoted(column.name)} is not determined", column)
75
+ for column in ordered
76
+ )
77
+
78
+
79
+ def _reaches_row_identity(closure: Result[Closure]) -> Result[bool]:
80
+ identity = RowIdentity(closure.value.relation)
81
+ if identity in closure.value.columns:
82
+ return Result(True, "The columns determine the row", (closure.value.relation,), [closure.members[identity]])
83
+ gaps = _uncovered_keys(closure)
84
+ if not gaps:
85
+ return unknown("No known unique set on this relation", closure.value.relation)
86
+ return any_of(gaps)
87
+
88
+
89
+ def _uncovered_keys(closure: Result[Closure]) -> list[Result[bool]]:
90
+ """Each known key the closure misses, naming its missing columns, down
91
+ through every input the closure looked into."""
92
+ relation = closure.value.relation
93
+ identity = RowIdentity(relation)
94
+ gaps: list[Result[bool]] = []
95
+ for dependency, evidence in _functional_dependencies(relation).value.items():
96
+ if dependency.dependent != identity or dependency.determinant <= closure.value.columns:
97
+ continue
98
+ missing = [column for column in relation.output_columns if column in dependency.determinant - closure.value.columns]
99
+ gaps.append(evidence & unknown("Unique-set columns are not covered", *missing))
100
+ for premise in closure.value.inputs:
101
+ if RowIdentity(premise.value.relation) not in premise.value.columns:
102
+ gaps.extend(_uncovered_keys(premise))
103
+ return gaps
104
+
105
+
106
+ # Closure -----------------------------------------------------------------------
107
+
108
+
109
+ @analysis(Stratum.CLOSURE)
110
+ def _closure(relation: ir.RelationExpr, columns: frozenset[Attribute], definite: frozenset[Attribute]) -> Result[Closure]:
111
+ """Every attribute of `relation` that `columns` determine, on the pairs of
112
+ rows where every `definite` attribute is non-null.
113
+
114
+ Counter-based (Paulley's FD-graph closure): a dependency fires once all of
115
+ its determinant is reached. Each reached attribute's member cites the
116
+ dependency or input that reached it.
117
+ """
118
+ reached: dict[Attribute, Result[bool]] = {}
119
+ queue: list[Attribute] = []
120
+
121
+ def reach(attribute: Attribute, evidence: Result[bool]) -> None:
122
+ if attribute in reached:
123
+ reached[attribute] = reached[attribute] | evidence
124
+ return
125
+ reached[attribute] = evidence
126
+ queue.append(attribute)
127
+
128
+ def is_definite(attribute: Attribute) -> bool:
129
+ return attribute in definite or _definite(relation, attribute) or _padded_with(relation, attribute, definite)
130
+
131
+ dependencies = _functional_dependencies(relation)
132
+ waiting: dict[Dependency, int] = {}
133
+ uses: dict[Attribute, list[Dependency]] = {}
134
+ for dependency in dependencies.value:
135
+ waiting[dependency] = len(dependency.determinant)
136
+ for attribute in dependency.determinant:
137
+ uses.setdefault(attribute, []).append(dependency)
138
+
139
+ def fire(dependency: Dependency) -> None:
140
+ if not dependency.strict and not all(is_definite(attribute) for attribute in dependency.determinant):
141
+ return # Lax steps need non-null middles (Paulley fd7b).
142
+ premises = [dependencies.value[dependency], *(reached[attribute] for attribute in dependency.determinant)]
143
+ reach(dependency.dependent, Result(True, "Functional dependency", (relation, dependency.dependent), premises))
144
+
145
+ for column in columns:
146
+ reach(column, Result(True, "In the requested set", (column,)))
147
+ for dependency, count in waiting.items():
148
+ if count == 0:
149
+ fire(dependency)
150
+ inputs: dict[int, Result[Closure]] = {}
151
+ while True:
152
+ while queue:
153
+ attribute = queue.pop()
154
+ if attribute == RowIdentity(relation):
155
+ for column in _row_attributes(relation):
156
+ reach(column, Result(True, "The row identity determines every column", (relation,), [reached[attribute]]))
157
+ for dependency in uses.get(attribute, ()):
158
+ waiting[dependency] -= 1
159
+ if waiting[dependency] == 0:
160
+ fire(dependency)
161
+ for index, delegation in enumerate(_delegations(relation)):
162
+ closure = delegation.run(reached, is_definite)
163
+ if closure is None:
164
+ continue
165
+ inputs[index] = closure
166
+ for source, attributes in delegation.back.items():
167
+ for attribute in attributes if source in closure.value.columns else ():
168
+ if attribute not in reached:
169
+ reach(attribute, Result(True, delegation.reason, (relation, attribute), [closure.members[source]]))
170
+ for attribute, sources in delegation.computed.items():
171
+ if sources <= closure.value.columns and attribute not in reached:
172
+ reason = "A deterministic function of determined input columns"
173
+ reach(attribute, Result(True, reason, (relation, attribute), [closure.members[source] for source in sources]))
174
+ if isinstance(relation, ir.SetOperation) and relation.operator == "union":
175
+ for attribute, proof in _union_closure(relation, reached, is_definite):
176
+ if attribute not in reached:
177
+ reach(attribute, proof)
178
+ if not queue:
179
+ break
180
+ value = Closure(relation, set(reached), tuple(inputs.values()))
181
+ return Result(value, "Closure", (relation,), list(inputs.values()), members=reached)
182
+
183
+
184
+ def _union_closure(
185
+ relation: ir.SetOperation, reached: dict[Attribute, Result[bool]], is_definite: Callable[[Attribute], bool]
186
+ ) -> Iterator[tuple[Attribute, Result[bool]]]:
187
+ """What a UNION's reached columns determine across its inputs."""
188
+ yield from _separated_inputs(relation, reached, is_definite)
189
+ yield from _shared_table_rows(relation, reached, is_definite)
190
+
191
+
192
+ def _separated_inputs(
193
+ relation: ir.SetOperation, reached: dict[Attribute, Result[bool]], is_definite: Callable[[Attribute], bool]
194
+ ) -> Iterator[tuple[Attribute, Result[bool]]]:
195
+ """A reached tag, constant and different in each input, keeps rows of one
196
+ input from agreeing with rows of the other; within each input, its own
197
+ closure decides. Both input closures start from every reached column,
198
+ whichever tag separates, so the first such tag suffices."""
199
+ arms = {column: pair for column in relation.output_columns if (pair := _typed_arms(relation, column)) is not None}
200
+ for tag, (left_tag, right_tag) in arms.items():
201
+ if tag not in reached:
202
+ continue
203
+ first, second = _constant_value(left_tag), _constant_value(right_tag)
204
+ if first.value is None or second.value is None or not _distinct_tags((left_tag, right_tag), first.value[0], second.value[0]):
205
+ continue
206
+ determined = [column for column in arms if column in reached]
207
+ closures = [
208
+ _closure(source, frozenset(arms[column][side] for column in determined),
209
+ frozenset(arms[column][side] for column in determined if is_definite(column)))
210
+ for side, source in enumerate((relation.left, relation.right))
211
+ ]
212
+ for attribute, (a, b) in [*arms.items(), (RowIdentity(relation), (RowIdentity(relation.left), RowIdentity(relation.right)))]:
213
+ if a in closures[0].members and b in closures[1].members:
214
+ yield attribute, Result(True, "The determinant separates the UNION inputs and determines the value in both",
215
+ (relation, tag), [first, second, reached[tag], closures[0].members[a], closures[1].members[b]])
216
+ return
217
+
218
+
219
+ # DOUBLE holds every integer of up to 15 digits exactly, so tags that short
220
+ # stay distinct whichever numeric type an engine gives the literal.
221
+ _EXACT_DIGITS = 15
222
+
223
+
224
+ def _distinct_tags(arms: tuple[ir.OutputColumn, ir.OutputColumn], first: ir.LiteralValue | None, second: ir.LiteralValue | None) -> bool:
225
+ """Whether the constants `first` and `second` of a UNION's input columns
226
+ `arms` never compare equal."""
227
+ if first is None or second is None:
228
+ return first != second
229
+ if first.type == second.type == "string" and all(_binary_text(arm).value for arm in arms):
230
+ return first != second
231
+ if first.type == second.type == "numeric":
232
+ return (
233
+ all(_signed_integer(arm) or isinstance(arm.scalar_expr, ir.Constant) for arm in arms)
234
+ and all(value.text.lstrip("-").isdigit() and len(value.text.lstrip("-")) <= _EXACT_DIGITS for value in (first, second))
235
+ and int(first.text) != int(second.text)
236
+ )
237
+ return False
238
+
239
+
240
+ def _shared_table_rows(
241
+ relation: ir.SetOperation, reached: dict[Attribute, Result[bool]], is_definite: Callable[[Attribute], bool]
242
+ ) -> Iterator[tuple[Attribute, Result[bool]]]:
243
+ """Both UNION inputs copying one table's columns along one path each: a
244
+ key of that table among the reached columns picks one table row, from
245
+ whichever input a row came, and that row fixes every column copied along
246
+ the same paths. `SELECT empno, deptno FROM emp WHERE deptno = 10 UNION
247
+ ALL SELECT empno, deptno FROM emp WHERE deptno = 20` keeps `empno ->
248
+ deptno`."""
249
+ paths: dict[tuple[tuple[ir.RelationExpr, ...], tuple[ir.RelationExpr, ...]], list[tuple[ir.OutputColumn, ir.OutputColumn]]] = {}
250
+ for column in relation.output_columns:
251
+ if (arms := _typed_arms(relation, column)) is None:
252
+ continue
253
+ left, right = (_table_column(arm) for arm in arms)
254
+ if left is not None and right is not None and left[1] is right[1]:
255
+ paths.setdefault((left[0], right[0]), []).append((column, left[1]))
256
+ program = current_arena().program
257
+ for members in paths.values():
258
+ determinant = [(column, source) for column, source in members if column in reached and _identity_comparison(column).value]
259
+ if not determinant:
260
+ continue
261
+ table = determinant[0][1].get_relation(program)
262
+ closure = _closure(
263
+ table, frozenset(source for _, source in determinant),
264
+ frozenset(source for column, source in determinant if is_definite(column)),
265
+ )
266
+ if RowIdentity(table) not in closure.value.columns:
267
+ continue
268
+ proof = Result(True, "Both UNION inputs copy one row of the table, which the determinant picks", (relation, table),
269
+ [closure.members[RowIdentity(table)], *(reached[column] for column, _ in determinant)])
270
+ for column, _ in members:
271
+ yield column, proof
272
+
273
+
274
+ def _table_column(column: ir.OutputColumn) -> tuple[tuple[ir.RelationExpr, ...], ir.OutputColumn] | None:
275
+ """The table column `column` copies and the relations it passes through,
276
+ or None when it is computed, grouped away, or read from a set operation.
277
+
278
+ Columns copied along one path carry one table row's values on each row:
279
+ each relation on it keeps a row's columns together (a join side, a group's
280
+ shared grouping values), and a padded row is NULL on all of them."""
281
+ program = current_arena().program
282
+ path: list[ir.RelationExpr] = []
283
+ while True:
284
+ relation = column.get_relation(program).closed
285
+ path.append(relation)
286
+ match relation:
287
+ case ir.NamedRelation(role=ir.RelationRole.TABLE):
288
+ return tuple(path), column
289
+ case ir.Join(left=left, right=right) if left is right:
290
+ return None # Two rows of one relation, on one path.
291
+ case ir.Aggregate(grouping_outputs=grouping) if column not in grouping:
292
+ return None
293
+ case ir.SetOperation() | ir.OpaqueRelation():
294
+ return None
295
+ case (
296
+ ir.NamedRelation() | ir.Alias() | ir.Join() | ir.Filter() | ir.Project() | ir.Limit()
297
+ | ir.Aggregate() | ir.Distinct() | ir.QualifyByPartition()
298
+ ):
299
+ pass
300
+ case _:
301
+ assert_never(relation)
302
+ if not isinstance(column.scalar_expr, ir.ColumnRef):
303
+ return None
304
+ column = column.scalar_expr.column
305
+
306
+
307
+ def _row_attributes(relation: ir.RelationExpr) -> tuple[Attribute, ...]:
308
+ match relation:
309
+ case ir.Join(kind="semi" | "anti", left=left):
310
+ return (*relation.output_columns, RowIdentity(left))
311
+ case ir.Join(left=left, right=right):
312
+ return (*relation.output_columns, RowIdentity(left), RowIdentity(right))
313
+ case _:
314
+ return relation.output_columns
315
+
316
+
317
+ def _definite(relation: ir.RelationExpr, attribute: Attribute) -> bool:
318
+ """Whether `attribute` is non-null on every row of `relation`."""
319
+ match attribute:
320
+ case RowIdentity(relation=owner) if owner is relation:
321
+ return True
322
+ case RowIdentity(relation=side):
323
+ # An input's identity at a join: NULL on the rows that pad its side.
324
+ return isinstance(relation, ir.Join) and (side is relation.left) not in _padded_sides(relation)
325
+ case ir.OutputColumn():
326
+ return non_null_column(attribute).value
327
+
328
+
329
+ def _padded_with(relation: ir.RelationExpr, attribute: Attribute, definite: frozenset[Attribute]) -> bool:
330
+ """Whether `attribute` is non-null wherever the `definite` columns are:
331
+ its only null sources are paddings that make one of them NULL too. Past
332
+ `d LEFT JOIN emp e ON d.deptno = e.deptno`, `e.deptno` is NULL only on
333
+ padded rows (ON rejects NULL on the others), so it is non-null on every
334
+ row where `e.empno` is."""
335
+ if isinstance(attribute, RowIdentity) and isinstance(relation, ir.Join):
336
+ return any(column in definite for column in _pass_through(relation, attribute.relation))
337
+ if not isinstance(attribute, ir.OutputColumn) or not definite:
338
+ return False
339
+ sources = _null_sources(attribute).value
340
+ covered = {
341
+ source for column in definite if isinstance(column, ir.OutputColumn)
342
+ for source in _null_sources(column).value if isinstance(source, Padding)
343
+ }
344
+ return bool(sources) and sources <= covered
345
+
346
+
347
+ @dataclass(frozen=True)
348
+ class _Delegation:
349
+ """How rows of a relation map onto rows of one input, for taking closure there.
350
+
351
+ `down` maps the relation's attributes to the input's; `back` maps input
352
+ attributes reached there back up, each to every attribute carrying it
353
+ (`SELECT deptno, deptno AS deptno2` passes one input column twice), and
354
+ `computed` maps each of the relation's columns computed from input
355
+ attributes to them: reaching all of them reaches it. `valid` says whether two rows agreeing on the reached
356
+ attributes may be compared as input rows at all.
357
+ """
358
+
359
+ input: ir.RelationExpr
360
+ down: dict[Attribute, Attribute]
361
+ back: dict[Attribute, tuple[Attribute, ...]]
362
+ reason: str
363
+ valid: Callable[[dict[Attribute, Result[bool]], Callable[[Attribute], bool]], bool] | None = None
364
+ computed: dict[Attribute, frozenset[Attribute]] = field(default_factory=dict)
365
+
366
+ def run(self, reached: dict[Attribute, Result[bool]], is_definite: Callable[[Attribute], bool]) -> Result[Closure] | None:
367
+ if self.valid is not None and not self.valid(reached, is_definite):
368
+ return None
369
+ columns = frozenset(self.down[attribute] for attribute in reached if attribute in self.down)
370
+ definite = frozenset(self.down[attribute] for attribute in reached if attribute in self.down and is_definite(attribute))
371
+ return _closure(self.input, columns, definite)
372
+
373
+
374
+ def _delegations(relation: ir.RelationExpr) -> list[_Delegation]:
375
+ relation = relation.closed
376
+ match relation:
377
+ 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.QualifyByPartition(input=source):
378
+ return [_row_preserving(relation, source)]
379
+ case ir.Join(kind="inner" | "cross" | "left" | "right" | "full"):
380
+ return [_join_side(relation, True), _join_side(relation, False)]
381
+ case ir.Join(kind="semi" | "anti", left=source):
382
+ # Each output row is one left row.
383
+ return [_row_preserving(relation, source)]
384
+ case ir.Aggregate(input=source):
385
+ grouped = _grouped(relation, source)
386
+ return [grouped, *_picked(relation, grouped)]
387
+ case ir.Distinct(input=source):
388
+ return [_grouped(relation, source)]
389
+ case ir.SetOperation(operator="intersect" | "except", left=source):
390
+ # A cast in the set operation may collapse distinct input rows.
391
+ if not _same_set_types(relation, relation.output_columns):
392
+ return []
393
+ delegations = [_grouped(relation, source)]
394
+ if relation.operator == "intersect" and all(
395
+ _identity_comparison(column).value for column in (*source.output_columns, *relation.right.output_columns)
396
+ ):
397
+ down: dict[Attribute, Attribute] = dict(zip(relation.output_columns, relation.right.output_columns))
398
+ back = _inverse(down)
399
+ back[RowIdentity(relation.right)] = (RowIdentity(relation),)
400
+ delegations.append(_Delegation(relation.right, down, back, "Determined in the matching INTERSECT input"))
401
+ return delegations
402
+ case ir.Join() | ir.SetOperation() | ir.NamedRelation() | ir.OpaqueRelation():
403
+ return []
404
+ case _:
405
+ assert_never(relation)
406
+
407
+
408
+ def _pass_through(relation: ir.RelationExpr, source: ir.RelationExpr) -> dict[ir.OutputColumn, ir.OutputColumn]:
409
+ """Each output column that passes an input column through, with that column."""
410
+ mapping: dict[ir.OutputColumn, ir.OutputColumn] = {}
411
+ for column in relation.output_columns:
412
+ match column.scalar_expr:
413
+ case ir.ColumnRef(column=upstream) if upstream in source.output_columns:
414
+ mapping[column] = upstream
415
+ case _:
416
+ pass # A computed column passes nothing through.
417
+ return mapping
418
+
419
+
420
+ def _one_to_one(relation: ir.RelationExpr, source: ir.RelationExpr) -> dict[ir.OutputColumn, ir.OutputColumn]:
421
+ """Each output column that is an input column, or a one-to-one function
422
+ of an integer or decimal one (`a + 1`), with that column: equal on one,
423
+ equal on the other."""
424
+ passed = _pass_through(relation, source)
425
+ mapping: dict[ir.OutputColumn, ir.OutputColumn] = {}
426
+ for column in relation.output_columns:
427
+ upstream = ir.injective_input(column.scalar_expr)
428
+ if column not in passed and upstream in source.output_columns and exact_numeric(upstream).value:
429
+ mapping[column] = upstream
430
+ return mapping | passed
431
+
432
+
433
+ def _inverse(down: dict[Attribute, Attribute]) -> dict[Attribute, tuple[Attribute, ...]]:
434
+ """Each input attribute `down` reaches, with every attribute mapped onto it."""
435
+ back: dict[Attribute, tuple[Attribute, ...]] = {}
436
+ for own, upstream in down.items():
437
+ back[upstream] = (*back.get(upstream, ()), own)
438
+ return back
439
+
440
+
441
+ def _row_preserving(relation: ir.RelationExpr, source: ir.RelationExpr) -> _Delegation:
442
+ """Each output row is one input row, so every input dependency holds."""
443
+ down: dict[Attribute, Attribute] = {own: upstream for own, upstream in _one_to_one(relation, source).items()}
444
+ down[RowIdentity(relation)] = RowIdentity(source)
445
+ return _Delegation(
446
+ source, down, _inverse(down), "Determined in the input",
447
+ computed=_computed(relation, source),
448
+ )
449
+
450
+
451
+ def _grouped(relation: ir.RelationExpr, source: ir.RelationExpr) -> _Delegation:
452
+ """Each output row stands for input rows that share its pass-through values.
453
+
454
+ Two output rows that agree on some of those values have representatives
455
+ that agree on them, so whatever they determine in the input is equal for
456
+ the two representatives. That carries back to an output column only if it
457
+ is a pass-through value (or, for an aggregate's AnyAggregate column, a
458
+ value constant across the group); and to the Row Identity because one
459
+ input row belongs to one output row.
460
+ """
461
+ down: dict[Attribute, Attribute] = {own: upstream for own, upstream in _one_to_one(relation, source).items()}
462
+ back = _inverse(down)
463
+ back[RowIdentity(source)] = (RowIdentity(relation),)
464
+ if isinstance(relation, ir.Aggregate):
465
+ grouping = frozenset(down[column] for column in relation.grouping_outputs if column in down)
466
+ constant = _closure(source, grouping, frozenset()).value.columns
467
+ down = {column: upstream for column, upstream in down.items() if column in relation.grouping_outputs}
468
+ for column in relation.output_columns:
469
+ # Count-sensitive and opaque aggregates are new values.
470
+ upstream = _picked_input(column.scalar_expr)
471
+ if upstream is not None and upstream in constant:
472
+ back[upstream] = (*back.get(upstream, ()), column)
473
+ # A computed column of an Aggregate that is not a grouping item wraps its
474
+ # value in AnyAggregate, so only grouping items and DISTINCT values remain.
475
+ return _Delegation(source, down, back, "Determined in the input rows", computed=_computed(relation, source))
476
+
477
+
478
+ def _picked(aggregate: ir.Aggregate, base: _Delegation) -> list[_Delegation]:
479
+ """Each output row of an aggregate, seen through one AnyAggregate of an
480
+ input column (min, max, any_value, a column the grouping determines): its value is that
481
+ column's value on one row of the group, NULL only if the group has a NULL
482
+ there. Groups are disjoint, so two output rows' picked rows are distinct
483
+ input rows, and a one-column Unique Set of the input makes the picked
484
+ column one of the output. One column at a time: two aggregates may pick
485
+ different rows (`min(key1), max(key2)` of a composite key)."""
486
+ source = base.input
487
+ delegations = []
488
+ for column in aggregate.output_columns:
489
+ upstream = _picked_input(column.scalar_expr)
490
+ if upstream is None or upstream not in source.output_columns:
491
+ continue # Other aggregates are no one row's value.
492
+ back = dict(base.back)
493
+ back[upstream] = tuple(dict.fromkeys((*back.get(upstream, ()), column)))
494
+ delegations.append(_Delegation(
495
+ source, base.down | {column: upstream}, back, "Determined in the row the aggregate picks",
496
+ lambda reached, is_definite, column=column: column in reached, base.computed,
497
+ ))
498
+ return delegations
499
+
500
+
501
+ def _picked_input(expression: ir.ScalarExpr) -> ir.OutputColumn | None:
502
+ """The input column whose value on the row an AnyAggregate picks
503
+ `expression` is a one-to-one function of: the AnyAggregate of that
504
+ column, or one with an injective Builtin inside it or around it
505
+ (`max(empno + 1)`, `max(empno) + 1`) when the column is an integer or
506
+ decimal (`ir.injective_input`)."""
507
+ match expression.closed:
508
+ case ir.AnyAggregate(input=ir.ColumnRef(column=column)):
509
+ return column
510
+ case ir.AnyAggregate(input=value):
511
+ column = ir.injective_input(value)
512
+ case ir.Call(injective_argument=ir.ScalarExpr() as argument):
513
+ column = _picked_input(argument)
514
+ case _:
515
+ return None
516
+ return column if column is not None and exact_numeric(column).value else None
517
+
518
+
519
+ def _computed(relation: ir.RelationExpr, source: ir.RelationExpr) -> dict[Attribute, frozenset[Attribute]]:
520
+ """Paulley §3.1.4: each column computed from columns of `source` by a pure
521
+ function, with those columns. Only columns compared by identity qualify:
522
+ under NOCASE `'a' = 'A'` while `upper(x) || x` tells them apart, and a
523
+ DOUBLE's `-0.0 = 0.0` while its text does not."""
524
+ computed: dict[Attribute, frozenset[Attribute]] = {}
525
+ for column in relation.output_columns:
526
+ if isinstance(column.scalar_expr, ir.ColumnRef):
527
+ continue # Pass-through columns map back directly.
528
+ inputs = _identity_inputs(column.scalar_expr, source.output_columns)
529
+ if inputs is not None:
530
+ computed[column] = frozenset(inputs)
531
+ return computed
532
+
533
+
534
+ def _identity_inputs(expression: ir.ScalarExpr, columns: tuple[ir.OutputColumn, ...]) -> tuple[ir.OutputColumn, ...] | None:
535
+ """The columns `expression` is a pure function of, when all are among
536
+ `columns` and compared by identity."""
537
+ inputs = ir.determinants(expression)
538
+ if inputs is None or not all(column in columns and _identity_comparison(column).value for column in inputs):
539
+ return None
540
+ return inputs
541
+
542
+
543
+ def _join_side(join: ir.Join, left: bool) -> _Delegation:
544
+ side = join.left if left else join.right
545
+ offset = 0 if left else len(join.left.output_columns)
546
+ down: dict[Attribute, Attribute] = {
547
+ own: upstream for own, upstream in zip(join.output_columns[offset:offset + len(side.output_columns)], side.output_columns)
548
+ }
549
+ down[RowIdentity(side)] = RowIdentity(side)
550
+ back = _inverse(down)
551
+ if left not in _padded_sides(join):
552
+ return _Delegation(side, down, back, "Determined in the joined input")
553
+
554
+ def valid(reached, is_definite) -> bool:
555
+ # A padded side's columns are all NULL on padded rows. Comparing two
556
+ # rows as input rows is sound when they are both matched or both
557
+ # padded: when some reached column of the side is NULL only on padded
558
+ # rows (Paulley's η), or when the other side fixes which rows match.
559
+ for attribute in reached:
560
+ if attribute == RowIdentity(side) or (attribute in down and is_definite(attribute)):
561
+ return True
562
+ if attribute in down and isinstance(attribute, ir.OutputColumn):
563
+ if _null_sources(attribute).value <= {Padding(join, left)}:
564
+ return True
565
+ if join.kind == "full":
566
+ return False # The other side pads too: its columns may be NULL.
567
+ status = _match_status(join, left)
568
+ return status is not None and status <= set(reached)
569
+
570
+ return _Delegation(side, down, back, "Determined in the null-supplying input", valid)
571
+
572
+
573
+ def _match_status(join: ir.Join, padded_left: bool) -> frozenset[Attribute] | None:
574
+ """Attributes of the side opposite the padding that fix which rows match."""
575
+ if join.kind not in {"left", "right", "full"}:
576
+ return None
577
+ preserved = join.right if padded_left else join.left
578
+ outputs = _join_outputs(join)
579
+ referenced = set()
580
+ for conjunct in join.conjuncts:
581
+ operands = _recognized_operands(conjunct)
582
+ if operands is not None:
583
+ reads = [operand.column for operand in operands if isinstance(operand, ir.ColumnRef)]
584
+ else:
585
+ # Paulley Lemma 9 (L6): a pure conjunct is fixed by the preserved
586
+ # columns it reads, when those compare by identity (under NOCASE
587
+ # `'a' = 'A'` while `x LIKE 'a%'` tells them apart).
588
+ inputs = ir.determinants(conjunct)
589
+ reads = [column for column in inputs or () if column in preserved.output_columns]
590
+ if inputs is None or not all(_identity_comparison(column).value for column in reads):
591
+ # Volatile, opaque, or read under a collation: only the preserved row fixes it.
592
+ return frozenset({RowIdentity(preserved)})
593
+ referenced.update(outputs[column] for column in reads if column in preserved.output_columns)
594
+ return frozenset(referenced)
595
+
596
+
597
+ def _recognized_operands(conjunct: ir.ScalarExpr) -> tuple[ir.ScalarExpr, ...] | None:
598
+ """A recognized conjunct's operands, when each is a column or a literal."""
599
+ match conjunct:
600
+ case ir.Equality(left=left, right=right) | ir.NullSafeEquality(left=left, right=right):
601
+ operands: tuple[ir.ScalarExpr, ...] = (left, right)
602
+ case ir.IsNull(operand=operand) | ir.IsNotNull(operand=operand):
603
+ operands = (operand,)
604
+ case _:
605
+ return None
606
+ if all(isinstance(operand, ir.ColumnRef | ir.Constant | ir.NullLiteral) for operand in operands):
607
+ return operands
608
+ return None
609
+
610
+
611
+ def _join_outputs(join: ir.Join) -> dict[ir.OutputColumn, ir.OutputColumn]:
612
+ """Each input column of `join` with the output column passing it through."""
613
+ return dict(zip((*join.left.output_columns, *join.right.output_columns), join.output_columns))
614
+
615
+
616
+ # Functional dependencies ---------------------------------------------------------
617
+
618
+
619
+ @analysis(Stratum.FUNCTIONAL_DEPENDENCY)
620
+ def _functional_dependencies(relation: ir.RelationExpr) -> Result[Dependencies]:
621
+ """The dependencies `relation` introduces itself, each with its evidence."""
622
+ dependencies: Dependencies = {}
623
+
624
+ def add(determinant, dependent: Attribute, strict: bool, evidence: Result[bool]) -> None:
625
+ dependency = Dependency(frozenset(determinant), dependent, strict)
626
+ dependencies[dependency] = dependencies[dependency] | evidence if dependency in dependencies else evidence
627
+
628
+ identity = RowIdentity(relation)
629
+ columns = set(relation.output_columns)
630
+ for (name, arguments), accepted in current_arena().accepted.items():
631
+ known = dict(arguments)
632
+ match name:
633
+ case "unique_set" if known["columns"] <= columns:
634
+ add(known["columns"], identity, False, any_of(accepted))
635
+ case "functional_dependency" if known["determinant"] | known["dependent"] <= columns:
636
+ for dependent in known["dependent"]:
637
+ add(known["determinant"], dependent, False, any_of(accepted))
638
+ case _:
639
+ pass # Other Knowledge is not a dependency of this relation.
640
+
641
+ for column in relation.output_columns:
642
+ match column.scalar_expr:
643
+ case ir.Constant() | ir.NullLiteral():
644
+ add((), column, True, Result(True, "A literal is constant", (column,)))
645
+ case _:
646
+ pass # Other expressions introduce no dependency here.
647
+
648
+ relation = relation.closed
649
+
650
+ if isinstance(relation, ir.SetOperation) and relation.operator == "union":
651
+ for column in relation.output_columns:
652
+ constant = _constant_value(column)
653
+ if constant.value is not None:
654
+ add((), column, True, Result(True, "The UNION column is constant", (column,), [constant]))
655
+ if _identity_comparison(column).value:
656
+ equal = _equal_columns(column)
657
+ for other in equal.value - {column}:
658
+ add((other,), column, True, Result(True, "The UNION columns are equal", (column, other), [equal]))
659
+
660
+ match relation:
661
+ case ir.Filter(input=source, conjuncts=conjuncts):
662
+ outputs = {upstream: own for own, upstream in _pass_through(relation, source).items()}
663
+ for determinant, dependent, evidence in _equality_dependencies(conjuncts, outputs, "WHERE"):
664
+ add(determinant, dependent, True, evidence)
665
+ case ir.Join():
666
+ for determinant, dependent, strict, evidence in _join_dependencies(relation):
667
+ add(determinant, dependent, strict, evidence)
668
+ case ir.Aggregate(grouping_outputs=grouping):
669
+ add(grouping, identity, True, Result(True, "GROUP BY makes its grouping columns a key", (relation,)))
670
+ case ir.Distinct():
671
+ add(relation.output_columns, identity, True, Result(True, "DISTINCT makes its output columns a key", (relation,)))
672
+ case ir.QualifyByPartition(partition_outputs=partition):
673
+ add(partition, identity, True, Result(True, "One row is kept per partition", (relation,)))
674
+ case ir.SetOperation(distinct=True):
675
+ add(relation.output_columns, identity, True, Result(True, f"{relation.operator.upper()} removes duplicate rows", (relation,)))
676
+ case ir.Limit(count=int() as count) if count <= 1:
677
+ add((), identity, True, Result(True, "LIMIT keeps at most one row", (relation,)))
678
+ case ir.Alias() | ir.NamedRelation() | ir.Project() | ir.Limit() | ir.SetOperation() | ir.OpaqueRelation():
679
+ pass
680
+ case _:
681
+ assert_never(relation)
682
+ return Result(dependencies, "Functional dependencies", (relation,), list(dependencies.values()))
683
+
684
+
685
+ def _equality_dependencies(conjuncts: tuple[ir.ScalarExpr, ...], outputs: dict[ir.OutputColumn, ir.OutputColumn], clause: str):
686
+ """Dependencies of conjuncts that hold on every row: `a = b` and
687
+ `a IS NOT DISTINCT FROM b` both ways, `a = literal` (or IS NOT DISTINCT
688
+ FROM it) and `a IS NULL` from the empty set, and `b = f(x...)` from
689
+ `x...` (Paulley Claim 20) when f is pure and they compare by identity."""
690
+ for conjunct in conjuncts:
691
+ evidence = Result(True, f"{clause} conjunct", (conjunct,))
692
+ match conjunct:
693
+ case ir.Or():
694
+ for column in _predicate_constants((conjunct,)):
695
+ if column in outputs:
696
+ yield (), outputs[column], evidence
697
+ for first, second in _predicate_equalities((conjunct,)):
698
+ if first in outputs and second in outputs and _identity_comparison(second).value:
699
+ yield (outputs[first],), outputs[second], evidence
700
+ # An equality that casts, or compares under a collation, relates
701
+ # values that differ: it gives no dependency.
702
+ # IS NOT DISTINCT FROM equates NULLs too, so NULL agrees with NULL.
703
+ case (
704
+ ir.Equality(left=ir.ColumnRef(column=first) as left, right=ir.ColumnRef(column=second) as right)
705
+ | ir.NullSafeEquality(left=ir.ColumnRef(column=first) as left, right=ir.ColumnRef(column=second) as right)
706
+ ) if first in outputs and second in outputs:
707
+ if _pins(second, left):
708
+ yield (outputs[first],), outputs[second], evidence
709
+ if _pins(first, right):
710
+ yield (outputs[second],), outputs[first], evidence
711
+ case (
712
+ ir.Equality(left=ir.ColumnRef(column=column), right=ir.Constant() as constant)
713
+ | ir.Equality(left=ir.Constant() as constant, right=ir.ColumnRef(column=column))
714
+ | ir.NullSafeEquality(left=ir.ColumnRef(column=column), right=ir.Constant() as constant)
715
+ | ir.NullSafeEquality(left=ir.Constant() as constant, right=ir.ColumnRef(column=column))
716
+ ) if column in outputs:
717
+ if _pins(column, constant):
718
+ yield (), outputs[column], evidence
719
+ case ir.IsNull(operand=ir.ColumnRef(column=column)) if column in outputs:
720
+ yield (), outputs[column], evidence
721
+ case ir.Equality(left=left, right=right):
722
+ for target, value in ((left, right), (right, left)):
723
+ if not (isinstance(target, ir.ColumnRef) and target.column in outputs and _identity_comparison(target.column).value):
724
+ continue
725
+ inputs = _identity_inputs(value, tuple(outputs))
726
+ if inputs is not None:
727
+ yield tuple(outputs[column] for column in inputs), outputs[target.column], evidence
728
+ # One-to-one: `b = a + 1` also gives b -> a, when both are exact.
729
+ source = ir.injective_input(value)
730
+ if source in outputs and exact_numeric(source).value and exact_numeric(target.column).value:
731
+ yield (outputs[target.column],), outputs[source], evidence
732
+ case _:
733
+ pass # Other conjuncts only remove rows.
734
+
735
+
736
+ def _join_dependencies(join: ir.Join):
737
+ from sqlassert.rules.join_cardinality import many_to_one_join
738
+
739
+ outputs = _join_outputs(join)
740
+ if join.kind == "semi":
741
+ # The matched right row satisfies ON; only left columns are output.
742
+ for determinant, dependent, strict_evidence in _equality_dependencies(join.conjuncts, outputs, "ON"):
743
+ yield determinant, dependent, True, strict_evidence
744
+ yield from _matched_dependencies(join, outputs)
745
+ return
746
+ if join.kind == "anti":
747
+ return # No right row satisfies ON.
748
+ left, right = RowIdentity(join.left), RowIdentity(join.right)
749
+ identity = RowIdentity(join)
750
+ yield (left, right), identity, True, Result(True, "A joined row is one row of each input", (join,))
751
+ # For a full join this holds only on rows with a left input row.
752
+ if join.kind in {"inner", "left", "cross", "full"}:
753
+ proof = many_to_one_join(join)
754
+ if proof.value:
755
+ yield (left,), identity, join.kind != "full", proof
756
+ yield (left,), right, join.kind != "full", proof
757
+ if join.scalar_subquery and join.predicate is not None:
758
+ # Which rows a correlated scalar subquery matches depends only on the
759
+ # outer columns its WHERE reads, when that WHERE is a pure function.
760
+ inputs = ir.determinants(join.predicate)
761
+ if inputs is not None:
762
+ outer = tuple(outputs[column] for column in inputs if column in join.left.output_columns)
763
+ yield outer, right, True, Result(True, "A correlated scalar subquery's row depends only on the outer columns its WHERE reads", (join,))
764
+ match join.kind:
765
+ case "inner" | "cross":
766
+ for determinant, dependent, strict_evidence in _equality_dependencies(join.conjuncts, outputs, "ON"):
767
+ yield determinant, dependent, True, strict_evidence
768
+ case "left" | "right":
769
+ yield from _outer_on_dependencies(join, outputs, padded_left=join.kind == "right")
770
+ case "full":
771
+ yield from _full_on_dependencies(join, outputs)
772
+ case "semi" | "anti":
773
+ raise AssertionError("semi and anti joins return above")
774
+ case _:
775
+ assert_never(join.kind)
776
+
777
+
778
+ def _matched_dependencies(join: ir.Join, outputs: dict[ir.OutputColumn, ir.OutputColumn]):
779
+ """A semi join's dependencies through a column of the matched right row:
780
+ every matched row satisfies ON, so where ON pins a right column to a left
781
+ column or a literal, that fixes it, and it fixes each left column ON pins
782
+ to it. `d.deptno = e.mgr AND d.deptno = e.comm` gives mgr -> comm."""
783
+ right = join.right.output_columns
784
+ pairs: list[tuple[ir.OutputColumn, ir.ScalarExpr, ir.ScalarExpr]] = []
785
+ for conjunct in join.conjuncts:
786
+ match conjunct:
787
+ case ir.Equality(left=first, right=second) | ir.NullSafeEquality(left=first, right=second):
788
+ pairs.extend((other.column, value, conjunct) for other, value in ((first, second), (second, first)) if isinstance(other, ir.ColumnRef) and other.column in right)
789
+ case _:
790
+ pass # Other conjuncts pin nothing.
791
+ for column, value, conjunct in pairs:
792
+ # What fixes the right column: a left column or a literal it is pinned to.
793
+ match value:
794
+ case ir.ColumnRef(column=source) if source in outputs and _pins(column, value):
795
+ determinant: tuple[ir.OutputColumn, ...] = (outputs[source],)
796
+ case ir.Constant() if _pins(column, value):
797
+ determinant = ()
798
+ case _:
799
+ continue
800
+ for other, bound, other_conjunct in pairs:
801
+ if other is column and other_conjunct is not conjunct and isinstance(bound, ir.ColumnRef) and bound.column in outputs:
802
+ if _pins(bound.column, ir.ColumnRef(origin=bound.origin, column=column)):
803
+ evidence = Result(True, f"ON conjuncts equal through {quoted(column.name)} of the matched right row", (conjunct, other_conjunct))
804
+ yield determinant, outputs[bound.column], True, evidence
805
+
806
+
807
+ def _outer_on_dependencies(join: ir.Join, outputs: dict[ir.OutputColumn, ir.OutputColumn], padded_left: bool):
808
+ """Paulley Lemma 9: what a left or right join's ON condition still guarantees.
809
+
810
+ The preserved row fixes whether a row matched, and a matched row satisfies
811
+ the condition, so the preserved side's ON columns determine every column
812
+ of the padded side the condition binds to them or to a literal. Equalities
813
+ within the padded side stay strict (padded rows are NULL on both sides);
814
+ a cross-side equality is lax from the padded side. IS NOT DISTINCT FROM
815
+ binds as `=` does: a matched row's sides are equal or both NULL, and a
816
+ padded row's padded side is NULL, whatever the preserved side holds.
817
+ """
818
+ padded = join.left if padded_left else join.right
819
+ status = _match_status(join, padded_left)
820
+ assert status is not None
821
+ for conjunct in join.conjuncts:
822
+ evidence = Result(True, "ON conjunct of an outer join", (conjunct,))
823
+ match conjunct:
824
+ case ir.Equality(left=first, right=second) | ir.NullSafeEquality(left=first, right=second):
825
+ pairs = ((first, second), (second, first))
826
+ case ir.IsNull(operand=ir.ColumnRef(column=column)) if column in padded.output_columns:
827
+ # NULL on matched rows and on padded rows alike.
828
+ yield (), outputs[column], True, evidence
829
+ continue
830
+ case _:
831
+ continue
832
+ for bound, value in pairs:
833
+ if not (isinstance(bound, ir.ColumnRef) and bound.column in padded.output_columns):
834
+ continue
835
+ match value:
836
+ case ir.ColumnRef(column=other) if other in padded.output_columns:
837
+ if _pins(bound.column, value):
838
+ yield (outputs[other],), outputs[bound.column], True, evidence
839
+ case ir.ColumnRef(column=other):
840
+ if _pins(bound.column, value):
841
+ yield status, outputs[bound.column], True, evidence
842
+ if _pins(other, bound):
843
+ yield (outputs[bound.column],), outputs[other], False, evidence
844
+ case ir.Constant() if _pins(bound.column, value):
845
+ yield status, outputs[bound.column], True, evidence
846
+ case _:
847
+ pass # A NULL, an unpinned constant, or an expression binds nothing.
848
+
849
+
850
+ def _full_on_dependencies(join: ir.Join, outputs: dict[ir.OutputColumn, ir.OutputColumn]):
851
+ """Paulley Lemma 10: what a full join's ON condition still guarantees.
852
+
853
+ Both sides pad, so only a cross-side `=` survives, laxly: a non-null
854
+ operand witnesses a real row on its side, and with the other ON columns
855
+ of that side it fixes which rows the row matches, each equal to it. Each
856
+ side's padded rows are unconstrained by ON, so a padded-side equality, a
857
+ literal, or IS NULL gives nothing; IS NOT DISTINCT FROM is not followed.
858
+ """
859
+ for padded_left in (False, True):
860
+ padded = join.left if padded_left else join.right
861
+ status = _match_status(join, padded_left)
862
+ assert status is not None
863
+ for conjunct in join.conjuncts:
864
+ evidence = Result(True, "ON conjunct of a full join", (conjunct,))
865
+ match conjunct:
866
+ case ir.Equality(left=first, right=second):
867
+ for bound, value in ((first, second), (second, first)):
868
+ match bound, value:
869
+ case ir.ColumnRef(column=column), ir.ColumnRef(column=other) if (
870
+ column in padded.output_columns and other not in padded.output_columns and _pins(column, value)
871
+ ):
872
+ yield status | {outputs[other]}, outputs[column], False, evidence
873
+ case _:
874
+ pass # Within one side, or not a column: ON holds on matched rows only.
875
+ case _:
876
+ pass # Other conjuncts hold on matched rows only.
877
+
878
+
879
+ def minimal_keys(relation: ir.RelationExpr, max_size: int = 3) -> list[tuple[ir.OutputColumn, ...]]:
880
+ """The minimal Unique Sets of `relation`, in output order.
881
+
882
+ Every one of up to `max_size` columns, smallest first; when none is that
883
+ small, one minimal set found by shrinking all the columns.
884
+ """
885
+ columns = relation.output_columns
886
+
887
+ def unique(members: tuple[ir.OutputColumn, ...]) -> bool:
888
+ return RowIdentity(relation) in _closure(relation, frozenset(members), frozenset(members)).value.columns
889
+
890
+ if not columns or not unique(columns):
891
+ return []
892
+ keys: list[tuple[ir.OutputColumn, ...]] = []
893
+ for size in range(1, min(max_size, len(columns)) + 1):
894
+ for members in combinations(columns, size):
895
+ if not any(set(key) <= set(members) for key in keys) and unique(members):
896
+ keys.append(members)
897
+ if keys:
898
+ return keys
899
+ members = columns
900
+ for column in columns:
901
+ rest = tuple(other for other in members if other is not column)
902
+ if rest and unique(rest):
903
+ members = rest
904
+ return [members]