sqlassert 0.3.1__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.
- sqlassert/__init__.py +1 -2
- sqlassert/__main__.py +2 -131
- sqlassert/check.py +98 -16
- sqlassert/diagnostics.py +31 -7
- sqlassert/dialects.py +504 -27
- sqlassert/discovery/bigquery.py +3 -1
- sqlassert/discovery/databricks.py +25 -2
- sqlassert/discovery/duckdb.py +61 -23
- sqlassert/discovery/fetcher.py +170 -45
- sqlassert/discovery/information_schema.py +34 -5
- sqlassert/discovery/mysql.py +22 -1
- sqlassert/discovery/postgres.py +28 -12
- sqlassert/discovery/redshift.py +3 -2
- sqlassert/discovery/snowflake.py +3 -0
- sqlassert/discovery/trino.py +2 -2
- sqlassert/edits.py +240 -0
- sqlassert/hazards.py +735 -0
- sqlassert/ir/__init__.py +6 -1
- sqlassert/ir/convert/__init__.py +13 -0
- sqlassert/ir/convert/aggregation.py +439 -0
- sqlassert/ir/convert/builtins.py +140 -0
- sqlassert/ir/convert/expressions.py +572 -0
- sqlassert/ir/convert/joins.py +264 -0
- sqlassert/ir/convert/markers.py +249 -0
- sqlassert/ir/convert/parser.py +253 -0
- sqlassert/ir/convert/queries.py +259 -0
- sqlassert/ir/convert/schema.py +606 -0
- sqlassert/ir/convert/scopes.py +205 -0
- sqlassert/ir/convert/selects.py +337 -0
- sqlassert/ir/convert/shared.py +429 -0
- sqlassert/ir/convert/sources.py +432 -0
- sqlassert/ir/convert/subqueries.py +364 -0
- sqlassert/ir/convert/value_types.py +223 -0
- sqlassert/ir/convert/windows.py +275 -0
- sqlassert/ir/model.py +247 -66
- sqlassert/ir/names.py +63 -0
- sqlassert/main.py +3 -9
- sqlassert/properties.py +12 -1
- sqlassert/provenance.py +5 -1
- sqlassert/python_engine.py +167 -50
- sqlassert/reporting.py +36 -32
- sqlassert/rewrites.py +1591 -0
- sqlassert/rules/STYLEGUIDE.md +3 -2
- sqlassert/rules/causes/__init__.py +41 -0
- sqlassert/rules/causes/coverage.py +113 -0
- sqlassert/rules/causes/domain.py +123 -0
- sqlassert/rules/causes/joins.py +73 -0
- sqlassert/rules/causes/nulls.py +154 -0
- sqlassert/rules/causes/unique.py +523 -0
- sqlassert/rules/domain.py +123 -26
- sqlassert/rules/equality.py +153 -85
- sqlassert/rules/exactly_one.py +42 -2
- sqlassert/rules/foreign_key.py +15 -13
- sqlassert/rules/join_cardinality.py +302 -39
- sqlassert/rules/nullability.py +244 -35
- sqlassert/rules/uniqueness.py +513 -86
- sqlassert/rules/value_typing.py +337 -0
- sqlassert/sql_parse.py +224 -90
- sqlassert/suggest.py +132 -57
- sqlassert-0.4.1.dist-info/METADATA +235 -0
- sqlassert-0.4.1.dist-info/RECORD +69 -0
- sqlassert-0.4.1.dist-info/entry_points.txt +2 -0
- sqlassert-0.4.1.dist-info/top_level.txt +2 -0
- sqlassert_cli.py +130 -0
- sqlassert/improvements.py +0 -528
- sqlassert/ir/convert.py +0 -2377
- sqlassert/smells.py +0 -306
- sqlassert-0.3.1.dist-info/METADATA +0 -725
- sqlassert-0.3.1.dist-info/RECORD +0 -44
- sqlassert-0.3.1.dist-info/entry_points.txt +0 -2
- sqlassert-0.3.1.dist-info/top_level.txt +0 -1
- {sqlassert-0.3.1.dist-info → sqlassert-0.4.1.dist-info}/WHEEL +0 -0
- {sqlassert-0.3.1.dist-info → sqlassert-0.4.1.dist-info}/licenses/LICENSE +0 -0
sqlassert/rules/foreign_key.py
CHANGED
|
@@ -21,16 +21,18 @@ Anything else stops propagation and names where.
|
|
|
21
21
|
from itertools import product
|
|
22
22
|
from typing import assert_never
|
|
23
23
|
|
|
24
|
+
from sqlassert.diagnostics import quoted, quoted_all
|
|
24
25
|
from sqlassert import ir
|
|
25
|
-
from sqlassert.properties import ReferentialCoverage
|
|
26
|
+
from sqlassert.properties import ForeignKey, ReferentialCoverage
|
|
26
27
|
from sqlassert.python_engine import Result, Stratum, analysis, any_of, current_arena, unknown
|
|
27
28
|
from sqlassert.rules.equality import _equal_columns
|
|
28
29
|
from sqlassert.rules.uniqueness import unique_set
|
|
30
|
+
from sqlassert.rules.value_typing import exact_comparison
|
|
29
31
|
|
|
30
32
|
type _Columns = tuple[ir.OutputColumn, ...]
|
|
31
33
|
|
|
32
34
|
|
|
33
|
-
@analysis(Stratum.FOREIGN_KEY)
|
|
35
|
+
@analysis(Stratum.FOREIGN_KEY, evaluates=ForeignKey)
|
|
34
36
|
def foreign_key(columns: _Columns, referenced_columns: _Columns) -> Result[bool]:
|
|
35
37
|
shape = _pairing(columns, referenced_columns)
|
|
36
38
|
if not shape.value:
|
|
@@ -38,7 +40,7 @@ def foreign_key(columns: _Columns, referenced_columns: _Columns) -> Result[bool]
|
|
|
38
40
|
return referential_coverage(columns, referenced_columns) & _referenced_unique_set(referenced_columns)
|
|
39
41
|
|
|
40
42
|
|
|
41
|
-
@analysis(Stratum.FOREIGN_KEY)
|
|
43
|
+
@analysis(Stratum.FOREIGN_KEY, evaluates=ReferentialCoverage)
|
|
42
44
|
def referential_coverage(columns: _Columns, referenced_columns: _Columns) -> Result[bool]:
|
|
43
45
|
shape = _pairing(columns, referenced_columns)
|
|
44
46
|
if not shape.value:
|
|
@@ -48,7 +50,7 @@ def referential_coverage(columns: _Columns, referenced_columns: _Columns) -> Res
|
|
|
48
50
|
# Pairs, not lists, are the relationship: (a, b) → (x, y) is (b, a) → (y, x).
|
|
49
51
|
pairs = set(zip(columns, target))
|
|
50
52
|
known = [
|
|
51
|
-
any_of(current_arena().
|
|
53
|
+
any_of(current_arena().accepted_evidence(coverage)) for coverage in _known()
|
|
52
54
|
if set(zip(coverage.columns, coverage.referenced_columns)) == pairs
|
|
53
55
|
]
|
|
54
56
|
if known:
|
|
@@ -72,8 +74,10 @@ def _targets(referenced_columns: _Columns) -> list[tuple[_Columns, list[Result[b
|
|
|
72
74
|
assert target is not None
|
|
73
75
|
match target:
|
|
74
76
|
case ir.SetOperation(operator="union"):
|
|
75
|
-
|
|
76
|
-
|
|
77
|
+
arms = [target.arms(column) for column in referenced_columns]
|
|
78
|
+
if any(pair is None for pair in arms):
|
|
79
|
+
return [(referenced_columns, [])]
|
|
80
|
+
upstream = list(zip(*(pair for pair in arms if pair is not None)))
|
|
77
81
|
reason = "A UNION keeps every row of each branch"
|
|
78
82
|
case _:
|
|
79
83
|
kept = [_kept(target, column) for column in referenced_columns]
|
|
@@ -100,7 +104,8 @@ def _referencing_side(
|
|
|
100
104
|
def _semi_join(join: ir.Join, columns: _Columns, referenced_columns: _Columns) -> list[Result[bool]]:
|
|
101
105
|
"""A semi join keeps a row only when some right row satisfies ON, so
|
|
102
106
|
columns ON equates with right columns take those columns' values: coverage
|
|
103
|
-
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`)."""
|
|
104
109
|
partners: list[list[tuple[ir.OutputColumn, ir.Equality]]] = []
|
|
105
110
|
for column in columns:
|
|
106
111
|
match column.scalar_expr:
|
|
@@ -114,6 +119,7 @@ def _semi_join(join: ir.Join, columns: _Columns, referenced_columns: _Columns) -
|
|
|
114
119
|
for own, other in ((conjunct.left, conjunct.right), (conjunct.right, conjunct.left))
|
|
115
120
|
if isinstance(own, ir.ColumnRef) and own.column is upstream
|
|
116
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.
|
|
117
123
|
]
|
|
118
124
|
if not found:
|
|
119
125
|
return []
|
|
@@ -146,7 +152,7 @@ def _input_rows(
|
|
|
146
152
|
alternatives: dict[_Columns, Result[bool]] = {}
|
|
147
153
|
for chosen in product(*(sorted(group.value, key=order.__getitem__) for group in equal)):
|
|
148
154
|
substituted = [
|
|
149
|
-
Result(True, f"{column.name} equals {stand_in.name} on every row where it is non-null", (column, stand_in), [group])
|
|
155
|
+
Result(True, f"{quoted(column.name)} equals {quoted(stand_in.name)} on every row where it is non-null", (column, stand_in), [group])
|
|
150
156
|
for column, stand_in, group in zip(columns, chosen, equal) if stand_in is not column
|
|
151
157
|
]
|
|
152
158
|
for target, widened in targets:
|
|
@@ -299,12 +305,8 @@ def _known() -> list[ReferentialCoverage]:
|
|
|
299
305
|
return [coverage for coverage in current_arena().knowledge if isinstance(coverage, ReferentialCoverage)]
|
|
300
306
|
|
|
301
307
|
|
|
302
|
-
def _key(coverage: ReferentialCoverage) -> tuple:
|
|
303
|
-
return ("referential_coverage", (("columns", coverage.columns), ("referenced_columns", coverage.referenced_columns)))
|
|
304
|
-
|
|
305
|
-
|
|
306
308
|
def _names(columns: _Columns) -> str:
|
|
307
|
-
return
|
|
309
|
+
return quoted_all(column.name for column in columns)
|
|
308
310
|
|
|
309
311
|
|
|
310
312
|
def _describe(columns: _Columns) -> str:
|
|
@@ -2,43 +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
|
|
6
|
-
|
|
7
|
-
|
|
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
|
|
14
|
+
matched input's Row Identity, a row matches at most one row and is never
|
|
15
|
+
repeated. A cross join is an ON with no
|
|
8
16
|
conjuncts: the other input must have at most one row. A semi or anti join
|
|
9
17
|
keeps or drops left rows whole and outputs no right row; its left rows are
|
|
10
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`).
|
|
11
21
|
"""
|
|
12
22
|
|
|
13
|
-
from
|
|
23
|
+
from collections.abc import Iterator
|
|
24
|
+
from dataclasses import dataclass, field
|
|
25
|
+
from typing import Literal
|
|
14
26
|
|
|
15
27
|
from sqlassert import ir
|
|
16
|
-
from sqlassert.
|
|
17
|
-
from sqlassert.
|
|
18
|
-
from sqlassert.rules.
|
|
19
|
-
from sqlassert.rules.
|
|
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
|
|
30
|
+
from sqlassert.rules.column_set import Attribute, ColumnSet
|
|
31
|
+
from sqlassert.rules.nullability import non_null_column
|
|
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
|
|
20
34
|
|
|
21
35
|
type Side = Literal["left", "right"]
|
|
22
36
|
|
|
23
37
|
|
|
24
|
-
@analysis(Stratum.UNIQUE_JOIN)
|
|
38
|
+
@analysis(Stratum.UNIQUE_JOIN, evaluates=ManyToOneJoin)
|
|
25
39
|
def many_to_one_join(join: ir.Join) -> Result[bool]:
|
|
26
40
|
if join.scalar_subquery:
|
|
27
41
|
return Result(True, "A scalar subquery returns at most one row for each outer row, or the query fails", (join,))
|
|
28
42
|
return _at_most_one_match(join, "right")
|
|
29
43
|
|
|
30
44
|
|
|
31
|
-
@analysis(Stratum.UNIQUE_JOIN)
|
|
45
|
+
@analysis(Stratum.UNIQUE_JOIN, evaluates=OneToManyJoin)
|
|
32
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,))
|
|
33
49
|
return _at_most_one_match(join, "left")
|
|
34
50
|
|
|
35
51
|
|
|
36
|
-
@analysis(Stratum.UNIQUE_JOIN)
|
|
52
|
+
@analysis(Stratum.UNIQUE_JOIN, evaluates=OneToOneJoin)
|
|
37
53
|
def one_to_one_join(join: ir.Join) -> Result[bool]:
|
|
38
54
|
return all_of((many_to_one_join(join), one_to_many_join(join)))
|
|
39
55
|
|
|
40
56
|
|
|
41
|
-
@analysis(Stratum.UNIQUE_JOIN)
|
|
57
|
+
@analysis(Stratum.UNIQUE_JOIN, evaluates=UniqueJoin)
|
|
42
58
|
def unique_join(join: ir.Join) -> Result[bool]:
|
|
43
59
|
# Not many to many: the proved alternative names the input that is unique.
|
|
44
60
|
return any_of((many_to_one_join(join), one_to_many_join(join)))
|
|
@@ -49,46 +65,293 @@ def _at_most_one_match(join: ir.Join, matched: Side) -> Result[bool]:
|
|
|
49
65
|
relation = join.right if matched == "right" else join.left
|
|
50
66
|
cols = _bound_columns(join, matched)
|
|
51
67
|
bound = frozenset(cols.value.columns)
|
|
52
|
-
reached = _reaches_row_identity(_closure(relation, bound,
|
|
68
|
+
reached = _reaches_row_identity(_closure(relation, bound, frozenset(cols.value.definite)))
|
|
53
69
|
reason = "Right columns bound for each left row" if matched == "right" else "Left columns bound for each right row"
|
|
54
70
|
return all_of((Result(True, reason, (join,), list(cols.members.values())), reached))
|
|
55
71
|
|
|
56
72
|
|
|
73
|
+
@dataclass(eq=False)
|
|
74
|
+
class BoundColumns(ColumnSet):
|
|
75
|
+
"""`columns` bound for each row of the other input; `definite` those of
|
|
76
|
+
them non-null on every matched row: bound by `=`, not only by IS NOT
|
|
77
|
+
DISTINCT FROM, which also matches NULL to NULL."""
|
|
78
|
+
|
|
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)
|
|
82
|
+
|
|
83
|
+
|
|
57
84
|
@analysis(Stratum.UNIQUE_JOIN)
|
|
58
|
-
def _bound_columns(join: ir.Join, matched: Side) -> Result[
|
|
59
|
-
"""The columns of `matched` an ON equality
|
|
85
|
+
def _bound_columns(join: ir.Join, matched: Side) -> Result[BoundColumns]:
|
|
86
|
+
"""The columns of `matched` an ON equality (or IS NOT DISTINCT FROM)
|
|
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
|
+
"""
|
|
60
96
|
relation, other = (join.right, join.left) if matched == "right" else (join.left, join.right)
|
|
61
97
|
members = {}
|
|
98
|
+
definite = set()
|
|
99
|
+
equalities = set()
|
|
62
100
|
for equality in join.conjuncts:
|
|
63
|
-
if not isinstance(equality, ir.Equality):
|
|
101
|
+
if not isinstance(equality, ir.Equality | ir.NullSafeEquality):
|
|
64
102
|
continue
|
|
65
103
|
for bound, value in ((equality.left, equality.right), (equality.right, equality.left)):
|
|
66
104
|
if bound is value:
|
|
67
105
|
continue
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
case _:
|
|
76
|
-
assert_never(bound)
|
|
77
|
-
|
|
78
|
-
# An equality that casts pins nothing: '01' and '1' both equal 1.
|
|
79
|
-
match value:
|
|
80
|
-
case ir.Constant():
|
|
81
|
-
if not _pins(column, value):
|
|
82
|
-
continue
|
|
83
|
-
case ir.ColumnRef(column=other_column):
|
|
84
|
-
if other_column not in other.output_columns or not _pins(column, value):
|
|
85
|
-
continue
|
|
86
|
-
case ir.NullLiteral() | ir.Coalesce() | ir.SimpleCase() | ir.OpaqueExpression() | ir.OpaquePureFunction() | ir.Call() | ir.Count() | ir.AnyAggregate() | ir.Elements() | ir.Equality() | ir.InList() | ir.IsNull() | ir.IsNotNull() | ir.And() | ir.Or():
|
|
87
|
-
continue
|
|
88
|
-
case _:
|
|
89
|
-
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
|
|
90
113
|
|
|
91
114
|
evidence = Result(True, "Equality fixes the matched column for each row of the other input", (equality, column, value))
|
|
92
115
|
members[column] = members[column] | evidence if column in members else evidence
|
|
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)):
|
|
119
|
+
definite.add(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
|
+
|
|
93
328
|
|
|
94
|
-
|
|
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
|