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.
Files changed (69) hide show
  1. sqlassert/__init__.py +1 -2
  2. sqlassert/check.py +88 -13
  3. sqlassert/declared_types.py +158 -0
  4. sqlassert/diagnostics.py +15 -7
  5. sqlassert/dialects.py +259 -107
  6. sqlassert/discovery/bigquery.py +4 -2
  7. sqlassert/discovery/databricks.py +26 -5
  8. sqlassert/discovery/duckdb.py +49 -7
  9. sqlassert/discovery/fetcher.py +137 -58
  10. sqlassert/discovery/information_schema.py +31 -6
  11. sqlassert/discovery/mysql.py +21 -4
  12. sqlassert/discovery/postgres.py +28 -20
  13. sqlassert/discovery/redshift.py +3 -2
  14. sqlassert/discovery/snowflake.py +5 -2
  15. sqlassert/discovery/trino.py +2 -2
  16. sqlassert/functions/__init__.py +10 -0
  17. sqlassert/functions/load.py +375 -0
  18. sqlassert/functions/table.py +2721 -0
  19. sqlassert/hazards.py +249 -88
  20. sqlassert/ir/__init__.py +15 -4
  21. sqlassert/ir/convert/__init__.py +13 -0
  22. sqlassert/ir/convert/aggregation.py +438 -0
  23. sqlassert/ir/convert/expressions.py +581 -0
  24. sqlassert/ir/convert/joins.py +264 -0
  25. sqlassert/ir/convert/markers.py +249 -0
  26. sqlassert/ir/convert/parser.py +249 -0
  27. sqlassert/ir/convert/queries.py +259 -0
  28. sqlassert/ir/convert/schema.py +537 -0
  29. sqlassert/ir/convert/scopes.py +205 -0
  30. sqlassert/ir/convert/selects.py +352 -0
  31. sqlassert/ir/convert/shared.py +428 -0
  32. sqlassert/ir/convert/sources.py +433 -0
  33. sqlassert/ir/convert/subqueries.py +364 -0
  34. sqlassert/ir/convert/value_types.py +78 -0
  35. sqlassert/ir/convert/windows.py +275 -0
  36. sqlassert/ir/model.py +417 -146
  37. sqlassert/ir/names.py +63 -0
  38. sqlassert/main.py +7 -10
  39. sqlassert/properties.py +12 -1
  40. sqlassert/provenance.py +5 -1
  41. sqlassert/python_engine.py +104 -44
  42. sqlassert/reporting.py +33 -32
  43. sqlassert/rewrites.py +111 -61
  44. sqlassert/rules/STYLEGUIDE.md +3 -2
  45. sqlassert/rules/causes/__init__.py +41 -0
  46. sqlassert/rules/causes/coverage.py +113 -0
  47. sqlassert/rules/causes/domain.py +123 -0
  48. sqlassert/rules/causes/joins.py +73 -0
  49. sqlassert/rules/causes/nulls.py +154 -0
  50. sqlassert/rules/causes/unique.py +564 -0
  51. sqlassert/rules/domain.py +9 -8
  52. sqlassert/rules/equality.py +6 -147
  53. sqlassert/rules/exactly_one.py +2 -1
  54. sqlassert/rules/foreign_key.py +8 -9
  55. sqlassert/rules/join_cardinality.py +277 -43
  56. sqlassert/rules/nullability.py +8 -8
  57. sqlassert/rules/uniqueness.py +212 -87
  58. sqlassert/rules/value_typing.py +470 -0
  59. sqlassert/sql_parse.py +28 -1
  60. sqlassert/suggest.py +13 -17
  61. sqlassert-0.4.2.dist-info/METADATA +239 -0
  62. sqlassert-0.4.2.dist-info/RECORD +72 -0
  63. sqlassert/ir/convert.py +0 -3509
  64. sqlassert-0.3.3.dist-info/METADATA +0 -807
  65. sqlassert-0.3.3.dist-info/RECORD +0 -46
  66. {sqlassert-0.3.3.dist-info → sqlassert-0.4.2.dist-info}/WHEEL +0 -0
  67. {sqlassert-0.3.3.dist-info → sqlassert-0.4.2.dist-info}/entry_points.txt +0 -0
  68. {sqlassert-0.3.3.dist-info → sqlassert-0.4.2.dist-info}/licenses/LICENSE +0 -0
  69. {sqlassert-0.3.3.dist-info → sqlassert-0.4.2.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,249 @@
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
+ # Relations a caller binds Properties onto after conversion, by name as
71
+ # SQL writes it, with the columns it names (the dbt plugin's relationships
72
+ # tests): each is reached as a Foreign Key marker reaches its referenced
73
+ # relation, so a table with no CREATE has those columns, and a fetcher
74
+ # hydrates it.
75
+ required_relations: tuple[tuple[str, tuple[str, ...]], ...] = ()
76
+ # The primary key of each table a catalog declares, by lower-case name: its
77
+ # CREATE TABLE lists columns only, and the fetcher binds the key's
78
+ # Properties, but a column-less REFERENCES and a GROUP BY read the key
79
+ # here, as they read one declared in the SQL.
80
+ catalog_primary_keys: Mapping[str, tuple[str, ...]] = field(default_factory=dict)
81
+ _global_symbols: dict[str, _Symbol] = field(default_factory=dict)
82
+ _symbols: list[_Symbol] = field(default_factory=list)
83
+ _query_scopes: dict[int, dict[str, _Symbol]] = field(default_factory=dict)
84
+ _table_symbols: dict[int, _Symbol] = field(default_factory=dict)
85
+ _source_required: dict[int, set[str]] = field(default_factory=dict)
86
+ _source_expressions: dict[int, Expr] = field(default_factory=dict)
87
+ _named_relations: dict[_Symbol, ir.NamedRelation] = field(default_factory=dict)
88
+ _resolving: set[_Symbol] = field(default_factory=set)
89
+ # The base case of each recursive CTE or view being resolved, once lowered:
90
+ # what a reference to it from the recursive arm takes its types from.
91
+ _recursion_bases: dict[_Symbol, ir.RelationExpr] = field(default_factory=dict)
92
+ # Those of them a recursive arm read: their body's set operation is recursive.
93
+ _recursed: set[_Symbol] = field(default_factory=set)
94
+ _knowledge: list[Property] = field(default_factory=list)
95
+ _assertions: list[ir.Assertion] = field(default_factory=list)
96
+ _declarations: list[Property] = field(default_factory=list)
97
+ _diagnostics: list[Diagnostic] = field(default_factory=list)
98
+ _warnings: list[Diagnostic] = field(default_factory=list)
99
+ _handled_column_markers: set[int] = field(default_factory=set)
100
+ _handled_joins: set[int] = field(default_factory=set)
101
+ _handled_cases: set[int] = field(default_factory=set)
102
+ _reported_cycles: set[_Symbol] = field(default_factory=set)
103
+ _attachment_sites: list[tuple[AttachmentSite, ir.RelationExpr | ir.SimpleCase]] = field(default_factory=list)
104
+ _syntax: dict[AttachmentSite, exp.Join | exp.Select] = field(default_factory=dict)
105
+ # A query that is the last operand of a set operation and ends where it
106
+ # does, by that offset, with its relation and the Select written there:
107
+ # it has no site of its own, and the set operation takes it once lowered.
108
+ _ending: dict[int, tuple[ir.RelationExpr, exp.Select | None]] = field(default_factory=dict)
109
+ _sited_cases: set[int] = field(default_factory=set)
110
+ _mixed_checked: set[int] = field(default_factory=set)
111
+ _mixed_cases: list[tuple[AttachmentSite, str]] = field(default_factory=list)
112
+ # Each scalar subquery lowered as a join, by id, and the qualifier of the
113
+ # binding that holds its value.
114
+ _scalar_values: dict[int, str] = field(default_factory=dict)
115
+ # Each aggregate call and grouping-determined column of the grouped
116
+ # select item being lowered, by id, and its value per group (`_lower_grouped`).
117
+ _grouped_values: dict[int, ir.ScalarExpr] = field(default_factory=dict)
118
+ # Each set-returning call of a select list, by id, and the qualifier of the
119
+ # binding that holds the values it returns.
120
+ _set_returning_values: dict[int, str] = field(default_factory=dict)
121
+ _scalar_subqueries: list[tuple[AttachmentSite, ir.Join]] = field(default_factory=list)
122
+ _sort_keys: dict[int, tuple[ir.OutputColumn, ...] | None] = field(default_factory=dict)
123
+ _site_sort_keys: dict[AttachmentSite, tuple[ir.OutputColumn, ...] | None] = field(default_factory=dict)
124
+ _set_operations: list[tuple[AttachmentSite, ir.SetOperation]] = field(default_factory=list)
125
+ _last_operands: list[tuple[AttachmentSite, ir.RelationExpr, str]] = field(default_factory=list)
126
+ _unsupported: list[tuple[ir.Node, str]] = field(default_factory=list)
127
+ # Joins written inside a SELECT that lowered opaque, with its construct.
128
+ _orphan_joins: list[tuple[ir.Join, str]] = field(default_factory=list)
129
+ # Columns made up for names a query uses: of a table with no CREATE, or an
130
+ # opaque relation (`_guessed`), and those a declared table does not have (`_absent`).
131
+ _guessed: set[ir.OutputColumn] = field(default_factory=set)
132
+ # A scalar subquery's columns, each bound to the scope that owns it.
133
+ _scoped_columns: dict[int, ir.OutputColumn] = field(default_factory=dict)
134
+ _absent: set[ir.OutputColumn] = field(default_factory=set)
135
+ # Each declared table column's type, as its CREATE TABLE writes it.
136
+ _declared_types: dict[ir.OutputColumn, exp.DataType] = field(default_factory=dict)
137
+ # Every set operation's output column: it refers to its left input only,
138
+ # so the left input's declared type need not describe its values.
139
+ _set_outputs: set[ir.OutputColumn] = field(default_factory=set)
140
+ # The comparisons already checked for a zoned timestamp's text, by id.
141
+ _zone_checked: set[int] = field(default_factory=set)
142
+ _untyped_calls: set[int] = field(default_factory=set)
143
+ # Each composite column or CAST a comparison reads, by id, with the
144
+ # comparison: a warning unless its elements are declared non-null.
145
+ _composite_comparisons: dict[int, tuple[Origin, str, str, ir.ScalarExpr]] = field(default_factory=dict)
146
+ _marker_targets: dict[int, _Symbol] = field(default_factory=dict)
147
+ _marker_references: list[_MarkerReference] = field(default_factory=list)
148
+ _constraint_references: list[_ConstraintReference] = field(default_factory=list)
149
+ # The USING columns merged so far, for the qualifier of each one's binding.
150
+ _using_columns: int = 0
151
+
152
+ @property
153
+ def semantics(self) -> DialectSemantics:
154
+ return semantics(self.dialect)
155
+
156
+ def parse(self, ast: ParsedProgram) -> IrConversionResult:
157
+ for statement in (*ast.create_statements, ast.root_select):
158
+ if statement is None:
159
+ continue
160
+ for node in statement.find_all(exp.Identifier):
161
+ if self.dialect == "postgres" and node.quoted and node.name != node.name.lower() and node.find_ancestor(exp.Collate, exp.CollateColumnConstraint) is None:
162
+ diagnostic = Diagnostic(diag.UNSUPPORTED_CONSTRUCT, "case-sensitive quoted PostgreSQL identifiers are not supported", self._origin(node))
163
+ return IrConversionResult(ir.Program(), (), (diagnostic,))
164
+ for collate in statement.find_all(exp.Collate, exp.CollateColumnConstraint):
165
+ # Every COLLATE warns where it is written, whatever reads it.
166
+ written = collate.find_ancestor(exp.ColumnDef) if isinstance(collate, exp.CollateColumnConstraint) else collate
167
+ self._warnings.append(Diagnostic(
168
+ diag.UNSUPPORTED_CONSTRUCT,
169
+ "COLLATE is not supported by sqlassert yet: only the dialect's default collation is, so facts that "
170
+ "compare its values are unknown",
171
+ self._origin(written or collate, _source_line(written or collate)),
172
+ ))
173
+ for table in statement.find_all(exp.Table):
174
+ if any("." in part.name for part in table.parts if isinstance(part, exp.Identifier)):
175
+ diagnostic = Diagnostic(diag.UNSUPPORTED_CONSTRUCT, "dots inside quoted relation identifiers are not supported", self._origin(table))
176
+ return IrConversionResult(ir.Program(), (), (diagnostic,))
177
+ for statement in ast.create_statements:
178
+ match statement:
179
+ case exp.Create(kind="INDEX"):
180
+ self._declare_index(statement)
181
+ case exp.Create(kind="SCHEMA"):
182
+ pass # A schema states nothing about rows, like a plain index.
183
+ case exp.Create():
184
+ self._declare(statement)
185
+ case exp.Alter():
186
+ self._alter(statement)
187
+ case _:
188
+ raise TypeError(f"Unhandled schema statement: {type(statement).__name__}")
189
+
190
+ for symbol in tuple(self._symbols):
191
+ if symbol.role is ir.RelationRole.VIEW and symbol.body is not None:
192
+ self._discover_query(symbol.body, {})
193
+ if ast.root_select is not None:
194
+ self._discover_query(ast.root_select, {})
195
+ for name, columns in self.required_relations:
196
+ self._require_undeclared(self._symbol_for_name(name, {}, Origin(SQL, name)), columns)
197
+ self._discover_constraint_references()
198
+ self._propagate_required_columns()
199
+
200
+ root = self._lower_query(ast.root_select) if ast.root_select is not None else None
201
+ # Every view is a query of its own: its markers are checked whether or
202
+ # not the root reads it, so a file of views (a project's models) needs
203
+ # no root SELECT.
204
+ for symbol in tuple(self._symbols):
205
+ if symbol.role is ir.RelationRole.VIEW and symbol not in self._named_relations:
206
+ self._resolve_symbol(symbol)
207
+ # Referenced relations are linked last: a marker on a view may name
208
+ # the view itself, or one that reads it.
209
+ self._link_constraint_references()
210
+ self._link_marker_references()
211
+ self._report_unanalyzed(ast)
212
+
213
+ named_relations = tuple(self._named_relations.get(symbol) or self._unresolved_named_relation(symbol) for symbol in self._symbols)
214
+ warnings = [*self._undeclared_table_warnings(), *self._warnings, *self._composite_warnings()]
215
+ program = ir.Program(
216
+ named_relations=named_relations, root=root, assertions=tuple(self._assertions), declarations=tuple(self._declarations), attachment_sites=tuple(self._attachment_sites),
217
+ unsupported=tuple(self._unsupported),
218
+ )
219
+ if self._orphan_joins:
220
+ # A join inside a Named Relation first lowered under an opaque SELECT is still in the program.
221
+ reachable = frozenset(program.nodes())
222
+ orphans = tuple((join, construct) for join, construct in self._orphan_joins if join not in reachable)
223
+ program = replace(program, unsupported=(*program.unsupported, *orphans))
224
+ return IrConversionResult(
225
+ program, tuple(self._knowledge), tuple(self._diagnostics), tuple(dict.fromkeys(warnings)),
226
+ syntax=self._syntax, scalar_subqueries=tuple(self._scalar_subqueries), sort_keys=self._site_sort_keys,
227
+ set_operations=tuple(self._set_operations), last_operands=tuple(self._last_operands), mixed_cases=tuple(self._mixed_cases),
228
+ )
229
+
230
+ def _undeclared_table_warnings(self) -> list[Diagnostic]:
231
+ return [
232
+ Diagnostic(
233
+ diag.UNDECLARED_TABLE,
234
+ f"table {symbol.name} has no CREATE TABLE in the program, so its keys, nullability and column types are unknown: "
235
+ "declare it with CREATE TABLE, or analyze with a database connection (analyze_database)",
236
+ replace(symbol.origin, line=symbol.first_line or symbol.origin.line),
237
+ )
238
+ for symbol in self._symbols
239
+ if symbol.role is ir.RelationRole.TABLE and symbol.statement is None
240
+ ]
241
+
242
+ def _placed(self, node: Expr) -> Origin:
243
+ """`node`'s Origin with where it is written, for a relation an
244
+ explanation points at (`rules/causes`)."""
245
+ return _placed(self._origin(node), node)
246
+
247
+ def _origin(self, node: Expr, line: int | None = None) -> Origin:
248
+ # A star's expansion names a merged USING column by a qualifier no SQL can write (`_merge_using`).
249
+ 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"}