sqlassert 0.3.3__py3-none-any.whl → 0.4.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sqlassert/__init__.py +1 -2
- sqlassert/check.py +88 -13
- sqlassert/declared_types.py +158 -0
- sqlassert/diagnostics.py +15 -7
- sqlassert/dialects.py +259 -107
- sqlassert/discovery/bigquery.py +4 -2
- sqlassert/discovery/databricks.py +26 -5
- sqlassert/discovery/duckdb.py +49 -7
- sqlassert/discovery/fetcher.py +137 -58
- sqlassert/discovery/information_schema.py +31 -6
- sqlassert/discovery/mysql.py +21 -4
- sqlassert/discovery/postgres.py +28 -20
- sqlassert/discovery/redshift.py +3 -2
- sqlassert/discovery/snowflake.py +5 -2
- sqlassert/discovery/trino.py +2 -2
- sqlassert/functions/__init__.py +10 -0
- sqlassert/functions/load.py +375 -0
- sqlassert/functions/table.py +2721 -0
- sqlassert/hazards.py +249 -88
- sqlassert/ir/__init__.py +15 -4
- sqlassert/ir/convert/__init__.py +13 -0
- sqlassert/ir/convert/aggregation.py +438 -0
- sqlassert/ir/convert/expressions.py +581 -0
- sqlassert/ir/convert/joins.py +264 -0
- sqlassert/ir/convert/markers.py +249 -0
- sqlassert/ir/convert/parser.py +249 -0
- sqlassert/ir/convert/queries.py +259 -0
- sqlassert/ir/convert/schema.py +537 -0
- sqlassert/ir/convert/scopes.py +205 -0
- sqlassert/ir/convert/selects.py +352 -0
- sqlassert/ir/convert/shared.py +428 -0
- sqlassert/ir/convert/sources.py +433 -0
- sqlassert/ir/convert/subqueries.py +364 -0
- sqlassert/ir/convert/value_types.py +78 -0
- sqlassert/ir/convert/windows.py +275 -0
- sqlassert/ir/model.py +417 -146
- sqlassert/ir/names.py +63 -0
- sqlassert/main.py +7 -10
- sqlassert/properties.py +12 -1
- sqlassert/provenance.py +5 -1
- sqlassert/python_engine.py +104 -44
- sqlassert/reporting.py +33 -32
- sqlassert/rewrites.py +111 -61
- 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 +564 -0
- sqlassert/rules/domain.py +9 -8
- sqlassert/rules/equality.py +6 -147
- sqlassert/rules/exactly_one.py +2 -1
- sqlassert/rules/foreign_key.py +8 -9
- sqlassert/rules/join_cardinality.py +277 -43
- sqlassert/rules/nullability.py +8 -8
- sqlassert/rules/uniqueness.py +212 -87
- sqlassert/rules/value_typing.py +470 -0
- sqlassert/sql_parse.py +28 -1
- sqlassert/suggest.py +13 -17
- sqlassert-0.4.2.dist-info/METADATA +239 -0
- sqlassert-0.4.2.dist-info/RECORD +72 -0
- sqlassert/ir/convert.py +0 -3509
- sqlassert-0.3.3.dist-info/METADATA +0 -807
- sqlassert-0.3.3.dist-info/RECORD +0 -46
- {sqlassert-0.3.3.dist-info → sqlassert-0.4.2.dist-info}/WHEEL +0 -0
- {sqlassert-0.3.3.dist-info → sqlassert-0.4.2.dist-info}/entry_points.txt +0 -0
- {sqlassert-0.3.3.dist-info → sqlassert-0.4.2.dist-info}/licenses/LICENSE +0 -0
- {sqlassert-0.3.3.dist-info → sqlassert-0.4.2.dist-info}/top_level.txt +0 -0
sqlassert/rules/equality.py
CHANGED
|
@@ -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
|
|
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
|
|
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
|
|
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, ...]:
|
sqlassert/rules/exactly_one.py
CHANGED
|
@@ -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.
|
sqlassert/rules/foreign_key.py
CHANGED
|
@@ -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().
|
|
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
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
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 a one-to-one
|
|
8
|
+
function of it is of (`-a.x`, `a.x + 1`, `a.x * 2` over exact numbers), to
|
|
9
|
+
such a value. Neither operand needs to be one-to-one to bind the other's column; the comparison must lose
|
|
10
|
+
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
|
|
25
|
+
from typing import Literal
|
|
18
26
|
|
|
19
27
|
from sqlassert import ir
|
|
20
|
-
from sqlassert.
|
|
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, fixes, reflected_column
|
|
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,274 @@ 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
|
|
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 a one-to-one function of it (`-a.x`, `a.x + 1`, `a.x * 2`) is of,
|
|
93
|
+
since that function takes that value at one column value only. Neither
|
|
94
|
+
needs the other to be one-to-one, but the comparison must fix the matched side (`fixes`).
|
|
95
|
+
"""
|
|
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
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
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))
|
|
106
|
+
fixed = reflected_column(bound)
|
|
107
|
+
column = fixed.value if fixed.value in relation.output_columns else None
|
|
108
|
+
inputs = ir.determinants(value)
|
|
109
|
+
if column is None or inputs is None or not all(read in other.output_columns for read in inputs):
|
|
110
|
+
continue
|
|
111
|
+
# A lossy cast pins nothing: '01' and '1' both equal 1.
|
|
112
|
+
if not fixes(bound, value).value:
|
|
113
|
+
continue
|
|
114
|
+
|
|
115
|
+
# A function of the column says why it is one-to-one.
|
|
116
|
+
through = [] if isinstance(bound.closed, ir.ColumnRef) else [fixed]
|
|
117
|
+
evidence = Result(True, "Equality fixes the matched column for each row of the other input", (equality, column, value), through)
|
|
108
118
|
members[column] = members[column] | evidence if column in members else evidence
|
|
109
|
-
|
|
110
|
-
|
|
119
|
+
equalities.add(equality)
|
|
120
|
+
# IS NOT DISTINCT FROM a value that is never NULL is `=`.
|
|
121
|
+
if isinstance(equality, ir.Equality) or (ir.total(value) and all(non_null_column(read).value for read in inputs)):
|
|
111
122
|
definite.add(column)
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
123
|
+
if not isinstance(equality, ir.Equality):
|
|
124
|
+
members[column] = all_of((members[column], *(non_null_column(read) for read in inputs)))
|
|
125
|
+
|
|
126
|
+
return Result(BoundColumns(relation, set(members), definite, equalities), "Bound columns", members=members)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
# Why a join has no proved Join Cardinality --------------------------------
|
|
130
|
+
|
|
131
|
+
type UnprovedReason = Literal["unsupported", "unconstrained", "unresolved-key", "untyped-key", "expression-key", "no-unique-set"]
|
|
132
|
+
type TypeLoss = Literal["values", "computed", "opaque-relation", "set-operation", "table", "type-mismatch"]
|
|
133
|
+
type NoUniqueSet = Literal["cascade", "partial-key", "undeclared-key"]
|
|
134
|
+
type _Operand = Literal["left", "right", "constant", "opaque", "both"]
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@dataclass(frozen=True)
|
|
138
|
+
class UnprovedJoin:
|
|
139
|
+
"""Why neither `many_to_one_join` nor `one_to_many_join` is proved for a
|
|
140
|
+
join: the first reason that applies, in the order of `UnprovedReason`.
|
|
141
|
+
|
|
142
|
+
- `unsupported`: an input is a source sqlassert does not model (LATERAL,
|
|
143
|
+
or a table function or UNNEST whose columns the dialect does not fix),
|
|
144
|
+
or the join is not reachable from the program: it sits in a SELECT that
|
|
145
|
+
lowered opaque.
|
|
146
|
+
- `unconstrained`: no ON equality relates one input to the other or to a
|
|
147
|
+
constant (a cross join, a range join). No Unique Set can make it a
|
|
148
|
+
Unique Join; whether rows repeat depends on the data, not on a key.
|
|
149
|
+
- `unresolved-key`: an operand of such an equality lowered opaque: a
|
|
150
|
+
column that does not resolve in its input, or an expression sqlassert
|
|
151
|
+
does not model.
|
|
152
|
+
- `untyped-key`: a column = column equality binds nothing, since the two
|
|
153
|
+
columns do not compare without a lossy coercion; `detail` names where
|
|
154
|
+
the type is lost (`TypeLoss`).
|
|
155
|
+
- `expression-key`: every such equality compares an expression, and none
|
|
156
|
+
binds a column (`_bound_columns`): the expression is not deterministic,
|
|
157
|
+
or has no type that fixes the other (`fixes`), or the
|
|
158
|
+
matched side is not a one-to-one function of one column
|
|
159
|
+
(`reflected_column`). `a.k = b.k % 2` is one, `a.k = b.k * 2` is not.
|
|
160
|
+
- `no-unique-set`: the equalities bind columns that reach the Row
|
|
161
|
+
Identity of neither input. `detail` says who can act, the first that
|
|
162
|
+
applies (`NoUniqueSet`):
|
|
163
|
+
`cascade`: something below an input is itself unproved or unsupported
|
|
164
|
+
(an upstream join with no proved Join Cardinality, through which no
|
|
165
|
+
Unique Set passes, or an unsupported construct), so fixing that may fix
|
|
166
|
+
this join; `construct` names the unsupported one, if any.
|
|
167
|
+
`partial-key`: the equalities bind a strict subset of a known Unique
|
|
168
|
+
Set of an input and every equality written binds a column; the rest of
|
|
169
|
+
ON is a range or inequality, so the join is as constrained as written.
|
|
170
|
+
`undeclared-key`: the bound side has no known Unique Set covering the
|
|
171
|
+
bound columns, a key the project could declare.
|
|
172
|
+
|
|
173
|
+
`construct` names the construct sqlassert does not support, when one
|
|
174
|
+
is behind the reason: the nearest one at or under the input, or the
|
|
175
|
+
relation, the reason points at; for a join in a SELECT that lowered
|
|
176
|
+
opaque, the one that made it so (`IrParser._name_orphan_joins`).
|
|
177
|
+
|
|
178
|
+
A diagnostic about a missing proof: it never changes what is proved."""
|
|
179
|
+
|
|
180
|
+
reason: UnprovedReason
|
|
181
|
+
detail: TypeLoss | NoUniqueSet | None = None
|
|
182
|
+
construct: str | None = None
|
|
183
|
+
# For `untyped-key`, the column where the type is lost.
|
|
184
|
+
untyped: ir.OutputColumn | None = field(default=None, compare=False)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def unproved_join(join: ir.Join, matched: Side | None = None) -> UnprovedJoin | None:
|
|
188
|
+
"""Why `join` has no proved Join Cardinality; None when it has one or is
|
|
189
|
+
a semi or anti join, which has none. With `matched`, why no row of the
|
|
190
|
+
other input is proved to match at most one row of that input (`right`:
|
|
191
|
+
why it is not many to one): the reasons that read an input's keys look
|
|
192
|
+
at that input alone. Runs inside an analysis session."""
|
|
193
|
+
if join.kind in {"semi", "anti"}:
|
|
194
|
+
return None
|
|
195
|
+
if join not in _reachable():
|
|
196
|
+
return UnprovedJoin("unsupported", construct=_unsupported_under(join))
|
|
197
|
+
directions: tuple[Side, ...] = ("right", "left") if matched is None else (matched,)
|
|
198
|
+
if any((many_to_one_join(join) if side == "right" else one_to_many_join(join)).value for side in directions):
|
|
199
|
+
return None
|
|
200
|
+
for relation in (join.left, join.right):
|
|
201
|
+
source = relation
|
|
202
|
+
while isinstance(source, ir.Alias):
|
|
203
|
+
source = source.source
|
|
204
|
+
if isinstance(source, ir.OpaqueRelation) and (construct := _unsupported_under(source)) is not None:
|
|
205
|
+
return UnprovedJoin("unsupported", construct=construct)
|
|
206
|
+
pairs = []
|
|
207
|
+
related = []
|
|
208
|
+
for equality in join.conjuncts:
|
|
209
|
+
if not isinstance(equality, ir.Equality | ir.NullSafeEquality):
|
|
210
|
+
continue
|
|
211
|
+
sides = (_operand(join, equality.left), _operand(join, equality.right))
|
|
212
|
+
if "both" not in sides and (sides[0] != sides[1] or sides[0] == "opaque"):
|
|
213
|
+
pairs.append((equality.left.closed, equality.right.closed, sides))
|
|
214
|
+
related.append(equality)
|
|
215
|
+
if not pairs:
|
|
216
|
+
return UnprovedJoin("unconstrained")
|
|
217
|
+
if any("opaque" in sides for _, _, sides in pairs):
|
|
218
|
+
return UnprovedJoin("unresolved-key", construct=_unsupported_under(join.left) or _unsupported_under(join.right))
|
|
219
|
+
for first, second, _ in pairs:
|
|
220
|
+
if isinstance(first, ir.ColumnRef) and isinstance(second, ir.ColumnRef) and not fixes(first, second).value:
|
|
221
|
+
for column in (first.column, second.column):
|
|
222
|
+
if (loss := _type_loss(column)) is not None:
|
|
223
|
+
construct = _unsupported_under(loss[1]) if loss[0] == "opaque-relation" else None
|
|
224
|
+
return UnprovedJoin("untyped-key", loss[0], construct, loss[2])
|
|
225
|
+
return UnprovedJoin("untyped-key", "type-mismatch")
|
|
226
|
+
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(
|
|
227
|
+
_bound_columns(join, side).value.columns for side in directions
|
|
228
|
+
):
|
|
229
|
+
return UnprovedJoin("expression-key")
|
|
230
|
+
return _no_unique_set(join, related, directions)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _no_unique_set(join: ir.Join, related: list[ir.ScalarExpr], sides: tuple[Side, ...]) -> UnprovedJoin:
|
|
234
|
+
"""Who can act on a join whose bound columns reach no Row Identity of
|
|
235
|
+
the `sides` asked about, from the IR and analyses it already ran: one
|
|
236
|
+
walk of each such input's tree, and the closures `_at_most_one_match`
|
|
237
|
+
took (`related`: its ON equalities that relate the inputs or an input to
|
|
238
|
+
a constant)."""
|
|
239
|
+
unproved, constructs = _cascade(join, tuple(sorted(sides)))
|
|
240
|
+
if unproved or any(constructs):
|
|
241
|
+
return UnprovedJoin("no-unique-set", "cascade", next(filter(None, constructs), None))
|
|
242
|
+
for matched in sides:
|
|
243
|
+
cols = _bound_columns(join, matched)
|
|
244
|
+
if not all(equality in cols.value.equalities for equality in related):
|
|
245
|
+
continue # An equality binds nothing here: not as constrained as written.
|
|
246
|
+
relation = join.right if matched == "right" else join.left
|
|
247
|
+
closure = _closure(relation, frozenset(cols.value.columns), frozenset(cols.value.definite))
|
|
248
|
+
if any(gap.reached for gap in _key_gaps(closure)):
|
|
249
|
+
return UnprovedJoin("no-unique-set", "partial-key")
|
|
250
|
+
return UnprovedJoin("no-unique-set", "undeclared-key")
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _cascade(join: ir.Join, sides: tuple[Side, ...] = ("left", "right")) -> tuple[bool, tuple[str | None, ...]]:
|
|
254
|
+
"""Whether a join below an input of `join` has no proved Join Cardinality
|
|
255
|
+
(a semi or anti join has none to prove), and the unsupported construct
|
|
256
|
+
nearest each input, in one walk of the two trees."""
|
|
257
|
+
unsupported = {id(node): construct for node, construct in current_arena().program.unsupported}
|
|
258
|
+
unproved = False
|
|
259
|
+
constructs = []
|
|
260
|
+
for relation in (join.left if side == "left" else join.right for side in sides):
|
|
261
|
+
nearest = None
|
|
262
|
+
for node in _tree(relation):
|
|
263
|
+
nearest = nearest or unsupported.get(id(node))
|
|
264
|
+
if isinstance(node, ir.Join) and node.kind not in {"semi", "anti"}:
|
|
265
|
+
unproved |= not (many_to_one_join(node).value or one_to_many_join(node).value)
|
|
266
|
+
constructs.append(nearest)
|
|
267
|
+
return unproved, tuple(constructs)
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _tree(relation: ir.RelationExpr) -> Iterator[ir.RelationExpr]:
|
|
271
|
+
"""`relation` and every relation it reads, nearest first, each once."""
|
|
272
|
+
pending, seen = [relation], set()
|
|
273
|
+
while pending:
|
|
274
|
+
node = pending.pop(0)
|
|
275
|
+
if id(node) in seen:
|
|
276
|
+
continue
|
|
277
|
+
seen.add(id(node))
|
|
278
|
+
yield node
|
|
279
|
+
pending.extend(child for child in ir.children(node) if isinstance(child, ir.RelationExpr))
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
@cache
|
|
283
|
+
def _reachable() -> frozenset[ir.Node]:
|
|
284
|
+
return frozenset(current_arena().program.nodes())
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _unsupported_under(relation: ir.RelationExpr) -> str | None:
|
|
288
|
+
"""The construct sqlassert does not support nearest to `relation`: its
|
|
289
|
+
own, else the first found reading down through its inputs."""
|
|
290
|
+
unsupported = {id(node): construct for node, construct in current_arena().program.unsupported}
|
|
291
|
+
return next((unsupported[id(node)] for node in _tree(relation) if id(node) in unsupported), None) if unsupported else None
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def _operand(join: ir.Join, expression: ir.ScalarExpr) -> _Operand:
|
|
295
|
+
"""Which input an equality operand reads: `opaque` when nothing is known
|
|
296
|
+
of it, `constant` when it reads neither (an outer column is fixed for
|
|
297
|
+
the join too)."""
|
|
298
|
+
sides = set()
|
|
299
|
+
pending = [expression]
|
|
300
|
+
while pending:
|
|
301
|
+
match node := pending.pop():
|
|
302
|
+
case ir.OpaqueExpression():
|
|
303
|
+
return "opaque"
|
|
304
|
+
case ir.ColumnRef(column=column):
|
|
305
|
+
if column in join.left.output_columns:
|
|
306
|
+
sides.add("left")
|
|
307
|
+
elif column in join.right.output_columns:
|
|
308
|
+
sides.add("right")
|
|
309
|
+
case _:
|
|
310
|
+
pending.extend(child for child in ir.children(node) if isinstance(child, ir.ScalarExpr))
|
|
311
|
+
match sorted(sides):
|
|
312
|
+
case []:
|
|
313
|
+
return "constant"
|
|
314
|
+
case ["left"]:
|
|
315
|
+
return "left"
|
|
316
|
+
case ["right"]:
|
|
317
|
+
return "right"
|
|
318
|
+
case _:
|
|
319
|
+
return "both"
|
|
320
|
+
|
|
115
321
|
|
|
116
|
-
|
|
322
|
+
def _type_loss(column: ir.OutputColumn) -> tuple[TypeLoss, ir.RelationExpr, ir.OutputColumn] | None:
|
|
323
|
+
"""Where `column` loses the type equality needs to bind it, following
|
|
324
|
+
plain column references (and set operation arms, only the base case's for a
|
|
325
|
+
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
|
|
326
|
+
type (no CREATE, or none in the catalog), else the kind of relation or
|
|
327
|
+
expression that computes it without a type compared by identity. None
|
|
328
|
+
when that column keeps its type. With the relation that column is of."""
|
|
329
|
+
relation = column.get_relation(current_arena().program)
|
|
330
|
+
if isinstance(relation, ir.SetOperation):
|
|
331
|
+
arms = relation.arms(column)
|
|
332
|
+
if arms is None:
|
|
333
|
+
return "set-operation", relation, column
|
|
334
|
+
return _type_loss(arms[0]) if relation.recursive else _type_loss(arms[0]) or _type_loss(arms[1])
|
|
335
|
+
if isinstance(relation, ir.RecursiveRelation) and relation.typed_by and (base := relation.typed_by[relation.output_columns.index(column)]):
|
|
336
|
+
return _type_loss(base)
|
|
337
|
+
match column.scalar_expr:
|
|
338
|
+
case ir.ColumnRef(column=source) | ir.AnyAggregate(input=ir.ColumnRef(column=source)):
|
|
339
|
+
return _type_loss(source)
|
|
340
|
+
typed = _comparison_type(column).value is not None
|
|
341
|
+
if isinstance(relation, ir.NamedRelation) and relation.role is ir.RelationRole.TABLE:
|
|
342
|
+
# A declared type that does not compare by identity is the type, not a loss.
|
|
343
|
+
return None if typed else ("table", relation, column)
|
|
344
|
+
if typed and _identity_comparison(column).value:
|
|
345
|
+
return None
|
|
346
|
+
if isinstance(relation, ir.ValuesList):
|
|
347
|
+
return "values", relation, column
|
|
348
|
+
if isinstance(relation, ir.OpaqueRelation) or isinstance(column.scalar_expr, ir.OpaqueExpression):
|
|
349
|
+
return "opaque-relation", relation, column
|
|
350
|
+
return "computed", relation, column
|