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,19 @@
|
|
|
1
|
+
# Rule Style Guide
|
|
2
|
+
|
|
3
|
+
Rules are analysis functions. Each returns `Result[Value]`: `.value`
|
|
4
|
+
is the computed Value and the remaining fields directly represent its evidence.
|
|
5
|
+
`@analysis(stratum)` provides declaration lookup and analysis-scoped caching for public and
|
|
6
|
+
internal analysis functions. Its `Stratum` orders facts about one relation: an analysis may
|
|
7
|
+
use facts about the same relation only at its own or a lower stratum, which keeps the
|
|
8
|
+
call graph acyclic; the decorator asserts this on every call. Every concrete public `Property` class has one
|
|
9
|
+
snake-case public analysis function whose parameters match its fields. Internal
|
|
10
|
+
analysis functions start with `_`. `ColumnSet`, `Closure`, and `RowIdentity` are
|
|
11
|
+
ordinary derived values defined in these rules. Uniqueness is a closure question:
|
|
12
|
+
derive dependencies a relation introduces in `_functional_dependencies`, and let
|
|
13
|
+
`_closure` reach into inputs; never copy an input's facts up to its consumer.
|
|
14
|
+
Use explicit matches for semantic dispatch, and fail on unhandled node types. Keep IR traversal and set operations in small helpers so analysis
|
|
15
|
+
functions state their semantic rule directly. Use `&` / `|` or `all_of` /
|
|
16
|
+
`any_of` to preserve evidence; Python's `and` / `or` deliberately reject
|
|
17
|
+
`Result` values. Use `.value` for every result, including Boolean results
|
|
18
|
+
(false means unproved). `&` / `|` and `all_of` / `any_of` compose only
|
|
19
|
+
`Result[bool]` values and retain their evidence.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""Python analysis functions establish public relational properties.
|
|
2
|
+
|
|
3
|
+
Equality groups say which columns carry one value (equality), for facts
|
|
4
|
+
about values.
|
|
5
|
+
|
|
6
|
+
Null sources say why a column may be NULL (nullability). Functional
|
|
7
|
+
dependencies and their closure decide uniqueness: a column set is a Unique
|
|
8
|
+
Set when its closure reaches the relation's Row Identity, and a join is
|
|
9
|
+
many to one when the right columns ON binds reach the right input's
|
|
10
|
+
(uniqueness, join_cardinality). Foreign Keys and Exactly One Joins build on both.
|
|
11
|
+
"""
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Intermediate values used by column-set property functions."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
|
|
7
|
+
from sqlassert import ir
|
|
8
|
+
from sqlassert.python_engine import Result
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True)
|
|
12
|
+
class RowIdentity:
|
|
13
|
+
"""Tells apart every row of `relation`, duplicates included (Paulley's ι).
|
|
14
|
+
|
|
15
|
+
Analysis only: never in the IR, in SQL, or shown to authors.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
relation: ir.RelationExpr
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
type Attribute = ir.OutputColumn | RowIdentity
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(eq=False)
|
|
25
|
+
class ColumnSet:
|
|
26
|
+
relation: ir.RelationExpr
|
|
27
|
+
columns: set[Attribute]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(eq=False)
|
|
31
|
+
class Closure(ColumnSet):
|
|
32
|
+
"""A closure, with the closures it took in the relation's inputs."""
|
|
33
|
+
|
|
34
|
+
inputs: tuple[Result[Closure], ...] = field(default=())
|
|
@@ -0,0 +1,472 @@
|
|
|
1
|
+
"""Enumerated Domains: the finite set a column's non-null values come from.
|
|
2
|
+
|
|
3
|
+
A column's own domain comes from Knowledge about it and from its expression:
|
|
4
|
+
a literal is its own value, NULL contributes none, and `coalesce` takes one of
|
|
5
|
+
its arguments' values. A pass-through column keeps its source's domain, which
|
|
6
|
+
a strict `WHERE` or `ON` conjunct `col = expr` or `col IN (...)` narrows to the
|
|
7
|
+
values on its other side. Its domain is then the intersection of the own
|
|
8
|
+
domains of every column in its equality group: on every row they carry one
|
|
9
|
+
value, or are all NULL. An unbounded domain is `None`.
|
|
10
|
+
|
|
11
|
+
NULL is outside every domain, so padding and NULL literals never widen one.
|
|
12
|
+
|
|
13
|
+
Members are typed literals, and covering is by identity: a value is covered
|
|
14
|
+
only by an identical literal, so numeric 1 never covers string '1', nor 1.0.
|
|
15
|
+
Intersecting is not by identity, because a column is compared with a literal
|
|
16
|
+
after implicit casts, so two distinct literals can both equal its value: a
|
|
17
|
+
FLOAT equals 0.1 and 0.100000001, a VARCHAR '1.4' equals 1 and 1.4, an
|
|
18
|
+
INTEGER '01' and '1', and a case-insensitive VARCHAR 'a' and 'A'. A meet
|
|
19
|
+
therefore keeps every value that may equal one on each other side
|
|
20
|
+
(`_may_coincide`), which only ever keeps more than the true intersection.
|
|
21
|
+
Distinct strings are distinct values only where the column is text compared
|
|
22
|
+
by identity (`_binary_text`).
|
|
23
|
+
|
|
24
|
+
A simple CASE takes one of its THEN values, or its ELSE value unless ELSE is
|
|
25
|
+
unreachable: the CASE is exhaustive and its operand non-null. Exhaustiveness
|
|
26
|
+
covers by identity too: an arm covers a domain member only when it is that
|
|
27
|
+
literal, so the operand compared with the arm is the very comparison that
|
|
28
|
+
puts its value in the domain.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
from __future__ import annotations
|
|
32
|
+
|
|
33
|
+
from decimal import Decimal
|
|
34
|
+
from fractions import Fraction
|
|
35
|
+
from typing import assert_never
|
|
36
|
+
|
|
37
|
+
from sqlassert.diagnostics import quoted
|
|
38
|
+
from sqlassert import ir
|
|
39
|
+
from sqlassert import properties as props
|
|
40
|
+
from sqlassert.properties import EnumeratedDomain
|
|
41
|
+
from sqlassert.python_engine import Result, Stratum, analysis, any_of, current_arena, unknown
|
|
42
|
+
from sqlassert.rules.equality import _equal_columns, _lax_equalities, _same_type
|
|
43
|
+
from sqlassert.rules.nullability import _non_null_expression, non_null_column
|
|
44
|
+
|
|
45
|
+
# A finite set of possible non-null values, or None when any value is possible.
|
|
46
|
+
type Domain = frozenset[ir.LiteralValue] | None
|
|
47
|
+
|
|
48
|
+
_TRUE = ir.LiteralValue(type="boolean", text="TRUE")
|
|
49
|
+
_FALSE = ir.LiteralValue(type="boolean", text="FALSE")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@analysis(Stratum.DOMAIN)
|
|
53
|
+
def enumerated_domain(column: ir.OutputColumn, values: frozenset[ir.LiteralValue]) -> Result[bool]:
|
|
54
|
+
domain = _domain(column)
|
|
55
|
+
if domain.value is None:
|
|
56
|
+
return Result(False, f"No finite domain is known for {quoted(column.name)}", (column,), [domain], kind="unknown")
|
|
57
|
+
uncovered = domain.value - values
|
|
58
|
+
if uncovered:
|
|
59
|
+
return Result(
|
|
60
|
+
False, f"{quoted(column.name)} may be {_render(uncovered)}, which the assertion does not cover",
|
|
61
|
+
(column,), [domain], kind="unknown",
|
|
62
|
+
)
|
|
63
|
+
return Result(True, "Every possible value is listed", (column,), [domain])
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@analysis(Stratum.DOMAIN)
|
|
67
|
+
def exhaustive_case(case: ir.SimpleCase) -> Result[bool]:
|
|
68
|
+
operand = _operand_name(case.operand)
|
|
69
|
+
domain = _expression_domain(case.operand)
|
|
70
|
+
if domain.value is None:
|
|
71
|
+
return Result(False, f"No finite domain is known for {operand}", (case,), [domain], kind="unknown")
|
|
72
|
+
missing = domain.value - _listed(case)
|
|
73
|
+
if missing:
|
|
74
|
+
return Result(False, f"{operand} may be {_render(missing)}, which no WHEN arm lists", (case,), [domain], kind="unknown")
|
|
75
|
+
return Result(True, f"Every possible value of {operand} has a WHEN arm", (case,), [domain])
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _listed(case: ir.SimpleCase) -> frozenset[ir.LiteralValue]:
|
|
79
|
+
"""The literals a WHEN arm is exactly."""
|
|
80
|
+
listed: set[ir.LiteralValue] = set()
|
|
81
|
+
for when in case.whens:
|
|
82
|
+
match when:
|
|
83
|
+
case ir.Constant(value=ir.LiteralValue() as value):
|
|
84
|
+
listed.add(value)
|
|
85
|
+
case _:
|
|
86
|
+
pass # Another arm covers no member by identity.
|
|
87
|
+
return frozenset(listed)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _operand_name(operand: ir.ScalarExpr) -> str:
|
|
91
|
+
match operand:
|
|
92
|
+
case ir.ColumnRef(column=column):
|
|
93
|
+
return column.name
|
|
94
|
+
case _:
|
|
95
|
+
return "the CASE operand"
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _else_unreachable(case: ir.SimpleCase) -> Result[bool]:
|
|
99
|
+
"""No row reaches ELSE: every non-null operand value has an arm, and the operand is non-null."""
|
|
100
|
+
match case.operand:
|
|
101
|
+
case ir.ColumnRef(column=column):
|
|
102
|
+
present = non_null_column(column)
|
|
103
|
+
case ir.Constant(value=ir.LiteralValue()):
|
|
104
|
+
present = Result(True, "A non-null literal", (case.operand,))
|
|
105
|
+
case _:
|
|
106
|
+
present = unknown("Nullability of the CASE operand is not inferred", case.operand)
|
|
107
|
+
return exhaustive_case(case) & present
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def always_null_columns(property: props.Property) -> tuple[ir.OutputColumn, ...]:
|
|
111
|
+
"""The columns named by `property` that are always NULL (an empty
|
|
112
|
+
domain) where NULL exempts a row from it, so it holds trivially: an
|
|
113
|
+
ENUM's or EXHAUSTIVE CASE operand's column, and any column of a Unique
|
|
114
|
+
Set, a dependency's determinant, Referential Coverage's referencing
|
|
115
|
+
columns, or NOT NULL ELEMENTS. NULL in a dependent is a value every row
|
|
116
|
+
agrees on, like a constant; a non-null Property fails on one instead."""
|
|
117
|
+
match property:
|
|
118
|
+
case props.EnumeratedDomain(column=column) | props.ExhaustiveCase(case=ir.SimpleCase(operand=ir.ColumnRef(column=column))):
|
|
119
|
+
columns: frozenset[ir.OutputColumn] = frozenset({column})
|
|
120
|
+
case props.ExhaustiveCase():
|
|
121
|
+
columns = frozenset() # An operand that is no column: only columns are named.
|
|
122
|
+
case props.NonNullUniqueSet() | props.NonNullColumns() | props.NonNullColumn():
|
|
123
|
+
columns = frozenset()
|
|
124
|
+
case props.UniqueSet(columns=columns) | props.NonNullElements(columns=columns):
|
|
125
|
+
pass
|
|
126
|
+
case props.FunctionalDependency(determinant=columns):
|
|
127
|
+
pass
|
|
128
|
+
case props.ReferentialCoverage(columns=referencing):
|
|
129
|
+
columns = frozenset(referencing)
|
|
130
|
+
case props.ManyToOneJoin() | props.OneToManyJoin() | props.OneToOneJoin() | props.UniqueJoin() | props.ExactlyOneJoin():
|
|
131
|
+
columns = frozenset()
|
|
132
|
+
case _:
|
|
133
|
+
raise AssertionError(f"unhandled property {type(property).__name__}")
|
|
134
|
+
return tuple(sorted((column for column in columns if _domain(column).value == frozenset()), key=lambda column: column.name))
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@analysis(Stratum.DOMAIN)
|
|
138
|
+
def _domain(column: ir.OutputColumn) -> Result[Domain]:
|
|
139
|
+
"""`column`'s domain: its own, intersected with every equal column's."""
|
|
140
|
+
group = _equal_columns(column)
|
|
141
|
+
relation = column.get_relation(current_arena().program)
|
|
142
|
+
reachable = set(group.value)
|
|
143
|
+
edges = _lax_equalities(relation).value
|
|
144
|
+
lax_evidence = []
|
|
145
|
+
pending = list(reachable)
|
|
146
|
+
while pending:
|
|
147
|
+
first = pending.pop()
|
|
148
|
+
for (source, other), reason in edges.items():
|
|
149
|
+
if source is first and other not in reachable:
|
|
150
|
+
new = _equal_columns(other).value - reachable
|
|
151
|
+
reachable.update(new)
|
|
152
|
+
pending.extend(new)
|
|
153
|
+
lax_evidence.append(Result(True, "A non-null value satisfies the ON equality", (reason,)))
|
|
154
|
+
members = [member for member in relation.output_columns if member in reachable]
|
|
155
|
+
owns = [_own_domain(member) for member in members]
|
|
156
|
+
known = [own for own in owns if own.value is not None]
|
|
157
|
+
if not known:
|
|
158
|
+
return Result(None, f"No finite domain is known for {quoted(column.name)}", (column,), owns)
|
|
159
|
+
value = _meet([own.value for own in known if own.value is not None], _binary_text(column))
|
|
160
|
+
premises = [group, *lax_evidence, *known] if len(members) > 1 else known
|
|
161
|
+
return Result(value, f"{quoted(column.name)} is one of {_render(value)}", (column,), premises)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
@analysis(Stratum.DOMAIN)
|
|
165
|
+
def _own_domain(column: ir.OutputColumn) -> Result[Domain]:
|
|
166
|
+
"""`column`'s domain from Knowledge about it and from how its relation computes it."""
|
|
167
|
+
arena = current_arena()
|
|
168
|
+
sources: list[Result[Domain]] = [_computed_domain(column.get_relation(arena.program), column)]
|
|
169
|
+
for item in arena.knowledge:
|
|
170
|
+
match item:
|
|
171
|
+
case EnumeratedDomain(column=known, values=values) if known is column:
|
|
172
|
+
sources.append(Result(values, f"{quoted(column.name)} is known to be one of {_render(values)}", (column,), [any_of(arena.accepted_evidence(item))]))
|
|
173
|
+
case _:
|
|
174
|
+
pass # Other Knowledge says nothing about values.
|
|
175
|
+
return _intersection(column, sources)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _computed_domain(relation: ir.RelationExpr, column: ir.OutputColumn) -> Result[Domain]:
|
|
179
|
+
relation = relation.closed
|
|
180
|
+
match relation:
|
|
181
|
+
case ir.NamedRelation(body=None) | ir.OpaqueRelation():
|
|
182
|
+
return Result(None, f"{quoted(column.name)} is not enumerated", (column,))
|
|
183
|
+
case ir.SetOperation():
|
|
184
|
+
return _set_operation_domain(relation, column)
|
|
185
|
+
case ir.Filter() | ir.Join():
|
|
186
|
+
return _intersection(column, [_expression_domain(column.scalar_expr), *_narrowings(relation, column)])
|
|
187
|
+
case ir.Alias() | ir.NamedRelation() | ir.Project() | ir.Limit() | ir.Aggregate() | ir.Distinct() | ir.QualifyByPartition():
|
|
188
|
+
return _expression_domain(column.scalar_expr)
|
|
189
|
+
case _:
|
|
190
|
+
assert_never(relation)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _set_operation_domain(relation: ir.SetOperation, column: ir.OutputColumn) -> Result[Domain]:
|
|
194
|
+
"""A UNION row comes from either input, an INTERSECT row equals a row of
|
|
195
|
+
both, an EXCEPT row is a left input row (Paulley §3.2.5-3.2.6). Inputs
|
|
196
|
+
pair by position; a UNION of mixed value types is not enumerated, since
|
|
197
|
+
the output type may convert one."""
|
|
198
|
+
left = _expression_domain(column.scalar_expr)
|
|
199
|
+
arms = relation.arms(column)
|
|
200
|
+
if relation.operator == "except" or arms is None and relation.operator == "intersect":
|
|
201
|
+
return left
|
|
202
|
+
if arms is None:
|
|
203
|
+
return Result(None, "The UNION's inputs are not paired by position", (relation, column))
|
|
204
|
+
right = _domain(arms[1])
|
|
205
|
+
if relation.operator == "intersect":
|
|
206
|
+
# The row carries the left value, equal to a right one under the left
|
|
207
|
+
# column's comparison: a string bounds it only if that is identity.
|
|
208
|
+
if right.value is not None and any(member.type == "string" for member in right.value) and not _binary_text(arms[0]):
|
|
209
|
+
return left
|
|
210
|
+
return _intersection(column, [left, right])
|
|
211
|
+
if left.value is None or right.value is None:
|
|
212
|
+
return Result(None, f"An input of the UNION does not enumerate {quoted(column.name)}", (relation, column), [left, right])
|
|
213
|
+
value = left.value | right.value
|
|
214
|
+
if len({member.type for member in value}) > 1:
|
|
215
|
+
return Result(None, f"The UNION's inputs give {quoted(column.name)} values of different types", (relation, column), [left, right])
|
|
216
|
+
return Result(value, f"{quoted(column.name)} is one of either input's values: {_render(value)}", (relation, column), [left, right])
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _expression_domain(expression: ir.ScalarExpr) -> Result[Domain]:
|
|
220
|
+
expression = expression.closed
|
|
221
|
+
match expression:
|
|
222
|
+
case ir.ColumnRef(column=source):
|
|
223
|
+
return _domain(source)
|
|
224
|
+
case ir.Constant(value=ir.LiteralValue() as value):
|
|
225
|
+
return Result(frozenset({value}), f"The literal {value.sql()}", (expression,))
|
|
226
|
+
case ir.NullLiteral():
|
|
227
|
+
return Result(frozenset(), "NULL is outside every domain", (expression,))
|
|
228
|
+
case ir.Coalesce(arguments=arguments):
|
|
229
|
+
# The first non-null argument, so one of theirs.
|
|
230
|
+
domains = [_expression_domain(argument) for argument in arguments]
|
|
231
|
+
if any(domain.value is None for domain in domains):
|
|
232
|
+
return Result(None, "A coalesce argument is not enumerated", (expression,), domains)
|
|
233
|
+
value = frozenset().union(*(domain.value for domain in domains if domain.value is not None))
|
|
234
|
+
return Result(value, "Coalesce takes one of its arguments' values", (expression,), domains)
|
|
235
|
+
case ir.AnyAggregate(input=value):
|
|
236
|
+
# The value comes from some input row, or is NULL (an empty group).
|
|
237
|
+
return _expression_domain(value)
|
|
238
|
+
case ir.SimpleCase(thens=thens, default=default):
|
|
239
|
+
arms = [_expression_domain(then) for then in thens]
|
|
240
|
+
unreachable = _else_unreachable(expression)
|
|
241
|
+
if not unreachable.value:
|
|
242
|
+
arms.append(_expression_domain(default))
|
|
243
|
+
if any(arm.value is None for arm in arms):
|
|
244
|
+
return Result(None, "A CASE arm is not enumerated", (expression,), arms)
|
|
245
|
+
value = frozenset().union(*(arm.value for arm in arms if arm.value is not None))
|
|
246
|
+
premises = [*arms, unreachable] if unreachable.value else arms
|
|
247
|
+
return Result(value, "A CASE takes one of its arms' values", (expression,), premises)
|
|
248
|
+
case ir.Call(strict_arguments=arguments) if arguments:
|
|
249
|
+
# NULL wherever a strict argument is, so always NULL where one always is.
|
|
250
|
+
for argument in arguments:
|
|
251
|
+
absent = _expression_domain(argument)
|
|
252
|
+
if absent.value == frozenset():
|
|
253
|
+
return Result(frozenset(), "A strict argument is always NULL, so it is", (expression,), [absent])
|
|
254
|
+
return Result(None, "Values of this expression are not enumerated", (expression,))
|
|
255
|
+
case ir.IsNull(operand=operand) | ir.IsNotNull(operand=operand):
|
|
256
|
+
# A constant where the operand is never NULL, or always.
|
|
257
|
+
null = isinstance(expression, ir.IsNull)
|
|
258
|
+
present = _non_null_expression(operand)
|
|
259
|
+
if present.value:
|
|
260
|
+
value = frozenset({_FALSE if null else _TRUE})
|
|
261
|
+
return Result(value, f"Its operand is never NULL, so it is {_render(value)}", (expression,), [present])
|
|
262
|
+
absent = _expression_domain(operand)
|
|
263
|
+
if absent.value == frozenset():
|
|
264
|
+
value = frozenset({_TRUE if null else _FALSE})
|
|
265
|
+
return Result(value, f"Its operand is always NULL, so it is {_render(value)}", (expression,), [absent])
|
|
266
|
+
return Result(None, "Its operand may be NULL or not", (expression,), [present, absent])
|
|
267
|
+
case (
|
|
268
|
+
ir.Constant() | ir.OpaqueExpression() | ir.OpaquePureFunction() | ir.Call() | ir.Count() | ir.Accumulation() | ir.Elements() | ir.Equality()
|
|
269
|
+
| ir.NullSafeEquality() | ir.InList() | ir.And() | ir.Or()
|
|
270
|
+
):
|
|
271
|
+
return Result(None, "Values of this expression are not enumerated", (expression,))
|
|
272
|
+
case _:
|
|
273
|
+
assert_never(expression)
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _narrowings(relation: ir.Filter | ir.Join, column: ir.OutputColumn) -> list[Result[Domain]]:
|
|
277
|
+
"""Domains a conjunct true on every row carrying `column`'s value bounds it to.
|
|
278
|
+
|
|
279
|
+
`WHERE` and an inner join's ON hold on every row; an outer join's ON holds
|
|
280
|
+
on the matched rows only, which pad nothing on the side it pads.
|
|
281
|
+
"""
|
|
282
|
+
match column.scalar_expr:
|
|
283
|
+
case ir.ColumnRef(column=source):
|
|
284
|
+
pass
|
|
285
|
+
case _:
|
|
286
|
+
raise TypeError(f"{type(relation).__name__} column {column.name} is not a pass-through")
|
|
287
|
+
match relation:
|
|
288
|
+
case ir.Filter(conjuncts=conjuncts):
|
|
289
|
+
clause = "WHERE"
|
|
290
|
+
case ir.Join(kind="inner" | "cross" | "semi", conjuncts=conjuncts):
|
|
291
|
+
clause = "ON"
|
|
292
|
+
case ir.Join(kind="left", right=padded, conjuncts=conjuncts) | ir.Join(kind="right", left=padded, conjuncts=conjuncts) if source in padded.output_columns:
|
|
293
|
+
clause = "ON"
|
|
294
|
+
case _:
|
|
295
|
+
return []
|
|
296
|
+
narrowings: list[Result[Domain]] = []
|
|
297
|
+
for conjunct in conjuncts:
|
|
298
|
+
bound = _conjunct_bound(conjunct, source)
|
|
299
|
+
if bound is not None and bound.value is not None:
|
|
300
|
+
narrowings.append(Result(bound.value, f"The {clause} conjunct bounds {quoted(column.name)} to {_render(bound.value)}", (conjunct,), [bound]))
|
|
301
|
+
if isinstance(relation, ir.Join) and relation.kind == "semi":
|
|
302
|
+
narrowings.extend(_matched_narrowings(relation, column, source))
|
|
303
|
+
return narrowings
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def _matched_narrowings(join: ir.Join, column: ir.OutputColumn, source: ir.OutputColumn) -> list[Result[Domain]]:
|
|
307
|
+
"""A semi join's left column equal to a right column of the same type
|
|
308
|
+
takes that column's value on the matched right row, which every other ON
|
|
309
|
+
conjunct bounds too: `d.deptno = e.mgr AND d.deptno = 10` bounds mgr."""
|
|
310
|
+
narrowings: list[Result[Domain]] = []
|
|
311
|
+
for conjunct in join.conjuncts:
|
|
312
|
+
match conjunct:
|
|
313
|
+
case (
|
|
314
|
+
ir.Equality(left=ir.ColumnRef(column=first), right=ir.ColumnRef(column=second))
|
|
315
|
+
| ir.NullSafeEquality(left=ir.ColumnRef(column=first), right=ir.ColumnRef(column=second))
|
|
316
|
+
) if source in (first, second):
|
|
317
|
+
other = second if first is source else first
|
|
318
|
+
case _:
|
|
319
|
+
continue
|
|
320
|
+
if other not in join.right.output_columns or not _same_type(source, other):
|
|
321
|
+
continue
|
|
322
|
+
bounds = [bound for part in join.conjuncts if part is not conjunct and (bound := _conjunct_bound(part, other)) is not None]
|
|
323
|
+
if bounds:
|
|
324
|
+
bound = _intersection(other, bounds)
|
|
325
|
+
if bound.value is not None:
|
|
326
|
+
reason = f"{quoted(column.name)} equals {quoted(other.name)} of the matched right row, which ON bounds to {_render(bound.value)}"
|
|
327
|
+
narrowings.append(Result(bound.value, reason, (conjunct,), [bound]))
|
|
328
|
+
return narrowings
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def _conjunct_bound(conjunct: ir.ScalarExpr, source: ir.OutputColumn) -> Result[Domain] | None:
|
|
332
|
+
"""The values `source` takes on rows where `conjunct` is TRUE, or None
|
|
333
|
+
when the conjunct does not bound it.
|
|
334
|
+
|
|
335
|
+
An AND bounds it to what each of its bounding parts allows; an OR to the
|
|
336
|
+
union of its parts' bounds, when every part bounds it. A bound is never an
|
|
337
|
+
unknown domain.
|
|
338
|
+
"""
|
|
339
|
+
match conjunct:
|
|
340
|
+
# A TRUE IS NOT DISTINCT FROM leaves a non-null side equal to the other.
|
|
341
|
+
case ir.Equality(left=ir.ColumnRef(column=first), right=other) | ir.NullSafeEquality(left=ir.ColumnRef(column=first), right=other) if first is source:
|
|
342
|
+
bounds = [_bound_domain(source, other)]
|
|
343
|
+
case ir.Equality(left=other, right=ir.ColumnRef(column=second)) | ir.NullSafeEquality(left=other, right=ir.ColumnRef(column=second)) if second is source:
|
|
344
|
+
bounds = [_bound_domain(source, other)]
|
|
345
|
+
case ir.InList(operand=ir.ColumnRef(column=operand), values=values) if operand is source:
|
|
346
|
+
bounds = [_bound_domain(source, value) for value in values]
|
|
347
|
+
case ir.And(parts=parts):
|
|
348
|
+
found = [bound for part in parts if (bound := _conjunct_bound(part, source)) is not None]
|
|
349
|
+
# Distinct literals may compare equal (issue 29), so parts meet as domains do.
|
|
350
|
+
return _intersection(source, found) if found else None
|
|
351
|
+
case ir.Or(parts=parts):
|
|
352
|
+
bounds = [_conjunct_bound(part, source) for part in parts]
|
|
353
|
+
if any(bound is None for bound in bounds):
|
|
354
|
+
return None # A part that does not bound the column lets any value through.
|
|
355
|
+
case _:
|
|
356
|
+
return None # Other conjuncts do not bound this column.
|
|
357
|
+
if any(bound is None or bound.value is None for bound in bounds):
|
|
358
|
+
return None
|
|
359
|
+
value = frozenset().union(*(bound.value for bound in bounds if bound is not None and bound.value is not None))
|
|
360
|
+
return Result(value, f"{quoted(source.name)} is in {_render(value)} on every row this conjunct keeps", (conjunct,), [bound for bound in bounds if bound is not None])
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def _bound_domain(column: ir.OutputColumn, expression: ir.ScalarExpr) -> Result[Domain]:
|
|
364
|
+
match expression:
|
|
365
|
+
case ir.Constant(value=ir.LiteralValue(type="numeric", text=text)) if "e" in text.lower():
|
|
366
|
+
return Result(None, "An approximate numeric comparison may collapse distinct values", (expression,))
|
|
367
|
+
case ir.Constant() | ir.NullLiteral():
|
|
368
|
+
return _expression_domain(expression)
|
|
369
|
+
case ir.ColumnRef(column=source) if _same_type(column, source):
|
|
370
|
+
return _expression_domain(expression)
|
|
371
|
+
case _:
|
|
372
|
+
return Result(None, "The comparison may cast its operands, so no value domain is transferred", (expression,))
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def _intersection(column: ir.OutputColumn, sources: list[Result[Domain]]) -> Result[Domain]:
|
|
376
|
+
known = [source for source in sources if source.value is not None]
|
|
377
|
+
if not known:
|
|
378
|
+
return Result(None, f"No finite domain is known for {quoted(column.name)}", (column,), sources)
|
|
379
|
+
if len(known) == 1:
|
|
380
|
+
return known[0]
|
|
381
|
+
value = _meet([source.value for source in known if source.value is not None], _binary_text(column))
|
|
382
|
+
return Result(value, f"{quoted(column.name)} is one of {_render(value)}", (column,), known)
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def _meet(domains: list[frozenset[ir.LiteralValue]], binary_text: bool) -> frozenset[ir.LiteralValue]:
|
|
386
|
+
"""The first domain's values that may equal a value of every other one.
|
|
387
|
+
|
|
388
|
+
A column's value equals some member of each domain, so the member of the
|
|
389
|
+
first it equals may coincide with one of every other and is kept.
|
|
390
|
+
"""
|
|
391
|
+
first, *others = domains
|
|
392
|
+
return frozenset(value for value in first if all(any(_may_coincide(value, other, binary_text) for other in domain) for domain in others))
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def _binary_text(column: ir.OutputColumn) -> bool:
|
|
396
|
+
"""Whether `column` and every column equated with it, here or upstream,
|
|
397
|
+
are text compared by identity, so carry one string value.
|
|
398
|
+
|
|
399
|
+
Only matching comparison types merge Equality Groups. A set operation's
|
|
400
|
+
type may widen its left input's, so its columns are not followed.
|
|
401
|
+
"""
|
|
402
|
+
relation = column.get_relation(current_arena().program)
|
|
403
|
+
for member in _equal_columns(column).value:
|
|
404
|
+
match member.scalar_expr:
|
|
405
|
+
case ir.ColumnRef(column=source) if not isinstance(relation, ir.SetOperation):
|
|
406
|
+
if not _binary_text(source):
|
|
407
|
+
return False
|
|
408
|
+
case _:
|
|
409
|
+
if not member.binary_text:
|
|
410
|
+
return False
|
|
411
|
+
return True
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
# A FLOAT keeps 24 significant bits: two numbers rounding to one FLOAT differ
|
|
415
|
+
# by at most its precision relative to their size, with margin for a literal
|
|
416
|
+
# rounded through DOUBLE first, or are both too small to tell from zero.
|
|
417
|
+
_FLOAT_RELATIVE = Fraction(1, 2**22)
|
|
418
|
+
_FLOAT_ABSOLUTE = Fraction(1, 2**148)
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def _may_coincide(first: ir.LiteralValue, second: ir.LiteralValue, binary_text: bool) -> bool:
|
|
422
|
+
"""Whether some column value may equal both literals.
|
|
423
|
+
|
|
424
|
+
Literals of different types may: SQL casts one side, so '1' and 1 both
|
|
425
|
+
equal INTEGER 1. Distinct booleans never do. Distinct strings may unless
|
|
426
|
+
the column is text compared by identity: an INTEGER equals '01' and '1',
|
|
427
|
+
a case-insensitive one 'a' and 'A'. Distinct numbers may when one value
|
|
428
|
+
rounds to both.
|
|
429
|
+
"""
|
|
430
|
+
if first == second or first.type != second.type:
|
|
431
|
+
return True
|
|
432
|
+
match first.type:
|
|
433
|
+
case "string":
|
|
434
|
+
return not binary_text
|
|
435
|
+
case "boolean":
|
|
436
|
+
return False
|
|
437
|
+
case "numeric":
|
|
438
|
+
return _numbers_may_coincide(first.text, second.text)
|
|
439
|
+
case _:
|
|
440
|
+
assert_never(first.type)
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def _numbers_may_coincide(first: str, second: str) -> bool:
|
|
444
|
+
gap = abs(_number(first) - _number(second))
|
|
445
|
+
# A string is cast to an exact literal's type, rounding half away from
|
|
446
|
+
# zero to its scale: one value rounds to both when the cells overlap.
|
|
447
|
+
if gap < _half_step(first) + _half_step(second):
|
|
448
|
+
return True
|
|
449
|
+
# A FLOAT or DOUBLE is compared at its own precision.
|
|
450
|
+
return gap <= max(abs(_number(first)), abs(_number(second))) * _FLOAT_RELATIVE or gap <= _FLOAT_ABSOLUTE
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def _half_step(text: str) -> Fraction:
|
|
454
|
+
"""Half the rounding step of a numeric literal's SQL type: an integer's
|
|
455
|
+
is one, a decimal's its last digit, and an exponent form is a DOUBLE."""
|
|
456
|
+
if "e" in text:
|
|
457
|
+
return Fraction(0)
|
|
458
|
+
_, _, decimals = text.partition(".")
|
|
459
|
+
return Fraction(1, 2 * 10 ** len(decimals))
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
def _number(text: str) -> Fraction:
|
|
463
|
+
return Fraction(Decimal(text))
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
def _render(values: frozenset[ir.LiteralValue]) -> str:
|
|
467
|
+
return ", ".join(value.sql() for value in sorted(values, key=_order)) if values else "no non-null value"
|
|
468
|
+
|
|
469
|
+
|
|
470
|
+
def _order(value: ir.LiteralValue) -> tuple[str, Fraction, str]:
|
|
471
|
+
"""Booleans, then numbers by value, then strings: a fixed reading order."""
|
|
472
|
+
return value.type, _number(value.text) if value.type == "numeric" else Fraction(0), value.text
|