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,428 @@
|
|
|
1
|
+
"""Symbols, bindings, and the syntax helpers more than one part of lowering reads."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterable
|
|
6
|
+
from dataclasses import dataclass, field, replace
|
|
7
|
+
from typing import Literal, TypeGuard
|
|
8
|
+
|
|
9
|
+
from sqlglot import Expr, exp
|
|
10
|
+
|
|
11
|
+
from sqlassert import ir
|
|
12
|
+
from sqlassert.declared_types import TEXT_TYPES as _TEXT_TYPES
|
|
13
|
+
from sqlassert.ir.names import may_be_renamed
|
|
14
|
+
from sqlassert.provenance import Origin
|
|
15
|
+
from sqlassert.sql_parse import ColumnMarker, marker_position, written_at
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(eq=False)
|
|
19
|
+
class _Symbol:
|
|
20
|
+
name: str
|
|
21
|
+
role: ir.RelationRole
|
|
22
|
+
origin: Origin
|
|
23
|
+
body: exp.Query | None = None
|
|
24
|
+
statement: exp.Create | None = None
|
|
25
|
+
column_aliases: tuple[str, ...] = ()
|
|
26
|
+
required_columns: set[str] = field(default_factory=set)
|
|
27
|
+
# Table-level constraints added after CREATE TABLE (ALTER TABLE, CREATE
|
|
28
|
+
# UNIQUE INDEX), shaped like the CREATE TABLE's own, and columns set NOT NULL.
|
|
29
|
+
constraints: list[Expr] = field(default_factory=list)
|
|
30
|
+
not_null: set[str] = field(default_factory=set)
|
|
31
|
+
# Where the SQL first reads it: an undeclared table's warning points there.
|
|
32
|
+
first_line: int | None = None
|
|
33
|
+
# Each unique index with an expression key part: its parts and statement.
|
|
34
|
+
expression_keys: list[tuple[list[Expr], exp.Create]] = field(default_factory=list)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(frozen=True)
|
|
38
|
+
class _Binding:
|
|
39
|
+
qualifier: str
|
|
40
|
+
# None for a repeat of a derived table's name: no reference reaches it, a star does.
|
|
41
|
+
name: str | None
|
|
42
|
+
column: ir.OutputColumn
|
|
43
|
+
# The schema (and catalog) of an unaliased table, as `s1` in `s1.t.k`.
|
|
44
|
+
schema: str = ""
|
|
45
|
+
# Hidden from unqualified names: a USING column's input sides, which an
|
|
46
|
+
# unqualified name reads merged (`_merge_using`).
|
|
47
|
+
shadowed: bool = False
|
|
48
|
+
# The lower-case names the derived table this column is of repeats
|
|
49
|
+
# (`ir/names.py`): a name `<repeated>_<digits>` may be one the engine gave
|
|
50
|
+
# a repeat, so no reference binds it.
|
|
51
|
+
repeated: frozenset[str] = frozenset()
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass(frozen=True)
|
|
55
|
+
class _MarkerReference:
|
|
56
|
+
"""A Foreign Key marker whose referencing columns are lowered, awaiting its referenced relation."""
|
|
57
|
+
|
|
58
|
+
marker: ColumnMarker
|
|
59
|
+
kind: Literal["foreign-key", "declared-foreign-key"]
|
|
60
|
+
origin: Origin
|
|
61
|
+
columns: tuple[ir.OutputColumn, ...]
|
|
62
|
+
target: _Symbol
|
|
63
|
+
position: int
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass(frozen=True)
|
|
67
|
+
class _ConstraintReference:
|
|
68
|
+
"""A `REFERENCES` constraint of a declared table onto a relation the program reaches."""
|
|
69
|
+
|
|
70
|
+
table: _Symbol
|
|
71
|
+
columns: tuple[str, ...]
|
|
72
|
+
target: _Symbol
|
|
73
|
+
target_columns: tuple[str, ...] | None
|
|
74
|
+
origin: Origin
|
|
75
|
+
# The `REFERENCES` or `FOREIGN KEY` constraint itself.
|
|
76
|
+
node: Expr
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass(frozen=True)
|
|
80
|
+
class _Lowered:
|
|
81
|
+
relation: ir.RelationExpr
|
|
82
|
+
bindings: tuple[_Binding, ...]
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _placed(origin: Origin, node: Expr | None) -> Origin:
|
|
86
|
+
"""`origin` with the span where `node` is written, when it has one."""
|
|
87
|
+
span = written_at(node) if node is not None else None
|
|
88
|
+
return origin if span is None else replace(origin, line=span.line, span=span)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _pass_output_columns(inputs: tuple[ir.OutputColumn, ...], origin: Origin) -> tuple[ir.OutputColumn, ...]:
|
|
92
|
+
return tuple(
|
|
93
|
+
ir.OutputColumn(origin=origin, name=column.name, scalar_expr=ir.ColumnRef(origin=origin, column=column))
|
|
94
|
+
for column in inputs
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _source_line(node: Expr) -> int | None:
|
|
99
|
+
"""The first source line of `node`, from the positions SQLGlot keeps on its tokens."""
|
|
100
|
+
lines = [descendant.meta["line"] for descendant in node.walk() if "line" in descendant.meta]
|
|
101
|
+
return min(lines, default=None)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _subquery_conjunct(conjunct: Expr) -> tuple[ir.JoinKind, exp.Select, Expr | None] | None:
|
|
105
|
+
"""A WHERE conjunct lowered as a filtering join: its kind, the subquery,
|
|
106
|
+
and the IN operand (None for EXISTS)."""
|
|
107
|
+
match conjunct:
|
|
108
|
+
case exp.Exists(this=exp.Select() as select):
|
|
109
|
+
return "semi", select, None
|
|
110
|
+
case exp.Not(this=exp.Exists(this=exp.Select() as select)):
|
|
111
|
+
return "anti", select, None
|
|
112
|
+
case exp.In(this=operand, args={"query": exp.Subquery() as subquery}) if not isinstance(operand, exp.Tuple):
|
|
113
|
+
body = _unwrap_query(subquery)
|
|
114
|
+
return ("semi", body, operand) if isinstance(body, exp.Select) else None
|
|
115
|
+
case _:
|
|
116
|
+
return None
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _and(parts: tuple[ir.ScalarExpr, ...], origin: Origin) -> ir.ScalarExpr | None:
|
|
120
|
+
"""The AND of `parts`: None for none, the part itself for one."""
|
|
121
|
+
match parts:
|
|
122
|
+
case ():
|
|
123
|
+
return None
|
|
124
|
+
case (part,):
|
|
125
|
+
return part
|
|
126
|
+
case _:
|
|
127
|
+
return ir.And(origin=origin, parts=parts)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _conjuncts(predicate: Expr) -> list[Expr]:
|
|
131
|
+
"""The operands of a predicate's top-level ANDs, parentheses removed."""
|
|
132
|
+
while isinstance(predicate, exp.Paren):
|
|
133
|
+
predicate = predicate.this
|
|
134
|
+
if isinstance(predicate, exp.And):
|
|
135
|
+
return _conjuncts(predicate.this) + _conjuncts(predicate.expression)
|
|
136
|
+
return [predicate]
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _filter_conjuncts(predicate: Expr) -> list[Expr]:
|
|
140
|
+
"""The conjuncts of a WHERE, ON or HAVING condition, each `p IS TRUE` as
|
|
141
|
+
`p`'s own: a filter keeps only the rows where its condition is TRUE, where
|
|
142
|
+
`p IS TRUE` is TRUE exactly when `p` is. Not in a value, where `p IS TRUE`
|
|
143
|
+
is FALSE, not NULL, on a NULL `p`."""
|
|
144
|
+
found: list[Expr] = []
|
|
145
|
+
for conjunct in _conjuncts(predicate):
|
|
146
|
+
if isinstance(conjunct, exp.Is) and isinstance(conjunct.expression, exp.Boolean) and conjunct.expression.this:
|
|
147
|
+
found.extend(_filter_conjuncts(conjunct.this))
|
|
148
|
+
else:
|
|
149
|
+
found.append(conjunct)
|
|
150
|
+
return found
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _direct_sources(select: exp.Select) -> list[Expr]:
|
|
154
|
+
"""The sources of `select`'s FROM, those of a parenthesized join in place of it."""
|
|
155
|
+
source = _from_source(select)
|
|
156
|
+
return _flattened(([] if source is None else [source]) + [join.this for join in select.args.get("joins") or ()])
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _flattened(sources: list[Expr]) -> list[Expr]:
|
|
160
|
+
flat: list[Expr] = []
|
|
161
|
+
for source in sources:
|
|
162
|
+
nested = _nested_join(source)
|
|
163
|
+
flat.extend([source] if nested is None else _flattened([nested[0], *(join.this for join in nested[1])]))
|
|
164
|
+
return flat
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _all_joins(select: exp.Select) -> list[exp.Join]:
|
|
168
|
+
"""The joins of `select`'s FROM, those inside a parenthesized join included."""
|
|
169
|
+
return [join for joins, _ in _join_levels(select) for join in joins]
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _join_levels(select: exp.Select) -> list[tuple[list[exp.Join], list[Expr]]]:
|
|
173
|
+
"""The joins of `select`'s FROM and of each parenthesized join in it, each
|
|
174
|
+
list with the sources it joins, flattened: a USING column is one of theirs."""
|
|
175
|
+
source = _from_source(select)
|
|
176
|
+
levels: list[tuple[list[exp.Join], list[Expr]]] = [(list(select.args.get("joins") or ()), _direct_sources(select))]
|
|
177
|
+
pending: list[Expr | None] = [source, *(join.this for join in select.args.get("joins") or ())]
|
|
178
|
+
while pending:
|
|
179
|
+
source = pending.pop()
|
|
180
|
+
nested = _nested_join(source) or _aliased_join(source)
|
|
181
|
+
if nested is not None:
|
|
182
|
+
first, joins = nested
|
|
183
|
+
levels.append((joins, _flattened([first, *(join.this for join in joins)])))
|
|
184
|
+
pending.extend([first, *(join.this for join in joins)])
|
|
185
|
+
return levels
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _nested_join(source: Expr | None) -> tuple[Expr, list[exp.Join]] | None:
|
|
189
|
+
"""A parenthesized join, `(a JOIN b ON ...)` without an alias: its first
|
|
190
|
+
source, which SQLGlot hangs the joins on, and those joins. Its columns keep
|
|
191
|
+
the names and qualifiers of its sources. Not with an alias, which DuckDB
|
|
192
|
+
reads as a subquery renaming repeated names (`x`, `x_1`) and other dialects
|
|
193
|
+
as names that may be ambiguous."""
|
|
194
|
+
if not isinstance(source, exp.Subquery) or any(value for key, value in source.args.items() if key not in {"this", "joins"}):
|
|
195
|
+
return None
|
|
196
|
+
first = source.this
|
|
197
|
+
if not isinstance(first, exp.Table | exp.Subquery) or not first.args.get("joins"):
|
|
198
|
+
return None
|
|
199
|
+
return first, list(first.args["joins"])
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _aliased_join(source: Expr | None) -> tuple[Expr, list[exp.Join]] | None:
|
|
203
|
+
"""A parenthesized join with an alias, `(a JOIN b ON ...) AS x`, perhaps
|
|
204
|
+
naming its columns: its first source and its joins, as `_nested_join`."""
|
|
205
|
+
if not isinstance(source, exp.Subquery) or not source.alias or any(
|
|
206
|
+
value for key, value in source.args.items() if key not in {"this", "alias"}
|
|
207
|
+
):
|
|
208
|
+
return None
|
|
209
|
+
first = source.this
|
|
210
|
+
if not isinstance(first, exp.Table | exp.Subquery) or not first.args.get("joins"):
|
|
211
|
+
return None
|
|
212
|
+
return first, list(first.args["joins"])
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _missing(relation: ir.RelationExpr, names: Iterable[str]) -> list[str]:
|
|
216
|
+
known = {column.name.lower() for column in relation.output_columns}
|
|
217
|
+
return [name for name in names if name.lower() not in known]
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _is_named_table(source: Expr) -> TypeGuard[exp.Table]:
|
|
221
|
+
"""A FROM source naming a table, view or CTE. SQLGlot parses a
|
|
222
|
+
table-valued function (`json_each(x)`, `read_parquet('f')`,
|
|
223
|
+
`generate_series(1, 3)`) as a Table whose `this` is the call: its rows
|
|
224
|
+
are opaque, like an UNNEST, and it names no relation."""
|
|
225
|
+
return isinstance(source, exp.Table) and isinstance(source.this, exp.Identifier)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _column_aliases(source: Expr) -> tuple[str, ...]:
|
|
229
|
+
alias = source.args.get("alias")
|
|
230
|
+
return tuple(column.name for column in alias.columns) if isinstance(alias, exp.TableAlias) else ()
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _qualified_name(table: exp.Table) -> str:
|
|
234
|
+
return ".".join(part for part in (table.catalog, table.db, table.name) if part)
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _unwrap_query(body: Expr | None) -> exp.Query | None:
|
|
238
|
+
while isinstance(body, exp.Subquery):
|
|
239
|
+
body = body.this
|
|
240
|
+
return body if isinstance(body, exp.Query) else None
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _arg(node: Expr, name: str) -> Expr | None:
|
|
244
|
+
return node.args.get(f"{name}_") or node.args.get(name)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _from_source(select: exp.Query) -> Expr | None:
|
|
248
|
+
source = _arg(select, "from")
|
|
249
|
+
return source.this if isinstance(source, exp.From) else None
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _unsupported_grouping(select: exp.Select) -> str | None:
|
|
253
|
+
"""The grouping construct that makes `select` opaque, if any."""
|
|
254
|
+
group = select.args.get("group")
|
|
255
|
+
if group is None:
|
|
256
|
+
return None
|
|
257
|
+
if group.args.get("all") and any(_projection_star(item) is not None or item.find(exp.Subquery) for item in select.expressions):
|
|
258
|
+
return "GROUP BY ALL" # Its keys are the items, which a star or a subquery leaves unknown.
|
|
259
|
+
for key, name in (("grouping_sets", "GROUPING SETS"), ("rollup", "ROLLUP"), ("cube", "CUBE"), ("totals", "WITH TOTALS")):
|
|
260
|
+
if group.args.get(key):
|
|
261
|
+
return name
|
|
262
|
+
for node, name in ((exp.GroupingSets, "GROUPING SETS"), (exp.Rollup, "ROLLUP"), (exp.Cube, "CUBE")):
|
|
263
|
+
if any(isinstance(expression, node) for expression in group.expressions):
|
|
264
|
+
return name
|
|
265
|
+
return None
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _unlowered_query(body: Expr | None) -> str:
|
|
269
|
+
"""What stands where a query body is expected but is not a SELECT or set
|
|
270
|
+
operation, which is not lowered."""
|
|
271
|
+
while isinstance(body, exp.Subquery):
|
|
272
|
+
body = body.this
|
|
273
|
+
if body is None:
|
|
274
|
+
return "a CTE or view body that is not a SELECT or set operation"
|
|
275
|
+
return "a VALUES list as a query body" if isinstance(body, exp.Values) else f"{body.key.upper()} as a query body"
|
|
276
|
+
|
|
277
|
+
# A USING column's merged binding (`_merge_using`): no qualifier can name it.
|
|
278
|
+
_USING_QUALIFIER = "\0using"
|
|
279
|
+
|
|
280
|
+
# A scalar subquery's value binding: no SQL name can match it.
|
|
281
|
+
_SCALAR_QUALIFIER = "\0scalar"
|
|
282
|
+
|
|
283
|
+
# Calls that return rows, not a value, in a select list: `unnest(arr)`,
|
|
284
|
+
# Spark's `explode(arr)`, Postgres's `generate_series(1, 3)`. Not DuckDB's
|
|
285
|
+
# `generate_series`, which there returns a list.
|
|
286
|
+
_SET_RETURNING = (exp.Explode, exp.Inline, exp.Stack, exp.ExplodingGenerateSeries, exp.Unnest)
|
|
287
|
+
|
|
288
|
+
# Set-returning functions SQLGlot parses as anonymous calls, by dialect.
|
|
289
|
+
_SET_RETURNING_NAMES: dict[str, frozenset[str]] = {
|
|
290
|
+
"postgres": frozenset({
|
|
291
|
+
"generate_subscripts", "json_array_elements", "json_array_elements_text", "json_each", "json_each_text",
|
|
292
|
+
"json_object_keys", "json_populate_recordset", "json_to_recordset", "jsonb_array_elements", "jsonb_array_elements_text",
|
|
293
|
+
"jsonb_each", "jsonb_each_text", "jsonb_object_keys", "jsonb_path_query", "jsonb_populate_recordset", "jsonb_to_recordset",
|
|
294
|
+
"regexp_matches", "regexp_split_to_table", "string_to_table",
|
|
295
|
+
}),
|
|
296
|
+
"spark": frozenset({"json_tuple", "inline_outer"}),
|
|
297
|
+
"databricks": frozenset({"json_tuple", "inline_outer"}),
|
|
298
|
+
"hive": frozenset({"json_tuple", "inline_outer"}),
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _set_returning_calls(item: Expr, dialect: str) -> list[Expr]:
|
|
303
|
+
"""The outermost set-returning calls a select list item evaluates itself:
|
|
304
|
+
not one inside a subquery, which returns rows of its own."""
|
|
305
|
+
names = _SET_RETURNING_NAMES.get(dialect, frozenset())
|
|
306
|
+
calls: list[Expr] = []
|
|
307
|
+
|
|
308
|
+
def returns_rows(node: Expr) -> bool:
|
|
309
|
+
return isinstance(node, _SET_RETURNING) or (isinstance(node, exp.Anonymous) and node.name.lower() in names)
|
|
310
|
+
|
|
311
|
+
for node in item.walk(prune=lambda node: isinstance(node, exp.Query | exp.Subquery) or returns_rows(node)):
|
|
312
|
+
if returns_rows(node):
|
|
313
|
+
calls.append(node)
|
|
314
|
+
return calls
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def _scalar_subqueries(expression: Expr) -> list[exp.Subquery]:
|
|
318
|
+
"""The scalar subqueries `expression` evaluates itself: not one under
|
|
319
|
+
EXISTS, IN, ANY or ALL, nor inside another subquery."""
|
|
320
|
+
found = []
|
|
321
|
+
for node in expression.walk(prune=lambda node: isinstance(node, (exp.Subquery, exp.Query, exp.Exists))):
|
|
322
|
+
if isinstance(node, exp.Subquery) and not isinstance(node.parent, (exp.In, exp.Exists, exp.Any, exp.All)):
|
|
323
|
+
found.append(node)
|
|
324
|
+
return found
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def _schema_path(node: exp.Table | exp.Column) -> str:
|
|
328
|
+
"""The catalog and schema a table or column is written with, as `s1` or `c.s1`."""
|
|
329
|
+
return ".".join(part for part in (node.catalog, node.db) if part).lower()
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def _projection_star(item: Expr) -> exp.Star | None:
|
|
333
|
+
star = item.this if isinstance(item, exp.Column) else item
|
|
334
|
+
return star if isinstance(star, exp.Star) else None
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
class _Carried:
|
|
338
|
+
"""A star's column, in the meta of the item it expands to: SQLGlot's deep
|
|
339
|
+
copy keeps it as itself, so the item binds that column, not a name."""
|
|
340
|
+
|
|
341
|
+
def __init__(self, column: ir.OutputColumn):
|
|
342
|
+
self.column = column
|
|
343
|
+
|
|
344
|
+
def __deepcopy__(self, memo: object) -> _Carried:
|
|
345
|
+
return self
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def _renamed(bindings: Iterable[_Binding], qualifier: str, schema: str, name: str) -> tuple[str, str] | None:
|
|
349
|
+
"""The derived table's qualifier and the repeated name that `name` may
|
|
350
|
+
be a rename of, when a column written `schema.qualifier.name` (no
|
|
351
|
+
qualifier: of any source) is of the form `<repeated>_<digits>`, in a
|
|
352
|
+
derived table that repeats the name: which column it reads is then the
|
|
353
|
+
engine's (`ir/names.py`)."""
|
|
354
|
+
for binding in bindings:
|
|
355
|
+
if qualifier and (binding.qualifier != qualifier or (schema and binding.schema != schema)):
|
|
356
|
+
continue
|
|
357
|
+
base = next((base for base in sorted(binding.repeated) if may_be_renamed((base,), name)), None)
|
|
358
|
+
if base is not None:
|
|
359
|
+
return binding.qualifier, base
|
|
360
|
+
return None
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def _star_only(select: exp.Select) -> bool:
|
|
364
|
+
return _only_star(select.expressions)
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def _only_star(items: list[Expr]) -> bool:
|
|
368
|
+
"""Whether `items` is a lone `*` with no modifier: all the input's columns, as they are."""
|
|
369
|
+
return len(items) == 1 and isinstance(items[0], exp.Star) and not any(items[0].args.values())
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def _selected_output_names(select: exp.Select) -> tuple[str, ...]:
|
|
373
|
+
return tuple(item.alias_or_name for item in select.expressions if not isinstance(item, exp.Star))
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def _matching_output(group_expression: Expr, items: list[Expr]) -> Expr | None:
|
|
377
|
+
return next(
|
|
378
|
+
(item for item in items if (item.this if isinstance(item, exp.Alias) else item) == group_expression),
|
|
379
|
+
None,
|
|
380
|
+
)
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def _unaliased(item: Expr) -> Expr:
|
|
384
|
+
return item.this if isinstance(item, exp.Alias) else item
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def _row_number_window(expression: Expr) -> exp.Window | None:
|
|
388
|
+
"""`expression` when it is a `row_number()` window call, however it is partitioned."""
|
|
389
|
+
while isinstance(expression, exp.Paren):
|
|
390
|
+
expression = expression.this
|
|
391
|
+
return expression if isinstance(expression, exp.Window) and isinstance(expression.this, exp.RowNumber) else None
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def _ended_set_operation(query: exp.Query, offset: int) -> exp.SetOperation | None:
|
|
395
|
+
"""The outermost set operation that `query`, ending at `offset`, is the
|
|
396
|
+
last operand of (or the last operand of its last operand, ...) and that
|
|
397
|
+
ends there too. Parentheses cannot end there: they are only passed
|
|
398
|
+
through where INTERSECT, binding first, is regrouped in them."""
|
|
399
|
+
found, node = None, query
|
|
400
|
+
while isinstance(node.parent, exp.SetOperation | exp.Subquery):
|
|
401
|
+
node = node.parent
|
|
402
|
+
position = marker_position(node)
|
|
403
|
+
if isinstance(node, exp.SetOperation) and position is not None and position[0] == offset:
|
|
404
|
+
found = node
|
|
405
|
+
return found
|
|
406
|
+
|
|
407
|
+
_NOT_A_FUNCTION_OF_ITS_COLUMNS = (
|
|
408
|
+
exp.Anonymous, exp.Rand, exp.Randn, exp.Uuid, exp.AggFunc, exp.Filter, exp.WithinGroup, exp.Window, exp.Query, exp.Subquery,
|
|
409
|
+
exp.CurrentDate, exp.CurrentDatetime, exp.CurrentTime, exp.CurrentTimestamp, exp.Localtimestamp, exp.Seq4, exp.Placeholder, exp.Parameter, exp.Star,
|
|
410
|
+
)
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def _select_label(select: exp.Query) -> str:
|
|
414
|
+
node = select.parent
|
|
415
|
+
while node is not None:
|
|
416
|
+
match node:
|
|
417
|
+
case exp.CTE():
|
|
418
|
+
return f"CTE {node.alias}"
|
|
419
|
+
case exp.Create():
|
|
420
|
+
table = node.this.this if isinstance(node.this, exp.Schema) else node.this
|
|
421
|
+
return f"view {table.name}"
|
|
422
|
+
case exp.Subquery() if node.alias:
|
|
423
|
+
return f"subquery {node.alias}"
|
|
424
|
+
case exp.Subquery():
|
|
425
|
+
return "subquery"
|
|
426
|
+
case _:
|
|
427
|
+
node = node.parent
|
|
428
|
+
return "Root Select"
|