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,253 @@
|
|
|
1
|
+
"""The driver: `IrParser` reads a parsed program's schema statements, discovers
|
|
2
|
+
its symbols, lowers its queries, and returns an `IrConversionResult`."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from collections.abc import Mapping
|
|
7
|
+
from dataclasses import dataclass, field, replace
|
|
8
|
+
|
|
9
|
+
from sqlglot import Expr, exp
|
|
10
|
+
|
|
11
|
+
from sqlassert import diagnostics as diag
|
|
12
|
+
from sqlassert import ir
|
|
13
|
+
from sqlassert.dialects import DialectSemantics, semantics
|
|
14
|
+
from sqlassert.diagnostics import Diagnostic
|
|
15
|
+
from sqlassert.properties import Property
|
|
16
|
+
from sqlassert.provenance import AttachmentSite, Origin, SQL
|
|
17
|
+
from sqlassert.sql_parse import ParsedProgram, written_sql
|
|
18
|
+
from sqlassert.ir.convert.shared import _Symbol, _MarkerReference, _ConstraintReference, _placed, _source_line, _USING_QUALIFIER
|
|
19
|
+
from sqlassert.ir.convert.aggregation import _Aggregation
|
|
20
|
+
from sqlassert.ir.convert.expressions import _Expressions
|
|
21
|
+
from sqlassert.ir.convert.joins import _Joins
|
|
22
|
+
from sqlassert.ir.convert.markers import _Markers
|
|
23
|
+
from sqlassert.ir.convert.queries import _Queries
|
|
24
|
+
from sqlassert.ir.convert.schema import _Schema
|
|
25
|
+
from sqlassert.ir.convert.scopes import _Scopes
|
|
26
|
+
from sqlassert.ir.convert.selects import _Selects
|
|
27
|
+
from sqlassert.ir.convert.sources import _Sources
|
|
28
|
+
from sqlassert.ir.convert.subqueries import _Subqueries
|
|
29
|
+
from sqlassert.ir.convert.value_types import _ValueTypes
|
|
30
|
+
from sqlassert.ir.convert.windows import _Windows
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class IrConversionResult:
|
|
35
|
+
program: ir.Program
|
|
36
|
+
knowledge: tuple[Property, ...]
|
|
37
|
+
diagnostics: tuple[Diagnostic, ...] = ()
|
|
38
|
+
warnings: tuple[Diagnostic, ...] = ()
|
|
39
|
+
# Below: what Hazards and Rewrites read to place their findings in the
|
|
40
|
+
# SQL, which the engine never needs.
|
|
41
|
+
# The Join or Select written at each Attachment Site of a JOIN or Select
|
|
42
|
+
# Expression; at a set operation's, the Select of its unparenthesised last
|
|
43
|
+
# operand, which ends there too (none for any other last operand).
|
|
44
|
+
syntax: Mapping[AttachmentSite, exp.Join | exp.Select] = field(default_factory=dict)
|
|
45
|
+
# Each scalar subquery lowered as a join, with where its Select is written.
|
|
46
|
+
scalar_subqueries: tuple[tuple[AttachmentSite, ir.Join], ...] = ()
|
|
47
|
+
# Each Select Expression's ORDER BY keys, by its trailing site, as columns
|
|
48
|
+
# of the stage it sorts: the input of a Project, else the Select's own
|
|
49
|
+
# relation. Empty with no ORDER BY; None when a key is an expression or a
|
|
50
|
+
# name that does not resolve to one column, and for DISTINCT ON, whose
|
|
51
|
+
# ORDER BY picks the rows it keeps. A set operation's sorts its whole result.
|
|
52
|
+
sort_keys: Mapping[AttachmentSite, tuple[ir.OutputColumn, ...] | None] = field(default_factory=dict)
|
|
53
|
+
# Each INTERSECT and EXCEPT, sited where its keyword follows its left
|
|
54
|
+
# input's last Select (no marker attaches there).
|
|
55
|
+
set_operations: tuple[tuple[AttachmentSite, ir.SetOperation], ...] = ()
|
|
56
|
+
# Each unparenthesised last operand of a set operation, with the site of
|
|
57
|
+
# the whole query it ends (the operand has none of its own, so no marker
|
|
58
|
+
# reaches it) and the operator it is the last operand of (`UNION ALL`).
|
|
59
|
+
# Its select-level Hazards are reported there.
|
|
60
|
+
last_operands: tuple[tuple[AttachmentSite, ir.RelationExpr, str], ...] = ()
|
|
61
|
+
# Each CASE (or IF) whose results have different declared types, which
|
|
62
|
+
# the engine casts to a common type, sited on its Select Expression, with
|
|
63
|
+
# what it mixes (a Hazard).
|
|
64
|
+
mixed_cases: tuple[tuple[AttachmentSite, str], ...] = ()
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@dataclass
|
|
68
|
+
class IrParser(_Schema, _Scopes, _Queries, _Sources, _ValueTypes, _Joins, _Selects, _Subqueries, _Aggregation, _Windows, _Expressions, _Markers):
|
|
69
|
+
dialect: str
|
|
70
|
+
# Unenforced keys and foreign keys become Property Declarations, as `RELY` makes them.
|
|
71
|
+
trust_unenforced_keys: bool = True
|
|
72
|
+
# Relations a caller binds Properties onto after conversion, by name as
|
|
73
|
+
# SQL writes it, with the columns it names (the dbt plugin's relationships
|
|
74
|
+
# tests): each is reached as a Foreign Key marker reaches its referenced
|
|
75
|
+
# relation, so a table with no CREATE has those columns, and a fetcher
|
|
76
|
+
# hydrates it.
|
|
77
|
+
required_relations: tuple[tuple[str, tuple[str, ...]], ...] = ()
|
|
78
|
+
# The primary key of each table a catalog declares, by lower-case name: its
|
|
79
|
+
# CREATE TABLE lists columns only, and the fetcher binds the key's
|
|
80
|
+
# Properties, but a column-less REFERENCES and a GROUP BY read the key
|
|
81
|
+
# here, as they read one declared in the SQL.
|
|
82
|
+
catalog_primary_keys: Mapping[str, tuple[str, ...]] = field(default_factory=dict)
|
|
83
|
+
_global_symbols: dict[str, _Symbol] = field(default_factory=dict)
|
|
84
|
+
_symbols: list[_Symbol] = field(default_factory=list)
|
|
85
|
+
_query_scopes: dict[int, dict[str, _Symbol]] = field(default_factory=dict)
|
|
86
|
+
_table_symbols: dict[int, _Symbol] = field(default_factory=dict)
|
|
87
|
+
_source_required: dict[int, set[str]] = field(default_factory=dict)
|
|
88
|
+
_source_expressions: dict[int, Expr] = field(default_factory=dict)
|
|
89
|
+
_named_relations: dict[_Symbol, ir.NamedRelation] = field(default_factory=dict)
|
|
90
|
+
_resolving: set[_Symbol] = field(default_factory=set)
|
|
91
|
+
# The base case of each recursive CTE or view being resolved, once lowered:
|
|
92
|
+
# what a reference to it from the recursive arm takes its types from.
|
|
93
|
+
_recursion_bases: dict[_Symbol, ir.RelationExpr] = field(default_factory=dict)
|
|
94
|
+
# Those of them a recursive arm read: their body's set operation is recursive.
|
|
95
|
+
_recursed: set[_Symbol] = field(default_factory=set)
|
|
96
|
+
_knowledge: list[Property] = field(default_factory=list)
|
|
97
|
+
_assertions: list[ir.Assertion] = field(default_factory=list)
|
|
98
|
+
_declarations: list[Property] = field(default_factory=list)
|
|
99
|
+
_diagnostics: list[Diagnostic] = field(default_factory=list)
|
|
100
|
+
_warnings: list[Diagnostic] = field(default_factory=list)
|
|
101
|
+
_handled_column_markers: set[int] = field(default_factory=set)
|
|
102
|
+
_handled_joins: set[int] = field(default_factory=set)
|
|
103
|
+
_handled_cases: set[int] = field(default_factory=set)
|
|
104
|
+
_reported_cycles: set[_Symbol] = field(default_factory=set)
|
|
105
|
+
_attachment_sites: list[tuple[AttachmentSite, ir.RelationExpr | ir.SimpleCase]] = field(default_factory=list)
|
|
106
|
+
_syntax: dict[AttachmentSite, exp.Join | exp.Select] = field(default_factory=dict)
|
|
107
|
+
# A query that is the last operand of a set operation and ends where it
|
|
108
|
+
# does, by that offset, with its relation and the Select written there:
|
|
109
|
+
# it has no site of its own, and the set operation takes it once lowered.
|
|
110
|
+
_ending: dict[int, tuple[ir.RelationExpr, exp.Select | None]] = field(default_factory=dict)
|
|
111
|
+
_sited_cases: set[int] = field(default_factory=set)
|
|
112
|
+
_mixed_checked: set[int] = field(default_factory=set)
|
|
113
|
+
_mixed_cases: list[tuple[AttachmentSite, str]] = field(default_factory=list)
|
|
114
|
+
# Each scalar subquery lowered as a join, by id, and the qualifier of the
|
|
115
|
+
# binding that holds its value.
|
|
116
|
+
_scalar_values: dict[int, str] = field(default_factory=dict)
|
|
117
|
+
# Each aggregate call and grouping-determined column of the grouped
|
|
118
|
+
# select item being lowered, by id, and its value per group (`_lower_grouped`).
|
|
119
|
+
_grouped_values: dict[int, ir.ScalarExpr] = field(default_factory=dict)
|
|
120
|
+
# Each set-returning call of a select list, by id, and the qualifier of the
|
|
121
|
+
# binding that holds the values it returns.
|
|
122
|
+
_set_returning_values: dict[int, str] = field(default_factory=dict)
|
|
123
|
+
_scalar_subqueries: list[tuple[AttachmentSite, ir.Join]] = field(default_factory=list)
|
|
124
|
+
_sort_keys: dict[int, tuple[ir.OutputColumn, ...] | None] = field(default_factory=dict)
|
|
125
|
+
_site_sort_keys: dict[AttachmentSite, tuple[ir.OutputColumn, ...] | None] = field(default_factory=dict)
|
|
126
|
+
_set_operations: list[tuple[AttachmentSite, ir.SetOperation]] = field(default_factory=list)
|
|
127
|
+
_last_operands: list[tuple[AttachmentSite, ir.RelationExpr, str]] = field(default_factory=list)
|
|
128
|
+
_unsupported: list[tuple[ir.Node, str]] = field(default_factory=list)
|
|
129
|
+
# Joins written inside a SELECT that lowered opaque, with its construct.
|
|
130
|
+
_orphan_joins: list[tuple[ir.Join, str]] = field(default_factory=list)
|
|
131
|
+
# Columns made up for names a query uses: of a table with no CREATE, or an
|
|
132
|
+
# opaque relation (`_guessed`), and those a declared table does not have (`_absent`).
|
|
133
|
+
_guessed: set[ir.OutputColumn] = field(default_factory=set)
|
|
134
|
+
# A scalar subquery's columns, each bound to the scope that owns it.
|
|
135
|
+
_scoped_columns: dict[int, ir.OutputColumn] = field(default_factory=dict)
|
|
136
|
+
_absent: set[ir.OutputColumn] = field(default_factory=set)
|
|
137
|
+
# Each declared table column's type, as its CREATE TABLE writes it.
|
|
138
|
+
_declared_types: dict[ir.OutputColumn, exp.DataType] = field(default_factory=dict)
|
|
139
|
+
# Every set operation's output column: it refers to its left input only,
|
|
140
|
+
# so the left input's declared type need not describe its values.
|
|
141
|
+
_set_outputs: set[ir.OutputColumn] = field(default_factory=set)
|
|
142
|
+
# The comparisons already checked for a zoned timestamp's text, by id.
|
|
143
|
+
_zone_checked: set[int] = field(default_factory=set)
|
|
144
|
+
_untyped_calls: set[int] = field(default_factory=set)
|
|
145
|
+
# Each composite column or CAST a comparison reads, by id, with the
|
|
146
|
+
# comparison: a warning unless its elements are declared non-null.
|
|
147
|
+
_composite_comparisons: dict[int, tuple[Origin, str, str, ir.ScalarExpr]] = field(default_factory=dict)
|
|
148
|
+
_marker_targets: dict[int, _Symbol] = field(default_factory=dict)
|
|
149
|
+
_marker_references: list[_MarkerReference] = field(default_factory=list)
|
|
150
|
+
_constraint_references: list[_ConstraintReference] = field(default_factory=list)
|
|
151
|
+
# Constraints an ALTER TABLE ... NOT VALID added: rows already there were never checked.
|
|
152
|
+
_unvalidated: set[int] = field(default_factory=set)
|
|
153
|
+
# The USING columns merged so far, for the qualifier of each one's binding.
|
|
154
|
+
_using_columns: int = 0
|
|
155
|
+
|
|
156
|
+
@property
|
|
157
|
+
def semantics(self) -> DialectSemantics:
|
|
158
|
+
return semantics(self.dialect)
|
|
159
|
+
|
|
160
|
+
def parse(self, ast: ParsedProgram) -> IrConversionResult:
|
|
161
|
+
for statement in (*ast.create_statements, ast.root_select):
|
|
162
|
+
if statement is None:
|
|
163
|
+
continue
|
|
164
|
+
for node in statement.find_all(exp.Identifier):
|
|
165
|
+
if self.dialect == "postgres" and node.quoted and node.name != node.name.lower() and node.find_ancestor(exp.Collate, exp.CollateColumnConstraint) is None:
|
|
166
|
+
diagnostic = Diagnostic(diag.UNSUPPORTED_CONSTRUCT, "case-sensitive quoted PostgreSQL identifiers are not supported", self._origin(node))
|
|
167
|
+
return IrConversionResult(ir.Program(), (), (diagnostic,))
|
|
168
|
+
for collate in statement.find_all(exp.Collate, exp.CollateColumnConstraint):
|
|
169
|
+
# Every COLLATE warns where it is written, whatever reads it.
|
|
170
|
+
written = collate.find_ancestor(exp.ColumnDef) if isinstance(collate, exp.CollateColumnConstraint) else collate
|
|
171
|
+
self._warnings.append(Diagnostic(
|
|
172
|
+
diag.UNSUPPORTED_CONSTRUCT,
|
|
173
|
+
"COLLATE is not supported by sqlassert yet: only the dialect's default collation is, so facts that "
|
|
174
|
+
"compare its values are unknown",
|
|
175
|
+
self._origin(written or collate, _source_line(written or collate)),
|
|
176
|
+
))
|
|
177
|
+
for table in statement.find_all(exp.Table):
|
|
178
|
+
if any("." in part.name for part in table.parts if isinstance(part, exp.Identifier)):
|
|
179
|
+
diagnostic = Diagnostic(diag.UNSUPPORTED_CONSTRUCT, "dots inside quoted relation identifiers are not supported", self._origin(table))
|
|
180
|
+
return IrConversionResult(ir.Program(), (), (diagnostic,))
|
|
181
|
+
for statement in ast.create_statements:
|
|
182
|
+
match statement:
|
|
183
|
+
case exp.Create(kind="INDEX"):
|
|
184
|
+
self._declare_index(statement)
|
|
185
|
+
case exp.Create(kind="SCHEMA"):
|
|
186
|
+
pass # A schema states nothing about rows, like a plain index.
|
|
187
|
+
case exp.Create():
|
|
188
|
+
self._declare(statement)
|
|
189
|
+
case exp.Alter():
|
|
190
|
+
self._alter(statement)
|
|
191
|
+
case _:
|
|
192
|
+
raise TypeError(f"Unhandled schema statement: {type(statement).__name__}")
|
|
193
|
+
|
|
194
|
+
for symbol in tuple(self._symbols):
|
|
195
|
+
if symbol.role is ir.RelationRole.VIEW and symbol.body is not None:
|
|
196
|
+
self._discover_query(symbol.body, {})
|
|
197
|
+
if ast.root_select is not None:
|
|
198
|
+
self._discover_query(ast.root_select, {})
|
|
199
|
+
for name, columns in self.required_relations:
|
|
200
|
+
self._require_undeclared(self._symbol_for_name(name, {}, Origin(SQL, name)), columns)
|
|
201
|
+
self._discover_constraint_references()
|
|
202
|
+
self._propagate_required_columns()
|
|
203
|
+
|
|
204
|
+
root = self._lower_query(ast.root_select) if ast.root_select is not None else None
|
|
205
|
+
# Every view is a query of its own: its markers are checked whether or
|
|
206
|
+
# not the root reads it, so a file of views (a project's models) needs
|
|
207
|
+
# no root SELECT.
|
|
208
|
+
for symbol in tuple(self._symbols):
|
|
209
|
+
if symbol.role is ir.RelationRole.VIEW and symbol not in self._named_relations:
|
|
210
|
+
self._resolve_symbol(symbol)
|
|
211
|
+
# Referenced relations are linked last: a marker on a view may name
|
|
212
|
+
# the view itself, or one that reads it.
|
|
213
|
+
self._link_constraint_references()
|
|
214
|
+
self._link_marker_references()
|
|
215
|
+
self._report_unanalyzed(ast)
|
|
216
|
+
|
|
217
|
+
named_relations = tuple(self._named_relations.get(symbol) or self._unresolved_named_relation(symbol) for symbol in self._symbols)
|
|
218
|
+
warnings = [*self._undeclared_table_warnings(), *self._warnings, *self._composite_warnings()]
|
|
219
|
+
program = ir.Program(
|
|
220
|
+
named_relations=named_relations, root=root, assertions=tuple(self._assertions), declarations=tuple(self._declarations), attachment_sites=tuple(self._attachment_sites),
|
|
221
|
+
unsupported=tuple(self._unsupported),
|
|
222
|
+
)
|
|
223
|
+
if self._orphan_joins:
|
|
224
|
+
# A join inside a Named Relation first lowered under an opaque SELECT is still in the program.
|
|
225
|
+
reachable = frozenset(program.nodes())
|
|
226
|
+
orphans = tuple((join, construct) for join, construct in self._orphan_joins if join not in reachable)
|
|
227
|
+
program = replace(program, unsupported=(*program.unsupported, *orphans))
|
|
228
|
+
return IrConversionResult(
|
|
229
|
+
program, tuple(self._knowledge), tuple(self._diagnostics), tuple(dict.fromkeys(warnings)),
|
|
230
|
+
syntax=self._syntax, scalar_subqueries=tuple(self._scalar_subqueries), sort_keys=self._site_sort_keys,
|
|
231
|
+
set_operations=tuple(self._set_operations), last_operands=tuple(self._last_operands), mixed_cases=tuple(self._mixed_cases),
|
|
232
|
+
)
|
|
233
|
+
|
|
234
|
+
def _undeclared_table_warnings(self) -> list[Diagnostic]:
|
|
235
|
+
return [
|
|
236
|
+
Diagnostic(
|
|
237
|
+
diag.UNDECLARED_TABLE,
|
|
238
|
+
f"table {symbol.name} has no CREATE TABLE in the program, so its keys, nullability and column types are unknown: "
|
|
239
|
+
"declare it with CREATE TABLE, or analyze with a database connection (analyze_database)",
|
|
240
|
+
replace(symbol.origin, line=symbol.first_line or symbol.origin.line),
|
|
241
|
+
)
|
|
242
|
+
for symbol in self._symbols
|
|
243
|
+
if symbol.role is ir.RelationRole.TABLE and symbol.statement is None
|
|
244
|
+
]
|
|
245
|
+
|
|
246
|
+
def _placed(self, node: Expr) -> Origin:
|
|
247
|
+
"""`node`'s Origin with where it is written, for a relation an
|
|
248
|
+
explanation points at (`rules/causes`)."""
|
|
249
|
+
return _placed(self._origin(node), node)
|
|
250
|
+
|
|
251
|
+
def _origin(self, node: Expr, line: int | None = None) -> Origin:
|
|
252
|
+
# A star's expansion names a merged USING column by a qualifier no SQL can write (`_merge_using`).
|
|
253
|
+
return Origin(SQL, written_sql(node, self.dialect).replace(_USING_QUALIFIER, "using"), line)
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
"""Queries: a Root Select, view, CTE or subquery body, its set operations
|
|
2
|
+
(UNION, INTERSECT, EXCEPT, BY NAME), a SELECT's FROM-to-select-list pipeline,
|
|
3
|
+
and LIMIT."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from dataclasses import replace
|
|
8
|
+
from typing import TYPE_CHECKING
|
|
9
|
+
|
|
10
|
+
from sqlglot import Expr, exp
|
|
11
|
+
|
|
12
|
+
from sqlassert import ir
|
|
13
|
+
from sqlassert.provenance import AttachmentSite
|
|
14
|
+
from sqlassert.sql_parse import marker_position
|
|
15
|
+
from sqlassert.ir.convert.shared import (
|
|
16
|
+
_Lowered, _pass_output_columns, _all_joins, _unwrap_query, _from_source, _unlowered_query, _selected_output_names, _ended_set_operation,
|
|
17
|
+
_select_label,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
if TYPE_CHECKING:
|
|
21
|
+
from sqlassert.ir.convert.parser import IrParser
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class _Queries:
|
|
25
|
+
def _lower_query(self: IrParser, query: exp.Query) -> ir.RelationExpr | None:
|
|
26
|
+
"""A Root Select, view, CTE, and FROM-subquery body all lower the same way."""
|
|
27
|
+
if isinstance(query, exp.Subquery):
|
|
28
|
+
# Parentheses add no rows, but a LIMIT or OFFSET written after them
|
|
29
|
+
# (`(SELECT ...) LIMIT 2`) keeps a subset of the body's rows.
|
|
30
|
+
inner = self._lower_query(query.this) if isinstance(query.this, exp.Query) else None
|
|
31
|
+
return self._lower_limit(inner, query) if inner is not None else None
|
|
32
|
+
if isinstance(query, exp.SetOperation):
|
|
33
|
+
left = self._lower_arm(query.this)
|
|
34
|
+
self._note_recursion_base(query, left)
|
|
35
|
+
right = self._lower_arm(query.expression)
|
|
36
|
+
arm = right # As lowered: BY NAME may read it through a reordering projection.
|
|
37
|
+
origin = self._origin(query)
|
|
38
|
+
unpaired, construct = False, None
|
|
39
|
+
if query.args.get("by_name"):
|
|
40
|
+
aligned = self._align_by_name(query, left, right)
|
|
41
|
+
if isinstance(aligned, tuple):
|
|
42
|
+
left, right = aligned
|
|
43
|
+
else:
|
|
44
|
+
unpaired, construct = True, aligned
|
|
45
|
+
if unpaired:
|
|
46
|
+
# The inputs' columns cannot be paired: the output is each name either input has, nothing known of it.
|
|
47
|
+
names: dict[str, str] = {}
|
|
48
|
+
for column in (*left.output_columns, *right.output_columns):
|
|
49
|
+
names.setdefault(column.name.lower(), column.name)
|
|
50
|
+
output_columns = self._opaque_output_columns(names.values(), origin)
|
|
51
|
+
else:
|
|
52
|
+
output_columns = _pass_output_columns(left.output_columns, origin)
|
|
53
|
+
self._set_outputs.update(output_columns)
|
|
54
|
+
relation = ir.SetOperation(
|
|
55
|
+
origin=self._placed(query), output_columns=output_columns, is_schema_complete=left.is_schema_complete and right.is_schema_complete,
|
|
56
|
+
operator=_SET_OPERATORS[type(query)], left=left, right=right, distinct=bool(query.args.get("distinct")),
|
|
57
|
+
unpaired=unpaired, recursive=self._is_recursion(query),
|
|
58
|
+
)
|
|
59
|
+
if construct is not None:
|
|
60
|
+
self._unsupported.append((relation, construct))
|
|
61
|
+
last = _last_select(query.this)
|
|
62
|
+
position = marker_position(last) if last is not None else None
|
|
63
|
+
if relation.operator != "union" and position is not None:
|
|
64
|
+
self._set_operations.append((AttachmentSite(relation.operator.upper(), position[1], position[0], True), relation))
|
|
65
|
+
limited = self._lower_limit(relation, query)
|
|
66
|
+
self._register_column_markers(limited, query)
|
|
67
|
+
# The query ending here, if any, is the last operand (`_add_query_site`):
|
|
68
|
+
# its Hazards are reported at the site of the outermost query ending here.
|
|
69
|
+
end = marker_position(query)
|
|
70
|
+
operand, written = self._ending.pop(end[0], (None, None)) if end is not None else (None, None)
|
|
71
|
+
last, owner = arm, relation # Through INTERSECT, which binds first: `a UNION b INTERSECT c` ends with c.
|
|
72
|
+
while isinstance(last, ir.SetOperation):
|
|
73
|
+
last, owner = last.right, last
|
|
74
|
+
if end is not None and operand is last:
|
|
75
|
+
operator = owner.operator.upper() + ("" if owner.distinct else " ALL")
|
|
76
|
+
whole = _ended_set_operation(query, end[0]) or query
|
|
77
|
+
self._last_operands.append((AttachmentSite(_select_label(whole), end[1], end[0], True), last, operator))
|
|
78
|
+
# The ORDER BY after the last operand sorts the whole result.
|
|
79
|
+
self._add_query_site(query, limited, written, _set_operation_order(query, relation))
|
|
80
|
+
return limited
|
|
81
|
+
if not isinstance(query, exp.Select):
|
|
82
|
+
return None
|
|
83
|
+
return self._lower_select(query)
|
|
84
|
+
|
|
85
|
+
def _note_recursion_base(self: IrParser, query: exp.SetOperation, base: ir.RelationExpr) -> None:
|
|
86
|
+
"""`query` is the body of a CTE or view being resolved: its left input,
|
|
87
|
+
lowered, is the base case, which the recursive arm (lowered next) reads
|
|
88
|
+
by name. A `BY NAME` set operation pairs columns by name, not position."""
|
|
89
|
+
if query.args.get("by_name"):
|
|
90
|
+
return
|
|
91
|
+
for symbol in self._resolving:
|
|
92
|
+
if _unwrap_query(symbol.body) is query:
|
|
93
|
+
self._recursion_bases[symbol] = base
|
|
94
|
+
|
|
95
|
+
def _is_recursion(self: IrParser, query: exp.SetOperation) -> bool:
|
|
96
|
+
"""Whether `query`, lowered, is the body of a CTE or view whose
|
|
97
|
+
recursive arm read it: only then does the engine type its columns from
|
|
98
|
+
the base case (a body that never reads itself is an ordinary set
|
|
99
|
+
operation, whose arms are cast to a common type)."""
|
|
100
|
+
return any(symbol in self._recursed and _unwrap_query(symbol.body) is query for symbol in self._resolving)
|
|
101
|
+
|
|
102
|
+
def _lower_arm(self: IrParser, arm: exp.Query) -> ir.RelationExpr:
|
|
103
|
+
"""One input of a set operation; one that is not a SELECT or set
|
|
104
|
+
operation (a VALUES list) lowers opaque, and is reported."""
|
|
105
|
+
relation = self._lower_query(arm)
|
|
106
|
+
if relation is None:
|
|
107
|
+
relation = self._opaque_relation(arm)
|
|
108
|
+
self._unsupported.append((relation, _unlowered_query(arm)))
|
|
109
|
+
return relation
|
|
110
|
+
|
|
111
|
+
def _align_by_name(
|
|
112
|
+
self: IrParser, query: exp.SetOperation, left: ir.RelationExpr, right: ir.RelationExpr
|
|
113
|
+
) -> tuple[ir.RelationExpr, ir.RelationExpr] | str | None:
|
|
114
|
+
"""A DuckDB `UNION [ALL] BY NAME` as the positional one it means: each
|
|
115
|
+
input is read as the output's columns in order, a column the input
|
|
116
|
+
lacks as NULL. The output is the left input's columns, then the
|
|
117
|
+
right's that the left lacks, names matching without regard to case,
|
|
118
|
+
the left's spelling kept; a column in one input only is NULL on the
|
|
119
|
+
other's rows, so no type is known of it and it may be NULL.
|
|
120
|
+
|
|
121
|
+
Returns None where the pairing needs a fact missing (an input whose
|
|
122
|
+
columns are not all known), else, when the form is not modelled, the
|
|
123
|
+
construct to report: another set operator (DuckDB rejects them), a
|
|
124
|
+
dialect other than DuckDB (Snowflake documents it too, with quoted
|
|
125
|
+
names matched exactly), a CORRESPONDING or ON list, or a column name
|
|
126
|
+
written twice in an input (DuckDB rejects that)."""
|
|
127
|
+
operator = type(query).__name__.upper()
|
|
128
|
+
if not isinstance(query, exp.Union):
|
|
129
|
+
return f"{operator} BY NAME"
|
|
130
|
+
if self.dialect != "duckdb":
|
|
131
|
+
return f"UNION BY NAME in {self.dialect}"
|
|
132
|
+
if query.args.get("on") or query.args.get("side") or query.args.get("kind"):
|
|
133
|
+
return "UNION BY NAME with a mode or column list"
|
|
134
|
+
if not (left.is_schema_complete and right.is_schema_complete):
|
|
135
|
+
return None
|
|
136
|
+
names = [[column.name.lower() for column in relation.output_columns] for relation in (left, right)]
|
|
137
|
+
if any(len(set(side)) != len(side) for side in names):
|
|
138
|
+
return "UNION BY NAME with a repeated column name"
|
|
139
|
+
spelled = {column.name.lower(): column.name for column in (*right.output_columns, *left.output_columns)}
|
|
140
|
+
output = [*names[0], *(name for name in names[1] if name not in names[0])]
|
|
141
|
+
origin = self._origin(query)
|
|
142
|
+
|
|
143
|
+
def read(relation: ir.RelationExpr, own: list[str]) -> ir.RelationExpr:
|
|
144
|
+
if own == output:
|
|
145
|
+
return relation
|
|
146
|
+
by_name = {column.name.lower(): column for column in relation.output_columns}
|
|
147
|
+
return ir.Project(
|
|
148
|
+
origin=origin, is_schema_complete=True, input=relation,
|
|
149
|
+
output_columns=tuple(
|
|
150
|
+
ir.OutputColumn(
|
|
151
|
+
origin=origin, name=spelled[name],
|
|
152
|
+
scalar_expr=ir.ColumnRef(origin=origin, column=by_name[name]) if name in by_name else ir.NullLiteral(origin=origin),
|
|
153
|
+
)
|
|
154
|
+
for name in output
|
|
155
|
+
),
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
return read(left, names[0]), read(right, names[1])
|
|
159
|
+
|
|
160
|
+
def _lower_select(self: IrParser, select: exp.Select) -> ir.RelationExpr | None:
|
|
161
|
+
source = _from_source(select)
|
|
162
|
+
if source is None:
|
|
163
|
+
# No FROM: the select list is evaluated once, over one row of no
|
|
164
|
+
# columns, which an opaque relation limited to one row stands for.
|
|
165
|
+
origin = self._origin(select)
|
|
166
|
+
row = ir.OpaqueRelation(origin=origin, output_columns=(), is_schema_complete=True, description="no FROM")
|
|
167
|
+
one_row = ir.Limit(origin=origin, output_columns=(), is_schema_complete=True, input=row, count=1)
|
|
168
|
+
relation = self._lower_select_tail(_Lowered(one_row, ()), select)
|
|
169
|
+
elif any(join.args.get("method") == "NATURAL" for join in _all_joins(select)):
|
|
170
|
+
relation = self._opaque_relation(select, _selected_output_names(select))
|
|
171
|
+
else:
|
|
172
|
+
start = len(self._attachment_sites)
|
|
173
|
+
lowered = self._lower_source(source)
|
|
174
|
+
for join in select.args.get("joins") or ():
|
|
175
|
+
lowered = self._lower_join(lowered, join)
|
|
176
|
+
lowered = self._sampled(lowered, select)
|
|
177
|
+
relation = self._lower_select_tail(lowered, select)
|
|
178
|
+
self._name_orphan_joins(relation, start)
|
|
179
|
+
return self._finish_select(relation, select)
|
|
180
|
+
|
|
181
|
+
def _sampled(self: IrParser, lowered: _Lowered, select: exp.Select) -> _Lowered:
|
|
182
|
+
"""DuckDB's `USING SAMPLE` keeps some of the rows of the FROM clause's
|
|
183
|
+
output, before WHERE and grouping (probed on DuckDB 2.0.0: `WHERE g = 1
|
|
184
|
+
USING SAMPLE 10 ROWS` samples the table, then filters): a row subset."""
|
|
185
|
+
sample = select.args.get("sample")
|
|
186
|
+
if sample is None:
|
|
187
|
+
return lowered
|
|
188
|
+
relation = self._row_subset(lowered.relation, sample, sample)
|
|
189
|
+
remapped = dict(zip(lowered.relation.output_columns, relation.output_columns))
|
|
190
|
+
return _Lowered(relation, tuple(replace(binding, column=remapped[binding.column]) for binding in lowered.bindings))
|
|
191
|
+
|
|
192
|
+
def _name_orphan_joins(self: IrParser, relation: ir.RelationExpr, start: int) -> None:
|
|
193
|
+
"""A SELECT that lowered opaque discards the joins written inside it
|
|
194
|
+
(`start`: the attachment sites before it). Each is named after the
|
|
195
|
+
construct that made the SELECT opaque, so a join that is no part of the
|
|
196
|
+
program is reported under it (`unproved_join`); `parse` keeps those
|
|
197
|
+
that are still unreachable at the end."""
|
|
198
|
+
if not isinstance(relation, ir.OpaqueRelation):
|
|
199
|
+
return
|
|
200
|
+
construct = next((construct for node, construct in reversed(self._unsupported) if node is relation), None)
|
|
201
|
+
if construct is not None:
|
|
202
|
+
self._orphan_joins.extend((node, construct) for _, node in self._attachment_sites[start:] if isinstance(node, ir.Join))
|
|
203
|
+
|
|
204
|
+
def _finish_select(self: IrParser, relation: ir.RelationExpr, select: exp.Select) -> ir.RelationExpr:
|
|
205
|
+
relation = self._lower_limit(relation, select)
|
|
206
|
+
self._register_column_markers(relation, select)
|
|
207
|
+
self._add_query_site(select, relation, select, self._sort_keys.get(id(select)))
|
|
208
|
+
return relation
|
|
209
|
+
|
|
210
|
+
def _lower_limit(self: IrParser, relation: ir.RelationExpr, query: exp.Query) -> ir.RelationExpr:
|
|
211
|
+
limit = query.args.get("limit")
|
|
212
|
+
if limit is None and query.args.get("offset") is None:
|
|
213
|
+
return relation
|
|
214
|
+
count = None
|
|
215
|
+
if limit is not None:
|
|
216
|
+
expression = limit.args.get("expression") if isinstance(limit, exp.Limit) else limit.args.get("count")
|
|
217
|
+
options = limit.args.get("limit_options")
|
|
218
|
+
hard_bound = options is None or not any(options.args.get(key) for key in ("percent", "with_ties"))
|
|
219
|
+
if hard_bound and isinstance(expression, exp.Literal) and expression.is_int:
|
|
220
|
+
count = int(expression.this)
|
|
221
|
+
origin = self._origin(query)
|
|
222
|
+
return ir.Limit(origin=origin, output_columns=_pass_output_columns(relation.output_columns, origin), is_schema_complete=relation.is_schema_complete, input=relation, count=count)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _set_operation_order(query: exp.SetOperation, relation: ir.SetOperation) -> tuple[ir.OutputColumn, ...] | None:
|
|
226
|
+
"""The ORDER BY of a set operation as its output columns: a name, the
|
|
227
|
+
first operand's, or a position. None when a key is anything else."""
|
|
228
|
+
order = query.args.get("order")
|
|
229
|
+
if order is None:
|
|
230
|
+
return ()
|
|
231
|
+
outputs = relation.output_columns
|
|
232
|
+
names = [column.name.lower() for column in outputs]
|
|
233
|
+
keys: list[ir.OutputColumn] = []
|
|
234
|
+
for ordered in order.expressions:
|
|
235
|
+
expression = ordered.this if isinstance(ordered, exp.Ordered) else ordered
|
|
236
|
+
match expression:
|
|
237
|
+
case exp.Literal(is_int=True) if 1 <= int(expression.this) <= len(outputs):
|
|
238
|
+
keys.append(outputs[int(expression.this) - 1])
|
|
239
|
+
case exp.Column(table="") if names.count(expression.name.lower()) == 1:
|
|
240
|
+
keys.append(outputs[names.index(expression.name.lower())])
|
|
241
|
+
case _:
|
|
242
|
+
return None
|
|
243
|
+
return tuple(keys)
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _last_select(query: Expr) -> exp.Select | None:
|
|
247
|
+
"""The Select a set operation's left input ends with."""
|
|
248
|
+
while True:
|
|
249
|
+
unwrapped = _unwrap_query(query) if isinstance(query, exp.Query) else None
|
|
250
|
+
match unwrapped:
|
|
251
|
+
case exp.SetOperation():
|
|
252
|
+
query = unwrapped.expression
|
|
253
|
+
case exp.Select():
|
|
254
|
+
return unwrapped
|
|
255
|
+
case _:
|
|
256
|
+
return None
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
_SET_OPERATORS: dict[type[Expr], ir.SetOperator] = {exp.Union: "union", exp.Intersect: "intersect", exp.Except: "except"}
|