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.
Files changed (65) hide show
  1. sqlassert/__init__.py +1 -2
  2. sqlassert/check.py +88 -13
  3. sqlassert/diagnostics.py +17 -6
  4. sqlassert/dialects.py +437 -7
  5. sqlassert/discovery/bigquery.py +3 -1
  6. sqlassert/discovery/databricks.py +25 -2
  7. sqlassert/discovery/duckdb.py +49 -7
  8. sqlassert/discovery/fetcher.py +130 -21
  9. sqlassert/discovery/information_schema.py +30 -2
  10. sqlassert/discovery/mysql.py +22 -1
  11. sqlassert/discovery/postgres.py +22 -5
  12. sqlassert/discovery/redshift.py +3 -2
  13. sqlassert/discovery/snowflake.py +3 -0
  14. sqlassert/discovery/trino.py +2 -2
  15. sqlassert/hazards.py +248 -87
  16. sqlassert/ir/__init__.py +4 -1
  17. sqlassert/ir/convert/__init__.py +13 -0
  18. sqlassert/ir/convert/aggregation.py +439 -0
  19. sqlassert/ir/convert/builtins.py +140 -0
  20. sqlassert/ir/convert/expressions.py +572 -0
  21. sqlassert/ir/convert/joins.py +264 -0
  22. sqlassert/ir/convert/markers.py +249 -0
  23. sqlassert/ir/convert/parser.py +253 -0
  24. sqlassert/ir/convert/queries.py +259 -0
  25. sqlassert/ir/convert/schema.py +606 -0
  26. sqlassert/ir/convert/scopes.py +205 -0
  27. sqlassert/ir/convert/selects.py +337 -0
  28. sqlassert/ir/convert/shared.py +429 -0
  29. sqlassert/ir/convert/sources.py +432 -0
  30. sqlassert/ir/convert/subqueries.py +364 -0
  31. sqlassert/ir/convert/value_types.py +223 -0
  32. sqlassert/ir/convert/windows.py +275 -0
  33. sqlassert/ir/model.py +125 -47
  34. sqlassert/ir/names.py +63 -0
  35. sqlassert/properties.py +12 -1
  36. sqlassert/provenance.py +5 -1
  37. sqlassert/python_engine.py +104 -44
  38. sqlassert/reporting.py +33 -32
  39. sqlassert/rewrites.py +111 -61
  40. sqlassert/rules/STYLEGUIDE.md +3 -2
  41. sqlassert/rules/causes/__init__.py +41 -0
  42. sqlassert/rules/causes/coverage.py +113 -0
  43. sqlassert/rules/causes/domain.py +123 -0
  44. sqlassert/rules/causes/joins.py +73 -0
  45. sqlassert/rules/causes/nulls.py +154 -0
  46. sqlassert/rules/causes/unique.py +523 -0
  47. sqlassert/rules/domain.py +8 -7
  48. sqlassert/rules/equality.py +6 -147
  49. sqlassert/rules/exactly_one.py +2 -1
  50. sqlassert/rules/foreign_key.py +8 -9
  51. sqlassert/rules/join_cardinality.py +282 -41
  52. sqlassert/rules/nullability.py +5 -5
  53. sqlassert/rules/uniqueness.py +171 -47
  54. sqlassert/rules/value_typing.py +337 -0
  55. sqlassert/sql_parse.py +28 -1
  56. sqlassert/suggest.py +11 -15
  57. sqlassert-0.4.1.dist-info/METADATA +235 -0
  58. sqlassert-0.4.1.dist-info/RECORD +69 -0
  59. sqlassert/ir/convert.py +0 -3509
  60. sqlassert-0.3.3.dist-info/METADATA +0 -807
  61. sqlassert-0.3.3.dist-info/RECORD +0 -46
  62. {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/WHEEL +0 -0
  63. {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/entry_points.txt +0 -0
  64. {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/licenses/LICENSE +0 -0
  65. {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.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,337 @@
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 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 DuckDB's EXCLUDE, REPLACE
27
+ and RENAME) 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
+ if any(any(star.args.values()) for star in stars) and (self.dialect != "duckdb" or grouped or not lowered.relation.is_schema_complete):
37
+ return None
38
+ if not lowered.relation.is_schema_complete:
39
+ return items, None # Connection Warnings say which columns are missing.
40
+ if grouped:
41
+ return items, _GROUPED_STAR
42
+ expanded: list[Expr] = []
43
+ unexpanded = None
44
+ renamed = False
45
+ for item in items:
46
+ star = _projection_star(item)
47
+ columns = None if star is None else _star_expansion(item, star, lowered)
48
+ if columns is None:
49
+ expanded.append(item)
50
+ elif isinstance(columns, str):
51
+ assert star is not None
52
+ if any(star.args.values()):
53
+ return None
54
+ expanded.append(item)
55
+ unexpanded = unexpanded or columns
56
+ else:
57
+ expanded.extend(columns[0])
58
+ renamed |= columns[1]
59
+ if renamed and any(not isinstance(item, exp.Alias | exp.Column) for item in expanded):
60
+ return None # A downstream SELECT may see DuckDB's generated names, which a renamed column may repeat.
61
+ return expanded, unexpanded
62
+
63
+ def _lower_select_tail(self: IrParser, lowered: _Lowered, select: exp.Select) -> ir.RelationExpr:
64
+ if select.args.get("laterals"):
65
+ # Hive and Spark's LATERAL VIEW repeats each row per generated value.
66
+ opaque = self._opaque_relation(select, _selected_output_names(select))
67
+ self._unsupported.append((opaque, "LATERAL VIEW"))
68
+ return opaque
69
+ keys = grouping(select)
70
+ items = select.expressions
71
+ unexpanded = None
72
+ if any(_projection_star(item) is not None for item in items):
73
+ expansion = self._expand_stars(items, lowered, grouped=keys is not None)
74
+ if expansion is None:
75
+ opaque = self._opaque_relation(select)
76
+ self._unsupported.append((opaque, "a modified star projection"))
77
+ return opaque
78
+ items, unexpanded = expansion
79
+ calls = [call for item in items for call in _set_returning_calls(item, self.dialect)]
80
+ if calls:
81
+ if keys is not None or isinstance(select.args.get("qualify"), exp.Qualify) or (
82
+ select.args.get("distinct") is not None and select.args["distinct"].args.get("on") is not None
83
+ ):
84
+ # Evaluated after grouping or a window: not modelled.
85
+ opaque = self._opaque_relation(select, _selected_output_names(select))
86
+ self._unsupported.append((opaque, "a set-returning function beside GROUP BY, QUALIFY or DISTINCT ON"))
87
+ return opaque
88
+ lowered = self._fan_out(lowered, calls, self._origin(select))
89
+ if keys is not None:
90
+ relation = self._qualified(self._lower_aggregate(lowered, select, keys), select, items, grouped=True)
91
+ distinct = select.args.get("distinct")
92
+ if relation is not None and distinct is not None and distinct.args.get("on") is not None:
93
+ # DISTINCT ON keeps one group per key, by an ORDER BY not modelled:
94
+ # it drops groups, keeping every fact of the ones left.
95
+ origin = self._origin(distinct)
96
+ relation = ir.Filter(
97
+ origin=origin, output_columns=_pass_output_columns(relation.output_columns, origin),
98
+ is_schema_complete=True, input=relation,
99
+ predicate=ir.OpaqueExpression(origin=origin, description=distinct.sql(dialect=self.dialect)),
100
+ )
101
+ elif select.args.get("distinct") is not None and select.args["distinct"].args.get("on") is not None:
102
+ relation = self._lower_distinct_on(lowered, select, items, select.args["distinct"].args["on"])
103
+ elif select.args.get("distinct") is not None:
104
+ relation = self._qualified(self._lower_distinct(lowered, select, items), select, items, grouped=False)
105
+ elif isinstance(select.args.get("qualify"), exp.Qualify):
106
+ relation = self._lower_qualify(lowered, select, items, select.args["qualify"])
107
+ else:
108
+ if select.args.get("where") is not None:
109
+ lowered = self._filter(lowered, select.args["where"])
110
+ if _star_only(select) and (not lowered.relation.is_schema_complete or not any(binding.shadowed for binding in lowered.bindings)):
111
+ relation = lowered.relation # Exact whatever the columns are called.
112
+ unexpanded = None
113
+ else:
114
+ lowered, _ = self._join_scalar_subqueries(lowered, items)
115
+ relation = self._project(lowered, items, self._placed(select))
116
+ if relation is None:
117
+ opaque = self._opaque_relation(select, _selected_output_names(select))
118
+ self._unsupported.append((opaque, _unsupported_grouping(select) or _unsupported_select(select, items, unexpanded)))
119
+ return opaque
120
+ if unexpanded is not None:
121
+ self._unsupported.append((relation, unexpanded))
122
+ self._sort_keys[id(select)] = self._resolve_order(select, items, lowered.bindings, relation)
123
+ return relation
124
+
125
+ def _resolve_order(
126
+ self: IrParser, select: exp.Select, projections: list[Expr], bindings: tuple[_Binding, ...], relation: ir.RelationExpr
127
+ ) -> tuple[ir.OutputColumn, ...] | None:
128
+ """Each ORDER BY key as a column of the stage it sorts (see
129
+ `IrConversionResult.sort_keys`): a selected column by its name or position, else
130
+ the column a name binds, qualifier and schema included."""
131
+ order = select.args.get("order")
132
+ if order is None:
133
+ return ()
134
+ distinct = select.args.get("distinct")
135
+ if distinct is not None and distinct.args.get("on") is not None:
136
+ return None # Its ORDER BY picks the row each group keeps.
137
+ scope = relation.input if isinstance(relation, ir.Project) else relation
138
+ outputs = relation.output_columns
139
+ items = [item for item in projections if not isinstance(item, exp.Star)]
140
+ keys: list[ir.OutputColumn] = []
141
+ for ordered in order.expressions:
142
+ expression = ordered.this if isinstance(ordered, exp.Ordered) else ordered
143
+ key: ir.OutputColumn | None = None
144
+ match expression:
145
+ case exp.Column(table="") if len(items) == len(outputs) and [item.alias_or_name.lower() for item in items].count(expression.name.lower()) == 1:
146
+ names = [item.alias_or_name.lower() for item in items]
147
+ key = _in_scope(outputs[names.index(expression.name.lower())], scope)
148
+ case exp.Literal(is_int=True) if len(items) == len(outputs) and 1 <= int(expression.this) <= len(outputs):
149
+ key = _in_scope(outputs[int(expression.this) - 1], scope)
150
+ case exp.Column():
151
+ schema, name = _schema_path(expression), expression.name.lower()
152
+ bound = [
153
+ binding for binding in bindings
154
+ if binding.name == name and (binding.qualifier == expression.table.lower() if expression.table else not binding.shadowed)
155
+ and (not schema or binding.schema == schema)
156
+ ]
157
+ if len(bound) == 1 and _renamed(bindings, expression.table.lower(), schema, name) is None:
158
+ key = _carrying(bound[0].column, scope)
159
+ case _:
160
+ pass
161
+ if key is None:
162
+ return None
163
+ keys.append(key)
164
+ return tuple(keys)
165
+
166
+ def _fan_out(self: IrParser, lowered: _Lowered, calls: list[Expr], origin: Origin) -> _Lowered:
167
+ """A select list's set-returning calls repeat each input row once per
168
+ value they return (none for none; several are zipped, padded with
169
+ NULL): a cross join with an opaque relation of their values. The rows
170
+ keep no key, the input's other columns keep their facts, and each
171
+ call's value is that relation's column, no function of its arguments."""
172
+ names = tuple(f"value{index}" for index in range(len(calls)))
173
+ values = ir.OpaqueRelation(
174
+ origin=origin, output_columns=self._opaque_output_columns(names, origin), is_schema_complete=True,
175
+ description="rows of " + ", ".join(call.sql(dialect=self.dialect) for call in calls),
176
+ )
177
+ input_columns = lowered.relation.output_columns + values.output_columns
178
+ output_columns = _pass_output_columns(input_columns, origin)
179
+ remapped = dict(zip(input_columns, output_columns))
180
+ join = ir.Join(
181
+ origin=origin, output_columns=output_columns, is_schema_complete=lowered.relation.is_schema_complete,
182
+ kind="cross", left=lowered.relation, right=values, predicate=None,
183
+ )
184
+ bindings = [replace(binding, column=remapped[binding.column]) for binding in lowered.bindings]
185
+ for call, column in zip(calls, values.output_columns):
186
+ qualifier = f"{_SET_RETURNING_QUALIFIER}{len(self._set_returning_values)}"
187
+ self._set_returning_values[id(call)] = qualifier
188
+ bindings.append(_Binding(qualifier, _SET_RETURNING_QUALIFIER, remapped[column]))
189
+ return _Lowered(join, tuple(bindings))
190
+
191
+ def _project(self: IrParser, lowered: _Lowered, items: list[Expr], origin: Origin) -> ir.Project:
192
+ output_columns = self._selected_output_columns(items, lowered)
193
+ return ir.Project(origin=origin, output_columns=output_columns, is_schema_complete=True, input=lowered.relation)
194
+
195
+ def _selected_output_columns(self: IrParser, items: list[Expr], lowered: _Lowered) -> tuple[ir.OutputColumn, ...]:
196
+ columns = []
197
+ for item in items:
198
+ expression = item.this if isinstance(item, exp.Alias) else item
199
+ value = self._lower_expression(expression, lowered.bindings, schema_complete=lowered.relation.is_schema_complete)
200
+ columns.append(self._output_column(item, expression, value))
201
+ self._state_row_numbers(items, columns)
202
+ return tuple(columns)
203
+
204
+ def _output_column(self: IrParser, item: Expr, expression: Expr, value: ir.ScalarExpr) -> ir.OutputColumn:
205
+ """The output column of a select item (`value` is `expression` lowered).
206
+ It has no declared type: it has its expression's (`rules/value_typing.py`),
207
+ whether it is a projected item or a grouping key. Only the declared
208
+ SQL type of a CAST, window or fixed-result call is recorded, for the
209
+ hazards that compare declared types (`_declared_type`)."""
210
+ column = ir.OutputColumn(origin=self._placed(item), name=item.alias_or_name, scalar_expr=value)
211
+ while isinstance(expression, exp.Paren):
212
+ expression = expression.this
213
+ kind: exp.DataType | None = None
214
+ match expression:
215
+ case exp.Cast():
216
+ kind = expression.to
217
+ case exp.Window() if _row_number_window(expression) is not None:
218
+ kind = exp.DataType.build("BIGINT", dialect=self.dialect)
219
+ case _:
220
+ kind = self._result_type(expression)
221
+ if kind is not None:
222
+ self._declared_types[column] = kind
223
+ return column
224
+
225
+
226
+ def _unsupported_select(select: exp.Select, items: list[Expr], star: str | None) -> str:
227
+ """The QUALIFY or DISTINCT ON form that makes `select` opaque, else the
228
+ clauses it is written with: one of them is not modelled in this form.
229
+ `star` is why a star stayed one item although its columns are known."""
230
+ qualify = select.args.get("qualify")
231
+ distinct = select.args.get("distinct")
232
+ 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
233
+ if clause is not None and grouping(select) is None:
234
+ if select.args.get("having") is not None:
235
+ return f"{clause} with HAVING"
236
+ if _only_star(items):
237
+ return star or f"{clause} on SELECT * over columns not all known"
238
+ return f"{clause} beside an aggregate without GROUP BY"
239
+ if star is not None and _only_star(items):
240
+ return star
241
+ clauses = [
242
+ name for key, name in (("distinct", "DISTINCT"), ("group", "GROUP BY"), ("having", "HAVING"), ("qualify", "QUALIFY"))
243
+ if select.args.get(key)
244
+ ]
245
+ if any(_projection_star(item) is not None for item in select.expressions):
246
+ clauses.append("*")
247
+ return f"this SELECT form ({', '.join(clauses)})" if clauses else "this SELECT form"
248
+ # The constructs a star that stays one select item is reported as.
249
+ _UNNAMEABLE_STAR = "a star whose columns cannot each be named unambiguously"
250
+ _GROUPED_STAR = "a star in a GROUP BY select"
251
+
252
+
253
+ # A set-returning call's value binding: no SQL name can match it.
254
+ _SET_RETURNING_QUALIFIER = "\0rows"
255
+
256
+
257
+ def _in_scope(column: ir.OutputColumn, scope: ir.RelationExpr) -> ir.OutputColumn | None:
258
+ """`column` as a column of `scope`: itself, or the input column it passes on."""
259
+ if column in scope.output_columns:
260
+ return column
261
+ match column.scalar_expr:
262
+ case ir.ColumnRef(column=upstream) if upstream in scope.output_columns:
263
+ return upstream
264
+ case _:
265
+ return None
266
+
267
+
268
+ def _carrying(column: ir.OutputColumn, scope: ir.RelationExpr) -> ir.OutputColumn | None:
269
+ """The one column of `scope` that passes `column` on, through any stages."""
270
+ found = []
271
+ for candidate in scope.output_columns:
272
+ current = candidate
273
+ while current is not column and isinstance(current.scalar_expr, ir.ColumnRef):
274
+ current = current.scalar_expr.column
275
+ if current is column:
276
+ found.append(candidate)
277
+ return found[0] if len(found) == 1 else None
278
+
279
+
280
+ def _star_expansion(item: Expr, star: exp.Star, lowered: _Lowered) -> tuple[list[Expr], bool] | str:
281
+ """The select items a star stands for, one per column in the input's
282
+ order, and whether any is renamed; else why it stays one item.
283
+
284
+ Each item is written as its column's qualified name and carries the
285
+ column itself (`_Carried`), which its lowering binds: a derived table's
286
+ repeat, which no name reaches, is carried on to the next relation so.
287
+ Modifiers (DuckDB's) act on the star's own columns, each named by exactly
288
+ one of them, never by a name an engine may have given a repeat."""
289
+ bindings = lowered.bindings
290
+ if isinstance(item, exp.Column):
291
+ # `a.*` selects all of a's columns, a USING column's own side included.
292
+ schema = _schema_path(item)
293
+ bindings = tuple(b for b in bindings if b.qualifier == item.table.lower() and (not schema or b.schema == schema))
294
+ else:
295
+ bindings = tuple(b for b in bindings if not b.shadowed) # A USING column once, where `_merge_using` put it.
296
+ covered = {b.column for b in lowered.bindings}
297
+ if not bindings or any(b.name == "*" for b in bindings) or not all(column in covered for column in lowered.relation.output_columns):
298
+ return _UNNAMEABLE_STAR
299
+
300
+ def find(name: str, qualifier: str = "", schema: str = "") -> int | None:
301
+ if _renamed(bindings, qualifier, schema, name) is not None:
302
+ return None # May be a name the engine gave a repeated column.
303
+ found = [index for index, b in enumerate(bindings) if _named((b,), qualifier or b.qualifier, name, schema)]
304
+ return found[0] if len(found) == 1 else None
305
+
306
+ def star_column(column: Expr) -> int | None:
307
+ return find(column.name.lower(), column.table.lower(), _schema_path(column)) if isinstance(column, exp.Column) else None
308
+
309
+ excluded = {star_column(column) for column in star.args.get("except_") or ()}
310
+ replaced = {find(alias.alias.lower()): alias for alias in star.args.get("replace") or ()}
311
+ renamed = {star_column(alias.this): alias.args.get("alias") for alias in star.args.get("rename") or ()}
312
+ if (
313
+ star.args.get("ilike") or None in excluded or None in replaced or None in renamed
314
+ or len(excluded) != len(star.args.get("except_") or ()) or len(replaced) != len(star.args.get("replace") or ())
315
+ or len(renamed) != len(star.args.get("rename") or ())
316
+ or any(not isinstance(target, exp.Identifier) for target in renamed.values())
317
+ or excluded & replaced.keys() or excluded & renamed.keys() or replaced.keys() & renamed.keys()
318
+ ):
319
+ return _UNNAMEABLE_STAR
320
+ columns: list[Expr] = []
321
+ for index, binding in enumerate(bindings):
322
+ if index in excluded:
323
+ continue
324
+ expression = replaced.get(index)
325
+ if expression is None:
326
+ catalog, _, db = binding.schema.rpartition(".")
327
+ expression = exp.column(binding.column.name, binding.qualifier, db or None, catalog or None, quoted=True)
328
+ expression.meta["star"] = _Carried(binding.column) # Also `_partition_plan`: a name it writes may be this column's.
329
+ if (target := renamed.get(index)) is not None:
330
+ expression = exp.Alias(this=expression, alias=target.copy())
331
+ columns.append(expression)
332
+ return (columns, bool(renamed)) if columns else _UNNAMEABLE_STAR # No column left is no select item.
333
+
334
+
335
+ def _named(bindings: Iterable[_Binding], qualifier: str, name: str, schema: str) -> list[_Binding]:
336
+ """The bindings a column written `schema.qualifier.name` reads."""
337
+ return [b for b in bindings if b.qualifier == qualifier and b.name == name and (not schema or b.schema == schema)]