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,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
|
+
]
|