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.
Files changed (50) hide show
  1. sqlassert/__init__.py +34 -9
  2. sqlassert/__main__.py +9 -0
  3. sqlassert/check.py +451 -0
  4. sqlassert/diagnostics.py +70 -0
  5. sqlassert/dialects.py +258 -0
  6. sqlassert/discovery/__init__.py +30 -0
  7. sqlassert/discovery/bigquery.py +71 -0
  8. sqlassert/discovery/databricks.py +18 -0
  9. sqlassert/discovery/duckdb.py +159 -0
  10. sqlassert/discovery/fetcher.py +418 -0
  11. sqlassert/discovery/information_schema.py +327 -0
  12. sqlassert/discovery/mysql.py +70 -0
  13. sqlassert/discovery/postgres.py +142 -0
  14. sqlassert/discovery/redshift.py +36 -0
  15. sqlassert/discovery/snowflake.py +63 -0
  16. sqlassert/discovery/trino.py +37 -0
  17. sqlassert/edits.py +240 -0
  18. sqlassert/hazards.py +574 -0
  19. sqlassert/ir/__init__.py +58 -0
  20. sqlassert/ir/convert.py +3509 -0
  21. sqlassert/ir/model.py +779 -0
  22. sqlassert/main.py +51 -0
  23. sqlassert/properties.py +121 -0
  24. sqlassert/provenance.py +73 -0
  25. sqlassert/python_engine.py +356 -0
  26. sqlassert/reporting.py +105 -0
  27. sqlassert/rewrites.py +1541 -0
  28. sqlassert/rules/STYLEGUIDE.md +19 -0
  29. sqlassert/rules/__init__.py +11 -0
  30. sqlassert/rules/column_set.py +34 -0
  31. sqlassert/rules/domain.py +472 -0
  32. sqlassert/rules/equality.py +442 -0
  33. sqlassert/rules/exactly_one.py +114 -0
  34. sqlassert/rules/foreign_key.py +319 -0
  35. sqlassert/rules/join_cardinality.py +116 -0
  36. sqlassert/rules/nullability.py +627 -0
  37. sqlassert/rules/uniqueness.py +904 -0
  38. sqlassert/sql_parse.py +1081 -0
  39. sqlassert/suggest.py +418 -0
  40. sqlassert-0.3.3.dist-info/METADATA +807 -0
  41. sqlassert-0.3.3.dist-info/RECORD +46 -0
  42. {sqlassert-0.1.2.dist-info → sqlassert-0.3.3.dist-info}/WHEEL +1 -1
  43. sqlassert-0.3.3.dist-info/entry_points.txt +2 -0
  44. sqlassert-0.3.3.dist-info/licenses/LICENSE +21 -0
  45. sqlassert-0.3.3.dist-info/top_level.txt +2 -0
  46. sqlassert_cli.py +130 -0
  47. sqlassert/unique.py +0 -605
  48. sqlassert-0.1.2.dist-info/METADATA +0 -173
  49. sqlassert-0.1.2.dist-info/RECORD +0 -6
  50. sqlassert-0.1.2.dist-info/top_level.txt +0 -1
sqlassert/main.py ADDED
@@ -0,0 +1,51 @@
1
+ """Compose parsing, IR conversion, and property analysis into a Report."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING
6
+
7
+ from sqlassert.ir.convert import IrParser
8
+ from sqlassert.python_engine import Engine
9
+ from sqlassert.reporting import Report
10
+ from sqlassert.sql_parse import SqlParser
11
+
12
+ if TYPE_CHECKING:
13
+ from sqlassert.discovery import DatabaseKnowledgeFetcher
14
+
15
+ DEFAULT_DIALECT = "duckdb"
16
+
17
+
18
+ def analyze(sql: str, *, dialect: str = DEFAULT_DIALECT, trust_unenforced_keys: bool = True) -> Report:
19
+ """Prove the Unique Join Assertions and Unique Set Assertions in one SQL Program.
20
+
21
+ Pure: the Program is the only source of Knowledge. `analyze_database`
22
+ adds a database catalog. Where a catalog would have helped (a table with
23
+ no `CREATE`, a column only a catalog can resolve), the Report warns.
24
+ `trust_unenforced_keys` (on by default) makes the keys the dialect does
25
+ not enforce Property Declarations, as `RELY` does; off, they are ignored
26
+ with an `unenforced-constraint` warning (`docs/dialects.md`).
27
+ """
28
+ sql_parser = SqlParser(dialect)
29
+ ir_parser = IrParser(dialect, trust_unenforced_keys)
30
+
31
+ ast = sql_parser.parse(sql)
32
+ conversion = ir_parser.parse(ast)
33
+ diagnostics = ast.diagnostics + conversion.diagnostics
34
+ return Engine().run(conversion.program, conversion.knowledge, diagnostics, conversion.warnings)
35
+
36
+
37
+ def analyze_database(
38
+ sql: str, fetcher: DatabaseKnowledgeFetcher, *, dialect: str = DEFAULT_DIALECT, trust_unenforced_keys: bool = True,
39
+ ) -> Report:
40
+ """`analyze`, with the external Relations the Program reaches hydrated from a catalog.
41
+
42
+ The fetcher reads catalog metadata only, never rows, and binds it to the
43
+ final IR before the engine runs once. No connection warnings: a relation
44
+ the catalog lacks is already a diagnostic. A catalog key the dialect does
45
+ not enforce warns, unless `trust_unenforced_keys` declares it, and so do
46
+ the SQL's own warnings (`diagnostics.SQL_WARNINGS`).
47
+ """
48
+ ast = SqlParser(dialect).parse(sql)
49
+ conversion, _ = fetcher.convert(ast, dialect=dialect, trust_unenforced_keys=trust_unenforced_keys)
50
+ diagnostics = ast.diagnostics + conversion.diagnostics
51
+ return Engine().run(conversion.program, conversion.knowledge, diagnostics, conversion.warnings)
@@ -0,0 +1,121 @@
1
+ """Structural properties over the relational IR."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from sqlassert.ir.model import Join, LiteralValue, NodeMeta, OutputColumn, SimpleCase
6
+
7
+
8
+ class Property(metaclass=NodeMeta, abstract=True):
9
+ """One semantic statement, independent of how it enters reasoning."""
10
+
11
+
12
+ class NonNullColumn(Property):
13
+ column: OutputColumn
14
+
15
+
16
+ class NonNullColumns(Property):
17
+ """Every listed column is non-null: one assertion for a whole column list."""
18
+
19
+ columns: frozenset[OutputColumn]
20
+
21
+
22
+ class NonNullElements(Property):
23
+ """No listed column's value has a NULL element: an ARRAY's elements, a
24
+ ROW's fields, a MAP's values, nested ones included (`NOT NULL ELEMENTS`).
25
+ Says nothing of the value itself, which may be NULL. No catalog states it,
26
+ so it is only asserted or declared."""
27
+
28
+ columns: frozenset[OutputColumn]
29
+
30
+
31
+ class UniqueSet(Property):
32
+ columns: frozenset[OutputColumn]
33
+
34
+
35
+ class NonNullUniqueSet(UniqueSet):
36
+ """A Unique Set whose columns are all non-null."""
37
+
38
+
39
+ class FunctionalDependency(Property):
40
+ """Rows agreeing on every `determinant` column, all non-null, agree on
41
+ every `dependent` column (`DETERMINES`). Lax: NULL in the determinant
42
+ exempts a row, as it does for a Unique Set."""
43
+
44
+ determinant: frozenset[OutputColumn]
45
+ dependent: frozenset[OutputColumn]
46
+
47
+
48
+ class EnumeratedDomain(Property):
49
+ """Every non-null value of `column` is one of `values`.
50
+
51
+ NULL is outside every domain (`NOT NULL` governs it), and a domain does
52
+ not claim that each of its values occurs.
53
+ """
54
+
55
+ column: OutputColumn
56
+ values: frozenset[LiteralValue]
57
+
58
+
59
+ class ExhaustiveCase(Property):
60
+ """Every member of `case`'s operand's Enumerated Domain has a WHEN arm
61
+ that is exactly that literal, so no non-null operand value reaches ELSE.
62
+
63
+ ELSE never substitutes for an arm, and a NULL operand, which matches no
64
+ arm, is left to `NOT NULL`.
65
+ """
66
+
67
+ case: SimpleCase
68
+
69
+
70
+ class ManyToOneJoin(Property):
71
+ """A join that cannot repeat a row of its left input: each left row
72
+ matches at most one right row (`MANY TO ONE`)."""
73
+
74
+ join: Join
75
+
76
+
77
+ class OneToManyJoin(Property):
78
+ """A join that cannot repeat a row of its right input: each right row
79
+ matches at most one left row (`ONE TO MANY`)."""
80
+
81
+ join: Join
82
+
83
+
84
+ class OneToOneJoin(Property):
85
+ """A join that repeats a row of neither input (`ONE TO ONE`)."""
86
+
87
+ join: Join
88
+
89
+
90
+ class UniqueJoin(Property):
91
+ """A join that repeats rows of at most one input: it is not many to many
92
+ (`UNIQUE`, `NOT MANY TO MANY`)."""
93
+
94
+ join: Join
95
+
96
+
97
+ class ExactlyOneJoin(Property):
98
+ """A join in which every row of its left input matches exactly one right row.
99
+
100
+ The join neither multiplies nor removes left rows, and a left join
101
+ null-extends none of them.
102
+ """
103
+
104
+ join: Join
105
+
106
+
107
+ class ReferentialCoverage(Property):
108
+ """Every row whose referencing columns are all non-null has a row of the
109
+ referenced relation equal to it on the paired referenced columns.
110
+
111
+ Columns pair by position. A row with a null referencing component is exempt
112
+ (`MATCH SIMPLE`). This is the part of a Foreign Key that Knowledge supplies:
113
+ `REFERENCES` constraints, catalog foreign keys, and declarations.
114
+ """
115
+
116
+ columns: tuple[OutputColumn, ...]
117
+ referenced_columns: tuple[OutputColumn, ...]
118
+
119
+
120
+ class ForeignKey(ReferentialCoverage):
121
+ """Referential Coverage onto a Unique Set of the referenced relation."""
@@ -0,0 +1,73 @@
1
+ """Source locations for semantic elements and diagnostics.
2
+
3
+ Origins hold plain values so that no SQLGlot node or connection can escape
4
+ through reporting.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass
10
+
11
+
12
+ SQL = "sql"
13
+
14
+
15
+ @dataclass(frozen=True, order=True)
16
+ class Span:
17
+ """A region of SQL text: where a Property Marker is written. Spans order by position.
18
+
19
+ Lines and columns count from 1, columns in characters; `end_column` is
20
+ one past the region's last character, as SARIF's `endColumn`.
21
+ """
22
+
23
+ line: int
24
+ column: int
25
+ end_line: int
26
+ end_column: int
27
+
28
+ @classmethod
29
+ def of(cls, sql: str, start: int, end: int) -> Span:
30
+ """The region of `sql[start:end]`."""
31
+ line, column = _position(sql, start)
32
+ end_line, end_column = _position(sql, end)
33
+ return cls(line, column, end_line, end_column)
34
+
35
+
36
+ def _position(sql: str, offset: int) -> tuple[int, int]:
37
+ return sql.count("\n", 0, offset) + 1, offset - sql.rfind("\n", 0, offset)
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class Origin:
42
+ """A SQL source span or catalog fact that a semantic element arose from.
43
+
44
+ `line` is the first source line, when known; `span` the exact region,
45
+ when the element is a Property Marker (its `line` is then `line`).
46
+ """
47
+
48
+ kind: str
49
+ detail: str
50
+ line: int | None = None
51
+ span: Span | None = None
52
+
53
+ @classmethod
54
+ def marked(cls, detail: str, span: Span) -> Origin:
55
+ """The Origin of something a Property Marker at `span` asserts or reports."""
56
+ return cls(SQL, detail, span.line, span)
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class AttachmentSite:
61
+ """Where a Property Marker for one JOIN or Select Expression is written.
62
+
63
+ `offset` indexes the SQL text: a join marker is inserted there, before the
64
+ join's first keyword; a trailing column marker is appended there, after
65
+ the Select Expression's last token. `label` names what the site marks
66
+ (`JOIN users AS u`, `view v`, `CTE c`, `subquery s`, `Root Select`);
67
+ anonymous Select Expressions share a label and are told apart by `line`.
68
+ """
69
+
70
+ label: str
71
+ line: int
72
+ offset: int
73
+ trailing: bool
@@ -0,0 +1,356 @@
1
+ """Analysis-scoped memoization and evidence for Python property functions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Generator, Iterable, Iterator
6
+ from contextlib import contextmanager
7
+ from contextvars import ContextVar
8
+ from dataclasses import dataclass, field, fields
9
+ from enum import IntEnum
10
+ from functools import wraps
11
+ from inspect import signature
12
+
13
+ from case_conversion import snake
14
+
15
+ from sqlassert import ir
16
+ from sqlassert.diagnostics import ALWAYS_NULL_COLUMN, DUPLICATE_DECLARATION, UNSUPPORTED_CONSTRUCT, Diagnostic, quoted
17
+ from sqlassert.properties import Property
18
+ from sqlassert.reporting import ASSERTED_KINDS, AssertionReport, Outcome, RelationFacts, Report
19
+
20
+
21
+ @dataclass(eq=False)
22
+ class Result[T]:
23
+ """A property function's value and evidence, including collection members."""
24
+
25
+ value: T
26
+ reason: str
27
+ subjects: tuple[object, ...] = ()
28
+ premises: list[Result] = field(default_factory=list)
29
+ kind: str = "structural"
30
+ members: dict = field(default_factory=dict)
31
+
32
+ def __bool__(self) -> bool:
33
+ raise TypeError("Use .value to inspect a result, or & and | to compose Boolean evidence")
34
+
35
+ def __and__(self: Result[bool], other: Result[bool]) -> Result[bool]:
36
+ return all_of((self, other))
37
+
38
+ def __or__(self: Result[bool], other: Result[bool]) -> Result[bool]:
39
+ return any_of((self, other))
40
+
41
+ def explain(self) -> str:
42
+ """Render the evidence, referring back to shared premises by number."""
43
+ lines: list[str] = []
44
+ seen: dict[Result, int] = {}
45
+
46
+ def visit(result: Result, depth: int) -> None:
47
+ indent = " " * depth
48
+ if result in seen:
49
+ lines.append(f"{indent}see #{seen[result]}")
50
+ return
51
+ seen[result] = len(seen) + 1
52
+ match result.value:
53
+ case True:
54
+ state = "PROVED"
55
+ case False:
56
+ state = "UNKNOWN"
57
+ case _:
58
+ state = "VALUE"
59
+ locations = []
60
+ for subject in result.subjects:
61
+ match subject:
62
+ case ir.Node(origin=origin):
63
+ locations.append(origin)
64
+ case _:
65
+ pass # Property arguments may also be sets and other plain values.
66
+ sources = "; ".join(
67
+ f"{origin.detail}" + (f" (line {origin.line})" if origin.line is not None else "")
68
+ for origin in dict.fromkeys(locations)
69
+ )
70
+ suffix = f" — {sources}" if sources else ""
71
+ lines.append(f"{indent}#{seen[result]} {state}: {result.reason}{suffix}")
72
+ for premise in result.premises:
73
+ visit(premise, depth + 1)
74
+
75
+ visit(self, 0)
76
+ return "\n".join(lines)
77
+
78
+
79
+ def unknown(reason: str, *subjects: object) -> Result[bool]:
80
+ return Result(False, reason, subjects, kind="unknown")
81
+
82
+
83
+ def all_of(results: Iterable[Result[bool]]) -> Result[bool]:
84
+ premises = list(results)
85
+ return Result(all(_boolean_values(premises)), "All premises required", premises=premises, kind="all")
86
+
87
+
88
+ def any_of(results: Iterable[Result[bool]]) -> Result[bool]:
89
+ premises = list(results)
90
+ return Result(any(_boolean_values(premises)), "Any alternative suffices", premises=premises, kind="any")
91
+
92
+
93
+ def _boolean_values(results):
94
+ values = []
95
+ for result in results:
96
+ match result.value:
97
+ case True | False:
98
+ values.append(result.value)
99
+ case _:
100
+ raise TypeError("Boolean composition requires Result[bool]")
101
+ return values
102
+
103
+
104
+ _active: ContextVar[Arena] = ContextVar("property_analysis")
105
+ analysis_functions = []
106
+
107
+
108
+ def cache(function):
109
+ """Memoize only within the active analysis, using normalized arguments."""
110
+ parameters = signature(function)
111
+
112
+ @wraps(function)
113
+ def cached(*args, **kwargs):
114
+ arena = current_arena()
115
+ bound = parameters.bind(*args, **kwargs)
116
+ bound.apply_defaults()
117
+ key = (function, tuple(bound.arguments.values()))
118
+ if key in arena.cache:
119
+ return arena.cache[key]
120
+ if key in arena.evaluating:
121
+ raise RuntimeError(
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
+ )
125
+ arena.evaluating.add(key)
126
+ try:
127
+ result = function(*args, **kwargs)
128
+ arena.cache[key] = result
129
+ return result
130
+ finally:
131
+ arena.evaluating.remove(key)
132
+
133
+ return cached
134
+
135
+
136
+ class Stratum(IntEnum):
137
+ """The order in which facts about one relation may use each other.
138
+
139
+ An analysis about relation R may use any fact about R's inputs, but facts
140
+ about R itself only at its own or a lower stratum. The IR's relations form a
141
+ DAG, so this keeps the whole call graph acyclic: the memoized engine cannot
142
+ compute mutually recursive facts, which would need a fixpoint.
143
+
144
+ Comparisons come first: comparison types, directed lax equalities, and
145
+ the constants a predicate fixes, all read from conjuncts. Unique Joins
146
+ (and Exactly One Joins) follow, so a relation's Null Sources may use them.
147
+ Equality Groups follow Null Sources, which strengthen lax equalities;
148
+ dependencies also use Null Sources (a padded side's
149
+ dependencies hold only when the join cannot pad an agreeing row) and Unique
150
+ Joins; closure uses dependencies and non-nullness; Unique Sets and
151
+ Functional Dependency assertions are closure questions; Foreign Keys use
152
+ Unique Sets. Enumerated Domains come last: they read equality groups and,
153
+ for a CASE's unreachable ELSE, non-nullness. A cycle is an internal sqlassert bug, not a problem
154
+ with the analyzed SQL.
155
+ """
156
+
157
+ COMPARISON = 5
158
+ UNIQUE_JOIN = 10
159
+ NON_NULL = 20
160
+ EQUALITY_GROUP = 25
161
+ FUNCTIONAL_DEPENDENCY = 30
162
+ CLOSURE = 40
163
+ UNIQUE_SET = 50
164
+ FOREIGN_KEY = 60
165
+ DOMAIN = 70
166
+
167
+
168
+ def analysis(stratum: Stratum):
169
+ """Cache and name an analysis function; public ones match Property names and fields."""
170
+
171
+ def decorate(function):
172
+ parameters = signature(function)
173
+
174
+ @cache
175
+ @wraps(function)
176
+ def evaluate(*args, **kwargs):
177
+ bound = parameters.bind(*args, **kwargs)
178
+ bound.apply_defaults()
179
+ arena = current_arena()
180
+ relation = _subject_relation(arena.program, bound.arguments.values())
181
+ if relation is not None:
182
+ for active, active_stratum, name in arena.active:
183
+ assert active is not relation or stratum <= active_stratum, (
184
+ f"{function.__name__} ({stratum.name}) called from {name} ({active_stratum.name}) "
185
+ "about the same relation: a fact may only use facts at its own or a lower stratum"
186
+ )
187
+ arena.active.append((relation, stratum, function.__name__))
188
+ try:
189
+ arguments = tuple(sorted(bound.arguments.items()))
190
+ accepted = arena.accepted.get((function.__name__, arguments), ())
191
+ result = any_of(accepted) if accepted else function(*args, **kwargs)
192
+ finally:
193
+ arena.active.pop()
194
+ return Result(result.value, function.__name__, tuple(bound.arguments.values()), [result], "claim", result.members)
195
+
196
+ evaluate.stratum = stratum
197
+ analysis_functions.append(evaluate)
198
+ return evaluate
199
+
200
+ return decorate
201
+
202
+
203
+ def _subject_relation(program: ir.Program, arguments: Iterable[object]) -> ir.RelationExpr | None:
204
+ """The relation an analysis call is about: its first argument that names one."""
205
+ for argument in arguments:
206
+ match argument:
207
+ case ir.RelationExpr():
208
+ return argument
209
+ case ir.OutputColumn():
210
+ return program.column_to_parent_relation_index.get(argument)
211
+ case frozenset() | tuple():
212
+ return program.relation_of(frozenset(argument))
213
+ case Result(value=value) if isinstance(getattr(value, "relation", None), ir.RelationExpr):
214
+ return value.relation
215
+ case _:
216
+ pass # Scalar expressions and plain values are not about one relation.
217
+ return None
218
+
219
+
220
+ def current_arena() -> Arena:
221
+ return _active.get()
222
+
223
+
224
+ class Arena:
225
+ """One immutable program's knowledge, memoized values, and evidence graph."""
226
+
227
+ def __init__(self, program: ir.Program, knowledge: tuple[Property, ...]):
228
+ self.cache: dict[tuple, object] = {}
229
+ self.evaluating: set[tuple] = set()
230
+ self.active: list[tuple[ir.RelationExpr | None, Stratum, str]] = []
231
+ self.accepted: dict[tuple, tuple[Result[bool], ...]] = {}
232
+ self.program = program
233
+ self.knowledge = (*knowledge, *program.declarations)
234
+ # Schema Knowledge is accepted; Property Declarations are the author's trusted claims.
235
+ sources = [("Accepted", item) for item in knowledge] + [("Declared", item) for item in program.declarations]
236
+ for label, item in sources:
237
+ values = tuple(getattr(item, field.name) for field in fields(item))
238
+ subjects = []
239
+ for value in values:
240
+ match value:
241
+ case frozenset() | set() | list() | tuple():
242
+ subjects.extend(value)
243
+ case _:
244
+ subjects.append(value)
245
+ evidence = Result(True, f"{label} {type(item).__name__}", (item, *subjects), kind="accepted")
246
+ for cls in Property._subclasses:
247
+ if cls not in type(item).__mro__:
248
+ continue
249
+ key = _accepted_key(cls, item)
250
+ self.accepted[key] = (*self.accepted.get(key, ()), evidence)
251
+
252
+ def accepted_evidence(self, item: Property) -> tuple[Result[bool], ...]:
253
+ """The evidence accepting `item` as Knowledge, empty when it is not."""
254
+ return self.accepted.get(_accepted_key(type(item), item), ())
255
+
256
+ def prove(self, property: Property) -> Result[bool]:
257
+ values = {field.name: getattr(property, field.name) for field in fields(property)}
258
+ evaluator, = (function for function in analysis_functions if function.__name__ == snake(type(property).__name__))
259
+ return evaluator(**values)
260
+
261
+
262
+ def _accepted_key(cls: type[Property], item: Property) -> tuple:
263
+ """How `item`, as an instance of `cls`, is looked up among accepted results."""
264
+ return (snake(cls.__name__), tuple(sorted((field.name, getattr(item, field.name)) for field in fields(cls))))
265
+
266
+
267
+ class Engine:
268
+ @contextmanager
269
+ def session(self, program: ir.Program, knowledge: tuple[Property, ...] = ()) -> Generator[Arena]:
270
+ assert _active.get(None) is None, "An analysis arena is already active"
271
+ # Importing registers analysis functions; inference remains in rules/.
272
+ from sqlassert.rules import domain, equality, exactly_one, foreign_key, join_cardinality, nullability, uniqueness # noqa: F401
273
+
274
+ arena = Arena(program, knowledge)
275
+ token = _active.set(arena)
276
+ try:
277
+ yield arena
278
+ finally:
279
+ _active.reset(token)
280
+
281
+ def run(
282
+ self, program: ir.Program, knowledge: tuple[Property, ...] = (), diagnostics: tuple[Diagnostic, ...] = (),
283
+ warnings: tuple[Diagnostic, ...] = (),
284
+ ) -> Report:
285
+ from sqlassert.rules.domain import always_null_columns
286
+ from sqlassert.rules.uniqueness import minimal_keys
287
+
288
+ with self.session(program, knowledge) as arena:
289
+ assertions = []
290
+ always_null: set[ir.OutputColumn] = set()
291
+ for index, assertion in enumerate(program.assertions, 1):
292
+ evidence = arena.prove(assertion.property)
293
+ if any(diagnostic.code == DUPLICATE_DECLARATION for diagnostic in diagnostics):
294
+ evidence = evidence & unknown("Duplicate declarations prevent accepting a proof", assertion)
295
+ unsupported = None if evidence.value else _unsupported_reached(program, assertion.property)
296
+ assertions.append(AssertionReport(
297
+ f"assert_{index}", Outcome.PROVED if evidence.value else Outcome.UNKNOWN, assertion.origin,
298
+ ASSERTED_KINDS[type(assertion.property)], evidence, unsupported,
299
+ ))
300
+ if evidence.value:
301
+ # NULL is exempt from the Property, so a column that is always NULL satisfies it: say so, once.
302
+ kind = ASSERTED_KINDS[type(assertion.property)].upper().replace("-", " ")
303
+ for column in always_null_columns(assertion.property):
304
+ if column not in always_null:
305
+ always_null.add(column)
306
+ warnings = (*warnings, Diagnostic(
307
+ ALWAYS_NULL_COLUMN, f"{quoted(column.name)} is always NULL, so this {kind} holds trivially: no non-null value of it is possible",
308
+ assertion.origin,
309
+ ))
310
+ if unsupported is not None:
311
+ warnings = (*warnings, Diagnostic(
312
+ UNSUPPORTED_CONSTRUCT, f"{unsupported} is not supported by sqlassert yet, which may be why this assertion is UNKNOWN",
313
+ assertion.origin,
314
+ ))
315
+ facts = {}
316
+ for relation in program.named_relations:
317
+ facts[relation.report_name.lower()] = tuple(
318
+ tuple(column.name for column in key) for key in minimal_keys(relation)
319
+ )
320
+ return Report(tuple(assertions), tuple(diagnostics), RelationFacts(facts), tuple(warnings))
321
+
322
+
323
+ def _unsupported_reached(program: ir.Program, property: Property) -> str | None:
324
+ """The first construct sqlassert does not support yet that `property`'s
325
+ proof depends on: reached from its columns through the expressions that
326
+ compute them, and from their relations through those relations' inputs.
327
+ Sibling columns are not followed, so a window function beside an
328
+ asserted column is not blamed for it."""
329
+ unsupported = {id(node): construct for node, construct in program.unsupported}
330
+ if not unsupported:
331
+ return None
332
+ seen: set[int] = set()
333
+ pending: list[ir.Node] = []
334
+ for item in fields(property):
335
+ value = getattr(property, item.name)
336
+ pending.extend(value if isinstance(value, frozenset | tuple) else (value,))
337
+ while pending:
338
+ node = pending.pop()
339
+ if not isinstance(node, ir.Node) or id(node) in seen:
340
+ continue
341
+ seen.add(id(node))
342
+ if id(node) in unsupported:
343
+ return unsupported[id(node)]
344
+ match node:
345
+ case ir.OutputColumn():
346
+ pending.append(node.scalar_expr)
347
+ pending.append(node.get_relation(program))
348
+ case ir.ColumnRef(column=column):
349
+ pending.append(column)
350
+ case ir.ScalarExpr():
351
+ pending.extend(ir.children(node))
352
+ case ir.RelationExpr():
353
+ pending.extend(child for child in ir.children(node) if isinstance(child, ir.RelationExpr | ir.ScalarExpr))
354
+ case _:
355
+ pass
356
+ return None