sqlassert 0.3.1__py3-none-any.whl → 0.3.3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sqlassert/__main__.py +2 -131
- sqlassert/check.py +10 -3
- sqlassert/diagnostics.py +19 -6
- sqlassert/dialects.py +69 -22
- sqlassert/discovery/duckdb.py +12 -16
- sqlassert/discovery/fetcher.py +45 -29
- sqlassert/discovery/information_schema.py +4 -3
- sqlassert/discovery/postgres.py +6 -7
- sqlassert/edits.py +240 -0
- sqlassert/hazards.py +574 -0
- sqlassert/ir/__init__.py +3 -1
- sqlassert/ir/convert.py +1315 -183
- sqlassert/ir/model.py +128 -25
- sqlassert/main.py +3 -9
- sqlassert/python_engine.py +63 -6
- sqlassert/reporting.py +3 -0
- sqlassert/rewrites.py +1541 -0
- sqlassert/rules/domain.py +117 -21
- sqlassert/rules/equality.py +238 -29
- sqlassert/rules/exactly_one.py +40 -1
- sqlassert/rules/foreign_key.py +7 -4
- sqlassert/rules/join_cardinality.py +33 -11
- sqlassert/rules/nullability.py +239 -30
- sqlassert/rules/uniqueness.py +355 -52
- sqlassert/sql_parse.py +196 -89
- sqlassert/suggest.py +127 -48
- {sqlassert-0.3.1.dist-info → sqlassert-0.3.3.dist-info}/METADATA +121 -39
- sqlassert-0.3.3.dist-info/RECORD +46 -0
- sqlassert-0.3.3.dist-info/entry_points.txt +2 -0
- sqlassert-0.3.3.dist-info/top_level.txt +2 -0
- sqlassert_cli.py +130 -0
- sqlassert/improvements.py +0 -528
- sqlassert/smells.py +0 -306
- 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.3.3.dist-info}/WHEEL +0 -0
- {sqlassert-0.3.1.dist-info → sqlassert-0.3.3.dist-info}/licenses/LICENSE +0 -0
sqlassert/rules/exactly_one.py
CHANGED
|
@@ -7,12 +7,19 @@ left columns, as one tuple, onto the right columns they are paired with: a
|
|
|
7
7
|
row of the right input carrying every left value then satisfies the whole ON.
|
|
8
8
|
Coverage of each column separately does not give a row matching all of them.
|
|
9
9
|
Any other conjunct may reject the covering row, so matching stays unknown.
|
|
10
|
+
`IS NOT DISTINCT FROM` pairs columns too: with the left columns non-null it
|
|
11
|
+
is `=`, and a NULL left value would match every right row whose column is
|
|
12
|
+
NULL (UNIQUE allows many), so non-null left columns stay required.
|
|
13
|
+
An ON that is always TRUE (none, for a CROSS JOIN) matches every right row,
|
|
14
|
+
so a right input that always has a row (a scalar aggregate) is matched.
|
|
10
15
|
Non-null left columns: a null equals nothing, and `MATCH SIMPLE` exempts a
|
|
11
16
|
row with any null referencing component. The input relations may be derived:
|
|
12
17
|
coverage, uniqueness and nullability each follow their own propagation, and
|
|
13
18
|
coverage onto a narrowed right input must hold on its own.
|
|
14
19
|
"""
|
|
15
20
|
|
|
21
|
+
from typing import assert_never
|
|
22
|
+
|
|
16
23
|
from sqlassert import ir
|
|
17
24
|
from sqlassert.python_engine import Result, Stratum, analysis, all_of, unknown
|
|
18
25
|
from sqlassert.rules.foreign_key import referential_coverage
|
|
@@ -27,6 +34,10 @@ def exactly_one_join(join: ir.Join) -> Result[bool]:
|
|
|
27
34
|
if join.kind == "anti":
|
|
28
35
|
return unknown("An anti join drops the rows it matches", join)
|
|
29
36
|
at_most_one = _half("At most one match: the right predicate columns cover a Unique Set", (join,), many_to_one_join(join))
|
|
37
|
+
if all(_is_true(conjunct) for conjunct in join.conjuncts):
|
|
38
|
+
return at_most_one & _half(
|
|
39
|
+
"At least one match: ON is always TRUE, and the right input has a row", (join,), _has_a_row(join.right),
|
|
40
|
+
)
|
|
30
41
|
pairs, others = _cross_equalities(join)
|
|
31
42
|
if not pairs:
|
|
32
43
|
return at_most_one & unknown(
|
|
@@ -49,6 +60,29 @@ def exactly_one_join(join: ir.Join) -> Result[bool]:
|
|
|
49
60
|
))
|
|
50
61
|
|
|
51
62
|
|
|
63
|
+
def _is_true(conjunct: ir.ScalarExpr) -> bool:
|
|
64
|
+
return isinstance(conjunct, ir.Constant) and conjunct.value == ir.LiteralValue(type="boolean", text="TRUE")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _has_a_row(relation: ir.RelationExpr) -> Result[bool]:
|
|
68
|
+
"""Whether `relation` has at least one row on every instance: an
|
|
69
|
+
aggregate grouped by nothing has one even over no input rows, and an
|
|
70
|
+
Alias, Project or DISTINCT keeps it. HAVING (a Filter) may drop it."""
|
|
71
|
+
relation = relation.closed
|
|
72
|
+
match relation:
|
|
73
|
+
case ir.Aggregate(grouping_outputs=()):
|
|
74
|
+
return Result(True, "An aggregate grouped by nothing has one row, even over no input rows", (relation,))
|
|
75
|
+
case ir.Alias(source=source) | ir.NamedRelation(body=ir.RelationExpr() as source) | ir.Project(input=source) | ir.Distinct(input=source):
|
|
76
|
+
return _has_a_row(source)
|
|
77
|
+
case (
|
|
78
|
+
ir.Aggregate() | ir.NamedRelation() | ir.Join() | ir.Filter() | ir.Limit() | ir.SetOperation()
|
|
79
|
+
| ir.QualifyByPartition() | ir.OpaqueRelation() | ir.RecursiveRelation()
|
|
80
|
+
):
|
|
81
|
+
return unknown("The right input may have no rows", relation)
|
|
82
|
+
case _:
|
|
83
|
+
assert_never(relation)
|
|
84
|
+
|
|
85
|
+
|
|
52
86
|
def _half(reason: str, subjects: tuple[object, ...], evidence: Result[bool]) -> Result[bool]:
|
|
53
87
|
return Result(evidence.value, reason, subjects, [evidence], kind="all")
|
|
54
88
|
|
|
@@ -61,7 +95,12 @@ def _cross_equalities(
|
|
|
61
95
|
others: list[ir.ScalarExpr] = []
|
|
62
96
|
for conjunct in join.conjuncts:
|
|
63
97
|
match conjunct:
|
|
64
|
-
|
|
98
|
+
# IS NOT DISTINCT FROM matches NULL to NULL, but the left columns
|
|
99
|
+
# must be non-null anyway, and then it is `=`.
|
|
100
|
+
case (
|
|
101
|
+
ir.Equality(left=ir.ColumnRef(column=first), right=ir.ColumnRef(column=second))
|
|
102
|
+
| ir.NullSafeEquality(left=ir.ColumnRef(column=first), right=ir.ColumnRef(column=second))
|
|
103
|
+
):
|
|
65
104
|
pair = next((
|
|
66
105
|
(left, right) for left, right in ((first, second), (second, first))
|
|
67
106
|
if left in join.left.output_columns and right in join.right.output_columns
|
sqlassert/rules/foreign_key.py
CHANGED
|
@@ -21,6 +21,7 @@ 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
26
|
from sqlassert.properties import ReferentialCoverage
|
|
26
27
|
from sqlassert.python_engine import Result, Stratum, analysis, any_of, current_arena, unknown
|
|
@@ -72,8 +73,10 @@ def _targets(referenced_columns: _Columns) -> list[tuple[_Columns, list[Result[b
|
|
|
72
73
|
assert target is not None
|
|
73
74
|
match target:
|
|
74
75
|
case ir.SetOperation(operator="union"):
|
|
75
|
-
|
|
76
|
-
|
|
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)))
|
|
77
80
|
reason = "A UNION keeps every row of each branch"
|
|
78
81
|
case _:
|
|
79
82
|
kept = [_kept(target, column) for column in referenced_columns]
|
|
@@ -146,7 +149,7 @@ def _input_rows(
|
|
|
146
149
|
alternatives: dict[_Columns, Result[bool]] = {}
|
|
147
150
|
for chosen in product(*(sorted(group.value, key=order.__getitem__) for group in equal)):
|
|
148
151
|
substituted = [
|
|
149
|
-
Result(True, f"{column.name} equals {stand_in.name} on every row where it is non-null", (column, stand_in), [group])
|
|
152
|
+
Result(True, f"{quoted(column.name)} equals {quoted(stand_in.name)} on every row where it is non-null", (column, stand_in), [group])
|
|
150
153
|
for column, stand_in, group in zip(columns, chosen, equal) if stand_in is not column
|
|
151
154
|
]
|
|
152
155
|
for target, widened in targets:
|
|
@@ -304,7 +307,7 @@ def _key(coverage: ReferentialCoverage) -> tuple:
|
|
|
304
307
|
|
|
305
308
|
|
|
306
309
|
def _names(columns: _Columns) -> str:
|
|
307
|
-
return
|
|
310
|
+
return quoted_all(column.name for column in columns)
|
|
308
311
|
|
|
309
312
|
|
|
310
313
|
def _describe(columns: _Columns) -> str:
|
|
@@ -3,19 +3,24 @@
|
|
|
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
5
|
column an ON equality binds to the first row's column or to a constant, all
|
|
6
|
-
non-null.
|
|
7
|
-
|
|
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
|
|
8
11
|
conjuncts: the other input must have at most one row. A semi or anti join
|
|
9
12
|
keeps or drops left rows whole and outputs no right row; its left rows are
|
|
10
13
|
never repeated (`many_to_one_join`), and no cardinality marker applies to it.
|
|
11
14
|
"""
|
|
12
15
|
|
|
16
|
+
from dataclasses import dataclass, field
|
|
13
17
|
from typing import Literal, assert_never
|
|
14
18
|
|
|
15
19
|
from sqlassert import ir
|
|
16
20
|
from sqlassert.python_engine import Result, Stratum, all_of, any_of, analysis
|
|
17
|
-
from sqlassert.rules.column_set import ColumnSet
|
|
21
|
+
from sqlassert.rules.column_set import Attribute, ColumnSet
|
|
18
22
|
from sqlassert.rules.equality import _pins
|
|
23
|
+
from sqlassert.rules.nullability import non_null_column
|
|
19
24
|
from sqlassert.rules.uniqueness import _closure, _reaches_row_identity
|
|
20
25
|
|
|
21
26
|
type Side = Literal["left", "right"]
|
|
@@ -49,18 +54,29 @@ def _at_most_one_match(join: ir.Join, matched: Side) -> Result[bool]:
|
|
|
49
54
|
relation = join.right if matched == "right" else join.left
|
|
50
55
|
cols = _bound_columns(join, matched)
|
|
51
56
|
bound = frozenset(cols.value.columns)
|
|
52
|
-
reached = _reaches_row_identity(_closure(relation, bound,
|
|
57
|
+
reached = _reaches_row_identity(_closure(relation, bound, frozenset(cols.value.definite)))
|
|
53
58
|
reason = "Right columns bound for each left row" if matched == "right" else "Left columns bound for each right row"
|
|
54
59
|
return all_of((Result(True, reason, (join,), list(cols.members.values())), reached))
|
|
55
60
|
|
|
56
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
|
+
|
|
57
71
|
@analysis(Stratum.UNIQUE_JOIN)
|
|
58
|
-
def _bound_columns(join: ir.Join, matched: Side) -> Result[
|
|
59
|
-
"""The columns of `matched` an ON equality
|
|
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."""
|
|
60
75
|
relation, other = (join.right, join.left) if matched == "right" else (join.left, join.right)
|
|
61
76
|
members = {}
|
|
77
|
+
definite = set()
|
|
62
78
|
for equality in join.conjuncts:
|
|
63
|
-
if not isinstance(equality, ir.Equality):
|
|
79
|
+
if not isinstance(equality, ir.Equality | ir.NullSafeEquality):
|
|
64
80
|
continue
|
|
65
81
|
for bound, value in ((equality.left, equality.right), (equality.right, equality.left)):
|
|
66
82
|
if bound is value:
|
|
@@ -70,7 +86,7 @@ def _bound_columns(join: ir.Join, matched: Side) -> Result[ColumnSet]:
|
|
|
70
86
|
case ir.ColumnRef(column=column):
|
|
71
87
|
if column not in relation.output_columns:
|
|
72
88
|
continue
|
|
73
|
-
case ir.Constant() | 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():
|
|
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():
|
|
74
90
|
continue
|
|
75
91
|
case _:
|
|
76
92
|
assert_never(bound)
|
|
@@ -83,12 +99,18 @@ def _bound_columns(join: ir.Join, matched: Side) -> Result[ColumnSet]:
|
|
|
83
99
|
case ir.ColumnRef(column=other_column):
|
|
84
100
|
if other_column not in other.output_columns or not _pins(column, value):
|
|
85
101
|
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():
|
|
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():
|
|
87
103
|
continue
|
|
88
104
|
case _:
|
|
89
105
|
assert_never(value)
|
|
90
106
|
|
|
91
107
|
evidence = Result(True, "Equality fixes the matched column for each row of the other input", (equality, column, value))
|
|
92
108
|
members[column] = members[column] | evidence if column in members else evidence
|
|
93
|
-
|
|
94
|
-
|
|
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)
|
sqlassert/rules/nullability.py
CHANGED
|
@@ -14,6 +14,7 @@ from __future__ import annotations
|
|
|
14
14
|
from dataclasses import dataclass
|
|
15
15
|
from typing import assert_never
|
|
16
16
|
|
|
17
|
+
from sqlassert.diagnostics import quoted
|
|
17
18
|
from sqlassert import ir
|
|
18
19
|
from sqlassert.properties import NonNullElements
|
|
19
20
|
from sqlassert.python_engine import Result, Stratum, all_of, analysis, any_of, current_arena, unknown
|
|
@@ -60,7 +61,7 @@ def non_null_columns(columns: frozenset[ir.OutputColumn]) -> Result[bool]:
|
|
|
60
61
|
def non_null_column(column: ir.OutputColumn) -> Result[bool]:
|
|
61
62
|
sources = _null_sources(column)
|
|
62
63
|
if sources.value:
|
|
63
|
-
return Result(False, f"{column.name} may be NULL", (column,), list(sources.members.values()), kind="unknown")
|
|
64
|
+
return Result(False, f"{quoted(column.name)} may be NULL", (column,), list(sources.members.values()), kind="unknown")
|
|
64
65
|
return Result(True, "No NULL source remains", (column,), [sources])
|
|
65
66
|
|
|
66
67
|
|
|
@@ -79,7 +80,7 @@ def _output_sources(relation: ir.RelationExpr, column: ir.OutputColumn) -> tuple
|
|
|
79
80
|
relation = relation.closed
|
|
80
81
|
match relation:
|
|
81
82
|
case ir.NamedRelation(body=None):
|
|
82
|
-
return {ORGANIC: unknown(f"{column.name} is nullable in {relation.name}", relation, column)}, []
|
|
83
|
+
return {ORGANIC: unknown(f"{quoted(column.name)} is nullable in {relation.name}", relation, column)}, []
|
|
83
84
|
case ir.OpaqueRelation():
|
|
84
85
|
return {ORGANIC: unknown("Nullability of an opaque relation's columns is not known", relation, column)}, []
|
|
85
86
|
case ir.SetOperation():
|
|
@@ -104,6 +105,14 @@ def _output_sources(relation: ir.RelationExpr, column: ir.OutputColumn) -> tuple
|
|
|
104
105
|
assert_never(relation)
|
|
105
106
|
|
|
106
107
|
|
|
108
|
+
def _non_null_expression(expression: ir.ScalarExpr) -> Result[bool]:
|
|
109
|
+
"""Whether `expression` is non-null on every row of the relation computing it."""
|
|
110
|
+
sources, premises = _expression_sources(expression)
|
|
111
|
+
if sources:
|
|
112
|
+
return Result(False, "It may be NULL", (expression,), list(sources.values()), kind="unknown")
|
|
113
|
+
return Result(True, "No NULL source remains", (expression,), premises)
|
|
114
|
+
|
|
115
|
+
|
|
107
116
|
def _expression_sources(expression: ir.ScalarExpr) -> tuple[_Sources, list[Result]]:
|
|
108
117
|
expression = expression.closed
|
|
109
118
|
match expression:
|
|
@@ -116,22 +125,41 @@ def _expression_sources(expression: ir.ScalarExpr) -> tuple[_Sources, list[Resul
|
|
|
116
125
|
return {}, [Result(True, "count(...) is never NULL", (expression,))]
|
|
117
126
|
case ir.NullLiteral():
|
|
118
127
|
return {ORGANIC: unknown("A NULL literal is null", expression)}, []
|
|
119
|
-
case ir.Coalesce(arguments=arguments):
|
|
128
|
+
case ir.Coalesce(arguments=arguments) | ir.Call(function=ir.Builtin(skips_null=True), arguments=arguments):
|
|
120
129
|
# Null only when every argument is, so one non-null argument suffices.
|
|
130
|
+
name = expression.function.name if isinstance(expression, ir.Call) else "coalesce"
|
|
121
131
|
arguments_sources = [_expression_sources(argument) for argument in arguments]
|
|
122
132
|
for sources, premises in arguments_sources:
|
|
123
133
|
if not sources:
|
|
124
|
-
return {}, [Result(True, "
|
|
134
|
+
return {}, [Result(True, f"{name} is non-null when any argument is", (expression,), premises)]
|
|
135
|
+
# A FULL JOIN pads its two sides on different rows: an argument NULL
|
|
136
|
+
# only on its left padding and one NULL only on its right padding
|
|
137
|
+
# are never NULL together (a FULL JOIN ... USING column).
|
|
138
|
+
# Seen through the same Aliases: one row of that join, not two copies of it.
|
|
139
|
+
sides = [
|
|
140
|
+
source for sources, _ in arguments_sources if len(sources) == 1
|
|
141
|
+
for source in sources if isinstance(source, Padding) and source.join.kind == "full"
|
|
142
|
+
]
|
|
143
|
+
for first in sides:
|
|
144
|
+
for second in sides:
|
|
145
|
+
if isinstance(first, Padding) and isinstance(second, Padding) and first.join is second.join and (
|
|
146
|
+
first.aliases == second.aliases and first.left != second.left
|
|
147
|
+
):
|
|
148
|
+
reason = "Coalesce of the two sides a FULL JOIN pads on different rows is never NULL"
|
|
149
|
+
return {}, [Result(True, reason, (expression, first.join))]
|
|
125
150
|
# NULL on a join's padded rows only if every argument is.
|
|
126
151
|
common = set.intersection(*({s for s in sources if isinstance(s, Padding)} for sources, _ in arguments_sources))
|
|
127
152
|
first, _ = arguments_sources[0]
|
|
128
153
|
result: _Sources = {source: first[source] for source in common}
|
|
129
154
|
if any(set(sources) - common for sources, _ in arguments_sources):
|
|
130
155
|
evidence = [evidence for sources, _ in arguments_sources for evidence in sources.values()]
|
|
131
|
-
result[ORGANIC] = Result(False, "Every
|
|
156
|
+
result[ORGANIC] = Result(False, f"Every {name} argument may be NULL", (expression,), evidence, kind="unknown")
|
|
132
157
|
return result, []
|
|
133
|
-
case ir.AnyAggregate(
|
|
134
|
-
|
|
158
|
+
case ir.AnyAggregate(empty=True) | ir.Accumulation(empty=True):
|
|
159
|
+
return {ORGANIC: unknown("An aggregate grouped by nothing is NULL over no rows", expression)}, []
|
|
160
|
+
case ir.AnyAggregate(input=value) | ir.Accumulation(input=value):
|
|
161
|
+
# Groups are never empty, so the value comes from some input row,
|
|
162
|
+
# NULL only when the rows' values are.
|
|
135
163
|
return _expression_sources(value)
|
|
136
164
|
case ir.Call(total_arguments=tuple() as arguments, description=description):
|
|
137
165
|
# NULL only when an argument it is total in is, so only through
|
|
@@ -157,7 +185,21 @@ def _expression_sources(expression: ir.ScalarExpr) -> tuple[_Sources, list[Resul
|
|
|
157
185
|
if elements.value:
|
|
158
186
|
return {}, [Result(True, "No element is NULL", (expression,), [elements])]
|
|
159
187
|
return {ORGANIC: Result(False, "An element may be NULL", (expression,), [elements], kind="unknown")}, []
|
|
160
|
-
case ir.
|
|
188
|
+
case ir.IsNull() | ir.IsNotNull() | ir.NullSafeEquality():
|
|
189
|
+
return {}, [Result(True, "The IS family is never NULL", (expression,))]
|
|
190
|
+
case ir.Equality(total=True, left=left, right=right):
|
|
191
|
+
# NULL exactly when a side is: strict and total in both.
|
|
192
|
+
result: _Sources = {}
|
|
193
|
+
premises: list[Result] = []
|
|
194
|
+
for side in (left, right):
|
|
195
|
+
sources, side_premises = _expression_sources(side)
|
|
196
|
+
for source, evidence in sources.items():
|
|
197
|
+
result[source] = result[source] | evidence if source in result else evidence
|
|
198
|
+
premises.extend(side_premises)
|
|
199
|
+
if result:
|
|
200
|
+
return result, []
|
|
201
|
+
return {}, [Result(True, "= is non-null when its operands are", (expression,), premises)]
|
|
202
|
+
case ir.Equality() | ir.InList() | ir.And() | ir.Or():
|
|
161
203
|
return {ORGANIC: unknown("Nullability of a comparison is not inferred", expression)}, []
|
|
162
204
|
case ir.SimpleCase():
|
|
163
205
|
return _case_sources(expression)
|
|
@@ -188,7 +230,7 @@ def _column_elements(column: ir.OutputColumn) -> Result[bool]:
|
|
|
188
230
|
return unknown("The set operation's inputs are not paired by position", relation, column)
|
|
189
231
|
return all_of(_column_elements(arm) for arm in arms if arm is not None)
|
|
190
232
|
if isinstance(column.scalar_expr.closed, ir.OpaqueExpression):
|
|
191
|
-
return unknown(f"{column.name} may hold a NULL element (DECLARE NOT NULL ELEMENTS({column.name}) states it does not)", column)
|
|
233
|
+
return unknown(f"{quoted(column.name)} may hold a NULL element (DECLARE NOT NULL ELEMENTS({column.name}) states it does not)", column)
|
|
192
234
|
return _expression_elements(column.scalar_expr)
|
|
193
235
|
|
|
194
236
|
|
|
@@ -206,8 +248,8 @@ def _expression_elements(expression: ir.ScalarExpr) -> Result[bool]:
|
|
|
206
248
|
case ir.SimpleCase(thens=thens, default=default):
|
|
207
249
|
return all_of(_expression_elements(arm) for arm in (*thens, default))
|
|
208
250
|
case (
|
|
209
|
-
ir.Constant() | ir.Count() | ir.Call() | ir.OpaqueExpression() | ir.OpaquePureFunction() | ir.Elements()
|
|
210
|
-
| ir.Equality() | ir.InList() | ir.IsNull() | ir.IsNotNull() | ir.And() | ir.Or()
|
|
251
|
+
ir.Constant() | ir.Count() | ir.Accumulation() | ir.Call() | ir.OpaqueExpression() | ir.OpaquePureFunction() | ir.Elements()
|
|
252
|
+
| ir.Equality() | ir.NullSafeEquality() | ir.InList() | ir.IsNull() | ir.IsNotNull() | ir.And() | ir.Or()
|
|
211
253
|
):
|
|
212
254
|
return unknown("Its elements may be NULL", expression)
|
|
213
255
|
case _:
|
|
@@ -268,10 +310,12 @@ def _join_sources(join: ir.Join, column: ir.OutputColumn) -> tuple[_Sources, lis
|
|
|
268
310
|
pass
|
|
269
311
|
case _:
|
|
270
312
|
raise TypeError(f"Join column {column.name} is not a pass-through")
|
|
271
|
-
sources, removal = _rejected(
|
|
313
|
+
sources, removal = _rejected(
|
|
314
|
+
_on_rejected(join), _on_rejected_paddings(join), source, sources, "The ON condition rejects NULL on matched rows"
|
|
315
|
+
)
|
|
272
316
|
left = source in join.left.output_columns
|
|
273
317
|
if left in _padded_sides(join):
|
|
274
|
-
sources[Padding(join, left)] = unknown(f"{column.name} is padded by the {join.kind.upper()} JOIN", join, column)
|
|
318
|
+
sources[Padding(join, left)] = unknown(f"{quoted(column.name)} is padded by the {join.kind.upper()} JOIN", join, column)
|
|
275
319
|
return sources, premises + removal
|
|
276
320
|
|
|
277
321
|
|
|
@@ -291,17 +335,17 @@ def _set_operation_sources(relation: ir.SetOperation, column: ir.OutputColumn) -
|
|
|
291
335
|
assert right is not None
|
|
292
336
|
if not left.value and not right.value:
|
|
293
337
|
return {}, [Result(True, "Non-null in both inputs of the UNION", (relation, column), [left, right])]
|
|
294
|
-
return {ORGANIC: Result(False, f"{column.name} may be NULL in an input of the UNION", (relation, column), [left, right], kind="unknown")}, []
|
|
338
|
+
return {ORGANIC: Result(False, f"{quoted(column.name)} may be NULL in an input of the UNION", (relation, column), [left, right], kind="unknown")}, []
|
|
295
339
|
case "intersect":
|
|
296
340
|
assert right is not None
|
|
297
341
|
for arm in (left, right):
|
|
298
342
|
if not arm.value:
|
|
299
343
|
return {}, [Result(True, "Non-null in one input of the INTERSECT, which every row equals", (relation, column), [arm])]
|
|
300
|
-
return {ORGANIC: Result(False, f"{column.name} may be NULL in both inputs of the INTERSECT", (relation, column), [left, right], kind="unknown")}, []
|
|
344
|
+
return {ORGANIC: Result(False, f"{quoted(column.name)} may be NULL in both inputs of the INTERSECT", (relation, column), [left, right], kind="unknown")}, []
|
|
301
345
|
case "except":
|
|
302
346
|
if not left.value:
|
|
303
347
|
return {}, [Result(True, "Non-null in the left input of the EXCEPT", (relation, column), [left])]
|
|
304
|
-
return {ORGANIC: Result(False, f"{column.name} may be NULL in the left input of the EXCEPT", (relation, column), [left], kind="unknown")}, []
|
|
348
|
+
return {ORGANIC: Result(False, f"{quoted(column.name)} may be NULL in the left input of the EXCEPT", (relation, column), [left], kind="unknown")}, []
|
|
305
349
|
case _:
|
|
306
350
|
assert_never(relation.operator)
|
|
307
351
|
|
|
@@ -321,37 +365,166 @@ def _filter_sources(relation: ir.Filter, column: ir.OutputColumn) -> tuple[_Sour
|
|
|
321
365
|
pass
|
|
322
366
|
case _:
|
|
323
367
|
raise TypeError(f"Filter column {column.name} is not a pass-through")
|
|
324
|
-
sources, removal = _rejected(
|
|
368
|
+
sources, removal = _rejected(
|
|
369
|
+
_null_rejected(relation.conjuncts), _rejected_paddings(relation.conjuncts), source, sources, "The WHERE clause rejects NULL"
|
|
370
|
+
)
|
|
325
371
|
return sources, premises + removal
|
|
326
372
|
|
|
327
373
|
|
|
328
374
|
def _rejected(
|
|
329
|
-
rejected: dict[ir.OutputColumn, ir.ScalarExpr],
|
|
375
|
+
rejected: dict[ir.OutputColumn, ir.ScalarExpr], paddings: dict[Padding, ir.ScalarExpr],
|
|
376
|
+
source: ir.OutputColumn, sources: _Sources, reason: str,
|
|
330
377
|
) -> tuple[_Sources, list[Result]]:
|
|
331
|
-
"""`sources` once the rows
|
|
378
|
+
"""`sources` once the rows a condition rejects are gone.
|
|
332
379
|
|
|
333
|
-
A rejected column loses its organic NULLs, and
|
|
334
|
-
|
|
380
|
+
A rejected column loses its organic NULLs, and so does one passing on a
|
|
381
|
+
column whose NULL would make a rejected one NULL on the same row
|
|
382
|
+
(`_row_lineage`): `WHERE q.ms > 0` with `ms = mgr + sal` rejects `q.mgr`.
|
|
383
|
+
Every rejected padding (`_rejected_paddings`) is proved matched, so it
|
|
384
|
+
goes from every column.
|
|
335
385
|
"""
|
|
336
386
|
sources = dict(sources)
|
|
337
387
|
removal = []
|
|
338
|
-
if
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
388
|
+
if ORGANIC in sources:
|
|
389
|
+
passed = _row_lineage(source, pass_through=True)
|
|
390
|
+
conjunct = next((c for column, c in rejected.items() if passed & _row_lineage(column)), None)
|
|
391
|
+
if conjunct is not None:
|
|
392
|
+
del sources[ORGANIC]
|
|
393
|
+
removal.append(Result(True, reason, (conjunct, source)))
|
|
394
|
+
for padding, conjunct in paddings.items():
|
|
395
|
+
if padding in sources:
|
|
396
|
+
del sources[padding]
|
|
397
|
+
removal.append(Result(True, f"{reason}, so the padding join matched", (conjunct, padding.join)))
|
|
346
398
|
return sources, removal
|
|
347
399
|
|
|
348
400
|
|
|
401
|
+
type _RowColumn = tuple[ir.OutputColumn, tuple[ir.Alias, ...]]
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def _row_lineage(column: ir.OutputColumn, *, pass_through: bool = False, aliases: tuple[ir.Alias, ...] = ()) -> frozenset[_RowColumn]:
|
|
405
|
+
"""`column` and the columns below it, on the one input row its value is
|
|
406
|
+
computed from, whose NULL makes it NULL (strict inputs), or that it equals
|
|
407
|
+
(`pass_through`); each with the Aliases of Named Relations it was reached
|
|
408
|
+
through, so two occurrences of a view or CTE never share a row.
|
|
409
|
+
|
|
410
|
+
Followed down through the relations that compute a row from one row of
|
|
411
|
+
each input: not through an aggregate (a group's rows), a set operation
|
|
412
|
+
(its columns name its left input's), or an expression reading columns of
|
|
413
|
+
no direct input (a correlated one). Apart from Named Relations, which
|
|
414
|
+
each occurrence enters through its own Alias, the IR is a tree (`Program`
|
|
415
|
+
checks it), so two columns of one relation reaching one column with the
|
|
416
|
+
same Aliases reach it on the same row.
|
|
417
|
+
"""
|
|
418
|
+
relation = column.get_relation(current_arena().program).closed
|
|
419
|
+
match relation:
|
|
420
|
+
case ir.Alias(source=ir.NamedRelation()):
|
|
421
|
+
below_aliases = (*aliases, relation)
|
|
422
|
+
case ir.Alias() | ir.NamedRelation() | ir.Project() | ir.Filter() | ir.Limit() | ir.Distinct() | ir.QualifyByPartition() | ir.Join():
|
|
423
|
+
below_aliases = aliases
|
|
424
|
+
case ir.Aggregate() | ir.SetOperation() | ir.OpaqueRelation() | ir.RecursiveRelation():
|
|
425
|
+
return frozenset({(column, aliases)})
|
|
426
|
+
case _:
|
|
427
|
+
assert_never(relation)
|
|
428
|
+
match column.scalar_expr:
|
|
429
|
+
case ir.ColumnRef(column=input_column):
|
|
430
|
+
below: tuple[ir.OutputColumn, ...] = (input_column,)
|
|
431
|
+
case expression if not pass_through:
|
|
432
|
+
below = ir.strict_inputs(expression)
|
|
433
|
+
case _:
|
|
434
|
+
return frozenset({(column, aliases)})
|
|
435
|
+
inputs = {each for child in ir.children(relation) if isinstance(child, ir.RelationExpr) for each in child.output_columns}
|
|
436
|
+
if not all(each in inputs for each in below):
|
|
437
|
+
return frozenset({(column, aliases)})
|
|
438
|
+
return frozenset({(column, aliases)}).union(
|
|
439
|
+
*(_row_lineage(each, pass_through=pass_through, aliases=below_aliases) for each in below)
|
|
440
|
+
)
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def _rejected_paddings(conjuncts: tuple[ir.ScalarExpr, ...]) -> dict[Padding, ir.ScalarExpr]:
|
|
444
|
+
"""Each padding no row of which a conjunct holds on, with that conjunct.
|
|
445
|
+
|
|
446
|
+
A padded row is NULL in every column its join pads, all at once: a
|
|
447
|
+
conjunct NULL there (`_null_with`) is never TRUE, nor is a Builtin with a
|
|
448
|
+
`rejecting` argument NULL there or `p IS TRUE` where p is never TRUE,
|
|
449
|
+
`IS NOT NULL` of such an expression is
|
|
450
|
+
FALSE, and an OR rejects the paddings every part rejects:
|
|
451
|
+
`e.sal > 0 OR e.comm > 0` and `coalesce(e.sal, e.comm) > 0` reject the
|
|
452
|
+
join that pads both (Calcite's whole-side `Strong`).
|
|
453
|
+
"""
|
|
454
|
+
rejected: dict[Padding, ir.ScalarExpr] = {}
|
|
455
|
+
for conjunct in conjuncts:
|
|
456
|
+
for padding in _conjunct_paddings(conjunct):
|
|
457
|
+
rejected.setdefault(padding, conjunct)
|
|
458
|
+
return rejected
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def _conjunct_paddings(conjunct: ir.ScalarExpr) -> frozenset[Padding]:
|
|
462
|
+
conjunct = conjunct.closed
|
|
463
|
+
match conjunct:
|
|
464
|
+
case ir.Or(parts=parts):
|
|
465
|
+
first, *others = (frozenset(_rejected_paddings(ir.conjuncts(part))) for part in parts)
|
|
466
|
+
return first.intersection(*others)
|
|
467
|
+
case ir.And(parts=parts):
|
|
468
|
+
return frozenset(_rejected_paddings(parts))
|
|
469
|
+
case ir.IsNotNull(operand=operand):
|
|
470
|
+
return _null_with(operand)
|
|
471
|
+
case ir.NullSafeEquality(left=left, right=right, rejects=True):
|
|
472
|
+
# Equal to a non-null side, the other is non-null too.
|
|
473
|
+
return frozenset(
|
|
474
|
+
padding for side, other in ((left, right), (right, left)) if not _expression_sources(other)[0]
|
|
475
|
+
for padding in _null_with(side)
|
|
476
|
+
)
|
|
477
|
+
case ir.Call(function=ir.Builtin(true_only_if_argument=True), arguments=(argument,)):
|
|
478
|
+
# TRUE only where its argument is: `p IS TRUE` rejects what p does.
|
|
479
|
+
return _conjunct_paddings(argument)
|
|
480
|
+
case ir.Call(rejecting_arguments=arguments):
|
|
481
|
+
# Never TRUE where a rejecting argument is NULL, though perhaps not NULL.
|
|
482
|
+
return frozenset(padding for argument in arguments for padding in _null_with(argument))
|
|
483
|
+
case _:
|
|
484
|
+
return _null_with(conjunct)
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def _null_with(expression: ir.ScalarExpr) -> frozenset[Padding]:
|
|
488
|
+
"""The paddings on every row of which `expression` is NULL: a column's,
|
|
489
|
+
those of an argument it is strict in, or, for AND and OR, those every part
|
|
490
|
+
is NULL on (`NULL OR TRUE` is TRUE). Any other expression is NULL on a
|
|
491
|
+
padding's rows when its Null Sources keep that padding (coalesce: when
|
|
492
|
+
every argument is NULL there)."""
|
|
493
|
+
expression = expression.closed
|
|
494
|
+
match expression:
|
|
495
|
+
case ir.ColumnRef(column=column):
|
|
496
|
+
return frozenset(source for source in _null_sources(column).value if isinstance(source, Padding))
|
|
497
|
+
case ir.Coalesce(arguments=(first, *others)) | ir.Call(function=ir.Builtin(skips_null=True), arguments=(first, *others)):
|
|
498
|
+
return _null_with(first).intersection(*(_null_with(other) for other in others))
|
|
499
|
+
case ir.Call(strict_arguments=arguments):
|
|
500
|
+
return frozenset(padding for argument in arguments for padding in _null_with(argument))
|
|
501
|
+
case ir.Equality(left=left, right=right):
|
|
502
|
+
return _null_with(left) | _null_with(right)
|
|
503
|
+
case ir.InList(operand=operand):
|
|
504
|
+
return _null_with(operand)
|
|
505
|
+
case ir.And(parts=(first, *others)) | ir.Or(parts=(first, *others)):
|
|
506
|
+
return _null_with(first).intersection(*(_null_with(other) for other in others))
|
|
507
|
+
case (
|
|
508
|
+
ir.And() | ir.Or() | ir.Coalesce() | ir.Constant() | ir.NullLiteral() | ir.SimpleCase() | ir.OpaquePureFunction()
|
|
509
|
+
| ir.OpaqueExpression() | ir.Count() | ir.AnyAggregate() | ir.Accumulation() | ir.Elements() | ir.IsNull()
|
|
510
|
+
| ir.IsNotNull() | ir.NullSafeEquality()
|
|
511
|
+
):
|
|
512
|
+
sources, _ = _expression_sources(expression)
|
|
513
|
+
return frozenset(source for source in sources if isinstance(source, Padding))
|
|
514
|
+
case _:
|
|
515
|
+
assert_never(expression)
|
|
516
|
+
|
|
517
|
+
|
|
349
518
|
def _null_rejected(conjuncts: tuple[ir.ScalarExpr, ...]) -> dict[ir.OutputColumn, ir.ScalarExpr]:
|
|
350
519
|
"""Each column a conjunct requires to be non-null, with that conjunct.
|
|
351
520
|
|
|
352
521
|
A conjunct cannot be TRUE while it is NULL, so it rejects every column it
|
|
353
522
|
is strict in; `IS NOT NULL` rejects those of its operand (Paulley §3.2.4,
|
|
354
|
-
footnote 9)
|
|
523
|
+
footnote 9), and `IS NOT DISTINCT FROM` a non-null value those of its
|
|
524
|
+
other side. A Builtin never TRUE on a NULL argument rejects that
|
|
525
|
+
argument's, though it may not be NULL there (Calcite's `Strong.isNotTrue`):
|
|
526
|
+
`x > ANY (...)` rejects x. `p IS TRUE` rejects whatever p does. An OR
|
|
527
|
+
rejects the columns each of its parts rejects.
|
|
355
528
|
"""
|
|
356
529
|
rejected: dict[ir.OutputColumn, ir.ScalarExpr] = {}
|
|
357
530
|
for conjunct in conjuncts:
|
|
@@ -361,6 +534,18 @@ def _null_rejected(conjuncts: tuple[ir.ScalarExpr, ...]) -> dict[ir.OutputColumn
|
|
|
361
534
|
columns = tuple(column for column in first if all(column in other for other in others))
|
|
362
535
|
case ir.IsNotNull(operand=operand):
|
|
363
536
|
columns = ir.strict_inputs(operand)
|
|
537
|
+
case ir.NullSafeEquality(left=left, right=right, rejects=True):
|
|
538
|
+
# Equal to a non-null side, the other is non-null too.
|
|
539
|
+
columns = tuple(dict.fromkeys(
|
|
540
|
+
column for side, other in ((left, right), (right, left)) if not _expression_sources(other)[0]
|
|
541
|
+
for column in ir.strict_inputs(side)
|
|
542
|
+
))
|
|
543
|
+
case ir.Call(function=ir.Builtin(true_only_if_argument=True), arguments=(argument,)):
|
|
544
|
+
# TRUE only where its argument is: `p IS TRUE` rejects what p does.
|
|
545
|
+
columns = tuple(_null_rejected((argument,)))
|
|
546
|
+
case ir.Call(rejecting_arguments=arguments):
|
|
547
|
+
# Never TRUE where a rejecting argument is NULL: `x > ANY (...)`.
|
|
548
|
+
columns = tuple(dict.fromkeys(column for argument in arguments for column in ir.strict_inputs(argument)))
|
|
364
549
|
case _:
|
|
365
550
|
columns = ir.strict_inputs(conjunct)
|
|
366
551
|
for column in columns:
|
|
@@ -390,6 +575,30 @@ def _on_rejected(join: ir.Join) -> dict[ir.OutputColumn, ir.ScalarExpr]:
|
|
|
390
575
|
assert_never(join.kind)
|
|
391
576
|
|
|
392
577
|
|
|
578
|
+
def _on_rejected_paddings(join: ir.Join) -> dict[Padding, ir.ScalarExpr]:
|
|
579
|
+
"""The paddings of `join`'s inputs its ON rejects, on the side whose
|
|
580
|
+
unmatched rows it drops (see `_on_rejected`)."""
|
|
581
|
+
match join.kind:
|
|
582
|
+
case "inner" | "semi":
|
|
583
|
+
sides: tuple[ir.RelationExpr, ...] = (join.left, join.right)
|
|
584
|
+
case "left":
|
|
585
|
+
sides = (join.right,)
|
|
586
|
+
case "right":
|
|
587
|
+
sides = (join.left,)
|
|
588
|
+
case "cross" | "full" | "anti":
|
|
589
|
+
return {}
|
|
590
|
+
case _:
|
|
591
|
+
assert_never(join.kind)
|
|
592
|
+
rejected = _rejected_paddings(join.conjuncts)
|
|
593
|
+
if not rejected:
|
|
594
|
+
return {}
|
|
595
|
+
own = {
|
|
596
|
+
source for side in sides for column in side.output_columns
|
|
597
|
+
for source in _null_sources(column).value if isinstance(source, Padding)
|
|
598
|
+
}
|
|
599
|
+
return {padding: conjunct for padding, conjunct in rejected.items() if padding in own}
|
|
600
|
+
|
|
601
|
+
|
|
393
602
|
def _padded_sides(join: ir.Join) -> frozenset[bool]:
|
|
394
603
|
"""The sides `join` null-extends: True for the left input, False for the right.
|
|
395
604
|
|