sqlassert 0.3.1__py3-none-any.whl → 0.3.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -21,15 +21,16 @@ non-null by the caller, or proved non-null.
21
21
 
22
22
  from __future__ import annotations
23
23
 
24
- from collections.abc import Callable
24
+ from collections.abc import Callable, Iterator
25
25
  from dataclasses import dataclass, field
26
26
  from itertools import combinations
27
27
  from typing import assert_never
28
28
 
29
+ from sqlassert.diagnostics import quoted
29
30
  from sqlassert import ir
30
31
  from sqlassert.python_engine import Result, Stratum, all_of, analysis, any_of, current_arena, unknown
31
32
  from sqlassert.rules.column_set import Attribute, Closure, RowIdentity
32
- from sqlassert.rules.equality import _identity_comparison, _pins, exact_numeric
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
33
34
  from sqlassert.rules.nullability import Padding, _null_sources, _padded_sides, non_null_column, non_null_columns
34
35
 
35
36
 
@@ -70,7 +71,7 @@ def functional_dependency(determinant: frozenset[ir.OutputColumn], dependent: fr
70
71
  ordered = [column for column in relation.output_columns if column in dependent]
71
72
  return all_of(
72
73
  closure.members[column] if column in closure.value.columns
73
- else unknown(f"{column.name} is not determined", column)
74
+ else unknown(f"{quoted(column.name)} is not determined", column)
74
75
  for column in ordered
75
76
  )
76
77
 
@@ -125,7 +126,7 @@ def _closure(relation: ir.RelationExpr, columns: frozenset[Attribute], definite:
125
126
  queue.append(attribute)
126
127
 
127
128
  def is_definite(attribute: Attribute) -> bool:
128
- return attribute in definite or _definite(relation, attribute)
129
+ return attribute in definite or _definite(relation, attribute) or _padded_with(relation, attribute, definite)
129
130
 
130
131
  dependencies = _functional_dependencies(relation)
131
132
  waiting: dict[Dependency, int] = {}
@@ -146,7 +147,7 @@ def _closure(relation: ir.RelationExpr, columns: frozenset[Attribute], definite:
146
147
  for dependency, count in waiting.items():
147
148
  if count == 0:
148
149
  fire(dependency)
149
- inputs: dict[ir.RelationExpr, Result[Closure]] = {}
150
+ inputs: dict[int, Result[Closure]] = {}
150
151
  while True:
151
152
  while queue:
152
153
  attribute = queue.pop()
@@ -157,24 +158,152 @@ def _closure(relation: ir.RelationExpr, columns: frozenset[Attribute], definite:
157
158
  waiting[dependency] -= 1
158
159
  if waiting[dependency] == 0:
159
160
  fire(dependency)
160
- for delegation in _delegations(relation):
161
+ for index, delegation in enumerate(_delegations(relation)):
161
162
  closure = delegation.run(reached, is_definite)
162
163
  if closure is None:
163
164
  continue
164
- inputs[delegation.input] = closure
165
- for source, attribute in delegation.back.items():
166
- if source in closure.value.columns and attribute not in reached:
167
- reach(attribute, Result(True, delegation.reason, (relation, attribute), [closure.members[source]]))
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]]))
168
170
  for attribute, sources in delegation.computed.items():
169
171
  if sources <= closure.value.columns and attribute not in reached:
170
172
  reason = "A deterministic function of determined input columns"
171
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)
172
178
  if not queue:
173
179
  break
174
180
  value = Closure(relation, set(reached), tuple(inputs.values()))
175
181
  return Result(value, "Closure", (relation,), list(inputs.values()), members=reached)
176
182
 
177
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
+
178
307
  def _row_attributes(relation: ir.RelationExpr) -> tuple[Attribute, ...]:
179
308
  match relation:
180
309
  case ir.Join(kind="semi" | "anti", left=left):
@@ -197,20 +326,39 @@ def _definite(relation: ir.RelationExpr, attribute: Attribute) -> bool:
197
326
  return non_null_column(attribute).value
198
327
 
199
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
+
200
347
  @dataclass(frozen=True)
201
348
  class _Delegation:
202
349
  """How rows of a relation map onto rows of one input, for taking closure there.
203
350
 
204
351
  `down` maps the relation's attributes to the input's; `back` maps input
205
- attributes reached there back up, and `computed` maps each of the
206
- relation's columns computed from input attributes to them: reaching all of
207
- them reaches it. `valid` says whether two rows agreeing on the reached
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
208
356
  attributes may be compared as input rows at all.
209
357
  """
210
358
 
211
359
  input: ir.RelationExpr
212
360
  down: dict[Attribute, Attribute]
213
- back: dict[Attribute, Attribute]
361
+ back: dict[Attribute, tuple[Attribute, ...]]
214
362
  reason: str
215
363
  valid: Callable[[dict[Attribute, Result[bool]], Callable[[Attribute], bool]], bool] | None = None
216
364
  computed: dict[Attribute, frozenset[Attribute]] = field(default_factory=dict)
@@ -234,12 +382,23 @@ def _delegations(relation: ir.RelationExpr) -> list[_Delegation]:
234
382
  # Each output row is one left row.
235
383
  return [_row_preserving(relation, source)]
236
384
  case ir.Aggregate(input=source):
237
- return [_grouped(relation, source)]
385
+ grouped = _grouped(relation, source)
386
+ return [grouped, *_picked(relation, grouped)]
238
387
  case ir.Distinct(input=source):
239
388
  return [_grouped(relation, source)]
240
389
  case ir.SetOperation(operator="intersect" | "except", left=source):
241
- # Every output row equals some row of the left input.
242
- return [_grouped(relation, 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
243
402
  case ir.Join() | ir.SetOperation() | ir.NamedRelation() | ir.OpaqueRelation():
244
403
  return []
245
404
  case _:
@@ -268,7 +427,15 @@ def _one_to_one(relation: ir.RelationExpr, source: ir.RelationExpr) -> dict[ir.O
268
427
  upstream = ir.injective_input(column.scalar_expr)
269
428
  if column not in passed and upstream in source.output_columns and exact_numeric(upstream).value:
270
429
  mapping[column] = upstream
271
- return mapping | passed # Last, so mapping back prefers a pass-through.
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
272
439
 
273
440
 
274
441
  def _row_preserving(relation: ir.RelationExpr, source: ir.RelationExpr) -> _Delegation:
@@ -276,7 +443,7 @@ def _row_preserving(relation: ir.RelationExpr, source: ir.RelationExpr) -> _Dele
276
443
  down: dict[Attribute, Attribute] = {own: upstream for own, upstream in _one_to_one(relation, source).items()}
277
444
  down[RowIdentity(relation)] = RowIdentity(source)
278
445
  return _Delegation(
279
- source, down, {upstream: own for own, upstream in down.items()}, "Determined in the input",
446
+ source, down, _inverse(down), "Determined in the input",
280
447
  computed=_computed(relation, source),
281
448
  )
282
449
 
@@ -292,23 +459,63 @@ def _grouped(relation: ir.RelationExpr, source: ir.RelationExpr) -> _Delegation:
292
459
  input row belongs to one output row.
293
460
  """
294
461
  down: dict[Attribute, Attribute] = {own: upstream for own, upstream in _one_to_one(relation, source).items()}
295
- back: dict[Attribute, Attribute] = {upstream: own for own, upstream in down.items()}
296
- back[RowIdentity(source)] = RowIdentity(relation)
462
+ back = _inverse(down)
463
+ back[RowIdentity(source)] = (RowIdentity(relation),)
297
464
  if isinstance(relation, ir.Aggregate):
298
465
  grouping = frozenset(down[column] for column in relation.grouping_outputs if column in down)
299
466
  constant = _closure(source, grouping, frozenset()).value.columns
300
467
  down = {column: upstream for column, upstream in down.items() if column in relation.grouping_outputs}
301
468
  for column in relation.output_columns:
302
- match column.scalar_expr:
303
- case ir.AnyAggregate(input=ir.ColumnRef(column=upstream)) if upstream in constant:
304
- back[upstream] = column
305
- case _:
306
- pass # Count-sensitive and opaque aggregates are new values.
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)
307
473
  # A computed column of an Aggregate that is not a grouping item wraps its
308
474
  # value in AnyAggregate, so only grouping items and DISTINCT values remain.
309
475
  return _Delegation(source, down, back, "Determined in the input rows", computed=_computed(relation, source))
310
476
 
311
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
+
312
519
  def _computed(relation: ir.RelationExpr, source: ir.RelationExpr) -> dict[Attribute, frozenset[Attribute]]:
313
520
  """Paulley §3.1.4: each column computed from columns of `source` by a pure
314
521
  function, with those columns. Only columns compared by identity qualify:
@@ -340,7 +547,7 @@ def _join_side(join: ir.Join, left: bool) -> _Delegation:
340
547
  own: upstream for own, upstream in zip(join.output_columns[offset:offset + len(side.output_columns)], side.output_columns)
341
548
  }
342
549
  down[RowIdentity(side)] = RowIdentity(side)
343
- back = {upstream: own for own, upstream in down.items()}
550
+ back = _inverse(down)
344
551
  if left not in _padded_sides(join):
345
552
  return _Delegation(side, down, back, "Determined in the joined input")
346
553
 
@@ -355,6 +562,8 @@ def _join_side(join: ir.Join, left: bool) -> _Delegation:
355
562
  if attribute in down and isinstance(attribute, ir.OutputColumn):
356
563
  if _null_sources(attribute).value <= {Padding(join, left)}:
357
564
  return True
565
+ if join.kind == "full":
566
+ return False # The other side pads too: its columns may be NULL.
358
567
  status = _match_status(join, left)
359
568
  return status is not None and status <= set(reached)
360
569
 
@@ -362,28 +571,33 @@ def _join_side(join: ir.Join, left: bool) -> _Delegation:
362
571
 
363
572
 
364
573
  def _match_status(join: ir.Join, padded_left: bool) -> frozenset[Attribute] | None:
365
- """Attributes of the preserved side that fix whether a row matched, for a
366
- left or right join; None for a full join, whose sides both pad."""
367
- if join.kind not in {"left", "right"}:
574
+ """Attributes of the side opposite the padding that fix which rows match."""
575
+ if join.kind not in {"left", "right", "full"}:
368
576
  return None
369
577
  preserved = join.right if padded_left else join.left
370
578
  outputs = _join_outputs(join)
371
579
  referenced = set()
372
580
  for conjunct in join.conjuncts:
373
581
  operands = _recognized_operands(conjunct)
374
- if operands is None:
375
- # An unrecognized conjunct: only the preserved row itself fixes it.
376
- return frozenset({RowIdentity(preserved)})
377
- for operand in operands:
378
- if isinstance(operand, ir.ColumnRef) and operand.column in preserved.output_columns:
379
- referenced.add(outputs[operand.column])
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)
380
594
  return frozenset(referenced)
381
595
 
382
596
 
383
597
  def _recognized_operands(conjunct: ir.ScalarExpr) -> tuple[ir.ScalarExpr, ...] | None:
384
598
  """A recognized conjunct's operands, when each is a column or a literal."""
385
599
  match conjunct:
386
- case ir.Equality(left=left, right=right):
600
+ case ir.Equality(left=left, right=right) | ir.NullSafeEquality(left=left, right=right):
387
601
  operands: tuple[ir.ScalarExpr, ...] = (left, right)
388
602
  case ir.IsNull(operand=operand) | ir.IsNotNull(operand=operand):
389
603
  operands = (operand,)
@@ -433,6 +647,16 @@ def _functional_dependencies(relation: ir.RelationExpr) -> Result[Dependencies]:
433
647
 
434
648
  relation = relation.closed
435
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
+
436
660
  match relation:
437
661
  case ir.Filter(input=source, conjuncts=conjuncts):
438
662
  outputs = {upstream: own for own, upstream in _pass_through(relation, source).items()}
@@ -459,20 +683,37 @@ def _functional_dependencies(relation: ir.RelationExpr) -> Result[Dependencies]:
459
683
 
460
684
 
461
685
  def _equality_dependencies(conjuncts: tuple[ir.ScalarExpr, ...], outputs: dict[ir.OutputColumn, ir.OutputColumn], clause: str):
462
- """Dependencies of conjuncts that hold on every row: `a = b` both ways,
463
- `a = literal` and `a IS NULL` from the empty set, and `b = f(x...)` from
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
464
689
  `x...` (Paulley Claim 20) when f is pure and they compare by identity."""
465
690
  for conjunct in conjuncts:
466
691
  evidence = Result(True, f"{clause} conjunct", (conjunct,))
467
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
468
700
  # An equality that casts, or compares under a collation, relates
469
701
  # values that differ: it gives no dependency.
470
- case ir.Equality(left=ir.ColumnRef(column=first) as left, right=ir.ColumnRef(column=second) as right) if first in outputs and second in outputs:
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:
471
707
  if _pins(second, left):
472
708
  yield (outputs[first],), outputs[second], evidence
473
709
  if _pins(first, right):
474
710
  yield (outputs[second],), outputs[first], evidence
475
- case ir.Equality(left=ir.ColumnRef(column=column), right=ir.Constant() as constant) | ir.Equality(left=ir.Constant() as constant, right=ir.ColumnRef(column=column)) if column in outputs:
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:
476
717
  if _pins(column, constant):
477
718
  yield (), outputs[column], evidence
478
719
  case ir.IsNull(operand=ir.ColumnRef(column=column)) if column in outputs:
@@ -500,18 +741,19 @@ def _join_dependencies(join: ir.Join):
500
741
  # The matched right row satisfies ON; only left columns are output.
501
742
  for determinant, dependent, strict_evidence in _equality_dependencies(join.conjuncts, outputs, "ON"):
502
743
  yield determinant, dependent, True, strict_evidence
744
+ yield from _matched_dependencies(join, outputs)
503
745
  return
504
746
  if join.kind == "anti":
505
747
  return # No right row satisfies ON.
506
748
  left, right = RowIdentity(join.left), RowIdentity(join.right)
507
749
  identity = RowIdentity(join)
508
750
  yield (left, right), identity, True, Result(True, "A joined row is one row of each input", (join,))
509
- # Not for a right or full join: its padded rows share one null left row.
510
- if join.kind in {"inner", "left", "cross"}:
751
+ # For a full join this holds only on rows with a left input row.
752
+ if join.kind in {"inner", "left", "cross", "full"}:
511
753
  proof = many_to_one_join(join)
512
754
  if proof.value:
513
- yield (left,), identity, True, proof
514
- yield (left,), right, True, proof
755
+ yield (left,), identity, join.kind != "full", proof
756
+ yield (left,), right, join.kind != "full", proof
515
757
  if join.scalar_subquery and join.predicate is not None:
516
758
  # Which rows a correlated scalar subquery matches depends only on the
517
759
  # outer columns its WHERE reads, when that WHERE is a pure function.
@@ -525,18 +767,53 @@ def _join_dependencies(join: ir.Join):
525
767
  yield determinant, dependent, True, strict_evidence
526
768
  case "left" | "right":
527
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")
528
774
  case _:
529
- pass # A full join pads both sides: its ON condition holds on neither.
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
530
805
 
531
806
 
532
807
  def _outer_on_dependencies(join: ir.Join, outputs: dict[ir.OutputColumn, ir.OutputColumn], padded_left: bool):
533
- """Paulley Lemma 9: what an outer join's ON condition still guarantees.
808
+ """Paulley Lemma 9: what a left or right join's ON condition still guarantees.
534
809
 
535
810
  The preserved row fixes whether a row matched, and a matched row satisfies
536
811
  the condition, so the preserved side's ON columns determine every column
537
812
  of the padded side the condition binds to them or to a literal. Equalities
538
813
  within the padded side stay strict (padded rows are NULL on both sides);
539
- a cross-side equality is lax from the padded side.
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.
540
817
  """
541
818
  padded = join.left if padded_left else join.right
542
819
  status = _match_status(join, padded_left)
@@ -544,7 +821,7 @@ def _outer_on_dependencies(join: ir.Join, outputs: dict[ir.OutputColumn, ir.Outp
544
821
  for conjunct in join.conjuncts:
545
822
  evidence = Result(True, "ON conjunct of an outer join", (conjunct,))
546
823
  match conjunct:
547
- case ir.Equality(left=first, right=second):
824
+ case ir.Equality(left=first, right=second) | ir.NullSafeEquality(left=first, right=second):
548
825
  pairs = ((first, second), (second, first))
549
826
  case ir.IsNull(operand=ir.ColumnRef(column=column)) if column in padded.output_columns:
550
827
  # NULL on matched rows and on padded rows alike.
@@ -566,11 +843,37 @@ def _outer_on_dependencies(join: ir.Join, outputs: dict[ir.OutputColumn, ir.Outp
566
843
  yield (outputs[bound.column],), outputs[other], False, evidence
567
844
  case ir.Constant() if _pins(bound.column, value):
568
845
  yield status, outputs[bound.column], True, evidence
569
- case ir.Constant():
570
- pass
571
846
  case _:
572
- pass # An expression or NULL binds nothing.
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.
573
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.
574
877
 
575
878
 
576
879
  def minimal_keys(relation: ir.RelationExpr, max_size: int = 3) -> list[tuple[ir.OutputColumn, ...]]: