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,264 @@
|
|
|
1
|
+
"""Joins: the join kinds, ON and USING conditions (USING columns merged), join
|
|
2
|
+
markers, and semi and anti joins."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from dataclasses import replace
|
|
7
|
+
from typing import TYPE_CHECKING, assert_never
|
|
8
|
+
|
|
9
|
+
from sqlglot import Expr, exp
|
|
10
|
+
|
|
11
|
+
from sqlassert import diagnostics as diag
|
|
12
|
+
from sqlassert import ir
|
|
13
|
+
from sqlassert.ir.names import may_be_renamed
|
|
14
|
+
from sqlassert.diagnostics import Diagnostic
|
|
15
|
+
from sqlassert.properties import ExactlyOneJoin, ManyToOneJoin, OneToManyJoin, OneToOneJoin, UniqueJoin
|
|
16
|
+
from sqlassert.provenance import Origin
|
|
17
|
+
from sqlassert.sql_parse import JOIN_MARKER_NOUNS, join_marker_kind, join_origin
|
|
18
|
+
from sqlassert.ir.convert.shared import (
|
|
19
|
+
_Binding, _Lowered, _placed, _pass_output_columns, _source_line, _and, _filter_conjuncts, _flattened, _nested_join, _USING_QUALIFIER,
|
|
20
|
+
_SCALAR_QUALIFIER,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
if TYPE_CHECKING:
|
|
24
|
+
from sqlassert.ir.convert.parser import IrParser
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class _Joins:
|
|
28
|
+
def _lower_join(self: IrParser, left: _Lowered, join: exp.Join) -> _Lowered:
|
|
29
|
+
right = self._lower_source(join.this)
|
|
30
|
+
origin = _placed(self._origin(join), join)
|
|
31
|
+
kind = _join_kind(join, self.dialect)
|
|
32
|
+
if kind is None:
|
|
33
|
+
return self._opaque_join(left, right, join, origin)
|
|
34
|
+
predicate = self._lower_join_predicate(join, left, right)
|
|
35
|
+
if kind == "semi" or kind == "anti":
|
|
36
|
+
# RIGHT SEMI and RIGHT ANTI keep right rows: the same join, inputs swapped.
|
|
37
|
+
kept, other = (right, left) if (join.args.get("side") or "").lower() == "right" else (left, right)
|
|
38
|
+
filtered = self._filtering_join(kept, other.relation, kind, predicate, origin)
|
|
39
|
+
assert isinstance(filtered.relation, ir.Join)
|
|
40
|
+
self._join_marker(join, filtered.relation)
|
|
41
|
+
self._add_attachment_site(join, _join_label(join, self.dialect), filtered.relation)
|
|
42
|
+
return filtered
|
|
43
|
+
if _is_positional(join):
|
|
44
|
+
# A FULL JOIN on row position: an opaque condition, as no column holds it.
|
|
45
|
+
predicate = ir.OpaqueExpression(origin=origin, description="row position")
|
|
46
|
+
input_columns = left.relation.output_columns + right.relation.output_columns
|
|
47
|
+
output_columns = _pass_output_columns(input_columns, origin)
|
|
48
|
+
remapped = {source: output for source, output in zip(input_columns, output_columns)}
|
|
49
|
+
relation = ir.Join(
|
|
50
|
+
origin=origin,
|
|
51
|
+
output_columns=output_columns,
|
|
52
|
+
is_schema_complete=left.relation.is_schema_complete and right.relation.is_schema_complete,
|
|
53
|
+
kind=kind,
|
|
54
|
+
left=left.relation,
|
|
55
|
+
right=right.relation,
|
|
56
|
+
predicate=predicate,
|
|
57
|
+
# A RIGHT or FULL join cannot read its left input (DuckDB rejects it).
|
|
58
|
+
lateral=kind in {"inner", "left", "cross"} and self._reads_left(join.this, left),
|
|
59
|
+
)
|
|
60
|
+
bindings = tuple(
|
|
61
|
+
replace(binding, column=remapped[binding.column])
|
|
62
|
+
for binding in left.bindings + right.bindings
|
|
63
|
+
)
|
|
64
|
+
self._join_marker(join, relation)
|
|
65
|
+
self._add_attachment_site(join, _join_label(join, self.dialect), relation)
|
|
66
|
+
lowered = _Lowered(relation, bindings)
|
|
67
|
+
return self._merge_using(lowered, join, kind, len(left.bindings), origin) if join.args.get("using") else lowered
|
|
68
|
+
|
|
69
|
+
def _merge_using(self: IrParser, lowered: _Lowered, join: exp.Join, kind: ir.JoinKind, left_count: int, origin: Origin) -> _Lowered:
|
|
70
|
+
"""`JOIN ... USING (k)` outputs one `k`: the left input's for an INNER
|
|
71
|
+
or LEFT JOIN (equal to the right's wherever both exist), the right's
|
|
72
|
+
for a RIGHT JOIN, and `coalesce(left.k, right.k)` for a FULL JOIN,
|
|
73
|
+
where either side may be padded. An unqualified `k` reads it, so a
|
|
74
|
+
later `USING (k)` or `WHERE k = ...` sees one column; `a.k` and `b.k`
|
|
75
|
+
still read their own side.
|
|
76
|
+
|
|
77
|
+
The bindings are in the order a star over the join selects them (the
|
|
78
|
+
shadowed ones, which a star skips, stay for `a.k` and `a.*`): the
|
|
79
|
+
merged columns first in USING order, then the left input's columns,
|
|
80
|
+
then the right's (standard SQL); or each at its left column's place, or
|
|
81
|
+
first in the left input's order, where the dialect does so
|
|
82
|
+
(`using_star_order`). A
|
|
83
|
+
USING name that is not one column of each input leaves the join's
|
|
84
|
+
columns unknown, as the engine's are then not these."""
|
|
85
|
+
bindings = list(lowered.bindings)
|
|
86
|
+
merging: list[tuple[int, str, int]] = []
|
|
87
|
+
unmerged = False
|
|
88
|
+
for identifier in join.args.get("using") or ():
|
|
89
|
+
name = identifier.name.lower()
|
|
90
|
+
sides = [
|
|
91
|
+
[index for index in (range(left_count) if left else range(left_count, len(bindings)))
|
|
92
|
+
if bindings[index].name == name and not bindings[index].shadowed and not bindings[index].qualifier.startswith(_SCALAR_QUALIFIER)
|
|
93
|
+
and not may_be_renamed(bindings[index].repeated, name)]
|
|
94
|
+
for left in (True, False)
|
|
95
|
+
]
|
|
96
|
+
if any(len(side) != 1 for side in sides):
|
|
97
|
+
unmerged = True
|
|
98
|
+
continue
|
|
99
|
+
(mine,), (theirs,) = sides
|
|
100
|
+
for index in (mine, theirs):
|
|
101
|
+
bindings[index] = replace(bindings[index], shadowed=True)
|
|
102
|
+
merging.append((mine, name, theirs))
|
|
103
|
+
relation = lowered.relation
|
|
104
|
+
values: tuple[ir.OutputColumn, ...] = ()
|
|
105
|
+
if (kind == "full" and merging) or (unmerged and relation.is_schema_complete):
|
|
106
|
+
passed = _pass_output_columns(relation.output_columns, origin)
|
|
107
|
+
remapped = dict(zip(relation.output_columns, passed))
|
|
108
|
+
bindings = [replace(binding, column=remapped[binding.column]) for binding in bindings]
|
|
109
|
+
if kind == "full":
|
|
110
|
+
values = tuple(
|
|
111
|
+
ir.OutputColumn(origin=origin, name=name, scalar_expr=ir.Coalesce(origin=origin, arguments=(
|
|
112
|
+
ir.ColumnRef(origin=origin, column=bindings[mine].column), ir.ColumnRef(origin=origin, column=bindings[theirs].column),
|
|
113
|
+
)))
|
|
114
|
+
for mine, name, theirs in merging
|
|
115
|
+
)
|
|
116
|
+
relation = ir.Project(
|
|
117
|
+
origin=origin, output_columns=(*passed, *values), is_schema_complete=relation.is_schema_complete and not unmerged, input=relation,
|
|
118
|
+
)
|
|
119
|
+
merged: list[tuple[int, _Binding]] = []
|
|
120
|
+
for position, (mine, name, theirs) in enumerate(merging):
|
|
121
|
+
column = values[position] if kind == "full" else bindings[theirs if kind == "right" else mine].column
|
|
122
|
+
self._using_columns += 1
|
|
123
|
+
merged.append((mine, _Binding(f"{_USING_QUALIFIER}{self._using_columns}", name, column)))
|
|
124
|
+
order = self.semantics.using_star_order
|
|
125
|
+
if order == "left_position":
|
|
126
|
+
at = dict(merged)
|
|
127
|
+
ordered = []
|
|
128
|
+
for index, binding in enumerate(bindings):
|
|
129
|
+
ordered.extend((at[index], binding) if index in at else (binding,))
|
|
130
|
+
else:
|
|
131
|
+
ordered = [*(binding for _, binding in (sorted(merged, key=lambda item: item[0]) if order == "left_order" else merged)), *bindings]
|
|
132
|
+
return _Lowered(relation, tuple(ordered))
|
|
133
|
+
|
|
134
|
+
def _opaque_join(self: IrParser, left: _Lowered, right: _Lowered, join: exp.Join, origin: Origin) -> _Lowered:
|
|
135
|
+
"""A join whose kind is not modelled: every column it outputs is opaque,
|
|
136
|
+
and a marker on it is reported as unanalyzed."""
|
|
137
|
+
description = join.sql(dialect=self.dialect)
|
|
138
|
+
input_columns = left.relation.output_columns + right.relation.output_columns
|
|
139
|
+
opaque = {
|
|
140
|
+
column: ir.OutputColumn(origin=origin, name=column.name, scalar_expr=ir.OpaqueExpression(origin=origin, description=description))
|
|
141
|
+
for column in input_columns
|
|
142
|
+
}
|
|
143
|
+
relation = ir.OpaqueRelation(origin=origin, output_columns=tuple(opaque.values()), is_schema_complete=False, description=description)
|
|
144
|
+
keywords = " ".join(part for part in (join.args.get("method"), join.side, join.kind, "JOIN") if part)
|
|
145
|
+
self._unsupported.append((relation, keywords + (" in ClickHouse" if self.dialect == "clickhouse" else "")))
|
|
146
|
+
return _Lowered(relation, tuple(
|
|
147
|
+
replace(binding, column=opaque[binding.column]) for binding in left.bindings + right.bindings
|
|
148
|
+
))
|
|
149
|
+
|
|
150
|
+
def _join_marker(self: IrParser, join: exp.Join, relation: ir.Join) -> None:
|
|
151
|
+
kind = join_marker_kind(join)
|
|
152
|
+
if kind is not None:
|
|
153
|
+
self._handled_joins.add(id(join))
|
|
154
|
+
cardinality = {"unique-join": UniqueJoin, "many-to-one-join": ManyToOneJoin, "one-to-many-join": OneToManyJoin, "one-to-one-join": OneToOneJoin}
|
|
155
|
+
if kind in cardinality and relation.kind in {"semi", "anti"}:
|
|
156
|
+
# It keeps or drops left rows whole and outputs no right row: cardinality does not apply.
|
|
157
|
+
self._diagnostics.append(Diagnostic(
|
|
158
|
+
diag.CARDINALITY_ON_FILTERING_JOIN,
|
|
159
|
+
f"the {JOIN_MARKER_NOUNS[kind]} marker on line {join_origin(join, self.dialect).line} is on a {relation.kind} join, "
|
|
160
|
+
"which outputs no right rows: join cardinality does not apply to it",
|
|
161
|
+
join_origin(join, self.dialect),
|
|
162
|
+
))
|
|
163
|
+
return
|
|
164
|
+
match kind:
|
|
165
|
+
case "unique-join" | "many-to-one-join" | "one-to-many-join" | "one-to-one-join":
|
|
166
|
+
self._assertions.append(ir.Assertion(origin=join_origin(join, self.dialect), property=cardinality[kind](join=relation)))
|
|
167
|
+
case "exactly-one-join":
|
|
168
|
+
self._assertions.append(
|
|
169
|
+
ir.Assertion(origin=join_origin(join, self.dialect), property=ExactlyOneJoin(join=relation))
|
|
170
|
+
)
|
|
171
|
+
case None:
|
|
172
|
+
pass
|
|
173
|
+
case _:
|
|
174
|
+
assert_never(kind)
|
|
175
|
+
|
|
176
|
+
def _lower_join_predicate(self: IrParser, join: exp.Join, left: _Lowered, right: _Lowered) -> ir.ScalarExpr | None:
|
|
177
|
+
"""The ON condition; USING is an AND of one equality per column."""
|
|
178
|
+
using = join.args.get("using")
|
|
179
|
+
if using:
|
|
180
|
+
return _and(tuple(
|
|
181
|
+
ir.Equality(
|
|
182
|
+
origin=self._origin(identifier, _source_line(identifier)),
|
|
183
|
+
left=self._lower_expression(
|
|
184
|
+
exp.column(identifier.name), left.bindings, schema_complete=left.relation.is_schema_complete, line=_source_line(identifier),
|
|
185
|
+
),
|
|
186
|
+
right=self._lower_expression(
|
|
187
|
+
exp.column(identifier.name), right.bindings, schema_complete=right.relation.is_schema_complete, line=_source_line(identifier),
|
|
188
|
+
),
|
|
189
|
+
)
|
|
190
|
+
for identifier in using
|
|
191
|
+
), self._origin(join))
|
|
192
|
+
predicate = join.args.get("on")
|
|
193
|
+
if predicate is None:
|
|
194
|
+
return None
|
|
195
|
+
complete = left.relation.is_schema_complete and right.relation.is_schema_complete
|
|
196
|
+
return self._lower_condition(predicate, _filter_conjuncts(predicate), left.bindings + right.bindings, schema_complete=complete)
|
|
197
|
+
|
|
198
|
+
def _lower_condition(
|
|
199
|
+
self: IrParser, source: Expr, conjuncts: list[Expr], bindings: tuple[_Binding, ...], *, schema_complete: bool
|
|
200
|
+
) -> ir.ScalarExpr:
|
|
201
|
+
"""The AND of `conjuncts`, the top-level conjuncts of `source`."""
|
|
202
|
+
assert conjuncts, "a condition has at least one conjunct"
|
|
203
|
+
lowered = _and(
|
|
204
|
+
tuple(self._lower_conjunct(conjunct, bindings, schema_complete=schema_complete) for conjunct in conjuncts),
|
|
205
|
+
self._origin(source, _source_line(source)),
|
|
206
|
+
)
|
|
207
|
+
assert lowered is not None
|
|
208
|
+
return lowered
|
|
209
|
+
|
|
210
|
+
def _lower_conjunct(self: IrParser, conjunct: Expr, bindings: tuple[_Binding, ...], *, schema_complete: bool) -> ir.ScalarExpr:
|
|
211
|
+
return self._lower_expression(conjunct, bindings, schema_complete=schema_complete, line=_source_line(conjunct))
|
|
212
|
+
|
|
213
|
+
def _filtering_join(
|
|
214
|
+
self: IrParser, left: _Lowered, right: ir.RelationExpr, kind: ir.JoinKind, predicate: ir.ScalarExpr | None, origin: Origin
|
|
215
|
+
) -> _Lowered:
|
|
216
|
+
"""A semi or anti join: it keeps or drops left rows, and outputs only theirs."""
|
|
217
|
+
output_columns = _pass_output_columns(left.relation.output_columns, origin)
|
|
218
|
+
remapped = {source: output for source, output in zip(left.relation.output_columns, output_columns)}
|
|
219
|
+
relation = ir.Join(
|
|
220
|
+
origin=origin, output_columns=output_columns, is_schema_complete=left.relation.is_schema_complete,
|
|
221
|
+
kind=kind, left=left.relation, right=right, predicate=predicate,
|
|
222
|
+
)
|
|
223
|
+
return _Lowered(relation, tuple(replace(binding, column=remapped[binding.column]) for binding in left.bindings))
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _is_positional(join: exp.Join) -> bool:
|
|
227
|
+
return (join.args.get("method") or "").lower() == "positional"
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _join_kind(join: exp.Join, dialect: str) -> ir.JoinKind | None:
|
|
231
|
+
"""SEMI, ANTI and CROSS whatever the side; otherwise the side, else INNER
|
|
232
|
+
(`STRAIGHT_JOIN`, and ASOF, which keeps a subset of the inner join's rows).
|
|
233
|
+
None for a join whose semantics are not modelled: it lowers opaque."""
|
|
234
|
+
if _is_positional(join):
|
|
235
|
+
return "full"
|
|
236
|
+
kind, side = (join.args.get("kind") or "").lower(), (join.args.get("side") or "").lower()
|
|
237
|
+
if dialect == "clickhouse" and (side or kind not in {"", "inner", "cross"}):
|
|
238
|
+
# TODO: check ClickHouse semantics. Outer joins pad with the column
|
|
239
|
+
# type's default, not NULL, unless join_use_nulls is set; SEMI and ANTI
|
|
240
|
+
# joins keep the right columns; ANY and ASOF pick one match.
|
|
241
|
+
return None
|
|
242
|
+
match kind, side:
|
|
243
|
+
case ("semi" | "anti" | "cross") as kind, _:
|
|
244
|
+
return kind
|
|
245
|
+
case "" | "inner" | "outer" | "straight_join", ("left" | "right" | "full") as side:
|
|
246
|
+
return side
|
|
247
|
+
case "outer", "":
|
|
248
|
+
return "full"
|
|
249
|
+
case "" | "inner" | "straight_join", "":
|
|
250
|
+
return "inner"
|
|
251
|
+
case _:
|
|
252
|
+
# TODO: check the semantics of each dialect's other join kinds
|
|
253
|
+
# (ClickHouse ARRAY JOIN, ANY, ...) before modelling one.
|
|
254
|
+
return None
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _join_label(join: exp.Join, dialect: str) -> str:
|
|
258
|
+
keywords = " ".join(part for part in (join.side, join.kind, "JOIN") if part)
|
|
259
|
+
source = join.this
|
|
260
|
+
if _nested_join(source) is not None:
|
|
261
|
+
return f"{keywords} ({', '.join(part.alias_or_name for part in _flattened([source]))})"
|
|
262
|
+
if isinstance(source, exp.Subquery):
|
|
263
|
+
return f"{keywords} subquery {source.alias}".rstrip()
|
|
264
|
+
return f"{keywords} {source.sql(dialect=dialect)}"
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
"""Property Markers and Attachment Sites: column markers on a query, each
|
|
2
|
+
site's syntax, Foreign Key markers linked to their referenced relation, and
|
|
3
|
+
markers left unanalyzed."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from collections.abc import Iterable
|
|
8
|
+
from typing import TYPE_CHECKING, assert_never
|
|
9
|
+
|
|
10
|
+
from sqlglot import exp
|
|
11
|
+
|
|
12
|
+
from sqlassert import diagnostics as diag
|
|
13
|
+
from sqlassert import ir
|
|
14
|
+
from sqlassert.ir.names import named_columns
|
|
15
|
+
from sqlassert.diagnostics import Diagnostic, quoted_all
|
|
16
|
+
from sqlassert.properties import (
|
|
17
|
+
EnumeratedDomain, ForeignKey, FunctionalDependency, NonNullColumn, NonNullColumns, NonNullElements, NonNullUniqueSet, ReferentialCoverage,
|
|
18
|
+
UniqueSet,
|
|
19
|
+
)
|
|
20
|
+
from sqlassert.provenance import AttachmentSite, Origin, SQL
|
|
21
|
+
from sqlassert.sql_parse import (
|
|
22
|
+
JOIN_MARKER_NOUNS, MARKER_NOUNS, ParsedProgram, assertion_span, column_markers, exhaustive_span, join_marker_kind, join_origin, marker_position,
|
|
23
|
+
)
|
|
24
|
+
from sqlassert.ir.convert.shared import _Symbol, _MarkerReference, _missing, _ended_set_operation, _select_label
|
|
25
|
+
|
|
26
|
+
if TYPE_CHECKING:
|
|
27
|
+
from sqlassert.ir.convert.parser import IrParser
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class _Markers:
|
|
31
|
+
def _register_column_markers(self: IrParser, relation: ir.RelationExpr, select: exp.Query) -> None:
|
|
32
|
+
for marker in column_markers(select):
|
|
33
|
+
kind, columns, line = marker.kind, marker.columns, marker.span.line
|
|
34
|
+
self._handled_column_markers.add(id(marker))
|
|
35
|
+
origin = Origin.marked(select.sql(dialect=self.dialect), marker.span)
|
|
36
|
+
# A name the output repeats (as a star over a derived table that does), or one an engine may give a repeat, is ambiguous.
|
|
37
|
+
by_name, duplicates, unknown = named_columns(relation.output_columns, (*columns, *marker.dependent))
|
|
38
|
+
if duplicates:
|
|
39
|
+
self._diagnostics.append(Diagnostic(
|
|
40
|
+
diag.UNRESOLVED_ASSERTED_COLUMN, f"output names {quoted_all(duplicates)} are ambiguous; use distinct aliases", origin,
|
|
41
|
+
))
|
|
42
|
+
continue
|
|
43
|
+
if unknown and relation.is_schema_complete:
|
|
44
|
+
self._diagnostics.append(
|
|
45
|
+
Diagnostic(
|
|
46
|
+
diag.UNKNOWN_ASSERTED_COLUMN,
|
|
47
|
+
f"the {MARKER_NOUNS[kind]} on line {line} names {', '.join(unknown)}, which is not among this Select Expression's own output columns",
|
|
48
|
+
origin,
|
|
49
|
+
)
|
|
50
|
+
)
|
|
51
|
+
continue
|
|
52
|
+
if unknown:
|
|
53
|
+
# The column may exist in a source whose columns are unknown,
|
|
54
|
+
# so it is neither absent nor something to state a Property of.
|
|
55
|
+
self._diagnostics.append(
|
|
56
|
+
Diagnostic(
|
|
57
|
+
diag.UNRESOLVED_ASSERTED_COLUMN,
|
|
58
|
+
f"the {MARKER_NOUNS[kind]} on line {line} names {', '.join(unknown)}, which cannot be resolved: "
|
|
59
|
+
"this Select Expression reads a relation whose columns are unknown (declare it with CREATE TABLE)",
|
|
60
|
+
origin,
|
|
61
|
+
)
|
|
62
|
+
)
|
|
63
|
+
continue
|
|
64
|
+
members = frozenset(by_name[column.lower()] for column in columns)
|
|
65
|
+
dependent = frozenset(by_name[column.lower()] for column in marker.dependent)
|
|
66
|
+
match kind:
|
|
67
|
+
case "foreign-key" | "declared-foreign-key":
|
|
68
|
+
self._marker_references.append(_MarkerReference(
|
|
69
|
+
marker, kind, origin, tuple(by_name[column.lower()] for column in columns),
|
|
70
|
+
self._marker_targets[id(marker)], len(self._assertions),
|
|
71
|
+
))
|
|
72
|
+
case "unique":
|
|
73
|
+
self._assertions.append(ir.Assertion(origin=origin, property=UniqueSet(columns=members)))
|
|
74
|
+
case "key":
|
|
75
|
+
self._assertions.append(ir.Assertion(origin=origin, property=NonNullUniqueSet(columns=members)))
|
|
76
|
+
case "not-null":
|
|
77
|
+
self._assertions.append(ir.Assertion(origin=origin, property=NonNullColumns(columns=members)))
|
|
78
|
+
case "declared-unique":
|
|
79
|
+
self._declarations.append(UniqueSet(columns=members))
|
|
80
|
+
case "declared-key":
|
|
81
|
+
# Non-nullness is declared per column too, so it outlives
|
|
82
|
+
# projections that drop part of a composite key.
|
|
83
|
+
self._declarations.append(NonNullUniqueSet(columns=members))
|
|
84
|
+
self._declarations.extend(NonNullColumn(column=column) for column in members)
|
|
85
|
+
case "declared-not-null":
|
|
86
|
+
self._declarations.extend(NonNullColumn(column=column) for column in members)
|
|
87
|
+
case "not-null-elements":
|
|
88
|
+
self._assertions.append(ir.Assertion(origin=origin, property=NonNullElements(columns=members)))
|
|
89
|
+
case "declared-not-null-elements":
|
|
90
|
+
# One per column, so each column's elements are known on their own.
|
|
91
|
+
self._declarations.extend(NonNullElements(columns=frozenset({column})) for column in members)
|
|
92
|
+
case "determines":
|
|
93
|
+
property = FunctionalDependency(determinant=members, dependent=dependent)
|
|
94
|
+
self._assertions.append(ir.Assertion(origin=origin, property=property))
|
|
95
|
+
case "declared-determines":
|
|
96
|
+
self._declarations.append(FunctionalDependency(determinant=members, dependent=dependent))
|
|
97
|
+
case "enum" | "declared-enum":
|
|
98
|
+
column, = members
|
|
99
|
+
values = frozenset(marker.values)
|
|
100
|
+
domain = EnumeratedDomain(column=column, values=values)
|
|
101
|
+
if kind == "enum":
|
|
102
|
+
self._assertions.append(ir.Assertion(origin=origin, property=domain))
|
|
103
|
+
else:
|
|
104
|
+
self._declarations.append(domain)
|
|
105
|
+
case _:
|
|
106
|
+
assert_never(kind)
|
|
107
|
+
|
|
108
|
+
def _add_attachment_site(self: IrParser, node: exp.Join | exp.Case, label: str, relation: ir.Join | ir.SimpleCase) -> None:
|
|
109
|
+
"""The site before a JOIN or simple CASE."""
|
|
110
|
+
position = marker_position(node)
|
|
111
|
+
if position is not None:
|
|
112
|
+
offset, line = position
|
|
113
|
+
site = AttachmentSite(label, line, offset, False)
|
|
114
|
+
self._attachment_sites.append((site, relation))
|
|
115
|
+
if isinstance(node, exp.Join):
|
|
116
|
+
self._syntax[site] = node
|
|
117
|
+
|
|
118
|
+
def _add_query_site(
|
|
119
|
+
self: IrParser, query: exp.Select | exp.SetOperation, relation: ir.RelationExpr, written: exp.Select | None,
|
|
120
|
+
sort_keys: tuple[ir.OutputColumn, ...] | None,
|
|
121
|
+
) -> None:
|
|
122
|
+
"""The site after the last token of `query`, with the Select written
|
|
123
|
+
there and its ORDER BY keys. A marker there marks the whole of the
|
|
124
|
+
set operation `query` is the last operand of, if it ends there too:
|
|
125
|
+
then `query` has no site of its own, and waits in `_ending` for the
|
|
126
|
+
set operation to take it."""
|
|
127
|
+
position = marker_position(query)
|
|
128
|
+
if position is None:
|
|
129
|
+
return
|
|
130
|
+
offset, line = position
|
|
131
|
+
if _ended_set_operation(query, offset) is not None:
|
|
132
|
+
self._ending[offset] = (relation, written)
|
|
133
|
+
return
|
|
134
|
+
site = AttachmentSite(_select_label(query), line, offset, True)
|
|
135
|
+
self._attachment_sites.append((site, relation))
|
|
136
|
+
if written is not None:
|
|
137
|
+
self._syntax[site] = written
|
|
138
|
+
self._site_sort_keys[site] = sort_keys
|
|
139
|
+
|
|
140
|
+
def _link_marker_references(self: IrParser) -> None:
|
|
141
|
+
"""Lower each Foreign Key marker's referenced relation, then state the
|
|
142
|
+
marker's Property; assertions keep the place their marker was written."""
|
|
143
|
+
placed: list[tuple[int, ir.Assertion]] = []
|
|
144
|
+
while self._marker_references:
|
|
145
|
+
pending = self._marker_references.pop(0)
|
|
146
|
+
target = self._resolve_symbol(pending.target)
|
|
147
|
+
marker = pending.marker
|
|
148
|
+
referenced = self._columns_named(target, marker.referenced_columns)
|
|
149
|
+
if referenced is None:
|
|
150
|
+
self._diagnostics.append(Diagnostic(
|
|
151
|
+
diag.UNKNOWN_REFERENCED_COLUMN,
|
|
152
|
+
f"the {MARKER_NOUNS[marker.kind]} on line {marker.span.line} references "
|
|
153
|
+
f"{target.name}({quoted_all(marker.referenced_columns)}), but {target.name} has no column "
|
|
154
|
+
f"{quoted_all(_missing(target, marker.referenced_columns))}",
|
|
155
|
+
pending.origin,
|
|
156
|
+
))
|
|
157
|
+
continue
|
|
158
|
+
match pending.kind:
|
|
159
|
+
case "foreign-key":
|
|
160
|
+
placed.append((pending.position, ir.Assertion(
|
|
161
|
+
origin=pending.origin, property=ForeignKey(columns=pending.columns, referenced_columns=referenced),
|
|
162
|
+
)))
|
|
163
|
+
case "declared-foreign-key":
|
|
164
|
+
self._declarations.append(ReferentialCoverage(columns=pending.columns, referenced_columns=referenced))
|
|
165
|
+
case _:
|
|
166
|
+
assert_never(pending.kind)
|
|
167
|
+
# Descending, so earlier positions stay valid; ties keep written order.
|
|
168
|
+
for position, assertion in reversed(placed):
|
|
169
|
+
self._assertions.insert(position, assertion)
|
|
170
|
+
|
|
171
|
+
def _columns_named(self: IrParser, relation: ir.RelationExpr, names: Iterable[str]) -> tuple[ir.OutputColumn, ...] | None:
|
|
172
|
+
names = tuple(names)
|
|
173
|
+
found, ambiguous, unknown = named_columns(relation.output_columns, names) # As a marker names them.
|
|
174
|
+
return None if ambiguous or unknown else tuple(found[name.lower()] for name in names)
|
|
175
|
+
|
|
176
|
+
def _report_cycle(self: IrParser, symbol: _Symbol, table: exp.Table) -> None:
|
|
177
|
+
if symbol in self._reported_cycles:
|
|
178
|
+
return
|
|
179
|
+
self._reported_cycles.add(symbol)
|
|
180
|
+
self._diagnostics.append(
|
|
181
|
+
Diagnostic(
|
|
182
|
+
diag.RECURSIVE_VIEW_DEFINITION,
|
|
183
|
+
f"view {symbol.name.lower()} is defined recursively, which is not supported",
|
|
184
|
+
Origin(SQL, table.sql(dialect=self.dialect)),
|
|
185
|
+
)
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
def _report_unanalyzed(self: IrParser, ast: ParsedProgram) -> None:
|
|
189
|
+
for join in _asserted_joins(ast):
|
|
190
|
+
origin, kind = join_origin(join, self.dialect), join_marker_kind(join)
|
|
191
|
+
if id(join) in self._handled_joins:
|
|
192
|
+
continue
|
|
193
|
+
assert kind is not None, "every asserted join records its marker kind"
|
|
194
|
+
self._diagnostics.append(
|
|
195
|
+
Diagnostic(
|
|
196
|
+
diag.UNANALYZED_ASSERTION,
|
|
197
|
+
f"the {JOIN_MARKER_NOUNS[kind]} assertion on line {origin.line} "
|
|
198
|
+
"is in a part of the program this analysis does not model",
|
|
199
|
+
origin,
|
|
200
|
+
)
|
|
201
|
+
)
|
|
202
|
+
for case in _asserted_cases(ast):
|
|
203
|
+
if id(case) in self._handled_cases:
|
|
204
|
+
continue
|
|
205
|
+
span = exhaustive_span(case)
|
|
206
|
+
assert span is not None, "every asserted case records its marker span"
|
|
207
|
+
self._diagnostics.append(
|
|
208
|
+
Diagnostic(
|
|
209
|
+
diag.UNANALYZED_ASSERTION,
|
|
210
|
+
f"the exhaustive assertion on line {span.line} is in a part of the program this analysis does not model",
|
|
211
|
+
Origin.marked(case.sql(dialect=self.dialect), span),
|
|
212
|
+
)
|
|
213
|
+
)
|
|
214
|
+
for select in _asserted_selects(ast):
|
|
215
|
+
for marker in column_markers(select):
|
|
216
|
+
if id(marker) in self._handled_column_markers:
|
|
217
|
+
continue
|
|
218
|
+
self._diagnostics.append(
|
|
219
|
+
Diagnostic(
|
|
220
|
+
diag.UNANALYZED_ASSERTION,
|
|
221
|
+
f"the {MARKER_NOUNS[marker.kind]} on line {marker.span.line} is in a part of the program this analysis does not model",
|
|
222
|
+
Origin.marked(select.sql(dialect=self.dialect), marker.span),
|
|
223
|
+
)
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _asserted_joins(ast: ParsedProgram) -> list[exp.Join]:
|
|
228
|
+
statements = (*ast.create_statements, ast.root_select)
|
|
229
|
+
return [
|
|
230
|
+
join for statement in statements if statement is not None
|
|
231
|
+
for join in statement.find_all(exp.Join) if assertion_span(join) is not None
|
|
232
|
+
]
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _asserted_selects(ast: ParsedProgram) -> list[exp.Query]:
|
|
236
|
+
statements = (*ast.create_statements, ast.root_select)
|
|
237
|
+
return [
|
|
238
|
+
select for statement in statements if statement is not None
|
|
239
|
+
for select in statement.find_all(exp.Select, exp.SetOperation) if column_markers(select)
|
|
240
|
+
]
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _asserted_cases(ast: ParsedProgram) -> list[exp.Case]:
|
|
245
|
+
statements = (*ast.create_statements, ast.root_select)
|
|
246
|
+
return [
|
|
247
|
+
case for statement in statements if statement is not None
|
|
248
|
+
for case in statement.find_all(exp.Case) if exhaustive_span(case) is not None
|
|
249
|
+
]
|