sqlassert 0.3.3__py3-none-any.whl → 0.4.1__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/diagnostics.py +17 -6
- sqlassert/dialects.py +437 -7
- sqlassert/discovery/bigquery.py +3 -1
- sqlassert/discovery/databricks.py +25 -2
- sqlassert/discovery/duckdb.py +49 -7
- sqlassert/discovery/fetcher.py +130 -21
- sqlassert/discovery/information_schema.py +30 -2
- sqlassert/discovery/mysql.py +22 -1
- sqlassert/discovery/postgres.py +22 -5
- sqlassert/discovery/redshift.py +3 -2
- sqlassert/discovery/snowflake.py +3 -0
- sqlassert/discovery/trino.py +2 -2
- sqlassert/hazards.py +248 -87
- sqlassert/ir/__init__.py +4 -1
- sqlassert/ir/convert/__init__.py +13 -0
- sqlassert/ir/convert/aggregation.py +439 -0
- sqlassert/ir/convert/builtins.py +140 -0
- sqlassert/ir/convert/expressions.py +572 -0
- sqlassert/ir/convert/joins.py +264 -0
- sqlassert/ir/convert/markers.py +249 -0
- sqlassert/ir/convert/parser.py +253 -0
- sqlassert/ir/convert/queries.py +259 -0
- sqlassert/ir/convert/schema.py +606 -0
- sqlassert/ir/convert/scopes.py +205 -0
- sqlassert/ir/convert/selects.py +337 -0
- sqlassert/ir/convert/shared.py +429 -0
- sqlassert/ir/convert/sources.py +432 -0
- sqlassert/ir/convert/subqueries.py +364 -0
- sqlassert/ir/convert/value_types.py +223 -0
- sqlassert/ir/convert/windows.py +275 -0
- sqlassert/ir/model.py +125 -47
- sqlassert/ir/names.py +63 -0
- 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 +523 -0
- sqlassert/rules/domain.py +8 -7
- 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 +282 -41
- sqlassert/rules/nullability.py +5 -5
- sqlassert/rules/uniqueness.py +171 -47
- sqlassert/rules/value_typing.py +337 -0
- sqlassert/sql_parse.py +28 -1
- sqlassert/suggest.py +11 -15
- sqlassert-0.4.1.dist-info/METADATA +235 -0
- sqlassert-0.4.1.dist-info/RECORD +69 -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.1.dist-info}/WHEEL +0 -0
- {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/entry_points.txt +0 -0
- {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/licenses/LICENSE +0 -0
- {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
"""Windows and row subsets: QUALIFY, DISTINCT ON, partitions kept one row each,
|
|
2
|
+
and the Knowledge a row number states."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from collections.abc import Sequence
|
|
7
|
+
from typing import TYPE_CHECKING
|
|
8
|
+
|
|
9
|
+
from sqlglot import Expr, exp
|
|
10
|
+
|
|
11
|
+
from sqlassert import ir
|
|
12
|
+
from sqlassert.properties import NonNullColumn, UniqueSet
|
|
13
|
+
from sqlassert.ir.convert.shared import (
|
|
14
|
+
_Lowered, _placed, _pass_output_columns, _filter_conjuncts, _set_returning_calls, _schema_path, _only_star, _matching_output, _unaliased,
|
|
15
|
+
_row_number_window,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
if TYPE_CHECKING:
|
|
19
|
+
from sqlassert.ir.convert.parser import IrParser
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class _Windows:
|
|
23
|
+
def _lower_qualify(
|
|
24
|
+
self: IrParser, lowered: _Lowered, select: exp.Select, items: list[Expr], qualify: exp.Qualify,
|
|
25
|
+
) -> ir.RelationExpr | None:
|
|
26
|
+
"""A non-grouped, non-DISTINCT select with a QUALIFY: a conjunct
|
|
27
|
+
`row_number() OVER (PARTITION BY k...) = 1` keeps at most one row per
|
|
28
|
+
partition (`_one_row_per_partition`), any other QUALIFY drops rows for
|
|
29
|
+
a reason not known. None for a select that aggregates without a GROUP
|
|
30
|
+
BY, which no projection stands for."""
|
|
31
|
+
if select.args.get("having") is not None or _only_star(items) or _aggregates(select):
|
|
32
|
+
return None
|
|
33
|
+
found = _row_number_equals_one(qualify.this)
|
|
34
|
+
window, others = found if found is not None else (None, [])
|
|
35
|
+
order = window.args.get("order") if window is not None else None
|
|
36
|
+
relation = self._one_row_per_partition(
|
|
37
|
+
lowered, select, items, None if window is None else window.args.get("partition_by") or (),
|
|
38
|
+
order.expressions if order else (), qualify, qualify.this, rest=exp.and_(*others) if others else None,
|
|
39
|
+
)
|
|
40
|
+
self._note_constant_partition(relation, qualify, select)
|
|
41
|
+
return relation
|
|
42
|
+
|
|
43
|
+
def _qualified(
|
|
44
|
+
self: IrParser, relation: ir.RelationExpr | None, select: exp.Select, items: list[Expr], *, grouped: bool,
|
|
45
|
+
) -> ir.RelationExpr | None:
|
|
46
|
+
"""`relation`, the groups (`grouped`) or distinct rows of `select`, after its
|
|
47
|
+
QUALIFY. Over groups, `row_number() OVER (PARTITION BY k...) = 1` with
|
|
48
|
+
every key a selected item keeps one row per partition. Any other
|
|
49
|
+
QUALIFY drops rows for a reason not known: an opaque Filter, which
|
|
50
|
+
keeps every fact of the rows and none that needs them all."""
|
|
51
|
+
qualify = select.args.get("qualify")
|
|
52
|
+
if relation is None or not isinstance(qualify, exp.Qualify):
|
|
53
|
+
return relation
|
|
54
|
+
found = _row_number_equals_one(qualify.this)
|
|
55
|
+
if found is not None and grouped: # Not over DISTINCT: its window sees the rows before it.
|
|
56
|
+
window, others = found
|
|
57
|
+
plan = self._partition_plan(window.args.get("partition_by") or (), items, grouped=True)
|
|
58
|
+
if plan is not None and all(isinstance(key, int) for key in plan) and len(relation.output_columns) == len(items):
|
|
59
|
+
origin = self._placed(qualify)
|
|
60
|
+
output_columns = _pass_output_columns(relation.output_columns, origin)
|
|
61
|
+
kept = ir.QualifyByPartition(
|
|
62
|
+
origin=origin, output_columns=output_columns, is_schema_complete=True, input=relation,
|
|
63
|
+
partition_outputs=tuple(output_columns[key] for key in plan if isinstance(key, int)),
|
|
64
|
+
)
|
|
65
|
+
return kept if not others else self._row_subset(kept, qualify, exp.and_(*others))
|
|
66
|
+
subset = self._row_subset(relation, qualify, qualify.this)
|
|
67
|
+
self._note_constant_partition(subset, qualify, select)
|
|
68
|
+
return subset
|
|
69
|
+
|
|
70
|
+
def _note_constant_partition(self: IrParser, relation: ir.RelationExpr, qualify: exp.Qualify, select: exp.Select) -> None:
|
|
71
|
+
"""Records `relation`, the select after its QUALIFY, as not modelled
|
|
72
|
+
when a window of the QUALIFY partitions by a constant: its one
|
|
73
|
+
partition is read as an unknown row subset (`_partition_plan`)."""
|
|
74
|
+
if _constant_partition_keys(qualify, select):
|
|
75
|
+
self._unsupported.append((relation, _CONSTANT_PARTITION))
|
|
76
|
+
|
|
77
|
+
def _row_subset(self: IrParser, relation: ir.RelationExpr, clause: Expr, dropping: Expr) -> ir.Filter:
|
|
78
|
+
"""`relation` after `clause` dropped rows of it for a reason not
|
|
79
|
+
known (`dropping`, as written): an opaque Filter, which keeps every
|
|
80
|
+
fact of each row or of any subset of them, and none that needs them all."""
|
|
81
|
+
origin = self._origin(clause)
|
|
82
|
+
return ir.Filter(
|
|
83
|
+
origin=origin, output_columns=_pass_output_columns(relation.output_columns, origin),
|
|
84
|
+
is_schema_complete=relation.is_schema_complete, input=relation,
|
|
85
|
+
predicate=ir.OpaqueExpression(origin=origin, description=dropping.sql(dialect=self.dialect)),
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
def _lower_distinct_on(
|
|
89
|
+
self: IrParser, lowered: _Lowered, select: exp.Select, items: list[Expr], on: Expr,
|
|
90
|
+
) -> ir.RelationExpr | None:
|
|
91
|
+
"""`DISTINCT ON (k...)` keeps one row per distinct `k...`, like
|
|
92
|
+
`QUALIFY ROW_NUMBER() OVER (PARTITION BY k...) = 1`. Its ORDER BY only
|
|
93
|
+
picks which row survives, and may name outputs, so it is not lowered.
|
|
94
|
+
A QUALIFY beside it drops rows first, and the one row per key is still
|
|
95
|
+
one: its Filter follows."""
|
|
96
|
+
if select.args.get("having") is not None or _only_star(items):
|
|
97
|
+
return None
|
|
98
|
+
keys = on.expressions if isinstance(on, exp.Tuple) else [on]
|
|
99
|
+
distinct = select.args["distinct"]
|
|
100
|
+
relation = self._one_row_per_partition(lowered, select, items, keys, (), distinct, distinct)
|
|
101
|
+
qualify = select.args.get("qualify")
|
|
102
|
+
return relation if qualify is None else self._row_subset(relation, qualify, qualify.this)
|
|
103
|
+
|
|
104
|
+
def _one_row_per_partition(
|
|
105
|
+
self: IrParser, lowered: _Lowered, select: exp.Select, items: list[Expr], partitions: Sequence[Expr] | None,
|
|
106
|
+
order: Sequence[exp.Ordered], clause: Expr, dropping: Expr, rest: Expr | None = None,
|
|
107
|
+
) -> ir.RelationExpr:
|
|
108
|
+
"""The projection of `items` over `lowered`, keeping one row per
|
|
109
|
+
distinct value of the key expressions `partitions` (none: one row in
|
|
110
|
+
all), as `clause` does. A key that is not an item is a hidden output
|
|
111
|
+
of the operation, which a Project then drops, as for a grouping key
|
|
112
|
+
(`_lower_aggregate`): a selected set of columns that determines every
|
|
113
|
+
key still has one row per value. `partitions` None, or a key that
|
|
114
|
+
cannot be read as one input expression (`_partition_plan`), is any
|
|
115
|
+
other clause: a row subset, `dropping` as written. `rest`, the other
|
|
116
|
+
conjuncts of a QUALIFY beside the one that keeps one row per
|
|
117
|
+
partition, drop rows after it (a QUALIFY evaluates its whole
|
|
118
|
+
predicate on the windowed rows): an opaque Filter follows."""
|
|
119
|
+
if select.args.get("where") is not None:
|
|
120
|
+
lowered = self._filter(lowered, select.args["where"])
|
|
121
|
+
origin = _placed(self._origin(select), clause)
|
|
122
|
+
plan = None if partitions is None else self._partition_plan(partitions, items)
|
|
123
|
+
if plan is None:
|
|
124
|
+
lowered, _ = self._join_scalar_subqueries(lowered, items)
|
|
125
|
+
return self._row_subset(self._project(lowered, items, origin), clause, dropping)
|
|
126
|
+
|
|
127
|
+
hidden = [
|
|
128
|
+
exp.alias_(key.copy(), f"{HIDDEN_PARTITION}{len(items) + index}")
|
|
129
|
+
for index, key in enumerate(key for key in plan if not isinstance(key, int))
|
|
130
|
+
]
|
|
131
|
+
output_columns = self._selected_output_columns([*items, *hidden], lowered)
|
|
132
|
+
hidden_outputs = iter(output_columns[len(items):])
|
|
133
|
+
partition_outputs = tuple(output_columns[key] if isinstance(key, int) else next(hidden_outputs) for key in plan)
|
|
134
|
+
ordering = tuple(
|
|
135
|
+
self._lower_expression(ordered.this, lowered.bindings, schema_complete=lowered.relation.is_schema_complete)
|
|
136
|
+
for ordered in order
|
|
137
|
+
)
|
|
138
|
+
qualified = ir.QualifyByPartition(
|
|
139
|
+
origin=origin, output_columns=output_columns, is_schema_complete=True, input=lowered.relation,
|
|
140
|
+
partition_outputs=partition_outputs, ordering=ordering,
|
|
141
|
+
)
|
|
142
|
+
kept: ir.RelationExpr = qualified if not hidden else ir.Project(
|
|
143
|
+
origin=origin, output_columns=_pass_output_columns(output_columns[:len(items)], origin),
|
|
144
|
+
is_schema_complete=True, input=qualified,
|
|
145
|
+
)
|
|
146
|
+
return kept if rest is None else self._row_subset(kept, clause, rest)
|
|
147
|
+
|
|
148
|
+
def _partition_plan(self: IrParser, partitions: Sequence[Expr], items: list[Expr], *, grouped: bool = False) -> list[int | Expr] | None:
|
|
149
|
+
"""Each partition key as the position of the select item it is written
|
|
150
|
+
as, or else the key itself; None when one cannot be read as one
|
|
151
|
+
expression of the input, so the partition it makes is not known. A key
|
|
152
|
+
is read as written over the input's columns, so it must be the same
|
|
153
|
+
value wherever it is evaluated (not a window, subquery, aggregate
|
|
154
|
+
over rows, literal or a call whose value varies) and no bare name in it may be a select
|
|
155
|
+
alias that is not that column (`_reads_alias`). A star's column
|
|
156
|
+
(`meta["star"]`) is written as its bare or qualified name."""
|
|
157
|
+
plan: list[int | Expr] = []
|
|
158
|
+
for key in partitions:
|
|
159
|
+
if (
|
|
160
|
+
key.find(exp.Window, exp.Query, exp.Subquery) is not None
|
|
161
|
+
or (not grouped and key.find(exp.AggFunc) is not None)
|
|
162
|
+
or not self._repeatable(key) or _reads_alias(key, items)
|
|
163
|
+
):
|
|
164
|
+
return None
|
|
165
|
+
item = _matching_output(key, items) or _star_output(key, items)
|
|
166
|
+
plan.append(key if item is None else next(index for index, other in enumerate(items) if other is item))
|
|
167
|
+
return plan
|
|
168
|
+
|
|
169
|
+
def _state_row_numbers(self: IrParser, items: list[Expr], columns: list[ir.OutputColumn]) -> None:
|
|
170
|
+
"""Knowledge of each select item that is exactly `row_number() OVER
|
|
171
|
+
(PARTITION BY k...)`: it is never NULL, and among the rows of the
|
|
172
|
+
select's input sharing `k...` (NULLs share one partition) its values
|
|
173
|
+
are distinct, so `(k..., rn)` is a Unique Set of the relation that
|
|
174
|
+
computes it, whatever filter or LIMIT follows. A filter that pins `rn`
|
|
175
|
+
(`rn = 1`) then leaves `k...` unique, by the same closure as any
|
|
176
|
+
constant.
|
|
177
|
+
|
|
178
|
+
Each key must be a selected item (`_partition_plan`: also refusing a
|
|
179
|
+
key that is not one value per row, or that may read an alias), so the
|
|
180
|
+
Unique Set is stated over output columns; any other is not stated, and
|
|
181
|
+
so is none beside a set-returning call, which some engines evaluate
|
|
182
|
+
after the window. RANK and DENSE_RANK repeat on ties, and a named
|
|
183
|
+
window may add keys the item does not write: neither is a row number
|
|
184
|
+
here. A row number inside an expression is no item of its own."""
|
|
185
|
+
if any(_set_returning_calls(item, self.dialect) for item in items):
|
|
186
|
+
return
|
|
187
|
+
for item, column in zip(items, columns):
|
|
188
|
+
window = _row_number_window(_unaliased(item))
|
|
189
|
+
if window is None or window.args.get("alias") is not None:
|
|
190
|
+
continue
|
|
191
|
+
plan = self._partition_plan(window.args.get("partition_by") or (), items)
|
|
192
|
+
if plan is None or not all(isinstance(key, int) for key in plan):
|
|
193
|
+
continue
|
|
194
|
+
keys = {columns[key] for key in plan if isinstance(key, int)}
|
|
195
|
+
self._knowledge.append(NonNullColumn(column=column))
|
|
196
|
+
self._knowledge.append(UniqueSet(columns=frozenset({*keys, column})))
|
|
197
|
+
# What it is is modelled: an UNKNOWN proof is not for lack of window support.
|
|
198
|
+
self._unsupported = [(node, construct) for node, construct in self._unsupported if node is not column.scalar_expr]
|
|
199
|
+
|
|
200
|
+
# A partition key not selected, kept as a hidden output of its QualifyByPartition: no SQL name can match it.
|
|
201
|
+
HIDDEN_PARTITION = "\0partition"
|
|
202
|
+
_CONSTANT_PARTITION = "a constant PARTITION BY key"
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _reads_alias(key: Expr, items: list[Expr]) -> bool:
|
|
206
|
+
"""Whether a bare name in `key` may read a select alias rather than the
|
|
207
|
+
input's column: some item is aliased that name and is not that column."""
|
|
208
|
+
for column in key.find_all(exp.Column):
|
|
209
|
+
if column.table:
|
|
210
|
+
continue
|
|
211
|
+
for item in items:
|
|
212
|
+
expression = _unaliased(item)
|
|
213
|
+
if item.alias_or_name.lower() == column.name.lower() and not (
|
|
214
|
+
isinstance(expression, exp.Column) and expression.name.lower() == column.name.lower()
|
|
215
|
+
):
|
|
216
|
+
return True
|
|
217
|
+
return False
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _aggregates(select: exp.Select) -> bool:
|
|
221
|
+
"""Whether `select` computes an aggregate outside any window of its own."""
|
|
222
|
+
return any(
|
|
223
|
+
node.find_ancestor(exp.Window, exp.Select) is select
|
|
224
|
+
for item in select.expressions for node in item.find_all(exp.AggFunc)
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _star_output(partition: Expr, items: list[Expr]) -> Expr | None:
|
|
229
|
+
"""The item a star expanded to that the column `partition` reads, if one."""
|
|
230
|
+
if not isinstance(partition, exp.Column) or isinstance(partition.this, exp.Star):
|
|
231
|
+
return None
|
|
232
|
+
matches = [
|
|
233
|
+
item for item in items
|
|
234
|
+
if isinstance(column := item.this if isinstance(item, exp.Alias) else item, exp.Column) and column.meta.get("star")
|
|
235
|
+
and column.name.lower() == partition.name.lower() and (not partition.table or column.table.lower() == partition.table.lower())
|
|
236
|
+
and (not _schema_path(partition) or _schema_path(column) == _schema_path(partition))
|
|
237
|
+
]
|
|
238
|
+
return matches[0] if len(matches) == 1 else None
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _row_number_equals_one(predicate: Expr) -> tuple[exp.Window, list[Expr]] | None:
|
|
242
|
+
"""The first conjunct of a QUALIFY's `predicate` that is `row_number() OVER
|
|
243
|
+
(...) = 1`, with the other conjuncts. Every conjunct is evaluated on the
|
|
244
|
+
windowed rows and the other conjuncts only drop rows, so the rows kept are
|
|
245
|
+
at most the one per partition that conjunct leaves. A second such conjunct
|
|
246
|
+
over another partition is one of the others: it too bounds the rows, but
|
|
247
|
+
only the first is read as a Unique Set."""
|
|
248
|
+
conjuncts = _filter_conjuncts(predicate)
|
|
249
|
+
for index, conjunct in enumerate(conjuncts):
|
|
250
|
+
if (window := _row_number_is_one(conjunct)) is not None:
|
|
251
|
+
return window, conjuncts[:index] + conjuncts[index + 1:]
|
|
252
|
+
return None
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _row_number_is_one(predicate: Expr) -> exp.Window | None:
|
|
256
|
+
if not isinstance(predicate, exp.EQ):
|
|
257
|
+
return None
|
|
258
|
+
left, right = predicate.this, predicate.expression
|
|
259
|
+
window = left if isinstance(left, exp.Window) else right if isinstance(right, exp.Window) else None
|
|
260
|
+
literal = right if window is left else left
|
|
261
|
+
if window is None or not isinstance(window.this, exp.RowNumber) or window.args.get("alias") is not None:
|
|
262
|
+
return None # A named window (`OVER w`, `OVER (w ...)`) may partition.
|
|
263
|
+
if not isinstance(literal, exp.Literal) or literal.is_string or literal.this != "1":
|
|
264
|
+
return None
|
|
265
|
+
return window
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _constant_partition_keys(clause: Expr, select: exp.Select) -> list[Expr]:
|
|
269
|
+
"""The literals among the PARTITION BY keys of the windows in `clause`
|
|
270
|
+
that belong to `select` (not those of a subquery in it): a constant is
|
|
271
|
+
one partition."""
|
|
272
|
+
return [
|
|
273
|
+
key for window in clause.find_all(exp.Window) if window.find_ancestor(exp.Select) is select
|
|
274
|
+
for key in window.args.get("partition_by") or () if isinstance(key.unnest(), exp.Literal | exp.Boolean | exp.Null)
|
|
275
|
+
]
|
sqlassert/ir/model.py
CHANGED
|
@@ -21,13 +21,19 @@ type SetOperator = Literal["union", "intersect", "except"]
|
|
|
21
21
|
|
|
22
22
|
@dataclass_transform(eq_default=False, frozen_default=True, kw_only_default=True)
|
|
23
23
|
class NodeMeta(type):
|
|
24
|
-
"""Turn every Node subclass into the same kind of semantic value.
|
|
24
|
+
"""Turn every Node subclass into the same kind of semantic value.
|
|
25
|
+
|
|
26
|
+
A node is the occurrence it stands for, so it equals only itself: two
|
|
27
|
+
Aliases of one table, or two Output Columns named alike, are different
|
|
28
|
+
nodes. A metaclass with `value_equality` makes its classes compare by
|
|
29
|
+
class and fields instead (ADR 0002)."""
|
|
25
30
|
|
|
26
31
|
_subclasses: list
|
|
32
|
+
value_equality = False
|
|
27
33
|
|
|
28
34
|
def __new__(metaclass, name, bases, namespace, *, abstract: bool = False):
|
|
29
35
|
node_type = super().__new__(metaclass, name, bases, namespace)
|
|
30
|
-
node_type = dataclass(frozen=True, eq=
|
|
36
|
+
node_type = dataclass(frozen=True, eq=metaclass.value_equality, kw_only=True)(node_type)
|
|
31
37
|
node_type.__ir_abstract__ = abstract
|
|
32
38
|
node_type._subclasses = []
|
|
33
39
|
if not abstract:
|
|
@@ -61,9 +67,13 @@ class ScalarExpr(Node, abstract=True):
|
|
|
61
67
|
class OpaqueExpression(ScalarExpr):
|
|
62
68
|
"""An expression nothing is known about: not even which columns its value
|
|
63
69
|
depends on. A user-defined or volatile function, an aggregate or window,
|
|
64
|
-
a subquery, or a column that does not resolve.
|
|
70
|
+
a subquery, or a column that does not resolve.
|
|
71
|
+
|
|
72
|
+
`typing` is how its values compare, where the type is known though the
|
|
73
|
+
value is not: a `row_number()` window is an integer."""
|
|
65
74
|
|
|
66
75
|
description: str
|
|
76
|
+
typing: ValueTyping | None = None
|
|
67
77
|
|
|
68
78
|
|
|
69
79
|
@dataclass(frozen=True)
|
|
@@ -79,8 +89,8 @@ class Builtin:
|
|
|
79
89
|
|
|
80
90
|
An `injective` one is one-to-one in its single argument that is not an
|
|
81
91
|
integer or decimal literal, when that argument is an integer or decimal:
|
|
82
|
-
`a + 1`, `10 - a`, `-a`.
|
|
83
|
-
|
|
92
|
+
`a + 1`, `10 - a`, `-a`. Values are assumed to stay in range, so how the
|
|
93
|
+
dialect overflows does not matter (ADR 0007).
|
|
84
94
|
|
|
85
95
|
A `rejecting` parameter makes the value never TRUE (FALSE or NULL)
|
|
86
96
|
whenever its argument is NULL, though perhaps not NULL: `x > ANY (...)`
|
|
@@ -146,12 +156,63 @@ class BuiltinVariadic(Builtin):
|
|
|
146
156
|
return None if self.total is None else self.total + (self.repeated_total,) * (count - len(self.total))
|
|
147
157
|
|
|
148
158
|
|
|
159
|
+
@dataclass(frozen=True)
|
|
160
|
+
class ValueTyping:
|
|
161
|
+
"""How the values of a typed expression compare, as a column declared with
|
|
162
|
+
that type would: its `comparison_type` (the type's SQL name, which two
|
|
163
|
+
values of one type share), whether it is `binary_text` (text compared by
|
|
164
|
+
identity: VARCHAR or TEXT in a dialect whose default collation is binary,
|
|
165
|
+
`DialectSemantics.text_is_binary`), whether `identity_comparison` holds
|
|
166
|
+
(equal values are identical: an integer, decimal, boolean, date, time,
|
|
167
|
+
timestamp, UUID or binary text; not a float, `-0.0 = 0.0`, an interval, or
|
|
168
|
+
text under a case-insensitive collation), whether it is `exact_numeric` (an
|
|
169
|
+
integer or decimal), whether it is `floating` (REAL, FLOAT, DOUBLE), and
|
|
170
|
+
its `integer` width rank when it is a signed integer type (TINYINT 0, up;
|
|
171
|
+
unsigned types are none), whether it is `text` (any character type, in any
|
|
172
|
+
collation the dialect ships as default), and whether it is `temporal` (a
|
|
173
|
+
date, time or timestamp), and the types it `casts_to` when compared with
|
|
174
|
+
them, keeping different values different (`DialectSemantics.injective_casts`:
|
|
175
|
+
a DATE becomes its midnight beside a TIMESTAMP). An expression whose type
|
|
176
|
+
is not known has no ValueTyping."""
|
|
177
|
+
|
|
178
|
+
comparison_type: str
|
|
179
|
+
binary_text: bool
|
|
180
|
+
identity_comparison: bool
|
|
181
|
+
exact_numeric: bool
|
|
182
|
+
floating: bool = False
|
|
183
|
+
integer: int | None = None
|
|
184
|
+
text: bool = False
|
|
185
|
+
temporal: bool = False
|
|
186
|
+
casts_to: frozenset[str] = frozenset()
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
@dataclass(frozen=True)
|
|
190
|
+
class ArgumentTyping:
|
|
191
|
+
"""The type of a call that depends on one argument's type
|
|
192
|
+
(`DialectSemantics.argument_result_types`): `results` by the argument's
|
|
193
|
+
`comparison_type`, and, when `keeps`, any other type is the argument's
|
|
194
|
+
own. A type not listed, or an argument of unknown type, leaves the call
|
|
195
|
+
untyped."""
|
|
196
|
+
|
|
197
|
+
argument: int
|
|
198
|
+
results: tuple[tuple[str, ValueTyping], ...]
|
|
199
|
+
keeps: bool = False
|
|
200
|
+
|
|
201
|
+
|
|
149
202
|
class Call(ScalarExpr):
|
|
150
|
-
"""A Builtin applied to arguments: `n + 1`, `n > 0`, `CAST(n AS BIGINT)`, `NOT p`.
|
|
203
|
+
"""A Builtin applied to arguments: `n + 1`, `n > 0`, `CAST(n AS BIGINT)`, `NOT p`.
|
|
204
|
+
|
|
205
|
+
`typing` is how its values compare, where the type is known from the call
|
|
206
|
+
itself: a CAST's (`IrParser._cast_typing`) or a function the dialect gives
|
|
207
|
+
a fixed result type (`DialectSemantics.result_types`). Arithmetic and
|
|
208
|
+
NULLIF are typed by their operands (`rules/value_typing.py`), and a
|
|
209
|
+
function whose type follows an argument's by `typed_by`."""
|
|
151
210
|
|
|
152
211
|
function: Builtin
|
|
153
212
|
arguments: tuple[ScalarExpr, ...]
|
|
154
213
|
description: str
|
|
214
|
+
typing: ValueTyping | None = None
|
|
215
|
+
typed_by: ArgumentTyping | None = None
|
|
155
216
|
|
|
156
217
|
def __post_init__(self) -> None:
|
|
157
218
|
assert self.function.accepts(len(self.arguments)), f"{self.function.name} takes no {len(self.arguments)} arguments"
|
|
@@ -190,10 +251,19 @@ class Call(ScalarExpr):
|
|
|
190
251
|
class OpaquePureFunction(ScalarExpr):
|
|
191
252
|
"""A built-in function or operator whose behaviour is not modelled: a pure
|
|
192
253
|
function of its arguments, and nothing else is known about it. Searched
|
|
193
|
-
CASE, and `concat`, `||` or `greatest` where the dialect's is not modelled.
|
|
254
|
+
CASE, and `concat`, `||` or `greatest` where the dialect's is not modelled.
|
|
255
|
+
|
|
256
|
+
`typing` is how its values compare, where the dialect fixes the result
|
|
257
|
+
type of the function (`DialectSemantics.result_types`). `results` are the
|
|
258
|
+
positions of the arguments it returns one of, or NULL, when it only
|
|
259
|
+
selects among them (a searched CASE, IF): its type is the type they share.
|
|
260
|
+
`typed_by`: its type follows an argument's (`ArgumentTyping`)."""
|
|
194
261
|
|
|
195
262
|
arguments: tuple[ScalarExpr, ...]
|
|
196
263
|
description: str
|
|
264
|
+
typing: ValueTyping | None = None
|
|
265
|
+
results: tuple[int, ...] | None = None
|
|
266
|
+
typed_by: ArgumentTyping | None = None
|
|
197
267
|
|
|
198
268
|
|
|
199
269
|
class Count(ScalarExpr):
|
|
@@ -232,9 +302,14 @@ class LiteralValue:
|
|
|
232
302
|
|
|
233
303
|
|
|
234
304
|
class Constant(ScalarExpr):
|
|
235
|
-
"""A non-null literal; `value` is None while its type is not modelled.
|
|
305
|
+
"""A non-null literal; `value` is None while its type is not modelled.
|
|
306
|
+
|
|
307
|
+
`typing` is how it compares, from the dialect's type for a literal of its
|
|
308
|
+
kind (`IrParser._literal_typing`); None where that is not known: a decimal
|
|
309
|
+
or exponent literal in a dialect whose type for it is not claimed."""
|
|
236
310
|
|
|
237
311
|
value: LiteralValue | None = None
|
|
312
|
+
typing: ValueTyping | None = None
|
|
238
313
|
|
|
239
314
|
|
|
240
315
|
class NullLiteral(ScalarExpr):
|
|
@@ -496,26 +571,15 @@ type AnyScalar = (
|
|
|
496
571
|
class OutputColumn(Node):
|
|
497
572
|
"""One named output of one relational stage and the expression producing it.
|
|
498
573
|
|
|
499
|
-
`
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
`identity_comparison` marks a table column whose equal values are
|
|
505
|
-
identical: an integer, decimal, boolean, date, time, timestamp or UUID
|
|
506
|
-
type, or binary text. Not a float (`-0.0 = 0.0`), an interval, or text
|
|
507
|
-
under a case-insensitive default collation (MySQL's).
|
|
508
|
-
|
|
509
|
-
`exact_numeric` marks a table column declared as an integer or decimal.
|
|
574
|
+
`typing` is how the values of a column declared with a type compare: a
|
|
575
|
+
table column, or a VALUES column (`IrParser._declared_typing`). None for a
|
|
576
|
+
column whose type is not declared; one that computes or passes on a value
|
|
577
|
+
has the type of its expression (`rules/value_typing.py`).
|
|
510
578
|
"""
|
|
511
579
|
|
|
512
580
|
name: str
|
|
513
581
|
scalar_expr: ScalarExpr
|
|
514
|
-
|
|
515
|
-
# Declared SQL type where equality compares values without casts.
|
|
516
|
-
comparison_type: str | None = None
|
|
517
|
-
identity_comparison: bool = False
|
|
518
|
-
exact_numeric: bool = False
|
|
582
|
+
typing: ValueTyping | None = None
|
|
519
583
|
|
|
520
584
|
def get_relation(self, program: Program) -> RelationExpr:
|
|
521
585
|
"""The one relation in ``program`` whose output includes this column."""
|
|
@@ -549,10 +613,6 @@ class NamedRelation(RelationExpr):
|
|
|
549
613
|
role: RelationRole
|
|
550
614
|
body: RelationExpr | None = None
|
|
551
615
|
|
|
552
|
-
@property
|
|
553
|
-
def report_name(self) -> str:
|
|
554
|
-
return f"CTE_{self.name}" if self.role is RelationRole.CTE else self.name
|
|
555
|
-
|
|
556
616
|
|
|
557
617
|
class Alias(RelationExpr):
|
|
558
618
|
"""One occurrence of a relation expression in a query scope."""
|
|
@@ -577,6 +637,12 @@ class Join(RelationExpr):
|
|
|
577
637
|
# subquery's body, and each left row matches at most one right row, or
|
|
578
638
|
# the query fails (more than one row is a runtime error).
|
|
579
639
|
scalar_subquery: bool = False
|
|
640
|
+
# An INNER, LEFT or CROSS join whose right input is a table function or
|
|
641
|
+
# UNNEST with an argument that reads a column of the left input: it is
|
|
642
|
+
# evaluated once per left row, so each right row is produced by exactly
|
|
643
|
+
# one left row and none is repeated (a left row may repeat, once per row
|
|
644
|
+
# the function returns for it).
|
|
645
|
+
lateral: bool = False
|
|
580
646
|
|
|
581
647
|
@property
|
|
582
648
|
def conjuncts(self) -> tuple[ScalarExpr, ...]:
|
|
@@ -627,26 +693,37 @@ class Distinct(RelationExpr):
|
|
|
627
693
|
|
|
628
694
|
class SetOperation(RelationExpr):
|
|
629
695
|
"""UNION, INTERSECT, or EXCEPT. Output columns refer to the left input;
|
|
630
|
-
`arms` pairs each with the right input's column at its position.
|
|
696
|
+
`arms` pairs each with the right input's column at its position. A
|
|
697
|
+
`UNION BY NAME` is lowered to that form (convert's `_align_by_name`).
|
|
698
|
+
|
|
699
|
+
`recursive` is the body of a recursive CTE or view: the left input is the
|
|
700
|
+
base case and the right one reads the relation itself. The engine fixes
|
|
701
|
+
each output column's type from the base case, whatever the recursive arm
|
|
702
|
+
computes (it casts the arm, or rejects a mismatch), so the type of a
|
|
703
|
+
column is its base case column's. Typing only: values, NULLs, keys and
|
|
704
|
+
domains still come from both inputs."""
|
|
631
705
|
|
|
632
706
|
operator: SetOperator
|
|
633
707
|
left: RelationExpr
|
|
634
708
|
right: RelationExpr
|
|
635
709
|
distinct: bool = True
|
|
636
|
-
|
|
710
|
+
unpaired: bool = False
|
|
711
|
+
recursive: bool = False
|
|
637
712
|
|
|
638
713
|
def arms(self, column: OutputColumn) -> tuple[OutputColumn, OutputColumn] | None:
|
|
639
714
|
"""The left and right input columns `column` is computed from, or None
|
|
640
|
-
when the inputs pair by
|
|
641
|
-
|
|
642
|
-
|
|
715
|
+
when the inputs do not pair by position: `unpaired` (a form of `BY
|
|
716
|
+
NAME` the IR does not model) or a different width (an input whose
|
|
717
|
+
columns are unknown)."""
|
|
718
|
+
if self.unpaired or len(self.left.output_columns) != len(self.right.output_columns):
|
|
643
719
|
return None
|
|
644
720
|
position = self.output_columns.index(column)
|
|
645
721
|
return self.left.output_columns[position], self.right.output_columns[position]
|
|
646
722
|
|
|
647
723
|
|
|
648
724
|
class QualifyByPartition(RelationExpr):
|
|
649
|
-
"""One row per partition: ``QUALIFY row_number() OVER (PARTITION BY ...) = 1`` or ``DISTINCT ON (...)``.
|
|
725
|
+
"""One row per partition: ``QUALIFY row_number() OVER (PARTITION BY ...) = 1`` or ``DISTINCT ON (...)``.
|
|
726
|
+
A partition key is an output column, possibly hidden (a Project over this drops it); no key is one row in all."""
|
|
650
727
|
|
|
651
728
|
input: RelationExpr
|
|
652
729
|
partition_outputs: tuple[OutputColumn, ...]
|
|
@@ -658,14 +735,26 @@ class OpaqueRelation(RelationExpr):
|
|
|
658
735
|
|
|
659
736
|
|
|
660
737
|
class RecursiveRelation(OpaqueRelation):
|
|
661
|
-
"""An explicit unsupported recursive reference, represented without a cycle.
|
|
738
|
+
"""An explicit unsupported recursive reference, represented without a cycle.
|
|
739
|
+
|
|
740
|
+
Its rows and values are unknown, but the engine fixes each column's type
|
|
741
|
+
from the base case, so `typed_by` is, per output column, the base case's
|
|
742
|
+
column whose type it takes (None when it has none: an untyped base column
|
|
743
|
+
is read through it). Typing only: no value, NULL, key, domain or lineage
|
|
744
|
+
is shared, since the recursive rows differ from the base case's."""
|
|
662
745
|
|
|
663
746
|
relation_name: str
|
|
747
|
+
typed_by: tuple[OutputColumn | None, ...] = ()
|
|
748
|
+
|
|
749
|
+
|
|
750
|
+
class ValuesList(OpaqueRelation):
|
|
751
|
+
"""`(VALUES (...), ...) AS t (a, ...)`: rows of written values, its
|
|
752
|
+
columns stated as Knowledge. No column has a declared type."""
|
|
664
753
|
|
|
665
754
|
|
|
666
755
|
type AnyRelation = (
|
|
667
756
|
NamedRelation | Alias | Join | Filter | Project | Limit | Aggregate | Distinct | SetOperation
|
|
668
|
-
| QualifyByPartition | OpaqueRelation | RecursiveRelation
|
|
757
|
+
| QualifyByPartition | OpaqueRelation | RecursiveRelation | ValuesList
|
|
669
758
|
)
|
|
670
759
|
|
|
671
760
|
|
|
@@ -684,17 +773,6 @@ class Program:
|
|
|
684
773
|
# Every JOIN, Select Expression, and simple CASE a marker can attach to, with
|
|
685
774
|
# the Join, the relation the Select produces, or the lowered CASE.
|
|
686
775
|
attachment_sites: tuple[tuple[AttachmentSite, RelationExpr | SimpleCase], ...] = ()
|
|
687
|
-
# Each scalar subquery lowered as a join, with where its Select is written.
|
|
688
|
-
scalar_subqueries: tuple[tuple[AttachmentSite, Join], ...] = ()
|
|
689
|
-
# Each Select Expression's ORDER BY keys, at its trailing site, as columns
|
|
690
|
-
# of the stage it sorts: the input of a Project, else the Select's own
|
|
691
|
-
# relation. Empty with no ORDER BY; None when a key is an expression or a
|
|
692
|
-
# name that does not resolve to one column, and for DISTINCT ON, whose
|
|
693
|
-
# ORDER BY picks the rows it keeps.
|
|
694
|
-
sort_keys: tuple[tuple[AttachmentSite, tuple[OutputColumn, ...] | None], ...] = ()
|
|
695
|
-
# Each INTERSECT and EXCEPT, sited where its keyword follows its left
|
|
696
|
-
# input's last Select (no marker attaches there).
|
|
697
|
-
set_operations: tuple[tuple[AttachmentSite, SetOperation], ...] = ()
|
|
698
776
|
# Each node standing for a construct sqlassert does not support yet (an
|
|
699
777
|
# opaque relation or value), with what it is: an assertion whose proof
|
|
700
778
|
# reaches one says so when it stays UNKNOWN.
|
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/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
|
|