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,205 @@
1
+ """Symbol discovery before lowering: each query's scope of tables, views and
2
+ CTEs, the relations Foreign Key markers reference, and the columns each
3
+ source is required to have."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from collections.abc import Iterable
8
+ from typing import TYPE_CHECKING
9
+
10
+ from sqlglot import Expr, exp
11
+
12
+ from sqlassert import ir
13
+ from sqlassert.provenance import Origin, SQL
14
+ from sqlassert.sql_parse import column_markers
15
+ from sqlassert.ir.convert.shared import (
16
+ _Symbol, _placed, _source_line, _subquery_conjunct, _filter_conjuncts, _direct_sources, _flattened, _join_levels, _aliased_join, _is_named_table,
17
+ _column_aliases, _qualified_name, _unwrap_query, _arg, _scalar_subqueries, _star_only,
18
+ )
19
+
20
+ if TYPE_CHECKING:
21
+ from sqlassert.ir.convert.parser import IrParser
22
+
23
+
24
+ class _Scopes:
25
+ def _discover_marker_targets(self: IrParser, query: exp.Query, scope: dict[str, _Symbol]) -> None:
26
+ """The relation each Foreign Key marker on `query` references."""
27
+ for marker in column_markers(query):
28
+ if marker.referenced_relation is not None:
29
+ origin = Origin.marked(marker.referenced_relation, marker.span)
30
+ target = self._symbol_for_name(marker.referenced_relation, scope, origin)
31
+ self._marker_targets[id(marker)] = target
32
+ self._require_undeclared(target, marker.referenced_columns)
33
+
34
+ def _discover_query(self: IrParser, query: exp.Query, inherited_scope: dict[str, _Symbol]) -> None:
35
+ if id(query) in self._query_scopes:
36
+ return
37
+
38
+ scope = dict(inherited_scope)
39
+ with_clause = _arg(query, "with")
40
+ if with_clause is not None:
41
+ bodies = []
42
+ recursive = bool(with_clause.args.get("recursive"))
43
+ forward = recursive and self.dialect != "duckdb"
44
+ for cte in with_clause.expressions:
45
+ body = _unwrap_query(cte.this)
46
+ duckdb_recursive = recursive and not forward and isinstance(body, exp.Union)
47
+ if not forward:
48
+ if duckdb_recursive and isinstance(body, exp.Union):
49
+ # The seed is outside the recursive name's scope.
50
+ seed = _unwrap_query(body.this)
51
+ if seed is not None and _arg(body, "with") is None:
52
+ self._discover_query(seed, scope)
53
+ elif body is not None:
54
+ self._discover_query(body, scope)
55
+ symbol = _Symbol(
56
+ name=cte.alias,
57
+ role=ir.RelationRole.CTE,
58
+ origin=_placed(Origin(SQL, cte.sql(dialect=self.dialect)), cte.args.get("alias")),
59
+ body=cte.this if body is not None else None,
60
+ column_aliases=_column_aliases(cte),
61
+ )
62
+ scope[cte.alias.lower()] = symbol
63
+ self._symbols.append(symbol)
64
+ if forward and body is not None:
65
+ bodies.append(body)
66
+ elif duckdb_recursive and body is not None:
67
+ self._discover_query(body, scope)
68
+ for body in bodies:
69
+ self._discover_query(body, scope)
70
+
71
+ self._query_scopes[id(query)] = scope
72
+ if isinstance(query, exp.Subquery):
73
+ # A parenthesised query: its body is what lowers (`_lower_query`).
74
+ inner = _unwrap_query(query)
75
+ if inner is not None:
76
+ self._discover_query(inner, scope)
77
+ return
78
+ if isinstance(query, exp.SetOperation):
79
+ # SQLGlot 30 wraps a nested set operation in a Subquery.
80
+ for side in (query.this, query.expression):
81
+ inner = _unwrap_query(side)
82
+ if inner is not None:
83
+ self._discover_query(inner, scope)
84
+ self._discover_marker_targets(query, scope)
85
+ return
86
+ if not isinstance(query, exp.Select):
87
+ return
88
+
89
+ sources = _direct_sources(query)
90
+ by_qualifier: dict[str, list[Expr]] = {}
91
+ for source in [*sources, *(hidden for source in sources for hidden in _hidden_sources(source))]:
92
+ self._source_required.setdefault(id(source), set())
93
+ self._source_expressions[id(source)] = source
94
+ qualifier = source.alias_or_name.lower()
95
+ if qualifier:
96
+ by_qualifier.setdefault(qualifier, []).append(source)
97
+ if _is_named_table(source):
98
+ symbol = self._symbol_for_table(source, scope)
99
+ self._table_symbols[id(source)] = symbol
100
+ elif isinstance(source, exp.Subquery):
101
+ body = _unwrap_query(source)
102
+ if body is not None:
103
+ self._discover_query(body, scope)
104
+
105
+ for column in query.find_all(exp.Column):
106
+ if isinstance(column.this, exp.Star):
107
+ continue # `a.*` selects a's columns; SQLGlot parses it as a column named `*`.
108
+ if column.table:
109
+ matching = by_qualifier.get(column.table.lower(), ())
110
+ for source in matching:
111
+ self._require(source, column.name)
112
+ elif len(sources) == 1 and column.find_ancestor(exp.Select) is query:
113
+ # An unqualified column in a nested query belongs to that query's scope.
114
+ self._require(sources[0], column.name)
115
+
116
+ for joins, level in _join_levels(query):
117
+ for join in joins:
118
+ for identifier in join.args.get("using") or ():
119
+ for source in level:
120
+ self._require(source, identifier.name)
121
+
122
+ if len(sources) == 1 and _star_only(query):
123
+ for marker in column_markers(query):
124
+ for column in (*marker.columns, *marker.dependent):
125
+ self._require(sources[0], column)
126
+
127
+ self._discover_marker_targets(query, scope)
128
+
129
+ where = query.args.get("where")
130
+ for conjunct in _filter_conjuncts(where.this) if where is not None else ():
131
+ matched = _subquery_conjunct(conjunct)
132
+ if matched is not None:
133
+ self._discover_query(matched[1], scope)
134
+ for expression in (*(_filter_conjuncts(where.this) if where is not None else ()), *query.expressions):
135
+ for subquery in _scalar_subqueries(expression):
136
+ if isinstance(subquery.this, exp.Select):
137
+ self._discover_query(subquery.this, scope)
138
+
139
+ def _symbol_for_table(self: IrParser, table: exp.Table, scope: dict[str, _Symbol]) -> _Symbol:
140
+ symbol = self._symbol_for_name(_qualified_name(table), scope, Origin(SQL, table.sql(dialect=self.dialect)))
141
+ if symbol.first_line is None:
142
+ symbol.first_line = _source_line(table)
143
+ return symbol
144
+
145
+ def _symbol_for_name(self: IrParser, name: str, scope: dict[str, _Symbol], origin: Origin) -> _Symbol:
146
+ key = name.lower()
147
+ if key in scope:
148
+ return scope[key]
149
+ symbol = self._global_symbols.get(key)
150
+ if symbol is None:
151
+ symbol = _Symbol(name=name, role=ir.RelationRole.TABLE, origin=origin)
152
+ self._global_symbols[key] = symbol
153
+ self._symbols.append(symbol)
154
+ return symbol
155
+
156
+ def _require_undeclared(self: IrParser, symbol: _Symbol, columns: Iterable[str]) -> None:
157
+ """Referenced columns become columns of an undeclared table only: a
158
+ declared relation's schema is never widened by a reference to it."""
159
+ if symbol.role is ir.RelationRole.TABLE and symbol.statement is None:
160
+ symbol.required_columns.update(columns)
161
+
162
+ def _require(self: IrParser, source: Expr, column: str) -> None:
163
+ self._source_required.setdefault(id(source), set()).add(column)
164
+ if _is_named_table(source) and column.lower() not in {name.lower() for name in _column_aliases(source)}:
165
+ symbol = self._table_symbols[id(source)]
166
+ # A declared table's columns are its CREATE's: a reference never widens them.
167
+ if not (symbol.role is ir.RelationRole.TABLE and symbol.statement is not None):
168
+ symbol.required_columns.add(column)
169
+
170
+ def _propagate_required_columns(self: IrParser) -> None:
171
+ """Push requested output columns through star-only view/CTE/subquery bodies."""
172
+ changed = True
173
+ while changed:
174
+ before = sum(len(symbol.required_columns) for symbol in self._symbols) + sum(len(columns) for columns in self._source_required.values())
175
+ for symbol in self._symbols:
176
+ body = _unwrap_query(symbol.body)
177
+ if isinstance(body, exp.Select) and _star_only(body):
178
+ sources = _direct_sources(body)
179
+ if len(sources) == 1:
180
+ aliases = {name.lower() for name in symbol.column_aliases}
181
+ for column in symbol.required_columns:
182
+ if column.lower() not in aliases:
183
+ self._require(sources[0], column)
184
+ for source_id, columns in tuple(self._source_required.items()):
185
+ source = self._source_expressions[source_id]
186
+ body = _unwrap_query(source) if isinstance(source, exp.Subquery) else None
187
+ if isinstance(body, exp.Select) and _star_only(body):
188
+ nested_sources = _direct_sources(body)
189
+ if len(nested_sources) == 1:
190
+ aliases = {name.lower() for name in _column_aliases(source)}
191
+ for column in columns:
192
+ if column.lower() not in aliases:
193
+ self._require(nested_sources[0], column)
194
+ after = sum(len(symbol.required_columns) for symbol in self._symbols) + sum(len(columns) for columns in self._source_required.values())
195
+ changed = after != before
196
+
197
+
198
+ def _hidden_sources(source: Expr) -> list[Expr]:
199
+ """The sources inside an aliased parenthesized join, at any depth: their
200
+ names are visible only inside it."""
201
+ nested = _aliased_join(source)
202
+ if nested is None:
203
+ return []
204
+ inner = _flattened([nested[0], *(join.this for join in nested[1])])
205
+ return [*inner, *(hidden for source in inner for hidden in _hidden_sources(source))]
@@ -0,0 +1,352 @@
1
+ """The select list: star expansion, set-returning calls, the projection and its
2
+ output columns, and ORDER BY keys."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from collections.abc import Iterable
7
+ from dataclasses import replace
8
+ from typing import TYPE_CHECKING
9
+
10
+ from sqlglot import Expr, exp
11
+
12
+ from sqlassert import functions, ir
13
+ from sqlassert.provenance import Origin
14
+ from sqlassert.sql_parse import grouping
15
+ from sqlassert.ir.convert.shared import (
16
+ _Binding, _Lowered, _pass_output_columns, _unsupported_grouping, _set_returning_calls, _schema_path, _projection_star, _Carried, _renamed,
17
+ _star_only, _only_star, _selected_output_names, _row_number_window,
18
+ )
19
+
20
+ if TYPE_CHECKING:
21
+ from sqlassert.ir.convert.parser import IrParser
22
+
23
+
24
+ class _Selects:
25
+ def _expand_stars(self: IrParser, items: list[Expr], lowered: _Lowered, *, grouped: bool) -> tuple[list[Expr], str | None] | None:
26
+ """`items` with each star (`*`, `t.*`, with the dialect's
27
+ `star_modifiers`) as the columns it selects, when every input column is
28
+ known (`_star_expansion`); and why a star stayed one item although
29
+ they are, which the caller reports. Each star expands on its own: one
30
+ that cannot is an opaque item beside the others' columns. Not a
31
+ modified one: its modifiers cannot be honoured, so which names the
32
+ select outputs (an excluded or renamed column is no longer, or now, a
33
+ name another item may repeat) is unknown, and the select is opaque
34
+ (None). A star in a GROUP BY select is left as it is."""
35
+ stars = [star for item in items if (star := _projection_star(item)) is not None]
36
+ modifiers = {_MODIFIERS.get(key, key) for star in stars for key, value in star.args.items() if value}
37
+ if modifiers and (not modifiers <= set(self.semantics.star_modifiers) or grouped or not lowered.relation.is_schema_complete):
38
+ return None
39
+ if not lowered.relation.is_schema_complete:
40
+ return items, None # Connection Warnings say which columns are missing.
41
+ if grouped:
42
+ return items, _GROUPED_STAR
43
+ expanded: list[Expr] = []
44
+ unexpanded = None
45
+ renamed = False
46
+ for item in items:
47
+ star = _projection_star(item)
48
+ columns = None if star is None else _star_expansion(item, star, lowered, exact=self.semantics.case_sensitive_names)
49
+ if columns is None:
50
+ expanded.append(item)
51
+ elif isinstance(columns, str):
52
+ assert star is not None
53
+ if any(star.args.values()):
54
+ return None
55
+ expanded.append(item)
56
+ unexpanded = unexpanded or columns
57
+ else:
58
+ expanded.extend(columns[0])
59
+ renamed |= columns[1]
60
+ if renamed and any(not isinstance(item, exp.Alias | exp.Column) for item in expanded):
61
+ return None # A downstream SELECT may see DuckDB's generated names, which a renamed column may repeat.
62
+ return expanded, unexpanded
63
+
64
+ def _lower_select_tail(self: IrParser, lowered: _Lowered, select: exp.Select) -> ir.RelationExpr:
65
+ if select.args.get("laterals"):
66
+ # Hive and Spark's LATERAL VIEW repeats each row per generated value.
67
+ opaque = self._opaque_relation(select, _selected_output_names(select))
68
+ self._unsupported.append((opaque, "LATERAL VIEW"))
69
+ return opaque
70
+ keys = grouping(select)
71
+ items = select.expressions
72
+ unexpanded = None
73
+ if any(isinstance(item, exp.Apply) or item.find(exp.Columns) for item in items):
74
+ # ClickHouse's `* APPLY(f)` and COLUMNS('re'), DuckDB's COLUMNS(...):
75
+ # which columns, and how many, the data's names decide.
76
+ opaque = self._opaque_relation(select)
77
+ self._unsupported.append((opaque, "a modified star projection"))
78
+ return opaque
79
+ if any(_projection_star(item) is not None for item in items):
80
+ expansion = self._expand_stars(items, lowered, grouped=keys is not None)
81
+ if expansion is None:
82
+ opaque = self._opaque_relation(select)
83
+ self._unsupported.append((opaque, "a modified star projection"))
84
+ return opaque
85
+ items, unexpanded = expansion
86
+ calls = [call for item in items for call in _set_returning_calls(item, self.dialect)]
87
+ if calls:
88
+ if keys is not None or isinstance(select.args.get("qualify"), exp.Qualify) or (
89
+ select.args.get("distinct") is not None and select.args["distinct"].args.get("on") is not None
90
+ ):
91
+ # Evaluated after grouping or a window: not modelled.
92
+ opaque = self._opaque_relation(select, _selected_output_names(select))
93
+ self._unsupported.append((opaque, "a set-returning function beside GROUP BY, QUALIFY or DISTINCT ON"))
94
+ return opaque
95
+ lowered = self._fan_out(lowered, calls, self._origin(select))
96
+ if keys is not None:
97
+ relation = self._qualified(self._lower_aggregate(lowered, select, keys), select, items, grouped=True)
98
+ distinct = select.args.get("distinct")
99
+ if relation is not None and distinct is not None and distinct.args.get("on") is not None:
100
+ # DISTINCT ON keeps one group per key, by an ORDER BY not modelled:
101
+ # it drops groups, keeping every fact of the ones left.
102
+ origin = self._origin(distinct)
103
+ relation = ir.Filter(
104
+ origin=origin, output_columns=_pass_output_columns(relation.output_columns, origin),
105
+ is_schema_complete=True, input=relation,
106
+ predicate=ir.OpaqueExpression(origin=origin, description=distinct.sql(dialect=self.dialect)),
107
+ )
108
+ elif select.args.get("distinct") is not None and select.args["distinct"].args.get("on") is not None:
109
+ relation = self._lower_distinct_on(lowered, select, items, select.args["distinct"].args["on"])
110
+ elif select.args.get("distinct") is not None:
111
+ relation = self._qualified(self._lower_distinct(lowered, select, items), select, items, grouped=False)
112
+ elif isinstance(select.args.get("qualify"), exp.Qualify):
113
+ relation = self._lower_qualify(lowered, select, items, select.args["qualify"])
114
+ else:
115
+ if select.args.get("where") is not None:
116
+ lowered = self._filter(lowered, select.args["where"])
117
+ if _star_only(select) and (not lowered.relation.is_schema_complete or not any(binding.shadowed for binding in lowered.bindings)):
118
+ relation = lowered.relation # Exact whatever the columns are called.
119
+ unexpanded = None
120
+ else:
121
+ lowered, _ = self._join_scalar_subqueries(lowered, items)
122
+ relation = self._project(lowered, items, self._placed(select))
123
+ if relation is None:
124
+ opaque = self._opaque_relation(select, _selected_output_names(select))
125
+ self._unsupported.append((opaque, _unsupported_grouping(select) or _unsupported_select(select, items, unexpanded)))
126
+ return opaque
127
+ if unexpanded is not None:
128
+ self._unsupported.append((relation, unexpanded))
129
+ self._sort_keys[id(select)] = self._resolve_order(select, items, lowered.bindings, relation)
130
+ return relation
131
+
132
+ def _resolve_order(
133
+ self: IrParser, select: exp.Select, projections: list[Expr], bindings: tuple[_Binding, ...], relation: ir.RelationExpr
134
+ ) -> tuple[ir.OutputColumn, ...] | None:
135
+ """Each ORDER BY key as a column of the stage it sorts (see
136
+ `IrConversionResult.sort_keys`): a selected column by its name or position, else
137
+ the column a name binds, qualifier and schema included."""
138
+ order = select.args.get("order")
139
+ if order is None:
140
+ return ()
141
+ distinct = select.args.get("distinct")
142
+ if distinct is not None and distinct.args.get("on") is not None:
143
+ return None # Its ORDER BY picks the row each group keeps.
144
+ scope = relation.input if isinstance(relation, ir.Project) else relation
145
+ outputs = relation.output_columns
146
+ items = [item for item in projections if not isinstance(item, exp.Star)]
147
+ keys: list[ir.OutputColumn] = []
148
+ for ordered in order.expressions:
149
+ expression = ordered.this if isinstance(ordered, exp.Ordered) else ordered
150
+ key: ir.OutputColumn | None = None
151
+ match expression:
152
+ case exp.Column(table="") if len(items) == len(outputs) and [item.alias_or_name.lower() for item in items].count(expression.name.lower()) == 1:
153
+ names = [item.alias_or_name.lower() for item in items]
154
+ key = _in_scope(outputs[names.index(expression.name.lower())], scope)
155
+ case exp.Literal(is_int=True) if len(items) == len(outputs) and 1 <= int(expression.this) <= len(outputs):
156
+ key = _in_scope(outputs[int(expression.this) - 1], scope)
157
+ case exp.Column():
158
+ schema, name = _schema_path(expression), expression.name.lower()
159
+ bound = [
160
+ binding for binding in bindings
161
+ if binding.name == name and (binding.qualifier == expression.table.lower() if expression.table else not binding.shadowed)
162
+ and (not schema or binding.schema == schema)
163
+ ]
164
+ if len(bound) == 1 and _renamed(bindings, expression.table.lower(), schema, name) is None:
165
+ key = _carrying(bound[0].column, scope)
166
+ case _:
167
+ pass
168
+ if key is None:
169
+ return None
170
+ keys.append(key)
171
+ return tuple(keys)
172
+
173
+ def _fan_out(self: IrParser, lowered: _Lowered, calls: list[Expr], origin: Origin) -> _Lowered:
174
+ """A select list's set-returning calls repeat each input row once per
175
+ value they return (none for none; several are zipped, padded with
176
+ NULL): a cross join with an opaque relation of their values. The rows
177
+ keep no key, the input's other columns keep their facts, and each
178
+ call's value is that relation's column, no function of its arguments."""
179
+ names = tuple(f"value{index}" for index in range(len(calls)))
180
+ values = ir.OpaqueRelation(
181
+ origin=origin, output_columns=self._opaque_output_columns(names, origin), is_schema_complete=True,
182
+ description="rows of " + ", ".join(call.sql(dialect=self.dialect) for call in calls),
183
+ )
184
+ input_columns = lowered.relation.output_columns + values.output_columns
185
+ output_columns = _pass_output_columns(input_columns, origin)
186
+ remapped = dict(zip(input_columns, output_columns))
187
+ join = ir.Join(
188
+ origin=origin, output_columns=output_columns, is_schema_complete=lowered.relation.is_schema_complete,
189
+ kind="cross", left=lowered.relation, right=values, predicate=None,
190
+ )
191
+ bindings = [replace(binding, column=remapped[binding.column]) for binding in lowered.bindings]
192
+ for call, column in zip(calls, values.output_columns):
193
+ qualifier = f"{_SET_RETURNING_QUALIFIER}{len(self._set_returning_values)}"
194
+ self._set_returning_values[id(call)] = qualifier
195
+ bindings.append(_Binding(qualifier, _SET_RETURNING_QUALIFIER, remapped[column]))
196
+ return _Lowered(join, tuple(bindings))
197
+
198
+ def _project(self: IrParser, lowered: _Lowered, items: list[Expr], origin: Origin) -> ir.Project:
199
+ output_columns = self._selected_output_columns(items, lowered)
200
+ return ir.Project(origin=origin, output_columns=output_columns, is_schema_complete=True, input=lowered.relation)
201
+
202
+ def _selected_output_columns(self: IrParser, items: list[Expr], lowered: _Lowered) -> tuple[ir.OutputColumn, ...]:
203
+ columns = []
204
+ for item in items:
205
+ expression = item.this if isinstance(item, exp.Alias) else item
206
+ value = self._lower_expression(expression, lowered.bindings, schema_complete=lowered.relation.is_schema_complete)
207
+ columns.append(self._output_column(item, expression, value))
208
+ self._state_row_numbers(items, columns)
209
+ return tuple(columns)
210
+
211
+ def _output_column(self: IrParser, item: Expr, expression: Expr, value: ir.ScalarExpr) -> ir.OutputColumn:
212
+ """The output column of a select item (`value` is `expression` lowered).
213
+ It has no declared type: it has its expression's (`rules/value_typing.py`),
214
+ whether it is a projected item or a grouping key. Only the declared
215
+ SQL type of a CAST, window or fixed-result call is recorded, for the
216
+ hazards that compare declared types (`_declared_type`)."""
217
+ column = ir.OutputColumn(origin=self._placed(item), name=item.alias_or_name, scalar_expr=value)
218
+ while isinstance(expression, exp.Paren):
219
+ expression = expression.this
220
+ kind: exp.DataType | None = None
221
+ match expression:
222
+ case exp.Cast():
223
+ kind = expression.to
224
+ case exp.Window() if _row_number_window(expression) is not None:
225
+ kind = exp.DataType.build("BIGINT", dialect=self.dialect)
226
+ case _:
227
+ kind = functions.result_type(self.dialect, expression)
228
+ if kind is not None:
229
+ self._declared_types[column] = kind
230
+ return column
231
+
232
+
233
+ def _unsupported_select(select: exp.Select, items: list[Expr], star: str | None) -> str:
234
+ """The QUALIFY or DISTINCT ON form that makes `select` opaque, else the
235
+ clauses it is written with: one of them is not modelled in this form.
236
+ `star` is why a star stayed one item although its columns are known."""
237
+ qualify = select.args.get("qualify")
238
+ distinct = select.args.get("distinct")
239
+ clause = "DISTINCT ON" if distinct is not None and distinct.args.get("on") is not None else "QUALIFY" if isinstance(qualify, exp.Qualify) else None
240
+ if clause is not None and grouping(select) is None:
241
+ if select.args.get("having") is not None:
242
+ return f"{clause} with HAVING"
243
+ if _only_star(items):
244
+ return star or f"{clause} on SELECT * over columns not all known"
245
+ return f"{clause} beside an aggregate without GROUP BY"
246
+ if star is not None and _only_star(items):
247
+ return star
248
+ clauses = [
249
+ name for key, name in (("distinct", "DISTINCT"), ("group", "GROUP BY"), ("having", "HAVING"), ("qualify", "QUALIFY"))
250
+ if select.args.get(key)
251
+ ]
252
+ if any(_projection_star(item) is not None for item in select.expressions):
253
+ clauses.append("*")
254
+ return f"this SELECT form ({', '.join(clauses)})" if clauses else "this SELECT form"
255
+ # A star's modifier by its SQLGlot argument (`DialectSemantics.star_modifiers`).
256
+ _MODIFIERS = {"except_": "except"}
257
+ # The constructs a star that stays one select item is reported as.
258
+ _UNNAMEABLE_STAR = "a star whose columns cannot each be named unambiguously"
259
+ _GROUPED_STAR = "a star in a GROUP BY select"
260
+
261
+
262
+ # A set-returning call's value binding: no SQL name can match it.
263
+ _SET_RETURNING_QUALIFIER = "\0rows"
264
+
265
+
266
+ def _in_scope(column: ir.OutputColumn, scope: ir.RelationExpr) -> ir.OutputColumn | None:
267
+ """`column` as a column of `scope`: itself, or the input column it passes on."""
268
+ if column in scope.output_columns:
269
+ return column
270
+ match column.scalar_expr:
271
+ case ir.ColumnRef(column=upstream) if upstream in scope.output_columns:
272
+ return upstream
273
+ case _:
274
+ return None
275
+
276
+
277
+ def _carrying(column: ir.OutputColumn, scope: ir.RelationExpr) -> ir.OutputColumn | None:
278
+ """The one column of `scope` that passes `column` on, through any stages."""
279
+ found = []
280
+ for candidate in scope.output_columns:
281
+ current = candidate
282
+ while current is not column and isinstance(current.scalar_expr, ir.ColumnRef):
283
+ current = current.scalar_expr.column
284
+ if current is column:
285
+ found.append(candidate)
286
+ return found[0] if len(found) == 1 else None
287
+
288
+
289
+ def _star_expansion(item: Expr, star: exp.Star, lowered: _Lowered, *, exact: bool = False) -> tuple[list[Expr], bool] | str:
290
+ """The select items a star stands for, one per column in the input's
291
+ order, and whether any is renamed; else why it stays one item.
292
+
293
+ Each item is written as its column's qualified name and carries the
294
+ column itself (`_Carried`), which its lowering binds: a derived table's
295
+ repeat, which no name reaches, is carried on to the next relation so.
296
+ Modifiers act on the star's own columns, each named by exactly one of
297
+ them (spelled exactly as declared where names are case-sensitive,
298
+ `exact`), never by a name an engine may have given a repeat, nor by
299
+ `q.c` where `q` also names one of them (Spark's `* EXCEPT (s.f)` drops a
300
+ field of the struct `s`)."""
301
+ bindings = lowered.bindings
302
+ if isinstance(item, exp.Column):
303
+ # `a.*` selects all of a's columns, a USING column's own side included.
304
+ schema = _schema_path(item)
305
+ bindings = tuple(b for b in bindings if b.qualifier == item.table.lower() and (not schema or b.schema == schema))
306
+ else:
307
+ bindings = tuple(b for b in bindings if not b.shadowed) # A USING column once, where `_merge_using` put it.
308
+ covered = {b.column for b in lowered.bindings}
309
+ if not bindings or any(b.name == "*" for b in bindings) or not all(column in covered for column in lowered.relation.output_columns):
310
+ return _UNNAMEABLE_STAR
311
+
312
+ def find(spelled: str, qualifier: str = "", schema: str = "") -> int | None:
313
+ name = spelled.lower()
314
+ if _renamed(bindings, qualifier, schema, name) is not None or (qualifier and any(b.name == qualifier for b in bindings)):
315
+ return None # May be a name the engine gave a repeated column, or a struct's field.
316
+ found = [index for index, b in enumerate(bindings) if _named((b,), qualifier or b.qualifier, name, schema)]
317
+ if len(found) != 1 or (exact and bindings[found[0]].column.name != spelled):
318
+ return None
319
+ return found[0]
320
+
321
+ def star_column(column: Expr) -> int | None:
322
+ return find(column.name, column.table.lower(), _schema_path(column)) if isinstance(column, exp.Column) else None
323
+
324
+ excluded = {star_column(column) for column in star.args.get("except_") or ()}
325
+ replaced = {find(alias.alias): alias for alias in star.args.get("replace") or ()}
326
+ renamed = {star_column(alias.this): alias.args.get("alias") for alias in star.args.get("rename") or ()}
327
+ if (
328
+ star.args.get("ilike") or None in excluded or None in replaced or None in renamed
329
+ or len(excluded) != len(star.args.get("except_") or ()) or len(replaced) != len(star.args.get("replace") or ())
330
+ or len(renamed) != len(star.args.get("rename") or ())
331
+ or any(not isinstance(target, exp.Identifier) for target in renamed.values())
332
+ or excluded & replaced.keys() or excluded & renamed.keys() or replaced.keys() & renamed.keys()
333
+ ):
334
+ return _UNNAMEABLE_STAR
335
+ columns: list[Expr] = []
336
+ for index, binding in enumerate(bindings):
337
+ if index in excluded:
338
+ continue
339
+ expression = replaced.get(index)
340
+ if expression is None:
341
+ catalog, _, db = binding.schema.rpartition(".")
342
+ expression = exp.column(binding.column.name, binding.qualifier, db or None, catalog or None, quoted=True)
343
+ expression.meta["star"] = _Carried(binding.column) # Also `_partition_plan`: a name it writes may be this column's.
344
+ if (target := renamed.get(index)) is not None:
345
+ expression = exp.Alias(this=expression, alias=target.copy())
346
+ columns.append(expression)
347
+ return (columns, bool(renamed)) if columns else _UNNAMEABLE_STAR # No column left is no select item.
348
+
349
+
350
+ def _named(bindings: Iterable[_Binding], qualifier: str, name: str, schema: str) -> list[_Binding]:
351
+ """The bindings a column written `schema.qualifier.name` reads."""
352
+ return [b for b in bindings if b.qualifier == qualifier and b.name == name and (not schema or b.schema == schema)]