sqlassert 0.1.2__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/__init__.py +34 -9
- sqlassert/__main__.py +9 -0
- sqlassert/check.py +451 -0
- sqlassert/diagnostics.py +70 -0
- sqlassert/dialects.py +258 -0
- sqlassert/discovery/__init__.py +30 -0
- sqlassert/discovery/bigquery.py +71 -0
- sqlassert/discovery/databricks.py +18 -0
- sqlassert/discovery/duckdb.py +159 -0
- sqlassert/discovery/fetcher.py +418 -0
- sqlassert/discovery/information_schema.py +327 -0
- sqlassert/discovery/mysql.py +70 -0
- sqlassert/discovery/postgres.py +142 -0
- sqlassert/discovery/redshift.py +36 -0
- sqlassert/discovery/snowflake.py +63 -0
- sqlassert/discovery/trino.py +37 -0
- sqlassert/edits.py +240 -0
- sqlassert/hazards.py +574 -0
- sqlassert/ir/__init__.py +58 -0
- sqlassert/ir/convert.py +3509 -0
- sqlassert/ir/model.py +779 -0
- sqlassert/main.py +51 -0
- sqlassert/properties.py +121 -0
- sqlassert/provenance.py +73 -0
- sqlassert/python_engine.py +356 -0
- sqlassert/reporting.py +105 -0
- sqlassert/rewrites.py +1541 -0
- sqlassert/rules/STYLEGUIDE.md +19 -0
- sqlassert/rules/__init__.py +11 -0
- sqlassert/rules/column_set.py +34 -0
- sqlassert/rules/domain.py +472 -0
- sqlassert/rules/equality.py +442 -0
- sqlassert/rules/exactly_one.py +114 -0
- sqlassert/rules/foreign_key.py +319 -0
- sqlassert/rules/join_cardinality.py +116 -0
- sqlassert/rules/nullability.py +627 -0
- sqlassert/rules/uniqueness.py +904 -0
- sqlassert/sql_parse.py +1081 -0
- sqlassert/suggest.py +418 -0
- sqlassert-0.3.3.dist-info/METADATA +807 -0
- sqlassert-0.3.3.dist-info/RECORD +46 -0
- {sqlassert-0.1.2.dist-info → sqlassert-0.3.3.dist-info}/WHEEL +1 -1
- sqlassert-0.3.3.dist-info/entry_points.txt +2 -0
- sqlassert-0.3.3.dist-info/licenses/LICENSE +21 -0
- sqlassert-0.3.3.dist-info/top_level.txt +2 -0
- sqlassert_cli.py +130 -0
- sqlassert/unique.py +0 -605
- sqlassert-0.1.2.dist-info/METADATA +0 -173
- sqlassert-0.1.2.dist-info/RECORD +0 -6
- sqlassert-0.1.2.dist-info/top_level.txt +0 -1
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
"""Foreign Keys: Referential Coverage onto a Unique Set of the referenced relation.
|
|
2
|
+
|
|
3
|
+
Knowledge -- `REFERENCES` constraints, catalog foreign keys, and
|
|
4
|
+
`DECLARE FOREIGN KEY` -- supplies coverage only; the referenced Unique Set is
|
|
5
|
+
proved separately, so a declaration never vouches for its target. Under
|
|
6
|
+
`MATCH SIMPLE` a row with a null referencing component is exempt, so
|
|
7
|
+
nullability never weakens a Foreign Key.
|
|
8
|
+
|
|
9
|
+
Coverage propagates down both sides. On the referencing side, it holds for
|
|
10
|
+
columns each output row takes from one row of one covered input: filters,
|
|
11
|
+
projections, aliases, views, CTEs, DISTINCT, grouping keys, and either side of
|
|
12
|
+
any join, since a padded side is NULL in every column. A column may stand in
|
|
13
|
+
for any column of its Equality Group, so an inner equality join onto the
|
|
14
|
+
referenced columns establishes coverage. On the referenced side, coverage of
|
|
15
|
+
an input carries over only to a relation that keeps every input row's values;
|
|
16
|
+
one that may drop rows (a filter, an inner join) must be covered on its own,
|
|
17
|
+
except the left input of a proved Exactly One Join, which keeps every left row.
|
|
18
|
+
Anything else stops propagation and names where.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from itertools import product
|
|
22
|
+
from typing import assert_never
|
|
23
|
+
|
|
24
|
+
from sqlassert.diagnostics import quoted, quoted_all
|
|
25
|
+
from sqlassert import ir
|
|
26
|
+
from sqlassert.properties import ReferentialCoverage
|
|
27
|
+
from sqlassert.python_engine import Result, Stratum, analysis, any_of, current_arena, unknown
|
|
28
|
+
from sqlassert.rules.equality import _equal_columns
|
|
29
|
+
from sqlassert.rules.uniqueness import unique_set
|
|
30
|
+
|
|
31
|
+
type _Columns = tuple[ir.OutputColumn, ...]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@analysis(Stratum.FOREIGN_KEY)
|
|
35
|
+
def foreign_key(columns: _Columns, referenced_columns: _Columns) -> Result[bool]:
|
|
36
|
+
shape = _pairing(columns, referenced_columns)
|
|
37
|
+
if not shape.value:
|
|
38
|
+
return shape
|
|
39
|
+
return referential_coverage(columns, referenced_columns) & _referenced_unique_set(referenced_columns)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@analysis(Stratum.FOREIGN_KEY)
|
|
43
|
+
def referential_coverage(columns: _Columns, referenced_columns: _Columns) -> Result[bool]:
|
|
44
|
+
shape = _pairing(columns, referenced_columns)
|
|
45
|
+
if not shape.value:
|
|
46
|
+
return shape
|
|
47
|
+
targets = _targets(referenced_columns)
|
|
48
|
+
for target, widened in targets:
|
|
49
|
+
# Pairs, not lists, are the relationship: (a, b) → (x, y) is (b, a) → (y, x).
|
|
50
|
+
pairs = set(zip(columns, target))
|
|
51
|
+
known = [
|
|
52
|
+
any_of(current_arena().accepted[_key(coverage)]) for coverage in _known()
|
|
53
|
+
if set(zip(coverage.columns, coverage.referenced_columns)) == pairs
|
|
54
|
+
]
|
|
55
|
+
if known:
|
|
56
|
+
return Result(True, f"Known coverage onto {_describe(target)}", columns, [*widened, *known])
|
|
57
|
+
if all(column is referenced for column, referenced in pairs):
|
|
58
|
+
return Result(True, "Columns cover themselves", columns, widened)
|
|
59
|
+
return any_of(_referencing_side(columns, referenced_columns, targets))
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _targets(referenced_columns: _Columns) -> list[tuple[_Columns, list[Result[bool]]]]:
|
|
63
|
+
"""The referenced columns, and each upstream column list whose coverage carries over to them.
|
|
64
|
+
|
|
65
|
+
Coverage onto an input carries over only through a relation that keeps
|
|
66
|
+
every input row's values. Narrowing the referenced relation (a filter, an
|
|
67
|
+
inner join) may drop the very rows the referencing columns match, so it
|
|
68
|
+
must be covered on its own: only the referencing side can show that.
|
|
69
|
+
Each entry lists the steps that carry coverage from it to the referenced
|
|
70
|
+
columns.
|
|
71
|
+
"""
|
|
72
|
+
target = current_arena().program.relation_of(frozenset(referenced_columns))
|
|
73
|
+
assert target is not None
|
|
74
|
+
match target:
|
|
75
|
+
case ir.SetOperation(operator="union"):
|
|
76
|
+
arms = [target.arms(column) for column in referenced_columns]
|
|
77
|
+
if any(pair is None for pair in arms):
|
|
78
|
+
return [(referenced_columns, [])]
|
|
79
|
+
upstream = list(zip(*(pair for pair in arms if pair is not None)))
|
|
80
|
+
reason = "A UNION keeps every row of each branch"
|
|
81
|
+
case _:
|
|
82
|
+
kept = [_kept(target, column) for column in referenced_columns]
|
|
83
|
+
sources = {source for source, _ in filter(None, kept)}
|
|
84
|
+
if None in kept or len(sources) != 1:
|
|
85
|
+
return [(referenced_columns, [])]
|
|
86
|
+
upstream = [tuple(column for _, column in filter(None, kept))]
|
|
87
|
+
reason = f"{_describe(referenced_columns)} keeps the values of every row of its input"
|
|
88
|
+
matched = [_exactly_one(target)] if isinstance(target, ir.Join) and target.kind == "inner" else []
|
|
89
|
+
step = Result(True, reason, (target,), matched)
|
|
90
|
+
return [(referenced_columns, []), *(
|
|
91
|
+
(columns, [step, *steps]) for branch in upstream for columns, steps in _targets(branch)
|
|
92
|
+
)]
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _referencing_side(
|
|
96
|
+
columns: _Columns, referenced_columns: _Columns, targets: list[tuple[_Columns, list[Result[bool]]]]
|
|
97
|
+
) -> list[Result[bool]]:
|
|
98
|
+
relation = current_arena().program.relation_of(frozenset(columns))
|
|
99
|
+
semi = _semi_join(relation, columns, referenced_columns) if isinstance(relation, ir.Join) and relation.kind == "semi" else []
|
|
100
|
+
return [*semi, *_input_rows(columns, referenced_columns, targets)]
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _semi_join(join: ir.Join, columns: _Columns, referenced_columns: _Columns) -> list[Result[bool]]:
|
|
104
|
+
"""A semi join keeps a row only when some right row satisfies ON, so
|
|
105
|
+
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
|
+
partners: list[list[tuple[ir.OutputColumn, ir.Equality]]] = []
|
|
108
|
+
for column in columns:
|
|
109
|
+
match column.scalar_expr:
|
|
110
|
+
case ir.ColumnRef(column=upstream):
|
|
111
|
+
pass
|
|
112
|
+
case _:
|
|
113
|
+
raise TypeError(f"Join column {column.name} is not a pass-through")
|
|
114
|
+
found = [
|
|
115
|
+
(other.column, conjunct)
|
|
116
|
+
for conjunct in join.conjuncts if isinstance(conjunct, ir.Equality)
|
|
117
|
+
for own, other in ((conjunct.left, conjunct.right), (conjunct.right, conjunct.left))
|
|
118
|
+
if isinstance(own, ir.ColumnRef) and own.column is upstream
|
|
119
|
+
and isinstance(other, ir.ColumnRef) and other.column in join.right.output_columns
|
|
120
|
+
]
|
|
121
|
+
if not found:
|
|
122
|
+
return []
|
|
123
|
+
partners.append(found)
|
|
124
|
+
alternatives = []
|
|
125
|
+
for chosen in product(*partners):
|
|
126
|
+
matched = tuple(partner for partner, _ in chosen)
|
|
127
|
+
reason = f"({_names(columns)}) equal ({_names(matched)}) of the right row the semi join matched"
|
|
128
|
+
step = Result(True, reason, (join, *columns), [Result(True, "ON equality", (conjunct,)) for _, conjunct in chosen])
|
|
129
|
+
alternatives.append(step & referential_coverage(matched, referenced_columns))
|
|
130
|
+
return alternatives
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _input_rows(
|
|
134
|
+
columns: _Columns, referenced_columns: _Columns, targets: list[tuple[_Columns, list[Result[bool]]]]
|
|
135
|
+
) -> list[Result[bool]]:
|
|
136
|
+
"""Coverage of the referencing columns, read from the input rows they come from.
|
|
137
|
+
|
|
138
|
+
Each output row's passed-through values come from one row of one input, or
|
|
139
|
+
are all NULL where a join padded that input, which MATCH SIMPLE exempts. A
|
|
140
|
+
column may stand in for any column of its Equality Group: on a row where it
|
|
141
|
+
is non-null, they are equal.
|
|
142
|
+
"""
|
|
143
|
+
relation = current_arena().program.relation_of(frozenset(columns))
|
|
144
|
+
assert relation is not None
|
|
145
|
+
if isinstance(relation, ir.SetOperation):
|
|
146
|
+
return [_set_operation(relation, columns, referenced_columns)]
|
|
147
|
+
equal = [_equal_columns(column) for column in columns]
|
|
148
|
+
order = {column: index for index, column in enumerate(relation.output_columns)}
|
|
149
|
+
alternatives: dict[_Columns, Result[bool]] = {}
|
|
150
|
+
for chosen in product(*(sorted(group.value, key=order.__getitem__) for group in equal)):
|
|
151
|
+
substituted = [
|
|
152
|
+
Result(True, f"{quoted(column.name)} equals {quoted(stand_in.name)} on every row where it is non-null", (column, stand_in), [group])
|
|
153
|
+
for column, stand_in, group in zip(columns, chosen, equal) if stand_in is not column
|
|
154
|
+
]
|
|
155
|
+
for target, widened in targets:
|
|
156
|
+
if all(stand_in is referenced for stand_in, referenced in zip(chosen, target)):
|
|
157
|
+
reason = f"Equal to {_describe(target)} on every row where they are non-null"
|
|
158
|
+
return [Result(True, reason, chosen, [*substituted, *widened])]
|
|
159
|
+
upstream = [_passed(relation, column) for column in chosen]
|
|
160
|
+
sources = {passed[0] for passed in upstream if passed is not None}
|
|
161
|
+
if None in upstream or len(sources) != 1:
|
|
162
|
+
continue
|
|
163
|
+
passed = tuple(column for _, column in filter(None, upstream))
|
|
164
|
+
if passed in alternatives:
|
|
165
|
+
continue
|
|
166
|
+
reason = f"Each row's ({_names(chosen)}) come from one input row, or are all NULL where a join padded it"
|
|
167
|
+
alternatives[passed] = Result(True, reason, (relation, *chosen), substituted) & referential_coverage(passed, referenced_columns)
|
|
168
|
+
if alternatives:
|
|
169
|
+
return list(alternatives.values())
|
|
170
|
+
match relation:
|
|
171
|
+
case ir.NamedRelation(body=None):
|
|
172
|
+
elsewhere = [
|
|
173
|
+
_describe(coverage.referenced_columns) for coverage in _known() if set(coverage.columns) == set(columns)
|
|
174
|
+
]
|
|
175
|
+
hint = f"; these columns reference {', '.join(elsewhere)}" if elsewhere else ""
|
|
176
|
+
named = dict.fromkeys([_describe(referenced_columns), *(
|
|
177
|
+
_describe(target) for target, _ in targets
|
|
178
|
+
if isinstance(current_arena().program.relation_of(frozenset(target)), ir.NamedRelation)
|
|
179
|
+
)])
|
|
180
|
+
missing = unknown(f"No known Foreign Key from {_describe(columns)} to {' or '.join(named)}{hint}", *columns)
|
|
181
|
+
return [missing, *_narrowed(targets)]
|
|
182
|
+
case ir.OpaqueRelation():
|
|
183
|
+
return [unknown("Foreign Keys do not propagate through an unanalyzed relation", relation, *columns)]
|
|
184
|
+
case _:
|
|
185
|
+
return [unknown(
|
|
186
|
+
f"({_names(columns)}) are not passed through from one input row of this {type(relation).__name__}, "
|
|
187
|
+
"so Foreign Keys stop here",
|
|
188
|
+
relation, *columns,
|
|
189
|
+
)]
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _set_operation(relation: ir.SetOperation, columns: _Columns, referenced_columns: _Columns) -> Result[bool]:
|
|
193
|
+
"""Coverage of a set operation's rows, from each branch's columns at the same positions."""
|
|
194
|
+
arms = [relation.arms(column) for column in columns]
|
|
195
|
+
if None in arms:
|
|
196
|
+
return unknown("The set operation's inputs are not paired by position", relation, *columns)
|
|
197
|
+
left = referential_coverage(tuple(arm[0] for arm in filter(None, arms)), referenced_columns)
|
|
198
|
+
right = referential_coverage(tuple(arm[1] for arm in filter(None, arms)), referenced_columns)
|
|
199
|
+
match relation.operator:
|
|
200
|
+
case "union":
|
|
201
|
+
return Result(True, "A UNION row comes from either branch, so both must be covered", (relation,)) & left & right
|
|
202
|
+
case "intersect":
|
|
203
|
+
return Result(True, "An INTERSECT row is in both branches, so one covered branch suffices", (relation,)) & (left | right)
|
|
204
|
+
case "except":
|
|
205
|
+
return Result(True, "An EXCEPT row comes from the left branch", (relation,)) & left
|
|
206
|
+
case _:
|
|
207
|
+
assert_never(relation.operator)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _narrowed(targets: list[tuple[_Columns, list[Result[bool]]]]) -> list[Result[bool]]:
|
|
211
|
+
"""Why coverage of a narrowed referenced relation's input does not carry over to it."""
|
|
212
|
+
notes = []
|
|
213
|
+
for target, _ in targets:
|
|
214
|
+
relation = current_arena().program.relation_of(frozenset(target))
|
|
215
|
+
if relation is not None and _narrows(relation):
|
|
216
|
+
reason = f"{_describe(target)} may drop rows of its input, so coverage of its input does not carry over to it"
|
|
217
|
+
notes.append(unknown(reason, relation))
|
|
218
|
+
return notes
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _passed(relation: ir.RelationExpr, column: ir.OutputColumn) -> tuple[ir.RelationExpr, ir.OutputColumn] | None:
|
|
222
|
+
"""The input column `column` repeats, when each output row takes it from one input row or padding."""
|
|
223
|
+
match relation, column.scalar_expr:
|
|
224
|
+
case (
|
|
225
|
+
ir.Alias(source=source) | ir.NamedRelation(body=ir.RelationExpr() as source) | ir.Filter(input=source)
|
|
226
|
+
| ir.Project(input=source) | ir.Limit(input=source) | ir.Distinct(input=source) | ir.QualifyByPartition(input=source),
|
|
227
|
+
ir.ColumnRef(column=upstream),
|
|
228
|
+
):
|
|
229
|
+
return source, upstream
|
|
230
|
+
case ir.Aggregate(input=source, grouping_outputs=grouping), ir.ColumnRef(column=upstream) if column in grouping:
|
|
231
|
+
return source, upstream
|
|
232
|
+
case ir.Join(left=left, right=right), ir.ColumnRef(column=upstream):
|
|
233
|
+
# Any join kind: a padded side is NULL in every column, which MATCH SIMPLE exempts.
|
|
234
|
+
return (left if upstream in left.output_columns else right), upstream
|
|
235
|
+
case _:
|
|
236
|
+
return None # A computed or aggregated column, or a relation with no input.
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _kept(relation: ir.RelationExpr, column: ir.OutputColumn) -> tuple[ir.RelationExpr, ir.OutputColumn] | None:
|
|
240
|
+
"""The input column whose value on every input row `column` takes on some output row."""
|
|
241
|
+
match relation, column.scalar_expr:
|
|
242
|
+
case (
|
|
243
|
+
ir.Alias(source=source) | ir.NamedRelation(body=ir.RelationExpr() as source) | ir.Project(input=source)
|
|
244
|
+
| ir.Distinct(input=source),
|
|
245
|
+
ir.ColumnRef(column=upstream),
|
|
246
|
+
):
|
|
247
|
+
return source, upstream
|
|
248
|
+
case ir.Aggregate(input=source, grouping_outputs=grouping), ir.ColumnRef(column=upstream) if column in grouping:
|
|
249
|
+
return source, upstream
|
|
250
|
+
case ir.Join(kind="left" | "full", left=left), ir.ColumnRef(column=upstream) if upstream in left.output_columns:
|
|
251
|
+
return left, upstream
|
|
252
|
+
case ir.Join(kind="right" | "full", right=right), ir.ColumnRef(column=upstream) if upstream in right.output_columns:
|
|
253
|
+
return right, upstream
|
|
254
|
+
case ir.Join(kind="inner", left=left), ir.ColumnRef(column=upstream) if upstream in left.output_columns:
|
|
255
|
+
return (left, upstream) if _exactly_one(relation).value else None
|
|
256
|
+
case _:
|
|
257
|
+
return None # The relation may drop input rows, or the column is computed.
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _exactly_one(join: ir.Join) -> Result[bool]:
|
|
261
|
+
"""Whether `join` matches every left row exactly once, so it keeps every left row."""
|
|
262
|
+
from sqlassert.rules.exactly_one import exactly_one_join # It builds on Referential Coverage.
|
|
263
|
+
|
|
264
|
+
return exactly_one_join(join)
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _narrows(relation: ir.RelationExpr) -> bool:
|
|
268
|
+
"""Whether `relation` may drop rows of an input it passes columns from."""
|
|
269
|
+
match relation:
|
|
270
|
+
case ir.Filter() | ir.Limit() | ir.QualifyByPartition() | ir.Join() | ir.SetOperation(operator="intersect" | "except"):
|
|
271
|
+
return True
|
|
272
|
+
case _:
|
|
273
|
+
return False
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _referenced_unique_set(referenced_columns: _Columns) -> Result[bool]:
|
|
277
|
+
relation = current_arena().program.relation_of(frozenset(referenced_columns))
|
|
278
|
+
match relation:
|
|
279
|
+
case ir.NamedRelation(role=ir.RelationRole.TABLE, is_schema_complete=False):
|
|
280
|
+
return unknown(
|
|
281
|
+
f"Referenced relation {relation.name} has no complete declared schema, so no Unique Set is known on it",
|
|
282
|
+
relation,
|
|
283
|
+
)
|
|
284
|
+
case _:
|
|
285
|
+
unique = unique_set(frozenset(referenced_columns))
|
|
286
|
+
reason = f"The referenced columns {_describe(referenced_columns)} must form a Unique Set"
|
|
287
|
+
return Result(unique.value, reason, referenced_columns, [unique], kind="all")
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def _pairing(columns: _Columns, referenced_columns: _Columns) -> Result[bool]:
|
|
291
|
+
program = current_arena().program
|
|
292
|
+
if not columns or len(columns) != len(referenced_columns):
|
|
293
|
+
return unknown("A Foreign Key pairs equally many referencing and referenced columns", *columns, *referenced_columns)
|
|
294
|
+
if program.relation_of(frozenset(columns)) is None:
|
|
295
|
+
return unknown("Referencing columns must belong to one relation", *columns)
|
|
296
|
+
if program.relation_of(frozenset(referenced_columns)) is None:
|
|
297
|
+
return unknown("Referenced columns must belong to one relation", *referenced_columns)
|
|
298
|
+
return Result(True, "Columns pair by position", (*columns, *referenced_columns))
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _known() -> list[ReferentialCoverage]:
|
|
302
|
+
return [coverage for coverage in current_arena().knowledge if isinstance(coverage, ReferentialCoverage)]
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def _key(coverage: ReferentialCoverage) -> tuple:
|
|
306
|
+
return ("referential_coverage", (("columns", coverage.columns), ("referenced_columns", coverage.referenced_columns)))
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def _names(columns: _Columns) -> str:
|
|
310
|
+
return quoted_all(column.name for column in columns)
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def _describe(columns: _Columns) -> str:
|
|
314
|
+
relation = current_arena().program.relation_of(frozenset(columns))
|
|
315
|
+
match relation:
|
|
316
|
+
case ir.NamedRelation(name=name) | ir.Alias(name=name):
|
|
317
|
+
return f"{name}({_names(columns)})"
|
|
318
|
+
case _:
|
|
319
|
+
return f"the {type(relation).__name__}'s ({_names(columns)})"
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""Join cardinality: whether a join can repeat rows of its left input, its right input, or both.
|
|
2
|
+
|
|
3
|
+
A row of one input appears once per matching row of the other, or once padded,
|
|
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
|
|
9
|
+
matched input's Row Identity, a row matches at most one row and is never
|
|
10
|
+
repeated. A cross join is an ON with no
|
|
11
|
+
conjuncts: the other input must have at most one row. A semi or anti join
|
|
12
|
+
keeps or drops left rows whole and outputs no right row; its left rows are
|
|
13
|
+
never repeated (`many_to_one_join`), and no cardinality marker applies to it.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from typing import Literal, assert_never
|
|
18
|
+
|
|
19
|
+
from sqlassert import ir
|
|
20
|
+
from sqlassert.python_engine import Result, Stratum, all_of, any_of, analysis
|
|
21
|
+
from sqlassert.rules.column_set import Attribute, ColumnSet
|
|
22
|
+
from sqlassert.rules.equality import _pins
|
|
23
|
+
from sqlassert.rules.nullability import non_null_column
|
|
24
|
+
from sqlassert.rules.uniqueness import _closure, _reaches_row_identity
|
|
25
|
+
|
|
26
|
+
type Side = Literal["left", "right"]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@analysis(Stratum.UNIQUE_JOIN)
|
|
30
|
+
def many_to_one_join(join: ir.Join) -> Result[bool]:
|
|
31
|
+
if join.scalar_subquery:
|
|
32
|
+
return Result(True, "A scalar subquery returns at most one row for each outer row, or the query fails", (join,))
|
|
33
|
+
return _at_most_one_match(join, "right")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@analysis(Stratum.UNIQUE_JOIN)
|
|
37
|
+
def one_to_many_join(join: ir.Join) -> Result[bool]:
|
|
38
|
+
return _at_most_one_match(join, "left")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@analysis(Stratum.UNIQUE_JOIN)
|
|
42
|
+
def one_to_one_join(join: ir.Join) -> Result[bool]:
|
|
43
|
+
return all_of((many_to_one_join(join), one_to_many_join(join)))
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@analysis(Stratum.UNIQUE_JOIN)
|
|
47
|
+
def unique_join(join: ir.Join) -> Result[bool]:
|
|
48
|
+
# Not many to many: the proved alternative names the input that is unique.
|
|
49
|
+
return any_of((many_to_one_join(join), one_to_many_join(join)))
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _at_most_one_match(join: ir.Join, matched: Side) -> Result[bool]:
|
|
53
|
+
"""Each row of the other input matches at most one row of `matched`."""
|
|
54
|
+
relation = join.right if matched == "right" else join.left
|
|
55
|
+
cols = _bound_columns(join, matched)
|
|
56
|
+
bound = frozenset(cols.value.columns)
|
|
57
|
+
reached = _reaches_row_identity(_closure(relation, bound, frozenset(cols.value.definite)))
|
|
58
|
+
reason = "Right columns bound for each left row" if matched == "right" else "Left columns bound for each right row"
|
|
59
|
+
return all_of((Result(True, reason, (join,), list(cols.members.values())), reached))
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass(eq=False)
|
|
63
|
+
class BoundColumns(ColumnSet):
|
|
64
|
+
"""`columns` bound for each row of the other input; `definite` those of
|
|
65
|
+
them non-null on every matched row: bound by `=`, not only by IS NOT
|
|
66
|
+
DISTINCT FROM, which also matches NULL to NULL."""
|
|
67
|
+
|
|
68
|
+
definite: set[Attribute] = field(default_factory=set)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@analysis(Stratum.UNIQUE_JOIN)
|
|
72
|
+
def _bound_columns(join: ir.Join, matched: Side) -> Result[BoundColumns]:
|
|
73
|
+
"""The columns of `matched` an ON equality (or IS NOT DISTINCT FROM)
|
|
74
|
+
binds to the other input's column or to a constant."""
|
|
75
|
+
relation, other = (join.right, join.left) if matched == "right" else (join.left, join.right)
|
|
76
|
+
members = {}
|
|
77
|
+
definite = set()
|
|
78
|
+
for equality in join.conjuncts:
|
|
79
|
+
if not isinstance(equality, ir.Equality | ir.NullSafeEquality):
|
|
80
|
+
continue
|
|
81
|
+
for bound, value in ((equality.left, equality.right), (equality.right, equality.left)):
|
|
82
|
+
if bound is value:
|
|
83
|
+
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
|
+
|
|
107
|
+
evidence = Result(True, "Equality fixes the matched column for each row of the other input", (equality, column, value))
|
|
108
|
+
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:
|
|
113
|
+
definite.add(column)
|
|
114
|
+
members[column] = members[column] & non_null_column(value.column)
|
|
115
|
+
|
|
116
|
+
return Result(BoundColumns(relation, set(members), definite), "Bound columns", members=members)
|