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
sqlassert/ir/convert.py DELETED
@@ -1,3509 +0,0 @@
1
- """Link a parsed SQL program into the framework-independent relational IR.
2
-
3
- Declaration and scope discovery happens before lowering. This gives table,
4
- view, and CTE references compiler-like symbol resolution: every occurrence is
5
- a fresh Alias, while all occurrences share one memoized NamedRelation.
6
- """
7
-
8
- from __future__ import annotations
9
-
10
- import re
11
- from collections import Counter
12
- from collections.abc import Callable, Iterable, Sequence, Set
13
- from dataclasses import dataclass, field, replace
14
- from functools import cache
15
- from typing import Literal, TypeGuard, assert_never
16
-
17
- from sqlglot import Expr, exp
18
-
19
- from sqlassert import diagnostics as diag
20
- from sqlassert import ir
21
- from sqlassert.dialects import DialectSemantics, semantics
22
- from sqlassert.diagnostics import Diagnostic, quoted, quoted_all
23
- from sqlassert.properties import (
24
- EnumeratedDomain, ExactlyOneJoin, ExhaustiveCase, ForeignKey, FunctionalDependency, ManyToOneJoin, NonNullColumn, NonNullColumns, NonNullElements, NonNullUniqueSet,
25
- OneToManyJoin, OneToOneJoin, Property, ReferentialCoverage, UniqueJoin,
26
- UniqueSet,
27
- )
28
- from sqlassert.provenance import AttachmentSite, Origin, SQL
29
- from sqlassert.sql_parse import (
30
- JOIN_MARKER_NOUNS, MARKER_NOUNS, ColumnMarker, ParsedProgram, assertion_span, column_markers,
31
- exhaustive_span, grouping, join_marker_kind, join_origin, literal_value, marker_position,
32
- written_sql,
33
- )
34
-
35
-
36
- @dataclass(frozen=True)
37
- class IrConversionResult:
38
- program: ir.Program
39
- knowledge: tuple[Property, ...]
40
- diagnostics: tuple[Diagnostic, ...] = ()
41
- warnings: tuple[Diagnostic, ...] = ()
42
-
43
-
44
- @dataclass(eq=False)
45
- class _Symbol:
46
- name: str
47
- role: ir.RelationRole
48
- origin: Origin
49
- body: exp.Query | None = None
50
- statement: exp.Create | None = None
51
- column_aliases: tuple[str, ...] = ()
52
- required_columns: set[str] = field(default_factory=set)
53
- # Table-level constraints added after CREATE TABLE (ALTER TABLE, CREATE
54
- # UNIQUE INDEX), shaped like the CREATE TABLE's own, and columns set NOT NULL.
55
- constraints: list[Expr] = field(default_factory=list)
56
- not_null: set[str] = field(default_factory=set)
57
- # Where the SQL first reads it: an undeclared table's warning points there.
58
- first_line: int | None = None
59
- # Each unique index with an expression key part: its parts and statement.
60
- expression_keys: list[tuple[list[Expr], exp.Create]] = field(default_factory=list)
61
-
62
-
63
- @dataclass(frozen=True)
64
- class _Binding:
65
- qualifier: str
66
- name: str
67
- column: ir.OutputColumn
68
- # The schema (and catalog) of an unaliased table, as `s1` in `s1.t.k`.
69
- schema: str = ""
70
- # Hidden from unqualified names: a USING column's input sides, which an
71
- # unqualified name reads merged (`_merge_using`).
72
- shadowed: bool = False
73
-
74
-
75
- @dataclass(frozen=True)
76
- class _MarkerReference:
77
- """A Foreign Key marker whose referencing columns are lowered, awaiting its referenced relation."""
78
-
79
- marker: ColumnMarker
80
- kind: Literal["foreign-key", "declared-foreign-key"]
81
- origin: Origin
82
- columns: tuple[ir.OutputColumn, ...]
83
- target: _Symbol
84
- position: int
85
-
86
-
87
- @dataclass(frozen=True)
88
- class _ConstraintReference:
89
- """A `REFERENCES` constraint of a declared table onto a relation the program reaches."""
90
-
91
- table: _Symbol
92
- columns: tuple[str, ...]
93
- target: _Symbol
94
- target_columns: tuple[str, ...] | None
95
- origin: Origin
96
- # The `REFERENCES` or `FOREIGN KEY` constraint itself.
97
- node: Expr
98
-
99
-
100
- @dataclass(frozen=True)
101
- class _Lowered:
102
- relation: ir.RelationExpr
103
- bindings: tuple[_Binding, ...]
104
-
105
-
106
- @dataclass
107
- class IrParser:
108
- dialect: str
109
- # Unenforced keys and foreign keys become Property Declarations, as `RELY` makes them.
110
- trust_unenforced_keys: bool = True
111
- _global_symbols: dict[str, _Symbol] = field(default_factory=dict)
112
- _symbols: list[_Symbol] = field(default_factory=list)
113
- _query_scopes: dict[int, dict[str, _Symbol]] = field(default_factory=dict)
114
- _table_symbols: dict[int, _Symbol] = field(default_factory=dict)
115
- _source_required: dict[int, set[str]] = field(default_factory=dict)
116
- _source_expressions: dict[int, Expr] = field(default_factory=dict)
117
- _named_relations: dict[_Symbol, ir.NamedRelation] = field(default_factory=dict)
118
- _resolving: set[_Symbol] = field(default_factory=set)
119
- _knowledge: list[Property] = field(default_factory=list)
120
- _assertions: list[ir.Assertion] = field(default_factory=list)
121
- _declarations: list[Property] = field(default_factory=list)
122
- _diagnostics: list[Diagnostic] = field(default_factory=list)
123
- _warnings: list[Diagnostic] = field(default_factory=list)
124
- _handled_column_markers: set[int] = field(default_factory=set)
125
- _handled_joins: set[int] = field(default_factory=set)
126
- _handled_cases: set[int] = field(default_factory=set)
127
- _reported_cycles: set[_Symbol] = field(default_factory=set)
128
- _attachment_sites: list[tuple[AttachmentSite, ir.RelationExpr | ir.SimpleCase]] = field(default_factory=list)
129
- _sited_cases: set[int] = field(default_factory=set)
130
- # Each scalar subquery lowered as a join, by id, and the qualifier of the
131
- # binding that holds its value.
132
- _scalar_values: dict[int, str] = field(default_factory=dict)
133
- # Each aggregate call and grouping-determined column of the grouped
134
- # select item being lowered, by id, and its value per group (`_lower_grouped`).
135
- _grouped_values: dict[int, ir.ScalarExpr] = field(default_factory=dict)
136
- # Each set-returning call of a select list, by id, and the qualifier of the
137
- # binding that holds the values it returns.
138
- _set_returning_values: dict[int, str] = field(default_factory=dict)
139
- _scalar_subqueries: list[tuple[AttachmentSite, ir.Join]] = field(default_factory=list)
140
- _sort_keys: dict[int, tuple[ir.OutputColumn, ...] | None] = field(default_factory=dict)
141
- _site_sort_keys: list[tuple[AttachmentSite, tuple[ir.OutputColumn, ...] | None]] = field(default_factory=list)
142
- _set_operations: list[tuple[AttachmentSite, ir.SetOperation]] = field(default_factory=list)
143
- _unsupported: list[tuple[ir.Node, str]] = field(default_factory=list)
144
- # Columns made up for names a query uses: of a table with no CREATE, or an
145
- # opaque relation (`_guessed`), and those a declared table does not have (`_absent`).
146
- _guessed: set[ir.OutputColumn] = field(default_factory=set)
147
- # A scalar subquery's columns, each bound to the scope that owns it.
148
- _scoped_columns: dict[int, ir.OutputColumn] = field(default_factory=dict)
149
- _absent: set[ir.OutputColumn] = field(default_factory=set)
150
- # Each declared table column's type, as its CREATE TABLE writes it.
151
- _declared_types: dict[ir.OutputColumn, exp.DataType] = field(default_factory=dict)
152
- # Every set operation's output column: it refers to its left input only,
153
- # so the left input's declared type need not describe its values.
154
- _set_outputs: set[ir.OutputColumn] = field(default_factory=set)
155
- # The comparisons already checked for a zoned timestamp's text, by id.
156
- _zone_checked: set[int] = field(default_factory=set)
157
- # Each composite column or CAST a comparison reads, by id, with the
158
- # comparison: a warning unless its elements are declared non-null.
159
- _composite_comparisons: dict[int, tuple[Origin, str, str, ir.ScalarExpr]] = field(default_factory=dict)
160
- _marker_targets: dict[int, _Symbol] = field(default_factory=dict)
161
- _marker_references: list[_MarkerReference] = field(default_factory=list)
162
- _constraint_references: list[_ConstraintReference] = field(default_factory=list)
163
- # Constraints an ALTER TABLE ... NOT VALID added: rows already there were never checked.
164
- _unvalidated: set[int] = field(default_factory=set)
165
-
166
- @property
167
- def semantics(self) -> DialectSemantics:
168
- return semantics(self.dialect)
169
-
170
- def parse(self, ast: ParsedProgram) -> IrConversionResult:
171
- for statement in (*ast.create_statements, ast.root_select):
172
- if statement is None:
173
- continue
174
- for node in statement.find_all(exp.Identifier):
175
- if self.dialect == "postgres" and node.quoted and node.name != node.name.lower() and node.find_ancestor(exp.Collate, exp.CollateColumnConstraint) is None:
176
- diagnostic = Diagnostic(diag.UNSUPPORTED_CONSTRUCT, "case-sensitive quoted PostgreSQL identifiers are not supported", self._origin(node))
177
- return IrConversionResult(ir.Program(), (), (diagnostic,))
178
- for collate in statement.find_all(exp.Collate, exp.CollateColumnConstraint):
179
- # Every COLLATE warns where it is written, whatever reads it.
180
- written = collate.find_ancestor(exp.ColumnDef) if isinstance(collate, exp.CollateColumnConstraint) else collate
181
- self._warnings.append(Diagnostic(
182
- diag.UNSUPPORTED_CONSTRUCT,
183
- "COLLATE is not supported by sqlassert yet: only the dialect's default collation is, so facts that "
184
- "compare its values are unknown",
185
- self._origin(written or collate, _source_line(written or collate)),
186
- ))
187
- for table in statement.find_all(exp.Table):
188
- if any("." in part.name for part in table.parts if isinstance(part, exp.Identifier)):
189
- diagnostic = Diagnostic(diag.UNSUPPORTED_CONSTRUCT, "dots inside quoted relation identifiers are not supported", self._origin(table))
190
- return IrConversionResult(ir.Program(), (), (diagnostic,))
191
- for statement in ast.create_statements:
192
- match statement:
193
- case exp.Create(kind="INDEX"):
194
- self._declare_index(statement)
195
- case exp.Create(kind="SCHEMA"):
196
- pass # A schema states nothing about rows, like a plain index.
197
- case exp.Create():
198
- self._declare(statement)
199
- case exp.Alter():
200
- self._alter(statement)
201
- case _:
202
- raise TypeError(f"Unhandled schema statement: {type(statement).__name__}")
203
-
204
- for symbol in tuple(self._symbols):
205
- if symbol.role is ir.RelationRole.VIEW and symbol.body is not None:
206
- self._discover_query(symbol.body, {})
207
- if ast.root_select is not None:
208
- self._discover_query(ast.root_select, {})
209
- self._discover_constraint_references()
210
- self._propagate_required_columns()
211
-
212
- root = self._lower_query(ast.root_select) if ast.root_select is not None else None
213
- # Every view is a query of its own: its markers are checked whether or
214
- # not the root reads it, so a file of views (a project's models) needs
215
- # no root SELECT.
216
- for symbol in tuple(self._symbols):
217
- if symbol.role is ir.RelationRole.VIEW and symbol not in self._named_relations:
218
- self._resolve_symbol(symbol)
219
- # Referenced relations are linked last: a marker on a view may name
220
- # the view itself, or one that reads it.
221
- self._link_constraint_references()
222
- self._link_marker_references()
223
- self._report_unanalyzed(ast)
224
-
225
- named_relations = tuple(self._named_relations.get(symbol) or self._unresolved_named_relation(symbol) for symbol in self._symbols)
226
- warnings = [*self._undeclared_table_warnings(), *self._warnings, *self._composite_warnings()]
227
- return IrConversionResult(
228
- ir.Program(named_relations=named_relations, root=root, assertions=tuple(self._assertions), declarations=tuple(self._declarations), attachment_sites=tuple(self._attachment_sites),
229
- scalar_subqueries=tuple(self._scalar_subqueries), sort_keys=tuple(self._site_sort_keys),
230
- set_operations=tuple(self._set_operations), unsupported=tuple(self._unsupported)),
231
- tuple(self._knowledge), tuple(self._diagnostics), tuple(dict.fromkeys(warnings)),
232
- )
233
-
234
- def _undeclared_table_warnings(self) -> list[Diagnostic]:
235
- return [
236
- Diagnostic(
237
- diag.UNDECLARED_TABLE,
238
- f"table {symbol.name} has no CREATE TABLE in the program, so its keys, nullability and column types are unknown: "
239
- "declare it with CREATE TABLE, or analyze with a database connection (analyze_database)",
240
- replace(symbol.origin, line=symbol.first_line or symbol.origin.line),
241
- )
242
- for symbol in self._symbols
243
- if symbol.role is ir.RelationRole.TABLE and symbol.statement is None
244
- ]
245
-
246
- # Declaration and symbol discovery ---------------------------------------
247
-
248
- def _declare(self, statement: exp.Create) -> None:
249
- kind = (statement.kind or "").upper()
250
- if kind not in _SUPPORTED_CREATE_KINDS:
251
- self._diagnostics.append(
252
- Diagnostic(
253
- diag.UNSUPPORTED_CREATE_STATEMENT,
254
- f"create statement kind {kind or '<unknown>'} is not supported; only TABLE, VIEW, INDEX, and SCHEMA are analyzed: {statement.sql(dialect=self.dialect)}",
255
- )
256
- )
257
- return
258
-
259
- table = _created_table(statement)
260
- if table is None:
261
- return
262
- name = _qualified_name(table)
263
- key = name.lower()
264
- origin = Origin(SQL, statement.sql(dialect=self.dialect))
265
- if key in self._global_symbols:
266
- self._diagnostics.append(Diagnostic(diag.DUPLICATE_DECLARATION, f"relation {name} is declared more than once", origin))
267
- return
268
-
269
- role = ir.RelationRole.TABLE if kind == "TABLE" else ir.RelationRole.VIEW
270
- body = statement.args.get("expression")
271
- query = _unwrap_query(body)
272
- aliases = tuple(column.name for column in statement.this.expressions) if role is ir.RelationRole.VIEW and isinstance(statement.this, exp.Schema) else ()
273
- symbol = _Symbol(name=name, role=role, origin=origin, body=query, statement=statement, column_aliases=aliases)
274
- self._global_symbols[key] = symbol
275
- self._symbols.append(symbol)
276
-
277
- def _declare_index(self, statement: exp.Create) -> None:
278
- """A unique index over plain columns is a Unique Set, like UNIQUE; one
279
- with an expression key part may be (`_expression_key`); a partial one,
280
- or any other index, states nothing about the data."""
281
- index = statement.this
282
- table = index.args.get("table") if isinstance(index, exp.Index) else None
283
- if not isinstance(table, exp.Table):
284
- self._unsupported_create(statement, "an index without a table")
285
- return
286
- symbol = self._created_before(table, statement)
287
- if symbol is None or not statement.args.get("unique"):
288
- return
289
- params = index.args.get("params")
290
- columns = params.args.get("columns") or () if isinstance(params, exp.IndexParameters) else ()
291
- plain = [
292
- column.this for column in columns
293
- if isinstance(column, exp.Ordered) and isinstance(column.this, exp.Column) and not column.this.table
294
- ]
295
- if not columns or params.args.get("where") is not None:
296
- # Uniqueness of only some rows is not a Unique Set.
297
- self._unsupported_create(statement, "a partial unique index")
298
- return
299
- if len(plain) != len(columns):
300
- parts = [column.this if isinstance(column, exp.Ordered) else column for column in columns]
301
- symbol.expression_keys.append(([part.unnest() for part in parts], statement))
302
- return
303
- schema = exp.Schema(expressions=[exp.to_identifier(column.name) for column in plain])
304
- symbol.constraints.append(exp.UniqueColumnConstraint(this=schema))
305
-
306
- def _alter(self, statement: exp.Alter) -> None:
307
- """ALTER TABLE adding PRIMARY KEY, UNIQUE, FOREIGN KEY or CHECK
308
- constraints, or setting columns NOT NULL. Any other action could invalidate what is
309
- known of the table, so a statement with one states nothing."""
310
- actions = statement.args.get("actions") or ()
311
- added: list[Expr] = []
312
- not_null: list[str] = []
313
- for action in actions:
314
- match action:
315
- case exp.AddConstraint():
316
- added.extend(_unwrap_constraints(action.expressions))
317
- case exp.AlterColumn() if action.args.get("allow_null") is False and {
318
- key for key, value in action.args.items() if value is not None and value is not False
319
- } == {"this"}:
320
- not_null.append(action.name)
321
- case _:
322
- added.append(action)
323
- if not actions or not all(_is_added_constraint(constraint) for constraint in added):
324
- self._diagnostics.append(Diagnostic(
325
- diag.UNSUPPORTED_STATEMENT,
326
- f"only ALTER TABLE adding PRIMARY KEY, UNIQUE, FOREIGN KEY or CHECK constraints, or setting NOT NULL, "
327
- f"is analyzed: {statement.sql(dialect=self.dialect)}",
328
- self._origin(statement),
329
- ))
330
- return
331
- table = statement.this
332
- symbol = self._created_before(table, statement) if isinstance(table, exp.Table) else None
333
- if symbol is None:
334
- return
335
- symbol.constraints.extend(added)
336
- symbol.not_null.update(not_null)
337
- if statement.args.get("not_valid"):
338
- self._unvalidated.update(id(constraint) for constraint in added)
339
-
340
- def _created_before(self, table: exp.Table, statement: Expr) -> _Symbol | None:
341
- """The table `statement` amends, which a CREATE TABLE earlier in the
342
- program must declare; otherwise the statement is diagnosed."""
343
- name = _qualified_name(table)
344
- symbol = self._global_symbols.get(name.lower())
345
- if symbol is None or symbol.role is not ir.RelationRole.TABLE or symbol.statement is None:
346
- self._diagnostics.append(Diagnostic(
347
- diag.CONSTRAINT_WITHOUT_TABLE,
348
- f"{name} is not a table created earlier in the program, so this statement's constraints are ignored: "
349
- f"{statement.sql(dialect=self.dialect)}",
350
- self._origin(statement),
351
- ))
352
- return None
353
- return symbol
354
-
355
- def _unsupported_create(self, statement: exp.Create, what: str) -> None:
356
- self._diagnostics.append(Diagnostic(
357
- diag.UNSUPPORTED_CREATE_STATEMENT,
358
- f"{what} is not analyzed: {statement.sql(dialect=self.dialect)}",
359
- self._origin(statement),
360
- ))
361
-
362
- def _discover_marker_targets(self, query: exp.Query, scope: dict[str, _Symbol]) -> None:
363
- """The relation each Foreign Key marker on `query` references."""
364
- for marker in column_markers(query):
365
- if marker.referenced_relation is not None:
366
- origin = Origin.marked(marker.referenced_relation, marker.span)
367
- target = self._symbol_for_name(marker.referenced_relation, scope, origin)
368
- self._marker_targets[id(marker)] = target
369
- self._require_undeclared(target, marker.referenced_columns)
370
-
371
- def _discover_query(self, query: exp.Query, inherited_scope: dict[str, _Symbol]) -> None:
372
- if id(query) in self._query_scopes:
373
- return
374
-
375
- scope = dict(inherited_scope)
376
- with_clause = _arg(query, "with")
377
- if with_clause is not None:
378
- bodies = []
379
- recursive = bool(with_clause.args.get("recursive"))
380
- forward = recursive and self.dialect != "duckdb"
381
- for cte in with_clause.expressions:
382
- body = _unwrap_query(cte.this)
383
- duckdb_recursive = recursive and not forward and isinstance(body, exp.Union)
384
- if not forward:
385
- if duckdb_recursive and isinstance(body, exp.Union):
386
- # The seed is outside the recursive name's scope.
387
- seed = _unwrap_query(body.this)
388
- if seed is not None and _arg(body, "with") is None:
389
- self._discover_query(seed, scope)
390
- elif body is not None:
391
- self._discover_query(body, scope)
392
- symbol = _Symbol(
393
- name=cte.alias,
394
- role=ir.RelationRole.CTE,
395
- origin=Origin(SQL, cte.sql(dialect=self.dialect)),
396
- body=body,
397
- column_aliases=_column_aliases(cte),
398
- )
399
- scope[cte.alias.lower()] = symbol
400
- self._symbols.append(symbol)
401
- if forward and body is not None:
402
- bodies.append(body)
403
- elif duckdb_recursive and body is not None:
404
- self._discover_query(body, scope)
405
- for body in bodies:
406
- self._discover_query(body, scope)
407
-
408
- self._query_scopes[id(query)] = scope
409
- if isinstance(query, exp.SetOperation):
410
- # SQLGlot 30 wraps a nested set operation in a Subquery.
411
- for side in (query.this, query.expression):
412
- inner = _unwrap_query(side)
413
- if inner is not None:
414
- self._discover_query(inner, scope)
415
- self._discover_marker_targets(query, scope)
416
- return
417
- if not isinstance(query, exp.Select):
418
- return
419
-
420
- sources = _direct_sources(query)
421
- by_qualifier: dict[str, list[Expr]] = {}
422
- for source in [*sources, *(hidden for source in sources for hidden in _hidden_sources(source))]:
423
- self._source_required.setdefault(id(source), set())
424
- self._source_expressions[id(source)] = source
425
- qualifier = source.alias_or_name.lower()
426
- if qualifier:
427
- by_qualifier.setdefault(qualifier, []).append(source)
428
- if _is_named_table(source):
429
- symbol = self._symbol_for_table(source, scope)
430
- self._table_symbols[id(source)] = symbol
431
- elif isinstance(source, exp.Subquery):
432
- body = _unwrap_query(source)
433
- if body is not None:
434
- self._discover_query(body, scope)
435
-
436
- for column in query.find_all(exp.Column):
437
- if column.table:
438
- matching = by_qualifier.get(column.table.lower(), ())
439
- for source in matching:
440
- self._require(source, column.name)
441
- elif len(sources) == 1 and column.find_ancestor(exp.Select) is query:
442
- # An unqualified column in a nested query belongs to that query's scope.
443
- self._require(sources[0], column.name)
444
-
445
- for joins, level in _join_levels(query):
446
- for join in joins:
447
- for identifier in join.args.get("using") or ():
448
- for source in level:
449
- self._require(source, identifier.name)
450
-
451
- if len(sources) == 1 and _star_only(query):
452
- for marker in column_markers(query):
453
- for column in (*marker.columns, *marker.dependent):
454
- self._require(sources[0], column)
455
-
456
- self._discover_marker_targets(query, scope)
457
-
458
- where = query.args.get("where")
459
- for conjunct in _filter_conjuncts(where.this) if where is not None else ():
460
- matched = _subquery_conjunct(conjunct)
461
- if matched is not None:
462
- self._discover_query(matched[1], scope)
463
- for expression in (*(_filter_conjuncts(where.this) if where is not None else ()), *query.expressions):
464
- for subquery in _scalar_subqueries(expression):
465
- if isinstance(subquery.this, exp.Select):
466
- self._discover_query(subquery.this, scope)
467
-
468
- def _symbol_for_table(self, table: exp.Table, scope: dict[str, _Symbol]) -> _Symbol:
469
- symbol = self._symbol_for_name(_qualified_name(table), scope, Origin(SQL, table.sql(dialect=self.dialect)))
470
- if symbol.first_line is None:
471
- symbol.first_line = _source_line(table)
472
- return symbol
473
-
474
- def _symbol_for_name(self, name: str, scope: dict[str, _Symbol], origin: Origin) -> _Symbol:
475
- key = name.lower()
476
- if key in scope:
477
- return scope[key]
478
- symbol = self._global_symbols.get(key)
479
- if symbol is None:
480
- symbol = _Symbol(name=name, role=ir.RelationRole.TABLE, origin=origin)
481
- self._global_symbols[key] = symbol
482
- self._symbols.append(symbol)
483
- return symbol
484
-
485
- def _require_undeclared(self, symbol: _Symbol, columns: Iterable[str]) -> None:
486
- """Referenced columns become columns of an undeclared table only: a
487
- declared relation's schema is never widened by a reference to it."""
488
- if symbol.role is ir.RelationRole.TABLE and symbol.statement is None:
489
- symbol.required_columns.update(columns)
490
-
491
- def _discover_constraint_references(self) -> None:
492
- """`REFERENCES` constraints onto relations the program reaches; one onto
493
- a relation outside the program can never be used, so it is not linked."""
494
- for symbol in tuple(self._symbols):
495
- if symbol.role is not ir.RelationRole.TABLE or symbol.statement is None:
496
- continue
497
- for columns, table, target_columns, node in _references(symbol):
498
- target = self._global_symbols.get(_qualified_name(table).lower())
499
- if target is None or target.role is not ir.RelationRole.TABLE:
500
- continue
501
- self._require_undeclared(target, target_columns or ())
502
- self._constraint_references.append(
503
- _ConstraintReference(symbol, columns, target, target_columns, self._origin(node.find_ancestor(exp.ColumnDef) or node), node)
504
- )
505
-
506
- def _require(self, source: Expr, column: str) -> None:
507
- self._source_required.setdefault(id(source), set()).add(column)
508
- if _is_named_table(source) and column.lower() not in {name.lower() for name in _column_aliases(source)}:
509
- self._table_symbols[id(source)].required_columns.add(column)
510
-
511
- def _propagate_required_columns(self) -> None:
512
- """Push requested output columns through star-only view/CTE/subquery bodies."""
513
- changed = True
514
- while changed:
515
- before = sum(len(symbol.required_columns) for symbol in self._symbols) + sum(len(columns) for columns in self._source_required.values())
516
- for symbol in self._symbols:
517
- if isinstance(symbol.body, exp.Select) and _star_only(symbol.body):
518
- sources = _direct_sources(symbol.body)
519
- if len(sources) == 1:
520
- aliases = {name.lower() for name in symbol.column_aliases}
521
- for column in symbol.required_columns:
522
- if column.lower() not in aliases:
523
- self._require(sources[0], column)
524
- for source_id, columns in tuple(self._source_required.items()):
525
- source = self._source_expressions[source_id]
526
- body = _unwrap_query(source) if isinstance(source, exp.Subquery) else None
527
- if isinstance(body, exp.Select) and _star_only(body):
528
- nested_sources = _direct_sources(body)
529
- if len(nested_sources) == 1:
530
- aliases = {name.lower() for name in _column_aliases(source)}
531
- for column in columns:
532
- if column.lower() not in aliases:
533
- self._require(nested_sources[0], column)
534
- after = sum(len(symbol.required_columns) for symbol in self._symbols) + sum(len(columns) for columns in self._source_required.values())
535
- changed = after != before
536
-
537
- # Lowering ---------------------------------------------------------------
538
-
539
- def _lower_query(self, query: exp.Query) -> ir.RelationExpr | None:
540
- """A Root Select, view, CTE, and FROM-subquery body all lower the same way."""
541
- unwrapped = _unwrap_query(query)
542
- if unwrapped is None:
543
- return None
544
- query = unwrapped
545
- if isinstance(query, exp.SetOperation):
546
- left = self._lower_query(query.this)
547
- right = self._lower_query(query.expression)
548
- if left is None:
549
- left = self._opaque_relation(query.this)
550
- if right is None:
551
- right = self._opaque_relation(query.expression)
552
- origin = self._origin(query)
553
- by_name = bool(query.args.get("by_name"))
554
- if by_name:
555
- names: dict[str, str] = {}
556
- for column in (*left.output_columns, *right.output_columns):
557
- names.setdefault(column.name.lower(), column.name)
558
- output_columns = self._opaque_output_columns(names.values(), origin)
559
- else:
560
- output_columns = _pass_output_columns(left.output_columns, origin)
561
- self._set_outputs.update(output_columns)
562
- relation = ir.SetOperation(
563
- origin=self._origin(query), output_columns=output_columns, is_schema_complete=left.is_schema_complete and right.is_schema_complete,
564
- operator=_SET_OPERATORS[type(query)], left=left, right=right, distinct=bool(query.args.get("distinct")),
565
- by_name=by_name,
566
- )
567
- last = _last_select(query.this)
568
- position = marker_position(last) if last is not None else None
569
- if relation.operator != "union" and position is not None:
570
- self._set_operations.append((AttachmentSite(relation.operator.upper(), position[1], position[0], True), relation))
571
- limited = self._lower_limit(relation, query)
572
- # A marker after the last token of the query marks the whole of it,
573
- # so the last operand, which ends there too, has no site of its own.
574
- self._register_column_markers(limited, query)
575
- end = marker_position(query)
576
- if end is not None:
577
- self._attachment_sites = [
578
- (site, other) for site, other in self._attachment_sites if not (site.trailing and site.offset == end[0])
579
- ]
580
- self._add_attachment_site(query, _select_label(query), limited, trailing=True)
581
- return limited
582
- if not isinstance(query, exp.Select):
583
- return None
584
- return self._lower_select(query)
585
-
586
- def _lower_select(self, select: exp.Select) -> ir.RelationExpr | None:
587
- source = _from_source(select)
588
- if source is None:
589
- # No FROM: the select list is evaluated once, over one row of no
590
- # columns, which an opaque relation limited to one row stands for.
591
- origin = self._origin(select)
592
- row = ir.OpaqueRelation(origin=origin, output_columns=(), is_schema_complete=True, description="no FROM")
593
- one_row = ir.Limit(origin=origin, output_columns=(), is_schema_complete=True, input=row, count=1)
594
- relation = self._lower_select_tail(_Lowered(one_row, ()), select)
595
- elif any(join.args.get("method") == "NATURAL" for join in _all_joins(select)):
596
- relation = self._opaque_relation(select, _selected_output_names(select))
597
- else:
598
- lowered = self._lower_source(source)
599
- for join in select.args.get("joins") or ():
600
- lowered = self._lower_join(lowered, join)
601
- relation = self._lower_select_tail(lowered, select)
602
- return self._finish_select(relation, select)
603
-
604
- def _finish_select(self, relation: ir.RelationExpr, select: exp.Select) -> ir.RelationExpr:
605
- relation = self._lower_limit(relation, select)
606
- self._register_column_markers(relation, select)
607
- self._add_attachment_site(select, _select_label(select), relation, trailing=True)
608
- position = marker_position(select)
609
- if position is not None:
610
- offset, line = position
611
- self._site_sort_keys.append((AttachmentSite(_select_label(select), line, offset, True), self._sort_keys.get(id(select))))
612
- return relation
613
-
614
- def _lower_limit(self, relation: ir.RelationExpr, query: exp.Query) -> ir.RelationExpr:
615
- limit = query.args.get("limit")
616
- if limit is None and query.args.get("offset") is None:
617
- return relation
618
- count = None
619
- if limit is not None:
620
- expression = limit.args.get("expression") if isinstance(limit, exp.Limit) else limit.args.get("count")
621
- options = limit.args.get("limit_options")
622
- hard_bound = options is None or not any(options.args.get(key) for key in ("percent", "with_ties"))
623
- if hard_bound and isinstance(expression, exp.Literal) and expression.is_int:
624
- count = int(expression.this)
625
- origin = self._origin(query)
626
- 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)
627
-
628
- def _lower_source(self, source: Expr) -> _Lowered:
629
- if any(source.args.get(key) for key in ("pivots", "sample", "version", "changes")):
630
- relation = self._opaque_relation(source, self._source_required.get(id(source), set()))
631
- self._unsupported.append((relation, "a FROM modifier that changes the input rows"))
632
- return self._alias(relation, source.alias_or_name, self._origin(source))
633
- if _is_named_table(source):
634
- symbol = self._table_symbols[id(source)]
635
- alias_name = source.alias or source.name
636
- # An unaliased table may be named with its schema: `s1.t.k`.
637
- schema = "" if source.alias else _schema_path(source)
638
- if symbol in self._resolving:
639
- if symbol.role is ir.RelationRole.VIEW:
640
- self._report_cycle(symbol, source)
641
- recursive = self._recursive_relation(symbol, source)
642
- return self._alias(recursive, alias_name, self._origin(source), schema)
643
- return self._alias(self._resolve_symbol(symbol), alias_name, self._origin(source), schema, _column_aliases(source))
644
-
645
- nested = _nested_join(source) or _aliased_join(source)
646
- if nested is not None:
647
- first, joins = nested
648
- lowered = self._lower_source(first)
649
- for join in joins:
650
- lowered = self._lower_join(lowered, join)
651
- return lowered if source.alias == "" else self._alias_join(lowered.relation, source)
652
-
653
- if isinstance(source, exp.Subquery):
654
- relation = self._lower_query(source)
655
- if relation is not None:
656
- # DuckDB allows an unaliased FROM subquery; nothing can qualify
657
- # a column by its name, so a placeholder serves.
658
- return self._alias(relation, source.alias or "subquery", self._origin(source), column_aliases=_column_aliases(source))
659
-
660
- if isinstance(source, exp.Values):
661
- values = self._lower_values(source)
662
- if values is not None:
663
- return self._alias(values, source.alias_or_name, self._origin(source))
664
-
665
- opaque = self._opaque_relation(source, self._source_required.get(id(source), set()))
666
- construct = _unsupported_source(source)
667
- if construct is not None:
668
- self._unsupported.append((opaque, construct))
669
- return self._alias(opaque, source.alias_or_name or "opaque", self._origin(source))
670
-
671
- def _alias_join(self, join: ir.RelationExpr, source: Expr) -> _Lowered:
672
- """`(a JOIN b ...) AS x`: a relation of its own, which hides the names
673
- of a and b and has each of their columns under its own name. A name
674
- two columns share each dialect resolves differently (DuckDB renames
675
- the second `x_1`, others reject reading it), so its columns are
676
- opaque, the first one readable by that name; every name is, when a
677
- source's columns are not all known."""
678
- origin = self._origin(source)
679
- counts = Counter(column.name.lower() for column in join.output_columns)
680
- relation = join
681
- if not join.is_schema_complete or any(count > 1 for count in counts.values()):
682
- outputs = tuple(
683
- ir.OutputColumn(
684
- origin=origin, name=column.name,
685
- scalar_expr=ir.ColumnRef(origin=origin, column=column) if join.is_schema_complete and counts[column.name.lower()] == 1
686
- else ir.OpaqueExpression(origin=origin, description=f"{source.alias}.{column.name}"),
687
- )
688
- for column in join.output_columns
689
- )
690
- relation = ir.Project(origin=origin, output_columns=outputs, is_schema_complete=join.is_schema_complete, input=join)
691
- lowered = self._alias(relation, source.alias, origin, column_aliases=_column_aliases(source))
692
- bindings: dict[str, _Binding] = {}
693
- for binding in lowered.bindings:
694
- bindings.setdefault(binding.name, binding)
695
- return _Lowered(lowered.relation, tuple(bindings.values()))
696
-
697
- def _lower_values(self, values: exp.Values) -> ir.OpaqueRelation | None:
698
- """`(VALUES (...), ...) AS t (a, ...)`: rows of literals, stated as
699
- Knowledge of its columns. A column is non-null when no row holds NULL
700
- there; its Enumerated Domain is its values, up to `_VALUES_DOMAIN_ROWS`
701
- rows (past that, a closed set is more noise than fact); it is a Unique
702
- Set when no two of its values may compare equal (`1` and `1.0` may,
703
- and `'a'` and `'A'` unless text compares by identity), and so are all
704
- columns together when no two rows may. A column with any other
705
- expression states nothing. Without column names it stays opaque."""
706
- from sqlassert.rules.domain import _may_coincide
707
-
708
- alias = values.args.get("alias")
709
- names = [column.name for column in alias.columns] if isinstance(alias, exp.TableAlias) else []
710
- rows = [row.expressions if isinstance(row, exp.Tuple) else [row] for row in values.expressions]
711
- if not names or not rows or any(len(row) != len(names) for row in rows):
712
- return None
713
- origin = self._origin(values)
714
- columns = tuple(
715
- ir.OutputColumn(origin=origin, name=name, scalar_expr=ir.OpaqueExpression(origin=origin, description=f"VALUES column {name}"))
716
- for name in names
717
- )
718
- binary = self.semantics.text_is_binary
719
-
720
- def distinct(items: list[ir.LiteralValue | None]) -> bool:
721
- # NULL equals nothing, so it never repeats (a lax Unique Set).
722
- known = [item for item in items if item is not None]
723
- return all(not _may_coincide(first, second, binary) for index, first in enumerate(known) for second in known[index + 1:])
724
-
725
- literal_rows: list[list[ir.LiteralValue | None]] = []
726
- for row in rows:
727
- literal_rows.append([None if isinstance(item, exp.Null) else literal_value(item) for item in row])
728
- for index, column in enumerate(columns):
729
- written = [row[index] for row in rows]
730
- if not all(isinstance(item, exp.Null) or literal_value(item) is not None for item in written):
731
- continue # Some value is an expression: nothing is stated.
732
- items = [row[index] for row in literal_rows]
733
- if not any(isinstance(item, exp.Null) for item in written):
734
- self._knowledge.append(NonNullColumn(column=column))
735
- present = frozenset(item for item in items if item is not None)
736
- if present and len(rows) <= _VALUES_DOMAIN_ROWS:
737
- self._knowledge.append(EnumeratedDomain(column=column, values=present))
738
- if distinct(items):
739
- self._knowledge.append(UniqueSet(columns=frozenset({column})))
740
- literal = all(all(isinstance(item, exp.Null) or literal_value(item) is not None for item in row) for row in rows)
741
- if literal and len(columns) > 1 and all(
742
- any(one is None or other is None or not _may_coincide(one, other, binary) for one, other in zip(first, second, strict=True))
743
- for position, first in enumerate(literal_rows) for second in literal_rows[position + 1:]
744
- ):
745
- self._knowledge.append(UniqueSet(columns=frozenset(columns)))
746
- return ir.OpaqueRelation(origin=origin, output_columns=columns, is_schema_complete=True, description=values.sql(dialect=self.dialect))
747
-
748
- def _resolve_symbol(self, symbol: _Symbol) -> ir.NamedRelation:
749
- existing = self._named_relations.get(symbol)
750
- if existing is not None:
751
- return existing
752
-
753
- if symbol.role is ir.RelationRole.TABLE:
754
- output_columns, complete = self._table_output_columns(symbol)
755
- named = ir.NamedRelation(
756
- origin=symbol.origin, output_columns=output_columns, is_schema_complete=complete, name=symbol.name, role=symbol.role
757
- )
758
- self._named_relations[symbol] = named
759
- self._table_knowledge(named, symbol)
760
- return named
761
-
762
- self._resolving.add(symbol)
763
- try:
764
- body = self._lower_query(symbol.body) if symbol.body is not None else None
765
- finally:
766
- self._resolving.discard(symbol)
767
- if body is None:
768
- body = self._opaque_relation(symbol.body or exp.Table(this=symbol.name), symbol.required_columns)
769
- output_columns = self._aliased_outputs(body, symbol.origin, symbol.column_aliases)
770
- named = ir.NamedRelation(
771
- origin=symbol.origin,
772
- output_columns=output_columns,
773
- is_schema_complete=body.is_schema_complete,
774
- name=symbol.name,
775
- role=symbol.role,
776
- body=body,
777
- )
778
- self._named_relations[symbol] = named
779
- return named
780
-
781
- def _unresolved_named_relation(self, symbol: _Symbol) -> ir.NamedRelation:
782
- output_columns, complete = self._table_output_columns(symbol) if symbol.role is ir.RelationRole.TABLE else (self._opaque_output_columns(symbol.required_columns, symbol.origin), False)
783
- named = ir.NamedRelation(
784
- origin=symbol.origin, output_columns=output_columns, is_schema_complete=complete, name=symbol.name, role=symbol.role
785
- )
786
- self._named_relations[symbol] = named
787
- if symbol.role is ir.RelationRole.TABLE:
788
- self._table_knowledge(named, symbol)
789
- return named
790
-
791
- def _table_output_columns(self, symbol: _Symbol) -> tuple[tuple[ir.OutputColumn, ...], bool]:
792
- definitions = list(symbol.statement.this.find_all(exp.ColumnDef)) if symbol.statement is not None else []
793
- names = [definition.name for definition in definitions]
794
- seen = {name.lower() for name in names}
795
- names.extend(column for column in sorted(symbol.required_columns, key=str.lower) if column.lower() not in seen)
796
- complete = symbol.statement is not None and {column.lower() for column in symbol.required_columns} <= seen
797
- columns = self._opaque_output_columns(names, symbol.origin)
798
- by_name = {definition.name: definition for definition in definitions}
799
- if symbol.statement is not None:
800
- self._absent.update(column for column in columns if column.name not in by_name)
801
- # A column declared with a COLLATE compares under a collation sqlassert
802
- # does not model (`parse` warns): it is left untyped, so its values are unknown.
803
- collated = {name for name, definition in by_name.items() if _collated(definition)}
804
- by_name = {name: definition for name, definition in by_name.items() if name not in collated}
805
- typed = tuple(
806
- replace(
807
- column, binary_text=self._is_binary_text(by_name[column.name]),
808
- comparison_type=self._comparison_type(by_name[column.name]),
809
- identity_comparison=self._identity_comparison(by_name[column.name]),
810
- exact_numeric=self._exact_numeric(by_name[column.name]),
811
- )
812
- if column.name in by_name else column for column in columns
813
- )
814
- for column in typed:
815
- kind = by_name[column.name].args.get("kind") if column.name in by_name else None
816
- if isinstance(kind, exp.DataType):
817
- self._declared_types[column] = kind
818
- return typed, complete
819
-
820
- def _comparison_type(self, definition: exp.ColumnDef) -> str | None:
821
- kind = definition.args.get("kind")
822
- if not isinstance(kind, exp.DataType):
823
- return None
824
- if kind.this in exp.DataType.TEXT_TYPES:
825
- return kind.sql(dialect=self.dialect) if self._is_binary_text(definition) else None
826
- if self._unscaled_decimal(kind):
827
- return None
828
- return kind.sql(dialect=self.dialect)
829
-
830
- def _identity_comparison(self, definition: exp.ColumnDef) -> bool:
831
- """Declared with a type whose equal values are identical (text only
832
- when compared by identity, which `_comparison_type` already checks)."""
833
- kind = definition.args.get("kind")
834
- if not (self._comparison_type(definition) is not None and isinstance(kind, exp.DataType)):
835
- return False
836
- if kind.this == exp.DataType.Type.TIMESTAMPTZ:
837
- return self.semantics.zoned_timestamp_is_instant
838
- return kind.this in _IDENTITY_TYPES
839
-
840
- def _exact_numeric(self, definition: exp.ColumnDef) -> bool:
841
- kind = definition.args.get("kind")
842
- return isinstance(kind, exp.DataType) and kind.this in _EXACT_NUMERIC_TYPES and not self._unscaled_decimal(kind)
843
-
844
- def _unscaled_decimal(self, kind: exp.DataType) -> bool:
845
- """A Postgres NUMERIC with no scale: 1.0 and 1.00 are equal values that differ."""
846
- return self.semantics.unscaled_decimal and kind.this == exp.DataType.Type.DECIMAL and not kind.expressions
847
-
848
- def _is_binary_text(self, definition: exp.ColumnDef) -> bool:
849
- """Declared VARCHAR or TEXT in a dialect whose default collation is
850
- binary: compared by identity. CHAR is not: it ignores trailing spaces
851
- when compared."""
852
- kind = definition.args.get("kind")
853
- return isinstance(kind, exp.DataType) and kind.this in _TEXT_TYPES and self.semantics.text_is_binary
854
-
855
- def _opaque_output_columns(self, names: Iterable[str], origin: Origin) -> tuple[ir.OutputColumn, ...]:
856
- if isinstance(names, Set):
857
- names = sorted(names, key=lambda name: (name.lower(), name))
858
- columns = tuple(
859
- ir.OutputColumn(
860
- origin=origin,
861
- name=name,
862
- scalar_expr=ir.OpaqueExpression(origin=origin, description=f"source column {name}"),
863
- )
864
- for name in names
865
- )
866
- self._guessed.update(columns)
867
- return columns
868
-
869
- def _recursive_relation(self, symbol: _Symbol, source: Expr) -> ir.RecursiveRelation:
870
- origin = self._origin(source)
871
- relation = ir.RecursiveRelation(
872
- origin=origin,
873
- output_columns=self._opaque_output_columns(symbol.required_columns, origin),
874
- is_schema_complete=False,
875
- description=source.sql(dialect=self.dialect),
876
- relation_name=symbol.name,
877
- )
878
- self._unsupported.append((relation, "a recursive CTE or view"))
879
- return relation
880
-
881
- def _aliased_outputs(self, source: ir.RelationExpr, origin: Origin, names: tuple[str, ...]) -> tuple[ir.OutputColumn, ...]:
882
- if names and not source.is_schema_complete:
883
- # Guessed source columns have no reliable positions.
884
- return self._opaque_output_columns(names, origin)
885
- return tuple(
886
- ir.OutputColumn(origin=origin, name=names[index] if index < len(names) else column.name, scalar_expr=ir.ColumnRef(origin=origin, column=column))
887
- for index, column in enumerate(source.output_columns)
888
- )
889
-
890
- def _alias(self, source: ir.RelationExpr, name: str, origin: Origin, schema: str = "", column_aliases: tuple[str, ...] = ()) -> _Lowered:
891
- output_columns = self._aliased_outputs(source, origin, column_aliases)
892
- alias = ir.Alias(origin=origin, output_columns=output_columns, is_schema_complete=source.is_schema_complete, source=source, name=name)
893
- return _Lowered(alias, tuple(_Binding(name.lower(), output.name.lower(), output, schema) for output in output_columns))
894
-
895
- def _lower_join(self, left: _Lowered, join: exp.Join) -> _Lowered:
896
- right = self._lower_source(join.this)
897
- marked = assertion_span(join)
898
- origin = self._origin(join, marked.line if marked is not None else None)
899
- kind = _join_kind(join, self.dialect)
900
- if kind is None:
901
- return self._opaque_join(left, right, join, origin)
902
- predicate = self._lower_join_predicate(join, left, right)
903
- if kind == "semi" or kind == "anti":
904
- # RIGHT SEMI and RIGHT ANTI keep right rows: the same join, inputs swapped.
905
- kept, other = (right, left) if (join.args.get("side") or "").lower() == "right" else (left, right)
906
- filtered = self._filtering_join(kept, other.relation, kind, predicate, origin)
907
- assert isinstance(filtered.relation, ir.Join)
908
- self._join_marker(join, filtered.relation)
909
- self._add_attachment_site(join, _join_label(join, self.dialect), filtered.relation, trailing=False)
910
- return filtered
911
- if _is_positional(join):
912
- # A FULL JOIN on row position: an opaque condition, as no column holds it.
913
- predicate = ir.OpaqueExpression(origin=origin, description="row position")
914
- input_columns = left.relation.output_columns + right.relation.output_columns
915
- output_columns = _pass_output_columns(input_columns, origin)
916
- remapped = {source: output for source, output in zip(input_columns, output_columns)}
917
- relation = ir.Join(
918
- origin=origin,
919
- output_columns=output_columns,
920
- is_schema_complete=left.relation.is_schema_complete and right.relation.is_schema_complete,
921
- kind=kind,
922
- left=left.relation,
923
- right=right.relation,
924
- predicate=predicate,
925
- )
926
- bindings = tuple(
927
- replace(binding, column=remapped[binding.column])
928
- for binding in left.bindings + right.bindings
929
- )
930
- self._join_marker(join, relation)
931
- self._add_attachment_site(join, _join_label(join, self.dialect), relation, trailing=False)
932
- lowered = _Lowered(relation, bindings)
933
- return self._merge_using(lowered, join, kind, len(left.bindings), origin) if join.args.get("using") else lowered
934
-
935
- def _merge_using(self, lowered: _Lowered, join: exp.Join, kind: ir.JoinKind, left_count: int, origin: Origin) -> _Lowered:
936
- """`JOIN ... USING (k)` outputs one `k`: the left input's for an INNER
937
- or LEFT JOIN (equal to the right's wherever both exist), the right's
938
- for a RIGHT JOIN, and `coalesce(left.k, right.k)` for a FULL JOIN,
939
- where either side may be padded. An unqualified `k` reads it, so a
940
- later `USING (k)` or `WHERE k = ...` sees one column; `a.k` and `b.k`
941
- still read their own side."""
942
- bindings = list(lowered.bindings)
943
- merged: list[_Binding] = []
944
- coalesced: list[tuple[str, ir.OutputColumn, ir.OutputColumn]] = []
945
- for identifier in join.args.get("using") or ():
946
- name = identifier.name.lower()
947
- sides = [
948
- [index for index in (range(left_count) if left else range(left_count, len(bindings)))
949
- if bindings[index].name == name and not bindings[index].shadowed and not bindings[index].qualifier.startswith(_SCALAR_QUALIFIER)]
950
- for left in (True, False)
951
- ]
952
- if any(len(side) != 1 for side in sides):
953
- continue # Not one column on each side: leave the names as they are.
954
- (mine,), (theirs,) = sides
955
- for index in (mine, theirs):
956
- bindings[index] = replace(bindings[index], shadowed=True)
957
- if kind == "full":
958
- coalesced.append((name, bindings[mine].column, bindings[theirs].column))
959
- else:
960
- column = bindings[theirs if kind == "right" else mine].column
961
- merged.append(_Binding(_USING_QUALIFIER, name, column))
962
- relation = lowered.relation
963
- if coalesced:
964
- passed = _pass_output_columns(relation.output_columns, origin)
965
- remapped = dict(zip(relation.output_columns, passed))
966
- values = tuple(
967
- ir.OutputColumn(origin=origin, name=name, scalar_expr=ir.Coalesce(origin=origin, arguments=(
968
- ir.ColumnRef(origin=origin, column=remapped[first]), ir.ColumnRef(origin=origin, column=remapped[second]),
969
- )))
970
- for name, first, second in coalesced
971
- )
972
- relation = ir.Project(origin=origin, output_columns=(*passed, *values), is_schema_complete=relation.is_schema_complete, input=relation)
973
- bindings = [replace(binding, column=remapped[binding.column]) for binding in bindings]
974
- merged = [replace(binding, column=remapped[binding.column]) for binding in merged]
975
- merged += [_Binding(_USING_QUALIFIER, name, value) for (name, _, _), value in zip(coalesced, values)]
976
- return _Lowered(relation, (*bindings, *merged))
977
-
978
- def _opaque_join(self, left: _Lowered, right: _Lowered, join: exp.Join, origin: Origin) -> _Lowered:
979
- """A join whose kind is not modelled: every column it outputs is opaque,
980
- and a marker on it is reported as unanalyzed."""
981
- description = join.sql(dialect=self.dialect)
982
- input_columns = left.relation.output_columns + right.relation.output_columns
983
- opaque = {
984
- column: ir.OutputColumn(origin=origin, name=column.name, scalar_expr=ir.OpaqueExpression(origin=origin, description=description))
985
- for column in input_columns
986
- }
987
- relation = ir.OpaqueRelation(origin=origin, output_columns=tuple(opaque.values()), is_schema_complete=False, description=description)
988
- return _Lowered(relation, tuple(
989
- replace(binding, column=opaque[binding.column]) for binding in left.bindings + right.bindings
990
- ))
991
-
992
- def _join_marker(self, join: exp.Join, relation: ir.Join) -> None:
993
- kind = join_marker_kind(join)
994
- if kind is not None:
995
- self._handled_joins.add(id(join))
996
- cardinality = {"unique-join": UniqueJoin, "many-to-one-join": ManyToOneJoin, "one-to-many-join": OneToManyJoin, "one-to-one-join": OneToOneJoin}
997
- if kind in cardinality and relation.kind in {"semi", "anti"}:
998
- # It keeps or drops left rows whole and outputs no right row: cardinality does not apply.
999
- self._diagnostics.append(Diagnostic(
1000
- diag.CARDINALITY_ON_FILTERING_JOIN,
1001
- f"the {JOIN_MARKER_NOUNS[kind]} marker on line {join_origin(join, self.dialect).line} is on a {relation.kind} join, "
1002
- "which outputs no right rows: join cardinality does not apply to it",
1003
- join_origin(join, self.dialect),
1004
- ))
1005
- return
1006
- match kind:
1007
- case "unique-join" | "many-to-one-join" | "one-to-many-join" | "one-to-one-join":
1008
- self._assertions.append(ir.Assertion(origin=join_origin(join, self.dialect), property=cardinality[kind](join=relation)))
1009
- case "exactly-one-join":
1010
- self._assertions.append(
1011
- ir.Assertion(origin=join_origin(join, self.dialect), property=ExactlyOneJoin(join=relation))
1012
- )
1013
- case None:
1014
- pass
1015
- case _:
1016
- assert_never(kind)
1017
-
1018
- def _lower_join_predicate(self, join: exp.Join, left: _Lowered, right: _Lowered) -> ir.ScalarExpr | None:
1019
- """The ON condition; USING is an AND of one equality per column."""
1020
- using = join.args.get("using")
1021
- if using:
1022
- return _and(tuple(
1023
- ir.Equality(
1024
- origin=self._origin(identifier, _source_line(identifier)),
1025
- left=self._lower_expression(
1026
- exp.column(identifier.name), left.bindings, schema_complete=left.relation.is_schema_complete, line=_source_line(identifier),
1027
- ),
1028
- right=self._lower_expression(
1029
- exp.column(identifier.name), right.bindings, schema_complete=right.relation.is_schema_complete, line=_source_line(identifier),
1030
- ),
1031
- )
1032
- for identifier in using
1033
- ), self._origin(join))
1034
- predicate = join.args.get("on")
1035
- if predicate is None:
1036
- return None
1037
- complete = left.relation.is_schema_complete and right.relation.is_schema_complete
1038
- return self._lower_condition(predicate, _filter_conjuncts(predicate), left.bindings + right.bindings, schema_complete=complete)
1039
-
1040
- def _lower_condition(
1041
- self, source: Expr, conjuncts: list[Expr], bindings: tuple[_Binding, ...], *, schema_complete: bool
1042
- ) -> ir.ScalarExpr:
1043
- """The AND of `conjuncts`, the top-level conjuncts of `source`."""
1044
- assert conjuncts, "a condition has at least one conjunct"
1045
- lowered = _and(
1046
- tuple(self._lower_conjunct(conjunct, bindings, schema_complete=schema_complete) for conjunct in conjuncts),
1047
- self._origin(source, _source_line(source)),
1048
- )
1049
- assert lowered is not None
1050
- return lowered
1051
-
1052
- def _lower_conjunct(self, conjunct: Expr, bindings: tuple[_Binding, ...], *, schema_complete: bool) -> ir.ScalarExpr:
1053
- return self._lower_expression(conjunct, bindings, schema_complete=schema_complete, line=_source_line(conjunct))
1054
-
1055
- def _lower_select_tail(self, lowered: _Lowered, select: exp.Select) -> ir.RelationExpr:
1056
- if select.args.get("laterals"):
1057
- # Hive and Spark's LATERAL VIEW repeats each row per generated value.
1058
- opaque = self._opaque_relation(select, _selected_output_names(select))
1059
- self._unsupported.append((opaque, "LATERAL VIEW"))
1060
- return opaque
1061
- if any(
1062
- isinstance(star, exp.Star) and any(star.args.values())
1063
- for item in select.expressions for star in (item.this if isinstance(item, exp.Column) else item,)
1064
- ):
1065
- opaque = self._opaque_relation(select)
1066
- self._unsupported.append((opaque, "a modified star projection"))
1067
- return opaque
1068
- keys = grouping(select)
1069
- calls = [call for item in select.expressions for call in _set_returning_calls(item, self.dialect)]
1070
- if calls:
1071
- if keys is not None or isinstance(select.args.get("qualify"), exp.Qualify) or (
1072
- select.args.get("distinct") is not None and select.args["distinct"].args.get("on") is not None
1073
- ):
1074
- # Evaluated after grouping or a window: not modelled.
1075
- opaque = self._opaque_relation(select, _selected_output_names(select))
1076
- self._unsupported.append((opaque, "a set-returning function beside GROUP BY, QUALIFY or DISTINCT ON"))
1077
- return opaque
1078
- lowered = self._fan_out(lowered, calls, self._origin(select))
1079
- if keys is not None:
1080
- relation = self._qualified(self._lower_aggregate(lowered, select, keys), select, grouped=True)
1081
- distinct = select.args.get("distinct")
1082
- if relation is not None and distinct is not None and distinct.args.get("on") is not None:
1083
- # DISTINCT ON keeps one group per key, by an ORDER BY not modelled:
1084
- # it drops groups, keeping every fact of the ones left.
1085
- origin = self._origin(distinct)
1086
- relation = ir.Filter(
1087
- origin=origin, output_columns=_pass_output_columns(relation.output_columns, origin),
1088
- is_schema_complete=True, input=relation,
1089
- predicate=ir.OpaqueExpression(origin=origin, description=distinct.sql(dialect=self.dialect)),
1090
- )
1091
- elif select.args.get("distinct") is not None and select.args["distinct"].args.get("on") is not None:
1092
- relation = self._lower_distinct_on(lowered, select, select.args["distinct"].args["on"])
1093
- elif select.args.get("distinct") is not None:
1094
- relation = self._qualified(self._lower_distinct(lowered, select), select, grouped=False)
1095
- elif isinstance(select.args.get("qualify"), exp.Qualify):
1096
- relation = self._lower_qualify(lowered, select, select.args["qualify"])
1097
- else:
1098
- if select.args.get("where") is not None:
1099
- lowered = self._filter(lowered, select.args["where"])
1100
- if _star_only(select):
1101
- relation = lowered.relation
1102
- else:
1103
- lowered, _ = self._join_scalar_subqueries(lowered, select.expressions)
1104
- relation = self._project(lowered, select.expressions, self._origin(select))
1105
- if relation is None:
1106
- opaque = self._opaque_relation(select, _selected_output_names(select))
1107
- construct = _unsupported_grouping(select)
1108
- if construct is not None:
1109
- self._unsupported.append((opaque, construct))
1110
- return opaque
1111
- self._sort_keys[id(select)] = self._resolve_order(select, lowered.bindings, relation)
1112
- return relation
1113
-
1114
- def _resolve_order(
1115
- self, select: exp.Select, bindings: tuple[_Binding, ...], relation: ir.RelationExpr
1116
- ) -> tuple[ir.OutputColumn, ...] | None:
1117
- """Each ORDER BY key as a column of the stage it sorts (see
1118
- `Program.sort_keys`): a selected column by its name or position, else
1119
- the column a name binds, qualifier and schema included."""
1120
- order = select.args.get("order")
1121
- if order is None:
1122
- return ()
1123
- distinct = select.args.get("distinct")
1124
- if distinct is not None and distinct.args.get("on") is not None:
1125
- return None # Its ORDER BY picks the row each group keeps.
1126
- scope = relation.input if isinstance(relation, ir.Project) else relation
1127
- outputs = relation.output_columns
1128
- items = [item for item in select.expressions if not isinstance(item, exp.Star)]
1129
- keys: list[ir.OutputColumn] = []
1130
- for ordered in order.expressions:
1131
- expression = ordered.this if isinstance(ordered, exp.Ordered) else ordered
1132
- key: ir.OutputColumn | None = None
1133
- match expression:
1134
- case exp.Column(table="") if len(items) == len(outputs) and [item.alias_or_name.lower() for item in items].count(expression.name.lower()) == 1:
1135
- names = [item.alias_or_name.lower() for item in items]
1136
- key = _in_scope(outputs[names.index(expression.name.lower())], scope)
1137
- case exp.Literal(is_int=True) if len(items) == len(outputs) and 1 <= int(expression.this) <= len(outputs):
1138
- key = _in_scope(outputs[int(expression.this) - 1], scope)
1139
- case exp.Column():
1140
- schema, name = _schema_path(expression), expression.name.lower()
1141
- bound = [
1142
- binding for binding in bindings
1143
- if binding.name == name and (binding.qualifier == expression.table.lower() if expression.table else not binding.shadowed)
1144
- and (not schema or binding.schema == schema)
1145
- ]
1146
- if len(bound) == 1:
1147
- key = _carrying(bound[0].column, scope)
1148
- case _:
1149
- pass
1150
- if key is None:
1151
- return None
1152
- keys.append(key)
1153
- return tuple(keys)
1154
-
1155
- def _fan_out(self, lowered: _Lowered, calls: list[Expr], origin: Origin) -> _Lowered:
1156
- """A select list's set-returning calls repeat each input row once per
1157
- value they return (none for none; several are zipped, padded with
1158
- NULL): a cross join with an opaque relation of their values. The rows
1159
- keep no key, the input's other columns keep their facts, and each
1160
- call's value is that relation's column, no function of its arguments."""
1161
- names = tuple(f"value{index}" for index in range(len(calls)))
1162
- values = ir.OpaqueRelation(
1163
- origin=origin, output_columns=self._opaque_output_columns(names, origin), is_schema_complete=True,
1164
- description="rows of " + ", ".join(call.sql(dialect=self.dialect) for call in calls),
1165
- )
1166
- input_columns = lowered.relation.output_columns + values.output_columns
1167
- output_columns = _pass_output_columns(input_columns, origin)
1168
- remapped = dict(zip(input_columns, output_columns))
1169
- join = ir.Join(
1170
- origin=origin, output_columns=output_columns, is_schema_complete=lowered.relation.is_schema_complete,
1171
- kind="cross", left=lowered.relation, right=values, predicate=None,
1172
- )
1173
- bindings = [replace(binding, column=remapped[binding.column]) for binding in lowered.bindings]
1174
- for call, column in zip(calls, values.output_columns):
1175
- qualifier = f"{_SET_RETURNING_QUALIFIER}{len(self._set_returning_values)}"
1176
- self._set_returning_values[id(call)] = qualifier
1177
- bindings.append(_Binding(qualifier, _SET_RETURNING_QUALIFIER, remapped[column]))
1178
- return _Lowered(join, tuple(bindings))
1179
-
1180
- def _filter(self, lowered: _Lowered, where: exp.Where) -> _Lowered:
1181
- """WHERE: each `EXISTS`, `NOT EXISTS`, or `IN (subquery)` conjunct as a
1182
- semi or anti join (Paulley §4.4.2), the other conjuncts as one Filter."""
1183
- remaining = []
1184
- for conjunct in _filter_conjuncts(where.this):
1185
- joined = self._subquery_join(lowered, conjunct)
1186
- if joined is None:
1187
- remaining.append(conjunct)
1188
- else:
1189
- lowered = joined
1190
- if not remaining:
1191
- return lowered
1192
- before = lowered.relation.output_columns
1193
- lowered, carried = self._join_scalar_subqueries(lowered, remaining)
1194
- origin = self._origin(where)
1195
- output_columns = _pass_output_columns(lowered.relation.output_columns, origin)
1196
- remapped = {source: output for source, output in zip(lowered.relation.output_columns, output_columns)}
1197
- complete = lowered.relation.is_schema_complete
1198
- relation = ir.Filter(
1199
- origin=origin, output_columns=output_columns, is_schema_complete=complete, input=lowered.relation,
1200
- predicate=self._lower_condition(where.this, remaining, lowered.bindings, schema_complete=complete),
1201
- )
1202
- bindings = tuple(
1203
- replace(binding, column=remapped[binding.column]) for binding in lowered.bindings
1204
- )
1205
- if all(carried[column] is column for column in before):
1206
- return _Lowered(relation, bindings)
1207
- # Scalar subqueries were joined in: keep only the columns from before,
1208
- # so their values stay inside this WHERE.
1209
- kept = tuple(remapped[carried[column]] for column in before)
1210
- project = ir.Project(
1211
- origin=origin, output_columns=_pass_output_columns(kept, origin), is_schema_complete=complete, input=relation,
1212
- )
1213
- projected = dict(zip(kept, project.output_columns))
1214
- return _Lowered(project, tuple(
1215
- replace(binding, column=projected[binding.column])
1216
- for binding in bindings if binding.column in projected
1217
- ))
1218
-
1219
- def _correlated(self, select: exp.Select, inner: _Lowered, outer: _Lowered) -> bool | None:
1220
- """Whether `select` reads the outer scope, only in its WHERE; None when
1221
- it reads it anywhere else, or when a column may belong to either scope."""
1222
- where = select.args.get("where")
1223
- correlated = False
1224
- for column in select.find_all(exp.Column):
1225
- found = self._scope_of(column, inner, outer)
1226
- if found is None:
1227
- return None
1228
- scope, binding = found
1229
- self._scoped_columns[id(column)] = binding.column
1230
- if scope == "outer":
1231
- if where is None or column.find_ancestor(exp.Where) is not where:
1232
- return None # Only a WHERE becomes the dependent join's ON.
1233
- correlated = True
1234
- return correlated
1235
-
1236
- def _scope_of(
1237
- self, column: exp.Column, inner: _Lowered, outer: _Lowered
1238
- ) -> tuple[Literal["inner", "outer"], _Binding] | None:
1239
- """The scope a subquery's column belongs to, the innermost that has it,
1240
- and its binding there. None when that is unknown (a table with no
1241
- CREATE may have the column) or the name binds more than one column."""
1242
- name = column.name.lower()
1243
-
1244
- def one(scope: Literal["inner", "outer"], bindings: list[_Binding]) -> tuple[Literal["inner", "outer"], _Binding] | None:
1245
- return (scope, bindings[0]) if len(bindings) == 1 else None
1246
-
1247
- if column.table:
1248
- qualifier, schema = column.table.lower(), _schema_path(column)
1249
- for scope, bindings in (("inner", inner.bindings), ("outer", outer.bindings)):
1250
- if any(binding.qualifier == qualifier and (not schema or binding.schema == schema) for binding in bindings):
1251
- return one(scope, [
1252
- binding for binding in bindings
1253
- if binding.qualifier == qualifier and (not schema or binding.schema == schema) and binding.name == name
1254
- ])
1255
- return None
1256
- inner_named = [binding for binding in inner.bindings if binding.name == name and not binding.shadowed and self._owns(binding) != "no"]
1257
- outer_named = [binding for binding in outer.bindings if binding.name == name and not binding.shadowed and self._owns(binding) != "no"]
1258
- owners = {self._owns(binding) for binding in inner_named}
1259
- if "yes" in owners:
1260
- return one("inner", inner_named)
1261
- outer_has = bool(outer_named)
1262
- if "unknown" in owners or (not inner_named and not inner.relation.is_schema_complete and not any(binding.name == name for binding in inner.bindings)):
1263
- if not outer_has:
1264
- return one("inner", inner_named)
1265
- self._warnings.append(Diagnostic(
1266
- diag.AMBIGUOUS_COLUMN,
1267
- f"column {quoted(column.name)} in a subquery may belong to its own FROM or to the outer query, "
1268
- "since some of its tables have no declared columns: qualify it, declare those tables with CREATE TABLE, "
1269
- "or analyze with a database connection (analyze_database)",
1270
- self._origin(column, _source_line(column)),
1271
- ))
1272
- return None
1273
- return one("outer", outer_named) if outer_has else None
1274
-
1275
- def _owns(self, binding: _Binding) -> Literal["yes", "no", "unknown"]:
1276
- """Whether the relation behind `binding` has its column: a declared or
1277
- computed column it has, one its declared table lacks it does not, and
1278
- one made up for a table with no CREATE it may have."""
1279
- base = binding.column
1280
- while isinstance(base.scalar_expr, ir.ColumnRef):
1281
- base = base.scalar_expr.column
1282
- if base in self._absent:
1283
- return "no"
1284
- return "unknown" if base in self._guessed else "yes"
1285
-
1286
- def _join_scalar_subqueries(
1287
- self, lowered: _Lowered, expressions: Sequence[Expr]
1288
- ) -> tuple[_Lowered, dict[ir.OutputColumn, ir.OutputColumn]]:
1289
- """Each scalar subquery in `expressions` joined onto `lowered`, and
1290
- where each of `lowered`'s columns went."""
1291
- carried = {column: column for column in lowered.relation.output_columns}
1292
- for expression in expressions:
1293
- for subquery in _scalar_subqueries(expression):
1294
- joined = self._scalar_subquery_join(lowered, subquery)
1295
- if joined is None:
1296
- continue
1297
- lowered, remapped = joined
1298
- carried = {column: remapped[current] for column, current in carried.items()}
1299
- return lowered, carried
1300
-
1301
- def _scalar_subquery_join(
1302
- self, lowered: _Lowered, subquery: exp.Subquery
1303
- ) -> tuple[_Lowered, dict[ir.OutputColumn, ir.OutputColumn]] | None:
1304
- """A scalar subquery with body B as a left join of `lowered` with B: no
1305
- row makes it NULL, which is a left join's padding. More than one row
1306
- is a runtime error, so the join is many to one, or the query fails.
1307
-
1308
- Uncorrelated, B is lowered whole under an implied LIMIT 1, sound since
1309
- it changes the result only when the query would fail: its value is
1310
- the same on every row. Correlated, B's WHERE becomes the ON of a
1311
- dependent join (as for EXISTS), so only a plain select-from-where
1312
- whose value is one of its columns is lowered. Anything else, or a
1313
- column that may belong to either scope, stays opaque."""
1314
- select = subquery.this
1315
- if not isinstance(select, exp.Select) or len(select.expressions) != 1 or _star_only(select):
1316
- return None
1317
- source = _from_source(select)
1318
- if source is None or select.args.get("with") or any(
1319
- join.args.get("method") == "NATURAL" for join in _all_joins(select)
1320
- ) or any(isinstance(node, (exp.Subquery, exp.Exists, exp.Query)) and node is not select for node in select.walk()):
1321
- return None
1322
- right = self._lower_source(source)
1323
- for join in select.args.get("joins") or ():
1324
- right = self._lower_join(right, join)
1325
- correlated = self._correlated(select, right, lowered)
1326
- origin = self._origin(subquery)
1327
- if correlated is None:
1328
- return None
1329
- if not correlated:
1330
- body = self._finish_select(self._lower_select_tail(right, select), select)
1331
- right_relation: ir.RelationExpr = ir.Limit(
1332
- origin=origin, output_columns=_pass_output_columns(body.output_columns, origin),
1333
- is_schema_complete=body.is_schema_complete, input=body, count=1,
1334
- )
1335
- value = right_relation.output_columns[0]
1336
- predicate = None
1337
- else:
1338
- if grouping(select) == [] and not any(select.args.get(key) for key in ("having", "qualify", "distinct", "limit", "offset", "windows")):
1339
- return self._aggregate_subquery_join(lowered, subquery, select, right)
1340
- if grouping(select) is not None or any(select.args.get(key) for key in ("having", "qualify", "distinct", "limit", "offset", "windows")):
1341
- return None
1342
- item = select.expressions[0]
1343
- lowered_value = self._lower_expression(
1344
- item.this if isinstance(item, exp.Alias) else item, right.bindings, schema_complete=right.relation.is_schema_complete,
1345
- )
1346
- if not (isinstance(lowered_value, ir.ColumnRef) and lowered_value.column in right.relation.output_columns):
1347
- return None
1348
- inner = select.args.get("where")
1349
- predicate = None if inner is None else self._lower_condition(
1350
- inner.this, _filter_conjuncts(inner.this), lowered.bindings + right.bindings,
1351
- schema_complete=lowered.relation.is_schema_complete and right.relation.is_schema_complete,
1352
- )
1353
- right_relation, value = right.relation, lowered_value.column
1354
- input_columns = lowered.relation.output_columns + right_relation.output_columns
1355
- output_columns = _pass_output_columns(input_columns, origin)
1356
- remapped = dict(zip(input_columns, output_columns))
1357
- join = ir.Join(
1358
- origin=origin, output_columns=output_columns,
1359
- is_schema_complete=lowered.relation.is_schema_complete and right_relation.is_schema_complete,
1360
- kind="left", left=lowered.relation, right=right_relation, predicate=predicate, scalar_subquery=True,
1361
- )
1362
- position = marker_position(select)
1363
- if position is not None:
1364
- self._scalar_subqueries.append((AttachmentSite("scalar subquery", position[1], position[0], True), join))
1365
- qualifier = f"{_SCALAR_QUALIFIER}{len(self._scalar_values)}"
1366
- self._scalar_values[id(subquery)] = qualifier
1367
- bindings = (
1368
- *(replace(binding, column=remapped[binding.column]) for binding in lowered.bindings),
1369
- _Binding(qualifier, _SCALAR_QUALIFIER, remapped[value]),
1370
- )
1371
- return _Lowered(join, bindings), remapped
1372
-
1373
- def _aggregate_subquery_join(
1374
- self, lowered: _Lowered, subquery: exp.Subquery, select: exp.Select, right: _Lowered,
1375
- ) -> tuple[_Lowered, dict[ir.OutputColumn, ir.OutputColumn]] | None:
1376
- """A correlated scalar subquery whose value is one aggregate call,
1377
- `(SELECT agg(...) FROM r WHERE r.k = outer.k AND p)`, decorrelated:
1378
- r filtered by p, grouped by k, left joined on `k = outer.k`. Each
1379
- outer row meets at most its one group, and its value is a function of
1380
- the key. A row with no group gets the aggregate over no rows: NULL,
1381
- the join's padding, for the aggregates whose value over no rows is
1382
- NULL (`_EMPTY_NULL_AGGREGATES`); a count's is 0 (the count bug), so its
1383
- value is `coalesce(count, 0)`; any other aggregate is not
1384
- decorrelated. Nor is one whose arguments read the outer row: SQL
1385
- then makes it an aggregate of the outer query. Only equalities to outer
1386
- columns of the same declared type correlate it: grouping by `k`
1387
- then merges exactly the rows one outer value matches."""
1388
- where = select.args.get("where")
1389
- item = select.expressions[0]
1390
- value_expression = item.this if isinstance(item, exp.Alias) else item
1391
- if where is None or not isinstance(value_expression, _EMPTY_NULL_AGGREGATES | exp.Count):
1392
- return None
1393
- if any(
1394
- found is None or found[0] != "inner"
1395
- for found in (self._scope_of(column, right, lowered) for column in value_expression.find_all(exp.Column))
1396
- ):
1397
- return None
1398
- keys: list[tuple[Expr, ir.OutputColumn, ir.OutputColumn]] = [] # (inner column, inner, outer)
1399
- inner_only: list[Expr] = []
1400
- for conjunct in _filter_conjuncts(where.this):
1401
- scoped = [self._scope_of(column, right, lowered) for column in conjunct.find_all(exp.Column)]
1402
- if any(found is None for found in scoped):
1403
- return None
1404
- scopes = {found[0] for found in scoped if found is not None}
1405
- if scopes <= {"inner"}:
1406
- inner_only.append(conjunct)
1407
- continue
1408
- if not isinstance(conjunct, exp.EQ) or not isinstance(conjunct.this, exp.Column) or not isinstance(conjunct.expression, exp.Column):
1409
- return None
1410
- sides = [(node, self._scope_of(node, right, lowered)) for node in (conjunct.this, conjunct.expression)]
1411
- inner = [(node, found[1].column) for node, found in sides if found is not None and found[0] == "inner"]
1412
- outer = [found[1].column for _, found in sides if found is not None and found[0] == "outer"]
1413
- if len(inner) != 1 or len(outer) != 1:
1414
- return None
1415
- if _traced_comparison_type(inner[0][1]) is None or _traced_comparison_type(inner[0][1]) != _traced_comparison_type(outer[0]):
1416
- return None
1417
- keys.append((inner[0][0], inner[0][1], outer[0]))
1418
- if not keys:
1419
- return None
1420
- grouped = select.copy()
1421
- grouped.set("expressions", [
1422
- *(exp.alias_(node.copy(), f"k{index}") for index, (node, _, _) in enumerate(keys)), exp.alias_(value_expression.copy(), "value"),
1423
- ])
1424
- grouped.set("where", exp.Where(this=exp.and_(*(conjunct.copy() for conjunct in inner_only))) if inner_only else None)
1425
- grouped.set("group", exp.Group(expressions=[node.copy() for node, _, _ in keys]))
1426
- body = self._lower_select_tail(right, grouped)
1427
- if not isinstance(body, ir.Aggregate):
1428
- return None
1429
- origin = self._origin(subquery)
1430
- predicate = _and(tuple(
1431
- ir.Equality(origin=origin, left=ir.ColumnRef(origin=origin, column=outer), right=ir.ColumnRef(origin=origin, column=body.output_columns[index]))
1432
- for index, (_, _, outer) in enumerate(keys)
1433
- ), origin)
1434
- input_columns = lowered.relation.output_columns + body.output_columns
1435
- output_columns = _pass_output_columns(input_columns, origin)
1436
- remapped = dict(zip(input_columns, output_columns))
1437
- join = ir.Join(
1438
- origin=origin, output_columns=output_columns, is_schema_complete=lowered.relation.is_schema_complete,
1439
- kind="left", left=lowered.relation, right=body, predicate=predicate, scalar_subquery=True,
1440
- )
1441
- position = marker_position(select)
1442
- if position is not None:
1443
- self._scalar_subqueries.append((AttachmentSite("scalar subquery", position[1], position[0], True), join))
1444
- relation: ir.RelationExpr = join
1445
- value = remapped[body.output_columns[-1]]
1446
- if isinstance(value_expression, exp.Count):
1447
- passed = _pass_output_columns(output_columns, origin)
1448
- zero = ir.Constant(origin=origin, value=ir.LiteralValue(type="numeric", text="0"))
1449
- counted = ir.OutputColumn(origin=origin, name="value", scalar_expr=ir.Coalesce(
1450
- origin=origin, arguments=(ir.ColumnRef(origin=origin, column=value), zero),
1451
- ))
1452
- relation = ir.Project(origin=origin, output_columns=(*passed, counted), is_schema_complete=join.is_schema_complete, input=join)
1453
- remapped = {source: passed[output_columns.index(output)] for source, output in remapped.items()}
1454
- value = counted
1455
- qualifier = f"{_SCALAR_QUALIFIER}{len(self._scalar_values)}"
1456
- self._scalar_values[id(subquery)] = qualifier
1457
- bindings = (
1458
- *(replace(binding, column=remapped[binding.column]) for binding in lowered.bindings),
1459
- _Binding(qualifier, _SCALAR_QUALIFIER, value),
1460
- )
1461
- return _Lowered(relation, bindings), remapped
1462
-
1463
- def _subquery_join(self, lowered: _Lowered, conjunct: Expr) -> _Lowered | None:
1464
- """`EXISTS (SELECT ... FROM r WHERE p)` as a semi join of r on p, and
1465
- `NOT EXISTS` as an anti join; `p` may read the outer row (a dependent
1466
- join, so the IR stays a DAG). `x IN (SELECT a ...)` as a semi join on
1467
- `x = a`. Not `NOT IN`: a NULL among the values makes it reject every row."""
1468
- matched = _subquery_conjunct(conjunct)
1469
- if matched is None:
1470
- return None
1471
- kind, select, operand = matched
1472
- if operand is None:
1473
- source = _from_source(select)
1474
- if source is None or grouping(select) is not None or any(
1475
- select.args.get(key) for key in ("having", "qualify", "distinct", "limit", "offset", "with", "windows")
1476
- ) or any(join.args.get("method") == "NATURAL" for join in _all_joins(select)):
1477
- # Grouped by nothing (`grouping` is []), it returns one row whatever its WHERE: EXISTS is always true.
1478
- return None
1479
- right = self._lower_source(source)
1480
- for join in select.args.get("joins") or ():
1481
- right = self._lower_join(right, join)
1482
- inner = select.args.get("where")
1483
- predicate = None if inner is None else self._lower_condition(
1484
- inner.this, _filter_conjuncts(inner.this), lowered.bindings + right.bindings,
1485
- schema_complete=lowered.relation.is_schema_complete and right.relation.is_schema_complete,
1486
- )
1487
- relation = right.relation
1488
- else:
1489
- subquery = self._lower_query(select)
1490
- if subquery is None or len(subquery.output_columns) != 1:
1491
- return None
1492
- relation = subquery
1493
- predicate = ir.Equality(
1494
- origin=self._origin(conjunct, _source_line(conjunct)),
1495
- left=self._lower_expression(operand, lowered.bindings, schema_complete=lowered.relation.is_schema_complete),
1496
- right=ir.ColumnRef(origin=subquery.origin, column=subquery.output_columns[0]),
1497
- )
1498
- return self._filtering_join(lowered, relation, kind, predicate, self._origin(conjunct))
1499
-
1500
- def _filtering_join(
1501
- self, left: _Lowered, right: ir.RelationExpr, kind: ir.JoinKind, predicate: ir.ScalarExpr | None, origin: Origin
1502
- ) -> _Lowered:
1503
- """A semi or anti join: it keeps or drops left rows, and outputs only theirs."""
1504
- output_columns = _pass_output_columns(left.relation.output_columns, origin)
1505
- remapped = {source: output for source, output in zip(left.relation.output_columns, output_columns)}
1506
- relation = ir.Join(
1507
- origin=origin, output_columns=output_columns, is_schema_complete=left.relation.is_schema_complete,
1508
- kind=kind, left=left.relation, right=right, predicate=predicate,
1509
- )
1510
- return _Lowered(relation, tuple(replace(binding, column=remapped[binding.column]) for binding in left.bindings))
1511
-
1512
- def _project(self, lowered: _Lowered, items: list[Expr], origin: Origin) -> ir.Project:
1513
- output_columns = self._selected_output_columns(items, lowered)
1514
- return ir.Project(origin=origin, output_columns=output_columns, is_schema_complete=True, input=lowered.relation)
1515
-
1516
- def _lower_aggregate(self, lowered: _Lowered, select: exp.Select, keys: list[Expr]) -> ir.RelationExpr | None:
1517
- """`select` grouped by `keys`; [] is one group, one row however many
1518
- rows its input has. HAVING filters the groups (`_lower_having`). A
1519
- key not selected, or an aggregate only HAVING reads, is a hidden
1520
- output of the Aggregate, which a Project then drops: a key still
1521
- splits the groups, and HAVING may read either.
1522
-
1523
- An item computed over aggregates (`max(sal) + 1`) is computed by that
1524
- Project from the Aggregate's outputs: each repeatable aggregate call
1525
- it contains is one output, shared with the item or HAVING conjunct
1526
- written the same, and so is each column outside them. HAVING's facts
1527
- about `max(sal)` then hold of the item's operand."""
1528
- if _unsupported_grouping(select) is not None:
1529
- return None
1530
- if select.args.get("where") is not None:
1531
- lowered = self._filter(lowered, select.args["where"])
1532
-
1533
- items: list[Expr] = list(select.expressions)
1534
- selected_names = {item.alias_or_name.lower() for item in items}
1535
- grouped_items: set[int] = set()
1536
- matched: list[Expr] = []
1537
- for group_expression in keys:
1538
- item = _matching_grouping_output(group_expression, select.expressions) or _same_column_alias(group_expression, select.expressions)
1539
- if item is None:
1540
- if (isinstance(group_expression, exp.Literal) and group_expression.is_int) or (
1541
- isinstance(group_expression, exp.Column) and not group_expression.table
1542
- and group_expression.name.lower() in selected_names
1543
- ) or group_expression.find(exp.AggFunc, exp.Window, exp.Subquery) is not None:
1544
- return None # A position out of range, a name that may be a select alias, or not a key.
1545
- item = exp.alias_(group_expression.copy(), f"{HIDDEN_GROUPING}{len(items)}")
1546
- items.append(item)
1547
- grouped_items.add(id(item))
1548
- matched.append(item)
1549
- computed = {id(item) for item in select.expressions if self._computed_over_aggregates(_unaliased(item))}
1550
- if any(id(item) in computed for item in matched):
1551
- return None # A grouping position naming an item that aggregates.
1552
- items = [item for item in items if id(item) not in computed]
1553
- # Each part of a computed item is an output: an item or hidden item
1554
- # written the same, when repeatable, else a hidden item of its own.
1555
- parts: dict[int, Expr] = {}
1556
- for item in select.expressions:
1557
- if id(item) not in computed:
1558
- continue
1559
- for part in _aggregate_parts(_unaliased(item)):
1560
- text = part.sql(dialect=self.dialect)
1561
- same = next((
1562
- other for other in items if self._repeatable(part) and _unaliased(other).sql(dialect=self.dialect) == text
1563
- ), None)
1564
- if same is None:
1565
- same = exp.alias_(part.copy(), f"{HIDDEN_AGGREGATE}{len(items)}")
1566
- items.append(same)
1567
- parts[id(part)] = same
1568
- having = select.args.get("having")
1569
- if having is not None:
1570
- # An aggregate HAVING reads that no item writes: a hidden output,
1571
- # like a grouping key not selected, that `_lower_having` reads.
1572
- written = {_unaliased(item).sql(dialect=self.dialect) for item in items}
1573
- for call in _outermost_aggregate_calls(having.this):
1574
- text = call.sql(dialect=self.dialect)
1575
- if text not in written and self._repeatable(call):
1576
- written.add(text)
1577
- items.append(exp.alias_(call.copy(), f"{HIDDEN_AGGREGATE}{len(items)}"))
1578
-
1579
- output_columns = self._aggregate_output_columns(items, lowered, grouped_items)
1580
- grouping_outputs = [output_columns[next(index for index, item in enumerate(items) if item is match)] for match in matched]
1581
- # Each call of the items, then each call only HAVING writes.
1582
- written_calls = [
1583
- call for item in select.expressions for call in item.find_all(exp.AggFunc)
1584
- if call.find_ancestor(exp.Window, exp.Select) is select
1585
- ]
1586
- if having is not None:
1587
- texts = {call.sql(dialect=self.dialect) for call in written_calls}
1588
- for call in having.find_all(exp.AggFunc):
1589
- text = call.sql(dialect=self.dialect)
1590
- if call.find_ancestor(exp.Window, exp.Select) is select and text not in texts:
1591
- texts.add(text)
1592
- written_calls.append(call)
1593
- calls = tuple(
1594
- ir.AggregateCall(
1595
- origin=self._origin(call), description=call.sql(dialect=self.dialect),
1596
- arguments=tuple(
1597
- self._lower_expression(argument, lowered.bindings, schema_complete=lowered.relation.is_schema_complete)
1598
- for argument in _aggregate_arguments(call)
1599
- ),
1600
- )
1601
- for call in written_calls
1602
- )
1603
- aggregate = ir.Aggregate(
1604
- origin=self._origin(select), output_columns=output_columns, is_schema_complete=True, input=lowered.relation,
1605
- grouping_outputs=tuple(grouping_outputs), calls=calls,
1606
- )
1607
- relation: ir.RelationExpr = aggregate if having is None else self._lower_having(aggregate, items, having)
1608
- if len(items) == len(select.expressions) and all(item is written for item, written in zip(items, select.expressions)):
1609
- return relation
1610
- origin = self._origin(select)
1611
- position = {id(item): index for index, item in enumerate(items)}
1612
- selected: list[ir.OutputColumn] = []
1613
- for item in select.expressions:
1614
- if id(item) not in computed:
1615
- selected.extend(_pass_output_columns((relation.output_columns[position[id(item)]],), origin))
1616
- continue
1617
- values = {
1618
- part: ir.ColumnRef(origin=self._origin(other), column=relation.output_columns[position[id(other)]])
1619
- for part, other in parts.items()
1620
- }
1621
- self._grouped_values.update(values)
1622
- try:
1623
- value = self._lower_expression(_unaliased(item), (), schema_complete=True)
1624
- finally:
1625
- for key in values:
1626
- del self._grouped_values[key]
1627
- selected.append(ir.OutputColumn(origin=self._origin(item), name=item.alias_or_name, scalar_expr=value))
1628
- return ir.Project(origin=origin, output_columns=tuple(selected), is_schema_complete=True, input=relation)
1629
-
1630
- def _lower_having(self, aggregate: ir.Aggregate, items: list[Expr], having: exp.Having) -> ir.Filter:
1631
- """HAVING as a Filter of the grouped rows. A condition reads the
1632
- aggregate's output columns, so each part of it written as a select
1633
- item is that item's column (`count(*) > 1` beside `count(*) AS c` is
1634
- `c > 1`), and so is each aggregate no item writes, a hidden item
1635
- (`_lower_aggregate`). A conjunct still reading anything else (a column
1636
- neither grouped nor aggregated, an aggregate whose repeated text may
1637
- differ, a subquery) is opaque: it removes groups for a reason not
1638
- known, which keeps every fact that holds of the groups, and states
1639
- nothing of its own: no selected column can show it."""
1640
- qualifier = "__having"
1641
- bindings = tuple(_Binding(qualifier, f"c{index}", column) for index, column in enumerate(aggregate.output_columns))
1642
- written: dict[str, int] = {}
1643
- for index, item in enumerate(items):
1644
- expression = _unaliased(item)
1645
- if self._repeatable(expression):
1646
- written.setdefault(expression.sql(dialect=self.dialect), index)
1647
-
1648
- def selected(node: Expr) -> Expr:
1649
- index = written.get(node.sql(dialect=self.dialect))
1650
- return node if index is None or isinstance(node, exp.Literal) else exp.column(f"c{index}", table=qualifier)
1651
-
1652
- origin = self._origin(having)
1653
- parts: list[ir.ScalarExpr] = []
1654
- for conjunct in _filter_conjuncts(having.this):
1655
- rewritten = conjunct.copy().transform(selected)
1656
- unknown = any(
1657
- column.table != qualifier for column in rewritten.find_all(exp.Column)
1658
- ) or rewritten.find(exp.AggFunc, exp.Subquery, exp.Window) is not None
1659
- if unknown:
1660
- parts.append(ir.OpaqueExpression(origin=self._origin(conjunct), description=conjunct.sql(dialect=self.dialect)))
1661
- else:
1662
- parts.append(self._lower_expression(rewritten, bindings, schema_complete=True, line=_source_line(conjunct)))
1663
- return ir.Filter(
1664
- origin=origin, output_columns=_pass_output_columns(aggregate.output_columns, origin), is_schema_complete=True,
1665
- input=aggregate, predicate=_and(tuple(parts), origin),
1666
- )
1667
-
1668
- def _computed_over_aggregates(self, expression: Expr) -> bool:
1669
- """Whether a grouped select item computes a value from aggregate
1670
- calls, rather than being one: `max(sal) + 1`, not `max(sal)`. One
1671
- with a window or a subquery stays an Aggregate output."""
1672
- return (
1673
- not _is_aggregate_call(expression) and bool(_outermost_aggregate_calls(expression))
1674
- and expression.find(exp.Window, exp.Query, exp.Subquery) is None
1675
- )
1676
-
1677
- def _repeatable(self, expression: Expr) -> bool:
1678
- """Whether every occurrence of `expression`'s SQL text in one grouped
1679
- select has one value per group. Repeated text need not denote the same
1680
- evaluation: only modelled pure expressions and aggregates over pure
1681
- inputs qualify, not a literal (which a name may shadow)."""
1682
- return not isinstance(expression, exp.Literal) and all(
1683
- not isinstance(node, _NOT_A_FUNCTION_OF_ITS_COLUMNS)
1684
- and (not isinstance(node, exp.Func) or type(node) in dialect_builtins(self.semantics))
1685
- or isinstance(node, exp.Count | exp.Sum | exp.Min | exp.Max | exp.Avg | exp.Star)
1686
- for node in expression.walk()
1687
- )
1688
-
1689
- def _lower_distinct(self, lowered: _Lowered, select: exp.Select) -> ir.Distinct | None:
1690
- distinct = select.args.get("distinct")
1691
- if distinct is None or select.args.get("having") is not None or _star_only(select):
1692
- return None
1693
- if select.args.get("where") is not None:
1694
- lowered = self._filter(lowered, select.args["where"])
1695
- return ir.Distinct(
1696
- origin=self._origin(select), output_columns=self._selected_output_columns(select.expressions, lowered),
1697
- is_schema_complete=True, input=lowered.relation,
1698
- )
1699
-
1700
- def _lower_qualify(self, lowered: _Lowered, select: exp.Select, qualify: exp.Qualify) -> ir.QualifyByPartition | None:
1701
- window = _row_number_equals_one(qualify.this)
1702
- if window is None:
1703
- return None
1704
- order = window.args.get("order")
1705
- return self._one_row_per_partition(
1706
- lowered, select, window.args.get("partition_by") or (), order.expressions if order else (),
1707
- )
1708
-
1709
- def _qualified(self, relation: ir.RelationExpr | None, select: exp.Select, *, grouped: bool) -> ir.RelationExpr | None:
1710
- """`relation`, the groups (`grouped`) or distinct rows of `select`, after its
1711
- QUALIFY. Over groups, `row_number() OVER (PARTITION BY k...) = 1` with
1712
- every key a selected item keeps one row per partition. Any other
1713
- QUALIFY drops rows for a reason not known: an opaque Filter, which
1714
- keeps every fact of the rows and none that needs them all."""
1715
- qualify = select.args.get("qualify")
1716
- if relation is None or not isinstance(qualify, exp.Qualify):
1717
- return relation
1718
- origin = self._origin(qualify)
1719
- output_columns = _pass_output_columns(relation.output_columns, origin)
1720
- window = _row_number_equals_one(qualify.this)
1721
- if window is not None and grouped: # Not over DISTINCT: its window sees the rows before it.
1722
- positions = _partition_positions(window.args.get("partition_by") or (), select.expressions)
1723
- if positions and len(relation.output_columns) == len(select.expressions):
1724
- return ir.QualifyByPartition(
1725
- origin=origin, output_columns=output_columns, is_schema_complete=True, input=relation,
1726
- partition_outputs=tuple(output_columns[position] for position in positions),
1727
- )
1728
- return ir.Filter(
1729
- origin=origin, output_columns=output_columns, is_schema_complete=True, input=relation,
1730
- predicate=ir.OpaqueExpression(origin=origin, description=qualify.this.sql(dialect=self.dialect)),
1731
- )
1732
-
1733
- def _lower_distinct_on(self, lowered: _Lowered, select: exp.Select, on: Expr) -> ir.QualifyByPartition | None:
1734
- """`DISTINCT ON (k...)` keeps one row per distinct `k...`, like
1735
- `QUALIFY ROW_NUMBER() OVER (PARTITION BY k...) = 1`. Its ORDER BY only
1736
- picks which row survives, and may name outputs, so it is not lowered."""
1737
- if select.args.get("qualify") is not None:
1738
- return None
1739
- keys = on.expressions if isinstance(on, exp.Tuple) else [on]
1740
- return self._one_row_per_partition(lowered, select, keys, ())
1741
-
1742
- def _one_row_per_partition(
1743
- self, lowered: _Lowered, select: exp.Select, partitions: Sequence[Expr], order: Sequence[exp.Ordered],
1744
- ) -> ir.QualifyByPartition | None:
1745
- """Every partition key must be a selected output: the Unique Set is stated on outputs."""
1746
- if not partitions or select.args.get("having") is not None or _star_only(select):
1747
- return None
1748
- if select.args.get("where") is not None:
1749
- lowered = self._filter(lowered, select.args["where"])
1750
-
1751
- positions = _partition_positions(partitions, select.expressions)
1752
- if positions is None:
1753
- return None
1754
- output_columns = self._selected_output_columns(select.expressions, lowered)
1755
- partition_outputs = [output_columns[position] for position in positions]
1756
- ordering = tuple(
1757
- self._lower_expression(ordered.this, lowered.bindings, schema_complete=lowered.relation.is_schema_complete)
1758
- for ordered in order
1759
- )
1760
- return ir.QualifyByPartition(
1761
- origin=self._origin(select), output_columns=output_columns, is_schema_complete=True, input=lowered.relation,
1762
- partition_outputs=tuple(partition_outputs), ordering=ordering,
1763
- )
1764
-
1765
- def _selected_output_columns(self, items: list[Expr], lowered: _Lowered) -> tuple[ir.OutputColumn, ...]:
1766
- columns = []
1767
- for item in items:
1768
- expression = item.this if isinstance(item, exp.Alias) else item
1769
- value = self._lower_expression(expression, lowered.bindings, schema_complete=lowered.relation.is_schema_complete)
1770
- comparison_type = None
1771
- if isinstance(expression, exp.Cast):
1772
- kind = expression.to
1773
- if kind.this not in exp.DataType.TEXT_TYPES or (
1774
- isinstance(value, ir.Call) and (source := self._declared_type(value.arguments[0])) is not None
1775
- and source.this in exp.DataType.NUMERIC_TYPES
1776
- ):
1777
- comparison_type = self._comparison_type(exp.ColumnDef(kind=kind))
1778
- column = ir.OutputColumn(origin=self._origin(item), name=item.alias_or_name, scalar_expr=value, comparison_type=comparison_type)
1779
- if isinstance(expression, exp.Cast):
1780
- self._declared_types[column] = expression.to
1781
- columns.append(column)
1782
- return tuple(columns)
1783
-
1784
- def _aggregate_output_columns(self, items: list[Expr], source: _Lowered, grouped_items: set[int]) -> tuple[ir.OutputColumn, ...]:
1785
- """Each item of a grouped select. A column outside every aggregate must
1786
- be one the grouping determines (`_grouping_determined`): any other
1787
- (SQLite's bare column) makes its item opaque (ADR 0006)."""
1788
- grouped = {
1789
- id(item): self._lower_expression(
1790
- item.this if isinstance(item, exp.Alias) else item, source.bindings, schema_complete=source.relation.is_schema_complete,
1791
- )
1792
- for item in items if id(item) in grouped_items
1793
- }
1794
- determined = self._grouping_determined({
1795
- lowered.column for lowered in grouped.values() if isinstance(lowered, ir.ColumnRef)
1796
- }, source.relation)
1797
- # Grouped by nothing (no grouped items), the one row exists even
1798
- # over no input rows, where an aggregate of its values is NULL.
1799
- empty = not grouped_items
1800
- output_columns: list[ir.OutputColumn] = []
1801
- for item in items:
1802
- expression = item.this if isinstance(item, exp.Alias) else item
1803
- lowered = grouped[id(item)] if id(item) in grouped else self._lower_grouped(expression, source, determined, empty=empty)
1804
- if id(item) not in grouped_items and _reads_ungrouped_column(lowered, determined):
1805
- lowered = ir.OpaqueExpression(origin=self._origin(expression), description=expression.sql(dialect=self.dialect))
1806
- self._unsupported.append((lowered, "a column neither grouped nor inside an aggregate"))
1807
- output_columns.append(ir.OutputColumn(origin=self._origin(item), name=item.alias_or_name, scalar_expr=lowered))
1808
- return tuple(output_columns)
1809
-
1810
- def _lower_grouped(
1811
- self, expression: Expr, source: _Lowered, determined: Callable[[ir.OutputColumn], bool], *, empty: bool,
1812
- ) -> ir.ScalarExpr:
1813
- """`expression`, computed once per group of `source`'s rows: each
1814
- aggregate call is its value (`_aggregate_value`), and each column
1815
- outside them the grouping determines is one value per group, an
1816
- AnyAggregate. Any other column is left as it is, for the caller to
1817
- reject; windows and subqueries are not entered."""
1818
- values: dict[int, ir.ScalarExpr] = {}
1819
- pending: list[Expr] = [expression]
1820
- while pending:
1821
- node = pending.pop()
1822
- if isinstance(node, exp.Window | exp.Query | exp.Subquery):
1823
- continue
1824
- if _is_aggregate_call(node):
1825
- value = self._aggregate_value(node, source, empty=empty)
1826
- if value is not None:
1827
- values[id(node)] = value
1828
- continue
1829
- if isinstance(node, exp.Column):
1830
- column = self._lower_expression(node, source.bindings, schema_complete=source.relation.is_schema_complete)
1831
- if isinstance(column, ir.ColumnRef) and determined(column.column):
1832
- values[id(node)] = ir.AnyAggregate(origin=column.origin, input=column, empty=empty)
1833
- continue
1834
- pending.extend(node.iter_expressions())
1835
- self._grouped_values.update(values)
1836
- try:
1837
- return self._lower_expression(expression, source.bindings, schema_complete=source.relation.is_schema_complete)
1838
- finally:
1839
- for key in values:
1840
- del self._grouped_values[key]
1841
-
1842
- def _aggregate_value(self, call: Expr, source: _Lowered, *, empty: bool) -> ir.ScalarExpr | None:
1843
- """The value of an aggregate `call` over a group of `source`'s rows,
1844
- or None when it is not modelled. `min`, `max` and `any_value` pick a
1845
- value of their argument (AnyAggregate), `sum` and `avg` accumulate
1846
- its non-null values where that is never NULL (Accumulation,
1847
- `checked_sum`), and `count` is never NULL. One with FILTER may
1848
- see none of the group's rows: NULL, but for count."""
1849
- if isinstance(call, exp.Filter):
1850
- call, empty = call.this, True
1851
- origin = self._origin(call)
1852
-
1853
- def lower(argument: Expr) -> ir.ScalarExpr:
1854
- return self._lower_expression(argument, source.bindings, schema_complete=source.relation.is_schema_complete)
1855
-
1856
- if isinstance(call, exp.Count):
1857
- return ir.Count(origin=origin, description=call.sql(dialect=self.dialect))
1858
- if (argument := _picked_argument(call)) is not None:
1859
- # One of its argument's values on some row of the group.
1860
- return ir.AnyAggregate(origin=origin, input=lower(argument), empty=empty)
1861
- if (argument := _aggregate_argument(call, (exp.Sum, exp.Avg), distinct=True)) is not None and self.semantics.checked_sum:
1862
- # Elsewhere an overflow or NaN over non-null values may be NULL.
1863
- return ir.Accumulation(origin=origin, input=lower(argument), empty=empty)
1864
- return None
1865
-
1866
- def _grouping_determined(self, grouping: set[ir.OutputColumn], relation: ir.RelationExpr) -> Callable[[ir.OutputColumn], bool]:
1867
- """Whether its `grouping` columns determine a column of `relation`: one of those,
1868
- and every column of a table occurrence whose primary key, declared in
1869
- the SQL, they include (SQL's functional dependence on a key, which
1870
- PostgreSQL and MySQL accept)."""
1871
- occurrences: dict[ir.OutputColumn, ir.Alias] = {}
1872
- pending: list[ir.RelationExpr] = [relation]
1873
- while pending:
1874
- node = pending.pop()
1875
- if isinstance(node, ir.Alias):
1876
- occurrences.update((output, node) for output in node.output_columns)
1877
- else:
1878
- pending.extend(child for child in ir.children(node) if isinstance(child, ir.RelationExpr))
1879
-
1880
- def occurrence(column: ir.OutputColumn) -> tuple[ir.Alias | None, ir.OutputColumn]:
1881
- while column not in occurrences and isinstance(column.scalar_expr, ir.ColumnRef):
1882
- column = column.scalar_expr.column
1883
- return occurrences.get(column), column
1884
-
1885
- keyed: set[ir.Alias] = set()
1886
- grouped_names: dict[ir.Alias, set[str]] = {}
1887
- for column in grouping:
1888
- alias, output = occurrence(column)
1889
- if alias is not None:
1890
- grouped_names.setdefault(alias, set()).add(output.name.lower())
1891
- for alias, names in grouped_names.items():
1892
- symbol = next((symbol for symbol, named in self._named_relations.items() if named is alias.source), None)
1893
- key = None if symbol is None or symbol.role is not ir.RelationRole.TABLE or symbol.statement is None else _primary_key(symbol)
1894
- if key and {name.lower() for name in key} <= names:
1895
- keyed.add(alias)
1896
- return lambda column: column in grouping or occurrence(column)[0] in keyed
1897
-
1898
- def _lower_expression(
1899
- self, expression: Expr, bindings: tuple[_Binding, ...], *, schema_complete: bool = False, line: int | None = None
1900
- ) -> ir.ScalarExpr:
1901
- """An unqualified column resolves by name across several sources only
1902
- when every source's schema is complete: otherwise the one visible match
1903
- might be shadowed by a column of a source whose columns are unknown.
1904
-
1905
- A Builtin becomes a Call; any other function or operator an
1906
- OpaquePureFunction of its lowered arguments, unless its value is not a
1907
- function of them (`_NOT_A_FUNCTION_OF_ITS_COLUMNS`)."""
1908
- origin = self._origin(expression, line)
1909
- if (grouped := self._grouped_values.get(id(expression))) is not None:
1910
- return grouped
1911
-
1912
- def lower(node: Expr) -> ir.ScalarExpr:
1913
- return self._lower_expression(node, bindings, schema_complete=schema_complete)
1914
-
1915
- if isinstance(expression, exp.Subquery) and id(expression) in self._scalar_values:
1916
- qualifier = self._scalar_values[id(expression)]
1917
- value = next((binding.column for binding in bindings if binding.qualifier == qualifier), None)
1918
- if value is not None:
1919
- return ir.ColumnRef(origin=origin, column=value)
1920
- if id(expression) in self._set_returning_values:
1921
- qualifier = self._set_returning_values[id(expression)]
1922
- value = next((binding.column for binding in bindings if binding.qualifier == qualifier), None)
1923
- if value is not None:
1924
- return ir.ColumnRef(origin=origin, column=value)
1925
- if isinstance(expression, exp.Column) and id(expression) in self._scoped_columns:
1926
- column = self._scoped_columns[id(expression)]
1927
- if any(binding.column is column for binding in bindings):
1928
- return ir.ColumnRef(origin=origin, column=column)
1929
- if isinstance(expression, exp.Column):
1930
- if expression.table:
1931
- schema = _schema_path(expression)
1932
- matches = [
1933
- binding for binding in bindings
1934
- if binding.qualifier == expression.table.lower() and binding.name == expression.name.lower() and (not schema or binding.schema == schema)
1935
- ]
1936
- elif schema_complete or len({
1937
- binding.qualifier for binding in bindings if not binding.qualifier.startswith((_SCALAR_QUALIFIER, _USING_QUALIFIER))
1938
- }) == 1:
1939
- matches = [binding for binding in bindings if binding.name == expression.name.lower() and not binding.shadowed]
1940
- else:
1941
- matches = []
1942
- sources = ", ".join(dict.fromkeys(binding.qualifier for binding in bindings))
1943
- self._warnings.append(Diagnostic(
1944
- diag.AMBIGUOUS_COLUMN,
1945
- f"column {quoted(expression.name)} is unqualified and more than one source may own it ({sources}), "
1946
- "since some have no declared columns: qualify it, declare those tables with CREATE TABLE, "
1947
- "or analyze with a database connection (analyze_database)",
1948
- origin if origin.line is not None else replace(origin, line=_source_line(expression)),
1949
- ))
1950
- if len(matches) == 1:
1951
- return ir.ColumnRef(origin=origin, column=matches[0].column)
1952
- return ir.OpaqueExpression(origin=origin, description=expression.sql(dialect=self.dialect))
1953
- if isinstance(expression, _COMPARISONS):
1954
- self._check_zoned_text(expression, lower, self._origin(expression, line or _source_line(expression)))
1955
- description = expression.sql(dialect=self.dialect)
1956
- quantified = isinstance(expression, exp.Binary) and any(
1957
- isinstance(operand, (exp.Any, exp.All)) for operand in (expression.this, expression.expression)
1958
- ) # `n > ANY (...)` is FALSE over no rows, even for a NULL `n`.
1959
- match expression:
1960
- case exp.Paren():
1961
- return self._lower_expression(expression.this, bindings, schema_complete=schema_complete, line=line)
1962
- case exp.Collate():
1963
- return ir.OpaqueExpression(origin=origin, description=description) # `parse` warns.
1964
- case exp.Null():
1965
- return ir.NullLiteral(origin=origin)
1966
- case exp.Count():
1967
- return ir.Count(origin=origin, description=description)
1968
- case exp.Coalesce():
1969
- return ir.Coalesce(origin=origin, arguments=tuple(lower(argument) for argument in (expression.this, *expression.expressions)))
1970
- case exp.Case() if expression.this is not None:
1971
- return self._lower_case(expression, bindings, schema_complete=schema_complete)
1972
- case exp.And():
1973
- return self._lower_condition(expression, _conjuncts(expression), bindings, schema_complete=schema_complete)
1974
- case exp.Or():
1975
- return ir.Or(origin=origin, parts=tuple(
1976
- self._lower_condition(branch, _conjuncts(branch), bindings, schema_complete=schema_complete)
1977
- for branch in _disjuncts(expression)
1978
- ))
1979
- case exp.EQ() if not quantified:
1980
- return ir.Equality(
1981
- origin=origin, left=lower(expression.this), right=lower(expression.expression),
1982
- total=self._checked_comparison(expression, lower),
1983
- )
1984
- case exp.NullSafeEQ() if not quantified:
1985
- return ir.NullSafeEquality(
1986
- origin=origin, left=lower(expression.this), right=lower(expression.expression),
1987
- rejects=self._checked_comparison(expression, lower),
1988
- )
1989
- case exp.NullSafeNEQ() if not quantified:
1990
- return ir.Call(origin=origin, function=_IS_DISTINCT_FROM, arguments=(lower(expression.this), lower(expression.expression)), description=description)
1991
- case exp.EQ() | exp.NEQ() | exp.GT() | exp.GTE() | exp.LT() | exp.LTE() if isinstance(expression.expression, exp.Any) and not isinstance(expression.this, (exp.Any, exp.All)):
1992
- function = _any_comparison(type(expression))
1993
- arguments = (lower(expression.this), lower(expression.expression))
1994
- return ir.Call(origin=origin, function=function, arguments=arguments, description=description)
1995
- case exp.Exists():
1996
- subquery = ir.OpaqueExpression(origin=origin, description=description)
1997
- return ir.Call(origin=origin, function=_EXISTS, arguments=(subquery,), description=description)
1998
- case exp.Is(expression=exp.Null()):
1999
- return ir.IsNull(origin=origin, operand=lower(expression.this))
2000
- case exp.Is(expression=exp.Boolean() as truth):
2001
- function = _IS_TRUE if truth.this else _IS_FALSE
2002
- return ir.Call(origin=origin, function=function, arguments=(lower(expression.this),), description=description)
2003
- case exp.Not(this=exp.Is(expression=exp.Null()) as test):
2004
- return ir.IsNotNull(origin=origin, operand=lower(test.this))
2005
- case exp.In() if expression.expressions and not any(expression.args.get(key) for key in ("query", "unnest", "field")):
2006
- return ir.InList(origin=origin, operand=lower(expression.this), values=tuple(lower(value) for value in expression.expressions))
2007
- case _:
2008
- pass
2009
- value = literal_value(expression) or _cast_integer_literal(expression)
2010
- if value == ir.LiteralValue(type="string", text="") and self.semantics.empty_string_is_null:
2011
- return ir.NullLiteral(origin=origin)
2012
- if value is not None or isinstance(expression, exp.Literal):
2013
- return ir.Constant(origin=origin, value=value)
2014
- builtin = dialect_builtins(self.semantics).get(type(expression))
2015
- if builtin is not None and not quantified:
2016
- function, keys = builtin
2017
- if type(expression) is exp.Cast and function.total is not None and self._is_json(expression.this, lower):
2018
- # `CAST(JSON 'null' AS BIGINT)` is NULL.
2019
- function = replace(function, total=None)
2020
- values = [value for key in keys for value in _as_list(expression.args[key])]
2021
- # `trim(x, chars)` and `floor(x, 2)` read more than their Builtin's arguments.
2022
- extra = type(expression) in _ONE_ARGUMENT_BUILTINS and any(
2023
- value for key, value in expression.args.items() if key not in keys
2024
- )
2025
- if function.accepts(len(values)) and not extra:
2026
- arguments = tuple(lower(value) for value in values)
2027
- if (
2028
- type(expression) is exp.Like and self.semantics.text_is_binary
2029
- and isinstance(arguments[1], ir.Constant)
2030
- and (pattern := arguments[1].value) is not None and pattern.type == "string"
2031
- and not any(character in pattern.text for character in "%_\\")
2032
- and expression.find_ancestor(exp.Escape) is None
2033
- and (kind := self._declared_type(arguments[0], through_sets=False)) is not None
2034
- and kind.this in _TEXT_TYPES
2035
- ):
2036
- return ir.Equality(origin=origin, left=arguments[0], right=arguments[1], total=True)
2037
- composites = [
2038
- (value, argument) for value, argument in zip(values, arguments)
2039
- if function.name in _ORDER_COMPARISONS and function.total is not None and self._is_composite(value, lower)
2040
- ]
2041
- if composites:
2042
- function, arguments = self._composite_comparison(expression, function, arguments, composites, self._origin(expression, line or _source_line(expression)))
2043
- return ir.Call(origin=origin, function=function, arguments=arguments, description=description)
2044
- if isinstance(expression, _NOT_A_FUNCTION_OF_ITS_COLUMNS):
2045
- opaque = ir.OpaqueExpression(origin=origin, description=description)
2046
- if isinstance(expression, exp.Window):
2047
- self._unsupported.append((opaque, "a window function (other than QUALIFY row_number() ... = 1)"))
2048
- return opaque
2049
- return ir.OpaquePureFunction(origin=origin, arguments=tuple(lower(child) for child in expression.iter_expressions()), description=description)
2050
-
2051
- def _checked_comparison(self, comparison: exp.Binary, lower: Callable[[Expr], ir.ScalarExpr]) -> bool:
2052
- """Whether `comparison` compares its operands' values as they are:
2053
- where a failed implicit cast raises, and neither is a composite, which
2054
- may hold a NULL element."""
2055
- return self.semantics.casts_raise and not any(
2056
- self._is_composite(operand, lower) for operand in (comparison.this, comparison.expression)
2057
- )
2058
-
2059
- def _check_zoned_text(self, comparison: Expr, lower: Callable[[Expr], ir.ScalarExpr], origin: Origin) -> None:
2060
- """Warn of a comparison with a CAST of a zoned timestamp, where it keeps
2061
- its zone: equal instants cast to different text (or dates, or local
2062
- times), so the comparison depends on the zone each value was given."""
2063
- if self.semantics.zoned_timestamp_is_instant or id(comparison) in self._zone_checked:
2064
- return
2065
- self._zone_checked.add(id(comparison))
2066
- operands = [comparison.this, *_as_list(comparison.args.get("expression") or []), *comparison.expressions]
2067
- operands += [comparison.args[key] for key in ("low", "high") if comparison.args.get(key) is not None]
2068
- for operand in operands:
2069
- while isinstance(operand, exp.Paren):
2070
- operand = operand.this
2071
- if not isinstance(operand, exp.Cast) or operand.to.this in _ZONED_TYPES or not isinstance(operand.this, exp.Column):
2072
- continue
2073
- kind = self._declared_type(lower(operand.this))
2074
- if kind is None or kind.this not in _ZONED_TYPES:
2075
- continue
2076
- cast = operand.sql(dialect=self.dialect)
2077
- self._warnings.append(Diagnostic(
2078
- diag.ZONED_TIMESTAMP_CAST,
2079
- f"{cast} is compared, but a {kind.sql(dialect=self.dialect)} keeps the zone it was given in {self.dialect}, "
2080
- "so equal instants cast to different values and the comparison depends on each value's zone: "
2081
- "compare the timestamps themselves, or convert to one zone first (AT TIME ZONE 'UTC')",
2082
- origin,
2083
- ))
2084
-
2085
- def _composite_comparison(
2086
- self, comparison: Expr, function: ir.Builtin, arguments: tuple[ir.ScalarExpr, ...],
2087
- composites: list[tuple[Expr, ir.ScalarExpr]], origin: Origin,
2088
- ) -> tuple[ir.Builtin, tuple[ir.ScalarExpr, ...]]:
2089
- """A comparison of composites (ARRAYs, ROWs, MAPs), non-null only when
2090
- no element is NULL either: `ARRAY[1, NULL] <> ARRAY[1, NULL]` is NULL in
2091
- Trino. So it also takes each composite operand's Elements, as a
2092
- non-strict, total argument. A composite column or CAST, whose elements
2093
- the SQL does not show, is noted for a warning."""
2094
- assert function.total is not None
2095
- extra = len(composites)
2096
- widened = ir.Builtin(
2097
- name=function.name, strict=function.strict + (False,) * extra, total=function.total + (True,) * extra, injective=False,
2098
- )
2099
- elements = tuple(ir.Elements(origin=argument.origin, operand=argument) for _, argument in composites)
2100
- for value, argument in composites:
2101
- while isinstance(value, exp.Paren):
2102
- value = value.this
2103
- if isinstance(value, (exp.Column, exp.Cast)) and id(value) not in self._composite_comparisons:
2104
- self._composite_comparisons[id(value)] = (origin, comparison.sql(dialect=self.dialect), value.sql(dialect=self.dialect), argument)
2105
- return widened, arguments + elements
2106
-
2107
- def _composite_warnings(self) -> list[Diagnostic]:
2108
- """A warning for each composite operand whose elements no NOT NULL
2109
- ELEMENTS declaration covers, on it or on a column it passes on from."""
2110
- declared = {column for item in self._declarations if isinstance(item, NonNullElements) for column in item.columns}
2111
- warnings = []
2112
- for origin, comparison, operand, argument in self._composite_comparisons.values():
2113
- expression, covered = argument, False
2114
- while isinstance(expression, ir.ColumnRef) and not covered:
2115
- covered = expression.column in declared
2116
- expression = expression.column.scalar_expr
2117
- if not covered:
2118
- warnings.append(Diagnostic(
2119
- diag.COMPOSITE_COMPARISON,
2120
- f"{comparison} compares {operand}, which may hold a NULL element, and a comparison of composites with "
2121
- "a NULL element may be NULL (it is in Trino), so it is not taken to be non-null: if its elements are "
2122
- "never NULL, say so with /**DECLARE NOT NULL ELEMENTS(...)**/ on a Select Expression that outputs it",
2123
- origin,
2124
- ))
2125
- return warnings
2126
-
2127
- def _is_composite(self, node: Expr, lower: Callable[[Expr], ir.ScalarExpr]) -> bool:
2128
- """Whether the operand may be composite, including unknown column types."""
2129
- match node:
2130
- case exp.Paren() | exp.Nullif():
2131
- return self._is_composite(node.this, lower)
2132
- case exp.Cast():
2133
- return node.to.this in _COMPOSITE_TYPES
2134
- case exp.Column():
2135
- kind = self._declared_type(lower(node))
2136
- return self.dialect in {"trino", "postgres"} if kind is None else kind.this in _COMPOSITE_TYPES
2137
- case exp.Array() | exp.Struct() | exp.Map() | exp.VarMap():
2138
- return True
2139
- case exp.Coalesce():
2140
- return any(self._is_composite(each, lower) for each in (node.this, *node.expressions))
2141
- case exp.Case():
2142
- arms = [arm.args["true"] for arm in node.args.get("ifs") or ()]
2143
- default = node.args.get("default")
2144
- return any(self._is_composite(each, lower) for each in (*arms, *([default] if default is not None else [])))
2145
- case exp.If():
2146
- false = node.args.get("false")
2147
- return any(self._is_composite(each, lower) for each in (node.args["true"], *([false] if false is not None else [])))
2148
- case _:
2149
- return False
2150
-
2151
- def _is_json(self, node: Expr, lower: Callable[[Expr], ir.ScalarExpr]) -> bool:
2152
- """Whether the operand may be JSON or VARIANT, whose null can cast to SQL NULL."""
2153
- match node:
2154
- case exp.Paren() | exp.Nullif():
2155
- return self._is_json(node.this, lower)
2156
- case exp.Cast():
2157
- return node.to.this in _JSON_TYPES
2158
- case exp.Column():
2159
- kind = self._declared_type(lower(node))
2160
- return kind is None or kind.this in _JSON_TYPES
2161
- case exp.ParseJSON() | exp.JSONExtract() | exp.JSONBExtract() | exp.JSONObject() | exp.JSONArray() | exp.JSONObjectAgg() | exp.JSONArrayAgg():
2162
- return True
2163
- case exp.Coalesce():
2164
- return any(self._is_json(each, lower) for each in (node.this, *node.expressions))
2165
- case exp.Case():
2166
- arms = [arm.args["true"] for arm in node.args.get("ifs") or ()]
2167
- default = node.args.get("default")
2168
- return any(self._is_json(each, lower) for each in (*arms, *([default] if default is not None else [])))
2169
- case exp.If():
2170
- false = node.args.get("false")
2171
- return any(self._is_json(each, lower) for each in (node.args["true"], *([false] if false is not None else [])))
2172
- case _:
2173
- return False
2174
-
2175
- def _declared_type(self, expression: ir.ScalarExpr, *, through_sets: bool = True) -> exp.DataType | None:
2176
- """The type a CREATE TABLE declares for the column `expression` reads,
2177
- through every column that passes it on. A set operation passes on its
2178
- left input's type, which hazard checks want; `through_sets=False`
2179
- stops there instead, for a rewrite that the right input's values must
2180
- also satisfy."""
2181
- while isinstance(expression, ir.ColumnRef):
2182
- column = expression.column
2183
- if not through_sets and column in self._set_outputs:
2184
- return None
2185
- if column in self._declared_types:
2186
- return self._declared_types[column]
2187
- expression = column.scalar_expr
2188
- return None
2189
-
2190
- def _lower_case(self, case: exp.Case, bindings: tuple[_Binding, ...], *, schema_complete: bool) -> ir.SimpleCase:
2191
- """A simple CASE, and the assertion its marker states, once per CASE."""
2192
-
2193
- def lower(expression: Expr) -> ir.ScalarExpr:
2194
- return self._lower_expression(expression, bindings, schema_complete=schema_complete)
2195
-
2196
- arms = case.args.get("ifs") or ()
2197
- default = case.args.get("default")
2198
- lowered = ir.SimpleCase(
2199
- origin=self._origin(case),
2200
- operand=lower(case.this),
2201
- whens=tuple(lower(arm.this) for arm in arms),
2202
- thens=tuple(lower(arm.args["true"]) for arm in arms),
2203
- default=lower(default) if default is not None else ir.NullLiteral(origin=self._origin(case)),
2204
- )
2205
- if id(case) not in self._sited_cases:
2206
- self._sited_cases.add(id(case))
2207
- self._add_attachment_site(case, f"CASE {case.this.sql(dialect=self.dialect)}", lowered, trailing=False)
2208
- span = exhaustive_span(case)
2209
- if span is not None and id(case) not in self._handled_cases:
2210
- self._handled_cases.add(id(case))
2211
- origin = Origin.marked(case.sql(dialect=self.dialect), span)
2212
- self._assertions.append(ir.Assertion(origin=origin, property=ExhaustiveCase(case=lowered)))
2213
- return lowered
2214
-
2215
- def _opaque_relation(self, source: Expr, names=()) -> ir.OpaqueRelation:
2216
- origin = self._origin(source)
2217
- return ir.OpaqueRelation(
2218
- origin=origin,
2219
- output_columns=self._opaque_output_columns(names, origin),
2220
- is_schema_complete=False,
2221
- description=source.sql(dialect=self.dialect),
2222
- )
2223
-
2224
- # Assertions and diagnostics --------------------------------------------
2225
-
2226
- def _register_column_markers(self, relation: ir.RelationExpr, select: exp.Query) -> None:
2227
- by_name = {output.name.lower(): output for output in relation.output_columns}
2228
- ambiguous = {name for name, count in Counter(output.name.lower() for output in relation.output_columns).items() if count > 1}
2229
- for marker in column_markers(select):
2230
- kind, columns, line = marker.kind, marker.columns, marker.span.line
2231
- self._handled_column_markers.add(id(marker))
2232
- origin = Origin.marked(select.sql(dialect=self.dialect), marker.span)
2233
- duplicates = [column for column in (*columns, *marker.dependent) if column.lower() in ambiguous]
2234
- if duplicates:
2235
- self._diagnostics.append(Diagnostic(
2236
- diag.UNRESOLVED_ASSERTED_COLUMN, f"output names {quoted_all(duplicates)} are ambiguous; use distinct aliases", origin,
2237
- ))
2238
- continue
2239
- unknown = [column for column in (*columns, *marker.dependent) if column.lower() not in by_name]
2240
- if unknown and relation.is_schema_complete:
2241
- self._diagnostics.append(
2242
- Diagnostic(
2243
- diag.UNKNOWN_ASSERTED_COLUMN,
2244
- f"the {MARKER_NOUNS[kind]} on line {line} names {', '.join(unknown)}, which is not among this Select Expression's own output columns",
2245
- origin,
2246
- )
2247
- )
2248
- continue
2249
- if unknown:
2250
- # The column may exist in a source whose columns are unknown,
2251
- # so it is neither absent nor something to state a Property of.
2252
- self._diagnostics.append(
2253
- Diagnostic(
2254
- diag.UNRESOLVED_ASSERTED_COLUMN,
2255
- f"the {MARKER_NOUNS[kind]} on line {line} names {', '.join(unknown)}, which cannot be resolved: "
2256
- "this Select Expression reads a relation whose columns are unknown (declare it with CREATE TABLE)",
2257
- origin,
2258
- )
2259
- )
2260
- continue
2261
- members = frozenset(by_name[column.lower()] for column in columns)
2262
- dependent = frozenset(by_name[column.lower()] for column in marker.dependent)
2263
- match kind:
2264
- case "foreign-key" | "declared-foreign-key":
2265
- self._marker_references.append(_MarkerReference(
2266
- marker, kind, origin, tuple(by_name[column.lower()] for column in columns),
2267
- self._marker_targets[id(marker)], len(self._assertions),
2268
- ))
2269
- case "unique":
2270
- self._assertions.append(ir.Assertion(origin=origin, property=UniqueSet(columns=members)))
2271
- case "key":
2272
- self._assertions.append(ir.Assertion(origin=origin, property=NonNullUniqueSet(columns=members)))
2273
- case "not-null":
2274
- self._assertions.append(ir.Assertion(origin=origin, property=NonNullColumns(columns=members)))
2275
- case "declared-unique":
2276
- self._declarations.append(UniqueSet(columns=members))
2277
- case "declared-key":
2278
- # Non-nullness is declared per column too, so it outlives
2279
- # projections that drop part of a composite key.
2280
- self._declarations.append(NonNullUniqueSet(columns=members))
2281
- self._declarations.extend(NonNullColumn(column=column) for column in members)
2282
- case "declared-not-null":
2283
- self._declarations.extend(NonNullColumn(column=column) for column in members)
2284
- case "not-null-elements":
2285
- self._assertions.append(ir.Assertion(origin=origin, property=NonNullElements(columns=members)))
2286
- case "declared-not-null-elements":
2287
- # One per column, so each column's elements are known on their own.
2288
- self._declarations.extend(NonNullElements(columns=frozenset({column})) for column in members)
2289
- case "determines":
2290
- property = FunctionalDependency(determinant=members, dependent=dependent)
2291
- self._assertions.append(ir.Assertion(origin=origin, property=property))
2292
- case "declared-determines":
2293
- self._declarations.append(FunctionalDependency(determinant=members, dependent=dependent))
2294
- case "enum" | "declared-enum":
2295
- column, = members
2296
- values = frozenset(marker.values)
2297
- domain = EnumeratedDomain(column=column, values=values)
2298
- if kind == "enum":
2299
- self._assertions.append(ir.Assertion(origin=origin, property=domain))
2300
- else:
2301
- self._declarations.append(domain)
2302
- case _:
2303
- assert_never(kind)
2304
-
2305
- def _add_attachment_site(
2306
- self, node: exp.Join | exp.Query | exp.Case, label: str, relation: ir.RelationExpr | ir.SimpleCase, *, trailing: bool
2307
- ) -> None:
2308
- position = marker_position(node)
2309
- if position is not None:
2310
- offset, line = position
2311
- self._attachment_sites.append((AttachmentSite(label, line, offset, trailing), relation))
2312
-
2313
- def _link_marker_references(self) -> None:
2314
- """Lower each Foreign Key marker's referenced relation, then state the
2315
- marker's Property; assertions keep the place their marker was written."""
2316
- placed: list[tuple[int, ir.Assertion]] = []
2317
- while self._marker_references:
2318
- pending = self._marker_references.pop(0)
2319
- target = self._resolve_symbol(pending.target)
2320
- marker = pending.marker
2321
- referenced = self._columns_named(target, marker.referenced_columns)
2322
- if referenced is None:
2323
- self._diagnostics.append(Diagnostic(
2324
- diag.UNKNOWN_REFERENCED_COLUMN,
2325
- f"the {MARKER_NOUNS[marker.kind]} on line {marker.span.line} references "
2326
- f"{target.name}({quoted_all(marker.referenced_columns)}), but {target.name} has no column "
2327
- f"{quoted_all(_missing(target, marker.referenced_columns))}",
2328
- pending.origin,
2329
- ))
2330
- continue
2331
- match pending.kind:
2332
- case "foreign-key":
2333
- placed.append((pending.position, ir.Assertion(
2334
- origin=pending.origin, property=ForeignKey(columns=pending.columns, referenced_columns=referenced),
2335
- )))
2336
- case "declared-foreign-key":
2337
- self._declarations.append(ReferentialCoverage(columns=pending.columns, referenced_columns=referenced))
2338
- case _:
2339
- assert_never(pending.kind)
2340
- # Descending, so earlier positions stay valid; ties keep written order.
2341
- for position, assertion in reversed(placed):
2342
- self._assertions.insert(position, assertion)
2343
-
2344
- def _link_constraint_references(self) -> None:
2345
- for reference in self._constraint_references:
2346
- table = self._resolve_symbol(reference.table)
2347
- target = self._resolve_symbol(reference.target)
2348
- target_names = reference.target_columns
2349
- if target_names is None:
2350
- if reference.target.statement is None:
2351
- continue # An undeclared table's primary key is unknown.
2352
- target_names = _primary_key(reference.target)
2353
- if target_names is None:
2354
- self._diagnostics.append(Diagnostic(
2355
- diag.UNKNOWN_REFERENCED_COLUMN,
2356
- f"a foreign key of {table.name} references {target.name} without columns, "
2357
- f"and {target.name} declares no primary key",
2358
- reference.origin,
2359
- ))
2360
- continue
2361
- columns = self._columns_named(table, reference.columns)
2362
- if columns is None or len(reference.columns) != len(target_names):
2363
- self._diagnostics.append(Diagnostic(
2364
- diag.INVALID_FOREIGN_KEY_CONSTRAINT,
2365
- f"a foreign key of {table.name} must pair columns of its own with equally many columns of "
2366
- f"{target.name}: ({quoted_all(reference.columns)}) references ({quoted_all(target_names)})",
2367
- reference.origin,
2368
- ))
2369
- continue
2370
- referenced = self._columns_named(target, target_names)
2371
- if referenced is None:
2372
- self._diagnostics.append(Diagnostic(
2373
- diag.UNKNOWN_REFERENCED_COLUMN,
2374
- f"a foreign key of {table.name} references {target.name}({quoted_all(target_names)}), "
2375
- f"but {target.name} has no column {quoted_all(_missing(target, target_names))}",
2376
- reference.origin,
2377
- ))
2378
- continue
2379
- trust = self._key_trust(reference.node, reference.table, reference.columns)
2380
- if trust is not None:
2381
- (self._knowledge if trust == "enforced" else self._declarations).append(
2382
- ReferentialCoverage(columns=columns, referenced_columns=referenced)
2383
- )
2384
-
2385
- def _columns_named(self, relation: ir.RelationExpr, names: Iterable[str]) -> tuple[ir.OutputColumn, ...] | None:
2386
- by_name = {column.name.lower(): column for column in relation.output_columns}
2387
- columns = [by_name.get(name.lower()) for name in names]
2388
- found = tuple(column for column in columns if column is not None)
2389
- return found if len(found) == len(columns) else None
2390
-
2391
- def _report_cycle(self, symbol: _Symbol, table: exp.Table) -> None:
2392
- if symbol in self._reported_cycles:
2393
- return
2394
- self._reported_cycles.add(symbol)
2395
- self._diagnostics.append(
2396
- Diagnostic(
2397
- diag.RECURSIVE_VIEW_DEFINITION,
2398
- f"view {symbol.name.lower()} is defined recursively, which is not supported",
2399
- Origin(SQL, table.sql(dialect=self.dialect)),
2400
- )
2401
- )
2402
-
2403
- def _report_unanalyzed(self, ast: ParsedProgram) -> None:
2404
- for join in _asserted_joins(ast):
2405
- origin, kind = join_origin(join, self.dialect), join_marker_kind(join)
2406
- if id(join) in self._handled_joins:
2407
- continue
2408
- assert kind is not None, "every asserted join records its marker kind"
2409
- self._diagnostics.append(
2410
- Diagnostic(
2411
- diag.UNANALYZED_ASSERTION,
2412
- f"the {JOIN_MARKER_NOUNS[kind]} assertion on line {origin.line} "
2413
- "is in a part of the program this analysis does not model",
2414
- origin,
2415
- )
2416
- )
2417
- for case in _asserted_cases(ast):
2418
- if id(case) in self._handled_cases:
2419
- continue
2420
- span = exhaustive_span(case)
2421
- assert span is not None, "every asserted case records its marker span"
2422
- self._diagnostics.append(
2423
- Diagnostic(
2424
- diag.UNANALYZED_ASSERTION,
2425
- f"the exhaustive assertion on line {span.line} is in a part of the program this analysis does not model",
2426
- Origin.marked(case.sql(dialect=self.dialect), span),
2427
- )
2428
- )
2429
- for select in _asserted_selects(ast):
2430
- for marker in column_markers(select):
2431
- if id(marker) in self._handled_column_markers:
2432
- continue
2433
- self._diagnostics.append(
2434
- Diagnostic(
2435
- diag.UNANALYZED_ASSERTION,
2436
- f"the {MARKER_NOUNS[marker.kind]} on line {marker.span.line} is in a part of the program this analysis does not model",
2437
- Origin.marked(select.sql(dialect=self.dialect), marker.span),
2438
- )
2439
- )
2440
-
2441
- def _table_knowledge(self, relation: ir.NamedRelation, symbol: _Symbol) -> None:
2442
- """A declared table's ENUM types, NOT NULL columns, keys and CHECK
2443
- domains: Knowledge where the dialect enforces them, Property
2444
- Declarations where they are trusted (`_key_trust`)."""
2445
- statement = symbol.statement
2446
- if statement is None:
2447
- return
2448
- columns = {column.name.lower(): column for column in relation.output_columns}
2449
- non_null = {column.lower() for column in symbol.not_null}
2450
- # Each key's columns, its constraint, and whether it is a primary key.
2451
- keys: list[tuple[tuple[str, ...], Expr, bool]] = []
2452
- checks: list[exp.CheckColumnConstraint] = []
2453
- for definition in statement.this.find_all(exp.ColumnDef):
2454
- domain = _enum_type_values(definition, self.semantics)
2455
- if domain is not None and definition.name.lower() in columns:
2456
- self._knowledge.append(EnumeratedDomain(column=columns[definition.name.lower()], values=domain))
2457
- for constraint in definition.constraints:
2458
- match constraint.args.get("kind"):
2459
- case exp.NotNullColumnConstraint() as not_null if not not_null.args.get("allow_null"):
2460
- non_null.add(definition.name.lower())
2461
- case exp.PrimaryKeyColumnConstraint() as key:
2462
- keys.append(((definition.name,), key, True))
2463
- case exp.UniqueColumnConstraint() as key:
2464
- keys.append(((definition.name,), key, False))
2465
- case exp.CheckColumnConstraint() as check:
2466
- checks.append(check)
2467
- case _:
2468
- pass # Other column constraints state nothing about keys or NULL.
2469
- for constraint in _table_constraints(symbol):
2470
- if isinstance(constraint, exp.CheckColumnConstraint):
2471
- checks.append(constraint)
2472
- continue
2473
- constrained = _table_level_unique_columns(constraint)
2474
- if constrained is not None:
2475
- keys.append((constrained, constraint, isinstance(constraint, exp.PrimaryKey)))
2476
- self._knowledge.extend(NonNullColumn(column=columns[name]) for name in sorted(non_null) if name in columns)
2477
- for column_names, constraint, primary in keys:
2478
- members = tuple(columns[name.lower()] for name in column_names if name.lower() in columns)
2479
- if len(members) != len(column_names):
2480
- continue
2481
- trust = self._key_trust(constraint, symbol, column_names)
2482
- if trust is None:
2483
- continue
2484
- facts: list[Property] = [UniqueSet(columns=frozenset(members))]
2485
- if primary and (trust == "declared" or self.semantics.primary_key_not_null):
2486
- facts.extend(NonNullColumn(column=member) for member in members if member.name.lower() not in non_null)
2487
- (self._knowledge if trust == "enforced" else self._declarations).extend(facts)
2488
- for parts, index in symbol.expression_keys:
2489
- members = self._expression_key(relation, parts, index)
2490
- if members is None:
2491
- continue
2492
- names = tuple(member.name for member in members)
2493
- trust = self._key_trust(exp.UniqueColumnConstraint(), symbol, names)
2494
- if trust is not None:
2495
- (self._knowledge if trust == "enforced" else self._declarations).append(UniqueSet(columns=frozenset(members)))
2496
- for check in checks:
2497
- self._check_knowledge(check, symbol, columns)
2498
-
2499
- def _check_knowledge(self, check: exp.CheckColumnConstraint, symbol: _Symbol, columns: dict[str, ir.OutputColumn]) -> None:
2500
- """A CHECK constraint's Enumerated Domains (`_check_domains`), or a
2501
- warning that its shape states none sqlassert reads."""
2502
- domains = _check_domains(check.this, self.semantics)
2503
- if domains is None or not all(name in columns for name, _ in domains):
2504
- assert symbol.statement is not None
2505
- self._warnings.append(Diagnostic(
2506
- diag.IGNORED_CHECK_CONSTRAINT,
2507
- f"CHECK ({check.this.sql(dialect=self.dialect)}) of {symbol.name} is ignored: only col IN (...) and col = v, "
2508
- "with literal values, joined by AND, give a column's values",
2509
- self._origin(check, _source_line(check) or _source_line(symbol.statement)),
2510
- ))
2511
- return
2512
- trust = self._key_trust(check, symbol, tuple(dict.fromkeys(name for name, _ in domains)))
2513
- if trust is None:
2514
- return
2515
- facts = [EnumeratedDomain(column=columns[name], values=values) for name, values in domains]
2516
- (self._knowledge if trust == "enforced" else self._declarations).extend(facts)
2517
-
2518
- def _expression_key(
2519
- self, relation: ir.NamedRelation, parts: list[Expr], index: exp.Create
2520
- ) -> tuple[ir.OutputColumn, ...] | None:
2521
- """The columns a unique index over `parts` makes a Unique Set, or None
2522
- (diagnosed) when it makes none.
2523
-
2524
- Two rows equal and non-null on the columns the parts read would give
2525
- equal index keys, which the index forbids, when every part is a pure
2526
- function of its columns (equal inputs, equal keys: so only over columns
2527
- whose equal values are identical; under a case-insensitive collation
2528
- `'A' = 'a'` yet their bytes differ) and total in them (a NULL key part
2529
- exempts the row: `nullif(email, '')` lets every '' through). No
2530
- injectivity is needed: `lower(email)` unique makes `email` unique."""
2531
- bindings = tuple(_Binding(relation.name.lower(), column.name.lower(), column) for column in relation.output_columns)
2532
- found: dict[ir.OutputColumn, None] = {}
2533
- for part in parts:
2534
- lowered = self._lower_expression(part, bindings, schema_complete=relation.is_schema_complete)
2535
- inputs = ir.determinants(lowered)
2536
- text = part.sql(dialect=self.dialect)
2537
- if inputs is None:
2538
- problem = f"{text} is not a function of the table's columns"
2539
- elif not ir.total(lowered):
2540
- problem = f"{text} may be NULL where its columns are not, which exempts the row from the index"
2541
- elif not all(column in relation.output_columns and column.identity_comparison for column in inputs):
2542
- problem = f"{text} reads a column whose equal values may differ (a float, or text under a collation)"
2543
- else:
2544
- found.update(dict.fromkeys(inputs))
2545
- continue
2546
- self._unsupported_create(index, f"a unique index whose key states no Unique Set ({problem})")
2547
- return None
2548
- return tuple(found)
2549
-
2550
- def _key_trust(self, constraint: Expr, symbol: _Symbol, columns: tuple[str, ...]) -> Literal["enforced", "declared"] | None:
2551
- """Whether a key or foreign key constraint holds: enforced by the
2552
- database (Knowledge), trusted by its author (a Property Declaration:
2553
- marked `RELY`, or any unenforced one under `trust_unenforced_keys`),
2554
- or neither, which a warning reports. An unenforced one is never
2555
- Knowledge, so never proves anything by itself (ADR 0005)."""
2556
- assert symbol.statement is not None
2557
- foreign = isinstance(constraint, exp.ForeignKey | exp.Reference)
2558
- check = isinstance(constraint, exp.CheckColumnConstraint)
2559
- reference = constraint.args.get("reference") if isinstance(constraint, exp.ForeignKey) else constraint
2560
- options = {str(option).upper() for option in (reference.args.get("options") or ())} if isinstance(reference, Expr) else set()
2561
- meaning = self.semantics
2562
- reason = None
2563
- if "NOT ENFORCED" in options:
2564
- reason = "it is declared NOT ENFORCED"
2565
- elif id(constraint) in self._unvalidated:
2566
- reason = "ALTER TABLE ... NOT VALID added it, so rows already in the table were never checked"
2567
- elif "DEFERRABLE" in options or "INITIALLY DEFERRED" in options:
2568
- reason = "it is DEFERRABLE, so a transaction may see it violated"
2569
- elif (meaning.check_constraints if check else meaning.foreign_keys if foreign else meaning.unique_keys) != "enforced":
2570
- reason = f"{self.dialect} does not enforce it"
2571
- elif isinstance(constraint, exp.Reference) and not meaning.inline_references:
2572
- reason = f"{self.dialect} before 9.0 ignores a column-level REFERENCES"
2573
- elif foreign and meaning.foreign_key_engines is not None and (engine := _engine(symbol)) not in meaning.foreign_key_engines:
2574
- reason = (
2575
- f"ENGINE={engine} does not enforce foreign keys" if engine is not None
2576
- else "its table names no ENGINE, and the server's default_storage_engine may not enforce foreign keys"
2577
- )
2578
- if reason is None:
2579
- return "enforced"
2580
- if ("RELY" in options and meaning.rely) or self.trust_unenforced_keys:
2581
- return "declared"
2582
- kind = "check constraint" if check else "foreign key" if foreign else "primary key" if isinstance(constraint, exp.PrimaryKey | exp.PrimaryKeyColumnConstraint) else "unique constraint"
2583
- fixes = ["mark it RELY"] if meaning.rely and not check else []
2584
- if foreign and meaning.foreign_key_engines is not None and _engine(symbol) is None:
2585
- fixes.append("write ENGINE=InnoDB")
2586
- fixes.append("analyze with trust_unenforced_keys=True")
2587
- self._warnings.append(Diagnostic(
2588
- diag.UNENFORCED_CONSTRAINT,
2589
- f"the {kind} ({quoted_all(columns)}) of {symbol.name} is not Knowledge, since {reason}: "
2590
- f"if the data satisfies it, {' or '.join(fixes)}",
2591
- self._origin(constraint, _source_line(constraint) or _source_line(symbol.statement)),
2592
- ))
2593
- return None
2594
-
2595
- def _origin(self, node: Expr, line: int | None = None) -> Origin:
2596
- return Origin(SQL, written_sql(node, self.dialect), line)
2597
-
2598
-
2599
- def _pass_output_columns(inputs: tuple[ir.OutputColumn, ...], origin: Origin) -> tuple[ir.OutputColumn, ...]:
2600
- return tuple(
2601
- ir.OutputColumn(origin=origin, name=column.name, scalar_expr=ir.ColumnRef(origin=origin, column=column))
2602
- for column in inputs
2603
- )
2604
-
2605
-
2606
- def _source_line(node: Expr) -> int | None:
2607
- """The first source line of `node`, from the positions SQLGlot keeps on its tokens."""
2608
- lines = [descendant.meta["line"] for descendant in node.walk() if "line" in descendant.meta]
2609
- return min(lines, default=None)
2610
-
2611
-
2612
- def _subquery_conjunct(conjunct: Expr) -> tuple[ir.JoinKind, exp.Select, Expr | None] | None:
2613
- """A WHERE conjunct lowered as a filtering join: its kind, the subquery,
2614
- and the IN operand (None for EXISTS)."""
2615
- match conjunct:
2616
- case exp.Exists(this=exp.Select() as select):
2617
- return "semi", select, None
2618
- case exp.Not(this=exp.Exists(this=exp.Select() as select)):
2619
- return "anti", select, None
2620
- case exp.In(this=operand, args={"query": exp.Subquery() as subquery}) if not isinstance(operand, exp.Tuple):
2621
- body = _unwrap_query(subquery)
2622
- return ("semi", body, operand) if isinstance(body, exp.Select) else None
2623
- case _:
2624
- return None
2625
-
2626
-
2627
- @cache
2628
- def dialect_builtins(meaning: DialectSemantics) -> dict[type[Expr], tuple[ir.Builtin, tuple[str, ...]]]:
2629
- """Each modelled Builtin, by the SQLGlot node it lowers from (exactly that
2630
- type: TRY_CAST, a subclass of CAST, may be NULL for a value), with the
2631
- argument keys its parameters come from, a list key in place of a variadic
2632
- Builtin's repeated parameter, as a dialect's semantics define it
2633
- (`dialects.py`; `scripts/certify_dialects.py` probes each Builtin fact).
2634
-
2635
- Comparisons, LIKE, NOT, BETWEEN and the bitwise operators are never NULL
2636
- for non-null arguments where a failed implicit cast raises (`casts_raise`;
2637
- in Hive `1 < 'x'` is NULL). Arithmetic and CAST only
2638
- where they raise an error rather than return NULL (`checked_arithmetic`:
2639
- SQLite turns a NaN into NULL, MySQL a bad date CAST), and division and
2640
- remainder only where division by zero raises too (`checked_division`).
2641
- A CAST from JSON is not total anywhere (`convert._is_json`): JSON `null`
2642
- is a value that casts to NULL. `+`, `-` and negation are injective where exact arithmetic overflows into
2643
- an error. `||`, `concat()`, `concat_ws()`, `greatest()`, `least()` and
2644
- subscripts (`xs[1]`) as each dialect treats NULL (MySQL's `||` is OR)."""
2645
- checked = meaning.checked_arithmetic
2646
- casts = meaning.casts_raise
2647
-
2648
- def builtin(name: str, arity: int, *, total: bool = True, injective: bool = False) -> ir.Builtin:
2649
- return ir.Builtin(name=name, strict=(True,) * arity, total=(True,) * arity if total else None, injective=injective)
2650
-
2651
- binary = {
2652
- exp.NEQ: "<>", exp.GT: ">", exp.GTE: ">=", exp.LT: "<", exp.LTE: "<=", exp.Like: "LIKE", exp.ILike: "ILIKE",
2653
- exp.BitwiseAnd: "&", exp.BitwiseOr: "|", exp.BitwiseXor: "^", exp.BitwiseLeftShift: "<<", exp.BitwiseRightShift: ">>",
2654
- }
2655
- division = {exp.Div: "/", exp.IntDiv: "//", exp.Mod: "%"}
2656
- builtins: dict[type[Expr], tuple[ir.Builtin, tuple[str, ...]]] = {
2657
- **{node: (builtin(name, 2, total=casts), ("this", "expression")) for node, name in binary.items()},
2658
- exp.Mul: (builtin("*", 2, total=checked), ("this", "expression")),
2659
- **{node: (builtin(name, 2, total=meaning.checked_division), ("this", "expression")) for node, name in division.items()},
2660
- **{node: (builtin(name, 2, total=checked, injective=checked), ("this", "expression")) for node, name in {exp.Add: "+", exp.Sub: "-"}.items()},
2661
- exp.Neg: (builtin("unary -", 1, total=checked, injective=checked), ("this",)),
2662
- exp.Not: (builtin("NOT", 1, total=casts), ("this",)),
2663
- exp.BitwiseNot: (builtin("~", 1, total=casts), ("this",)),
2664
- exp.Cast: (builtin("CAST", 1, total=checked), ("this",)),
2665
- # `1 BETWEEN NULL AND 0` is FALSE.
2666
- exp.Between: (ir.Builtin(name="BETWEEN", strict=(True, False, False), total=(True, True, True) if casts else None, injective=False), ("this", "low", "high")),
2667
- # Text functions take any value as text, so no cast fails. `trim(' ')`
2668
- # is '', which is NULL where '' is.
2669
- exp.Lower: (builtin("lower", 1), ("this",)),
2670
- exp.Upper: (builtin("upper", 1), ("this",)),
2671
- exp.Length: (builtin("length", 1), ("this",)),
2672
- exp.Trim: (builtin("trim", 1, total=not meaning.empty_string_is_null), ("this",)),
2673
- # A number read from bad text is an error only where a bad CAST is
2674
- # (SQLite's `floor('x')` is NULL though its comparisons raise).
2675
- exp.Abs: (builtin("abs", 1, total=checked), ("this",)),
2676
- exp.Floor: (builtin("floor", 1, total=checked), ("this",)),
2677
- exp.Ceil: (builtin("ceil", 1, total=checked), ("this",)),
2678
- # NULL when its arguments are equal; NULL only through the first otherwise.
2679
- exp.Nullif: (ir.Builtin(name="nullif", strict=(True, False), total=None, injective=False), ("this", "expression")),
2680
- }
2681
- match meaning.pipes:
2682
- case "strict":
2683
- builtins[exp.DPipe] = (builtin("||", 2), ("this", "expression"))
2684
- case "lenient":
2685
- builtins[exp.DPipe] = (ir.Builtin(name="||", strict=(False, False), total=(True, True), injective=False), ("this", "expression"))
2686
- case None:
2687
- pass
2688
- case _:
2689
- assert_never(meaning.pipes)
2690
- match meaning.concat:
2691
- case "strict":
2692
- builtins[exp.Concat] = (
2693
- ir.BuiltinVariadic(name="concat", strict=(), total=(), injective=False, repeated_strict=True, repeated_total=True), ("expressions",),
2694
- )
2695
- case "skips-null":
2696
- # `concat(NULL)` is ''.
2697
- builtins[exp.Concat] = (
2698
- ir.BuiltinVariadic(name="concat", strict=(), total=(), injective=False, repeated_strict=False, repeated_total=False), ("expressions",),
2699
- )
2700
- case None:
2701
- pass
2702
- case _:
2703
- assert_never(meaning.concat)
2704
- match meaning.greatest:
2705
- case "skips-null":
2706
- # NULL only when every argument is: `greatest(NULL, 1)` is 1.
2707
- for node, name in {exp.Greatest: "greatest", exp.Least: "least"}.items():
2708
- builtins[node] = (
2709
- ir.BuiltinVariadic(
2710
- name=name, strict=(False,), total=None, injective=False, repeated_strict=False, repeated_total=False, skips_null=True,
2711
- ),
2712
- ("this", "expressions"),
2713
- )
2714
- case "strict":
2715
- # NULL when any argument is: `greatest(NULL, 1)` is NULL.
2716
- for node, name in {exp.Greatest: "greatest", exp.Least: "least"}.items():
2717
- builtins[node] = (
2718
- ir.BuiltinVariadic(name=name, strict=(True,), total=None, injective=False, repeated_strict=True, repeated_total=False),
2719
- ("this", "expressions"),
2720
- )
2721
- case None:
2722
- pass
2723
- case _:
2724
- assert_never(meaning.greatest)
2725
- if meaning.subscript_strict:
2726
- # NULL for a NULL list, and for an index out of range or a NULL element.
2727
- builtins[exp.Bracket] = (ir.Builtin(name="[]", strict=(True, False), total=None, injective=False), ("this", "expressions"))
2728
- match meaning.concat_ws:
2729
- case "strict":
2730
- builtins[exp.ConcatWs] = (
2731
- ir.BuiltinVariadic(name="concat_ws", strict=(True,), total=(True,), injective=False, repeated_strict=True, repeated_total=True),
2732
- ("expressions",),
2733
- )
2734
- case "skips-null":
2735
- # NULL values are skipped: `concat_ws(',', NULL)` is ''.
2736
- builtins[exp.ConcatWs] = (
2737
- ir.BuiltinVariadic(name="concat_ws", strict=(True,), total=(True,), injective=False, repeated_strict=False, repeated_total=False),
2738
- ("expressions",),
2739
- )
2740
- case None:
2741
- pass
2742
- case _:
2743
- assert_never(meaning.concat_ws)
2744
- return builtins
2745
-
2746
-
2747
- def _as_list(value: Expr | list[Expr]) -> list[Expr]:
2748
- return value if isinstance(value, list) else [value]
2749
-
2750
-
2751
- def _disjuncts(predicate: Expr) -> list[Expr]:
2752
- """The operands of a predicate's top-level ORs, parentheses removed."""
2753
- while isinstance(predicate, exp.Paren):
2754
- predicate = predicate.this
2755
- if isinstance(predicate, exp.Or):
2756
- return _disjuncts(predicate.this) + _disjuncts(predicate.expression)
2757
- return [predicate]
2758
-
2759
-
2760
- def _and(parts: tuple[ir.ScalarExpr, ...], origin: Origin) -> ir.ScalarExpr | None:
2761
- """The AND of `parts`: None for none, the part itself for one."""
2762
- match parts:
2763
- case ():
2764
- return None
2765
- case (part,):
2766
- return part
2767
- case _:
2768
- return ir.And(origin=origin, parts=parts)
2769
-
2770
-
2771
- def _conjuncts(predicate: Expr) -> list[Expr]:
2772
- """The operands of a predicate's top-level ANDs, parentheses removed."""
2773
- while isinstance(predicate, exp.Paren):
2774
- predicate = predicate.this
2775
- if isinstance(predicate, exp.And):
2776
- return _conjuncts(predicate.this) + _conjuncts(predicate.expression)
2777
- return [predicate]
2778
-
2779
-
2780
- def _filter_conjuncts(predicate: Expr) -> list[Expr]:
2781
- """The conjuncts of a WHERE, ON or HAVING condition, each `p IS TRUE` as
2782
- `p`'s own: a filter keeps only the rows where its condition is TRUE, where
2783
- `p IS TRUE` is TRUE exactly when `p` is. Not in a value, where `p IS TRUE`
2784
- is FALSE, not NULL, on a NULL `p`."""
2785
- found: list[Expr] = []
2786
- for conjunct in _conjuncts(predicate):
2787
- if isinstance(conjunct, exp.Is) and isinstance(conjunct.expression, exp.Boolean) and conjunct.expression.this:
2788
- found.extend(_filter_conjuncts(conjunct.this))
2789
- else:
2790
- found.append(conjunct)
2791
- return found
2792
-
2793
-
2794
- def _direct_sources(select: exp.Select) -> list[Expr]:
2795
- """The sources of `select`'s FROM, those of a parenthesized join in place of it."""
2796
- source = _from_source(select)
2797
- return _flattened(([] if source is None else [source]) + [join.this for join in select.args.get("joins") or ()])
2798
-
2799
-
2800
- def _flattened(sources: list[Expr]) -> list[Expr]:
2801
- flat: list[Expr] = []
2802
- for source in sources:
2803
- nested = _nested_join(source)
2804
- flat.extend([source] if nested is None else _flattened([nested[0], *(join.this for join in nested[1])]))
2805
- return flat
2806
-
2807
-
2808
- def _all_joins(select: exp.Select) -> list[exp.Join]:
2809
- """The joins of `select`'s FROM, those inside a parenthesized join included."""
2810
- return [join for joins, _ in _join_levels(select) for join in joins]
2811
-
2812
-
2813
- def _join_levels(select: exp.Select) -> list[tuple[list[exp.Join], list[Expr]]]:
2814
- """The joins of `select`'s FROM and of each parenthesized join in it, each
2815
- list with the sources it joins, flattened: a USING column is one of theirs."""
2816
- source = _from_source(select)
2817
- levels: list[tuple[list[exp.Join], list[Expr]]] = [(list(select.args.get("joins") or ()), _direct_sources(select))]
2818
- pending: list[Expr | None] = [source, *(join.this for join in select.args.get("joins") or ())]
2819
- while pending:
2820
- source = pending.pop()
2821
- nested = _nested_join(source) or _aliased_join(source)
2822
- if nested is not None:
2823
- first, joins = nested
2824
- levels.append((joins, _flattened([first, *(join.this for join in joins)])))
2825
- pending.extend([first, *(join.this for join in joins)])
2826
- return levels
2827
-
2828
-
2829
- def _nested_join(source: Expr | None) -> tuple[Expr, list[exp.Join]] | None:
2830
- """A parenthesized join, `(a JOIN b ON ...)` without an alias: its first
2831
- source, which SQLGlot hangs the joins on, and those joins. Its columns keep
2832
- the names and qualifiers of its sources. Not with an alias, which DuckDB
2833
- reads as a subquery renaming repeated names (`x`, `x_1`) and other dialects
2834
- as names that may be ambiguous."""
2835
- if not isinstance(source, exp.Subquery) or any(value for key, value in source.args.items() if key not in {"this", "joins"}):
2836
- return None
2837
- first = source.this
2838
- if not isinstance(first, exp.Table | exp.Subquery) or not first.args.get("joins"):
2839
- return None
2840
- return first, list(first.args["joins"])
2841
-
2842
-
2843
- def _aliased_join(source: Expr | None) -> tuple[Expr, list[exp.Join]] | None:
2844
- """A parenthesized join with an alias, `(a JOIN b ON ...) AS x`, perhaps
2845
- naming its columns: its first source and its joins, as `_nested_join`."""
2846
- if not isinstance(source, exp.Subquery) or not source.alias or any(
2847
- value for key, value in source.args.items() if key not in {"this", "alias"}
2848
- ):
2849
- return None
2850
- first = source.this
2851
- if not isinstance(first, exp.Table | exp.Subquery) or not first.args.get("joins"):
2852
- return None
2853
- return first, list(first.args["joins"])
2854
-
2855
-
2856
- def _hidden_sources(source: Expr) -> list[Expr]:
2857
- """The sources inside an aliased parenthesized join, at any depth: their
2858
- names are visible only inside it."""
2859
- nested = _aliased_join(source)
2860
- if nested is None:
2861
- return []
2862
- inner = _flattened([nested[0], *(join.this for join in nested[1])])
2863
- return [*inner, *(hidden for source in inner for hidden in _hidden_sources(source))]
2864
-
2865
-
2866
- def _asserted_joins(ast: ParsedProgram) -> list[exp.Join]:
2867
- statements = (*ast.create_statements, ast.root_select)
2868
- return [
2869
- join for statement in statements if statement is not None
2870
- for join in statement.find_all(exp.Join) if assertion_span(join) is not None
2871
- ]
2872
-
2873
-
2874
- def _asserted_selects(ast: ParsedProgram) -> list[exp.Query]:
2875
- statements = (*ast.create_statements, ast.root_select)
2876
- return [
2877
- select for statement in statements if statement is not None
2878
- for select in statement.find_all(exp.Select, exp.SetOperation) if column_markers(select)
2879
- ]
2880
-
2881
-
2882
-
2883
- def _asserted_cases(ast: ParsedProgram) -> list[exp.Case]:
2884
- statements = (*ast.create_statements, ast.root_select)
2885
- return [
2886
- case for statement in statements if statement is not None
2887
- for case in statement.find_all(exp.Case) if exhaustive_span(case) is not None
2888
- ]
2889
-
2890
-
2891
- def _table_level_unique_columns(constraint: Expr) -> tuple[str, ...] | None:
2892
- if isinstance(constraint, exp.PrimaryKey):
2893
- return tuple(identifier.name for identifier in constraint.expressions)
2894
- if isinstance(constraint, exp.UniqueColumnConstraint) and isinstance(constraint.this, exp.Schema):
2895
- return tuple(identifier.name for identifier in constraint.this.expressions)
2896
- return None
2897
-
2898
-
2899
- def _table_constraints(symbol: _Symbol) -> list[Expr]:
2900
- """A declared table's table-level constraints, named or not: its CREATE
2901
- TABLE's, then those added later."""
2902
- assert symbol.statement is not None
2903
- schema = symbol.statement.this
2904
- own = _unwrap_constraints(schema.expressions) if isinstance(schema, exp.Schema) else []
2905
- return own + symbol.constraints
2906
-
2907
-
2908
- def _unwrap_constraints(constraints: Iterable[Expr]) -> list[Expr]:
2909
- """`CONSTRAINT name ...` is the constraints it names."""
2910
- return [
2911
- inner for constraint in constraints
2912
- for inner in (constraint.expressions if isinstance(constraint, exp.Constraint) else (constraint,))
2913
- ]
2914
-
2915
-
2916
- def _is_added_constraint(constraint: Expr) -> bool:
2917
- return (
2918
- isinstance(constraint, exp.PrimaryKey | exp.ForeignKey | exp.CheckColumnConstraint)
2919
- or _table_level_unique_columns(constraint) is not None
2920
- )
2921
-
2922
-
2923
- def _references(symbol: _Symbol) -> list[tuple[tuple[str, ...], exp.Table, tuple[str, ...] | None, Expr]]:
2924
- """Every `REFERENCES` constraint of a table, column-level and table-level,
2925
- as `(columns, referenced table, referenced columns, node)`. Referenced
2926
- columns are None when omitted, meaning the referenced primary key."""
2927
- found = []
2928
- assert symbol.statement is not None
2929
- for definition in symbol.statement.this.find_all(exp.ColumnDef):
2930
- for constraint in definition.constraints:
2931
- reference = constraint.args.get("kind")
2932
- if isinstance(reference, exp.Reference):
2933
- found.append(((definition.name,), *_reference_target(reference), reference))
2934
- for foreign_key in _table_constraints(symbol):
2935
- if not isinstance(foreign_key, exp.ForeignKey):
2936
- continue
2937
- reference = foreign_key.args.get("reference")
2938
- if isinstance(reference, exp.Reference):
2939
- columns = tuple(identifier.name for identifier in foreign_key.expressions)
2940
- found.append((columns, *_reference_target(reference), foreign_key))
2941
- return found
2942
-
2943
-
2944
- def _reference_target(reference: exp.Reference) -> tuple[exp.Table, tuple[str, ...] | None]:
2945
- target = reference.this
2946
- if isinstance(target, exp.Schema):
2947
- return target.this, tuple(identifier.name for identifier in target.expressions)
2948
- return target, None
2949
-
2950
-
2951
- def _primary_key(symbol: _Symbol) -> tuple[str, ...] | None:
2952
- assert symbol.statement is not None
2953
- for definition in symbol.statement.this.find_all(exp.ColumnDef):
2954
- if any(isinstance(constraint.args.get("kind"), exp.PrimaryKeyColumnConstraint) for constraint in definition.constraints):
2955
- return (definition.name,)
2956
- for constraint in _table_constraints(symbol):
2957
- if isinstance(constraint, exp.PrimaryKey):
2958
- return tuple(identifier.name for identifier in constraint.expressions)
2959
- return None
2960
-
2961
-
2962
- def _missing(relation: ir.RelationExpr, names: Iterable[str]) -> list[str]:
2963
- known = {column.name.lower() for column in relation.output_columns}
2964
- return [name for name in names if name.lower() not in known]
2965
-
2966
-
2967
- _SUPPORTED_CREATE_KINDS = {"TABLE", "VIEW"}
2968
-
2969
- _TEXT_TYPES = {exp.DataType.Type.VARCHAR, exp.DataType.Type.TEXT}
2970
-
2971
-
2972
- def _collated(definition: exp.ColumnDef) -> bool:
2973
- """Whether a column is declared with a `COLLATE`."""
2974
- return any(isinstance(constraint.args.get("kind"), exp.CollateColumnConstraint) for constraint in definition.constraints)
2975
-
2976
-
2977
- def _created_table(statement: exp.Create) -> exp.Table | None:
2978
- target = statement.this
2979
- if isinstance(target, exp.Schema):
2980
- target = target.this
2981
- return target if isinstance(target, exp.Table) else None
2982
-
2983
-
2984
- def _is_named_table(source: Expr) -> TypeGuard[exp.Table]:
2985
- """A FROM source naming a table, view or CTE. SQLGlot parses a
2986
- table-valued function (`json_each(x)`, `read_parquet('f')`,
2987
- `generate_series(1, 3)`) as a Table whose `this` is the call: its rows
2988
- are opaque, like an UNNEST, and it names no relation."""
2989
- return isinstance(source, exp.Table) and isinstance(source.this, exp.Identifier)
2990
-
2991
-
2992
- def _column_aliases(source: Expr) -> tuple[str, ...]:
2993
- alias = source.args.get("alias")
2994
- return tuple(column.name for column in alias.columns) if isinstance(alias, exp.TableAlias) else ()
2995
-
2996
-
2997
- def _qualified_name(table: exp.Table) -> str:
2998
- return ".".join(part for part in (table.catalog, table.db, table.name) if part)
2999
-
3000
-
3001
- def _unwrap_query(body: Expr | None) -> exp.Query | None:
3002
- while isinstance(body, exp.Subquery):
3003
- body = body.this
3004
- return body if isinstance(body, exp.Query) else None
3005
-
3006
-
3007
- def _arg(node: Expr, name: str) -> Expr | None:
3008
- return node.args.get(f"{name}_") or node.args.get(name)
3009
-
3010
-
3011
- def _from_source(select: exp.Query) -> Expr | None:
3012
- source = _arg(select, "from")
3013
- return source.this if isinstance(source, exp.From) else None
3014
-
3015
-
3016
- def _unsupported_grouping(select: exp.Select) -> str | None:
3017
- """The grouping construct that makes `select` opaque, if any."""
3018
- group = select.args.get("group")
3019
- if group is None:
3020
- return None
3021
- for key, name in (("grouping_sets", "GROUPING SETS"), ("rollup", "ROLLUP"), ("cube", "CUBE"), ("totals", "WITH TOTALS")):
3022
- if group.args.get(key):
3023
- return name
3024
- for node, name in ((exp.GroupingSets, "GROUPING SETS"), (exp.Rollup, "ROLLUP"), (exp.Cube, "CUBE")):
3025
- if any(isinstance(expression, node) for expression in group.expressions):
3026
- return name
3027
- return None
3028
-
3029
-
3030
- def _unsupported_source(source: Expr) -> str | None:
3031
- """The FROM source construct that lowers opaque, if sqlassert does not support it yet."""
3032
- if isinstance(source, exp.Lateral) or source.find(exp.Lateral) is not None:
3033
- return "LATERAL"
3034
- if isinstance(source, exp.Unnest) or source.find(exp.Unnest) is not None:
3035
- return "UNNEST"
3036
- if isinstance(source, exp.Table) and isinstance(source.this, exp.Func):
3037
- return "a table function"
3038
- return None
3039
-
3040
-
3041
- def _traced_comparison_type(column: ir.OutputColumn) -> str | None:
3042
- """The declared comparison type of the column `column` passes on."""
3043
- while column.comparison_type is None and isinstance(column.scalar_expr, ir.ColumnRef):
3044
- column = column.scalar_expr.column
3045
- return column.comparison_type
3046
-
3047
-
3048
- # Rows of a VALUES list past which its columns get no Enumerated Domain.
3049
- _VALUES_DOMAIN_ROWS = 100
3050
-
3051
- # A grouping key not selected, kept as a hidden Aggregate output: no SQL name can match it.
3052
- HIDDEN_GROUPING = "\0grouping"
3053
-
3054
- # An aggregate HAVING reads that no item writes, a hidden Aggregate output too.
3055
- HIDDEN_AGGREGATE = "\0aggregate"
3056
-
3057
- # A USING column's merged binding (`_merge_using`): no qualifier can name it.
3058
- _USING_QUALIFIER = "\0using"
3059
-
3060
- # A scalar subquery's value binding: no SQL name can match it.
3061
- _SCALAR_QUALIFIER = "\0scalar"
3062
- # Aggregates whose value over no rows is NULL, so a decorrelated subquery's
3063
- # padding is that value. Not count_if, approx_count_distinct and the like: 0.
3064
- _EMPTY_NULL_AGGREGATES = (
3065
- exp.Sum | exp.Avg | exp.Min | exp.Max | exp.AnyValue | exp.LogicalAnd | exp.LogicalOr
3066
- | exp.ArgMax | exp.ArgMin | exp.First | exp.Last | exp.Stddev | exp.Variance
3067
- )
3068
-
3069
-
3070
- # A set-returning call's value binding: no SQL name can match it.
3071
- _SET_RETURNING_QUALIFIER = "\0rows"
3072
-
3073
- # Calls that return rows, not a value, in a select list: `unnest(arr)`,
3074
- # Spark's `explode(arr)`, Postgres's `generate_series(1, 3)`. Not DuckDB's
3075
- # `generate_series`, which there returns a list.
3076
- _SET_RETURNING = (exp.Explode, exp.Inline, exp.Stack, exp.ExplodingGenerateSeries, exp.Unnest)
3077
-
3078
- # Set-returning functions SQLGlot parses as anonymous calls, by dialect.
3079
- _SET_RETURNING_NAMES: dict[str, frozenset[str]] = {
3080
- "postgres": frozenset({
3081
- "generate_subscripts", "json_array_elements", "json_array_elements_text", "json_each", "json_each_text",
3082
- "json_object_keys", "json_populate_recordset", "json_to_recordset", "jsonb_array_elements", "jsonb_array_elements_text",
3083
- "jsonb_each", "jsonb_each_text", "jsonb_object_keys", "jsonb_path_query", "jsonb_populate_recordset", "jsonb_to_recordset",
3084
- "regexp_matches", "regexp_split_to_table", "string_to_table",
3085
- }),
3086
- "spark": frozenset({"json_tuple", "inline_outer"}),
3087
- "databricks": frozenset({"json_tuple", "inline_outer"}),
3088
- "hive": frozenset({"json_tuple", "inline_outer"}),
3089
- }
3090
-
3091
-
3092
- def _set_returning_calls(item: Expr, dialect: str) -> list[Expr]:
3093
- """The outermost set-returning calls a select list item evaluates itself:
3094
- not one inside a subquery, which returns rows of its own."""
3095
- names = _SET_RETURNING_NAMES.get(dialect, frozenset())
3096
- calls: list[Expr] = []
3097
-
3098
- def returns_rows(node: Expr) -> bool:
3099
- return isinstance(node, _SET_RETURNING) or (isinstance(node, exp.Anonymous) and node.name.lower() in names)
3100
-
3101
- for node in item.walk(prune=lambda node: isinstance(node, exp.Query | exp.Subquery) or returns_rows(node)):
3102
- if returns_rows(node):
3103
- calls.append(node)
3104
- return calls
3105
-
3106
-
3107
- def _scalar_subqueries(expression: Expr) -> list[exp.Subquery]:
3108
- """The scalar subqueries `expression` evaluates itself: not one under
3109
- EXISTS, IN, ANY or ALL, nor inside another subquery."""
3110
- found = []
3111
- for node in expression.walk(prune=lambda node: isinstance(node, (exp.Subquery, exp.Query, exp.Exists))):
3112
- if isinstance(node, exp.Subquery) and not isinstance(node.parent, (exp.In, exp.Exists, exp.Any, exp.All)):
3113
- found.append(node)
3114
- return found
3115
-
3116
-
3117
- def _in_scope(column: ir.OutputColumn, scope: ir.RelationExpr) -> ir.OutputColumn | None:
3118
- """`column` as a column of `scope`: itself, or the input column it passes on."""
3119
- if column in scope.output_columns:
3120
- return column
3121
- match column.scalar_expr:
3122
- case ir.ColumnRef(column=upstream) if upstream in scope.output_columns:
3123
- return upstream
3124
- case _:
3125
- return None
3126
-
3127
-
3128
- def _carrying(column: ir.OutputColumn, scope: ir.RelationExpr) -> ir.OutputColumn | None:
3129
- """The one column of `scope` that passes `column` on, through any stages."""
3130
- found = []
3131
- for candidate in scope.output_columns:
3132
- current = candidate
3133
- while current is not column and isinstance(current.scalar_expr, ir.ColumnRef):
3134
- current = current.scalar_expr.column
3135
- if current is column:
3136
- found.append(candidate)
3137
- return found[0] if len(found) == 1 else None
3138
-
3139
-
3140
- def _schema_path(node: exp.Table | exp.Column) -> str:
3141
- """The catalog and schema a table or column is written with, as `s1` or `c.s1`."""
3142
- return ".".join(part for part in (node.catalog, node.db) if part).lower()
3143
-
3144
-
3145
- def _star_only(select: exp.Select) -> bool:
3146
- return len(select.expressions) == 1 and isinstance(select.expressions[0], exp.Star) and not any(select.expressions[0].args.values())
3147
-
3148
-
3149
- def _selected_output_names(select: exp.Select) -> tuple[str, ...]:
3150
- return tuple(item.alias_or_name for item in select.expressions if not isinstance(item, exp.Star))
3151
-
3152
-
3153
- def _matching_output(group_expression: Expr, items: list[Expr]) -> Expr | None:
3154
- return next(
3155
- (item for item in items if (item.this if isinstance(item, exp.Alias) else item) == group_expression),
3156
- None,
3157
- )
3158
-
3159
-
3160
- def _partition_positions(partitions: Sequence[Expr], items: list[Expr]) -> list[int] | None:
3161
- """The position of the select item each partition key is written as, or
3162
- None when one is not an item, or is a bare name another item is aliased
3163
- to (it may read that alias instead)."""
3164
- positions = []
3165
- for partition in partitions:
3166
- item = _matching_output(partition, items)
3167
- if item is None:
3168
- return None
3169
- if isinstance(partition, exp.Column) and not partition.table and any(
3170
- other is not item and other.alias_or_name.lower() == partition.name.lower() for other in items
3171
- ):
3172
- return None
3173
- positions.append(next(index for index, other in enumerate(items) if other is item))
3174
- return positions
3175
-
3176
-
3177
- def _same_column_alias(group_expression: Expr, items: list[Expr]) -> Expr | None:
3178
- """The item `GROUP BY x` names when `x` is both the item's alias and the
3179
- column it selects (`t.x AS x`): either reading of the name is that column."""
3180
- if not isinstance(group_expression, exp.Column) or group_expression.table:
3181
- return None
3182
- name = group_expression.name.lower()
3183
- return next((
3184
- item for item in items
3185
- if isinstance(item, exp.Alias) and item.alias.lower() == name and isinstance(item.this, exp.Column) and item.this.name.lower() == name
3186
- ), None)
3187
-
3188
-
3189
- def _matching_grouping_output(group_expression: Expr, items: list[Expr]) -> Expr | None:
3190
- if isinstance(group_expression, exp.Literal) and group_expression.is_int:
3191
- position = int(group_expression.this)
3192
- return items[position - 1] if 1 <= position <= len(items) else None
3193
- return _matching_output(group_expression, items)
3194
-
3195
-
3196
- def _aggregate_argument(expression: Expr, kinds: tuple[type[exp.AggFunc], ...], *, distinct: bool = False) -> Expr | None:
3197
- """The one argument of a plain call of one of `kinds`: no FILTER, window,
3198
- or other argument (DuckDB's `max(x, 3)` is a list), and no DISTINCT
3199
- unless `distinct` allows one argument's."""
3200
- if type(expression) not in kinds or isinstance(expression.this, exp.Star) or expression.this is None:
3201
- return None
3202
- if any(value for key, value in expression.args.items() if key != "this"):
3203
- return None
3204
- if isinstance(expression.this, exp.Distinct):
3205
- arguments = expression.this.expressions
3206
- return arguments[0] if distinct and len(arguments) == 1 and not expression.this.args.get("on") else None
3207
- return expression.this
3208
-
3209
-
3210
- def _picked_argument(expression: Expr) -> Expr | None:
3211
- """The argument of an aggregate whose value is the argument's value on
3212
- some row of the group: `min` and `max` (a non-null one when there is one;
3213
- of distinct values or not, the same) and `any_value`, whatever its NULL
3214
- treatment (DuckDB parses its own as IGNORE NULLS). Not BigQuery's
3215
- `any_value(x HAVING MAX y)`, opaque."""
3216
- if isinstance(expression, (exp.IgnoreNulls, exp.RespectNulls)):
3217
- expression = expression.this
3218
- argument = _aggregate_argument(expression, (exp.Min, exp.Max), distinct=True) or _aggregate_argument(expression, (exp.AnyValue,))
3219
- return None if isinstance(argument, exp.HavingMax) else argument
3220
-
3221
-
3222
- def _outermost_aggregate_calls(expression: Expr) -> list[Expr]:
3223
- """The aggregate calls of `expression` not inside another, a window or a
3224
- subquery, with the FILTER or NULL treatment written on them."""
3225
- calls: list[Expr] = []
3226
- pending: list[Expr] = [expression]
3227
- while pending:
3228
- node = pending.pop()
3229
- if _is_aggregate_call(node):
3230
- calls.append(node)
3231
- elif not isinstance(node, exp.Window | exp.Query | exp.Subquery):
3232
- pending.extend(node.iter_expressions())
3233
- return calls
3234
-
3235
-
3236
- def _aggregate_parts(expression: Expr) -> list[Expr]:
3237
- """The aggregate calls of a grouped select item not inside another, and
3238
- its columns outside them: what it is computed from, per group."""
3239
- parts: list[Expr] = []
3240
- pending: list[Expr] = [expression]
3241
- while pending:
3242
- node = pending.pop()
3243
- if _is_aggregate_call(node) or isinstance(node, exp.Column):
3244
- parts.append(node)
3245
- else:
3246
- pending.extend(node.iter_expressions())
3247
- return parts
3248
-
3249
-
3250
- def _unaliased(item: Expr) -> Expr:
3251
- return item.this if isinstance(item, exp.Alias) else item
3252
-
3253
-
3254
- def _is_aggregate_call(node: Expr) -> bool:
3255
- """An aggregate call, with the FILTER or NULL treatment written on it."""
3256
- while isinstance(node, exp.Filter | exp.IgnoreNulls | exp.RespectNulls | exp.WithinGroup):
3257
- node = node.this
3258
- return isinstance(node, exp.AggFunc)
3259
-
3260
-
3261
- def _reads_ungrouped_column(lowered: ir.ScalarExpr, determined: Callable[[ir.OutputColumn], bool]) -> bool:
3262
- """Whether `lowered`, an item of a grouped select, reads a column outside
3263
- every aggregate that the grouping columns do not determine (`determined`).
3264
- Windows and subqueries lower opaque, and an aggregate's argument is read
3265
- per row, so every other column `lowered` reads is outside them."""
3266
- pending: list[ir.ScalarExpr] = [lowered]
3267
- while pending:
3268
- node = pending.pop()
3269
- if isinstance(node, ir.ColumnRef):
3270
- if not determined(node.column):
3271
- return True
3272
- continue
3273
- if isinstance(node, ir.AnyAggregate | ir.Accumulation | ir.Count):
3274
- continue
3275
- pending.extend(child for child in ir.children(node) if isinstance(child, ir.ScalarExpr))
3276
- return False
3277
-
3278
-
3279
- def _row_number_equals_one(predicate: Expr) -> exp.Window | None:
3280
- if not isinstance(predicate, exp.EQ):
3281
- return None
3282
- left, right = predicate.this, predicate.expression
3283
- window = left if isinstance(left, exp.Window) else right if isinstance(right, exp.Window) else None
3284
- literal = right if window is left else left
3285
- if window is None or not isinstance(window.this, exp.RowNumber):
3286
- return None
3287
- if not isinstance(literal, exp.Literal) or literal.is_string or literal.this != "1":
3288
- return None
3289
- return window
3290
-
3291
-
3292
- def _last_select(query: Expr) -> exp.Select | None:
3293
- """The Select a set operation's left input ends with."""
3294
- while True:
3295
- unwrapped = _unwrap_query(query) if isinstance(query, exp.Query) else None
3296
- match unwrapped:
3297
- case exp.SetOperation():
3298
- query = unwrapped.expression
3299
- case exp.Select():
3300
- return unwrapped
3301
- case _:
3302
- return None
3303
-
3304
-
3305
- _SET_OPERATORS: dict[type[Expr], ir.SetOperator] = {exp.Union: "union", exp.Intersect: "intersect", exp.Except: "except"}
3306
-
3307
-
3308
- # Types whose equal values are identical: no collation (text has a comparison
3309
- # type only when compared by identity), no signed zero or NaN, no two
3310
- # spellings of one interval.
3311
- _IDENTITY_TYPES = {
3312
- *exp.DataType.INTEGER_TYPES, *exp.DataType.TEXT_TYPES,
3313
- exp.DataType.Type.DECIMAL, exp.DataType.Type.BOOLEAN, exp.DataType.Type.DATE, exp.DataType.Type.TIME,
3314
- exp.DataType.Type.TIMESTAMP, exp.DataType.Type.UUID,
3315
- }
3316
- # TIMESTAMPTZ is too, where it holds an instant only (`zoned_timestamp_is_instant`).
3317
-
3318
- # Types whose values keep the zone they were given, where a TIMESTAMP WITH
3319
- # TIME ZONE is not an instant only: a CAST to another type reads that zone.
3320
- _ZONED_TYPES = {exp.DataType.Type.TIMESTAMPTZ, exp.DataType.Type.TIMETZ}
3321
-
3322
- # Types whose `null` (JSON's, a VARIANT's) is a non-null value that a CAST turns into NULL.
3323
- _JSON_TYPES = {exp.DataType.Type.JSON, exp.DataType.Type.JSONB, exp.DataType.Type.VARIANT, exp.DataType.Type.OBJECT}
3324
-
3325
- # Composite types: a comparison of their values may be NULL for a NULL element.
3326
- _COMPOSITE_TYPES = {exp.DataType.Type.ARRAY, exp.DataType.Type.LIST, exp.DataType.Type.STRUCT, exp.DataType.Type.MAP, exp.DataType.Type.NESTED}
3327
-
3328
- # The Builtins that compare two values, which compare composites element by element.
3329
- # Never NULL, in every dialect: a NULL operand is a value they compare.
3330
- _IS_DISTINCT_FROM = ir.Builtin(name="IS DISTINCT FROM", strict=(False, False), total=(False, False), injective=False)
3331
- # Never NULL: TRUE or FALSE, whatever its subquery returns.
3332
- _EXISTS = ir.Builtin(name="EXISTS", strict=(False,), total=(False,), injective=False)
3333
- _ORDER_COMPARISONS = {"<>", ">", ">=", "<", "<=", "BETWEEN"}
3334
- # Never NULL: `NULL IS TRUE` is FALSE, so never TRUE where the operand is NULL.
3335
- _IS_TRUE = ir.Builtin(name="IS TRUE", strict=(False,), total=(False,), injective=False, true_only_if_argument=True)
3336
- _IS_FALSE = ir.Builtin(name="IS FALSE", strict=(False,), total=(False,), injective=False, rejecting=(True,))
3337
-
3338
-
3339
- @cache
3340
- def _any_comparison(node: type[Expr]) -> ir.Builtin:
3341
- """`x op ANY (...)`, in every dialect: FALSE over no values, even for a
3342
- NULL `x`, else NULL where `x` is, so never TRUE where `x` is NULL. Not
3343
- `ALL`, which is TRUE over no values."""
3344
- names: dict[type[Expr], str] = {exp.EQ: "=", exp.NEQ: "<>", exp.GT: ">", exp.GTE: ">=", exp.LT: "<", exp.LTE: "<="}
3345
- name = names[node]
3346
- return ir.Builtin(name=f"{name} ANY", strict=(False, False), total=None, injective=False, rejecting=(True, False))
3347
-
3348
- # Comparisons, whose operands a zoned timestamp's text may be.
3349
- _COMPARISONS = (exp.EQ, exp.NEQ, exp.GT, exp.GTE, exp.LT, exp.LTE, exp.NullSafeEQ, exp.NullSafeNEQ, exp.In, exp.Like, exp.ILike, exp.Between)
3350
-
3351
- _EXACT_NUMERIC_TYPES = {*exp.DataType.INTEGER_TYPES, exp.DataType.Type.DECIMAL}
3352
-
3353
- # The largest value of each signed integer type, the same in every dialect.
3354
- _INTEGER_MAXIMA = {
3355
- exp.DataType.Type.TINYINT: 2**7 - 1, exp.DataType.Type.SMALLINT: 2**15 - 1,
3356
- exp.DataType.Type.INT: 2**31 - 1, exp.DataType.Type.BIGINT: 2**63 - 1,
3357
- }
3358
-
3359
-
3360
- def _cast_integer_literal(expression: Expr) -> ir.LiteralValue | None:
3361
- """The value of `CAST('1' AS INTEGER)` or `CAST(1 AS BIGINT)`: a
3362
- non-negative integer, written as a number or a string with no sign,
3363
- leading zero or space, within a signed integer type's range. That is the
3364
- same integer in every dialect; a decimal (`CAST('1.5' AS INTEGER)` rounds
3365
- or truncates by dialect) or any other cast is not folded."""
3366
- if type(expression) is not exp.Cast: # TRY_CAST and the like are not modelled
3367
- return None
3368
- to = expression.args.get("to")
3369
- maximum = _INTEGER_MAXIMA.get(to.this) if isinstance(to, exp.DataType) else None
3370
- value = literal_value(expression.this)
3371
- if maximum is None or value is None or value.type == "boolean" or not _PLAIN_INTEGER.fullmatch(value.text):
3372
- return None
3373
- return ir.LiteralValue(type="numeric", text=value.text) if int(value.text) <= maximum else None
3374
-
3375
-
3376
- _PLAIN_INTEGER = re.compile(r"0|[1-9][0-9]{0,18}")
3377
-
3378
- # Nodes whose value is not a function of the columns an expression reads.
3379
- # Builtins modelled only when the call sets no argument but their own.
3380
- _ONE_ARGUMENT_BUILTINS = (exp.Lower, exp.Upper, exp.Length, exp.Trim, exp.Abs, exp.Floor, exp.Ceil)
3381
-
3382
- _NOT_A_FUNCTION_OF_ITS_COLUMNS = (
3383
- exp.Anonymous, exp.Rand, exp.Randn, exp.Uuid, exp.AggFunc, exp.Filter, exp.WithinGroup, exp.Window, exp.Query, exp.Subquery,
3384
- exp.CurrentDate, exp.CurrentDatetime, exp.CurrentTime, exp.CurrentTimestamp, exp.Placeholder, exp.Parameter, exp.Star,
3385
- )
3386
-
3387
-
3388
- def _enum_type_values(definition: exp.ColumnDef, meaning: DialectSemantics) -> frozenset[ir.LiteralValue] | None:
3389
- """The values of a column declared `ENUM('a', ...)`: its members, with
3390
- their trailing spaces removed where the dialect does (MySQL)."""
3391
- kind = definition.args.get("kind")
3392
- if not (isinstance(kind, exp.DataType) and kind.this == exp.DataType.Type.ENUM and kind.expressions):
3393
- return None
3394
- values = [literal_value(member) for member in kind.expressions]
3395
- if any(value is None or value.type != "string" for value in values):
3396
- return None
3397
- members = {value for value in values if value is not None}
3398
- if meaning.enum_strips_trailing_spaces:
3399
- members = {replace(value, text=value.text.rstrip(" ")) for value in members}
3400
- return frozenset(members)
3401
-
3402
-
3403
- def _check_domains(condition: Expr, meaning: DialectSemantics) -> list[tuple[str, frozenset[ir.LiteralValue]]] | None:
3404
- """The Enumerated Domains a CHECK condition states, by lower-cased
3405
- column name, or None for a shape that states none sqlassert reads.
3406
-
3407
- A CHECK passes a row unless its condition is FALSE, so NULL passes. Each
3408
- AND-ed `col IN (v, ...)` or `col = v` over non-null literals is FALSE for
3409
- a non-null value equal to no v, which makes the whole condition FALSE: so
3410
- every non-null value of col equals one of them, exactly what ENUM states.
3411
- A NULL among the values would make the IN NULL instead, and pass any row.
3412
- """
3413
- parts = list(condition.flatten()) if isinstance(condition, exp.And) else [condition]
3414
- found = []
3415
- for part in parts:
3416
- match part.unnest():
3417
- case exp.EQ(this=exp.Column() as column, expression=value) | exp.EQ(this=value, expression=exp.Column() as column):
3418
- values = [value]
3419
- case exp.In(this=exp.Column() as column, expressions=list(values)) if values and part.unnest().args.get("query") is None:
3420
- pass
3421
- case _:
3422
- return None
3423
- literals = [literal_value(value) for value in values]
3424
- if column.table or any(
3425
- literal is None or (meaning.empty_string_is_null and literal.type == "string" and literal.text == "")
3426
- for literal in literals
3427
- ):
3428
- return None
3429
- found.append((column.name.lower(), frozenset(literal for literal in literals if literal is not None)))
3430
- return found
3431
-
3432
-
3433
- def _engine(symbol: _Symbol) -> str | None:
3434
- """The storage ENGINE a CREATE TABLE names (lower-cased), if any."""
3435
- assert symbol.statement is not None
3436
- engine = symbol.statement.find(exp.EngineProperty)
3437
- return engine.name.lower() if engine is not None else None
3438
-
3439
-
3440
- def _aggregate_arguments(call: exp.AggFunc) -> list[Expr]:
3441
- """The value arguments of an aggregate call: none for `count(*)`, the
3442
- listed ones under DISTINCT."""
3443
- this = call.this
3444
- if this is None or isinstance(this, exp.Star):
3445
- return []
3446
- if isinstance(this, exp.Distinct):
3447
- return list(this.expressions)
3448
- if not isinstance(this, Expr): # An unknown call's name (`main.max(x)` in ClickHouse).
3449
- return list(call.expressions)
3450
- return [this, *call.expressions]
3451
-
3452
-
3453
- def _is_positional(join: exp.Join) -> bool:
3454
- return (join.args.get("method") or "").lower() == "positional"
3455
-
3456
-
3457
- def _join_kind(join: exp.Join, dialect: str) -> ir.JoinKind | None:
3458
- """SEMI, ANTI and CROSS whatever the side; otherwise the side, else INNER
3459
- (`STRAIGHT_JOIN`, and ASOF, which keeps a subset of the inner join's rows).
3460
- None for a join whose semantics are not modelled: it lowers opaque."""
3461
- if _is_positional(join):
3462
- return "full"
3463
- kind, side = (join.args.get("kind") or "").lower(), (join.args.get("side") or "").lower()
3464
- if dialect == "clickhouse" and (side or kind not in {"", "inner", "cross"}):
3465
- # TODO: check ClickHouse semantics. Outer joins pad with the column
3466
- # type's default, not NULL, unless join_use_nulls is set; SEMI and ANTI
3467
- # joins keep the right columns; ANY and ASOF pick one match.
3468
- return None
3469
- match kind, side:
3470
- case ("semi" | "anti" | "cross") as kind, _:
3471
- return kind
3472
- case "" | "inner" | "outer" | "straight_join", ("left" | "right" | "full") as side:
3473
- return side
3474
- case "outer", "":
3475
- return "full"
3476
- case "" | "inner" | "straight_join", "":
3477
- return "inner"
3478
- case _:
3479
- # TODO: check the semantics of each dialect's other join kinds
3480
- # (ClickHouse ARRAY JOIN, ANY, ...) before modelling one.
3481
- return None
3482
-
3483
-
3484
- def _join_label(join: exp.Join, dialect: str) -> str:
3485
- keywords = " ".join(part for part in (join.side, join.kind, "JOIN") if part)
3486
- source = join.this
3487
- if _nested_join(source) is not None:
3488
- return f"{keywords} ({', '.join(part.alias_or_name for part in _flattened([source]))})"
3489
- if isinstance(source, exp.Subquery):
3490
- return f"{keywords} subquery {source.alias}".rstrip()
3491
- return f"{keywords} {source.sql(dialect=dialect)}"
3492
-
3493
-
3494
- def _select_label(select: exp.Query) -> str:
3495
- node = select.parent
3496
- while node is not None:
3497
- match node:
3498
- case exp.CTE():
3499
- return f"CTE {node.alias}"
3500
- case exp.Create():
3501
- table = node.this.this if isinstance(node.this, exp.Schema) else node.this
3502
- return f"view {table.name}"
3503
- case exp.Subquery() if node.alias:
3504
- return f"subquery {node.alias}"
3505
- case exp.Subquery():
3506
- return "subquery"
3507
- case _:
3508
- node = node.parent
3509
- return "Root Select"