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
|
@@ -0,0 +1,564 @@
|
|
|
1
|
+
"""Why a Unique Set assertion is UNKNOWN: the relations it passes through,
|
|
2
|
+
down to the Causes that lose it (CONTEXT.md, Cause).
|
|
3
|
+
|
|
4
|
+
The walk reads the closure `unique_set` took and the analyses that closure
|
|
5
|
+
ran; it proves nothing of its own, so it never changes an outcome. At each
|
|
6
|
+
relation it asks one question, whether the asserted columns reach its Row
|
|
7
|
+
Identity there, and follows the inputs that decide it:
|
|
8
|
+
|
|
9
|
+
- an Alias, projection, filter, LIMIT, semi or anti join passes the question
|
|
10
|
+
to its input; a CTE or view is a Step of its own, over its body; an
|
|
11
|
+
asserted column a projection computes without keeping its input's values
|
|
12
|
+
apart is a Cause there;
|
|
13
|
+
- a join must match each row of the input the columns fix at most once in
|
|
14
|
+
the other; a many-to-one join repeats no left row, so the walk follows its
|
|
15
|
+
left input (a one-to-many one, its right). A join that falls short is a
|
|
16
|
+
Cause, with its Unproved Join Reason for that direction and the key the
|
|
17
|
+
matched input misses;
|
|
18
|
+
- a UNION needs a column that separates its inputs and each input unique; an
|
|
19
|
+
EXCEPT ALL or INTERSECT ALL keeps its left input's rows;
|
|
20
|
+
- any other relation (a table, a GROUP BY, a DISTINCT) is a Cause when the
|
|
21
|
+
columns miss every key it has: its closest minimal keys, and what each lacks.
|
|
22
|
+
|
|
23
|
+
A relation where the question is answered PROVED is one line: its proof is
|
|
24
|
+
not repeated.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from __future__ import annotations
|
|
28
|
+
|
|
29
|
+
from collections.abc import Callable, Iterable
|
|
30
|
+
from dataclasses import dataclass
|
|
31
|
+
|
|
32
|
+
from sqlassert import ir
|
|
33
|
+
from sqlassert.diagnostics import quoted
|
|
34
|
+
from sqlassert.provenance import Origin
|
|
35
|
+
from sqlassert.python_engine import Result, current_arena
|
|
36
|
+
from sqlassert.reporting import CauseTag, Step
|
|
37
|
+
from sqlassert.rules.column_set import Attribute, Closure, RowIdentity
|
|
38
|
+
from sqlassert.rules.equality import _constant_value, _typed_arms
|
|
39
|
+
from sqlassert.rules.join_cardinality import Side, _unsupported_under, many_to_one_join, one_to_many_join, unproved_join
|
|
40
|
+
from sqlassert.rules.value_typing import respected_inputs, stopping_call, untyped_source
|
|
41
|
+
from sqlassert.rules.uniqueness import _closure, _definite, _distinct_tags, _functional_dependencies, _one_to_one, _padded_with
|
|
42
|
+
|
|
43
|
+
# Who can act on each Unproved Join Reason. A cascade is no Cause of its own:
|
|
44
|
+
# the walk follows it to the join or relation below that is.
|
|
45
|
+
_JOIN_TAGS: dict[str, CauseTag] = {
|
|
46
|
+
"unsupported": "sqlassert", "unresolved-key": "sqlassert", "untyped-key": "sqlassert", "expression-key": "sqlassert",
|
|
47
|
+
"unconstrained": "sql", "partial-key": "sql", "undeclared-key": "declare",
|
|
48
|
+
# An untyped key from a table with no declared type: declaring the table fixes it.
|
|
49
|
+
"table": "declare",
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
# Codes of a relation's own key gap: folded into the join that matches it.
|
|
53
|
+
_KEY_GAPS = {"missing-key-columns", "no-unique-set", "nullable-key", "undeclared-table"}
|
|
54
|
+
|
|
55
|
+
# The longest relation text shown before it is shortened.
|
|
56
|
+
_WIDTH = 80
|
|
57
|
+
|
|
58
|
+
# Hidden outputs (a GROUP BY or PARTITION BY key not selected) are named so.
|
|
59
|
+
_HIDDEN = "\0"
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass(frozen=True)
|
|
63
|
+
class _Place:
|
|
64
|
+
"""How the relation being walked is named, and where it is written."""
|
|
65
|
+
|
|
66
|
+
subject: str
|
|
67
|
+
origin: Origin | None = None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def null_causes(columns: frozenset[ir.OutputColumn], place: _Place) -> tuple[Step, ...]:
|
|
71
|
+
from sqlassert.rules.causes.nulls import null_causes as causes # The null walk names places as this module does.
|
|
72
|
+
|
|
73
|
+
return causes(columns, place)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def explain_unique_set(columns: frozenset[ir.OutputColumn], non_null: bool) -> Step | None:
|
|
77
|
+
"""Why `columns` is not proved a Unique Set (a Non-Null one when
|
|
78
|
+
`non_null`): a Step for the asserted relation over the relations the
|
|
79
|
+
explanation follows. None when no Cause is found, so the caller falls back
|
|
80
|
+
to the proof itself. Runs inside an analysis session."""
|
|
81
|
+
program = current_arena().program
|
|
82
|
+
relation = program.relation_of(columns)
|
|
83
|
+
if relation is None:
|
|
84
|
+
return None
|
|
85
|
+
place = asserted_place(relation)
|
|
86
|
+
closure = _closure(relation, frozenset(columns), frozenset(columns))
|
|
87
|
+
unique = RowIdentity(relation) in closure.value.columns
|
|
88
|
+
steps = () if unique else walk_unique(closure, place)
|
|
89
|
+
nullable = null_causes(columns, place) if non_null else ()
|
|
90
|
+
named = names(column for column in relation.output_columns if column in columns)
|
|
91
|
+
top = Step(f"{place.subject}: {'unique' if unique else 'not unique'} on {named}", unique, None, steps=(*steps, *nullable))
|
|
92
|
+
return top if top.causes() else None
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def explain_dependency(determinant: frozenset[ir.OutputColumn], dependent: frozenset[ir.OutputColumn]) -> Step | None:
|
|
96
|
+
"""Why `determinant` is not proved to determine `dependent`: for each
|
|
97
|
+
dependent column the closure misses, the walk down to where its value is
|
|
98
|
+
no longer fixed by the determinant's."""
|
|
99
|
+
program = current_arena().program
|
|
100
|
+
relation = program.relation_of(determinant | dependent)
|
|
101
|
+
if relation is None:
|
|
102
|
+
return None
|
|
103
|
+
place = asserted_place(relation)
|
|
104
|
+
closure = _closure(relation, frozenset(determinant), frozenset(determinant))
|
|
105
|
+
missed = [column for column in relation.output_columns if column in dependent and column not in closure.value.columns]
|
|
106
|
+
steps = tuple(step for column in missed for step in walk_dependent(closure, column, place))
|
|
107
|
+
top = Step(f"{place.subject}: {names(column for column in relation.output_columns if column in determinant)} does not determine "
|
|
108
|
+
f"{names(missed)}", False, None, steps=steps)
|
|
109
|
+
return top if top.causes() else None
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def walk_dependent(closure: Result[Closure], target: ir.OutputColumn, place: _Place) -> tuple[Step, ...]:
|
|
113
|
+
"""Why the closure does not reach `target`, a column of its relation: the
|
|
114
|
+
walk follows the input columns its value comes from, to the relation
|
|
115
|
+
whose rows the determinant does not fix (where the Unique Set walk takes
|
|
116
|
+
over) or the expression that loses it."""
|
|
117
|
+
relation = closure.value.relation.closed
|
|
118
|
+
place = own_place(relation, place)
|
|
119
|
+
if target in closure.value.columns:
|
|
120
|
+
return ()
|
|
121
|
+
match relation:
|
|
122
|
+
case ir.Alias(source=source) | ir.NamedRelation(body=ir.RelationExpr() as source) | ir.Filter(input=source) | ir.Limit(input=source) | ir.Join(kind="semi" | "anti", left=source):
|
|
123
|
+
return _follow_value(closure, target, source, place)
|
|
124
|
+
case ir.Project(input=source):
|
|
125
|
+
at = _Place(place.subject, _spanned(relation.origin, place))
|
|
126
|
+
if target not in _one_to_one(relation, source) and not isinstance(target.scalar_expr, ir.ColumnRef):
|
|
127
|
+
read = ir.determinants(target.scalar_expr)
|
|
128
|
+
if read is None:
|
|
129
|
+
return (computed_column(target, at),)
|
|
130
|
+
inner = _input(closure, source)
|
|
131
|
+
if inner is not None and all(column in inner.value.columns for column in read):
|
|
132
|
+
# Its inputs are fixed, yet two equal inputs may give it different values.
|
|
133
|
+
written = brief(target.origin.detail.rsplit(" AS ", 1)[0])
|
|
134
|
+
details = (respected_inputs(target.scalar_expr).reason, _RESPECTS_HINT)
|
|
135
|
+
return (Step(f"{quoted(target.name)} = {written}: inputs that compare equal may give it different values", False, at.origin,
|
|
136
|
+
"sqlassert", "not-identity", details),)
|
|
137
|
+
return _follow_value(closure, target, source, place)
|
|
138
|
+
case ir.Join():
|
|
139
|
+
side = join_side(relation, target)
|
|
140
|
+
if side is None:
|
|
141
|
+
return (_keys(closure, relation, place),)
|
|
142
|
+
matched, source = side
|
|
143
|
+
inner = _input(closure, source)
|
|
144
|
+
if inner is None or RowIdentity(source) in closure.value.columns:
|
|
145
|
+
return _follow_value(closure, target, source, place)
|
|
146
|
+
reads = _upstream(target, source)
|
|
147
|
+
below = tuple(step for column in reads for step in walk_dependent(inner, column, side_place(source, relation)))
|
|
148
|
+
if matched == "right" and not many_to_one_join(relation).value:
|
|
149
|
+
return (join_cause(relation, "right", below),)
|
|
150
|
+
return below
|
|
151
|
+
case _:
|
|
152
|
+
# A table, a GROUP BY, a DISTINCT, a set operation: the row decides the value.
|
|
153
|
+
return walk_unique(closure, place)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def join_side(join: ir.Join, column: ir.OutputColumn) -> tuple[Side, ir.RelationExpr] | None:
|
|
157
|
+
"""The input a join's output column comes from."""
|
|
158
|
+
if not isinstance(column.scalar_expr, ir.ColumnRef):
|
|
159
|
+
return None
|
|
160
|
+
source = column.scalar_expr.column
|
|
161
|
+
if source in join.left.output_columns:
|
|
162
|
+
return "left", join.left
|
|
163
|
+
if source in join.right.output_columns:
|
|
164
|
+
return "right", join.right
|
|
165
|
+
return None
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _follow_value(closure: Result[Closure], target: ir.OutputColumn, source: ir.RelationExpr, place: _Place) -> tuple[Step, ...]:
|
|
169
|
+
inner = _input(closure, source)
|
|
170
|
+
if inner is None:
|
|
171
|
+
return (Step(f"{place.subject}: sqlassert does not follow {quoted(target.name)} into it", False, place.origin, "sqlassert", "not-followed"),)
|
|
172
|
+
return tuple(step for column in _upstream(target, source) for step in walk_dependent(inner, column, place))
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _upstream(target: ir.OutputColumn, source: ir.RelationExpr) -> tuple[ir.OutputColumn, ...]:
|
|
176
|
+
"""The columns of `source` that `target`'s value is computed from."""
|
|
177
|
+
read = ir.determinants(target.scalar_expr) or ()
|
|
178
|
+
return tuple(column for column in read if column in source.output_columns)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def asserted_place(relation: ir.RelationExpr) -> _Place:
|
|
182
|
+
"""The relation a marker asserts about, named by its Attachment Site."""
|
|
183
|
+
program = current_arena().program
|
|
184
|
+
label = next((site.label for site, node in program.attachment_sites if node is relation), None)
|
|
185
|
+
if label is None and isinstance(relation, ir.NamedRelation | ir.Alias):
|
|
186
|
+
return own_place(relation, _Place(relation.name))
|
|
187
|
+
return _Place("the final SELECT" if label in (None, "Root Select") else label, relation.origin if relation.origin.span else None)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def walk_unique(closure: Result[Closure], place: _Place) -> tuple[Step, ...]:
|
|
191
|
+
"""Steps saying why the closure misses its relation's Row Identity, or one
|
|
192
|
+
PROVED Step when it reaches it."""
|
|
193
|
+
relation = closure.value.relation.closed
|
|
194
|
+
place = own_place(relation, place)
|
|
195
|
+
if RowIdentity(closure.value.relation) in closure.value.columns:
|
|
196
|
+
return (Step(f"{place.subject}: unique on {_requested(closure)}", True, place.origin),)
|
|
197
|
+
match relation:
|
|
198
|
+
case ir.Alias(source=source):
|
|
199
|
+
return _follow(closure, source, place)
|
|
200
|
+
case ir.NamedRelation(body=ir.RelationExpr() as body):
|
|
201
|
+
inner = _follow(closure, body, place)
|
|
202
|
+
return (Step(f"{place.subject}: not unique on {_requested(closure)}", False, place.origin, steps=inner),)
|
|
203
|
+
case ir.Project(input=source):
|
|
204
|
+
return _project(closure, relation, source, place)
|
|
205
|
+
case ir.Filter(input=source) | ir.Limit(input=source) | ir.Join(kind="semi" | "anti", left=source):
|
|
206
|
+
return _follow(closure, source, place)
|
|
207
|
+
case ir.Join():
|
|
208
|
+
return _join(closure, relation, place)
|
|
209
|
+
case ir.SetOperation(operator="union"):
|
|
210
|
+
return _union(closure, relation)
|
|
211
|
+
case ir.SetOperation(distinct=False, left=source):
|
|
212
|
+
# EXCEPT ALL and INTERSECT ALL keep left rows, as many as each input allows.
|
|
213
|
+
return _follow(closure, source, place)
|
|
214
|
+
case ir.OpaqueRelation():
|
|
215
|
+
return (_opaque(relation, place),)
|
|
216
|
+
case _:
|
|
217
|
+
return (_keys(closure, relation, place),)
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def own_place(relation: ir.RelationExpr, place: _Place) -> _Place:
|
|
221
|
+
"""How `relation` is named: an Alias or a CTE or view by itself, a clause
|
|
222
|
+
that keeps one row per key by that clause, anything else as the relation
|
|
223
|
+
that reads it names it."""
|
|
224
|
+
match relation.closed:
|
|
225
|
+
case ir.Alias() as alias:
|
|
226
|
+
return _alias_place(alias)
|
|
227
|
+
case ir.NamedRelation(body=ir.RelationExpr()) as named:
|
|
228
|
+
return _named_place(named)
|
|
229
|
+
case ir.Aggregate(grouping_outputs=grouping):
|
|
230
|
+
return _Place(f"GROUP BY {listed(grouping)}", _spanned(relation.origin, place))
|
|
231
|
+
case ir.Distinct():
|
|
232
|
+
return _Place("SELECT DISTINCT", _spanned(relation.origin, place))
|
|
233
|
+
case ir.QualifyByPartition(partition_outputs=partition):
|
|
234
|
+
return _Place(f"one row per {names(partition)}", _spanned(relation.origin, place))
|
|
235
|
+
case ir.SetOperation(operator=operator, distinct=distinct):
|
|
236
|
+
return _Place(f"{operator.upper()}{'' if distinct else ' ALL'}", _spanned(relation.origin, place))
|
|
237
|
+
case _:
|
|
238
|
+
return place
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _spanned(origin: Origin, place: _Place) -> Origin | None:
|
|
242
|
+
return origin if origin.span is not None else place.origin
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _follow(closure: Result[Closure], source: ir.RelationExpr, place: _Place) -> tuple[Step, ...]:
|
|
246
|
+
"""The walk of the closure the relation took in `source`."""
|
|
247
|
+
inner = _input(closure, source)
|
|
248
|
+
if inner is None:
|
|
249
|
+
return (Step(f"{place.subject}: sqlassert does not follow the asserted columns into it", False, place.origin, "sqlassert", "not-followed"),)
|
|
250
|
+
return walk_unique(inner, place)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _input(closure: Result[Closure], source: ir.RelationExpr) -> Result[Closure] | None:
|
|
254
|
+
return next((inner for inner in closure.value.inputs if inner.value.relation is source), None)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _alias_place(alias: ir.Alias) -> _Place:
|
|
258
|
+
"""A table is named as it is read (`accounts AS a`), a derived table by
|
|
259
|
+
its alias; a CTE or view names itself."""
|
|
260
|
+
match alias.source.closed:
|
|
261
|
+
case ir.NamedRelation(body=None):
|
|
262
|
+
return _Place(brief(alias.origin.detail), alias.origin)
|
|
263
|
+
case ir.NamedRelation() as named:
|
|
264
|
+
return _named_place(named)
|
|
265
|
+
case _:
|
|
266
|
+
return _Place(f"subquery {alias.name}", alias.origin)
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def _named_place(relation: ir.NamedRelation) -> _Place:
|
|
270
|
+
"""A CTE or view, named where it is defined."""
|
|
271
|
+
kind = "CTE" if relation.role is ir.RelationRole.CTE else relation.role.value
|
|
272
|
+
return _Place(f"{kind} {relation.name}", relation.origin)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _project(closure: Result[Closure], project: ir.Project, source: ir.RelationExpr, place: _Place) -> tuple[Step, ...]:
|
|
276
|
+
"""A projection passes the question to its input, except for an asserted
|
|
277
|
+
column it computes so that two input rows may give it one value."""
|
|
278
|
+
_, requested, _ = closure.subjects
|
|
279
|
+
assert isinstance(requested, frozenset)
|
|
280
|
+
kept = _one_to_one(project, source)
|
|
281
|
+
inner = _input(closure, source)
|
|
282
|
+
reached = inner.value.columns if inner is not None else set()
|
|
283
|
+
|
|
284
|
+
def loses(column: ir.OutputColumn) -> bool:
|
|
285
|
+
# A constant, or a function of input columns the walk fixes anyway, loses nothing.
|
|
286
|
+
read = ir.determinants(column.scalar_expr)
|
|
287
|
+
return read is None or not all(member in reached for member in read)
|
|
288
|
+
|
|
289
|
+
computed = [column for column in project.output_columns if column in requested and column not in kept and loses(column)]
|
|
290
|
+
at = _Place(place.subject, _spanned(project.origin, place))
|
|
291
|
+
causes = tuple(computed_column(column, at) for column in computed)
|
|
292
|
+
passed = any(column in kept for column in requested)
|
|
293
|
+
return (*(_follow(closure, source, place) if passed or not causes else ()), *causes)
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
# What fixes a computed value, for a Cause where a function does not.
|
|
297
|
+
_RESPECTS_HINT = "a function fixes its value only where inputs that compare equal give equal values: -0.0 = 0.0 as a DOUBLE, but not as text"
|
|
298
|
+
|
|
299
|
+
# What keeps rows apart, for a Cause where a computed key does not.
|
|
300
|
+
_KEEPS_HINT = "only a column, or a function that keeps different values different (x + 1 over integers, a CAST that widens), keeps rows apart"
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def computed_column(column: ir.OutputColumn, place: _Place) -> Step:
|
|
304
|
+
"""A column whose expression may give rows that differ one value, with
|
|
305
|
+
the call that may (`merging_call`)."""
|
|
306
|
+
written = brief(column.origin.detail.rsplit(" AS ", 1)[0])
|
|
307
|
+
if isinstance(column.scalar_expr, ir.OpaqueExpression):
|
|
308
|
+
return Step(f"{quoted(column.name)} = {written}: sqlassert does not model its values", False, place.origin, "sqlassert", "opaque-column")
|
|
309
|
+
merging = merging_call(column.scalar_expr)
|
|
310
|
+
return Step(f"{quoted(column.name)} = {written} may give two rows one value", False, place.origin, "sql", "computed-column",
|
|
311
|
+
(*((merging,) if merging else ()), _KEEPS_HINT))
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def merging_call(expression: ir.ScalarExpr) -> str | None:
|
|
315
|
+
"""The call in `expression` that may give two values one result, and its
|
|
316
|
+
property function's reason (`stopping_call`), `CAST(s AS INT): a cast
|
|
317
|
+
from VARCHAR to INT may make two values one (...)`; None when no one call
|
|
318
|
+
is to blame."""
|
|
319
|
+
stop = stopping_call(expression)
|
|
320
|
+
if stop is None:
|
|
321
|
+
return None
|
|
322
|
+
call, reason = stop
|
|
323
|
+
return f"{brief(call.description)}: {reason}"
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def _opaque(relation: ir.RelationExpr, place: _Place) -> Step:
|
|
327
|
+
construct = _unsupported_under(relation)
|
|
328
|
+
return Step(f"{place.subject}: its rows are not modelled", False, place.origin, "sqlassert", "unsupported",
|
|
329
|
+
(f"{construct} is not supported by sqlassert yet",) if construct else ())
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def _join(closure: Result[Closure], join: ir.Join, place: _Place) -> tuple[Step, ...]:
|
|
333
|
+
"""A join needs each row of the input the columns fix to match at most
|
|
334
|
+
once in the other input."""
|
|
335
|
+
reached = closure.value.columns
|
|
336
|
+
left, right = RowIdentity(join.left) in reached, RowIdentity(join.right) in reached
|
|
337
|
+
subject = brief(join.origin.detail)
|
|
338
|
+
if left and not right:
|
|
339
|
+
return _matched(closure, join, "right")
|
|
340
|
+
# A many-to-one join repeats no left row: the left input is what is not unique.
|
|
341
|
+
if many_to_one_join(join).value:
|
|
342
|
+
return (*_follow(closure, join.left, place), Step(f"{subject}: many-to-one", True, join.origin))
|
|
343
|
+
if right and not left:
|
|
344
|
+
return _matched(closure, join, "left")
|
|
345
|
+
# A table function's rows have no key: follow the left input, whose rows it repeats.
|
|
346
|
+
if one_to_many_join(join).value and not join.lateral:
|
|
347
|
+
return (*_follow(closure, join.right, place), Step(f"{subject}: one-to-many", True, join.origin))
|
|
348
|
+
return (*_follow(closure, join.left, place), *_matched(closure, join, "right"))
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def _matched(closure: Result[Closure], join: ir.Join, matched: Side) -> tuple[Step, ...]:
|
|
352
|
+
"""The join as a Cause: a row of the other input may match several rows
|
|
353
|
+
of `matched`, with what `matched` lacks."""
|
|
354
|
+
side = join.right if matched == "right" else join.left
|
|
355
|
+
inner = _input(closure, side)
|
|
356
|
+
if join.lateral and matched == "right":
|
|
357
|
+
return (Step(f"{brief(join.origin.detail)} repeats each row of its left input once per row it returns", False, join.origin, "sql", "table-function"),)
|
|
358
|
+
return (join_cause(join, matched, walk_unique(inner, side_place(side, join)) if inner is not None else ()),)
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def join_cause(join: ir.Join, matched: Side, side: tuple[Step, ...]) -> Step:
|
|
362
|
+
"""A join whose rows of the other input may each match several rows of
|
|
363
|
+
`matched`: its Unproved Join Reason in that direction; `side`, the walk
|
|
364
|
+
into `matched`, gives the detail (a table's key gap) or the Steps under it."""
|
|
365
|
+
subject = brief(join.origin.detail)
|
|
366
|
+
reason = unproved_join(join, matched)
|
|
367
|
+
if reason is None:
|
|
368
|
+
# Proved in this direction, yet the identity is not reached: a padded side.
|
|
369
|
+
return Step(f"{subject}: its padded rows cannot be told apart", False, join.origin, "sqlassert", "padded-rows", steps=side)
|
|
370
|
+
details: list[str] = []
|
|
371
|
+
nested: list[Step] = []
|
|
372
|
+
# An ON that binds no column of the input: its keys are beside the point.
|
|
373
|
+
binds = reason.reason not in {"unsupported", "unconstrained", "unresolved-key", "untyped-key", "expression-key"}
|
|
374
|
+
for step in side if binds else ():
|
|
375
|
+
if step.tag is not None and not step.steps and step.code in _KEY_GAPS:
|
|
376
|
+
details.extend((step.text, *step.details))
|
|
377
|
+
elif not step.proved:
|
|
378
|
+
nested.append(step)
|
|
379
|
+
if reason.construct is not None:
|
|
380
|
+
details.append(f"{reason.construct} is not supported by sqlassert yet")
|
|
381
|
+
if reason.untyped is not None:
|
|
382
|
+
details.append(_type_lost(reason.untyped, reason.detail))
|
|
383
|
+
merging = _merging_keys(join, matched) if reason.reason == "expression-key" else []
|
|
384
|
+
details.extend(merging)
|
|
385
|
+
code = reason.reason if reason.detail is None else f"{reason.reason} ({reason.detail})"
|
|
386
|
+
# A key the matched input lacks because of something below it: that is the Cause.
|
|
387
|
+
deferred = reason.reason == "no-unique-set" and any(step.causes() for step in nested)
|
|
388
|
+
tag = None if deferred else _JOIN_TAGS.get(reason.detail or "", _JOIN_TAGS.get(reason.reason, "sql"))
|
|
389
|
+
if merging:
|
|
390
|
+
tag = "sql" # A call that may merge values: the SQL, not sqlassert, matches several rows.
|
|
391
|
+
verb = "is not many-to-one" if matched == "right" else "is not one-to-many"
|
|
392
|
+
return Step(f"{subject} {verb}", False, join.origin, tag, code if tag is not None else None, tuple(details), tuple(nested))
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def _merging_keys(join: ir.Join, matched: Side) -> list[str]:
|
|
396
|
+
"""For each ON equality, the call in its operand over `matched` that may
|
|
397
|
+
give two of its rows one value (`merging_call`)."""
|
|
398
|
+
side = join.right if matched == "right" else join.left
|
|
399
|
+
found: dict[str, None] = {}
|
|
400
|
+
for equality in join.conjuncts:
|
|
401
|
+
if not isinstance(equality, ir.Equality | ir.NullSafeEquality):
|
|
402
|
+
continue
|
|
403
|
+
for operand in (equality.left, equality.right):
|
|
404
|
+
read = ir.determinants(operand)
|
|
405
|
+
if read and all(column in side.output_columns for column in read) and (merging := merging_call(operand)) is not None:
|
|
406
|
+
found[merging] = None
|
|
407
|
+
return list(found)
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def _type_lost(column: ir.OutputColumn, loss: str | None) -> str:
|
|
411
|
+
"""Where a join key's type is lost, for an `untyped-key` join."""
|
|
412
|
+
owner = current_arena().program.column_to_parent_relation_index.get(column)
|
|
413
|
+
where = f" (line {column.origin.line})" if column.origin.line else ""
|
|
414
|
+
match loss:
|
|
415
|
+
case "table":
|
|
416
|
+
name = owner.name if isinstance(owner, ir.NamedRelation) else "its table"
|
|
417
|
+
return f"{quoted(column.name)} has no type: {name} is not declared with CREATE TABLE, or not in the catalog"
|
|
418
|
+
case "computed" | "opaque-relation" if not isinstance(owner, ir.OpaqueRelation):
|
|
419
|
+
computed = f"{quoted(column.name)} = {brief(column.origin.detail.rsplit(' AS ', 1)[0])}{where}"
|
|
420
|
+
if (source := untyped_source(column.scalar_expr)) is None:
|
|
421
|
+
return f"{computed} has a type whose equal values need not be identical"
|
|
422
|
+
return f"{computed} has no type sqlassert knows: {_untyped(source, column.scalar_expr.closed)}"
|
|
423
|
+
case "values":
|
|
424
|
+
return f"{quoted(column.name)} of a VALUES list{where} has no type that compares by identity"
|
|
425
|
+
case "set-operation":
|
|
426
|
+
return f"{quoted(column.name)} of a set operation{where} pairs inputs whose types are not known to agree"
|
|
427
|
+
case "opaque-relation":
|
|
428
|
+
return f"{quoted(column.name)} comes from a relation sqlassert does not model"
|
|
429
|
+
case _:
|
|
430
|
+
return f"{quoted(column.name)} does not compare with the other key without a lossy coercion"
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def _untyped(source: Result, top: ir.ScalarExpr) -> str:
|
|
434
|
+
"""Why a computed key has no type, from the expression in it that loses
|
|
435
|
+
the type (`untyped_source`): the key's own, or one nested in it, named."""
|
|
436
|
+
subject = source.subjects[0]
|
|
437
|
+
match subject:
|
|
438
|
+
case ir.Call():
|
|
439
|
+
why = ("no result type is known for its function", "has no result type sqlassert knows")
|
|
440
|
+
case ir.OpaqueExpression():
|
|
441
|
+
why = ("sqlassert does not model it", "is not modelled by sqlassert")
|
|
442
|
+
case ir.Constant():
|
|
443
|
+
why = ("no type is claimed for the literal in this dialect", "has no type claimed in this dialect")
|
|
444
|
+
case _:
|
|
445
|
+
reason = source.reason[0].lower() + source.reason[1:]
|
|
446
|
+
why = (reason, f"has no type: {reason}")
|
|
447
|
+
if subject is top or not isinstance(subject, ir.ScalarExpr):
|
|
448
|
+
return why[0]
|
|
449
|
+
return f"{brief(subject.origin.detail)} {why[1]}"
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def side_place(side: ir.RelationExpr, join: ir.Join) -> _Place:
|
|
453
|
+
"""An input of a join, named as it is read."""
|
|
454
|
+
if isinstance(source := side.closed, ir.Alias):
|
|
455
|
+
return _alias_place(source)
|
|
456
|
+
return _Place("its input", join.origin)
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def _union(closure: Result[Closure], union: ir.SetOperation) -> tuple[Step, ...]:
|
|
460
|
+
reached = closure.value.columns
|
|
461
|
+
is_definite = _definiteness(closure)
|
|
462
|
+
arms = {column: pair for column in union.output_columns if (pair := _typed_arms(union, column)) is not None}
|
|
463
|
+
determined = [column for column in arms if column in reached]
|
|
464
|
+
separator = next((column for column in determined if _separates(arms[column])), None)
|
|
465
|
+
inputs: list[Step] = []
|
|
466
|
+
for side, source in enumerate((union.left, union.right)):
|
|
467
|
+
inner = _closure(
|
|
468
|
+
source, frozenset(arms[column][side] for column in determined),
|
|
469
|
+
frozenset(arms[column][side] for column in determined if is_definite(column)),
|
|
470
|
+
)
|
|
471
|
+
ordinal = "first" if side == 0 else "second"
|
|
472
|
+
inputs.extend(walk_unique(inner, _Place(f"its {ordinal} input", source.origin if source.origin.span else None)))
|
|
473
|
+
name = "UNION" if union.distinct else "UNION ALL"
|
|
474
|
+
origin = union.origin if union.origin.span else None
|
|
475
|
+
if separator is not None:
|
|
476
|
+
return (Step(f"{name}: inputs separated by {quoted(separator.name)}", True, origin, steps=tuple(inputs)),)
|
|
477
|
+
return (Step(
|
|
478
|
+
f"{name}: no asserted column separates its inputs", False, origin, "sql", "inputs-not-separated",
|
|
479
|
+
("a column holding a different constant in each input, such as a literal tag, tells their rows apart",),
|
|
480
|
+
tuple(inputs),
|
|
481
|
+
),)
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
def _separates(arms: tuple[ir.OutputColumn, ir.OutputColumn]) -> bool:
|
|
485
|
+
"""Whether a UNION column is a constant different in each input, as
|
|
486
|
+
`_separated_inputs` requires."""
|
|
487
|
+
first, second = (_constant_value(arm) for arm in arms)
|
|
488
|
+
return first.value is not None and second.value is not None and _distinct_tags(arms, first.value[0], second.value[0])
|
|
489
|
+
|
|
490
|
+
|
|
491
|
+
def _keys(closure: Result[Closure], relation: ir.RelationExpr, place: _Place) -> Step:
|
|
492
|
+
"""A relation whose keys the reached columns miss: each closest minimal
|
|
493
|
+
key, and what it lacks."""
|
|
494
|
+
reached = closure.value.columns
|
|
495
|
+
have = _requested(closure)
|
|
496
|
+
missed = f"{place.subject}: {have} is not a key" if have != "()" else f"{place.subject}: none of its columns is fixed"
|
|
497
|
+
if isinstance(relation, ir.NamedRelation) and relation.role is ir.RelationRole.TABLE and not relation.is_schema_complete:
|
|
498
|
+
return Step(f"{place.subject}: no CREATE TABLE declares it, so its keys are unknown", False, place.origin, "declare", "undeclared-table",
|
|
499
|
+
("declare it with CREATE TABLE, or analyze with a database connection",))
|
|
500
|
+
keys = relation_keys(closure.value.relation)
|
|
501
|
+
if not keys:
|
|
502
|
+
hint = "declare one if it holds" if isinstance(relation, ir.NamedRelation) else "nothing below it keeps its rows apart"
|
|
503
|
+
return Step(missed, False, place.origin, "declare" if isinstance(relation, ir.NamedRelation) else "sql", "no-unique-set",
|
|
504
|
+
(f"it has no Unique Set: {hint}",))
|
|
505
|
+
gaps = [(key, [column for column in relation.output_columns if column in key and column not in reached]) for key in keys]
|
|
506
|
+
fewest = min(len(missing) for _, missing in gaps)
|
|
507
|
+
closest = [(key, missing) for key, missing in gaps if len(missing) == fewest]
|
|
508
|
+
if fewest == 0:
|
|
509
|
+
is_definite = _definiteness(closure)
|
|
510
|
+
nullable = [column for key, _ in closest for column in relation.output_columns if column in key and not is_definite(column)]
|
|
511
|
+
return Step(f"{place.subject}: {have} covers a key whose columns may be NULL", False, place.origin, "sql", "nullable-key",
|
|
512
|
+
(f"a key holds only where {listed(dict.fromkeys(nullable))} are non-null",))
|
|
513
|
+
return Step(missed, False, place.origin, "sql", "missing-key-columns", tuple(
|
|
514
|
+
f"closest minimal key {names(column for column in relation.output_columns if column in key)}, missing {listed(missing)}"
|
|
515
|
+
for key, missing in closest
|
|
516
|
+
))
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
def relation_keys(relation: ir.RelationExpr) -> list[frozenset[ir.OutputColumn]]:
|
|
520
|
+
"""The minimal keys a relation introduces itself, over its own columns."""
|
|
521
|
+
identity = RowIdentity(relation)
|
|
522
|
+
keys = [
|
|
523
|
+
frozenset(column for column in dependency.determinant if isinstance(column, ir.OutputColumn))
|
|
524
|
+
for dependency in _functional_dependencies(relation).value
|
|
525
|
+
if dependency.dependent == identity and all(isinstance(member, ir.OutputColumn) for member in dependency.determinant)
|
|
526
|
+
]
|
|
527
|
+
return [key for key in dict.fromkeys(keys) if not any(other < key for other in keys)]
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
def _definiteness(closure: Result[Closure]) -> Callable[[Attribute], bool]:
|
|
531
|
+
"""`_closure`'s own test of a non-null attribute, for the closure taken."""
|
|
532
|
+
relation, _, definite = closure.subjects
|
|
533
|
+
assert isinstance(relation, ir.RelationExpr) and isinstance(definite, frozenset)
|
|
534
|
+
return lambda attribute: attribute in definite or _definite(relation, attribute) or _padded_with(relation, attribute, definite)
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
def _requested(closure: Result[Closure]) -> str:
|
|
538
|
+
"""The columns the closure was taken from: those the assertion fixes in this relation."""
|
|
539
|
+
_, columns, _ = closure.subjects
|
|
540
|
+
assert isinstance(columns, frozenset)
|
|
541
|
+
return names(column for column in closure.value.relation.output_columns if column in columns)
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
def names(columns: Iterable[ir.OutputColumn]) -> str:
|
|
545
|
+
return f"({listed(columns)})"
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
def listed(columns: Iterable[ir.OutputColumn]) -> str:
|
|
549
|
+
return ", ".join(shown(column) for column in columns)
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
def shown(column: ir.OutputColumn) -> str:
|
|
553
|
+
"""A column's name, or for a hidden one the expression it holds."""
|
|
554
|
+
if column.name.startswith(_HIDDEN):
|
|
555
|
+
return " ".join(column.origin.detail.rsplit(" AS ", 1)[0].split())
|
|
556
|
+
return column.name
|
|
557
|
+
|
|
558
|
+
|
|
559
|
+
def brief(text: str) -> str:
|
|
560
|
+
"""Relation SQL on one line, its ON condition left out when long."""
|
|
561
|
+
text = " ".join(text.split())
|
|
562
|
+
if len(text) > _WIDTH and " ON " in text:
|
|
563
|
+
text = text.split(" ON ")[0] + " ON …"
|
|
564
|
+
return text if len(text) <= _WIDTH else text[:_WIDTH - 1] + "…"
|
sqlassert/rules/domain.py
CHANGED
|
@@ -37,9 +37,10 @@ from typing import assert_never
|
|
|
37
37
|
from sqlassert.diagnostics import quoted
|
|
38
38
|
from sqlassert import ir
|
|
39
39
|
from sqlassert import properties as props
|
|
40
|
-
from sqlassert.properties import EnumeratedDomain
|
|
40
|
+
from sqlassert.properties import EnumeratedDomain, ExhaustiveCase
|
|
41
41
|
from sqlassert.python_engine import Result, Stratum, analysis, any_of, current_arena, unknown
|
|
42
|
-
from sqlassert.rules.equality import _equal_columns, _lax_equalities
|
|
42
|
+
from sqlassert.rules.equality import _equal_columns, _lax_equalities
|
|
43
|
+
from sqlassert.rules.value_typing import _binary_text as _typed_binary_text, column_ref, exact_comparison
|
|
43
44
|
from sqlassert.rules.nullability import _non_null_expression, non_null_column
|
|
44
45
|
|
|
45
46
|
# A finite set of possible non-null values, or None when any value is possible.
|
|
@@ -49,7 +50,7 @@ _TRUE = ir.LiteralValue(type="boolean", text="TRUE")
|
|
|
49
50
|
_FALSE = ir.LiteralValue(type="boolean", text="FALSE")
|
|
50
51
|
|
|
51
52
|
|
|
52
|
-
@analysis(Stratum.DOMAIN)
|
|
53
|
+
@analysis(Stratum.DOMAIN, evaluates=EnumeratedDomain)
|
|
53
54
|
def enumerated_domain(column: ir.OutputColumn, values: frozenset[ir.LiteralValue]) -> Result[bool]:
|
|
54
55
|
domain = _domain(column)
|
|
55
56
|
if domain.value is None:
|
|
@@ -63,7 +64,7 @@ def enumerated_domain(column: ir.OutputColumn, values: frozenset[ir.LiteralValue
|
|
|
63
64
|
return Result(True, "Every possible value is listed", (column,), [domain])
|
|
64
65
|
|
|
65
66
|
|
|
66
|
-
@analysis(Stratum.DOMAIN)
|
|
67
|
+
@analysis(Stratum.DOMAIN, evaluates=ExhaustiveCase)
|
|
67
68
|
def exhaustive_case(case: ir.SimpleCase) -> Result[bool]:
|
|
68
69
|
operand = _operand_name(case.operand)
|
|
69
70
|
domain = _expression_domain(case.operand)
|
|
@@ -265,7 +266,7 @@ def _expression_domain(expression: ir.ScalarExpr) -> Result[Domain]:
|
|
|
265
266
|
return Result(value, f"Its operand is always NULL, so it is {_render(value)}", (expression,), [absent])
|
|
266
267
|
return Result(None, "Its operand may be NULL or not", (expression,), [present, absent])
|
|
267
268
|
case (
|
|
268
|
-
ir.Constant() | ir.OpaqueExpression() | ir.
|
|
269
|
+
ir.Constant() | ir.OpaqueExpression() | ir.Call() | ir.Count() | ir.Accumulation() | ir.Elements() | ir.Equality()
|
|
269
270
|
| ir.NullSafeEquality() | ir.InList() | ir.And() | ir.Or()
|
|
270
271
|
):
|
|
271
272
|
return Result(None, "Values of this expression are not enumerated", (expression,))
|
|
@@ -317,7 +318,7 @@ def _matched_narrowings(join: ir.Join, column: ir.OutputColumn, source: ir.Outpu
|
|
|
317
318
|
other = second if first is source else first
|
|
318
319
|
case _:
|
|
319
320
|
continue
|
|
320
|
-
if other not in join.right.output_columns or not
|
|
321
|
+
if other not in join.right.output_columns or not exact_comparison(column_ref(source), column_ref(other)).value:
|
|
321
322
|
continue
|
|
322
323
|
bounds = [bound for part in join.conjuncts if part is not conjunct and (bound := _conjunct_bound(part, other)) is not None]
|
|
323
324
|
if bounds:
|
|
@@ -366,7 +367,7 @@ def _bound_domain(column: ir.OutputColumn, expression: ir.ScalarExpr) -> Result[
|
|
|
366
367
|
return Result(None, "An approximate numeric comparison may collapse distinct values", (expression,))
|
|
367
368
|
case ir.Constant() | ir.NullLiteral():
|
|
368
369
|
return _expression_domain(expression)
|
|
369
|
-
case ir.ColumnRef(column=source) if
|
|
370
|
+
case ir.ColumnRef(column=source) if exact_comparison(column_ref(column), expression).value:
|
|
370
371
|
return _expression_domain(expression)
|
|
371
372
|
case _:
|
|
372
373
|
return Result(None, "The comparison may cast its operands, so no value domain is transferred", (expression,))
|
|
@@ -406,7 +407,7 @@ def _binary_text(column: ir.OutputColumn) -> bool:
|
|
|
406
407
|
if not _binary_text(source):
|
|
407
408
|
return False
|
|
408
409
|
case _:
|
|
409
|
-
if not member.
|
|
410
|
+
if not _typed_binary_text(member).value:
|
|
410
411
|
return False
|
|
411
412
|
return True
|
|
412
413
|
|