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,627 @@
1
+ """Null sources: every reason an output column may be NULL.
2
+
3
+ A column is NULL organically (a nullable source column, an opaque expression,
4
+ a NULL literal) or because an outer join padded its row. Padding is tracked per
5
+ join and side, so a null-rejecting conjunct on one padded column proves that
6
+ side matched and removes its padding from every column it padded; organic
7
+ NULLs are removed one column at a time. A column is non-null when no source
8
+ remains. A padding source means NULL on *every* padded row: an expression that
9
+ may be non-null on some (a CASE arm, a non-strict argument) turns it organic.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from dataclasses import dataclass
15
+ from typing import assert_never
16
+
17
+ from sqlassert.diagnostics import quoted
18
+ from sqlassert import ir
19
+ from sqlassert.properties import NonNullElements
20
+ from sqlassert.python_engine import Result, Stratum, all_of, analysis, any_of, current_arena, unknown
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class Organic:
25
+ """The value itself may be NULL."""
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class Padding:
30
+ """`join` pads the column: it is NULL on every row the join null-extends
31
+ on its `left` (or right) side. A FULL join pads each side on different rows.
32
+
33
+ `aliases` are the Aliases the column was seen through, innermost last, so
34
+ two occurrences of one relation never share a padding.
35
+ """
36
+
37
+ join: ir.Join
38
+ left: bool
39
+ aliases: tuple[ir.Alias, ...] = ()
40
+
41
+
42
+ type NullSource = Organic | Padding
43
+
44
+ ORGANIC = Organic()
45
+
46
+ # A column's null sources, each with the evidence that it is present.
47
+ type _Sources = dict[NullSource, Result[bool]]
48
+
49
+
50
+ @analysis(Stratum.NON_NULL)
51
+ def non_null_columns(columns: frozenset[ir.OutputColumn]) -> Result[bool]:
52
+ relation = current_arena().program.relation_of(columns)
53
+ if relation is None:
54
+ return unknown("Non-null columns must belong to one relation", *columns)
55
+ # Every column is evaluated, so an unknown names each one that failed.
56
+ ordered = [column for column in relation.output_columns if column in columns]
57
+ return all_of(non_null_column(column) for column in ordered)
58
+
59
+
60
+ @analysis(Stratum.NON_NULL)
61
+ def non_null_column(column: ir.OutputColumn) -> Result[bool]:
62
+ sources = _null_sources(column)
63
+ if sources.value:
64
+ return Result(False, f"{quoted(column.name)} may be NULL", (column,), list(sources.members.values()), kind="unknown")
65
+ return Result(True, "No NULL source remains", (column,), [sources])
66
+
67
+
68
+ @analysis(Stratum.NON_NULL)
69
+ def _null_sources(column: ir.OutputColumn) -> Result[frozenset[NullSource]]:
70
+ arena = current_arena()
71
+ accepted = arena.accepted.get(("non_null_column", (("column", column),)), ())
72
+ if accepted:
73
+ return Result(frozenset(), "Known non-null", (column,), [any_of(accepted)])
74
+ relation = column.get_relation(arena.program)
75
+ sources, premises = _output_sources(relation, column)
76
+ return Result(frozenset(sources), "Null sources", (column,), premises, members=sources)
77
+
78
+
79
+ def _output_sources(relation: ir.RelationExpr, column: ir.OutputColumn) -> tuple[_Sources, list[Result]]:
80
+ relation = relation.closed
81
+ match relation:
82
+ case ir.NamedRelation(body=None):
83
+ return {ORGANIC: unknown(f"{quoted(column.name)} is nullable in {relation.name}", relation, column)}, []
84
+ case ir.OpaqueRelation():
85
+ return {ORGANIC: unknown("Nullability of an opaque relation's columns is not known", relation, column)}, []
86
+ case ir.SetOperation():
87
+ return _set_operation_sources(relation, column)
88
+ case ir.Join():
89
+ return _join_sources(relation, column)
90
+ case ir.Filter():
91
+ return _filter_sources(relation, column)
92
+ case ir.Alias():
93
+ sources, premises = _expression_sources(column.scalar_expr)
94
+ return {_seen_through(relation, source): evidence for source, evidence in sources.items()}, premises
95
+ case ir.Aggregate():
96
+ sources, premises = _expression_sources(column.scalar_expr)
97
+ if column in relation.grouping_outputs:
98
+ return sources, premises
99
+ # A group's value comes from one of its rows: padding of that row is
100
+ # no longer tied to the rows of the join that padded it.
101
+ return {(ORGANIC if isinstance(source, Padding) else source): evidence for source, evidence in sources.items()}, premises
102
+ case ir.NamedRelation() | ir.Project() | ir.Limit() | ir.Distinct() | ir.QualifyByPartition():
103
+ return _expression_sources(column.scalar_expr)
104
+ case _:
105
+ assert_never(relation)
106
+
107
+
108
+ def _non_null_expression(expression: ir.ScalarExpr) -> Result[bool]:
109
+ """Whether `expression` is non-null on every row of the relation computing it."""
110
+ sources, premises = _expression_sources(expression)
111
+ if sources:
112
+ return Result(False, "It may be NULL", (expression,), list(sources.values()), kind="unknown")
113
+ return Result(True, "No NULL source remains", (expression,), premises)
114
+
115
+
116
+ def _expression_sources(expression: ir.ScalarExpr) -> tuple[_Sources, list[Result]]:
117
+ expression = expression.closed
118
+ match expression:
119
+ case ir.ColumnRef(column=source):
120
+ sources = _null_sources(source)
121
+ return dict(sources.members), [Result(True, "Column passes through its source", (expression,), [sources])]
122
+ case ir.Constant():
123
+ return {}, [Result(True, "A non-null literal", (expression,))]
124
+ case ir.Count():
125
+ return {}, [Result(True, "count(...) is never NULL", (expression,))]
126
+ case ir.NullLiteral():
127
+ return {ORGANIC: unknown("A NULL literal is null", expression)}, []
128
+ case ir.Coalesce(arguments=arguments) | ir.Call(function=ir.Builtin(skips_null=True), arguments=arguments):
129
+ # Null only when every argument is, so one non-null argument suffices.
130
+ name = expression.function.name if isinstance(expression, ir.Call) else "coalesce"
131
+ arguments_sources = [_expression_sources(argument) for argument in arguments]
132
+ for sources, premises in arguments_sources:
133
+ if not sources:
134
+ return {}, [Result(True, f"{name} is non-null when any argument is", (expression,), premises)]
135
+ # A FULL JOIN pads its two sides on different rows: an argument NULL
136
+ # only on its left padding and one NULL only on its right padding
137
+ # are never NULL together (a FULL JOIN ... USING column).
138
+ # Seen through the same Aliases: one row of that join, not two copies of it.
139
+ sides = [
140
+ source for sources, _ in arguments_sources if len(sources) == 1
141
+ for source in sources if isinstance(source, Padding) and source.join.kind == "full"
142
+ ]
143
+ for first in sides:
144
+ for second in sides:
145
+ if isinstance(first, Padding) and isinstance(second, Padding) and first.join is second.join and (
146
+ first.aliases == second.aliases and first.left != second.left
147
+ ):
148
+ reason = "Coalesce of the two sides a FULL JOIN pads on different rows is never NULL"
149
+ return {}, [Result(True, reason, (expression, first.join))]
150
+ # NULL on a join's padded rows only if every argument is.
151
+ common = set.intersection(*({s for s in sources if isinstance(s, Padding)} for sources, _ in arguments_sources))
152
+ first, _ = arguments_sources[0]
153
+ result: _Sources = {source: first[source] for source in common}
154
+ if any(set(sources) - common for sources, _ in arguments_sources):
155
+ evidence = [evidence for sources, _ in arguments_sources for evidence in sources.values()]
156
+ result[ORGANIC] = Result(False, f"Every {name} argument may be NULL", (expression,), evidence, kind="unknown")
157
+ return result, []
158
+ case ir.AnyAggregate(empty=True) | ir.Accumulation(empty=True):
159
+ return {ORGANIC: unknown("An aggregate grouped by nothing is NULL over no rows", expression)}, []
160
+ case ir.AnyAggregate(input=value) | ir.Accumulation(input=value):
161
+ # Groups are never empty, so the value comes from some input row,
162
+ # NULL only when the rows' values are.
163
+ return _expression_sources(value)
164
+ case ir.Call(total_arguments=tuple() as arguments, description=description):
165
+ # NULL only when an argument it is total in is, so only through
166
+ # theirs; NULL on every padded row only through a strict one.
167
+ strict = {id(argument) for argument in expression.strict_arguments}
168
+ result: _Sources = {}
169
+ premises: list[Result] = []
170
+ for argument in arguments:
171
+ sources, argument_premises = _expression_sources(argument)
172
+ if id(argument) not in strict:
173
+ sources = _may_be_null(sources, f"{expression.function.name} may be non-null where this argument is NULL", argument)
174
+ for source, evidence in sources.items():
175
+ result[source] = result[source] | evidence if source in result else evidence
176
+ premises.extend(argument_premises)
177
+ if result:
178
+ return result, []
179
+ reason = f"{expression.function.name} is non-null when its arguments are" if arguments else f"{expression.function.name} is never NULL"
180
+ return {}, [Result(True, reason, (expression,), premises)]
181
+ case ir.OpaqueExpression(description=description) | ir.OpaquePureFunction(description=description) | ir.Call(description=description):
182
+ return {ORGANIC: unknown(f"Nullability of {description} is not known", expression)}, []
183
+ case ir.Elements(operand=operand):
184
+ elements = _expression_elements(operand)
185
+ if elements.value:
186
+ return {}, [Result(True, "No element is NULL", (expression,), [elements])]
187
+ return {ORGANIC: Result(False, "An element may be NULL", (expression,), [elements], kind="unknown")}, []
188
+ case ir.IsNull() | ir.IsNotNull() | ir.NullSafeEquality():
189
+ return {}, [Result(True, "The IS family is never NULL", (expression,))]
190
+ case ir.Equality(total=True, left=left, right=right):
191
+ # NULL exactly when a side is: strict and total in both.
192
+ result: _Sources = {}
193
+ premises: list[Result] = []
194
+ for side in (left, right):
195
+ sources, side_premises = _expression_sources(side)
196
+ for source, evidence in sources.items():
197
+ result[source] = result[source] | evidence if source in result else evidence
198
+ premises.extend(side_premises)
199
+ if result:
200
+ return result, []
201
+ return {}, [Result(True, "= is non-null when its operands are", (expression,), premises)]
202
+ case ir.Equality() | ir.InList() | ir.And() | ir.Or():
203
+ return {ORGANIC: unknown("Nullability of a comparison is not inferred", expression)}, []
204
+ case ir.SimpleCase():
205
+ return _case_sources(expression)
206
+ case _:
207
+ assert_never(expression)
208
+
209
+
210
+ @analysis(Stratum.NON_NULL)
211
+ def non_null_elements(columns: frozenset[ir.OutputColumn]) -> Result[bool]:
212
+ relation = current_arena().program.relation_of(columns)
213
+ if relation is None:
214
+ return unknown("Columns with non-null elements must belong to one relation", *columns)
215
+ return all_of(_column_elements(column) for column in relation.output_columns if column in columns)
216
+
217
+
218
+ @analysis(Stratum.NON_NULL)
219
+ def _column_elements(column: ir.OutputColumn) -> Result[bool]:
220
+ """Whether no element of `column`'s value is NULL: declared, or so in
221
+ every value it passes on (a set operation's from each input)."""
222
+ arena = current_arena()
223
+ declared = arena.accepted_evidence(NonNullElements(columns=frozenset({column})))
224
+ if declared:
225
+ return Result(True, "Declared non-null elements", (column,), [any_of(declared)])
226
+ relation = column.get_relation(arena.program)
227
+ if isinstance(relation, ir.SetOperation):
228
+ arms = relation.arms(column)
229
+ if arms is None:
230
+ return unknown("The set operation's inputs are not paired by position", relation, column)
231
+ return all_of(_column_elements(arm) for arm in arms if arm is not None)
232
+ if isinstance(column.scalar_expr.closed, ir.OpaqueExpression):
233
+ return unknown(f"{quoted(column.name)} may hold a NULL element (DECLARE NOT NULL ELEMENTS({column.name}) states it does not)", column)
234
+ return _expression_elements(column.scalar_expr)
235
+
236
+
237
+ def _expression_elements(expression: ir.ScalarExpr) -> Result[bool]:
238
+ expression = expression.closed
239
+ match expression:
240
+ case ir.ColumnRef(column=column):
241
+ return _column_elements(column)
242
+ case ir.NullLiteral():
243
+ return Result(True, "NULL has no elements", (expression,))
244
+ case ir.AnyAggregate(input=value):
245
+ return _expression_elements(value)
246
+ case ir.Coalesce(arguments=arguments):
247
+ return all_of(_expression_elements(argument) for argument in arguments)
248
+ case ir.SimpleCase(thens=thens, default=default):
249
+ return all_of(_expression_elements(arm) for arm in (*thens, default))
250
+ case (
251
+ ir.Constant() | ir.Count() | ir.Accumulation() | ir.Call() | ir.OpaqueExpression() | ir.OpaquePureFunction() | ir.Elements()
252
+ | ir.Equality() | ir.NullSafeEquality() | ir.InList() | ir.IsNull() | ir.IsNotNull() | ir.And() | ir.Or()
253
+ ):
254
+ return unknown("Its elements may be NULL", expression)
255
+ case _:
256
+ assert_never(expression)
257
+
258
+
259
+ def _case_sources(case: ir.SimpleCase) -> tuple[_Sources, list[Result]]:
260
+ """A CASE is NULL when the arm it takes is: any THEN, or ELSE (NULL when
261
+ missing) unless no row reaches it, the operand non-null and every value
262
+ of its domain listed by a WHEN (issue 32)."""
263
+ from sqlassert.rules.domain import _else_unreachable # Domains read non-nullness.
264
+
265
+ sources: _Sources = {}
266
+ premises: list[Result] = []
267
+ arm_paddings: list[set[NullSource]] = []
268
+
269
+ def add(reason: str, arm: ir.ScalarExpr, *why: Result) -> None:
270
+ arm_sources, arm_premises = _expression_sources(arm)
271
+ premises.extend(arm_premises)
272
+ arm_paddings.append({source for source in arm_sources if isinstance(source, Padding)})
273
+ for source, evidence in arm_sources.items():
274
+ named = Result(False, reason, (arm,), [evidence, *why], kind="unknown")
275
+ sources[source] = sources[source] | named if source in sources else named
276
+
277
+ for index, then in enumerate(case.thens, 1):
278
+ add(f"THEN arm {index} may be NULL", then)
279
+ unreachable = _else_unreachable(case)
280
+ if unreachable.value:
281
+ premises.append(Result(True, "No row reaches ELSE", (case,), [unreachable]))
282
+ else:
283
+ missing = isinstance(case.default, ir.NullLiteral) and case.default.origin == case.origin
284
+ reason = "With no ELSE, a row no WHEN matches is NULL" if missing else "ELSE may be NULL"
285
+ add(reason, case.default, unreachable)
286
+ # NULL on a join's padded rows only if every arm it may take is.
287
+ common = set.intersection(*arm_paddings) if arm_paddings else set()
288
+ kept = {source: evidence for source, evidence in sources.items() if not isinstance(source, Padding) or source in common}
289
+ others = {source: evidence for source, evidence in sources.items() if source not in kept}
290
+ for source, evidence in _may_be_null(others, "Another arm may be non-null on padded rows", case).items():
291
+ kept[source] = kept[source] | evidence if source in kept else evidence
292
+ return kept, premises
293
+
294
+
295
+ def _may_be_null(sources: _Sources, reason: str, expression: ir.ScalarExpr) -> _Sources:
296
+ """`sources` where a padding only means "may be NULL": organic."""
297
+ result: _Sources = {}
298
+ for source, evidence in sources.items():
299
+ if isinstance(source, Padding):
300
+ evidence = Result(False, reason, (expression,), [evidence], kind="unknown")
301
+ source = ORGANIC
302
+ result[source] = result[source] | evidence if source in result else evidence
303
+ return result
304
+
305
+
306
+ def _join_sources(join: ir.Join, column: ir.OutputColumn) -> tuple[_Sources, list[Result]]:
307
+ sources, premises = _expression_sources(column.scalar_expr)
308
+ match column.scalar_expr:
309
+ case ir.ColumnRef(column=source):
310
+ pass
311
+ case _:
312
+ raise TypeError(f"Join column {column.name} is not a pass-through")
313
+ sources, removal = _rejected(
314
+ _on_rejected(join), _on_rejected_paddings(join), source, sources, "The ON condition rejects NULL on matched rows"
315
+ )
316
+ left = source in join.left.output_columns
317
+ if left in _padded_sides(join):
318
+ sources[Padding(join, left)] = unknown(f"{quoted(column.name)} is padded by the {join.kind.upper()} JOIN", join, column)
319
+ return sources, premises + removal
320
+
321
+
322
+ def _set_operation_sources(relation: ir.SetOperation, column: ir.OutputColumn) -> tuple[_Sources, list[Result]]:
323
+ """Paulley §3.2.5-3.2.6: a UNION row comes from either input, an INTERSECT
324
+ row equals a row of both, an EXCEPT row is a left input row. An input's
325
+ padding is not this relation's, so any remaining source is organic."""
326
+ arms = relation.arms(column)
327
+ if arms is None:
328
+ if relation.operator != "except":
329
+ return {ORGANIC: unknown("The set operation's inputs are not paired by position", relation, column)}, []
330
+ arms = (_left_input(column), None)
331
+ left, right = (_null_sources(arm) if arm is not None else None for arm in arms)
332
+ assert left is not None
333
+ match relation.operator:
334
+ case "union":
335
+ assert right is not None
336
+ if not left.value and not right.value:
337
+ return {}, [Result(True, "Non-null in both inputs of the UNION", (relation, column), [left, right])]
338
+ return {ORGANIC: Result(False, f"{quoted(column.name)} may be NULL in an input of the UNION", (relation, column), [left, right], kind="unknown")}, []
339
+ case "intersect":
340
+ assert right is not None
341
+ for arm in (left, right):
342
+ if not arm.value:
343
+ return {}, [Result(True, "Non-null in one input of the INTERSECT, which every row equals", (relation, column), [arm])]
344
+ return {ORGANIC: Result(False, f"{quoted(column.name)} may be NULL in both inputs of the INTERSECT", (relation, column), [left, right], kind="unknown")}, []
345
+ case "except":
346
+ if not left.value:
347
+ return {}, [Result(True, "Non-null in the left input of the EXCEPT", (relation, column), [left])]
348
+ return {ORGANIC: Result(False, f"{quoted(column.name)} may be NULL in the left input of the EXCEPT", (relation, column), [left], kind="unknown")}, []
349
+ case _:
350
+ assert_never(relation.operator)
351
+
352
+
353
+ def _left_input(column: ir.OutputColumn) -> ir.OutputColumn:
354
+ match column.scalar_expr:
355
+ case ir.ColumnRef(column=source):
356
+ return source
357
+ case _:
358
+ raise TypeError(f"Set operation column {column.name} is not a pass-through")
359
+
360
+
361
+ def _filter_sources(relation: ir.Filter, column: ir.OutputColumn) -> tuple[_Sources, list[Result]]:
362
+ sources, premises = _expression_sources(column.scalar_expr)
363
+ match column.scalar_expr:
364
+ case ir.ColumnRef(column=source):
365
+ pass
366
+ case _:
367
+ raise TypeError(f"Filter column {column.name} is not a pass-through")
368
+ sources, removal = _rejected(
369
+ _null_rejected(relation.conjuncts), _rejected_paddings(relation.conjuncts), source, sources, "The WHERE clause rejects NULL"
370
+ )
371
+ return sources, premises + removal
372
+
373
+
374
+ def _rejected(
375
+ rejected: dict[ir.OutputColumn, ir.ScalarExpr], paddings: dict[Padding, ir.ScalarExpr],
376
+ source: ir.OutputColumn, sources: _Sources, reason: str,
377
+ ) -> tuple[_Sources, list[Result]]:
378
+ """`sources` once the rows a condition rejects are gone.
379
+
380
+ A rejected column loses its organic NULLs, and so does one passing on a
381
+ column whose NULL would make a rejected one NULL on the same row
382
+ (`_row_lineage`): `WHERE q.ms > 0` with `ms = mgr + sal` rejects `q.mgr`.
383
+ Every rejected padding (`_rejected_paddings`) is proved matched, so it
384
+ goes from every column.
385
+ """
386
+ sources = dict(sources)
387
+ removal = []
388
+ if ORGANIC in sources:
389
+ passed = _row_lineage(source, pass_through=True)
390
+ conjunct = next((c for column, c in rejected.items() if passed & _row_lineage(column)), None)
391
+ if conjunct is not None:
392
+ del sources[ORGANIC]
393
+ removal.append(Result(True, reason, (conjunct, source)))
394
+ for padding, conjunct in paddings.items():
395
+ if padding in sources:
396
+ del sources[padding]
397
+ removal.append(Result(True, f"{reason}, so the padding join matched", (conjunct, padding.join)))
398
+ return sources, removal
399
+
400
+
401
+ type _RowColumn = tuple[ir.OutputColumn, tuple[ir.Alias, ...]]
402
+
403
+
404
+ def _row_lineage(column: ir.OutputColumn, *, pass_through: bool = False, aliases: tuple[ir.Alias, ...] = ()) -> frozenset[_RowColumn]:
405
+ """`column` and the columns below it, on the one input row its value is
406
+ computed from, whose NULL makes it NULL (strict inputs), or that it equals
407
+ (`pass_through`); each with the Aliases of Named Relations it was reached
408
+ through, so two occurrences of a view or CTE never share a row.
409
+
410
+ Followed down through the relations that compute a row from one row of
411
+ each input: not through an aggregate (a group's rows), a set operation
412
+ (its columns name its left input's), or an expression reading columns of
413
+ no direct input (a correlated one). Apart from Named Relations, which
414
+ each occurrence enters through its own Alias, the IR is a tree (`Program`
415
+ checks it), so two columns of one relation reaching one column with the
416
+ same Aliases reach it on the same row.
417
+ """
418
+ relation = column.get_relation(current_arena().program).closed
419
+ match relation:
420
+ case ir.Alias(source=ir.NamedRelation()):
421
+ below_aliases = (*aliases, relation)
422
+ case ir.Alias() | ir.NamedRelation() | ir.Project() | ir.Filter() | ir.Limit() | ir.Distinct() | ir.QualifyByPartition() | ir.Join():
423
+ below_aliases = aliases
424
+ case ir.Aggregate() | ir.SetOperation() | ir.OpaqueRelation() | ir.RecursiveRelation():
425
+ return frozenset({(column, aliases)})
426
+ case _:
427
+ assert_never(relation)
428
+ match column.scalar_expr:
429
+ case ir.ColumnRef(column=input_column):
430
+ below: tuple[ir.OutputColumn, ...] = (input_column,)
431
+ case expression if not pass_through:
432
+ below = ir.strict_inputs(expression)
433
+ case _:
434
+ return frozenset({(column, aliases)})
435
+ inputs = {each for child in ir.children(relation) if isinstance(child, ir.RelationExpr) for each in child.output_columns}
436
+ if not all(each in inputs for each in below):
437
+ return frozenset({(column, aliases)})
438
+ return frozenset({(column, aliases)}).union(
439
+ *(_row_lineage(each, pass_through=pass_through, aliases=below_aliases) for each in below)
440
+ )
441
+
442
+
443
+ def _rejected_paddings(conjuncts: tuple[ir.ScalarExpr, ...]) -> dict[Padding, ir.ScalarExpr]:
444
+ """Each padding no row of which a conjunct holds on, with that conjunct.
445
+
446
+ A padded row is NULL in every column its join pads, all at once: a
447
+ conjunct NULL there (`_null_with`) is never TRUE, nor is a Builtin with a
448
+ `rejecting` argument NULL there or `p IS TRUE` where p is never TRUE,
449
+ `IS NOT NULL` of such an expression is
450
+ FALSE, and an OR rejects the paddings every part rejects:
451
+ `e.sal > 0 OR e.comm > 0` and `coalesce(e.sal, e.comm) > 0` reject the
452
+ join that pads both (Calcite's whole-side `Strong`).
453
+ """
454
+ rejected: dict[Padding, ir.ScalarExpr] = {}
455
+ for conjunct in conjuncts:
456
+ for padding in _conjunct_paddings(conjunct):
457
+ rejected.setdefault(padding, conjunct)
458
+ return rejected
459
+
460
+
461
+ def _conjunct_paddings(conjunct: ir.ScalarExpr) -> frozenset[Padding]:
462
+ conjunct = conjunct.closed
463
+ match conjunct:
464
+ case ir.Or(parts=parts):
465
+ first, *others = (frozenset(_rejected_paddings(ir.conjuncts(part))) for part in parts)
466
+ return first.intersection(*others)
467
+ case ir.And(parts=parts):
468
+ return frozenset(_rejected_paddings(parts))
469
+ case ir.IsNotNull(operand=operand):
470
+ return _null_with(operand)
471
+ case ir.NullSafeEquality(left=left, right=right, rejects=True):
472
+ # Equal to a non-null side, the other is non-null too.
473
+ return frozenset(
474
+ padding for side, other in ((left, right), (right, left)) if not _expression_sources(other)[0]
475
+ for padding in _null_with(side)
476
+ )
477
+ case ir.Call(function=ir.Builtin(true_only_if_argument=True), arguments=(argument,)):
478
+ # TRUE only where its argument is: `p IS TRUE` rejects what p does.
479
+ return _conjunct_paddings(argument)
480
+ case ir.Call(rejecting_arguments=arguments):
481
+ # Never TRUE where a rejecting argument is NULL, though perhaps not NULL.
482
+ return frozenset(padding for argument in arguments for padding in _null_with(argument))
483
+ case _:
484
+ return _null_with(conjunct)
485
+
486
+
487
+ def _null_with(expression: ir.ScalarExpr) -> frozenset[Padding]:
488
+ """The paddings on every row of which `expression` is NULL: a column's,
489
+ those of an argument it is strict in, or, for AND and OR, those every part
490
+ is NULL on (`NULL OR TRUE` is TRUE). Any other expression is NULL on a
491
+ padding's rows when its Null Sources keep that padding (coalesce: when
492
+ every argument is NULL there)."""
493
+ expression = expression.closed
494
+ match expression:
495
+ case ir.ColumnRef(column=column):
496
+ return frozenset(source for source in _null_sources(column).value if isinstance(source, Padding))
497
+ case ir.Coalesce(arguments=(first, *others)) | ir.Call(function=ir.Builtin(skips_null=True), arguments=(first, *others)):
498
+ return _null_with(first).intersection(*(_null_with(other) for other in others))
499
+ case ir.Call(strict_arguments=arguments):
500
+ return frozenset(padding for argument in arguments for padding in _null_with(argument))
501
+ case ir.Equality(left=left, right=right):
502
+ return _null_with(left) | _null_with(right)
503
+ case ir.InList(operand=operand):
504
+ return _null_with(operand)
505
+ case ir.And(parts=(first, *others)) | ir.Or(parts=(first, *others)):
506
+ return _null_with(first).intersection(*(_null_with(other) for other in others))
507
+ case (
508
+ ir.And() | ir.Or() | ir.Coalesce() | ir.Constant() | ir.NullLiteral() | ir.SimpleCase() | ir.OpaquePureFunction()
509
+ | ir.OpaqueExpression() | ir.Count() | ir.AnyAggregate() | ir.Accumulation() | ir.Elements() | ir.IsNull()
510
+ | ir.IsNotNull() | ir.NullSafeEquality()
511
+ ):
512
+ sources, _ = _expression_sources(expression)
513
+ return frozenset(source for source in sources if isinstance(source, Padding))
514
+ case _:
515
+ assert_never(expression)
516
+
517
+
518
+ def _null_rejected(conjuncts: tuple[ir.ScalarExpr, ...]) -> dict[ir.OutputColumn, ir.ScalarExpr]:
519
+ """Each column a conjunct requires to be non-null, with that conjunct.
520
+
521
+ A conjunct cannot be TRUE while it is NULL, so it rejects every column it
522
+ is strict in; `IS NOT NULL` rejects those of its operand (Paulley §3.2.4,
523
+ footnote 9), and `IS NOT DISTINCT FROM` a non-null value those of its
524
+ other side. A Builtin never TRUE on a NULL argument rejects that
525
+ argument's, though it may not be NULL there (Calcite's `Strong.isNotTrue`):
526
+ `x > ANY (...)` rejects x. `p IS TRUE` rejects whatever p does. An OR
527
+ rejects the columns each of its parts rejects.
528
+ """
529
+ rejected: dict[ir.OutputColumn, ir.ScalarExpr] = {}
530
+ for conjunct in conjuncts:
531
+ match conjunct:
532
+ case ir.Or(parts=parts):
533
+ first, *others = (_null_rejected(ir.conjuncts(part)) for part in parts)
534
+ columns = tuple(column for column in first if all(column in other for other in others))
535
+ case ir.IsNotNull(operand=operand):
536
+ columns = ir.strict_inputs(operand)
537
+ case ir.NullSafeEquality(left=left, right=right, rejects=True):
538
+ # Equal to a non-null side, the other is non-null too.
539
+ columns = tuple(dict.fromkeys(
540
+ column for side, other in ((left, right), (right, left)) if not _expression_sources(other)[0]
541
+ for column in ir.strict_inputs(side)
542
+ ))
543
+ case ir.Call(function=ir.Builtin(true_only_if_argument=True), arguments=(argument,)):
544
+ # TRUE only where its argument is: `p IS TRUE` rejects what p does.
545
+ columns = tuple(_null_rejected((argument,)))
546
+ case ir.Call(rejecting_arguments=arguments):
547
+ # Never TRUE where a rejecting argument is NULL: `x > ANY (...)`.
548
+ columns = tuple(dict.fromkeys(column for argument in arguments for column in ir.strict_inputs(argument)))
549
+ case _:
550
+ columns = ir.strict_inputs(conjunct)
551
+ for column in columns:
552
+ rejected.setdefault(column, conjunct)
553
+ return rejected
554
+
555
+
556
+ def _on_rejected(join: ir.Join) -> dict[ir.OutputColumn, ir.ScalarExpr]:
557
+ """Input columns non-null on every matched row of `join`, on its padded side.
558
+
559
+ An inner join drops rows failing ON on both sides; an outer join keeps them
560
+ padded, so ON only constrains the side it pads. A semi join keeps the left
561
+ rows some right row matches, an anti join those none does: ON constrains
562
+ only the semi join's.
563
+ """
564
+ rejected = _null_rejected(join.conjuncts)
565
+ match join.kind:
566
+ case "inner" | "semi":
567
+ return rejected
568
+ case "left":
569
+ return {column: c for column, c in rejected.items() if column in join.right.output_columns}
570
+ case "right":
571
+ return {column: c for column, c in rejected.items() if column in join.left.output_columns}
572
+ case "cross" | "full" | "anti":
573
+ return {}
574
+ case _:
575
+ assert_never(join.kind)
576
+
577
+
578
+ def _on_rejected_paddings(join: ir.Join) -> dict[Padding, ir.ScalarExpr]:
579
+ """The paddings of `join`'s inputs its ON rejects, on the side whose
580
+ unmatched rows it drops (see `_on_rejected`)."""
581
+ match join.kind:
582
+ case "inner" | "semi":
583
+ sides: tuple[ir.RelationExpr, ...] = (join.left, join.right)
584
+ case "left":
585
+ sides = (join.right,)
586
+ case "right":
587
+ sides = (join.left,)
588
+ case "cross" | "full" | "anti":
589
+ return {}
590
+ case _:
591
+ assert_never(join.kind)
592
+ rejected = _rejected_paddings(join.conjuncts)
593
+ if not rejected:
594
+ return {}
595
+ own = {
596
+ source for side in sides for column in side.output_columns
597
+ for source in _null_sources(column).value if isinstance(source, Padding)
598
+ }
599
+ return {padding: conjunct for padding, conjunct in rejected.items() if padding in own}
600
+
601
+
602
+ def _padded_sides(join: ir.Join) -> frozenset[bool]:
603
+ """The sides `join` null-extends: True for the left input, False for the right.
604
+
605
+ A proved Exactly One LEFT join matches every left row, so it pads nothing.
606
+ """
607
+ from sqlassert.rules.exactly_one import exactly_one_join
608
+
609
+ match join.kind:
610
+ case "left":
611
+ return frozenset() if exactly_one_join(join).value else frozenset({False})
612
+ case "right":
613
+ return frozenset({True})
614
+ case "full":
615
+ return frozenset({True, False})
616
+ case "inner" | "cross" | "semi" | "anti":
617
+ return frozenset()
618
+ case _:
619
+ assert_never(join.kind)
620
+
621
+
622
+ def _seen_through(alias: ir.Alias, source: NullSource) -> NullSource:
623
+ match source:
624
+ case Padding(join=join, left=left, aliases=aliases):
625
+ return Padding(join, left, (*aliases, alias))
626
+ case Organic():
627
+ return source