sqlassert 0.4.1__py3-none-any.whl → 0.4.2__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 (42) hide show
  1. sqlassert/declared_types.py +158 -0
  2. sqlassert/diagnostics.py +1 -4
  3. sqlassert/dialects.py +118 -396
  4. sqlassert/discovery/bigquery.py +2 -2
  5. sqlassert/discovery/databricks.py +4 -6
  6. sqlassert/discovery/fetcher.py +22 -52
  7. sqlassert/discovery/information_schema.py +7 -10
  8. sqlassert/discovery/mysql.py +4 -8
  9. sqlassert/discovery/postgres.py +17 -26
  10. sqlassert/discovery/redshift.py +2 -2
  11. sqlassert/discovery/snowflake.py +2 -2
  12. sqlassert/functions/__init__.py +10 -0
  13. sqlassert/functions/load.py +375 -0
  14. sqlassert/functions/table.py +2721 -0
  15. sqlassert/hazards.py +1 -1
  16. sqlassert/ir/__init__.py +13 -5
  17. sqlassert/ir/convert/aggregation.py +2 -3
  18. sqlassert/ir/convert/expressions.py +76 -67
  19. sqlassert/ir/convert/parser.py +0 -4
  20. sqlassert/ir/convert/schema.py +11 -80
  21. sqlassert/ir/convert/selects.py +30 -15
  22. sqlassert/ir/convert/shared.py +2 -3
  23. sqlassert/ir/convert/sources.py +2 -1
  24. sqlassert/ir/convert/value_types.py +12 -157
  25. sqlassert/ir/model.py +331 -138
  26. sqlassert/main.py +7 -10
  27. sqlassert/rules/causes/domain.py +1 -1
  28. sqlassert/rules/causes/unique.py +46 -5
  29. sqlassert/rules/domain.py +1 -1
  30. sqlassert/rules/join_cardinality.py +14 -21
  31. sqlassert/rules/nullability.py +3 -3
  32. sqlassert/rules/uniqueness.py +42 -41
  33. sqlassert/rules/value_typing.py +266 -133
  34. sqlassert/suggest.py +2 -2
  35. {sqlassert-0.4.1.dist-info → sqlassert-0.4.2.dist-info}/METADATA +18 -14
  36. sqlassert-0.4.2.dist-info/RECORD +72 -0
  37. sqlassert/ir/convert/builtins.py +0 -140
  38. sqlassert-0.4.1.dist-info/RECORD +0 -69
  39. {sqlassert-0.4.1.dist-info → sqlassert-0.4.2.dist-info}/WHEEL +0 -0
  40. {sqlassert-0.4.1.dist-info → sqlassert-0.4.2.dist-info}/entry_points.txt +0 -0
  41. {sqlassert-0.4.1.dist-info → sqlassert-0.4.2.dist-info}/licenses/LICENSE +0 -0
  42. {sqlassert-0.4.1.dist-info → sqlassert-0.4.2.dist-info}/top_level.txt +0 -0
@@ -37,7 +37,7 @@ from sqlassert.reporting import CauseTag, Step
37
37
  from sqlassert.rules.column_set import Attribute, Closure, RowIdentity
38
38
  from sqlassert.rules.equality import _constant_value, _typed_arms
39
39
  from sqlassert.rules.join_cardinality import Side, _unsupported_under, many_to_one_join, one_to_many_join, unproved_join
40
- from sqlassert.rules.value_typing import untyped_source
40
+ from sqlassert.rules.value_typing import respected_inputs, stopping_call, untyped_source
41
41
  from sqlassert.rules.uniqueness import _closure, _definite, _distinct_tags, _functional_dependencies, _one_to_one, _padded_with
42
42
 
43
43
  # Who can act on each Unproved Join Reason. A cascade is no Cause of its own:
@@ -131,8 +131,9 @@ def walk_dependent(closure: Result[Closure], target: ir.OutputColumn, place: _Pl
131
131
  if inner is not None and all(column in inner.value.columns for column in read):
132
132
  # Its inputs are fixed, yet two equal inputs may give it different values.
133
133
  written = brief(target.origin.detail.rsplit(" AS ", 1)[0])
134
+ details = (respected_inputs(target.scalar_expr).reason, _RESPECTS_HINT)
134
135
  return (Step(f"{quoted(target.name)} = {written}: inputs that compare equal may give it different values", False, at.origin,
135
- "sqlassert", "not-identity", ("only inputs compared by identity fix a computed value: -0.0 = 0.0 as a DOUBLE, but not as text",)),)
136
+ "sqlassert", "not-identity", details),)
136
137
  return _follow_value(closure, target, source, place)
137
138
  case ir.Join():
138
139
  side = join_side(relation, target)
@@ -292,13 +293,34 @@ def _project(closure: Result[Closure], project: ir.Project, source: ir.RelationE
292
293
  return (*(_follow(closure, source, place) if passed or not causes else ()), *causes)
293
294
 
294
295
 
296
+ # What fixes a computed value, for a Cause where a function does not.
297
+ _RESPECTS_HINT = "a function fixes its value only where inputs that compare equal give equal values: -0.0 = 0.0 as a DOUBLE, but not as text"
298
+
299
+ # What keeps rows apart, for a Cause where a computed key does not.
300
+ _KEEPS_HINT = "only a column, or a function that keeps different values different (x + 1 over integers, a CAST that widens), keeps rows apart"
301
+
302
+
295
303
  def computed_column(column: ir.OutputColumn, place: _Place) -> Step:
296
- """A column whose expression may give rows that differ one value."""
304
+ """A column whose expression may give rows that differ one value, with
305
+ the call that may (`merging_call`)."""
297
306
  written = brief(column.origin.detail.rsplit(" AS ", 1)[0])
298
307
  if isinstance(column.scalar_expr, ir.OpaqueExpression):
299
308
  return Step(f"{quoted(column.name)} = {written}: sqlassert does not model its values", False, place.origin, "sqlassert", "opaque-column")
309
+ merging = merging_call(column.scalar_expr)
300
310
  return Step(f"{quoted(column.name)} = {written} may give two rows one value", False, place.origin, "sql", "computed-column",
301
- ("only a column itself, or an exact one-to-one function of one (x + 1), keeps rows apart",))
311
+ (*((merging,) if merging else ()), _KEEPS_HINT))
312
+
313
+
314
+ def merging_call(expression: ir.ScalarExpr) -> str | None:
315
+ """The call in `expression` that may give two values one result, and its
316
+ property function's reason (`stopping_call`), `CAST(s AS INT): a cast
317
+ from VARCHAR to INT may make two values one (...)`; None when no one call
318
+ is to blame."""
319
+ stop = stopping_call(expression)
320
+ if stop is None:
321
+ return None
322
+ call, reason = stop
323
+ return f"{brief(call.description)}: {reason}"
302
324
 
303
325
 
304
326
  def _opaque(relation: ir.RelationExpr, place: _Place) -> Step:
@@ -358,14 +380,33 @@ def join_cause(join: ir.Join, matched: Side, side: tuple[Step, ...]) -> Step:
358
380
  details.append(f"{reason.construct} is not supported by sqlassert yet")
359
381
  if reason.untyped is not None:
360
382
  details.append(_type_lost(reason.untyped, reason.detail))
383
+ merging = _merging_keys(join, matched) if reason.reason == "expression-key" else []
384
+ details.extend(merging)
361
385
  code = reason.reason if reason.detail is None else f"{reason.reason} ({reason.detail})"
362
386
  # A key the matched input lacks because of something below it: that is the Cause.
363
387
  deferred = reason.reason == "no-unique-set" and any(step.causes() for step in nested)
364
388
  tag = None if deferred else _JOIN_TAGS.get(reason.detail or "", _JOIN_TAGS.get(reason.reason, "sql"))
389
+ if merging:
390
+ tag = "sql" # A call that may merge values: the SQL, not sqlassert, matches several rows.
365
391
  verb = "is not many-to-one" if matched == "right" else "is not one-to-many"
366
392
  return Step(f"{subject} {verb}", False, join.origin, tag, code if tag is not None else None, tuple(details), tuple(nested))
367
393
 
368
394
 
395
+ def _merging_keys(join: ir.Join, matched: Side) -> list[str]:
396
+ """For each ON equality, the call in its operand over `matched` that may
397
+ give two of its rows one value (`merging_call`)."""
398
+ side = join.right if matched == "right" else join.left
399
+ found: dict[str, None] = {}
400
+ for equality in join.conjuncts:
401
+ if not isinstance(equality, ir.Equality | ir.NullSafeEquality):
402
+ continue
403
+ for operand in (equality.left, equality.right):
404
+ read = ir.determinants(operand)
405
+ if read and all(column in side.output_columns for column in read) and (merging := merging_call(operand)) is not None:
406
+ found[merging] = None
407
+ return list(found)
408
+
409
+
369
410
  def _type_lost(column: ir.OutputColumn, loss: str | None) -> str:
370
411
  """Where a join key's type is lost, for an `untyped-key` join."""
371
412
  owner = current_arena().program.column_to_parent_relation_index.get(column)
@@ -394,7 +435,7 @@ def _untyped(source: Result, top: ir.ScalarExpr) -> str:
394
435
  the type (`untyped_source`): the key's own, or one nested in it, named."""
395
436
  subject = source.subjects[0]
396
437
  match subject:
397
- case ir.Call() | ir.OpaquePureFunction():
438
+ case ir.Call():
398
439
  why = ("no result type is known for its function", "has no result type sqlassert knows")
399
440
  case ir.OpaqueExpression():
400
441
  why = ("sqlassert does not model it", "is not modelled by sqlassert")
sqlassert/rules/domain.py CHANGED
@@ -266,7 +266,7 @@ def _expression_domain(expression: ir.ScalarExpr) -> Result[Domain]:
266
266
  return Result(value, f"Its operand is always NULL, so it is {_render(value)}", (expression,), [absent])
267
267
  return Result(None, "Its operand may be NULL or not", (expression,), [present, absent])
268
268
  case (
269
- ir.Constant() | ir.OpaqueExpression() | ir.OpaquePureFunction() | ir.Call() | ir.Count() | ir.Accumulation() | ir.Elements() | ir.Equality()
269
+ ir.Constant() | ir.OpaqueExpression() | ir.Call() | ir.Count() | ir.Accumulation() | ir.Elements() | ir.Equality()
270
270
  | ir.NullSafeEquality() | ir.InList() | ir.And() | ir.Or()
271
271
  ):
272
272
  return Result(None, "Values of this expression are not enumerated", (expression,))
@@ -4,9 +4,9 @@ A row of one input appears once per matching row of the other, or once padded,
4
4
  whatever the join kind. Matching rows satisfy ON, so they agree on every
5
5
  column an ON equality binds, all non-null: to a constant or to a pure function
6
6
  of the first row's columns (a column, `-b.x`, `b.x + 1`, `CAST(b.ts AS DATE)`),
7
- which is one value for that row, or, for the one column an exact injective
8
- function of it is of (`-a.x`, `a.x + 1`), to such a value. Neither operand
9
- needs to be injective to bind the other's column; the comparison must lose
7
+ which is one value for that row, or, for the one column a one-to-one
8
+ function of it is of (`-a.x`, `a.x + 1`, `a.x * 2` over exact numbers), to
9
+ such a value. Neither operand needs to be one-to-one to bind the other's column; the comparison must lose
10
10
  nothing (`fixes`). IS NOT DISTINCT FROM binds them too, but matches NULL to
11
11
  NULL, so those columns are non-null only where proved, or where the other side
12
12
  is a literal or an expression of non-null columns that is never NULL for them
@@ -30,7 +30,7 @@ from sqlassert.python_engine import Result, Stratum, all_of, any_of, analysis, c
30
30
  from sqlassert.rules.column_set import Attribute, ColumnSet
31
31
  from sqlassert.rules.nullability import non_null_column
32
32
  from sqlassert.rules.uniqueness import _closure, _key_gaps, _reaches_row_identity
33
- from sqlassert.rules.value_typing import _comparison_type, _identity_comparison, exact_numeric, fixes
33
+ from sqlassert.rules.value_typing import _comparison_type, _identity_comparison, fixes, reflected_column
34
34
 
35
35
  type Side = Literal["left", "right"]
36
36
 
@@ -89,9 +89,9 @@ def _bound_columns(join: ir.Join, matched: Side) -> Result[BoundColumns]:
89
89
  One operand is a constant or a pure function of that row's columns: a
90
90
  column, `-b.x`, `b.x + 1`, `CAST(b.ts AS DATE)`; for one row it is one
91
91
  value. The other fixes a column of `matched`: the column itself, or the one
92
- column an injective function of it (`-a.x`, `a.x + 1`) is of, since that
93
- function takes that value at one column value only. Neither needs the
94
- other to be injective, but the comparison must fix the matched side (`fixes`).
92
+ column a one-to-one function of it (`-a.x`, `a.x + 1`, `a.x * 2`) is of,
93
+ since that function takes that value at one column value only. Neither
94
+ needs the other to be one-to-one, but the comparison must fix the matched side (`fixes`).
95
95
  """
96
96
  relation, other = (join.right, join.left) if matched == "right" else (join.left, join.right)
97
97
  members = {}
@@ -103,7 +103,8 @@ def _bound_columns(join: ir.Join, matched: Side) -> Result[BoundColumns]:
103
103
  for bound, value in ((equality.left, equality.right), (equality.right, equality.left)):
104
104
  if bound is value:
105
105
  continue
106
- column = _fixed_column(bound, relation)
106
+ fixed = reflected_column(bound)
107
+ column = fixed.value if fixed.value in relation.output_columns else None
107
108
  inputs = ir.determinants(value)
108
109
  if column is None or inputs is None or not all(read in other.output_columns for read in inputs):
109
110
  continue
@@ -111,7 +112,9 @@ def _bound_columns(join: ir.Join, matched: Side) -> Result[BoundColumns]:
111
112
  if not fixes(bound, value).value:
112
113
  continue
113
114
 
114
- evidence = Result(True, "Equality fixes the matched column for each row of the other input", (equality, column, value))
115
+ # A function of the column says why it is one-to-one.
116
+ through = [] if isinstance(bound.closed, ir.ColumnRef) else [fixed]
117
+ evidence = Result(True, "Equality fixes the matched column for each row of the other input", (equality, column, value), through)
115
118
  members[column] = members[column] | evidence if column in members else evidence
116
119
  equalities.add(equality)
117
120
  # IS NOT DISTINCT FROM a value that is never NULL is `=`.
@@ -123,16 +126,6 @@ def _bound_columns(join: ir.Join, matched: Side) -> Result[BoundColumns]:
123
126
  return Result(BoundColumns(relation, set(members), definite, equalities), "Bound columns", members=members)
124
127
 
125
128
 
126
- def _fixed_column(expression: ir.ScalarExpr, relation: ir.RelationExpr) -> ir.OutputColumn | None:
127
- """The column of `relation` that `expression` taking one value fixes: the
128
- column itself, or the one an exact, injective function of it is of
129
- (`ir.injective_input`; the value of `-x` or `x + 1` has one `x`)."""
130
- column = ir.injective_input(expression)
131
- if column is None or column not in relation.output_columns:
132
- return None
133
- return column if isinstance(expression.closed, ir.ColumnRef) or exact_numeric(column).value else None
134
-
135
-
136
129
  # Why a join has no proved Join Cardinality --------------------------------
137
130
 
138
131
  type UnprovedReason = Literal["unsupported", "unconstrained", "unresolved-key", "untyped-key", "expression-key", "no-unique-set"]
@@ -162,8 +155,8 @@ class UnprovedJoin:
162
155
  - `expression-key`: every such equality compares an expression, and none
163
156
  binds a column (`_bound_columns`): the expression is not deterministic,
164
157
  or has no type that fixes the other (`fixes`), or the
165
- matched side is not an injective function of one exact column. `a.k =
166
- b.k * 2` is one, `a.k = b.k + 1` is not.
158
+ matched side is not a one-to-one function of one column
159
+ (`reflected_column`). `a.k = b.k % 2` is one, `a.k = b.k * 2` is not.
167
160
  - `no-unique-set`: the equalities bind columns that reach the Row
168
161
  Identity of neither input. `detail` says who can act, the first that
169
162
  applies (`NoUniqueSet`):
@@ -178,7 +178,7 @@ def _expression_sources(expression: ir.ScalarExpr) -> tuple[_Sources, list[Resul
178
178
  return result, []
179
179
  reason = f"{expression.function.name} is non-null when its arguments are" if arguments else f"{expression.function.name} is never NULL"
180
180
  return {}, [Result(True, reason, (expression,), premises)]
181
- case ir.OpaqueExpression(description=description) | ir.OpaquePureFunction(description=description) | ir.Call(description=description):
181
+ case ir.OpaqueExpression(description=description) | ir.Call(description=description):
182
182
  return {ORGANIC: unknown(f"Nullability of {description} is not known", expression)}, []
183
183
  case ir.Elements(operand=operand):
184
184
  elements = _expression_elements(operand)
@@ -248,7 +248,7 @@ def _expression_elements(expression: ir.ScalarExpr) -> Result[bool]:
248
248
  case ir.SimpleCase(thens=thens, default=default):
249
249
  return all_of(_expression_elements(arm) for arm in (*thens, default))
250
250
  case (
251
- ir.Constant() | ir.Count() | ir.Accumulation() | ir.Call() | ir.OpaqueExpression() | ir.OpaquePureFunction() | ir.Elements()
251
+ ir.Constant() | ir.Count() | ir.Accumulation() | ir.Call() | ir.OpaqueExpression() | ir.Elements()
252
252
  | ir.Equality() | ir.NullSafeEquality() | ir.InList() | ir.IsNull() | ir.IsNotNull() | ir.And() | ir.Or()
253
253
  ):
254
254
  return unknown("Its elements may be NULL", expression)
@@ -505,7 +505,7 @@ def _null_with(expression: ir.ScalarExpr) -> frozenset[Padding]:
505
505
  case ir.And(parts=(first, *others)) | ir.Or(parts=(first, *others)):
506
506
  return _null_with(first).intersection(*(_null_with(other) for other in others))
507
507
  case (
508
- ir.And() | ir.Or() | ir.Coalesce() | ir.Constant() | ir.NullLiteral() | ir.SimpleCase() | ir.OpaquePureFunction()
508
+ ir.And() | ir.Or() | ir.Coalesce() | ir.Constant() | ir.NullLiteral() | ir.SimpleCase()
509
509
  | ir.OpaqueExpression() | ir.Count() | ir.AnyAggregate() | ir.Accumulation() | ir.Elements() | ir.IsNull()
510
510
  | ir.IsNotNull() | ir.NullSafeEquality()
511
511
  ):
@@ -32,7 +32,10 @@ from sqlassert.properties import FunctionalDependency, NonNullUniqueSet, UniqueS
32
32
  from sqlassert.python_engine import Result, Stratum, all_of, analysis, any_of, current_arena, unknown
33
33
  from sqlassert.rules.column_set import Attribute, Closure, RowIdentity
34
34
  from sqlassert.rules.equality import _constant_value, _equal_columns, _predicate_constants, _predicate_equalities, _same_set_types, _typed_arms
35
- from sqlassert.rules.value_typing import _binary_text, _boolean, _identity_comparison, _signed_integer, exact_comparison, exact_numeric, fixes, scalar_typing
35
+ from sqlassert.rules.value_typing import (
36
+ _binary_text, _boolean, _identity_comparison, _signed_integer, exact_comparison, fixes, reflected_column, reflected_operand, respected_inputs,
37
+ respects_equality, scalar_typing,
38
+ )
36
39
  from sqlassert.rules.nullability import Padding, _null_sources, _padded_sides, non_null_column, non_null_columns
37
40
 
38
41
 
@@ -180,10 +183,12 @@ def _closure(relation: ir.RelationExpr, columns: frozenset[Attribute], definite:
180
183
  if closure is None:
181
184
  continue
182
185
  inputs[index] = closure
186
+ # The one-to-one calls that carried reached columns down.
187
+ carried = [proof for attribute, proof in delegation.through.items() if attribute in reached]
183
188
  for source, attributes in delegation.back.items():
184
189
  for attribute in attributes if source in closure.value.columns else ():
185
190
  if attribute not in reached:
186
- reach(attribute, Result(True, delegation.reason, (relation, attribute), [closure.members[source]]))
191
+ reach(attribute, Result(True, delegation.reason, (relation, attribute), [closure.members[source], *carried]))
187
192
  for attribute, sources in delegation.computed.items():
188
193
  if sources <= closure.value.columns and attribute not in reached:
189
194
  reason = "A deterministic function of determined input columns"
@@ -381,6 +386,8 @@ class _Delegation:
381
386
  reason: str
382
387
  valid: Callable[[dict[Attribute, Result[bool]], Callable[[Attribute], bool]], bool] | None = None
383
388
  computed: dict[Attribute, frozenset[Attribute]] = field(default_factory=dict)
389
+ # Why each attribute `down` maps through a one-to-one call keeps rows apart.
390
+ through: dict[Attribute, Result] = field(default_factory=dict)
384
391
 
385
392
  def run(self, reached: dict[Attribute, Result[bool]], is_definite: Callable[[Attribute], bool]) -> Result[Closure] | None:
386
393
  if self.valid is not None and not self.valid(reached, is_definite):
@@ -438,17 +445,24 @@ def _pass_through(relation: ir.RelationExpr, source: ir.RelationExpr) -> dict[ir
438
445
 
439
446
  def _one_to_one(relation: ir.RelationExpr, source: ir.RelationExpr) -> dict[ir.OutputColumn, ir.OutputColumn]:
440
447
  """Each output column that is an input column, or a one-to-one function
441
- of an integer or decimal one (`a + 1`), with that column: equal on one,
442
- equal on the other."""
448
+ of one (`a + 1` over integers: `reflected_column`), with that column:
449
+ equal on one, equal on the other."""
443
450
  passed = _pass_through(relation, source)
444
451
  mapping: dict[ir.OutputColumn, ir.OutputColumn] = {}
445
452
  for column in relation.output_columns:
446
- upstream = ir.injective_input(column.scalar_expr)
447
- if column not in passed and upstream in source.output_columns and exact_numeric(upstream).value:
453
+ upstream = reflected_column(column.scalar_expr).value
454
+ if column not in passed and upstream in source.output_columns:
448
455
  mapping[column] = upstream
449
456
  return mapping | passed
450
457
 
451
458
 
459
+ def _through(relation: ir.RelationExpr, source: ir.RelationExpr) -> dict[Attribute, Result]:
460
+ """Each output column `_one_to_one` maps through a call, with why the call
461
+ keeps different values different (`reflected_column`)."""
462
+ passed = _pass_through(relation, source)
463
+ return {column: reflected_column(column.scalar_expr) for column in _one_to_one(relation, source) if column not in passed}
464
+
465
+
452
466
  def _inverse(down: dict[Attribute, Attribute]) -> dict[Attribute, tuple[Attribute, ...]]:
453
467
  """Each input attribute `down` reaches, with every attribute mapped onto it."""
454
468
  back: dict[Attribute, tuple[Attribute, ...]] = {}
@@ -463,7 +477,7 @@ def _row_preserving(relation: ir.RelationExpr, source: ir.RelationExpr) -> _Dele
463
477
  down[RowIdentity(relation)] = RowIdentity(source)
464
478
  return _Delegation(
465
479
  source, down, _inverse(down), "Determined in the input",
466
- computed=_computed(relation, source),
480
+ computed=_computed(relation, source), through=_through(relation, source),
467
481
  )
468
482
 
469
483
 
@@ -491,7 +505,8 @@ def _grouped(relation: ir.RelationExpr, source: ir.RelationExpr) -> _Delegation:
491
505
  back[upstream] = (*back.get(upstream, ()), column)
492
506
  # A computed column of an Aggregate that is not a grouping item wraps its
493
507
  # value in AnyAggregate, so only grouping items and DISTINCT values remain.
494
- return _Delegation(source, down, back, "Determined in the input rows", computed=_computed(relation, source))
508
+ through = {column: proof for column, proof in _through(relation, source).items() if column in down}
509
+ return _Delegation(source, down, back, "Determined in the input rows", computed=_computed(relation, source), through=through)
495
510
 
496
511
 
497
512
  def _picked(aggregate: ir.Aggregate, base: _Delegation) -> list[_Delegation]:
@@ -520,45 +535,31 @@ def _picked(aggregate: ir.Aggregate, base: _Delegation) -> list[_Delegation]:
520
535
  def _picked_input(expression: ir.ScalarExpr) -> ir.OutputColumn | None:
521
536
  """The input column whose value on the row an AnyAggregate picks
522
537
  `expression` is a one-to-one function of: the AnyAggregate of that
523
- column, or one with an injective Builtin inside it or around it
524
- (`max(empno + 1)`, `max(empno) + 1`) when the column is an integer or
525
- decimal (`ir.injective_input`)."""
526
- match expression.closed:
527
- case ir.AnyAggregate(input=ir.ColumnRef(column=column)):
528
- return column
538
+ column, or one with a one-to-one function inside it or around it
539
+ (`max(empno + 1)`, `max(empno) + 1` over integers: `reflected_operand`)."""
540
+ match reflected_operand(expression).value.closed:
529
541
  case ir.AnyAggregate(input=value):
530
- column = ir.injective_input(value)
531
- case ir.Call(injective_argument=ir.ScalarExpr() as argument):
532
- column = _picked_input(argument)
542
+ return reflected_column(value).value
533
543
  case _:
534
544
  return None
535
- return column if column is not None and exact_numeric(column).value else None
536
545
 
537
546
 
538
547
  def _computed(relation: ir.RelationExpr, source: ir.RelationExpr) -> dict[Attribute, frozenset[Attribute]]:
539
- """Paulley §3.1.4: each column computed from columns of `source` by a pure
540
- function, with those columns. Only columns compared by identity qualify:
541
- under NOCASE `'a' = 'A'` while `upper(x) || x` tells them apart, and a
542
- DOUBLE's `-0.0 = 0.0` while its text does not."""
548
+ """Paulley §3.1.4: each column computed from columns of `source` by a
549
+ function that respects their equality (`respected_inputs`), with those
550
+ columns. Any pure function of columns compared by identity does; under
551
+ NOCASE `'a' = 'A'` while `upper(x) || x` tells them apart, and a DOUBLE's
552
+ `-0.0 = 0.0` while its text does not."""
543
553
  computed: dict[Attribute, frozenset[Attribute]] = {}
544
554
  for column in relation.output_columns:
545
555
  if isinstance(column.scalar_expr, ir.ColumnRef):
546
556
  continue # Pass-through columns map back directly.
547
- inputs = _identity_inputs(column.scalar_expr, source.output_columns)
548
- if inputs is not None:
557
+ inputs = respected_inputs(column.scalar_expr).value
558
+ if inputs is not None and all(read in source.output_columns for read in inputs):
549
559
  computed[column] = frozenset(inputs)
550
560
  return computed
551
561
 
552
562
 
553
- def _identity_inputs(expression: ir.ScalarExpr, columns: tuple[ir.OutputColumn, ...]) -> tuple[ir.OutputColumn, ...] | None:
554
- """The columns `expression` is a pure function of, when all are among
555
- `columns` and compared by identity."""
556
- inputs = ir.determinants(expression)
557
- if inputs is None or not all(column in columns and _identity_comparison(column).value for column in inputs):
558
- return None
559
- return inputs
560
-
561
-
562
563
  def _join_side(join: ir.Join, left: bool) -> _Delegation:
563
564
  side = join.left if left else join.right
564
565
  offset = 0 if left else len(join.left.output_columns)
@@ -602,11 +603,11 @@ def _match_status(join: ir.Join, padded_left: bool) -> frozenset[Attribute] | No
602
603
  reads = [operand.column for operand in operands if isinstance(operand, ir.ColumnRef)]
603
604
  else:
604
605
  # Paulley Lemma 9 (L6): a pure conjunct is fixed by the preserved
605
- # columns it reads, when those compare by identity (under NOCASE
606
+ # columns it reads, when it respects their equality (under NOCASE
606
607
  # `'a' = 'A'` while `x LIKE 'a%'` tells them apart).
607
608
  inputs = ir.determinants(conjunct)
608
609
  reads = [column for column in inputs or () if column in preserved.output_columns]
609
- if inputs is None or not all(_identity_comparison(column).value for column in reads):
610
+ if inputs is None or not all(respects_equality(conjunct, column).value for column in reads):
610
611
  # Volatile, opaque, or read under a collation: only the preserved row fixes it.
611
612
  return frozenset({RowIdentity(preserved)})
612
613
  referenced.update(outputs[column] for column in reads if column in preserved.output_columns)
@@ -709,7 +710,7 @@ def _equality_dependencies(conjuncts: tuple[ir.ScalarExpr, ...], outputs: dict[i
709
710
  """Dependencies of conjuncts that hold on every row: `a = b` and
710
711
  `a IS NOT DISTINCT FROM b` both ways, `a = literal` (or IS NOT DISTINCT
711
712
  FROM it) and `a IS NULL` from the empty set, and `b = f(x...)` from
712
- `x...` (Paulley Claim 20) when f is pure and they compare by identity."""
713
+ `x...` (Paulley Claim 20) when f respects their equality."""
713
714
  for conjunct in conjuncts:
714
715
  evidence = Result(True, f"{clause} conjunct", (conjunct,))
715
716
  match conjunct:
@@ -746,12 +747,12 @@ def _equality_dependencies(conjuncts: tuple[ir.ScalarExpr, ...], outputs: dict[i
746
747
  # The comparison must lose nothing, or `b` equals `f(x)` for values of `b` that differ.
747
748
  if not (isinstance(target, ir.ColumnRef) and target.column in outputs and fixes(target, value).value):
748
749
  continue
749
- inputs = _identity_inputs(value, tuple(outputs))
750
- if inputs is not None:
750
+ inputs = respected_inputs(value).value
751
+ if inputs is not None and all(column in outputs for column in inputs):
751
752
  yield tuple(outputs[column] for column in inputs), outputs[target.column], evidence
752
- # One-to-one: `b = a + 1` also gives b -> a, when both are exact.
753
- source = ir.injective_input(value)
754
- if source in outputs and exact_numeric(source).value and exact_numeric(target.column).value:
753
+ # One-to-one: `b = a + 1` also gives b -> a, the comparison fixing each side.
754
+ source = reflected_column(value).value
755
+ if source in outputs:
755
756
  yield (outputs[target.column],), outputs[source], evidence
756
757
  case _:
757
758
  pass # Other conjuncts only remove rows.