sqlassert 0.1.2__py3-none-any.whl → 0.3.3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sqlassert/__init__.py +34 -9
- sqlassert/__main__.py +9 -0
- sqlassert/check.py +451 -0
- sqlassert/diagnostics.py +70 -0
- sqlassert/dialects.py +258 -0
- sqlassert/discovery/__init__.py +30 -0
- sqlassert/discovery/bigquery.py +71 -0
- sqlassert/discovery/databricks.py +18 -0
- sqlassert/discovery/duckdb.py +159 -0
- sqlassert/discovery/fetcher.py +418 -0
- sqlassert/discovery/information_schema.py +327 -0
- sqlassert/discovery/mysql.py +70 -0
- sqlassert/discovery/postgres.py +142 -0
- sqlassert/discovery/redshift.py +36 -0
- sqlassert/discovery/snowflake.py +63 -0
- sqlassert/discovery/trino.py +37 -0
- sqlassert/edits.py +240 -0
- sqlassert/hazards.py +574 -0
- sqlassert/ir/__init__.py +58 -0
- sqlassert/ir/convert.py +3509 -0
- sqlassert/ir/model.py +779 -0
- sqlassert/main.py +51 -0
- sqlassert/properties.py +121 -0
- sqlassert/provenance.py +73 -0
- sqlassert/python_engine.py +356 -0
- sqlassert/reporting.py +105 -0
- sqlassert/rewrites.py +1541 -0
- sqlassert/rules/STYLEGUIDE.md +19 -0
- sqlassert/rules/__init__.py +11 -0
- sqlassert/rules/column_set.py +34 -0
- sqlassert/rules/domain.py +472 -0
- sqlassert/rules/equality.py +442 -0
- sqlassert/rules/exactly_one.py +114 -0
- sqlassert/rules/foreign_key.py +319 -0
- sqlassert/rules/join_cardinality.py +116 -0
- sqlassert/rules/nullability.py +627 -0
- sqlassert/rules/uniqueness.py +904 -0
- sqlassert/sql_parse.py +1081 -0
- sqlassert/suggest.py +418 -0
- sqlassert-0.3.3.dist-info/METADATA +807 -0
- sqlassert-0.3.3.dist-info/RECORD +46 -0
- {sqlassert-0.1.2.dist-info → sqlassert-0.3.3.dist-info}/WHEEL +1 -1
- sqlassert-0.3.3.dist-info/entry_points.txt +2 -0
- sqlassert-0.3.3.dist-info/licenses/LICENSE +21 -0
- sqlassert-0.3.3.dist-info/top_level.txt +2 -0
- sqlassert_cli.py +130 -0
- sqlassert/unique.py +0 -605
- sqlassert-0.1.2.dist-info/METADATA +0 -173
- sqlassert-0.1.2.dist-info/RECORD +0 -6
- sqlassert-0.1.2.dist-info/top_level.txt +0 -1
sqlassert/suggest.py
ADDED
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
"""Suggest the Property Markers sqlassert can prove for a SQL Program.
|
|
2
|
+
|
|
3
|
+
Four types of suggestion (`SuggestType`). Rewrites: changes to the SQL
|
|
4
|
+
itself that a proof shows leave its result unchanged (`rewrites.py`), each
|
|
5
|
+
made by exact edits (`edits.py`), with a caveat when a column's type or
|
|
6
|
+
precision may change. Markers: what is provable but not asserted, to lock in. Hazards: places
|
|
7
|
+
whose result the SQL leaves unspecified (`hazards.py`).
|
|
8
|
+
|
|
9
|
+
Marker candidates are generated mechanically from the Program IR, one
|
|
10
|
+
Attachment Site at a time: every markable JOIN may be a Unique Join (or
|
|
11
|
+
Exactly One), every Select Expression's output columns may form Unique Sets,
|
|
12
|
+
be non-null, or have a small Enumerated Domain, and every markable simple
|
|
13
|
+
CASE may be exhaustive. `suggest` proves them and keeps only what is PROVED,
|
|
14
|
+
in its strongest, minimal form. `candidates` is the generator alone, for
|
|
15
|
+
callers that judge candidates by other means.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
from collections.abc import Callable, Iterable, Iterator
|
|
21
|
+
from contextlib import AbstractContextManager
|
|
22
|
+
from dataclasses import dataclass, fields
|
|
23
|
+
from decimal import Decimal
|
|
24
|
+
from itertools import combinations
|
|
25
|
+
from typing import ClassVar
|
|
26
|
+
|
|
27
|
+
from sqlglot import exp
|
|
28
|
+
|
|
29
|
+
from sqlassert import diagnostics as diag
|
|
30
|
+
from sqlassert import ir
|
|
31
|
+
from sqlassert.diagnostics import Diagnostic
|
|
32
|
+
from sqlassert.edits import Edit
|
|
33
|
+
from sqlassert.rewrites import Rewrite, SuggestType, RewriteKind, rewrites
|
|
34
|
+
from sqlassert.ir.convert import IrConversionResult, IrParser
|
|
35
|
+
from sqlassert.hazards import Concern, Hazard, hazards
|
|
36
|
+
from sqlassert.main import DEFAULT_DIALECT
|
|
37
|
+
from sqlassert.properties import (
|
|
38
|
+
EnumeratedDomain, ExactlyOneJoin, ExhaustiveCase, ManyToOneJoin, NonNullColumn, NonNullColumns, NonNullUniqueSet,
|
|
39
|
+
OneToManyJoin, OneToOneJoin, Property, UniqueJoin, UniqueSet,
|
|
40
|
+
)
|
|
41
|
+
from sqlassert.python_engine import Arena, Engine, Result
|
|
42
|
+
from sqlassert.provenance import AttachmentSite
|
|
43
|
+
from sqlassert.rules.domain import _domain
|
|
44
|
+
from sqlassert.sql_parse import ParsedProgram, SqlParser
|
|
45
|
+
|
|
46
|
+
DEFAULT_MAX_SIZE = 3
|
|
47
|
+
|
|
48
|
+
# The most values an ENUM marker lists. A short closed list is a category
|
|
49
|
+
# worth locking in; a longer one is mostly a long IN list restated, and its
|
|
50
|
+
# marker would be noise at every site the column passes through.
|
|
51
|
+
MAX_ENUM_VALUES = 10
|
|
52
|
+
|
|
53
|
+
__all__ = [
|
|
54
|
+
"Candidate", "Concern", "Edit", "Rewrite", "SuggestType", "RewriteKind", "Hazard", "Suggester", "Suggestion", "SuggestionReport",
|
|
55
|
+
"annotate", "candidates", "suggest", "suggest_parsed",
|
|
56
|
+
]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@dataclass(frozen=True)
|
|
60
|
+
class Candidate:
|
|
61
|
+
"""A Property worth trying at one Attachment Site, with its marker text."""
|
|
62
|
+
|
|
63
|
+
site: AttachmentSite
|
|
64
|
+
property: Property
|
|
65
|
+
marker: str
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass(frozen=True)
|
|
69
|
+
class Suggestion:
|
|
70
|
+
"""A proved Candidate: its marker can be pasted and will be PROVED."""
|
|
71
|
+
|
|
72
|
+
site: AttachmentSite
|
|
73
|
+
property: Property
|
|
74
|
+
marker: str
|
|
75
|
+
evidence: Result[bool]
|
|
76
|
+
suggest_type: ClassVar[SuggestType] = SuggestType.MARKER
|
|
77
|
+
|
|
78
|
+
@property
|
|
79
|
+
def kind(self) -> str:
|
|
80
|
+
"""The Property's name, as a listing shows it."""
|
|
81
|
+
return _KINDS[type(self.property)]
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@dataclass(frozen=True)
|
|
85
|
+
class SuggestionReport:
|
|
86
|
+
"""`rewrites` rewrite the SQL, some with a caveat; `suggestions` are
|
|
87
|
+
markers to paste; `hazards` point at results the SQL leaves unspecified."""
|
|
88
|
+
|
|
89
|
+
sql: str
|
|
90
|
+
suggestions: tuple[Suggestion, ...] = ()
|
|
91
|
+
diagnostics: tuple[Diagnostic, ...] = ()
|
|
92
|
+
rewrites: tuple[Rewrite, ...] = ()
|
|
93
|
+
warnings: tuple[Diagnostic, ...] = ()
|
|
94
|
+
hazards: tuple[Hazard, ...] = ()
|
|
95
|
+
|
|
96
|
+
def annotated(self, chosen: Iterable[Suggestion] | None = None) -> str:
|
|
97
|
+
"""The SQL with the chosen suggestions' markers pasted in (all by default)."""
|
|
98
|
+
return annotate(self.sql, self.suggestions if chosen is None else chosen)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def annotate(sql: str, items: Iterable[Candidate | Suggestion]) -> str:
|
|
102
|
+
"""`sql` with each item's marker pasted at its Attachment Site.
|
|
103
|
+
|
|
104
|
+
Markers never add a line break, so every line number in `sql` still holds.
|
|
105
|
+
"""
|
|
106
|
+
inserts: dict[int, list[Candidate | Suggestion]] = {}
|
|
107
|
+
for item in items:
|
|
108
|
+
inserts.setdefault(item.site.offset, []).append(item)
|
|
109
|
+
for offset in sorted(inserts, reverse=True):
|
|
110
|
+
text = "".join(f" {item.marker}" if item.site.trailing else f"{item.marker} " for item in inserts[offset])
|
|
111
|
+
sql = sql[:offset] + text + sql[offset:]
|
|
112
|
+
return sql
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def suggest(
|
|
116
|
+
sql: str, *, dialect: str = DEFAULT_DIALECT, max_size: int = DEFAULT_MAX_SIZE, trust_unenforced_keys: bool = True,
|
|
117
|
+
) -> SuggestionReport:
|
|
118
|
+
"""Every Property sqlassert can prove about `sql`, as markers to paste,
|
|
119
|
+
and every Rewrite a proof justifies.
|
|
120
|
+
|
|
121
|
+
Per Select Expression: each minimal Unique Set up to `max_size` columns,
|
|
122
|
+
as a Non-Null Unique Set when that also holds, plus one minimal set found
|
|
123
|
+
among wider ones when none that small exists; and the non-null columns no
|
|
124
|
+
suggested Non-Null Unique Set already implies; and an Enumerated Domain of
|
|
125
|
+
up to `MAX_ENUM_VALUES` values for each column not written as a literal.
|
|
126
|
+
Per JOIN: Exactly One Join, else Unique Join, unless the join already
|
|
127
|
+
carries a marker. Per simple CASE a marker can precede: Exhaustive Case.
|
|
128
|
+
Properties the SQL already asserts or declares are left out.
|
|
129
|
+
"""
|
|
130
|
+
ast = SqlParser(dialect).parse(sql)
|
|
131
|
+
return suggest_parsed(sql, ast, IrParser(dialect, trust_unenforced_keys).parse(ast), dialect=dialect, max_size=max_size)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def suggest_parsed(
|
|
135
|
+
sql: str, ast: ParsedProgram, conversion: IrConversionResult, *, dialect: str = DEFAULT_DIALECT,
|
|
136
|
+
max_size: int = DEFAULT_MAX_SIZE,
|
|
137
|
+
) -> SuggestionReport:
|
|
138
|
+
"""`suggest` of a Program already parsed and lowered: for a caller that
|
|
139
|
+
adds Property Declarations to `conversion.program` before proving."""
|
|
140
|
+
with Suggester(sql, ast, conversion, dialect=dialect, max_size=max_size) as suggester:
|
|
141
|
+
return suggester.suggest()
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
class Suggester:
|
|
145
|
+
"""`suggest` over one lowered Program, one part at a time, for a caller
|
|
146
|
+
that wants each part as soon as it is found: proofs are memoized across
|
|
147
|
+
parts, and Rewrites and Hazards are found once, for every site
|
|
148
|
+
`sites` accepts (all by default). Use it as a context manager: it holds
|
|
149
|
+
the Program's analysis session."""
|
|
150
|
+
|
|
151
|
+
def __init__(
|
|
152
|
+
self, sql: str, ast: ParsedProgram, conversion: IrConversionResult, *, dialect: str = DEFAULT_DIALECT,
|
|
153
|
+
max_size: int = DEFAULT_MAX_SIZE, sites: Callable[[AttachmentSite], bool] | None = None,
|
|
154
|
+
):
|
|
155
|
+
self.sql, self.ast, self.conversion, self.dialect, self.max_size = sql, ast, conversion, dialect, max_size
|
|
156
|
+
self.sites = sites or (lambda site: True)
|
|
157
|
+
self.program = conversion.program
|
|
158
|
+
self.diagnostics = ast.diagnostics + conversion.diagnostics
|
|
159
|
+
self.blocked = any(diagnostic.code in _BLOCKING for diagnostic in self.diagnostics)
|
|
160
|
+
present = (*self.program.declarations, *(assertion.property for assertion in self.program.assertions))
|
|
161
|
+
self.marked = {_identity(item) for item in present}
|
|
162
|
+
self.marked_non_null = {
|
|
163
|
+
column
|
|
164
|
+
for item in present
|
|
165
|
+
for column in (
|
|
166
|
+
(item.column,) if isinstance(item, NonNullColumn) else item.columns if isinstance(item, NonNullColumns) else ()
|
|
167
|
+
)
|
|
168
|
+
}
|
|
169
|
+
self.marked_joins = {item.join for item in present if isinstance(item, _JOIN_PROPERTIES)}
|
|
170
|
+
self.marked_cases = {item.case for item in present if isinstance(item, ExhaustiveCase)}
|
|
171
|
+
self.reachable = set(self.program.nodes())
|
|
172
|
+
self._session: AbstractContextManager[Arena] | None = None
|
|
173
|
+
self._arena: Arena | None = None
|
|
174
|
+
self._rewrites: list[Rewrite] = []
|
|
175
|
+
self._hazards: list[Hazard] = []
|
|
176
|
+
|
|
177
|
+
def __enter__(self) -> Suggester:
|
|
178
|
+
self._session = Engine().session(self.program, self.conversion.knowledge)
|
|
179
|
+
self._arena = self._session.__enter__()
|
|
180
|
+
try:
|
|
181
|
+
if not self.blocked:
|
|
182
|
+
self._rewrites = rewrites(self.ast, self.program, self._arena, self.dialect, wanted=self.sites)
|
|
183
|
+
self._hazards = hazards(self.ast, self.program, self._arena, self.dialect, wanted=self.sites)
|
|
184
|
+
except BaseException as error:
|
|
185
|
+
self.__exit__(type(error), error, error.__traceback__)
|
|
186
|
+
raise
|
|
187
|
+
return self
|
|
188
|
+
|
|
189
|
+
def __exit__(self, *exc: object) -> None:
|
|
190
|
+
assert self._session is not None
|
|
191
|
+
self._session.__exit__(*exc) # ty: ignore[invalid-argument-type]
|
|
192
|
+
self._arena = None
|
|
193
|
+
|
|
194
|
+
def suggest(self, sites: Callable[[AttachmentSite], bool] | None = None) -> SuggestionReport:
|
|
195
|
+
"""What is found at the sites both `sites` and the Suggester's accept."""
|
|
196
|
+
arena = self._arena
|
|
197
|
+
assert arena is not None, "use the Suggester as a context manager"
|
|
198
|
+
wanted = sites or (lambda site: True)
|
|
199
|
+
if self.blocked:
|
|
200
|
+
return SuggestionReport(self.sql, (), self.diagnostics, warnings=self.conversion.warnings)
|
|
201
|
+
suggestions: list[Suggestion] = []
|
|
202
|
+
dialect, reachable = self.dialect, self.reachable
|
|
203
|
+
for site, relation in self.program.attachment_sites:
|
|
204
|
+
if not (self.sites(site) and wanted(site)):
|
|
205
|
+
continue
|
|
206
|
+
match relation:
|
|
207
|
+
case ir.Join() if not site.trailing and relation not in self.marked_joins and relation in reachable:
|
|
208
|
+
# The strongest proved form. Not many to many is implied by each
|
|
209
|
+
# cardinality, so it is never suggested on its own; a semi or
|
|
210
|
+
# anti join outputs no right rows, so no cardinality applies.
|
|
211
|
+
kinds = (ExactlyOneJoin,) if relation.kind in {"semi", "anti"} else _JOIN_PROPERTIES[:4]
|
|
212
|
+
suggestions.extend(next(
|
|
213
|
+
(proved for kind in kinds if (proved := _proved(arena, site, kind(join=relation), (), dialect))), []
|
|
214
|
+
))
|
|
215
|
+
case ir.Join() if not site.trailing:
|
|
216
|
+
# Already marked, or unreachable: lowered inside a Select that is
|
|
217
|
+
# opaque as a whole (one with HAVING, say), so nothing is known about it.
|
|
218
|
+
pass
|
|
219
|
+
case ir.SimpleCase() if relation not in self.marked_cases and relation in reachable and _markable(relation):
|
|
220
|
+
suggestions.extend(_proved(arena, site, ExhaustiveCase(case=relation), (), dialect))
|
|
221
|
+
case ir.SimpleCase():
|
|
222
|
+
pass # Already marked, unreachable, or with a WHEN no marker allows.
|
|
223
|
+
case _ if relation in reachable:
|
|
224
|
+
suggestions.extend(_select_suggestions(arena, site, relation, self.max_size, self.marked_non_null, dialect))
|
|
225
|
+
kept = tuple(
|
|
226
|
+
sorted(
|
|
227
|
+
(suggestion for suggestion in suggestions if _identity(suggestion.property) not in self.marked),
|
|
228
|
+
key=lambda suggestion: suggestion.site.offset,
|
|
229
|
+
)
|
|
230
|
+
)
|
|
231
|
+
return SuggestionReport(
|
|
232
|
+
self.sql, kept, self.diagnostics, tuple(item for item in self._rewrites if wanted(item.site)),
|
|
233
|
+
self.conversion.warnings, tuple(item for item in self._hazards if wanted(item.site)),
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
# How each suggested Property reads in a listing.
|
|
238
|
+
_KINDS: dict[type[Property], str] = {
|
|
239
|
+
ExactlyOneJoin: "Exactly One Join",
|
|
240
|
+
OneToOneJoin: "One To One Join",
|
|
241
|
+
ManyToOneJoin: "Many To One Join",
|
|
242
|
+
OneToManyJoin: "One To Many Join",
|
|
243
|
+
UniqueJoin: "Unique Join",
|
|
244
|
+
UniqueSet: "Unique Set",
|
|
245
|
+
NonNullUniqueSet: "Non-Null Unique Set",
|
|
246
|
+
NonNullColumns: "Not Null",
|
|
247
|
+
EnumeratedDomain: "Enumerated Domain",
|
|
248
|
+
ExhaustiveCase: "Exhaustive Case",
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
# The join Properties, strongest first.
|
|
252
|
+
_JOIN_PROPERTIES = (ExactlyOneJoin, OneToOneJoin, ManyToOneJoin, OneToManyJoin, UniqueJoin)
|
|
253
|
+
|
|
254
|
+
# A parse failure leaves nothing to suggest on; duplicate declarations make
|
|
255
|
+
# `analyze` refuse every proof, so nothing suggested could round-trip.
|
|
256
|
+
_BLOCKING = {diag.SQL_PARSE_FAILED, diag.UNATTACHED_MARKER, diag.DUPLICATE_DECLARATION, diag.UNSUPPORTED_NATURAL_JOIN}
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def candidates(
|
|
260
|
+
program: ir.Program, *, dialect: str = DEFAULT_DIALECT, max_size: int = DEFAULT_MAX_SIZE
|
|
261
|
+
) -> Iterator[Candidate]:
|
|
262
|
+
"""Every candidate Property at every Attachment Site of `program`, proved or not.
|
|
263
|
+
|
|
264
|
+
Per JOIN but a semi or anti one: Unique Join. Per markable simple CASE: Exhaustive Case. Per
|
|
265
|
+
Select Expression: each output column non-null, and each set of up to
|
|
266
|
+
`max_size` output columns, plus the set of all of them, as a Unique Set
|
|
267
|
+
and as a Non-Null Unique Set. Only columns a marker can name
|
|
268
|
+
unambiguously take part. Enumerated Domains are not candidates: which
|
|
269
|
+
values to list is itself something only analysis finds.
|
|
270
|
+
"""
|
|
271
|
+
for site, relation in program.attachment_sites:
|
|
272
|
+
match relation:
|
|
273
|
+
case ir.Join() if not site.trailing and relation.kind not in {"semi", "anti"}:
|
|
274
|
+
yield _candidate(site, UniqueJoin(join=relation), (), dialect)
|
|
275
|
+
case ir.Join() if not site.trailing:
|
|
276
|
+
pass # No cardinality applies to a semi or anti join.
|
|
277
|
+
case ir.SimpleCase() if _markable(relation):
|
|
278
|
+
yield _candidate(site, ExhaustiveCase(case=relation), (), dialect)
|
|
279
|
+
case ir.SimpleCase():
|
|
280
|
+
pass
|
|
281
|
+
case _:
|
|
282
|
+
columns = _nameable_columns(relation)
|
|
283
|
+
for column in columns:
|
|
284
|
+
yield _candidate(site, NonNullColumns(columns=frozenset((column,))), columns, dialect)
|
|
285
|
+
for members in _column_sets(columns, max_size):
|
|
286
|
+
yield _candidate(site, UniqueSet(columns=frozenset(members)), columns, dialect)
|
|
287
|
+
yield _candidate(site, NonNullUniqueSet(columns=frozenset(members)), columns, dialect)
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def _select_suggestions(
|
|
291
|
+
arena: Arena,
|
|
292
|
+
site: AttachmentSite,
|
|
293
|
+
relation: ir.RelationExpr,
|
|
294
|
+
max_size: int,
|
|
295
|
+
marked_non_null: set[ir.OutputColumn],
|
|
296
|
+
dialect: str,
|
|
297
|
+
) -> list[Suggestion]:
|
|
298
|
+
columns = _nameable_columns(relation)
|
|
299
|
+
suggestions = []
|
|
300
|
+
# Proof is monotone in the column set: when the whole set is not unique,
|
|
301
|
+
# no subset is, and enumerating them would be wasted work.
|
|
302
|
+
minimal: list[tuple[ir.OutputColumn, ...]] = []
|
|
303
|
+
if columns and arena.prove(UniqueSet(columns=frozenset(columns))).value:
|
|
304
|
+
for members in _column_sets(columns, max_size):
|
|
305
|
+
if any(set(found) <= set(members) for found in minimal):
|
|
306
|
+
continue
|
|
307
|
+
if arena.prove(UniqueSet(columns=frozenset(members))).value:
|
|
308
|
+
minimal.append(_shrink(arena, members))
|
|
309
|
+
for members in minimal:
|
|
310
|
+
strong = _proved(arena, site, NonNullUniqueSet(columns=frozenset(members)), columns, dialect)
|
|
311
|
+
suggestions.extend(strong or _proved(arena, site, UniqueSet(columns=frozenset(members)), columns, dialect))
|
|
312
|
+
|
|
313
|
+
implied = {column for s in suggestions if isinstance(s.property, NonNullUniqueSet) for column in s.property.columns}
|
|
314
|
+
non_null = frozenset(
|
|
315
|
+
column for column in columns
|
|
316
|
+
if column not in implied | marked_non_null
|
|
317
|
+
and arena.prove(NonNullColumns(columns=frozenset((column,)))).value
|
|
318
|
+
)
|
|
319
|
+
if non_null:
|
|
320
|
+
suggestions.extend(_proved(arena, site, NonNullColumns(columns=non_null), columns, dialect))
|
|
321
|
+
|
|
322
|
+
for column in columns:
|
|
323
|
+
if isinstance(column.scalar_expr, ir.Constant):
|
|
324
|
+
continue # The marker would restate the literal.
|
|
325
|
+
# Which values to list comes from the domain analysis; the marker is
|
|
326
|
+
# then proved like any other.
|
|
327
|
+
domain = _domain(column).value
|
|
328
|
+
if domain and len(domain) <= MAX_ENUM_VALUES:
|
|
329
|
+
suggestions.extend(_proved(arena, site, EnumeratedDomain(column=column, values=domain), columns, dialect))
|
|
330
|
+
return suggestions
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def _markable(case: ir.SimpleCase) -> bool:
|
|
334
|
+
"""A case marker requires every WHEN to be a distinct non-null literal."""
|
|
335
|
+
values = [when.value for when in case.whens if isinstance(when, ir.Constant) and when.value is not None]
|
|
336
|
+
return len(values) == len(case.whens) and len(set(values)) == len(values)
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def _proved(
|
|
340
|
+
arena: Arena, site: AttachmentSite, property: Property, order: tuple[ir.OutputColumn, ...], dialect: str
|
|
341
|
+
) -> list[Suggestion]:
|
|
342
|
+
"""`property` as a one-item list when it is proved, else empty."""
|
|
343
|
+
evidence = arena.prove(property)
|
|
344
|
+
if not evidence.value:
|
|
345
|
+
return []
|
|
346
|
+
candidate = _candidate(site, property, order, dialect)
|
|
347
|
+
return [Suggestion(site, property, candidate.marker, evidence)]
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def _shrink(arena: Arena, members: tuple[ir.OutputColumn, ...]) -> tuple[ir.OutputColumn, ...]:
|
|
351
|
+
"""Drop columns while the rest stays unique. Every set up to `max_size` was
|
|
352
|
+
tried smallest first, so only a set wider than that can shrink."""
|
|
353
|
+
for column in members:
|
|
354
|
+
rest = tuple(other for other in members if other is not column)
|
|
355
|
+
if rest and arena.prove(UniqueSet(columns=frozenset(rest))).value:
|
|
356
|
+
return _shrink(arena, rest)
|
|
357
|
+
return members
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def _column_sets(columns: tuple[ir.OutputColumn, ...], max_size: int) -> Iterator[tuple[ir.OutputColumn, ...]]:
|
|
361
|
+
"""Column sets smallest first, ending with all columns when wider than `max_size`."""
|
|
362
|
+
for size in range(1, min(max_size, len(columns)) + 1):
|
|
363
|
+
yield from combinations(columns, size)
|
|
364
|
+
if len(columns) > max_size:
|
|
365
|
+
yield columns
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def _nameable_columns(relation: ir.RelationExpr) -> tuple[ir.OutputColumn, ...]:
|
|
369
|
+
"""Output columns a marker names unambiguously: named, and named once."""
|
|
370
|
+
names = [column.name.lower() for column in relation.output_columns]
|
|
371
|
+
return tuple(column for column in relation.output_columns if column.name and names.count(column.name.lower()) == 1)
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def _identity(item: Property) -> tuple:
|
|
375
|
+
"""Properties compare by identity; this compares them by kind and fields."""
|
|
376
|
+
return (type(item), tuple(getattr(item, field.name) for field in fields(item)))
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def _value_order(value: ir.LiteralValue) -> tuple:
|
|
380
|
+
"""Booleans, then numbers by value, then strings."""
|
|
381
|
+
match value.type:
|
|
382
|
+
case "numeric":
|
|
383
|
+
return (1, Decimal(value.text), value.text)
|
|
384
|
+
case "string":
|
|
385
|
+
return (2, 0, value.text)
|
|
386
|
+
case _:
|
|
387
|
+
return (0, 0, value.text)
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def _candidate(site: AttachmentSite, property: Property, order: tuple[ir.OutputColumn, ...], dialect: str) -> Candidate:
|
|
391
|
+
"""`property` at `site`; its marker lists columns in `order`, the output order."""
|
|
392
|
+
match property:
|
|
393
|
+
case ExactlyOneJoin():
|
|
394
|
+
return Candidate(site, property, "/**ASSERT EXACTLY ONE**/")
|
|
395
|
+
case OneToOneJoin():
|
|
396
|
+
return Candidate(site, property, "/**ASSERT ONE TO ONE**/")
|
|
397
|
+
case ManyToOneJoin():
|
|
398
|
+
return Candidate(site, property, "/**ASSERT MANY TO ONE**/")
|
|
399
|
+
case OneToManyJoin():
|
|
400
|
+
return Candidate(site, property, "/**ASSERT ONE TO MANY**/")
|
|
401
|
+
case UniqueJoin():
|
|
402
|
+
return Candidate(site, property, "/**ASSERT UNIQUE**/")
|
|
403
|
+
case ExhaustiveCase():
|
|
404
|
+
return Candidate(site, property, "/**ASSERT EXHAUSTIVE**/")
|
|
405
|
+
case EnumeratedDomain(column=column, values=values):
|
|
406
|
+
name = exp.to_identifier(column.name).sql(dialect=dialect)
|
|
407
|
+
listed = ", ".join(value.sql() for value in sorted(values, key=_value_order))
|
|
408
|
+
return Candidate(site, property, f"/**ASSERT ENUM({name} IN ({listed}))**/")
|
|
409
|
+
case NonNullUniqueSet(columns=columns):
|
|
410
|
+
kind = "NOT NULL UNIQUE"
|
|
411
|
+
case UniqueSet(columns=columns):
|
|
412
|
+
kind = "UNIQUE"
|
|
413
|
+
case NonNullColumns(columns=columns):
|
|
414
|
+
kind = "NOT NULL"
|
|
415
|
+
case _:
|
|
416
|
+
raise TypeError(f"No marker asserts {type(property).__name__}")
|
|
417
|
+
names = ", ".join(exp.to_identifier(column.name).sql(dialect=dialect) for column in order if column in columns)
|
|
418
|
+
return Candidate(site, property, f"/**ASSERT {kind}({names})**/")
|