sqlassert 0.3.3__py3-none-any.whl → 0.4.1__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 (65) hide show
  1. sqlassert/__init__.py +1 -2
  2. sqlassert/check.py +88 -13
  3. sqlassert/diagnostics.py +17 -6
  4. sqlassert/dialects.py +437 -7
  5. sqlassert/discovery/bigquery.py +3 -1
  6. sqlassert/discovery/databricks.py +25 -2
  7. sqlassert/discovery/duckdb.py +49 -7
  8. sqlassert/discovery/fetcher.py +130 -21
  9. sqlassert/discovery/information_schema.py +30 -2
  10. sqlassert/discovery/mysql.py +22 -1
  11. sqlassert/discovery/postgres.py +22 -5
  12. sqlassert/discovery/redshift.py +3 -2
  13. sqlassert/discovery/snowflake.py +3 -0
  14. sqlassert/discovery/trino.py +2 -2
  15. sqlassert/hazards.py +248 -87
  16. sqlassert/ir/__init__.py +4 -1
  17. sqlassert/ir/convert/__init__.py +13 -0
  18. sqlassert/ir/convert/aggregation.py +439 -0
  19. sqlassert/ir/convert/builtins.py +140 -0
  20. sqlassert/ir/convert/expressions.py +572 -0
  21. sqlassert/ir/convert/joins.py +264 -0
  22. sqlassert/ir/convert/markers.py +249 -0
  23. sqlassert/ir/convert/parser.py +253 -0
  24. sqlassert/ir/convert/queries.py +259 -0
  25. sqlassert/ir/convert/schema.py +606 -0
  26. sqlassert/ir/convert/scopes.py +205 -0
  27. sqlassert/ir/convert/selects.py +337 -0
  28. sqlassert/ir/convert/shared.py +429 -0
  29. sqlassert/ir/convert/sources.py +432 -0
  30. sqlassert/ir/convert/subqueries.py +364 -0
  31. sqlassert/ir/convert/value_types.py +223 -0
  32. sqlassert/ir/convert/windows.py +275 -0
  33. sqlassert/ir/model.py +125 -47
  34. sqlassert/ir/names.py +63 -0
  35. sqlassert/properties.py +12 -1
  36. sqlassert/provenance.py +5 -1
  37. sqlassert/python_engine.py +104 -44
  38. sqlassert/reporting.py +33 -32
  39. sqlassert/rewrites.py +111 -61
  40. sqlassert/rules/STYLEGUIDE.md +3 -2
  41. sqlassert/rules/causes/__init__.py +41 -0
  42. sqlassert/rules/causes/coverage.py +113 -0
  43. sqlassert/rules/causes/domain.py +123 -0
  44. sqlassert/rules/causes/joins.py +73 -0
  45. sqlassert/rules/causes/nulls.py +154 -0
  46. sqlassert/rules/causes/unique.py +523 -0
  47. sqlassert/rules/domain.py +8 -7
  48. sqlassert/rules/equality.py +6 -147
  49. sqlassert/rules/exactly_one.py +2 -1
  50. sqlassert/rules/foreign_key.py +8 -9
  51. sqlassert/rules/join_cardinality.py +282 -41
  52. sqlassert/rules/nullability.py +5 -5
  53. sqlassert/rules/uniqueness.py +171 -47
  54. sqlassert/rules/value_typing.py +337 -0
  55. sqlassert/sql_parse.py +28 -1
  56. sqlassert/suggest.py +11 -15
  57. sqlassert-0.4.1.dist-info/METADATA +235 -0
  58. sqlassert-0.4.1.dist-info/RECORD +69 -0
  59. sqlassert/ir/convert.py +0 -3509
  60. sqlassert-0.3.3.dist-info/METADATA +0 -807
  61. sqlassert-0.3.3.dist-info/RECORD +0 -46
  62. {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/WHEEL +0 -0
  63. {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/entry_points.txt +0 -0
  64. {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/licenses/LICENSE +0 -0
  65. {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/top_level.txt +0 -0
@@ -24,10 +24,10 @@ from dataclasses import dataclass
24
24
  from itertools import combinations
25
25
  from collections.abc import Callable, Iterable, Mapping
26
26
  from typing import assert_never
27
- import re
28
27
 
29
28
  from sqlassert import ir
30
29
  from sqlassert.python_engine import Result, Stratum, analysis, current_arena
30
+ from sqlassert.rules.value_typing import _column_typing, exact_comparison
31
31
 
32
32
  type _Group = tuple[ir.OutputColumn, ...]
33
33
 
@@ -151,9 +151,9 @@ def _predicate_equalities(conjuncts: tuple[ir.ScalarExpr, ...]) -> Equalities:
151
151
  case ir.Or():
152
152
  pairs.update(dict.fromkeys(_in_every_branch(conjunct, _predicate_equalities), conjunct))
153
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):
154
+ ir.Equality(left=ir.ColumnRef(column=first) as left, right=ir.ColumnRef(column=second) as right)
155
+ | ir.NullSafeEquality(left=ir.ColumnRef(column=first) as left, right=ir.ColumnRef(column=second) as right)
156
+ ) if exact_comparison(left, right).value:
157
157
  pairs[first, second] = pairs[second, first] = conjunct
158
158
  return pairs
159
159
 
@@ -194,7 +194,7 @@ def _pinned_values(conjuncts: tuple[ir.ScalarExpr, ...]) -> dict[tuple[ir.Output
194
194
  case ir.Equality(left=left, right=right) | ir.NullSafeEquality(left=left, right=right):
195
195
  for column, literal in ((left, right), (right, left)):
196
196
  if isinstance(column, ir.ColumnRef) and isinstance(literal, ir.Constant) and literal.value is not None:
197
- if _pins(column.column, literal):
197
+ if exact_comparison(column, literal).value:
198
198
  pinned[column.column, literal.value] = conjunct
199
199
  case ir.IsNull(operand=ir.ColumnRef(column=column)):
200
200
  pinned[column, None] = conjunct
@@ -240,107 +240,6 @@ def _constant_value(column: ir.OutputColumn) -> Result[tuple[ir.LiteralValue | N
240
240
  assert_never(relation)
241
241
 
242
242
 
243
- def _same_type(first: ir.OutputColumn, second: ir.OutputColumn) -> bool:
244
- """Equalities are value identities only for known, matching comparison types."""
245
- first_type = _comparison_type(first).value
246
- return first is second or first_type is not None and first_type == _comparison_type(second).value
247
-
248
-
249
- @analysis(Stratum.COMPARISON)
250
- def _comparison_type(column: ir.OutputColumn) -> Result[str | None]:
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])
257
- match column.scalar_expr:
258
- case ir.ColumnRef(column=source) | ir.AnyAggregate(input=ir.ColumnRef(column=source)) if not isinstance(relation, ir.SetOperation):
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,))
262
- case _:
263
- return Result(column.comparison_type, "Declared comparison type", (column,))
264
-
265
-
266
- @analysis(Stratum.COMPARISON)
267
- def _identity_comparison(column: ir.OutputColumn) -> Result[bool]:
268
- """Whether equal values of `column` are identical, from its declared type."""
269
- relation = column.get_relation(current_arena().program)
270
- if (both := _both_inputs(column, relation, _identity_comparison)) is not None:
271
- return both
272
- match column.scalar_expr:
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.
275
- return _identity_comparison(source)
276
- case _:
277
- return Result(column.identity_comparison, "Declared type compares by identity", (column,))
278
-
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
-
294
- def _pins(column: ir.OutputColumn, value: ir.ScalarExpr) -> bool:
295
- """Whether equality can pin the column without a lossy coercion."""
296
- if _binary_text(column).value:
297
- match value:
298
- case ir.Constant(value=ir.LiteralValue(type="string")):
299
- return True
300
- case ir.ColumnRef(column=other):
301
- return _binary_text(other).value
302
- case _:
303
- return False
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
243
  def _same_set_types(operation: ir.SetOperation, columns: Iterable[ir.OutputColumn]) -> bool:
345
244
  """Whether set output columns retain the same types as their inputs."""
346
245
  return all(_typed_arms(operation, column) is not None for column in columns)
@@ -349,47 +248,7 @@ def _same_set_types(operation: ir.SetOperation, columns: Iterable[ir.OutputColum
349
248
  def _typed_arms(operation: ir.SetOperation, column: ir.OutputColumn) -> tuple[ir.OutputColumn, ir.OutputColumn] | None:
350
249
  """`column`'s input columns, when it keeps their type: its values are theirs."""
351
250
  arms = operation.arms(column)
352
- return arms if arms is not None and _same_type(*arms) else None
353
-
354
-
355
- def _exact_arithmetic(column: ir.OutputColumn) -> bool:
356
- """Whether `column` is an integer or decimal it computes: a `count`, or
357
- exact arithmetic over an integer or decimal (`id + 7`)."""
358
- program = current_arena().program
359
- while isinstance(column.scalar_expr, ir.ColumnRef) and not isinstance(column.get_relation(program), ir.SetOperation):
360
- column = column.scalar_expr.column
361
- if isinstance(column.scalar_expr, ir.Count):
362
- return True
363
- if not isinstance(column.scalar_expr, ir.Call):
364
- return False
365
- source = ir.injective_input(column.scalar_expr)
366
- return source is not None and exact_numeric(source).value
367
-
368
-
369
- @analysis(Stratum.COMPARISON)
370
- def _binary_text(column: ir.OutputColumn) -> Result[bool]:
371
- """Whether `column` is text compared by identity, from its declared type."""
372
- relation = column.get_relation(current_arena().program)
373
- if (both := _both_inputs(column, relation, _binary_text)) is not None:
374
- return both
375
- match column.scalar_expr:
376
- case ir.ColumnRef(column=source) if not isinstance(relation, ir.SetOperation):
377
- return _binary_text(source)
378
- case _:
379
- return Result(column.binary_text, "Declared as text compared by identity", (column,))
380
-
381
-
382
- @analysis(Stratum.COMPARISON)
383
- def exact_numeric(column: ir.OutputColumn) -> Result[bool]:
384
- """Whether `column` is an integer or decimal, from its declared type."""
385
- relation = column.get_relation(current_arena().program)
386
- if (both := _both_inputs(column, relation, exact_numeric)) is not None:
387
- return both
388
- match column.scalar_expr:
389
- case ir.ColumnRef(column=source) | ir.AnyAggregate(input=ir.ColumnRef(column=source)) if not isinstance(relation, ir.SetOperation):
390
- return exact_numeric(source)
391
- case _:
392
- return Result(column.exact_numeric, "Declared an integer or decimal", (column,))
251
+ return arms if arms is not None and _column_typing(column).value is not None else None
393
252
 
394
253
 
395
254
  def _inputs(relation: ir.RelationExpr) -> tuple[ir.RelationExpr, ...]:
@@ -21,13 +21,14 @@ coverage onto a narrowed right input must hold on its own.
21
21
  from typing import assert_never
22
22
 
23
23
  from sqlassert import ir
24
+ from sqlassert.properties import ExactlyOneJoin
24
25
  from sqlassert.python_engine import Result, Stratum, analysis, all_of, unknown
25
26
  from sqlassert.rules.foreign_key import referential_coverage
26
27
  from sqlassert.rules.nullability import non_null_columns
27
28
  from sqlassert.rules.join_cardinality import many_to_one_join
28
29
 
29
30
 
30
- @analysis(Stratum.UNIQUE_JOIN)
31
+ @analysis(Stratum.UNIQUE_JOIN, evaluates=ExactlyOneJoin)
31
32
  def exactly_one_join(join: ir.Join) -> Result[bool]:
32
33
  # As for a Many To One Join, the left row's matches decide it, except that an
33
34
  # anti join drops every matched row.
@@ -23,15 +23,16 @@ from typing import assert_never
23
23
 
24
24
  from sqlassert.diagnostics import quoted, quoted_all
25
25
  from sqlassert import ir
26
- from sqlassert.properties import ReferentialCoverage
26
+ from sqlassert.properties import ForeignKey, ReferentialCoverage
27
27
  from sqlassert.python_engine import Result, Stratum, analysis, any_of, current_arena, unknown
28
28
  from sqlassert.rules.equality import _equal_columns
29
29
  from sqlassert.rules.uniqueness import unique_set
30
+ from sqlassert.rules.value_typing import exact_comparison
30
31
 
31
32
  type _Columns = tuple[ir.OutputColumn, ...]
32
33
 
33
34
 
34
- @analysis(Stratum.FOREIGN_KEY)
35
+ @analysis(Stratum.FOREIGN_KEY, evaluates=ForeignKey)
35
36
  def foreign_key(columns: _Columns, referenced_columns: _Columns) -> Result[bool]:
36
37
  shape = _pairing(columns, referenced_columns)
37
38
  if not shape.value:
@@ -39,7 +40,7 @@ def foreign_key(columns: _Columns, referenced_columns: _Columns) -> Result[bool]
39
40
  return referential_coverage(columns, referenced_columns) & _referenced_unique_set(referenced_columns)
40
41
 
41
42
 
42
- @analysis(Stratum.FOREIGN_KEY)
43
+ @analysis(Stratum.FOREIGN_KEY, evaluates=ReferentialCoverage)
43
44
  def referential_coverage(columns: _Columns, referenced_columns: _Columns) -> Result[bool]:
44
45
  shape = _pairing(columns, referenced_columns)
45
46
  if not shape.value:
@@ -49,7 +50,7 @@ def referential_coverage(columns: _Columns, referenced_columns: _Columns) -> Res
49
50
  # Pairs, not lists, are the relationship: (a, b) → (x, y) is (b, a) → (y, x).
50
51
  pairs = set(zip(columns, target))
51
52
  known = [
52
- any_of(current_arena().accepted[_key(coverage)]) for coverage in _known()
53
+ any_of(current_arena().accepted_evidence(coverage)) for coverage in _known()
53
54
  if set(zip(coverage.columns, coverage.referenced_columns)) == pairs
54
55
  ]
55
56
  if known:
@@ -103,7 +104,8 @@ def _referencing_side(
103
104
  def _semi_join(join: ir.Join, columns: _Columns, referenced_columns: _Columns) -> list[Result[bool]]:
104
105
  """A semi join keeps a row only when some right row satisfies ON, so
105
106
  columns ON equates with right columns take those columns' values: coverage
106
- of the right columns, as one tuple, covers them (`x IN (SELECT id ...)`)."""
107
+ of the right columns, as one tuple, covers them (`x IN (SELECT id ...)`),
108
+ when the equality compares without a lossy coercion (`exact_comparison`)."""
107
109
  partners: list[list[tuple[ir.OutputColumn, ir.Equality]]] = []
108
110
  for column in columns:
109
111
  match column.scalar_expr:
@@ -117,6 +119,7 @@ def _semi_join(join: ir.Join, columns: _Columns, referenced_columns: _Columns) -
117
119
  for own, other in ((conjunct.left, conjunct.right), (conjunct.right, conjunct.left))
118
120
  if isinstance(own, ir.ColumnRef) and own.column is upstream
119
121
  and isinstance(other, ir.ColumnRef) and other.column in join.right.output_columns
122
+ and exact_comparison(own, other).value # A lossy `=` leaves the left value out of the right column's.
120
123
  ]
121
124
  if not found:
122
125
  return []
@@ -302,10 +305,6 @@ def _known() -> list[ReferentialCoverage]:
302
305
  return [coverage for coverage in current_arena().knowledge if isinstance(coverage, ReferentialCoverage)]
303
306
 
304
307
 
305
- def _key(coverage: ReferentialCoverage) -> tuple:
306
- return ("referential_coverage", (("columns", coverage.columns), ("referenced_columns", coverage.referenced_columns)))
307
-
308
-
309
308
  def _names(columns: _Columns) -> str:
310
309
  return quoted_all(column.name for column in columns)
311
310
 
@@ -2,48 +2,59 @@
2
2
 
3
3
  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
- column an ON equality binds to the first row's column or to a constant, all
6
- non-null. IS NOT DISTINCT FROM binds them too, but matches NULL to NULL, so
7
- those columns are non-null only where proved, or where the other side is a
8
- literal or a non-null column, which no NULL equals. When those columns reach the
5
+ column an ON equality binds, all non-null: to a constant or to a pure function
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
10
+ nothing (`fixes`). IS NOT DISTINCT FROM binds them too, but matches NULL to
11
+ NULL, so those columns are non-null only where proved, or where the other side
12
+ is a literal or an expression of non-null columns that is never NULL for them
13
+ (`ir.total`), which no NULL equals. When those columns reach the
9
14
  matched input's Row Identity, a row matches at most one row and is never
10
15
  repeated. A cross join is an ON with no
11
16
  conjuncts: the other input must have at most one row. A semi or anti join
12
17
  keeps or drops left rows whole and outputs no right row; its left rows are
13
18
  never repeated (`many_to_one_join`), and no cardinality marker applies to it.
19
+ A table function or UNNEST that reads the left input is evaluated once per
20
+ left row, so none of its rows is repeated (`Join.lateral`, `one_to_many_join`).
14
21
  """
15
22
 
23
+ from collections.abc import Iterator
16
24
  from dataclasses import dataclass, field
17
- from typing import Literal, assert_never
25
+ from typing import Literal
18
26
 
19
27
  from sqlassert import ir
20
- from sqlassert.python_engine import Result, Stratum, all_of, any_of, analysis
28
+ from sqlassert.properties import ManyToOneJoin, OneToManyJoin, OneToOneJoin, UniqueJoin
29
+ from sqlassert.python_engine import Result, Stratum, all_of, any_of, analysis, cache, current_arena
21
30
  from sqlassert.rules.column_set import Attribute, ColumnSet
22
- from sqlassert.rules.equality import _pins
23
31
  from sqlassert.rules.nullability import non_null_column
24
- from sqlassert.rules.uniqueness import _closure, _reaches_row_identity
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
25
34
 
26
35
  type Side = Literal["left", "right"]
27
36
 
28
37
 
29
- @analysis(Stratum.UNIQUE_JOIN)
38
+ @analysis(Stratum.UNIQUE_JOIN, evaluates=ManyToOneJoin)
30
39
  def many_to_one_join(join: ir.Join) -> Result[bool]:
31
40
  if join.scalar_subquery:
32
41
  return Result(True, "A scalar subquery returns at most one row for each outer row, or the query fails", (join,))
33
42
  return _at_most_one_match(join, "right")
34
43
 
35
44
 
36
- @analysis(Stratum.UNIQUE_JOIN)
45
+ @analysis(Stratum.UNIQUE_JOIN, evaluates=OneToManyJoin)
37
46
  def one_to_many_join(join: ir.Join) -> Result[bool]:
47
+ if join.lateral:
48
+ return Result(True, "A table function reading the left input is evaluated once per left row, so each of its rows has one left row", (join,))
38
49
  return _at_most_one_match(join, "left")
39
50
 
40
51
 
41
- @analysis(Stratum.UNIQUE_JOIN)
52
+ @analysis(Stratum.UNIQUE_JOIN, evaluates=OneToOneJoin)
42
53
  def one_to_one_join(join: ir.Join) -> Result[bool]:
43
54
  return all_of((many_to_one_join(join), one_to_many_join(join)))
44
55
 
45
56
 
46
- @analysis(Stratum.UNIQUE_JOIN)
57
+ @analysis(Stratum.UNIQUE_JOIN, evaluates=UniqueJoin)
47
58
  def unique_join(join: ir.Join) -> Result[bool]:
48
59
  # Not many to many: the proved alternative names the input that is unique.
49
60
  return any_of((many_to_one_join(join), one_to_many_join(join)))
@@ -66,51 +77,281 @@ class BoundColumns(ColumnSet):
66
77
  DISTINCT FROM, which also matches NULL to NULL."""
67
78
 
68
79
  definite: set[Attribute] = field(default_factory=set)
80
+ # The ON equalities that bound a column.
81
+ equalities: set[ir.ScalarExpr] = field(default_factory=set)
69
82
 
70
83
 
71
84
  @analysis(Stratum.UNIQUE_JOIN)
72
85
  def _bound_columns(join: ir.Join, matched: Side) -> Result[BoundColumns]:
73
86
  """The columns of `matched` an ON equality (or IS NOT DISTINCT FROM)
74
- binds to the other input's column or to a constant."""
87
+ binds for each row of the other input.
88
+
89
+ One operand is a constant or a pure function of that row's columns: a
90
+ column, `-b.x`, `b.x + 1`, `CAST(b.ts AS DATE)`; for one row it is one
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`).
95
+ """
75
96
  relation, other = (join.right, join.left) if matched == "right" else (join.left, join.right)
76
97
  members = {}
77
98
  definite = set()
99
+ equalities = set()
78
100
  for equality in join.conjuncts:
79
101
  if not isinstance(equality, ir.Equality | ir.NullSafeEquality):
80
102
  continue
81
103
  for bound, value in ((equality.left, equality.right), (equality.right, equality.left)):
82
104
  if bound is value:
83
105
  continue
84
- bound, value = bound.closed, value.closed
85
- match bound:
86
- case ir.ColumnRef(column=column):
87
- if column not in relation.output_columns:
88
- continue
89
- case ir.Constant() | ir.NullLiteral() | ir.Coalesce() | ir.SimpleCase() | ir.OpaqueExpression() | ir.OpaquePureFunction() | ir.Call() | ir.Count() | ir.AnyAggregate() | ir.Accumulation() | ir.Elements() | ir.Equality() | ir.NullSafeEquality() | ir.InList() | ir.IsNull() | ir.IsNotNull() | ir.And() | ir.Or():
90
- continue
91
- case _:
92
- assert_never(bound)
93
-
94
- # An equality that casts pins nothing: '01' and '1' both equal 1.
95
- match value:
96
- case ir.Constant():
97
- if not _pins(column, value):
98
- continue
99
- case ir.ColumnRef(column=other_column):
100
- if other_column not in other.output_columns or not _pins(column, value):
101
- continue
102
- case ir.NullLiteral() | ir.Coalesce() | ir.SimpleCase() | ir.OpaqueExpression() | ir.OpaquePureFunction() | ir.Call() | ir.Count() | ir.AnyAggregate() | ir.Accumulation() | ir.Elements() | ir.Equality() | ir.NullSafeEquality() | ir.InList() | ir.IsNull() | ir.IsNotNull() | ir.And() | ir.Or():
103
- continue
104
- case _:
105
- assert_never(value)
106
+ column = _fixed_column(bound, relation)
107
+ inputs = ir.determinants(value)
108
+ if column is None or inputs is None or not all(read in other.output_columns for read in inputs):
109
+ continue
110
+ # A lossy cast pins nothing: '01' and '1' both equal 1.
111
+ if not fixes(bound, value).value:
112
+ continue
106
113
 
107
114
  evidence = Result(True, "Equality fixes the matched column for each row of the other input", (equality, column, value))
108
115
  members[column] = members[column] | evidence if column in members else evidence
109
- # IS NOT DISTINCT FROM a literal or a non-null column is `=`.
110
- if isinstance(equality, ir.Equality) or isinstance(value, ir.Constant):
111
- definite.add(column)
112
- elif non_null_column(value.column).value:
116
+ equalities.add(equality)
117
+ # IS NOT DISTINCT FROM a value that is never NULL is `=`.
118
+ if isinstance(equality, ir.Equality) or (ir.total(value) and all(non_null_column(read).value for read in inputs)):
113
119
  definite.add(column)
114
- members[column] = members[column] & non_null_column(value.column)
120
+ if not isinstance(equality, ir.Equality):
121
+ members[column] = all_of((members[column], *(non_null_column(read) for read in inputs)))
122
+
123
+ return Result(BoundColumns(relation, set(members), definite, equalities), "Bound columns", members=members)
124
+
125
+
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
+ # Why a join has no proved Join Cardinality --------------------------------
137
+
138
+ type UnprovedReason = Literal["unsupported", "unconstrained", "unresolved-key", "untyped-key", "expression-key", "no-unique-set"]
139
+ type TypeLoss = Literal["values", "computed", "opaque-relation", "set-operation", "table", "type-mismatch"]
140
+ type NoUniqueSet = Literal["cascade", "partial-key", "undeclared-key"]
141
+ type _Operand = Literal["left", "right", "constant", "opaque", "both"]
142
+
143
+
144
+ @dataclass(frozen=True)
145
+ class UnprovedJoin:
146
+ """Why neither `many_to_one_join` nor `one_to_many_join` is proved for a
147
+ join: the first reason that applies, in the order of `UnprovedReason`.
148
+
149
+ - `unsupported`: an input is a source sqlassert does not model (LATERAL,
150
+ or a table function or UNNEST whose columns the dialect does not fix),
151
+ or the join is not reachable from the program: it sits in a SELECT that
152
+ lowered opaque.
153
+ - `unconstrained`: no ON equality relates one input to the other or to a
154
+ constant (a cross join, a range join). No Unique Set can make it a
155
+ Unique Join; whether rows repeat depends on the data, not on a key.
156
+ - `unresolved-key`: an operand of such an equality lowered opaque: a
157
+ column that does not resolve in its input, or an expression sqlassert
158
+ does not model.
159
+ - `untyped-key`: a column = column equality binds nothing, since the two
160
+ columns do not compare without a lossy coercion; `detail` names where
161
+ the type is lost (`TypeLoss`).
162
+ - `expression-key`: every such equality compares an expression, and none
163
+ binds a column (`_bound_columns`): the expression is not deterministic,
164
+ 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.
167
+ - `no-unique-set`: the equalities bind columns that reach the Row
168
+ Identity of neither input. `detail` says who can act, the first that
169
+ applies (`NoUniqueSet`):
170
+ `cascade`: something below an input is itself unproved or unsupported
171
+ (an upstream join with no proved Join Cardinality, through which no
172
+ Unique Set passes, or an unsupported construct), so fixing that may fix
173
+ this join; `construct` names the unsupported one, if any.
174
+ `partial-key`: the equalities bind a strict subset of a known Unique
175
+ Set of an input and every equality written binds a column; the rest of
176
+ ON is a range or inequality, so the join is as constrained as written.
177
+ `undeclared-key`: the bound side has no known Unique Set covering the
178
+ bound columns, a key the project could declare.
179
+
180
+ `construct` names the construct sqlassert does not support, when one
181
+ is behind the reason: the nearest one at or under the input, or the
182
+ relation, the reason points at; for a join in a SELECT that lowered
183
+ opaque, the one that made it so (`IrParser._name_orphan_joins`).
184
+
185
+ A diagnostic about a missing proof: it never changes what is proved."""
186
+
187
+ reason: UnprovedReason
188
+ detail: TypeLoss | NoUniqueSet | None = None
189
+ construct: str | None = None
190
+ # For `untyped-key`, the column where the type is lost.
191
+ untyped: ir.OutputColumn | None = field(default=None, compare=False)
192
+
193
+
194
+ def unproved_join(join: ir.Join, matched: Side | None = None) -> UnprovedJoin | None:
195
+ """Why `join` has no proved Join Cardinality; None when it has one or is
196
+ a semi or anti join, which has none. With `matched`, why no row of the
197
+ other input is proved to match at most one row of that input (`right`:
198
+ why it is not many to one): the reasons that read an input's keys look
199
+ at that input alone. Runs inside an analysis session."""
200
+ if join.kind in {"semi", "anti"}:
201
+ return None
202
+ if join not in _reachable():
203
+ return UnprovedJoin("unsupported", construct=_unsupported_under(join))
204
+ directions: tuple[Side, ...] = ("right", "left") if matched is None else (matched,)
205
+ if any((many_to_one_join(join) if side == "right" else one_to_many_join(join)).value for side in directions):
206
+ return None
207
+ for relation in (join.left, join.right):
208
+ source = relation
209
+ while isinstance(source, ir.Alias):
210
+ source = source.source
211
+ if isinstance(source, ir.OpaqueRelation) and (construct := _unsupported_under(source)) is not None:
212
+ return UnprovedJoin("unsupported", construct=construct)
213
+ pairs = []
214
+ related = []
215
+ for equality in join.conjuncts:
216
+ if not isinstance(equality, ir.Equality | ir.NullSafeEquality):
217
+ continue
218
+ sides = (_operand(join, equality.left), _operand(join, equality.right))
219
+ if "both" not in sides and (sides[0] != sides[1] or sides[0] == "opaque"):
220
+ pairs.append((equality.left.closed, equality.right.closed, sides))
221
+ related.append(equality)
222
+ if not pairs:
223
+ return UnprovedJoin("unconstrained")
224
+ if any("opaque" in sides for _, _, sides in pairs):
225
+ return UnprovedJoin("unresolved-key", construct=_unsupported_under(join.left) or _unsupported_under(join.right))
226
+ for first, second, _ in pairs:
227
+ if isinstance(first, ir.ColumnRef) and isinstance(second, ir.ColumnRef) and not fixes(first, second).value:
228
+ for column in (first.column, second.column):
229
+ if (loss := _type_loss(column)) is not None:
230
+ construct = _unsupported_under(loss[1]) if loss[0] == "opaque-relation" else None
231
+ return UnprovedJoin("untyped-key", loss[0], construct, loss[2])
232
+ return UnprovedJoin("untyped-key", "type-mismatch")
233
+ if all(not isinstance(first, ir.ColumnRef | ir.Constant) or not isinstance(second, ir.ColumnRef | ir.Constant) for first, second, _ in pairs) and not any(
234
+ _bound_columns(join, side).value.columns for side in directions
235
+ ):
236
+ return UnprovedJoin("expression-key")
237
+ return _no_unique_set(join, related, directions)
238
+
239
+
240
+ def _no_unique_set(join: ir.Join, related: list[ir.ScalarExpr], sides: tuple[Side, ...]) -> UnprovedJoin:
241
+ """Who can act on a join whose bound columns reach no Row Identity of
242
+ the `sides` asked about, from the IR and analyses it already ran: one
243
+ walk of each such input's tree, and the closures `_at_most_one_match`
244
+ took (`related`: its ON equalities that relate the inputs or an input to
245
+ a constant)."""
246
+ unproved, constructs = _cascade(join, tuple(sorted(sides)))
247
+ if unproved or any(constructs):
248
+ return UnprovedJoin("no-unique-set", "cascade", next(filter(None, constructs), None))
249
+ for matched in sides:
250
+ cols = _bound_columns(join, matched)
251
+ if not all(equality in cols.value.equalities for equality in related):
252
+ continue # An equality binds nothing here: not as constrained as written.
253
+ relation = join.right if matched == "right" else join.left
254
+ closure = _closure(relation, frozenset(cols.value.columns), frozenset(cols.value.definite))
255
+ if any(gap.reached for gap in _key_gaps(closure)):
256
+ return UnprovedJoin("no-unique-set", "partial-key")
257
+ return UnprovedJoin("no-unique-set", "undeclared-key")
258
+
259
+
260
+ def _cascade(join: ir.Join, sides: tuple[Side, ...] = ("left", "right")) -> tuple[bool, tuple[str | None, ...]]:
261
+ """Whether a join below an input of `join` has no proved Join Cardinality
262
+ (a semi or anti join has none to prove), and the unsupported construct
263
+ nearest each input, in one walk of the two trees."""
264
+ unsupported = {id(node): construct for node, construct in current_arena().program.unsupported}
265
+ unproved = False
266
+ constructs = []
267
+ for relation in (join.left if side == "left" else join.right for side in sides):
268
+ nearest = None
269
+ for node in _tree(relation):
270
+ nearest = nearest or unsupported.get(id(node))
271
+ if isinstance(node, ir.Join) and node.kind not in {"semi", "anti"}:
272
+ unproved |= not (many_to_one_join(node).value or one_to_many_join(node).value)
273
+ constructs.append(nearest)
274
+ return unproved, tuple(constructs)
275
+
276
+
277
+ def _tree(relation: ir.RelationExpr) -> Iterator[ir.RelationExpr]:
278
+ """`relation` and every relation it reads, nearest first, each once."""
279
+ pending, seen = [relation], set()
280
+ while pending:
281
+ node = pending.pop(0)
282
+ if id(node) in seen:
283
+ continue
284
+ seen.add(id(node))
285
+ yield node
286
+ pending.extend(child for child in ir.children(node) if isinstance(child, ir.RelationExpr))
287
+
288
+
289
+ @cache
290
+ def _reachable() -> frozenset[ir.Node]:
291
+ return frozenset(current_arena().program.nodes())
292
+
293
+
294
+ def _unsupported_under(relation: ir.RelationExpr) -> str | None:
295
+ """The construct sqlassert does not support nearest to `relation`: its
296
+ own, else the first found reading down through its inputs."""
297
+ unsupported = {id(node): construct for node, construct in current_arena().program.unsupported}
298
+ return next((unsupported[id(node)] for node in _tree(relation) if id(node) in unsupported), None) if unsupported else None
299
+
300
+
301
+ def _operand(join: ir.Join, expression: ir.ScalarExpr) -> _Operand:
302
+ """Which input an equality operand reads: `opaque` when nothing is known
303
+ of it, `constant` when it reads neither (an outer column is fixed for
304
+ the join too)."""
305
+ sides = set()
306
+ pending = [expression]
307
+ while pending:
308
+ match node := pending.pop():
309
+ case ir.OpaqueExpression():
310
+ return "opaque"
311
+ case ir.ColumnRef(column=column):
312
+ if column in join.left.output_columns:
313
+ sides.add("left")
314
+ elif column in join.right.output_columns:
315
+ sides.add("right")
316
+ case _:
317
+ pending.extend(child for child in ir.children(node) if isinstance(child, ir.ScalarExpr))
318
+ match sorted(sides):
319
+ case []:
320
+ return "constant"
321
+ case ["left"]:
322
+ return "left"
323
+ case ["right"]:
324
+ return "right"
325
+ case _:
326
+ return "both"
327
+
115
328
 
116
- return Result(BoundColumns(relation, set(members), definite), "Bound columns", members=members)
329
+ def _type_loss(column: ir.OutputColumn) -> tuple[TypeLoss, ir.RelationExpr, ir.OutputColumn] | None:
330
+ """Where `column` loses the type equality needs to bind it, following
331
+ plain column references (and set operation arms, only the base case's for a
332
+ recursive CTE, and a recursive reference's base case) down to the first column that is not one: `table` for a table column with no declared
333
+ type (no CREATE, or none in the catalog), else the kind of relation or
334
+ expression that computes it without a type compared by identity. None
335
+ when that column keeps its type. With the relation that column is of."""
336
+ relation = column.get_relation(current_arena().program)
337
+ if isinstance(relation, ir.SetOperation):
338
+ arms = relation.arms(column)
339
+ if arms is None:
340
+ return "set-operation", relation, column
341
+ return _type_loss(arms[0]) if relation.recursive else _type_loss(arms[0]) or _type_loss(arms[1])
342
+ if isinstance(relation, ir.RecursiveRelation) and relation.typed_by and (base := relation.typed_by[relation.output_columns.index(column)]):
343
+ return _type_loss(base)
344
+ match column.scalar_expr:
345
+ case ir.ColumnRef(column=source) | ir.AnyAggregate(input=ir.ColumnRef(column=source)):
346
+ return _type_loss(source)
347
+ typed = _comparison_type(column).value is not None
348
+ if isinstance(relation, ir.NamedRelation) and relation.role is ir.RelationRole.TABLE:
349
+ # A declared type that does not compare by identity is the type, not a loss.
350
+ return None if typed else ("table", relation, column)
351
+ if typed and _identity_comparison(column).value:
352
+ return None
353
+ if isinstance(relation, ir.ValuesList):
354
+ return "values", relation, column
355
+ if isinstance(relation, ir.OpaqueRelation) or isinstance(column.scalar_expr, ir.OpaqueExpression):
356
+ return "opaque-relation", relation, column
357
+ return "computed", relation, column