sqlassert 0.3.3__py3-none-any.whl → 0.4.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sqlassert/__init__.py +1 -2
- sqlassert/check.py +88 -13
- sqlassert/declared_types.py +158 -0
- sqlassert/diagnostics.py +15 -7
- sqlassert/dialects.py +259 -107
- sqlassert/discovery/bigquery.py +4 -2
- sqlassert/discovery/databricks.py +26 -5
- sqlassert/discovery/duckdb.py +49 -7
- sqlassert/discovery/fetcher.py +137 -58
- sqlassert/discovery/information_schema.py +31 -6
- sqlassert/discovery/mysql.py +21 -4
- sqlassert/discovery/postgres.py +28 -20
- sqlassert/discovery/redshift.py +3 -2
- sqlassert/discovery/snowflake.py +5 -2
- sqlassert/discovery/trino.py +2 -2
- sqlassert/functions/__init__.py +10 -0
- sqlassert/functions/load.py +375 -0
- sqlassert/functions/table.py +2721 -0
- sqlassert/hazards.py +249 -88
- sqlassert/ir/__init__.py +15 -4
- sqlassert/ir/convert/__init__.py +13 -0
- sqlassert/ir/convert/aggregation.py +438 -0
- sqlassert/ir/convert/expressions.py +581 -0
- sqlassert/ir/convert/joins.py +264 -0
- sqlassert/ir/convert/markers.py +249 -0
- sqlassert/ir/convert/parser.py +249 -0
- sqlassert/ir/convert/queries.py +259 -0
- sqlassert/ir/convert/schema.py +537 -0
- sqlassert/ir/convert/scopes.py +205 -0
- sqlassert/ir/convert/selects.py +352 -0
- sqlassert/ir/convert/shared.py +428 -0
- sqlassert/ir/convert/sources.py +433 -0
- sqlassert/ir/convert/subqueries.py +364 -0
- sqlassert/ir/convert/value_types.py +78 -0
- sqlassert/ir/convert/windows.py +275 -0
- sqlassert/ir/model.py +417 -146
- sqlassert/ir/names.py +63 -0
- sqlassert/main.py +7 -10
- sqlassert/properties.py +12 -1
- sqlassert/provenance.py +5 -1
- sqlassert/python_engine.py +104 -44
- sqlassert/reporting.py +33 -32
- sqlassert/rewrites.py +111 -61
- sqlassert/rules/STYLEGUIDE.md +3 -2
- sqlassert/rules/causes/__init__.py +41 -0
- sqlassert/rules/causes/coverage.py +113 -0
- sqlassert/rules/causes/domain.py +123 -0
- sqlassert/rules/causes/joins.py +73 -0
- sqlassert/rules/causes/nulls.py +154 -0
- sqlassert/rules/causes/unique.py +564 -0
- sqlassert/rules/domain.py +9 -8
- sqlassert/rules/equality.py +6 -147
- sqlassert/rules/exactly_one.py +2 -1
- sqlassert/rules/foreign_key.py +8 -9
- sqlassert/rules/join_cardinality.py +277 -43
- sqlassert/rules/nullability.py +8 -8
- sqlassert/rules/uniqueness.py +212 -87
- sqlassert/rules/value_typing.py +470 -0
- sqlassert/sql_parse.py +28 -1
- sqlassert/suggest.py +13 -17
- sqlassert-0.4.2.dist-info/METADATA +239 -0
- sqlassert-0.4.2.dist-info/RECORD +72 -0
- sqlassert/ir/convert.py +0 -3509
- sqlassert-0.3.3.dist-info/METADATA +0 -807
- sqlassert-0.3.3.dist-info/RECORD +0 -46
- {sqlassert-0.3.3.dist-info → sqlassert-0.4.2.dist-info}/WHEEL +0 -0
- {sqlassert-0.3.3.dist-info → sqlassert-0.4.2.dist-info}/entry_points.txt +0 -0
- {sqlassert-0.3.3.dist-info → sqlassert-0.4.2.dist-info}/licenses/LICENSE +0 -0
- {sqlassert-0.3.3.dist-info → sqlassert-0.4.2.dist-info}/top_level.txt +0 -0
sqlassert/ir/names.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""The names of a derived table's columns, when some repeat.
|
|
2
|
+
|
|
3
|
+
A derived table (a subquery, CTE, view or aliased join) keeps each column's
|
|
4
|
+
name as written, so a name may repeat. DuckDB renames the repeats: `SELECT *
|
|
5
|
+
FROM (SELECT a.k, b.k, b.k_1 ...) s` has the columns `k, k_1, k_1_1`, so
|
|
6
|
+
`s.k_1` is `b.k` and `b.k_1` is `s.k_1_1`. Another engine rejects the
|
|
7
|
+
reference. Best effort, the same in every dialect (ADR 0008): a repeated name
|
|
8
|
+
binds its first column, and warns; `may_be_renamed` says which names cannot be
|
|
9
|
+
trusted to bind at all, every `<repeated>_<digits>`. A repeat is reached by
|
|
10
|
+
no name: a star carries it on by itself.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import re
|
|
16
|
+
from collections import Counter
|
|
17
|
+
from collections.abc import Iterable, Sequence
|
|
18
|
+
|
|
19
|
+
from sqlassert.ir.model import OutputColumn
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def repeated_names(names: Iterable[str]) -> frozenset[str]:
|
|
23
|
+
"""The lower-case names `names` repeat."""
|
|
24
|
+
counts = Counter(name.lower() for name in names)
|
|
25
|
+
return frozenset(name for name, count in counts.items() if count > 1)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def may_be_renamed(repeated: Iterable[str], name: str) -> bool:
|
|
29
|
+
"""Whether `name` is of the form `<repeated>_<digits>...`: one an engine may
|
|
30
|
+
give a repeat of `repeated` (`k_1`, `k_2`, or `k_1_1` when `k_1` was taken;
|
|
31
|
+
SQLite's is `k:1`)."""
|
|
32
|
+
return any(re.fullmatch(re.escape(base) + r"([_:][0-9]+)+", name.lower()) for base in repeated)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def nameable(columns: Sequence[OutputColumn]) -> tuple[OutputColumn, ...]:
|
|
36
|
+
"""The columns of one relation a marker can name unambiguously: named, not
|
|
37
|
+
a name the relation repeats (the first of a repeat included), and not one
|
|
38
|
+
an engine may have given a repeat."""
|
|
39
|
+
repeated = repeated_names(column.name for column in columns)
|
|
40
|
+
return tuple(
|
|
41
|
+
column for column in columns
|
|
42
|
+
if column.name and column.name.lower() not in repeated and not may_be_renamed(repeated, column.name)
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def named_columns(columns: Sequence[OutputColumn], names: Iterable[str]) -> tuple[dict[str, OutputColumn], list[str], list[str]]:
|
|
47
|
+
"""How a Property Marker, or a test bound as one, names columns of one
|
|
48
|
+
relation: each name that names one column, lower-case, with it; the names
|
|
49
|
+
that are ambiguous (repeated, or one an engine may give a repeat); and
|
|
50
|
+
those that name no column."""
|
|
51
|
+
repeated = repeated_names(column.name for column in columns)
|
|
52
|
+
by_name = {column.name.lower(): column for column in columns}
|
|
53
|
+
found: dict[str, OutputColumn] = {}
|
|
54
|
+
ambiguous: list[str] = []
|
|
55
|
+
unknown: list[str] = []
|
|
56
|
+
for name in names:
|
|
57
|
+
if name.lower() in repeated or may_be_renamed(repeated, name):
|
|
58
|
+
ambiguous.append(name)
|
|
59
|
+
elif name.lower() in by_name:
|
|
60
|
+
found[name.lower()] = by_name[name.lower()]
|
|
61
|
+
else:
|
|
62
|
+
unknown.append(name)
|
|
63
|
+
return found, ambiguous, unknown
|
sqlassert/main.py
CHANGED
|
@@ -15,18 +15,16 @@ if TYPE_CHECKING:
|
|
|
15
15
|
DEFAULT_DIALECT = "duckdb"
|
|
16
16
|
|
|
17
17
|
|
|
18
|
-
def analyze(sql: str, *, dialect: str = DEFAULT_DIALECT
|
|
18
|
+
def analyze(sql: str, *, dialect: str = DEFAULT_DIALECT) -> Report:
|
|
19
19
|
"""Prove the Unique Join Assertions and Unique Set Assertions in one SQL Program.
|
|
20
20
|
|
|
21
21
|
Pure: the Program is the only source of Knowledge. `analyze_database`
|
|
22
22
|
adds a database catalog. Where a catalog would have helped (a table with
|
|
23
23
|
no `CREATE`, a column only a catalog can resolve), the Report warns.
|
|
24
|
-
|
|
25
|
-
not enforce Property Declarations, as `RELY` does; off, they are ignored
|
|
26
|
-
with an `unenforced-constraint` warning (`docs/dialects.md`).
|
|
24
|
+
Every declared constraint is Knowledge, enforced or not (ADR 0012).
|
|
27
25
|
"""
|
|
28
26
|
sql_parser = SqlParser(dialect)
|
|
29
|
-
ir_parser = IrParser(dialect
|
|
27
|
+
ir_parser = IrParser(dialect)
|
|
30
28
|
|
|
31
29
|
ast = sql_parser.parse(sql)
|
|
32
30
|
conversion = ir_parser.parse(ast)
|
|
@@ -35,17 +33,16 @@ def analyze(sql: str, *, dialect: str = DEFAULT_DIALECT, trust_unenforced_keys:
|
|
|
35
33
|
|
|
36
34
|
|
|
37
35
|
def analyze_database(
|
|
38
|
-
sql: str, fetcher: DatabaseKnowledgeFetcher, *, dialect: str = DEFAULT_DIALECT,
|
|
36
|
+
sql: str, fetcher: DatabaseKnowledgeFetcher, *, dialect: str = DEFAULT_DIALECT,
|
|
39
37
|
) -> Report:
|
|
40
38
|
"""`analyze`, with the external Relations the Program reaches hydrated from a catalog.
|
|
41
39
|
|
|
42
40
|
The fetcher reads catalog metadata only, never rows, and binds it to the
|
|
43
41
|
final IR before the engine runs once. No connection warnings: a relation
|
|
44
|
-
the catalog lacks is already a diagnostic.
|
|
45
|
-
|
|
46
|
-
the SQL's own warnings (`diagnostics.SQL_WARNINGS`).
|
|
42
|
+
the catalog lacks is already a diagnostic. The SQL's own warnings stay
|
|
43
|
+
(`diagnostics.SQL_WARNINGS`).
|
|
47
44
|
"""
|
|
48
45
|
ast = SqlParser(dialect).parse(sql)
|
|
49
|
-
conversion, _ = fetcher.convert(ast, dialect=dialect
|
|
46
|
+
conversion, _ = fetcher.convert(ast, dialect=dialect)
|
|
50
47
|
diagnostics = ast.diagnostics + conversion.diagnostics
|
|
51
48
|
return Engine().run(conversion.program, conversion.knowledge, diagnostics, conversion.warnings)
|
sqlassert/properties.py
CHANGED
|
@@ -2,10 +2,21 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
from typing import dataclass_transform
|
|
6
|
+
|
|
5
7
|
from sqlassert.ir.model import Join, LiteralValue, NodeMeta, OutputColumn, SimpleCase
|
|
6
8
|
|
|
7
9
|
|
|
8
|
-
|
|
10
|
+
@dataclass_transform(eq_default=True, frozen_default=True, kw_only_default=True)
|
|
11
|
+
class PropertyMeta(NodeMeta):
|
|
12
|
+
"""Make every Property a value: two claims of the same class over the
|
|
13
|
+
same subjects are one claim (ADR 0002). Its fields hold IR nodes, which
|
|
14
|
+
keep their identity, so equal claims are about the same occurrences."""
|
|
15
|
+
|
|
16
|
+
value_equality = True
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Property(metaclass=PropertyMeta, abstract=True):
|
|
9
20
|
"""One semantic statement, independent of how it enters reasoning."""
|
|
10
21
|
|
|
11
22
|
|
sqlassert/provenance.py
CHANGED
|
@@ -10,6 +10,9 @@ from dataclasses import dataclass
|
|
|
10
10
|
|
|
11
11
|
|
|
12
12
|
SQL = "sql"
|
|
13
|
+
# The SQLGlot meta key of a node that is not the SQL's (a CHECK a catalog
|
|
14
|
+
# declares with its table): its Origin, which diagnostics about it carry.
|
|
15
|
+
ORIGIN_META = "origin"
|
|
13
16
|
|
|
14
17
|
|
|
15
18
|
@dataclass(frozen=True, order=True)
|
|
@@ -42,7 +45,8 @@ class Origin:
|
|
|
42
45
|
"""A SQL source span or catalog fact that a semantic element arose from.
|
|
43
46
|
|
|
44
47
|
`line` is the first source line, when known; `span` the exact region,
|
|
45
|
-
when the element is a Property Marker
|
|
48
|
+
when the element is a Property Marker or a relation an explanation points
|
|
49
|
+
at: a JOIN, a FROM item, a CTE's name (its `line` is then `line`).
|
|
46
50
|
"""
|
|
47
51
|
|
|
48
52
|
kind: str
|
sqlassert/python_engine.py
CHANGED
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
import sys
|
|
6
|
+
from collections.abc import Callable, Generator, Iterable, Iterator
|
|
6
7
|
from contextlib import contextmanager
|
|
7
8
|
from contextvars import ContextVar
|
|
8
9
|
from dataclasses import dataclass, field, fields
|
|
@@ -10,12 +11,10 @@ from enum import IntEnum
|
|
|
10
11
|
from functools import wraps
|
|
11
12
|
from inspect import signature
|
|
12
13
|
|
|
13
|
-
from case_conversion import snake
|
|
14
|
-
|
|
15
14
|
from sqlassert import ir
|
|
16
15
|
from sqlassert.diagnostics import ALWAYS_NULL_COLUMN, DUPLICATE_DECLARATION, UNSUPPORTED_CONSTRUCT, Diagnostic, quoted
|
|
17
16
|
from sqlassert.properties import Property
|
|
18
|
-
from sqlassert.reporting import ASSERTED_KINDS, AssertionReport, Outcome,
|
|
17
|
+
from sqlassert.reporting import ASSERTED_KINDS, AssertionReport, Outcome, Report, Step
|
|
19
18
|
|
|
20
19
|
|
|
21
20
|
@dataclass(eq=False)
|
|
@@ -39,12 +38,18 @@ class Result[T]:
|
|
|
39
38
|
return any_of((self, other))
|
|
40
39
|
|
|
41
40
|
def explain(self) -> str:
|
|
42
|
-
"""Render the evidence, referring back to shared premises by number.
|
|
41
|
+
"""Render the evidence, referring back to shared premises by number.
|
|
42
|
+
|
|
43
|
+
Under an UNKNOWN result, a PROVED premise is one line: what failed is
|
|
44
|
+
what matters, so its proof is not repeated. A PROVED result shows its
|
|
45
|
+
whole proof."""
|
|
43
46
|
lines: list[str] = []
|
|
44
47
|
seen: dict[Result, int] = {}
|
|
48
|
+
folded = self.value is False
|
|
45
49
|
|
|
46
50
|
def visit(result: Result, depth: int) -> None:
|
|
47
51
|
indent = " " * depth
|
|
52
|
+
result, names = _folded(result)
|
|
48
53
|
if result in seen:
|
|
49
54
|
lines.append(f"{indent}see #{seen[result]}")
|
|
50
55
|
return
|
|
@@ -64,11 +69,13 @@ class Result[T]:
|
|
|
64
69
|
case _:
|
|
65
70
|
pass # Property arguments may also be sets and other plain values.
|
|
66
71
|
sources = "; ".join(
|
|
67
|
-
|
|
72
|
+
_cited(origin.detail) + (f" (line {origin.line})" if origin.line is not None else "")
|
|
68
73
|
for origin in dict.fromkeys(locations)
|
|
69
74
|
)
|
|
70
75
|
suffix = f" — {sources}" if sources else ""
|
|
71
|
-
lines.append(f"{indent}#{seen[result]} {state}: {result.reason}{suffix}")
|
|
76
|
+
lines.append(f"{indent}#{seen[result]} {state}: {': '.join((*names, result.reason))}{suffix}")
|
|
77
|
+
if folded and result.value is True:
|
|
78
|
+
return
|
|
72
79
|
for premise in result.premises:
|
|
73
80
|
visit(premise, depth + 1)
|
|
74
81
|
|
|
@@ -76,18 +83,44 @@ class Result[T]:
|
|
|
76
83
|
return "\n".join(lines)
|
|
77
84
|
|
|
78
85
|
|
|
86
|
+
def _folded(result: Result) -> tuple[Result, tuple[str, ...]]:
|
|
87
|
+
"""The line a result is shown as: an analysis's own line (`claim`), or
|
|
88
|
+
"one of"/"each of" over a single premise, folds into that premise, and a
|
|
89
|
+
result into its one premise when that says the same thing about a
|
|
90
|
+
relation further down."""
|
|
91
|
+
names: list[str] = []
|
|
92
|
+
while len(result.premises) == 1:
|
|
93
|
+
premise = result.premises[0]
|
|
94
|
+
generic = result.reason in {"Each of these is needed", "One of these suffices"}
|
|
95
|
+
if result.kind == "claim" or generic or (premise.reason == result.reason and premise.value == result.value):
|
|
96
|
+
if result.kind == "claim" and result.reason not in names:
|
|
97
|
+
names.append(result.reason) # The analysis's name stays on the line it folds into.
|
|
98
|
+
result = premise
|
|
99
|
+
else:
|
|
100
|
+
break
|
|
101
|
+
return result, tuple(names)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _cited(detail: str) -> str:
|
|
105
|
+
"""How evidence cites an Origin: a CREATE statement by its first words
|
|
106
|
+
(`CREATE TABLE users`), not its whole text on every line that cites it."""
|
|
107
|
+
if detail.startswith("CREATE "):
|
|
108
|
+
return detail.split(" (", 1)[0].split(" AS ", 1)[0]
|
|
109
|
+
return detail
|
|
110
|
+
|
|
111
|
+
|
|
79
112
|
def unknown(reason: str, *subjects: object) -> Result[bool]:
|
|
80
113
|
return Result(False, reason, subjects, kind="unknown")
|
|
81
114
|
|
|
82
115
|
|
|
83
116
|
def all_of(results: Iterable[Result[bool]]) -> Result[bool]:
|
|
84
117
|
premises = list(results)
|
|
85
|
-
return Result(all(_boolean_values(premises)), "
|
|
118
|
+
return Result(all(_boolean_values(premises)), "Each of these is needed", premises=premises, kind="all")
|
|
86
119
|
|
|
87
120
|
|
|
88
121
|
def any_of(results: Iterable[Result[bool]]) -> Result[bool]:
|
|
89
122
|
premises = list(results)
|
|
90
|
-
return Result(any(_boolean_values(premises)), "
|
|
123
|
+
return Result(any(_boolean_values(premises)), "One of these suffices", premises=premises, kind="any")
|
|
91
124
|
|
|
92
125
|
|
|
93
126
|
def _boolean_values(results):
|
|
@@ -102,7 +135,8 @@ def _boolean_values(results):
|
|
|
102
135
|
|
|
103
136
|
|
|
104
137
|
_active: ContextVar[Arena] = ContextVar("property_analysis")
|
|
105
|
-
|
|
138
|
+
# Each Property class's evaluator: the analysis function that proves it.
|
|
139
|
+
evaluators: dict[type[Property], Callable[..., Result[bool]]] = {}
|
|
106
140
|
|
|
107
141
|
|
|
108
142
|
def cache(function):
|
|
@@ -118,10 +152,7 @@ def cache(function):
|
|
|
118
152
|
if key in arena.cache:
|
|
119
153
|
return arena.cache[key]
|
|
120
154
|
if key in arena.evaluating:
|
|
121
|
-
raise
|
|
122
|
-
f"cyclic property dependency: {cached.__name__}. This is an internal sqlassert bug, "
|
|
123
|
-
"not a problem with the analyzed SQL: an analysis broke the Stratum order"
|
|
124
|
-
)
|
|
155
|
+
raise _cycle(cached.__name__)
|
|
125
156
|
arena.evaluating.add(key)
|
|
126
157
|
try:
|
|
127
158
|
result = function(*args, **kwargs)
|
|
@@ -133,6 +164,13 @@ def cache(function):
|
|
|
133
164
|
return cached
|
|
134
165
|
|
|
135
166
|
|
|
167
|
+
def _cycle(name: str) -> RuntimeError:
|
|
168
|
+
return RuntimeError(
|
|
169
|
+
f"cyclic property dependency: {name}. This is an internal sqlassert bug, "
|
|
170
|
+
"not a problem with the analyzed SQL: an analysis broke the Stratum order"
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
|
|
136
174
|
class Stratum(IntEnum):
|
|
137
175
|
"""The order in which facts about one relation may use each other.
|
|
138
176
|
|
|
@@ -165,37 +203,52 @@ class Stratum(IntEnum):
|
|
|
165
203
|
DOMAIN = 70
|
|
166
204
|
|
|
167
205
|
|
|
168
|
-
def analysis(stratum: Stratum):
|
|
169
|
-
"""Cache and name an analysis function
|
|
206
|
+
def analysis(stratum: Stratum, evaluates: type[Property] | None = None):
|
|
207
|
+
"""Cache and name an analysis function. One that `evaluates` a Property
|
|
208
|
+
takes that Property's fields as its parameters, and accepted Knowledge of
|
|
209
|
+
the Property stands in for its body."""
|
|
170
210
|
|
|
171
211
|
def decorate(function):
|
|
172
212
|
parameters = signature(function)
|
|
173
213
|
|
|
174
|
-
|
|
214
|
+
# One frame per call, the Stratum check before the cache lookup, so a
|
|
215
|
+
# cached result cannot bypass it and deep chains of views stay within
|
|
216
|
+
# Python's recursion limit.
|
|
175
217
|
@wraps(function)
|
|
176
|
-
def
|
|
218
|
+
def checked(*args, **kwargs):
|
|
177
219
|
bound = parameters.bind(*args, **kwargs)
|
|
178
220
|
bound.apply_defaults()
|
|
179
221
|
arena = current_arena()
|
|
180
|
-
|
|
222
|
+
arguments = tuple(bound.arguments.values())
|
|
223
|
+
relation = _subject_relation(arena.program, arguments)
|
|
181
224
|
if relation is not None:
|
|
182
225
|
for active, active_stratum, name in arena.active:
|
|
183
226
|
assert active is not relation or stratum <= active_stratum, (
|
|
184
227
|
f"{function.__name__} ({stratum.name}) called from {name} ({active_stratum.name}) "
|
|
185
228
|
"about the same relation: a fact may only use facts at its own or a lower stratum"
|
|
186
229
|
)
|
|
230
|
+
key = (function, arguments)
|
|
231
|
+
if key in arena.cache:
|
|
232
|
+
return arena.cache[key]
|
|
233
|
+
if key in arena.evaluating:
|
|
234
|
+
raise _cycle(function.__name__)
|
|
235
|
+
arena.evaluating.add(key)
|
|
187
236
|
arena.active.append((relation, stratum, function.__name__))
|
|
188
237
|
try:
|
|
189
|
-
|
|
190
|
-
accepted = arena.accepted.get((function.__name__, arguments), ())
|
|
238
|
+
accepted = arena.accepted.get(evaluates(**bound.arguments), ()) if evaluates is not None else ()
|
|
191
239
|
result = any_of(accepted) if accepted else function(*args, **kwargs)
|
|
240
|
+
claim = Result(result.value, function.__name__, arguments, [result], "claim", result.members)
|
|
241
|
+
arena.cache[key] = claim
|
|
242
|
+
return claim
|
|
192
243
|
finally:
|
|
193
244
|
arena.active.pop()
|
|
194
|
-
|
|
245
|
+
arena.evaluating.remove(key)
|
|
195
246
|
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
247
|
+
checked.stratum = stratum # ty: ignore[missing-attribute]
|
|
248
|
+
if evaluates is not None:
|
|
249
|
+
assert evaluates not in evaluators, f"{evaluates.__name__} already has an evaluator"
|
|
250
|
+
evaluators[evaluates] = checked
|
|
251
|
+
return checked
|
|
199
252
|
|
|
200
253
|
return decorate
|
|
201
254
|
|
|
@@ -228,7 +281,8 @@ class Arena:
|
|
|
228
281
|
self.cache: dict[tuple, object] = {}
|
|
229
282
|
self.evaluating: set[tuple] = set()
|
|
230
283
|
self.active: list[tuple[ir.RelationExpr | None, Stratum, str]] = []
|
|
231
|
-
|
|
284
|
+
# Each accepted claim's evidence, under every Property class it is an instance of.
|
|
285
|
+
self.accepted: dict[Property, tuple[Result[bool], ...]] = {}
|
|
232
286
|
self.program = program
|
|
233
287
|
self.knowledge = (*knowledge, *program.declarations)
|
|
234
288
|
# Schema Knowledge is accepted; Property Declarations are the author's trusted claims.
|
|
@@ -244,24 +298,21 @@ class Arena:
|
|
|
244
298
|
subjects.append(value)
|
|
245
299
|
evidence = Result(True, f"{label} {type(item).__name__}", (item, *subjects), kind="accepted")
|
|
246
300
|
for cls in Property._subclasses:
|
|
247
|
-
if
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
301
|
+
if isinstance(item, cls):
|
|
302
|
+
# A Foreign Key is also Referential Coverage over the same columns.
|
|
303
|
+
claim = cls(**{field.name: getattr(item, field.name) for field in fields(cls)})
|
|
304
|
+
self.accepted[claim] = (*self.accepted.get(claim, ()), evidence)
|
|
251
305
|
|
|
252
306
|
def accepted_evidence(self, item: Property) -> tuple[Result[bool], ...]:
|
|
253
307
|
"""The evidence accepting `item` as Knowledge, empty when it is not."""
|
|
254
|
-
return self.accepted.get(
|
|
308
|
+
return self.accepted.get(item, ())
|
|
255
309
|
|
|
256
310
|
def prove(self, property: Property) -> Result[bool]:
|
|
257
|
-
|
|
258
|
-
evaluator, = (function for function in analysis_functions if function.__name__ == snake(type(property).__name__))
|
|
259
|
-
return evaluator(**values)
|
|
311
|
+
return evaluators[type(property)](**{field.name: getattr(property, field.name) for field in fields(property)})
|
|
260
312
|
|
|
261
313
|
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
return (snake(cls.__name__), tuple(sorted((field.name, getattr(item, field.name)) for field in fields(cls))))
|
|
314
|
+
# Deep enough for a chain of thousands of views or CTEs (`Engine.session`).
|
|
315
|
+
_RECURSION_LIMIT = 100_000
|
|
265
316
|
|
|
266
317
|
|
|
267
318
|
class Engine:
|
|
@@ -273,9 +324,16 @@ class Engine:
|
|
|
273
324
|
|
|
274
325
|
arena = Arena(program, knowledge)
|
|
275
326
|
token = _active.set(arena)
|
|
327
|
+
# An analysis recurses through every relation below the one it is about,
|
|
328
|
+
# about 25 frames per view or CTE, so Python's default limit of 1000 stops
|
|
329
|
+
# a chain of about 40. Python 3.13 keeps pure-Python calls off the C stack
|
|
330
|
+
# and guards the C recursion separately, so a high limit is safe.
|
|
331
|
+
limit = sys.getrecursionlimit()
|
|
332
|
+
sys.setrecursionlimit(max(limit, _RECURSION_LIMIT))
|
|
276
333
|
try:
|
|
277
334
|
yield arena
|
|
278
335
|
finally:
|
|
336
|
+
sys.setrecursionlimit(limit)
|
|
279
337
|
_active.reset(token)
|
|
280
338
|
|
|
281
339
|
def run(
|
|
@@ -283,7 +341,6 @@ class Engine:
|
|
|
283
341
|
warnings: tuple[Diagnostic, ...] = (),
|
|
284
342
|
) -> Report:
|
|
285
343
|
from sqlassert.rules.domain import always_null_columns
|
|
286
|
-
from sqlassert.rules.uniqueness import minimal_keys
|
|
287
344
|
|
|
288
345
|
with self.session(program, knowledge) as arena:
|
|
289
346
|
assertions = []
|
|
@@ -296,6 +353,7 @@ class Engine:
|
|
|
296
353
|
assertions.append(AssertionReport(
|
|
297
354
|
f"assert_{index}", Outcome.PROVED if evidence.value else Outcome.UNKNOWN, assertion.origin,
|
|
298
355
|
ASSERTED_KINDS[type(assertion.property)], evidence, unsupported,
|
|
356
|
+
None if evidence.value else _explanation(assertion.property),
|
|
299
357
|
))
|
|
300
358
|
if evidence.value:
|
|
301
359
|
# NULL is exempt from the Property, so a column that is always NULL satisfies it: say so, once.
|
|
@@ -312,12 +370,14 @@ class Engine:
|
|
|
312
370
|
UNSUPPORTED_CONSTRUCT, f"{unsupported} is not supported by sqlassert yet, which may be why this assertion is UNKNOWN",
|
|
313
371
|
assertion.origin,
|
|
314
372
|
))
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
373
|
+
return Report(tuple(assertions), tuple(diagnostics), tuple(warnings))
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def _explanation(property: Property) -> Step | None:
|
|
377
|
+
"""Why an UNKNOWN assertion is UNKNOWN, down to its Causes (`rules/causes`)."""
|
|
378
|
+
from sqlassert.rules.causes import explain
|
|
379
|
+
|
|
380
|
+
return explain(property)
|
|
321
381
|
|
|
322
382
|
|
|
323
383
|
def _unsupported_reached(program: ir.Program, property: Property) -> str | None:
|
sqlassert/reporting.py
CHANGED
|
@@ -1,14 +1,13 @@
|
|
|
1
|
-
"""The durable Report an analysis returns: assertion outcomes, diagnostics, and
|
|
1
|
+
"""The durable Report an analysis returns: assertion outcomes, diagnostics, and warnings.
|
|
2
2
|
|
|
3
3
|
The Report holds plain values only, plus each assertion's evidence. It never prints.
|
|
4
4
|
"""
|
|
5
5
|
|
|
6
6
|
from __future__ import annotations
|
|
7
7
|
|
|
8
|
-
from collections.abc import Sequence
|
|
9
8
|
from dataclasses import dataclass, field
|
|
10
9
|
from enum import Enum
|
|
11
|
-
from typing import TYPE_CHECKING
|
|
10
|
+
from typing import TYPE_CHECKING, Literal
|
|
12
11
|
|
|
13
12
|
from sqlassert import properties as props
|
|
14
13
|
from sqlassert.diagnostics import Diagnostic
|
|
@@ -25,6 +24,34 @@ class Outcome(Enum):
|
|
|
25
24
|
UNKNOWN = "unknown"
|
|
26
25
|
|
|
27
26
|
|
|
27
|
+
# Who can act on a Cause: `sql`, the query lets rows repeat as written;
|
|
28
|
+
# `declare`, a key the tables do not declare would prove it; `sqlassert`, a
|
|
29
|
+
# construct or comparison sqlassert does not see through.
|
|
30
|
+
type CauseTag = Literal["sql", "declare", "sqlassert"]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class Step:
|
|
35
|
+
"""One relation on the way from an UNKNOWN assertion to what it lacks
|
|
36
|
+
(`rules/causes`): `text` says what is proved of it there, `steps` the
|
|
37
|
+
relations under it that the explanation follows. A Step with a `tag` is a
|
|
38
|
+
Cause: where the Property is lost, and who can act on it; `code` names the
|
|
39
|
+
kind (`no-unique-set (partial-key)`), `details` the columns and key it misses."""
|
|
40
|
+
|
|
41
|
+
text: str
|
|
42
|
+
proved: bool
|
|
43
|
+
origin: Origin | None = None
|
|
44
|
+
tag: CauseTag | None = None
|
|
45
|
+
code: str | None = None
|
|
46
|
+
details: tuple[str, ...] = ()
|
|
47
|
+
steps: tuple[Step, ...] = ()
|
|
48
|
+
|
|
49
|
+
def causes(self) -> tuple[Step, ...]:
|
|
50
|
+
"""Every Cause under this Step, in source order of the walk."""
|
|
51
|
+
own = (self,) if self.tag is not None else ()
|
|
52
|
+
return (*own, *(cause for step in self.steps for cause in step.causes()))
|
|
53
|
+
|
|
54
|
+
|
|
28
55
|
@dataclass(frozen=True)
|
|
29
56
|
class AssertionReport:
|
|
30
57
|
"""One assertion's outcome. `kind` is the marker that states it
|
|
@@ -38,6 +65,9 @@ class AssertionReport:
|
|
|
38
65
|
# For an UNKNOWN assertion whose proof reaches a construct sqlassert does
|
|
39
66
|
# not support yet: what that construct is.
|
|
40
67
|
unsupported: str | None = None
|
|
68
|
+
# For an UNKNOWN Unique Set assertion: the relations it passes through,
|
|
69
|
+
# down to the Causes that lose it.
|
|
70
|
+
explanation: Step | None = None
|
|
41
71
|
|
|
42
72
|
|
|
43
73
|
# The marker each assertable Property is written as, in the words of its `/**ASSERT ...**/`.
|
|
@@ -59,39 +89,10 @@ ASSERTED_KINDS: dict[type[props.Property], str] = {
|
|
|
59
89
|
}
|
|
60
90
|
|
|
61
91
|
|
|
62
|
-
@dataclass(frozen=True)
|
|
63
|
-
class RelationFacts:
|
|
64
|
-
"""What was proved about every Named Relation in one analysis.
|
|
65
|
-
|
|
66
|
-
Tables and views use their declared name; CTEs use a ``CTE_``-prefixed
|
|
67
|
-
report label. Anonymous Relation Expressions are omitted: ask about the
|
|
68
|
-
assertion they feed into instead.
|
|
69
|
-
|
|
70
|
-
Holds only Unique Sets for now; further properties join it as typed
|
|
71
|
-
methods, the same way, rather than as a generic ask-anything query.
|
|
72
|
-
"""
|
|
73
|
-
|
|
74
|
-
_unique_sets: dict[str, tuple[tuple[str, ...], ...]] = field(default_factory=dict)
|
|
75
|
-
|
|
76
|
-
def unique_sets(self, relation: str) -> tuple[tuple[str, ...], ...]:
|
|
77
|
-
"""The minimal Unique Sets proved for `relation`, smallest first.
|
|
78
|
-
|
|
79
|
-
Every minimal set of up to three columns; when none is that small,
|
|
80
|
-
one minimal set. A superset of any of them is unique too."""
|
|
81
|
-
return self._unique_sets.get(relation.lower(), ())
|
|
82
|
-
|
|
83
|
-
def is_unique(self, relation: str, columns: Sequence[str]) -> bool:
|
|
84
|
-
"""Whether `columns` is guaranteed unique on `relation`: some proved
|
|
85
|
-
Unique Set's members are all among `columns`."""
|
|
86
|
-
candidate = {column.lower() for column in columns}
|
|
87
|
-
return any(set(unique_set) <= candidate for unique_set in self.unique_sets(relation))
|
|
88
|
-
|
|
89
|
-
|
|
90
92
|
@dataclass(frozen=True)
|
|
91
93
|
class Report:
|
|
92
94
|
assertions: tuple[AssertionReport, ...] = ()
|
|
93
95
|
diagnostics: tuple[Diagnostic, ...] = ()
|
|
94
|
-
facts: RelationFacts = field(default_factory=RelationFacts)
|
|
95
96
|
warnings: tuple[Diagnostic, ...] = ()
|
|
96
97
|
|
|
97
98
|
@property
|