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.
sqlassert/rules/domain.py CHANGED
@@ -34,25 +34,30 @@ from decimal import Decimal
34
34
  from fractions import Fraction
35
35
  from typing import assert_never
36
36
 
37
+ from sqlassert.diagnostics import quoted
37
38
  from sqlassert import ir
39
+ from sqlassert import properties as props
38
40
  from sqlassert.properties import EnumeratedDomain
39
41
  from sqlassert.python_engine import Result, Stratum, analysis, any_of, current_arena, unknown
40
- from sqlassert.rules.equality import _equal_columns, _same_type
41
- from sqlassert.rules.nullability import non_null_column
42
+ from sqlassert.rules.equality import _equal_columns, _lax_equalities, _same_type
43
+ from sqlassert.rules.nullability import _non_null_expression, non_null_column
42
44
 
43
45
  # A finite set of possible non-null values, or None when any value is possible.
44
46
  type Domain = frozenset[ir.LiteralValue] | None
45
47
 
48
+ _TRUE = ir.LiteralValue(type="boolean", text="TRUE")
49
+ _FALSE = ir.LiteralValue(type="boolean", text="FALSE")
50
+
46
51
 
47
52
  @analysis(Stratum.DOMAIN)
48
53
  def enumerated_domain(column: ir.OutputColumn, values: frozenset[ir.LiteralValue]) -> Result[bool]:
49
54
  domain = _domain(column)
50
55
  if domain.value is None:
51
- return Result(False, f"No finite domain is known for {column.name}", (column,), [domain], kind="unknown")
56
+ return Result(False, f"No finite domain is known for {quoted(column.name)}", (column,), [domain], kind="unknown")
52
57
  uncovered = domain.value - values
53
58
  if uncovered:
54
59
  return Result(
55
- False, f"{column.name} may be {_render(uncovered)}, which the assertion does not cover",
60
+ False, f"{quoted(column.name)} may be {_render(uncovered)}, which the assertion does not cover",
56
61
  (column,), [domain], kind="unknown",
57
62
  )
58
63
  return Result(True, "Every possible value is listed", (column,), [domain])
@@ -102,19 +107,58 @@ def _else_unreachable(case: ir.SimpleCase) -> Result[bool]:
102
107
  return exhaustive_case(case) & present
103
108
 
104
109
 
110
+ def always_null_columns(property: props.Property) -> tuple[ir.OutputColumn, ...]:
111
+ """The columns named by `property` that are always NULL (an empty
112
+ domain) where NULL exempts a row from it, so it holds trivially: an
113
+ ENUM's or EXHAUSTIVE CASE operand's column, and any column of a Unique
114
+ Set, a dependency's determinant, Referential Coverage's referencing
115
+ columns, or NOT NULL ELEMENTS. NULL in a dependent is a value every row
116
+ agrees on, like a constant; a non-null Property fails on one instead."""
117
+ match property:
118
+ case props.EnumeratedDomain(column=column) | props.ExhaustiveCase(case=ir.SimpleCase(operand=ir.ColumnRef(column=column))):
119
+ columns: frozenset[ir.OutputColumn] = frozenset({column})
120
+ case props.ExhaustiveCase():
121
+ columns = frozenset() # An operand that is no column: only columns are named.
122
+ case props.NonNullUniqueSet() | props.NonNullColumns() | props.NonNullColumn():
123
+ columns = frozenset()
124
+ case props.UniqueSet(columns=columns) | props.NonNullElements(columns=columns):
125
+ pass
126
+ case props.FunctionalDependency(determinant=columns):
127
+ pass
128
+ case props.ReferentialCoverage(columns=referencing):
129
+ columns = frozenset(referencing)
130
+ case props.ManyToOneJoin() | props.OneToManyJoin() | props.OneToOneJoin() | props.UniqueJoin() | props.ExactlyOneJoin():
131
+ columns = frozenset()
132
+ case _:
133
+ raise AssertionError(f"unhandled property {type(property).__name__}")
134
+ return tuple(sorted((column for column in columns if _domain(column).value == frozenset()), key=lambda column: column.name))
135
+
136
+
105
137
  @analysis(Stratum.DOMAIN)
106
138
  def _domain(column: ir.OutputColumn) -> Result[Domain]:
107
139
  """`column`'s domain: its own, intersected with every equal column's."""
108
140
  group = _equal_columns(column)
109
141
  relation = column.get_relation(current_arena().program)
110
- members = [member for member in relation.output_columns if member in group.value]
142
+ reachable = set(group.value)
143
+ edges = _lax_equalities(relation).value
144
+ lax_evidence = []
145
+ pending = list(reachable)
146
+ while pending:
147
+ first = pending.pop()
148
+ for (source, other), reason in edges.items():
149
+ if source is first and other not in reachable:
150
+ new = _equal_columns(other).value - reachable
151
+ reachable.update(new)
152
+ pending.extend(new)
153
+ lax_evidence.append(Result(True, "A non-null value satisfies the ON equality", (reason,)))
154
+ members = [member for member in relation.output_columns if member in reachable]
111
155
  owns = [_own_domain(member) for member in members]
112
156
  known = [own for own in owns if own.value is not None]
113
157
  if not known:
114
- return Result(None, f"No finite domain is known for {column.name}", (column,), owns)
158
+ return Result(None, f"No finite domain is known for {quoted(column.name)}", (column,), owns)
115
159
  value = _meet([own.value for own in known if own.value is not None], _binary_text(column))
116
- premises = [group, *known] if len(members) > 1 else known
117
- return Result(value, f"{column.name} is one of {_render(value)}", (column,), premises)
160
+ premises = [group, *lax_evidence, *known] if len(members) > 1 else known
161
+ return Result(value, f"{quoted(column.name)} is one of {_render(value)}", (column,), premises)
118
162
 
119
163
 
120
164
  @analysis(Stratum.DOMAIN)
@@ -125,7 +169,7 @@ def _own_domain(column: ir.OutputColumn) -> Result[Domain]:
125
169
  for item in arena.knowledge:
126
170
  match item:
127
171
  case EnumeratedDomain(column=known, values=values) if known is column:
128
- sources.append(Result(values, f"{column.name} is known to be one of {_render(values)}", (column,), [any_of(arena.accepted_evidence(item))]))
172
+ sources.append(Result(values, f"{quoted(column.name)} is known to be one of {_render(values)}", (column,), [any_of(arena.accepted_evidence(item))]))
129
173
  case _:
130
174
  pass # Other Knowledge says nothing about values.
131
175
  return _intersection(column, sources)
@@ -135,7 +179,7 @@ def _computed_domain(relation: ir.RelationExpr, column: ir.OutputColumn) -> Resu
135
179
  relation = relation.closed
136
180
  match relation:
137
181
  case ir.NamedRelation(body=None) | ir.OpaqueRelation():
138
- return Result(None, f"{column.name} is not enumerated", (column,))
182
+ return Result(None, f"{quoted(column.name)} is not enumerated", (column,))
139
183
  case ir.SetOperation():
140
184
  return _set_operation_domain(relation, column)
141
185
  case ir.Filter() | ir.Join():
@@ -165,11 +209,11 @@ def _set_operation_domain(relation: ir.SetOperation, column: ir.OutputColumn) ->
165
209
  return left
166
210
  return _intersection(column, [left, right])
167
211
  if left.value is None or right.value is None:
168
- return Result(None, f"An input of the UNION does not enumerate {column.name}", (relation, column), [left, right])
212
+ return Result(None, f"An input of the UNION does not enumerate {quoted(column.name)}", (relation, column), [left, right])
169
213
  value = left.value | right.value
170
214
  if len({member.type for member in value}) > 1:
171
- return Result(None, f"The UNION's inputs give {column.name} values of different types", (relation, column), [left, right])
172
- return Result(value, f"{column.name} is one of either input's values: {_render(value)}", (relation, column), [left, right])
215
+ return Result(None, f"The UNION's inputs give {quoted(column.name)} values of different types", (relation, column), [left, right])
216
+ return Result(value, f"{quoted(column.name)} is one of either input's values: {_render(value)}", (relation, column), [left, right])
173
217
 
174
218
 
175
219
  def _expression_domain(expression: ir.ScalarExpr) -> Result[Domain]:
@@ -189,7 +233,7 @@ def _expression_domain(expression: ir.ScalarExpr) -> Result[Domain]:
189
233
  value = frozenset().union(*(domain.value for domain in domains if domain.value is not None))
190
234
  return Result(value, "Coalesce takes one of its arguments' values", (expression,), domains)
191
235
  case ir.AnyAggregate(input=value):
192
- # Groups are never empty, so the value comes from some input row.
236
+ # The value comes from some input row, or is NULL (an empty group).
193
237
  return _expression_domain(value)
194
238
  case ir.SimpleCase(thens=thens, default=default):
195
239
  arms = [_expression_domain(then) for then in thens]
@@ -201,7 +245,29 @@ def _expression_domain(expression: ir.ScalarExpr) -> Result[Domain]:
201
245
  value = frozenset().union(*(arm.value for arm in arms if arm.value is not None))
202
246
  premises = [*arms, unreachable] if unreachable.value else arms
203
247
  return Result(value, "A CASE takes one of its arms' values", (expression,), premises)
204
- case ir.Constant() | ir.OpaqueExpression() | ir.OpaquePureFunction() | ir.Call() | ir.Count() | ir.Elements() | ir.Equality() | ir.InList() | ir.IsNull() | ir.IsNotNull() | ir.And() | ir.Or():
248
+ case ir.Call(strict_arguments=arguments) if arguments:
249
+ # NULL wherever a strict argument is, so always NULL where one always is.
250
+ for argument in arguments:
251
+ absent = _expression_domain(argument)
252
+ if absent.value == frozenset():
253
+ return Result(frozenset(), "A strict argument is always NULL, so it is", (expression,), [absent])
254
+ return Result(None, "Values of this expression are not enumerated", (expression,))
255
+ case ir.IsNull(operand=operand) | ir.IsNotNull(operand=operand):
256
+ # A constant where the operand is never NULL, or always.
257
+ null = isinstance(expression, ir.IsNull)
258
+ present = _non_null_expression(operand)
259
+ if present.value:
260
+ value = frozenset({_FALSE if null else _TRUE})
261
+ return Result(value, f"Its operand is never NULL, so it is {_render(value)}", (expression,), [present])
262
+ absent = _expression_domain(operand)
263
+ if absent.value == frozenset():
264
+ value = frozenset({_TRUE if null else _FALSE})
265
+ return Result(value, f"Its operand is always NULL, so it is {_render(value)}", (expression,), [absent])
266
+ return Result(None, "Its operand may be NULL or not", (expression,), [present, absent])
267
+ case (
268
+ ir.Constant() | ir.OpaqueExpression() | ir.OpaquePureFunction() | ir.Call() | ir.Count() | ir.Accumulation() | ir.Elements() | ir.Equality()
269
+ | ir.NullSafeEquality() | ir.InList() | ir.And() | ir.Or()
270
+ ):
205
271
  return Result(None, "Values of this expression are not enumerated", (expression,))
206
272
  case _:
207
273
  assert_never(expression)
@@ -231,7 +297,34 @@ def _narrowings(relation: ir.Filter | ir.Join, column: ir.OutputColumn) -> list[
231
297
  for conjunct in conjuncts:
232
298
  bound = _conjunct_bound(conjunct, source)
233
299
  if bound is not None and bound.value is not None:
234
- narrowings.append(Result(bound.value, f"The {clause} conjunct bounds {column.name} to {_render(bound.value)}", (conjunct,), [bound]))
300
+ narrowings.append(Result(bound.value, f"The {clause} conjunct bounds {quoted(column.name)} to {_render(bound.value)}", (conjunct,), [bound]))
301
+ if isinstance(relation, ir.Join) and relation.kind == "semi":
302
+ narrowings.extend(_matched_narrowings(relation, column, source))
303
+ return narrowings
304
+
305
+
306
+ def _matched_narrowings(join: ir.Join, column: ir.OutputColumn, source: ir.OutputColumn) -> list[Result[Domain]]:
307
+ """A semi join's left column equal to a right column of the same type
308
+ takes that column's value on the matched right row, which every other ON
309
+ conjunct bounds too: `d.deptno = e.mgr AND d.deptno = 10` bounds mgr."""
310
+ narrowings: list[Result[Domain]] = []
311
+ for conjunct in join.conjuncts:
312
+ match conjunct:
313
+ case (
314
+ ir.Equality(left=ir.ColumnRef(column=first), right=ir.ColumnRef(column=second))
315
+ | ir.NullSafeEquality(left=ir.ColumnRef(column=first), right=ir.ColumnRef(column=second))
316
+ ) if source in (first, second):
317
+ other = second if first is source else first
318
+ case _:
319
+ continue
320
+ if other not in join.right.output_columns or not _same_type(source, other):
321
+ continue
322
+ bounds = [bound for part in join.conjuncts if part is not conjunct and (bound := _conjunct_bound(part, other)) is not None]
323
+ if bounds:
324
+ bound = _intersection(other, bounds)
325
+ if bound.value is not None:
326
+ reason = f"{quoted(column.name)} equals {quoted(other.name)} of the matched right row, which ON bounds to {_render(bound.value)}"
327
+ narrowings.append(Result(bound.value, reason, (conjunct,), [bound]))
235
328
  return narrowings
236
329
 
237
330
 
@@ -244,9 +337,10 @@ def _conjunct_bound(conjunct: ir.ScalarExpr, source: ir.OutputColumn) -> Result[
244
337
  unknown domain.
245
338
  """
246
339
  match conjunct:
247
- case ir.Equality(left=ir.ColumnRef(column=first), right=other) if first is source:
340
+ # A TRUE IS NOT DISTINCT FROM leaves a non-null side equal to the other.
341
+ case ir.Equality(left=ir.ColumnRef(column=first), right=other) | ir.NullSafeEquality(left=ir.ColumnRef(column=first), right=other) if first is source:
248
342
  bounds = [_bound_domain(source, other)]
249
- case ir.Equality(left=other, right=ir.ColumnRef(column=second)) if second is source:
343
+ case ir.Equality(left=other, right=ir.ColumnRef(column=second)) | ir.NullSafeEquality(left=other, right=ir.ColumnRef(column=second)) if second is source:
250
344
  bounds = [_bound_domain(source, other)]
251
345
  case ir.InList(operand=ir.ColumnRef(column=operand), values=values) if operand is source:
252
346
  bounds = [_bound_domain(source, value) for value in values]
@@ -263,11 +357,13 @@ def _conjunct_bound(conjunct: ir.ScalarExpr, source: ir.OutputColumn) -> Result[
263
357
  if any(bound is None or bound.value is None for bound in bounds):
264
358
  return None
265
359
  value = frozenset().union(*(bound.value for bound in bounds if bound is not None and bound.value is not None))
266
- return Result(value, f"{source.name} is in {_render(value)} on every row this conjunct keeps", (conjunct,), [bound for bound in bounds if bound is not None])
360
+ return Result(value, f"{quoted(source.name)} is in {_render(value)} on every row this conjunct keeps", (conjunct,), [bound for bound in bounds if bound is not None])
267
361
 
268
362
 
269
363
  def _bound_domain(column: ir.OutputColumn, expression: ir.ScalarExpr) -> Result[Domain]:
270
364
  match expression:
365
+ case ir.Constant(value=ir.LiteralValue(type="numeric", text=text)) if "e" in text.lower():
366
+ return Result(None, "An approximate numeric comparison may collapse distinct values", (expression,))
271
367
  case ir.Constant() | ir.NullLiteral():
272
368
  return _expression_domain(expression)
273
369
  case ir.ColumnRef(column=source) if _same_type(column, source):
@@ -279,11 +375,11 @@ def _bound_domain(column: ir.OutputColumn, expression: ir.ScalarExpr) -> Result[
279
375
  def _intersection(column: ir.OutputColumn, sources: list[Result[Domain]]) -> Result[Domain]:
280
376
  known = [source for source in sources if source.value is not None]
281
377
  if not known:
282
- return Result(None, f"No finite domain is known for {column.name}", (column,), sources)
378
+ return Result(None, f"No finite domain is known for {quoted(column.name)}", (column,), sources)
283
379
  if len(known) == 1:
284
380
  return known[0]
285
381
  value = _meet([source.value for source in known if source.value is not None], _binary_text(column))
286
- return Result(value, f"{column.name} is one of {_render(value)}", (column,), known)
382
+ return Result(value, f"{quoted(column.name)} is one of {_render(value)}", (column,), known)
287
383
 
288
384
 
289
385
  def _meet(domains: list[frozenset[ir.LiteralValue]], binary_text: bool) -> frozenset[ir.LiteralValue]:
@@ -1,13 +1,16 @@
1
1
  """Equality groups: the output columns of a relation that carry one value.
2
2
 
3
3
  A strict equality -- a `WHERE` or inner-join `ON` conjunct `a = b` -- keeps
4
- only rows on which `a` and `b` are non-null and equal. Equality groups are a
4
+ only rows on which `a` and `b` are non-null and equal; `a IS NOT DISTINCT
5
+ FROM b` those on which they are equal or both NULL. Equality groups are a
5
6
  union-find over those equalities, per relation, over its output columns: an
6
7
  input's groups pass through every column that passes an input column through,
7
8
  then the relation's own strict equalities merge them. On every row a group's
8
- members are equal, or all NULL where an outer join padded them (padding nulls
9
- a whole side). An outer join's ON never merges: it holds on matched rows only,
10
- and a padded row keeps the preserved side's value.
9
+ members are equal, or all NULL (an outer join padded them, padding nulling a
10
+ whole side, or IS NOT DISTINCT FROM equated NULLs): where one is non-null,
11
+ every one equals it. A semi join's ON merges through the columns of the
12
+ matched right row, which no output carries. An outer join's ON merges columns on the side it pads together. Cross-side
13
+ equalities become strict when a filter excludes the padding.
11
14
 
12
15
  A functional dependency `a ↔ b` also holds for an injective `a = f(b)`, whose
13
16
  values differ; a group says the values are the same. Facts about values read
@@ -18,7 +21,10 @@ never does.
18
21
  from __future__ import annotations
19
22
 
20
23
  from dataclasses import dataclass
24
+ from itertools import combinations
25
+ from collections.abc import Callable, Iterable, Mapping
21
26
  from typing import assert_never
27
+ import re
22
28
 
23
29
  from sqlassert import ir
24
30
  from sqlassert.python_engine import Result, Stratum, analysis, current_arena
@@ -76,13 +82,41 @@ def _equality_groups(relation: ir.RelationExpr) -> Result[EqualityGroups]:
76
82
  own = [column for upstream in group for column in passed.get(upstream, ())]
77
83
  merge(own, Result(True, "Equal in the input", (), [groups.members[group]]))
78
84
 
85
+ if isinstance(relation, ir.Join) and relation.kind == "semi":
86
+ # The matched right row's columns carry values too, though no output
87
+ # does: two left columns equal to one right column are equal.
88
+ right = relation.right
89
+ for column in right.output_columns:
90
+ roots[column], evidence[column], outputs[column] = column, [], [column]
91
+ groups = _equality_groups(right)
92
+ for group in groups.value.groups:
93
+ merge(list(group), Result(True, "Equal in the matched right row", (), [groups.members[group]]))
94
+
79
95
  conjuncts, clause = _strict_conjuncts(relation)
80
- for conjunct in conjuncts:
81
- match conjunct:
82
- case ir.Equality(left=ir.ColumnRef(column=first), right=ir.ColumnRef(column=second)) if first in outputs and second in outputs and _same_type(first, second):
83
- merge([*outputs[first], *outputs[second]], Result(True, f"{clause} equality", (conjunct,)))
84
- case _:
85
- pass # Other conjuncts only remove rows.
96
+ for (first, second), reason in _predicate_equalities(conjuncts).items():
97
+ if first in outputs and second in outputs:
98
+ merge([*outputs[first], *outputs[second]], Result(True, f"{clause} equality", (reason,)))
99
+
100
+ if isinstance(relation, ir.Join) and relation.kind in {"left", "right"}:
101
+ padded = relation.right if relation.kind == "left" else relation.left
102
+ for (first, second), reason in _predicate_equalities(relation.conjuncts).items():
103
+ if first in padded.output_columns and second in padded.output_columns:
104
+ merge([*outputs[first], *outputs[second]], Result(True, "ON equality within the padded side", (reason,)))
105
+
106
+ if isinstance(relation, ir.Filter):
107
+ from sqlassert.rules.nullability import non_null_column
108
+
109
+ for (first, second), reason in _lax_equalities(relation).value.items():
110
+ definite = non_null_column(first)
111
+ if definite.value:
112
+ merge([first, second], Result(True, "The ON equality holds without padding", (reason,), [definite]))
113
+
114
+ if isinstance(relation, ir.SetOperation) and relation.operator == "union":
115
+ typed = {column: arms for column in relation.output_columns if (arms := _typed_arms(relation, column)) is not None}
116
+ for first, second in combinations(typed, 2):
117
+ arm_groups = [_equal_columns(arm) for arm in typed[first]]
118
+ if all(other in group.value for other, group in zip(typed[second], arm_groups)):
119
+ merge([first, second], Result(True, "Equal in both UNION inputs", (relation,), arm_groups))
86
120
 
87
121
  grouped: dict[ir.OutputColumn, list[ir.OutputColumn]] = {}
88
122
  for column in relation.output_columns:
@@ -98,44 +132,167 @@ def _equality_groups(relation: ir.RelationExpr) -> Result[EqualityGroups]:
98
132
  return Result(value, "Equality groups", (relation,), list(members.values()), members=members)
99
133
 
100
134
 
135
+ # Ordered pairs of columns an equality relates, each with the conjunct that
136
+ # relates them.
137
+ type Equalities = dict[tuple[ir.OutputColumn, ir.OutputColumn], ir.ScalarExpr]
138
+
139
+
140
+ def _in_every_branch[Key](disjunction: ir.Or, facts: Callable[[tuple[ir.ScalarExpr, ...]], Mapping[Key, object]]) -> list[Key]:
141
+ """The facts every branch of an OR establishes: one of them holds on each row."""
142
+ first, *rest = (facts(ir.conjuncts(part)) for part in disjunction.parts)
143
+ return [key for key in first if all(key in branch for branch in rest)]
144
+
145
+
146
+ def _predicate_equalities(conjuncts: tuple[ir.ScalarExpr, ...]) -> Equalities:
147
+ """The column equalities every row satisfying `conjuncts` meets."""
148
+ pairs: Equalities = {}
149
+ for conjunct in conjuncts:
150
+ match conjunct:
151
+ case ir.Or():
152
+ pairs.update(dict.fromkeys(_in_every_branch(conjunct, _predicate_equalities), conjunct))
153
+ case (
154
+ ir.Equality(left=ir.ColumnRef(column=first), right=ir.ColumnRef(column=second))
155
+ | ir.NullSafeEquality(left=ir.ColumnRef(column=first), right=ir.ColumnRef(column=second))
156
+ ) if _same_type(first, second):
157
+ pairs[first, second] = pairs[second, first] = conjunct
158
+ return pairs
159
+
160
+
161
+ @analysis(Stratum.COMPARISON)
162
+ def _lax_equalities(relation: ir.RelationExpr) -> Result[Equalities]:
163
+ """Directed pairs: where the first is non-null, it equals the second."""
164
+ pairs: Equalities = {}
165
+ for source in _inputs(relation):
166
+ passed = _pass_through(relation, source)
167
+ for (first, second), reason in _lax_equalities(source).value.items():
168
+ for own in passed.get(first, ()):
169
+ for other in passed.get(second, ()):
170
+ pairs[own, other] = reason
171
+ if isinstance(relation, ir.Join) and relation.kind in {"left", "right"}:
172
+ padded, preserved = (relation.right, relation.left) if relation.kind == "left" else (relation.left, relation.right)
173
+ padded_outputs = _pass_through(relation, padded)
174
+ preserved_outputs = _pass_through(relation, preserved)
175
+ for (first, second), reason in _predicate_equalities(relation.conjuncts).items():
176
+ for own in padded_outputs.get(first, ()):
177
+ for other in preserved_outputs.get(second, ()):
178
+ pairs[own, other] = reason
179
+ return Result(pairs, "Lax equalities", (relation,))
180
+
181
+
182
+ def _predicate_constants(conjuncts: tuple[ir.ScalarExpr, ...]) -> dict[ir.OutputColumn, tuple[ir.LiteralValue | None, ir.ScalarExpr]]:
183
+ """The constant (SQL NULL included) each column has on every row
184
+ satisfying `conjuncts`, with the conjunct that fixes it."""
185
+ return {column: (value, conjunct) for (column, value), conjunct in _pinned_values(conjuncts).items()}
186
+
187
+
188
+ def _pinned_values(conjuncts: tuple[ir.ScalarExpr, ...]) -> dict[tuple[ir.OutputColumn, ir.LiteralValue | None], ir.ScalarExpr]:
189
+ pinned: dict[tuple[ir.OutputColumn, ir.LiteralValue | None], ir.ScalarExpr] = {}
190
+ for conjunct in conjuncts:
191
+ match conjunct:
192
+ case ir.Or():
193
+ pinned.update(dict.fromkeys(_in_every_branch(conjunct, _pinned_values), conjunct))
194
+ case ir.Equality(left=left, right=right) | ir.NullSafeEquality(left=left, right=right):
195
+ for column, literal in ((left, right), (right, left)):
196
+ if isinstance(column, ir.ColumnRef) and isinstance(literal, ir.Constant) and literal.value is not None:
197
+ if _pins(column.column, literal):
198
+ pinned[column.column, literal.value] = conjunct
199
+ case ir.IsNull(operand=ir.ColumnRef(column=column)):
200
+ pinned[column, None] = conjunct
201
+ return pinned
202
+
203
+
204
+ @analysis(Stratum.COMPARISON)
205
+ def _constant_value(column: ir.OutputColumn) -> Result[tuple[ir.LiteralValue | None] | None]:
206
+ """An exact constant, including SQL NULL, on every row carrying this column."""
207
+ relation = column.get_relation(current_arena().program).closed
208
+ unknown_value: Result[tuple[ir.LiteralValue | None] | None] = Result(None, "No exact constant is known", (column,))
209
+ match relation:
210
+ case ir.SetOperation(operator="union"):
211
+ if (arms := _typed_arms(relation, column)) is None:
212
+ return unknown_value
213
+ left, right = (_constant_value(arm) for arm in arms)
214
+ if left.value is not None and left.value == right.value:
215
+ return Result(left.value, "The same constant in both UNION inputs", (column,), [left, right])
216
+ return unknown_value
217
+ case ir.Filter(conjuncts=conjuncts):
218
+ match column.scalar_expr:
219
+ case ir.ColumnRef(column=source) if (constant := _predicate_constants(conjuncts).get(source)) is not None:
220
+ value, conjunct = constant
221
+ return Result((value,), "The WHERE clause fixes the value", (conjunct,))
222
+ case ir.ColumnRef(column=source):
223
+ return _constant_value(source)
224
+ case _:
225
+ return unknown_value
226
+ case ir.Project() | ir.Alias() | ir.NamedRelation() | ir.Distinct() | ir.Limit() | ir.QualifyByPartition():
227
+ match column.scalar_expr:
228
+ case ir.ColumnRef(column=source):
229
+ return _constant_value(source)
230
+ case ir.Constant(value=ir.LiteralValue() as literal):
231
+ return Result((literal,), "A literal is constant", (column,))
232
+ case ir.NullLiteral():
233
+ return Result((None,), "A NULL literal is constant", (column,))
234
+ case _:
235
+ return unknown_value
236
+ case ir.Join() | ir.Aggregate() | ir.SetOperation() | ir.OpaqueRelation():
237
+ # Padding, grouping, and the other set operations are not followed.
238
+ return unknown_value
239
+ case _:
240
+ assert_never(relation)
241
+
242
+
101
243
  def _same_type(first: ir.OutputColumn, second: ir.OutputColumn) -> bool:
102
244
  """Equalities are value identities only for known, matching comparison types."""
103
245
  first_type = _comparison_type(first).value
104
246
  return first is second or first_type is not None and first_type == _comparison_type(second).value
105
247
 
106
248
 
107
- @analysis(Stratum.EQUALITY_GROUP)
249
+ @analysis(Stratum.COMPARISON)
108
250
  def _comparison_type(column: ir.OutputColumn) -> Result[str | None]:
109
251
  relation = column.get_relation(current_arena().program)
252
+ if isinstance(relation, ir.SetOperation) and (arms := relation.arms(column)) is not None:
253
+ # Both inputs of one type: the output is that type.
254
+ left, right = (_comparison_type(arm) for arm in arms)
255
+ if left.value is not None and left.value == right.value:
256
+ return Result(left.value, "Both inputs of the set operation share the comparison type", (column,), [left, right])
110
257
  match column.scalar_expr:
111
- case ir.ColumnRef(column=source) if not isinstance(relation, ir.SetOperation):
258
+ case ir.ColumnRef(column=source) | ir.AnyAggregate(input=ir.ColumnRef(column=source)) if not isinstance(relation, ir.SetOperation):
112
259
  return _comparison_type(source)
260
+ case ir.Constant(value=ir.LiteralValue(type="numeric", text=text)) if _small_integer(text):
261
+ return Result("INT", "Integer literal", (column,))
113
262
  case _:
114
263
  return Result(column.comparison_type, "Declared comparison type", (column,))
115
264
 
116
265
 
117
- @analysis(Stratum.EQUALITY_GROUP)
266
+ @analysis(Stratum.COMPARISON)
118
267
  def _identity_comparison(column: ir.OutputColumn) -> Result[bool]:
119
268
  """Whether equal values of `column` are identical, from its declared type."""
120
269
  relation = column.get_relation(current_arena().program)
270
+ if (both := _both_inputs(column, relation, _identity_comparison)) is not None:
271
+ return both
121
272
  match column.scalar_expr:
122
- case ir.ColumnRef(column=source) if not isinstance(relation, ir.SetOperation):
273
+ case ir.ColumnRef(column=source) | ir.AnyAggregate(input=ir.ColumnRef(column=source)) if not isinstance(relation, ir.SetOperation):
274
+ # A picked value (min, max, any_value) is a value of its column.
123
275
  return _identity_comparison(source)
124
276
  case _:
125
277
  return Result(column.identity_comparison, "Declared type compares by identity", (column,))
126
278
 
127
279
 
280
+ def _both_inputs(
281
+ column: ir.OutputColumn, relation: ir.RelationExpr | None, fact: Callable[[ir.OutputColumn], Result[bool]]
282
+ ) -> Result[bool] | None:
283
+ """A set operation's column has a type fact when both its input columns
284
+ have one comparison type and the fact: its type is theirs, not widened.
285
+ None when that is not shown, and the column's own declaration decides."""
286
+ if not isinstance(relation, ir.SetOperation) or (arms := relation.arms(column)) is None or not _same_type(*arms):
287
+ return None
288
+ left, right = (fact(arm) for arm in arms)
289
+ if not (left.value and right.value):
290
+ return None
291
+ return Result(True, "Both inputs of the set operation have it", (column,), [left, right])
292
+
293
+
128
294
  def _pins(column: ir.OutputColumn, value: ir.ScalarExpr) -> bool:
129
- """Whether `column = value` leaves `column` one value for each value of
130
- `value`, whatever casts the comparison adds.
131
-
132
- A column of a non-text type whose equal values are identical is: the
133
- other side is cast to its type, or it is cast to a wider type, which
134
- loses nothing. Text compared by identity is only when the other side is
135
- such text too, or a string literal: compared with a number it is cast to
136
- the number (`'01'` and `'1'` both equal 1). Anything else is not: a
137
- collation or a float equates different values, and of an unknown type
138
- nothing is known."""
295
+ """Whether equality can pin the column without a lossy coercion."""
139
296
  if _binary_text(column).value:
140
297
  match value:
141
298
  case ir.Constant(value=ir.LiteralValue(type="string")):
@@ -144,7 +301,55 @@ def _pins(column: ir.OutputColumn, value: ir.ScalarExpr) -> bool:
144
301
  return _binary_text(other).value
145
302
  case _:
146
303
  return False
147
- return _identity_comparison(column).value or _exact_arithmetic(column)
304
+ if not (_identity_comparison(column).value or _signed_integer(column)):
305
+ return False
306
+ match value:
307
+ case ir.ColumnRef(column=other):
308
+ return _same_type(column, other) or (
309
+ _signed_integer(column) and _signed_integer(other)
310
+ )
311
+ case ir.Constant(value=ir.LiteralValue(type="numeric", text=text)):
312
+ return "e" not in text.lower() and (exact_numeric(column).value or _exact_arithmetic(column))
313
+ case ir.Constant(value=ir.LiteralValue(type="boolean")):
314
+ return _comparison_type(column).value == "BOOLEAN"
315
+ case _:
316
+ return False
317
+
318
+
319
+ _SIGNED_INTEGERS = {"TINYINT", "SMALLINT", "INT", "INTEGER", "BIGINT", "HUGEINT", "INT128"}
320
+
321
+
322
+ def _small_integer(text: str) -> bool:
323
+ return re.fullmatch(r"-?[0-9]{1,10}", text) is not None and -(2**31) <= int(text) < 2**31
324
+
325
+
326
+ def _signed_integer(column: ir.OutputColumn) -> bool:
327
+ if _comparison_type(column).value in _SIGNED_INTEGERS:
328
+ return True
329
+ program = current_arena().program
330
+ while isinstance(column.scalar_expr, ir.ColumnRef) and not isinstance(column.get_relation(program), ir.SetOperation):
331
+ column = column.scalar_expr.column
332
+ if isinstance(column.scalar_expr, ir.Count):
333
+ return True
334
+ if not isinstance(column.scalar_expr, ir.Call):
335
+ return False
336
+ argument = column.scalar_expr.injective_argument
337
+ return isinstance(argument, ir.ColumnRef) and _comparison_type(argument.column).value in _SIGNED_INTEGERS and all(
338
+ node is argument or isinstance(node, ir.Constant) and node.value is not None
339
+ and node.value.type == "numeric" and _small_integer(node.value.text)
340
+ for node in column.scalar_expr.arguments
341
+ )
342
+
343
+
344
+ def _same_set_types(operation: ir.SetOperation, columns: Iterable[ir.OutputColumn]) -> bool:
345
+ """Whether set output columns retain the same types as their inputs."""
346
+ return all(_typed_arms(operation, column) is not None for column in columns)
347
+
348
+
349
+ def _typed_arms(operation: ir.SetOperation, column: ir.OutputColumn) -> tuple[ir.OutputColumn, ir.OutputColumn] | None:
350
+ """`column`'s input columns, when it keeps their type: its values are theirs."""
351
+ arms = operation.arms(column)
352
+ return arms if arms is not None and _same_type(*arms) else None
148
353
 
149
354
 
150
355
  def _exact_arithmetic(column: ir.OutputColumn) -> bool:
@@ -161,10 +366,12 @@ def _exact_arithmetic(column: ir.OutputColumn) -> bool:
161
366
  return source is not None and exact_numeric(source).value
162
367
 
163
368
 
164
- @analysis(Stratum.EQUALITY_GROUP)
369
+ @analysis(Stratum.COMPARISON)
165
370
  def _binary_text(column: ir.OutputColumn) -> Result[bool]:
166
371
  """Whether `column` is text compared by identity, from its declared type."""
167
372
  relation = column.get_relation(current_arena().program)
373
+ if (both := _both_inputs(column, relation, _binary_text)) is not None:
374
+ return both
168
375
  match column.scalar_expr:
169
376
  case ir.ColumnRef(column=source) if not isinstance(relation, ir.SetOperation):
170
377
  return _binary_text(source)
@@ -172,12 +379,14 @@ def _binary_text(column: ir.OutputColumn) -> Result[bool]:
172
379
  return Result(column.binary_text, "Declared as text compared by identity", (column,))
173
380
 
174
381
 
175
- @analysis(Stratum.EQUALITY_GROUP)
382
+ @analysis(Stratum.COMPARISON)
176
383
  def exact_numeric(column: ir.OutputColumn) -> Result[bool]:
177
384
  """Whether `column` is an integer or decimal, from its declared type."""
178
385
  relation = column.get_relation(current_arena().program)
386
+ if (both := _both_inputs(column, relation, exact_numeric)) is not None:
387
+ return both
179
388
  match column.scalar_expr:
180
- case ir.ColumnRef(column=source) if not isinstance(relation, ir.SetOperation):
389
+ case ir.ColumnRef(column=source) | ir.AnyAggregate(input=ir.ColumnRef(column=source)) if not isinstance(relation, ir.SetOperation):
181
390
  return exact_numeric(source)
182
391
  case _:
183
392
  return Result(column.exact_numeric, "Declared an integer or decimal", (column,))
@@ -198,7 +407,7 @@ def _inputs(relation: ir.RelationExpr) -> tuple[ir.RelationExpr, ...]:
198
407
  case ir.Join(left=left):
199
408
  # A semi or anti join keeps left rows; its right columns have no row.
200
409
  return (left,)
201
- case ir.SetOperation(operator="intersect" | "except", left=left):
410
+ case ir.SetOperation(operator="intersect" | "except", left=left) if _same_set_types(relation, relation.output_columns):
202
411
  # Every output row equals some row of the left input.
203
412
  return (left,)
204
413
  case ir.SetOperation() | ir.NamedRelation() | ir.OpaqueRelation():