sqlassert 0.3.1__py3-none-any.whl → 0.3.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
sqlassert/ir/convert.py CHANGED
@@ -7,17 +7,19 @@ a fresh Alias, while all occurrences share one memoized NamedRelation.
7
7
 
8
8
  from __future__ import annotations
9
9
 
10
+ import re
11
+ from collections import Counter
10
12
  from collections.abc import Callable, Iterable, Sequence, Set
11
13
  from dataclasses import dataclass, field, replace
12
14
  from functools import cache
13
- from typing import Literal, assert_never
15
+ from typing import Literal, TypeGuard, assert_never
14
16
 
15
17
  from sqlglot import Expr, exp
16
18
 
17
19
  from sqlassert import diagnostics as diag
18
20
  from sqlassert import ir
19
21
  from sqlassert.dialects import DialectSemantics, semantics
20
- from sqlassert.diagnostics import Diagnostic
22
+ from sqlassert.diagnostics import Diagnostic, quoted, quoted_all
21
23
  from sqlassert.properties import (
22
24
  EnumeratedDomain, ExactlyOneJoin, ExhaustiveCase, ForeignKey, FunctionalDependency, ManyToOneJoin, NonNullColumn, NonNullColumns, NonNullElements, NonNullUniqueSet,
23
25
  OneToManyJoin, OneToOneJoin, Property, ReferentialCoverage, UniqueJoin,
@@ -26,7 +28,8 @@ from sqlassert.properties import (
26
28
  from sqlassert.provenance import AttachmentSite, Origin, SQL
27
29
  from sqlassert.sql_parse import (
28
30
  JOIN_MARKER_NOUNS, MARKER_NOUNS, ColumnMarker, ParsedProgram, assertion_span, column_markers,
29
- exhaustive_span, grouping, is_ambiguous_pipes, join_marker_kind, join_origin, literal_value, marker_position,
31
+ exhaustive_span, grouping, join_marker_kind, join_origin, literal_value, marker_position,
32
+ written_sql,
30
33
  )
31
34
 
32
35
 
@@ -45,11 +48,14 @@ class _Symbol:
45
48
  origin: Origin
46
49
  body: exp.Query | None = None
47
50
  statement: exp.Create | None = None
51
+ column_aliases: tuple[str, ...] = ()
48
52
  required_columns: set[str] = field(default_factory=set)
49
53
  # Table-level constraints added after CREATE TABLE (ALTER TABLE, CREATE
50
54
  # UNIQUE INDEX), shaped like the CREATE TABLE's own, and columns set NOT NULL.
51
55
  constraints: list[Expr] = field(default_factory=list)
52
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
53
59
  # Each unique index with an expression key part: its parts and statement.
54
60
  expression_keys: list[tuple[list[Expr], exp.Create]] = field(default_factory=list)
55
61
 
@@ -61,6 +67,9 @@ class _Binding:
61
67
  column: ir.OutputColumn
62
68
  # The schema (and catalog) of an unaliased table, as `s1` in `s1.t.k`.
63
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
64
73
 
65
74
 
66
75
  @dataclass(frozen=True)
@@ -121,10 +130,17 @@ class IrParser:
121
130
  # Each scalar subquery lowered as a join, by id, and the qualifier of the
122
131
  # binding that holds its value.
123
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)
124
139
  _scalar_subqueries: list[tuple[AttachmentSite, ir.Join]] = field(default_factory=list)
125
140
  _sort_keys: dict[int, tuple[ir.OutputColumn, ...] | None] = field(default_factory=dict)
126
141
  _site_sort_keys: list[tuple[AttachmentSite, tuple[ir.OutputColumn, ...] | None]] = field(default_factory=list)
127
142
  _set_operations: list[tuple[AttachmentSite, ir.SetOperation]] = field(default_factory=list)
143
+ _unsupported: list[tuple[ir.Node, str]] = field(default_factory=list)
128
144
  # Columns made up for names a query uses: of a table with no CREATE, or an
129
145
  # opaque relation (`_guessed`), and those a declared table does not have (`_absent`).
130
146
  _guessed: set[ir.OutputColumn] = field(default_factory=set)
@@ -133,6 +149,9 @@ class IrParser:
133
149
  _absent: set[ir.OutputColumn] = field(default_factory=set)
134
150
  # Each declared table column's type, as its CREATE TABLE writes it.
135
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)
136
155
  # The comparisons already checked for a zoned timestamp's text, by id.
137
156
  _zone_checked: set[int] = field(default_factory=set)
138
157
  # Each composite column or CAST a comparison reads, by id, with the
@@ -149,6 +168,26 @@ class IrParser:
149
168
  return semantics(self.dialect)
150
169
 
151
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,))
152
191
  for statement in ast.create_statements:
153
192
  match statement:
154
193
  case exp.Create(kind="INDEX"):
@@ -188,7 +227,7 @@ class IrParser:
188
227
  return IrConversionResult(
189
228
  ir.Program(named_relations=named_relations, root=root, assertions=tuple(self._assertions), declarations=tuple(self._declarations), attachment_sites=tuple(self._attachment_sites),
190
229
  scalar_subqueries=tuple(self._scalar_subqueries), sort_keys=tuple(self._site_sort_keys),
191
- set_operations=tuple(self._set_operations)),
230
+ set_operations=tuple(self._set_operations), unsupported=tuple(self._unsupported)),
192
231
  tuple(self._knowledge), tuple(self._diagnostics), tuple(dict.fromkeys(warnings)),
193
232
  )
194
233
 
@@ -198,7 +237,7 @@ class IrParser:
198
237
  diag.UNDECLARED_TABLE,
199
238
  f"table {symbol.name} has no CREATE TABLE in the program, so its keys, nullability and column types are unknown: "
200
239
  "declare it with CREATE TABLE, or analyze with a database connection (analyze_database)",
201
- symbol.origin,
240
+ replace(symbol.origin, line=symbol.first_line or symbol.origin.line),
202
241
  )
203
242
  for symbol in self._symbols
204
243
  if symbol.role is ir.RelationRole.TABLE and symbol.statement is None
@@ -230,7 +269,8 @@ class IrParser:
230
269
  role = ir.RelationRole.TABLE if kind == "TABLE" else ir.RelationRole.VIEW
231
270
  body = statement.args.get("expression")
232
271
  query = _unwrap_query(body)
233
- symbol = _Symbol(name=name, role=role, origin=origin, body=query, statement=statement)
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)
234
274
  self._global_symbols[key] = symbol
235
275
  self._symbols.append(symbol)
236
276
 
@@ -264,8 +304,8 @@ class IrParser:
264
304
  symbol.constraints.append(exp.UniqueColumnConstraint(this=schema))
265
305
 
266
306
  def _alter(self, statement: exp.Alter) -> None:
267
- """ALTER TABLE adding PRIMARY KEY, UNIQUE, or FOREIGN KEY constraints, or
268
- setting columns NOT NULL. Any other action could invalidate what is
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
269
309
  known of the table, so a statement with one states nothing."""
270
310
  actions = statement.args.get("actions") or ()
271
311
  added: list[Expr] = []
@@ -283,7 +323,7 @@ class IrParser:
283
323
  if not actions or not all(_is_added_constraint(constraint) for constraint in added):
284
324
  self._diagnostics.append(Diagnostic(
285
325
  diag.UNSUPPORTED_STATEMENT,
286
- f"only ALTER TABLE adding PRIMARY KEY, UNIQUE, or FOREIGN KEY constraints, or setting NOT NULL, "
326
+ f"only ALTER TABLE adding PRIMARY KEY, UNIQUE, FOREIGN KEY or CHECK constraints, or setting NOT NULL, "
287
327
  f"is analyzed: {statement.sql(dialect=self.dialect)}",
288
328
  self._origin(statement),
289
329
  ))
@@ -319,6 +359,15 @@ class IrParser:
319
359
  self._origin(statement),
320
360
  ))
321
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
+
322
371
  def _discover_query(self, query: exp.Query, inherited_scope: dict[str, _Symbol]) -> None:
323
372
  if id(query) in self._query_scopes:
324
373
  return
@@ -326,16 +375,35 @@ class IrParser:
326
375
  scope = dict(inherited_scope)
327
376
  with_clause = _arg(query, "with")
328
377
  if with_clause is not None:
378
+ bodies = []
379
+ recursive = bool(with_clause.args.get("recursive"))
380
+ forward = recursive and self.dialect != "duckdb"
329
381
  for cte in with_clause.expressions:
330
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)
331
392
  symbol = _Symbol(
332
393
  name=cte.alias,
333
394
  role=ir.RelationRole.CTE,
334
395
  origin=Origin(SQL, cte.sql(dialect=self.dialect)),
335
396
  body=body,
397
+ column_aliases=_column_aliases(cte),
336
398
  )
337
399
  scope[cte.alias.lower()] = symbol
338
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)
339
407
 
340
408
  self._query_scopes[id(query)] = scope
341
409
  if isinstance(query, exp.SetOperation):
@@ -344,19 +412,20 @@ class IrParser:
344
412
  inner = _unwrap_query(side)
345
413
  if inner is not None:
346
414
  self._discover_query(inner, scope)
415
+ self._discover_marker_targets(query, scope)
347
416
  return
348
417
  if not isinstance(query, exp.Select):
349
418
  return
350
419
 
351
420
  sources = _direct_sources(query)
352
421
  by_qualifier: dict[str, list[Expr]] = {}
353
- for source in sources:
422
+ for source in [*sources, *(hidden for source in sources for hidden in _hidden_sources(source))]:
354
423
  self._source_required.setdefault(id(source), set())
355
424
  self._source_expressions[id(source)] = source
356
425
  qualifier = source.alias_or_name.lower()
357
426
  if qualifier:
358
427
  by_qualifier.setdefault(qualifier, []).append(source)
359
- if isinstance(source, exp.Table):
428
+ if _is_named_table(source):
360
429
  symbol = self._symbol_for_table(source, scope)
361
430
  self._table_symbols[id(source)] = symbol
362
431
  elif isinstance(source, exp.Subquery):
@@ -373,41 +442,34 @@ class IrParser:
373
442
  # An unqualified column in a nested query belongs to that query's scope.
374
443
  self._require(sources[0], column.name)
375
444
 
376
- for join in query.args.get("joins") or ():
377
- for identifier in join.args.get("using") or ():
378
- for source in sources:
379
- self._require(source, identifier.name)
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)
380
450
 
381
451
  if len(sources) == 1 and _star_only(query):
382
452
  for marker in column_markers(query):
383
453
  for column in (*marker.columns, *marker.dependent):
384
454
  self._require(sources[0], column)
385
455
 
386
- for marker in column_markers(query):
387
- if marker.referenced_relation is not None:
388
- origin = Origin.marked(marker.referenced_relation, marker.span)
389
- target = self._symbol_for_name(marker.referenced_relation, scope, origin)
390
- self._marker_targets[id(marker)] = target
391
- self._require_undeclared(target, marker.referenced_columns)
456
+ self._discover_marker_targets(query, scope)
392
457
 
393
458
  where = query.args.get("where")
394
- for conjunct in _conjuncts(where.this) if where is not None else ():
459
+ for conjunct in _filter_conjuncts(where.this) if where is not None else ():
395
460
  matched = _subquery_conjunct(conjunct)
396
461
  if matched is not None:
397
462
  self._discover_query(matched[1], scope)
398
- for expression in (*(_conjuncts(where.this) if where is not None else ()), *query.expressions):
463
+ for expression in (*(_filter_conjuncts(where.this) if where is not None else ()), *query.expressions):
399
464
  for subquery in _scalar_subqueries(expression):
400
465
  if isinstance(subquery.this, exp.Select):
401
466
  self._discover_query(subquery.this, scope)
402
467
 
403
- if with_clause is not None:
404
- for cte in with_clause.expressions:
405
- body = _unwrap_query(cte.this)
406
- if body is not None:
407
- self._discover_query(body, scope)
408
-
409
468
  def _symbol_for_table(self, table: exp.Table, scope: dict[str, _Symbol]) -> _Symbol:
410
- return self._symbol_for_name(_qualified_name(table), scope, Origin(SQL, table.sql(dialect=self.dialect)))
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
411
473
 
412
474
  def _symbol_for_name(self, name: str, scope: dict[str, _Symbol], origin: Origin) -> _Symbol:
413
475
  key = name.lower()
@@ -443,7 +505,7 @@ class IrParser:
443
505
 
444
506
  def _require(self, source: Expr, column: str) -> None:
445
507
  self._source_required.setdefault(id(source), set()).add(column)
446
- if isinstance(source, exp.Table):
508
+ if _is_named_table(source) and column.lower() not in {name.lower() for name in _column_aliases(source)}:
447
509
  self._table_symbols[id(source)].required_columns.add(column)
448
510
 
449
511
  def _propagate_required_columns(self) -> None:
@@ -455,16 +517,20 @@ class IrParser:
455
517
  if isinstance(symbol.body, exp.Select) and _star_only(symbol.body):
456
518
  sources = _direct_sources(symbol.body)
457
519
  if len(sources) == 1:
520
+ aliases = {name.lower() for name in symbol.column_aliases}
458
521
  for column in symbol.required_columns:
459
- self._require(sources[0], column)
522
+ if column.lower() not in aliases:
523
+ self._require(sources[0], column)
460
524
  for source_id, columns in tuple(self._source_required.items()):
461
525
  source = self._source_expressions[source_id]
462
526
  body = _unwrap_query(source) if isinstance(source, exp.Subquery) else None
463
527
  if isinstance(body, exp.Select) and _star_only(body):
464
528
  nested_sources = _direct_sources(body)
465
529
  if len(nested_sources) == 1:
530
+ aliases = {name.lower() for name in _column_aliases(source)}
466
531
  for column in columns:
467
- self._require(nested_sources[0], column)
532
+ if column.lower() not in aliases:
533
+ self._require(nested_sources[0], column)
468
534
  after = sum(len(symbol.required_columns) for symbol in self._symbols) + sum(len(columns) for columns in self._source_required.values())
469
535
  changed = after != before
470
536
 
@@ -483,17 +549,36 @@ class IrParser:
483
549
  left = self._opaque_relation(query.this)
484
550
  if right is None:
485
551
  right = self._opaque_relation(query.expression)
486
- output_columns = _pass_output_columns(left.output_columns, self._origin(query))
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)
487
562
  relation = ir.SetOperation(
488
563
  origin=self._origin(query), output_columns=output_columns, is_schema_complete=left.is_schema_complete and right.is_schema_complete,
489
564
  operator=_SET_OPERATORS[type(query)], left=left, right=right, distinct=bool(query.args.get("distinct")),
490
- by_name=bool(query.args.get("by_name")),
565
+ by_name=by_name,
491
566
  )
492
567
  last = _last_select(query.this)
493
568
  position = marker_position(last) if last is not None else None
494
569
  if relation.operator != "union" and position is not None:
495
570
  self._set_operations.append((AttachmentSite(relation.operator.upper(), position[1], position[0], True), relation))
496
- return self._lower_limit(relation, query)
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
497
582
  if not isinstance(query, exp.Select):
498
583
  return None
499
584
  return self._lower_select(query)
@@ -507,7 +592,7 @@ class IrParser:
507
592
  row = ir.OpaqueRelation(origin=origin, output_columns=(), is_schema_complete=True, description="no FROM")
508
593
  one_row = ir.Limit(origin=origin, output_columns=(), is_schema_complete=True, input=row, count=1)
509
594
  relation = self._lower_select_tail(_Lowered(one_row, ()), select)
510
- elif any(join.args.get("method") == "NATURAL" for join in select.args.get("joins") or ()):
595
+ elif any(join.args.get("method") == "NATURAL" for join in _all_joins(select)):
511
596
  relation = self._opaque_relation(select, _selected_output_names(select))
512
597
  else:
513
598
  lowered = self._lower_source(source)
@@ -541,7 +626,11 @@ class IrParser:
541
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)
542
627
 
543
628
  def _lower_source(self, source: Expr) -> _Lowered:
544
- if isinstance(source, exp.Table):
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):
545
634
  symbol = self._table_symbols[id(source)]
546
635
  alias_name = source.alias or source.name
547
636
  # An unaliased table may be named with its schema: `s1.t.k`.
@@ -551,18 +640,111 @@ class IrParser:
551
640
  self._report_cycle(symbol, source)
552
641
  recursive = self._recursive_relation(symbol, source)
553
642
  return self._alias(recursive, alias_name, self._origin(source), schema)
554
- return self._alias(self._resolve_symbol(symbol), 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)
555
652
 
556
653
  if isinstance(source, exp.Subquery):
557
654
  relation = self._lower_query(source)
558
655
  if relation is not None:
559
656
  # DuckDB allows an unaliased FROM subquery; nothing can qualify
560
657
  # a column by its name, so a placeholder serves.
561
- return self._alias(relation, source.alias or "subquery", self._origin(source))
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))
562
664
 
563
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))
564
669
  return self._alias(opaque, source.alias_or_name or "opaque", self._origin(source))
565
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
+
566
748
  def _resolve_symbol(self, symbol: _Symbol) -> ir.NamedRelation:
567
749
  existing = self._named_relations.get(symbol)
568
750
  if existing is not None:
@@ -584,7 +766,7 @@ class IrParser:
584
766
  self._resolving.discard(symbol)
585
767
  if body is None:
586
768
  body = self._opaque_relation(symbol.body or exp.Table(this=symbol.name), symbol.required_columns)
587
- output_columns = _pass_output_columns(body.output_columns, symbol.origin)
769
+ output_columns = self._aliased_outputs(body, symbol.origin, symbol.column_aliases)
588
770
  named = ir.NamedRelation(
589
771
  origin=symbol.origin,
590
772
  output_columns=output_columns,
@@ -616,6 +798,10 @@ class IrParser:
616
798
  by_name = {definition.name: definition for definition in definitions}
617
799
  if symbol.statement is not None:
618
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}
619
805
  typed = tuple(
620
806
  replace(
621
807
  column, binary_text=self._is_binary_text(by_name[column.name]),
@@ -637,7 +823,7 @@ class IrParser:
637
823
  return None
638
824
  if kind.this in exp.DataType.TEXT_TYPES:
639
825
  return kind.sql(dialect=self.dialect) if self._is_binary_text(definition) else None
640
- if _collated(definition) or self._unscaled_decimal(kind):
826
+ if self._unscaled_decimal(kind):
641
827
  return None
642
828
  return kind.sql(dialect=self.dialect)
643
829
 
@@ -660,16 +846,11 @@ class IrParser:
660
846
  return self.semantics.unscaled_decimal and kind.this == exp.DataType.Type.DECIMAL and not kind.expressions
661
847
 
662
848
  def _is_binary_text(self, definition: exp.ColumnDef) -> bool:
663
- """Declared VARCHAR or TEXT, with no COLLATE, in a dialect whose
664
- default collation is binary: compared by identity.
665
-
666
- CHAR is not: it ignores trailing spaces when compared. Any COLLATE,
667
- even a binary one, is not modelled (issue 49)."""
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."""
668
852
  kind = definition.args.get("kind")
669
- return (
670
- isinstance(kind, exp.DataType) and kind.this in _TEXT_TYPES
671
- and not _collated(definition) and self.semantics.text_is_binary
672
- )
853
+ return isinstance(kind, exp.DataType) and kind.this in _TEXT_TYPES and self.semantics.text_is_binary
673
854
 
674
855
  def _opaque_output_columns(self, names: Iterable[str], origin: Origin) -> tuple[ir.OutputColumn, ...]:
675
856
  if isinstance(names, Set):
@@ -687,16 +868,27 @@ class IrParser:
687
868
 
688
869
  def _recursive_relation(self, symbol: _Symbol, source: Expr) -> ir.RecursiveRelation:
689
870
  origin = self._origin(source)
690
- return ir.RecursiveRelation(
871
+ relation = ir.RecursiveRelation(
691
872
  origin=origin,
692
873
  output_columns=self._opaque_output_columns(symbol.required_columns, origin),
693
874
  is_schema_complete=False,
694
875
  description=source.sql(dialect=self.dialect),
695
876
  relation_name=symbol.name,
696
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
+ )
697
889
 
698
- def _alias(self, source: ir.RelationExpr, name: str, origin: Origin, schema: str = "") -> _Lowered:
699
- output_columns = _pass_output_columns(source.output_columns, origin)
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)
700
892
  alias = ir.Alias(origin=origin, output_columns=output_columns, is_schema_complete=source.is_schema_complete, source=source, name=name)
701
893
  return _Lowered(alias, tuple(_Binding(name.lower(), output.name.lower(), output, schema) for output in output_columns))
702
894
 
@@ -737,7 +929,51 @@ class IrParser:
737
929
  )
738
930
  self._join_marker(join, relation)
739
931
  self._add_attachment_site(join, _join_label(join, self.dialect), relation, trailing=False)
740
- return _Lowered(relation, bindings)
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))
741
977
 
742
978
  def _opaque_join(self, left: _Lowered, right: _Lowered, join: exp.Join, origin: Origin) -> _Lowered:
743
979
  """A join whose kind is not modelled: every column it outputs is opaque,
@@ -786,8 +1022,12 @@ class IrParser:
786
1022
  return _and(tuple(
787
1023
  ir.Equality(
788
1024
  origin=self._origin(identifier, _source_line(identifier)),
789
- left=self._lower_expression(exp.column(identifier.name), left.bindings),
790
- right=self._lower_expression(exp.column(identifier.name), right.bindings),
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
+ ),
791
1031
  )
792
1032
  for identifier in using
793
1033
  ), self._origin(join))
@@ -795,7 +1035,7 @@ class IrParser:
795
1035
  if predicate is None:
796
1036
  return None
797
1037
  complete = left.relation.is_schema_complete and right.relation.is_schema_complete
798
- return self._lower_condition(predicate, _conjuncts(predicate), left.bindings + right.bindings, schema_complete=complete)
1038
+ return self._lower_condition(predicate, _filter_conjuncts(predicate), left.bindings + right.bindings, schema_complete=complete)
799
1039
 
800
1040
  def _lower_condition(
801
1041
  self, source: Expr, conjuncts: list[Expr], bindings: tuple[_Binding, ...], *, schema_complete: bool
@@ -813,13 +1053,45 @@ class IrParser:
813
1053
  return self._lower_expression(conjunct, bindings, schema_complete=schema_complete, line=_source_line(conjunct))
814
1054
 
815
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
816
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))
817
1079
  if keys is not None:
818
- relation = self._lower_aggregate(lowered, select, keys)
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
+ )
819
1091
  elif select.args.get("distinct") is not None and select.args["distinct"].args.get("on") is not None:
820
1092
  relation = self._lower_distinct_on(lowered, select, select.args["distinct"].args["on"])
821
1093
  elif select.args.get("distinct") is not None:
822
- relation = self._lower_distinct(lowered, select)
1094
+ relation = self._qualified(self._lower_distinct(lowered, select), select, grouped=False)
823
1095
  elif isinstance(select.args.get("qualify"), exp.Qualify):
824
1096
  relation = self._lower_qualify(lowered, select, select.args["qualify"])
825
1097
  else:
@@ -831,7 +1103,11 @@ class IrParser:
831
1103
  lowered, _ = self._join_scalar_subqueries(lowered, select.expressions)
832
1104
  relation = self._project(lowered, select.expressions, self._origin(select))
833
1105
  if relation is None:
834
- return self._opaque_relation(select, _selected_output_names(select))
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
835
1111
  self._sort_keys[id(select)] = self._resolve_order(select, lowered.bindings, relation)
836
1112
  return relation
837
1113
 
@@ -864,7 +1140,7 @@ class IrParser:
864
1140
  schema, name = _schema_path(expression), expression.name.lower()
865
1141
  bound = [
866
1142
  binding for binding in bindings
867
- if binding.name == name and (not expression.table or binding.qualifier == expression.table.lower())
1143
+ if binding.name == name and (binding.qualifier == expression.table.lower() if expression.table else not binding.shadowed)
868
1144
  and (not schema or binding.schema == schema)
869
1145
  ]
870
1146
  if len(bound) == 1:
@@ -876,11 +1152,36 @@ class IrParser:
876
1152
  keys.append(key)
877
1153
  return tuple(keys)
878
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
+
879
1180
  def _filter(self, lowered: _Lowered, where: exp.Where) -> _Lowered:
880
1181
  """WHERE: each `EXISTS`, `NOT EXISTS`, or `IN (subquery)` conjunct as a
881
1182
  semi or anti join (Paulley §4.4.2), the other conjuncts as one Filter."""
882
1183
  remaining = []
883
- for conjunct in _conjuncts(where.this):
1184
+ for conjunct in _filter_conjuncts(where.this):
884
1185
  joined = self._subquery_join(lowered, conjunct)
885
1186
  if joined is None:
886
1187
  remaining.append(conjunct)
@@ -952,8 +1253,8 @@ class IrParser:
952
1253
  if binding.qualifier == qualifier and (not schema or binding.schema == schema) and binding.name == name
953
1254
  ])
954
1255
  return None
955
- inner_named = [binding for binding in inner.bindings if binding.name == name and self._owns(binding) != "no"]
956
- outer_named = [binding for binding in outer.bindings if binding.name == name and self._owns(binding) != "no"]
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"]
957
1258
  owners = {self._owns(binding) for binding in inner_named}
958
1259
  if "yes" in owners:
959
1260
  return one("inner", inner_named)
@@ -963,7 +1264,7 @@ class IrParser:
963
1264
  return one("inner", inner_named)
964
1265
  self._warnings.append(Diagnostic(
965
1266
  diag.AMBIGUOUS_COLUMN,
966
- f"column {column.name} in a subquery may belong to its own FROM or to the outer query, "
1267
+ f"column {quoted(column.name)} in a subquery may belong to its own FROM or to the outer query, "
967
1268
  "since some of its tables have no declared columns: qualify it, declare those tables with CREATE TABLE, "
968
1269
  "or analyze with a database connection (analyze_database)",
969
1270
  self._origin(column, _source_line(column)),
@@ -1015,7 +1316,7 @@ class IrParser:
1015
1316
  return None
1016
1317
  source = _from_source(select)
1017
1318
  if source is None or select.args.get("with") or any(
1018
- join.args.get("method") == "NATURAL" for join in select.args.get("joins") or ()
1319
+ join.args.get("method") == "NATURAL" for join in _all_joins(select)
1019
1320
  ) or any(isinstance(node, (exp.Subquery, exp.Exists, exp.Query)) and node is not select for node in select.walk()):
1020
1321
  return None
1021
1322
  right = self._lower_source(source)
@@ -1034,6 +1335,8 @@ class IrParser:
1034
1335
  value = right_relation.output_columns[0]
1035
1336
  predicate = None
1036
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)
1037
1340
  if grouping(select) is not None or any(select.args.get(key) for key in ("having", "qualify", "distinct", "limit", "offset", "windows")):
1038
1341
  return None
1039
1342
  item = select.expressions[0]
@@ -1044,7 +1347,7 @@ class IrParser:
1044
1347
  return None
1045
1348
  inner = select.args.get("where")
1046
1349
  predicate = None if inner is None else self._lower_condition(
1047
- inner.this, _conjuncts(inner.this), lowered.bindings + right.bindings,
1350
+ inner.this, _filter_conjuncts(inner.this), lowered.bindings + right.bindings,
1048
1351
  schema_complete=lowered.relation.is_schema_complete and right.relation.is_schema_complete,
1049
1352
  )
1050
1353
  right_relation, value = right.relation, lowered_value.column
@@ -1067,6 +1370,96 @@ class IrParser:
1067
1370
  )
1068
1371
  return _Lowered(join, bindings), remapped
1069
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
+
1070
1463
  def _subquery_join(self, lowered: _Lowered, conjunct: Expr) -> _Lowered | None:
1071
1464
  """`EXISTS (SELECT ... FROM r WHERE p)` as a semi join of r on p, and
1072
1465
  `NOT EXISTS` as an anti join; `p` may read the outer row (a dependent
@@ -1080,7 +1473,7 @@ class IrParser:
1080
1473
  source = _from_source(select)
1081
1474
  if source is None or grouping(select) is not None or any(
1082
1475
  select.args.get(key) for key in ("having", "qualify", "distinct", "limit", "offset", "with", "windows")
1083
- ) or any(join.args.get("method") == "NATURAL" for join in select.args.get("joins") or ()):
1476
+ ) or any(join.args.get("method") == "NATURAL" for join in _all_joins(select)):
1084
1477
  # Grouped by nothing (`grouping` is []), it returns one row whatever its WHERE: EXISTS is always true.
1085
1478
  return None
1086
1479
  right = self._lower_source(source)
@@ -1088,7 +1481,7 @@ class IrParser:
1088
1481
  right = self._lower_join(right, join)
1089
1482
  inner = select.args.get("where")
1090
1483
  predicate = None if inner is None else self._lower_condition(
1091
- inner.this, _conjuncts(inner.this), lowered.bindings + right.bindings,
1484
+ inner.this, _filter_conjuncts(inner.this), lowered.bindings + right.bindings,
1092
1485
  schema_complete=lowered.relation.is_schema_complete and right.relation.is_schema_complete,
1093
1486
  )
1094
1487
  relation = right.relation
@@ -1117,42 +1510,86 @@ class IrParser:
1117
1510
  return _Lowered(relation, tuple(replace(binding, column=remapped[binding.column]) for binding in left.bindings))
1118
1511
 
1119
1512
  def _project(self, lowered: _Lowered, items: list[Expr], origin: Origin) -> ir.Project:
1120
- output_columns = tuple(
1121
- ir.OutputColumn(
1122
- origin=self._origin(item),
1123
- name=item.alias_or_name,
1124
- scalar_expr=self._lower_expression(
1125
- item.this if isinstance(item, exp.Alias) else item,
1126
- lowered.bindings,
1127
- schema_complete=lowered.relation.is_schema_complete,
1128
- ),
1129
- )
1130
- for item in items
1131
- )
1513
+ output_columns = self._selected_output_columns(items, lowered)
1132
1514
  return ir.Project(origin=origin, output_columns=output_columns, is_schema_complete=True, input=lowered.relation)
1133
1515
 
1134
- def _lower_aggregate(self, lowered: _Lowered, select: exp.Select, keys: list[Expr]) -> ir.Aggregate | None:
1135
- """`select` grouped by `keys`; [] is one group, one row however many rows its input has."""
1136
- group = select.args.get("group")
1137
- if select.args.get("having") is not None or (
1138
- group is not None and any(group.args.get(key) for key in ("grouping_sets", "rollup", "cube", "totals"))
1139
- ):
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:
1140
1529
  return None
1141
1530
  if select.args.get("where") is not None:
1142
1531
  lowered = self._filter(lowered, select.args["where"])
1143
1532
 
1533
+ items: list[Expr] = list(select.expressions)
1534
+ selected_names = {item.alias_or_name.lower() for item in items}
1144
1535
  grouped_items: set[int] = set()
1536
+ matched: list[Expr] = []
1145
1537
  for group_expression in keys:
1146
- item = _matching_grouping_output(group_expression, select.expressions)
1538
+ item = _matching_grouping_output(group_expression, select.expressions) or _same_column_alias(group_expression, select.expressions)
1147
1539
  if item is None:
1148
- return 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)
1149
1547
  grouped_items.add(id(item))
1150
-
1151
- output_columns = self._aggregate_output_columns(select.expressions, lowered, grouped_items)
1152
- grouping_outputs: list[ir.OutputColumn] = []
1153
- for group_expression in keys:
1154
- item = _matching_grouping_output(group_expression, select.expressions)
1155
- grouping_outputs.append(output_columns[select.expressions.index(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)
1156
1593
  calls = tuple(
1157
1594
  ir.AggregateCall(
1158
1595
  origin=self._origin(call), description=call.sql(dialect=self.dialect),
@@ -1161,13 +1598,93 @@ class IrParser:
1161
1598
  for argument in _aggregate_arguments(call)
1162
1599
  ),
1163
1600
  )
1164
- for item in select.expressions for call in item.find_all(exp.AggFunc)
1165
- if call.find_ancestor(exp.Window, exp.Select) is select
1601
+ for call in written_calls
1166
1602
  )
1167
- return ir.Aggregate(
1603
+ aggregate = ir.Aggregate(
1168
1604
  origin=self._origin(select), output_columns=output_columns, is_schema_complete=True, input=lowered.relation,
1169
1605
  grouping_outputs=tuple(grouping_outputs), calls=calls,
1170
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
+ )
1171
1688
 
1172
1689
  def _lower_distinct(self, lowered: _Lowered, select: exp.Select) -> ir.Distinct | None:
1173
1690
  distinct = select.args.get("distinct")
@@ -1189,6 +1706,30 @@ class IrParser:
1189
1706
  lowered, select, window.args.get("partition_by") or (), order.expressions if order else (),
1190
1707
  )
1191
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
+
1192
1733
  def _lower_distinct_on(self, lowered: _Lowered, select: exp.Select, on: Expr) -> ir.QualifyByPartition | None:
1193
1734
  """`DISTINCT ON (k...)` keeps one row per distinct `k...`, like
1194
1735
  `QUALIFY ROW_NUMBER() OVER (PARTITION BY k...) = 1`. Its ORDER BY only
@@ -1207,13 +1748,11 @@ class IrParser:
1207
1748
  if select.args.get("where") is not None:
1208
1749
  lowered = self._filter(lowered, select.args["where"])
1209
1750
 
1751
+ positions = _partition_positions(partitions, select.expressions)
1752
+ if positions is None:
1753
+ return None
1210
1754
  output_columns = self._selected_output_columns(select.expressions, lowered)
1211
- partition_outputs: list[ir.OutputColumn] = []
1212
- for partition in partitions:
1213
- item = _matching_output(partition, select.expressions)
1214
- if item is None:
1215
- return None
1216
- partition_outputs.append(output_columns[select.expressions.index(item)])
1755
+ partition_outputs = [output_columns[position] for position in positions]
1217
1756
  ordering = tuple(
1218
1757
  self._lower_expression(ordered.this, lowered.bindings, schema_complete=lowered.relation.is_schema_complete)
1219
1758
  for ordered in order
@@ -1224,35 +1763,138 @@ class IrParser:
1224
1763
  )
1225
1764
 
1226
1765
  def _selected_output_columns(self, items: list[Expr], lowered: _Lowered) -> tuple[ir.OutputColumn, ...]:
1227
- return tuple(
1228
- ir.OutputColumn(
1229
- origin=self._origin(item),
1230
- name=item.alias_or_name,
1231
- scalar_expr=self._lower_expression(
1232
- item.this if isinstance(item, exp.Alias) else item,
1233
- lowered.bindings,
1234
- schema_complete=lowered.relation.is_schema_complete,
1235
- ),
1236
- )
1237
- for item in items
1238
- )
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)
1239
1783
 
1240
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
1241
1800
  output_columns: list[ir.OutputColumn] = []
1242
1801
  for item in items:
1243
1802
  expression = item.this if isinstance(item, exp.Alias) else item
1244
- lowered = self._lower_expression(expression, source.bindings, schema_complete=source.relation.is_schema_complete)
1245
- if id(item) not in grouped_items and _is_bare_aggregate_expression(expression):
1246
- # Grouped by nothing (no grouped items), the one row exists even
1247
- # over no input rows, so a bare column, where a dialect allows
1248
- # one, may be NULL.
1249
- lowered = (
1250
- ir.AnyAggregate(origin=self._origin(expression), input=lowered) if grouped_items
1251
- else ir.OpaqueExpression(origin=self._origin(expression), description=expression.sql(dialect=self.dialect))
1252
- )
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"))
1253
1807
  output_columns.append(ir.OutputColumn(origin=self._origin(item), name=item.alias_or_name, scalar_expr=lowered))
1254
1808
  return tuple(output_columns)
1255
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
+
1256
1898
  def _lower_expression(
1257
1899
  self, expression: Expr, bindings: tuple[_Binding, ...], *, schema_complete: bool = False, line: int | None = None
1258
1900
  ) -> ir.ScalarExpr:
@@ -1264,6 +1906,8 @@ class IrParser:
1264
1906
  OpaquePureFunction of its lowered arguments, unless its value is not a
1265
1907
  function of them (`_NOT_A_FUNCTION_OF_ITS_COLUMNS`)."""
1266
1908
  origin = self._origin(expression, line)
1909
+ if (grouped := self._grouped_values.get(id(expression))) is not None:
1910
+ return grouped
1267
1911
 
1268
1912
  def lower(node: Expr) -> ir.ScalarExpr:
1269
1913
  return self._lower_expression(node, bindings, schema_complete=schema_complete)
@@ -1273,6 +1917,11 @@ class IrParser:
1273
1917
  value = next((binding.column for binding in bindings if binding.qualifier == qualifier), None)
1274
1918
  if value is not None:
1275
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)
1276
1925
  if isinstance(expression, exp.Column) and id(expression) in self._scoped_columns:
1277
1926
  column = self._scoped_columns[id(expression)]
1278
1927
  if any(binding.column is column for binding in bindings):
@@ -1284,17 +1933,19 @@ class IrParser:
1284
1933
  binding for binding in bindings
1285
1934
  if binding.qualifier == expression.table.lower() and binding.name == expression.name.lower() and (not schema or binding.schema == schema)
1286
1935
  ]
1287
- elif schema_complete or len({binding.qualifier for binding in bindings if not binding.qualifier.startswith(_SCALAR_QUALIFIER)}) == 1:
1288
- matches = [binding for binding in bindings if binding.name == expression.name.lower()]
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]
1289
1940
  else:
1290
1941
  matches = []
1291
1942
  sources = ", ".join(dict.fromkeys(binding.qualifier for binding in bindings))
1292
1943
  self._warnings.append(Diagnostic(
1293
1944
  diag.AMBIGUOUS_COLUMN,
1294
- f"column {expression.name} is unqualified and more than one source may own it ({sources}), "
1945
+ f"column {quoted(expression.name)} is unqualified and more than one source may own it ({sources}), "
1295
1946
  "since some have no declared columns: qualify it, declare those tables with CREATE TABLE, "
1296
1947
  "or analyze with a database connection (analyze_database)",
1297
- origin,
1948
+ origin if origin.line is not None else replace(origin, line=_source_line(expression)),
1298
1949
  ))
1299
1950
  if len(matches) == 1:
1300
1951
  return ir.ColumnRef(origin=origin, column=matches[0].column)
@@ -1308,6 +1959,8 @@ class IrParser:
1308
1959
  match expression:
1309
1960
  case exp.Paren():
1310
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.
1311
1964
  case exp.Null():
1312
1965
  return ir.NullLiteral(origin=origin)
1313
1966
  case exp.Count():
@@ -1318,31 +1971,42 @@ class IrParser:
1318
1971
  return self._lower_case(expression, bindings, schema_complete=schema_complete)
1319
1972
  case exp.And():
1320
1973
  return self._lower_condition(expression, _conjuncts(expression), bindings, schema_complete=schema_complete)
1321
- case exp.Or() if is_ambiguous_pipes(expression):
1322
- pipes = f"{expression.this.sql(dialect=self.dialect)} || {expression.expression.sql(dialect=self.dialect)}"
1323
- self._warnings.append(Diagnostic(
1324
- diag.AMBIGUOUS_OPERATOR,
1325
- f"`||` is OR in {self.dialect}, or concatenation under sql_mode PIPES_AS_CONCAT, which also groups "
1326
- f"its operands differently, so {pipes} is an unknown function of its columns: write OR or CONCAT()",
1327
- self._origin(expression, line or _source_line(expression)),
1328
- ))
1329
- return ir.OpaquePureFunction(origin=origin, arguments=tuple(lower(child) for child in expression.iter_expressions()), description=pipes)
1330
1974
  case exp.Or():
1331
1975
  return ir.Or(origin=origin, parts=tuple(
1332
1976
  self._lower_condition(branch, _conjuncts(branch), bindings, schema_complete=schema_complete)
1333
1977
  for branch in _disjuncts(expression)
1334
1978
  ))
1335
1979
  case exp.EQ() if not quantified:
1336
- return ir.Equality(origin=origin, left=lower(expression.this), right=lower(expression.expression))
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)
1337
1998
  case exp.Is(expression=exp.Null()):
1338
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)
1339
2003
  case exp.Not(this=exp.Is(expression=exp.Null()) as test):
1340
2004
  return ir.IsNotNull(origin=origin, operand=lower(test.this))
1341
2005
  case exp.In() if expression.expressions and not any(expression.args.get(key) for key in ("query", "unnest", "field")):
1342
2006
  return ir.InList(origin=origin, operand=lower(expression.this), values=tuple(lower(value) for value in expression.expressions))
1343
2007
  case _:
1344
2008
  pass
1345
- value = literal_value(expression)
2009
+ value = literal_value(expression) or _cast_integer_literal(expression)
1346
2010
  if value == ir.LiteralValue(type="string", text="") and self.semantics.empty_string_is_null:
1347
2011
  return ir.NullLiteral(origin=origin)
1348
2012
  if value is not None or isinstance(expression, exp.Literal):
@@ -1354,8 +2018,22 @@ class IrParser:
1354
2018
  # `CAST(JSON 'null' AS BIGINT)` is NULL.
1355
2019
  function = replace(function, total=None)
1356
2020
  values = [value for key in keys for value in _as_list(expression.args[key])]
1357
- if function.accepts(len(values)):
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:
1358
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)
1359
2037
  composites = [
1360
2038
  (value, argument) for value, argument in zip(values, arguments)
1361
2039
  if function.name in _ORDER_COMPARISONS and function.total is not None and self._is_composite(value, lower)
@@ -1364,9 +2042,20 @@ class IrParser:
1364
2042
  function, arguments = self._composite_comparison(expression, function, arguments, composites, self._origin(expression, line or _source_line(expression)))
1365
2043
  return ir.Call(origin=origin, function=function, arguments=arguments, description=description)
1366
2044
  if isinstance(expression, _NOT_A_FUNCTION_OF_ITS_COLUMNS):
1367
- return ir.OpaqueExpression(origin=origin, description=description)
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
1368
2049
  return ir.OpaquePureFunction(origin=origin, arguments=tuple(lower(child) for child in expression.iter_expressions()), description=description)
1369
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
+
1370
2059
  def _check_zoned_text(self, comparison: Expr, lower: Callable[[Expr], ir.ScalarExpr], origin: Origin) -> None:
1371
2060
  """Warn of a comparison with a CAST of a zoned timestamp, where it keeps
1372
2061
  its zone: equal instants cast to different text (or dates, or local
@@ -1436,8 +2125,7 @@ class IrParser:
1436
2125
  return warnings
1437
2126
 
1438
2127
  def _is_composite(self, node: Expr, lower: Callable[[Expr], ir.ScalarExpr]) -> bool:
1439
- """Whether `node`'s value is known to be an ARRAY, ROW or MAP. A column
1440
- of unknown type is taken to be a scalar: composites are rare."""
2128
+ """Whether the operand may be composite, including unknown column types."""
1441
2129
  match node:
1442
2130
  case exp.Paren() | exp.Nullif():
1443
2131
  return self._is_composite(node.this, lower)
@@ -1445,7 +2133,7 @@ class IrParser:
1445
2133
  return node.to.this in _COMPOSITE_TYPES
1446
2134
  case exp.Column():
1447
2135
  kind = self._declared_type(lower(node))
1448
- return kind is not None and kind.this in _COMPOSITE_TYPES
2136
+ return self.dialect in {"trino", "postgres"} if kind is None else kind.this in _COMPOSITE_TYPES
1449
2137
  case exp.Array() | exp.Struct() | exp.Map() | exp.VarMap():
1450
2138
  return True
1451
2139
  case exp.Coalesce():
@@ -1461,8 +2149,7 @@ class IrParser:
1461
2149
  return False
1462
2150
 
1463
2151
  def _is_json(self, node: Expr, lower: Callable[[Expr], ir.ScalarExpr]) -> bool:
1464
- """Whether `node`'s value is known to be JSON (or a VARIANT), whose
1465
- `null` a CAST turns into NULL. A column of unknown type is taken not to be."""
2152
+ """Whether the operand may be JSON or VARIANT, whose null can cast to SQL NULL."""
1466
2153
  match node:
1467
2154
  case exp.Paren() | exp.Nullif():
1468
2155
  return self._is_json(node.this, lower)
@@ -1470,7 +2157,7 @@ class IrParser:
1470
2157
  return node.to.this in _JSON_TYPES
1471
2158
  case exp.Column():
1472
2159
  kind = self._declared_type(lower(node))
1473
- return kind is not None and kind.this in _JSON_TYPES
2160
+ return kind is None or kind.this in _JSON_TYPES
1474
2161
  case exp.ParseJSON() | exp.JSONExtract() | exp.JSONBExtract() | exp.JSONObject() | exp.JSONArray() | exp.JSONObjectAgg() | exp.JSONArrayAgg():
1475
2162
  return True
1476
2163
  case exp.Coalesce():
@@ -1485,11 +2172,16 @@ class IrParser:
1485
2172
  case _:
1486
2173
  return False
1487
2174
 
1488
- def _declared_type(self, expression: ir.ScalarExpr) -> exp.DataType | None:
2175
+ def _declared_type(self, expression: ir.ScalarExpr, *, through_sets: bool = True) -> exp.DataType | None:
1489
2176
  """The type a CREATE TABLE declares for the column `expression` reads,
1490
- through every column that passes it on."""
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."""
1491
2181
  while isinstance(expression, ir.ColumnRef):
1492
2182
  column = expression.column
2183
+ if not through_sets and column in self._set_outputs:
2184
+ return None
1493
2185
  if column in self._declared_types:
1494
2186
  return self._declared_types[column]
1495
2187
  expression = column.scalar_expr
@@ -1531,12 +2223,19 @@ class IrParser:
1531
2223
 
1532
2224
  # Assertions and diagnostics --------------------------------------------
1533
2225
 
1534
- def _register_column_markers(self, relation: ir.RelationExpr, select: exp.Select) -> None:
2226
+ def _register_column_markers(self, relation: ir.RelationExpr, select: exp.Query) -> None:
1535
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}
1536
2229
  for marker in column_markers(select):
1537
2230
  kind, columns, line = marker.kind, marker.columns, marker.span.line
1538
2231
  self._handled_column_markers.add(id(marker))
1539
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
1540
2239
  unknown = [column for column in (*columns, *marker.dependent) if column.lower() not in by_name]
1541
2240
  if unknown and relation.is_schema_complete:
1542
2241
  self._diagnostics.append(
@@ -1604,7 +2303,7 @@ class IrParser:
1604
2303
  assert_never(kind)
1605
2304
 
1606
2305
  def _add_attachment_site(
1607
- self, node: exp.Join | exp.Select | exp.Case, label: str, relation: ir.RelationExpr | ir.SimpleCase, *, trailing: bool
2306
+ self, node: exp.Join | exp.Query | exp.Case, label: str, relation: ir.RelationExpr | ir.SimpleCase, *, trailing: bool
1608
2307
  ) -> None:
1609
2308
  position = marker_position(node)
1610
2309
  if position is not None:
@@ -1624,8 +2323,8 @@ class IrParser:
1624
2323
  self._diagnostics.append(Diagnostic(
1625
2324
  diag.UNKNOWN_REFERENCED_COLUMN,
1626
2325
  f"the {MARKER_NOUNS[marker.kind]} on line {marker.span.line} references "
1627
- f"{target.name}({', '.join(marker.referenced_columns)}), but {target.name} has no column "
1628
- f"{', '.join(_missing(target, marker.referenced_columns))}",
2326
+ f"{target.name}({quoted_all(marker.referenced_columns)}), but {target.name} has no column "
2327
+ f"{quoted_all(_missing(target, marker.referenced_columns))}",
1629
2328
  pending.origin,
1630
2329
  ))
1631
2330
  continue
@@ -1664,7 +2363,7 @@ class IrParser:
1664
2363
  self._diagnostics.append(Diagnostic(
1665
2364
  diag.INVALID_FOREIGN_KEY_CONSTRAINT,
1666
2365
  f"a foreign key of {table.name} must pair columns of its own with equally many columns of "
1667
- f"{target.name}: ({', '.join(reference.columns)}) references ({', '.join(target_names)})",
2366
+ f"{target.name}: ({quoted_all(reference.columns)}) references ({quoted_all(target_names)})",
1668
2367
  reference.origin,
1669
2368
  ))
1670
2369
  continue
@@ -1672,8 +2371,8 @@ class IrParser:
1672
2371
  if referenced is None:
1673
2372
  self._diagnostics.append(Diagnostic(
1674
2373
  diag.UNKNOWN_REFERENCED_COLUMN,
1675
- f"a foreign key of {table.name} references {target.name}({', '.join(target_names)}), "
1676
- f"but {target.name} has no column {', '.join(_missing(target, target_names))}",
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))}",
1677
2376
  reference.origin,
1678
2377
  ))
1679
2378
  continue
@@ -1740,9 +2439,9 @@ class IrParser:
1740
2439
  )
1741
2440
 
1742
2441
  def _table_knowledge(self, relation: ir.NamedRelation, symbol: _Symbol) -> None:
1743
- """A declared table's ENUM types, NOT NULL columns and keys: Knowledge
1744
- where the dialect enforces them, Property Declarations where they are
1745
- trusted (`_key_trust`)."""
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`)."""
1746
2445
  statement = symbol.statement
1747
2446
  if statement is None:
1748
2447
  return
@@ -1750,6 +2449,7 @@ class IrParser:
1750
2449
  non_null = {column.lower() for column in symbol.not_null}
1751
2450
  # Each key's columns, its constraint, and whether it is a primary key.
1752
2451
  keys: list[tuple[tuple[str, ...], Expr, bool]] = []
2452
+ checks: list[exp.CheckColumnConstraint] = []
1753
2453
  for definition in statement.this.find_all(exp.ColumnDef):
1754
2454
  domain = _enum_type_values(definition, self.semantics)
1755
2455
  if domain is not None and definition.name.lower() in columns:
@@ -1762,9 +2462,14 @@ class IrParser:
1762
2462
  keys.append(((definition.name,), key, True))
1763
2463
  case exp.UniqueColumnConstraint() as key:
1764
2464
  keys.append(((definition.name,), key, False))
2465
+ case exp.CheckColumnConstraint() as check:
2466
+ checks.append(check)
1765
2467
  case _:
1766
2468
  pass # Other column constraints state nothing about keys or NULL.
1767
2469
  for constraint in _table_constraints(symbol):
2470
+ if isinstance(constraint, exp.CheckColumnConstraint):
2471
+ checks.append(constraint)
2472
+ continue
1768
2473
  constrained = _table_level_unique_columns(constraint)
1769
2474
  if constrained is not None:
1770
2475
  keys.append((constrained, constraint, isinstance(constraint, exp.PrimaryKey)))
@@ -1788,6 +2493,27 @@ class IrParser:
1788
2493
  trust = self._key_trust(exp.UniqueColumnConstraint(), symbol, names)
1789
2494
  if trust is not None:
1790
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)
1791
2517
 
1792
2518
  def _expression_key(
1793
2519
  self, relation: ir.NamedRelation, parts: list[Expr], index: exp.Create
@@ -1829,6 +2555,7 @@ class IrParser:
1829
2555
  Knowledge, so never proves anything by itself (ADR 0005)."""
1830
2556
  assert symbol.statement is not None
1831
2557
  foreign = isinstance(constraint, exp.ForeignKey | exp.Reference)
2558
+ check = isinstance(constraint, exp.CheckColumnConstraint)
1832
2559
  reference = constraint.args.get("reference") if isinstance(constraint, exp.ForeignKey) else constraint
1833
2560
  options = {str(option).upper() for option in (reference.args.get("options") or ())} if isinstance(reference, Expr) else set()
1834
2561
  meaning = self.semantics
@@ -1839,7 +2566,7 @@ class IrParser:
1839
2566
  reason = "ALTER TABLE ... NOT VALID added it, so rows already in the table were never checked"
1840
2567
  elif "DEFERRABLE" in options or "INITIALLY DEFERRED" in options:
1841
2568
  reason = "it is DEFERRABLE, so a transaction may see it violated"
1842
- elif (meaning.foreign_keys if foreign else meaning.unique_keys) != "enforced":
2569
+ elif (meaning.check_constraints if check else meaning.foreign_keys if foreign else meaning.unique_keys) != "enforced":
1843
2570
  reason = f"{self.dialect} does not enforce it"
1844
2571
  elif isinstance(constraint, exp.Reference) and not meaning.inline_references:
1845
2572
  reason = f"{self.dialect} before 9.0 ignores a column-level REFERENCES"
@@ -1852,21 +2579,21 @@ class IrParser:
1852
2579
  return "enforced"
1853
2580
  if ("RELY" in options and meaning.rely) or self.trust_unenforced_keys:
1854
2581
  return "declared"
1855
- kind = "foreign key" if foreign else "primary key" if isinstance(constraint, exp.PrimaryKey | exp.PrimaryKeyColumnConstraint) else "unique constraint"
1856
- fixes = ["mark it RELY"] if meaning.rely else []
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 []
1857
2584
  if foreign and meaning.foreign_key_engines is not None and _engine(symbol) is None:
1858
2585
  fixes.append("write ENGINE=InnoDB")
1859
2586
  fixes.append("analyze with trust_unenforced_keys=True")
1860
2587
  self._warnings.append(Diagnostic(
1861
2588
  diag.UNENFORCED_CONSTRAINT,
1862
- f"the {kind} ({', '.join(columns)}) of {symbol.name} is not Knowledge, since {reason}: "
2589
+ f"the {kind} ({quoted_all(columns)}) of {symbol.name} is not Knowledge, since {reason}: "
1863
2590
  f"if the data satisfies it, {' or '.join(fixes)}",
1864
2591
  self._origin(constraint, _source_line(constraint) or _source_line(symbol.statement)),
1865
2592
  ))
1866
2593
  return None
1867
2594
 
1868
2595
  def _origin(self, node: Expr, line: int | None = None) -> Origin:
1869
- return Origin(SQL, node.sql(dialect=self.dialect), line)
2596
+ return Origin(SQL, written_sql(node, self.dialect), line)
1870
2597
 
1871
2598
 
1872
2599
  def _pass_output_columns(inputs: tuple[ir.OutputColumn, ...], origin: Origin) -> tuple[ir.OutputColumn, ...]:
@@ -1907,15 +2634,14 @@ def dialect_builtins(meaning: DialectSemantics) -> dict[type[Expr], tuple[ir.Bui
1907
2634
 
1908
2635
  Comparisons, LIKE, NOT, BETWEEN and the bitwise operators are never NULL
1909
2636
  for non-null arguments where a failed implicit cast raises (`casts_raise`;
1910
- in Spark without ANSI mode `1 < 'x'` is NULL). Arithmetic and CAST only
2637
+ in Hive `1 < 'x'` is NULL). Arithmetic and CAST only
1911
2638
  where they raise an error rather than return NULL (`checked_arithmetic`:
1912
2639
  SQLite turns a NaN into NULL, MySQL a bad date CAST), and division and
1913
2640
  remainder only where division by zero raises too (`checked_division`).
1914
2641
  A CAST from JSON is not total anywhere (`convert._is_json`): JSON `null`
1915
2642
  is a value that casts to NULL. `+`, `-` and negation are injective where exact arithmetic overflows into
1916
- an error. `||`, `concat()` and `concat_ws()` as each dialect treats NULL;
1917
- `||` not at all where a setting decides what it means (MySQL: OR, or
1918
- concatenation)."""
2643
+ an error. `||`, `concat()`, `concat_ws()`, `greatest()`, `least()` and
2644
+ subscripts (`xs[1]`) as each dialect treats NULL (MySQL's `||` is OR)."""
1919
2645
  checked = meaning.checked_arithmetic
1920
2646
  casts = meaning.casts_raise
1921
2647
 
@@ -1938,13 +2664,26 @@ def dialect_builtins(meaning: DialectSemantics) -> dict[type[Expr], tuple[ir.Bui
1938
2664
  exp.Cast: (builtin("CAST", 1, total=checked), ("this",)),
1939
2665
  # `1 BETWEEN NULL AND 0` is FALSE.
1940
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")),
1941
2680
  }
1942
2681
  match meaning.pipes:
1943
2682
  case "strict":
1944
2683
  builtins[exp.DPipe] = (builtin("||", 2), ("this", "expression"))
1945
2684
  case "lenient":
1946
2685
  builtins[exp.DPipe] = (ir.Builtin(name="||", strict=(False, False), total=(True, True), injective=False), ("this", "expression"))
1947
- case "ambiguous" | None:
2686
+ case None:
1948
2687
  pass
1949
2688
  case _:
1950
2689
  assert_never(meaning.pipes)
@@ -1962,6 +2701,30 @@ def dialect_builtins(meaning: DialectSemantics) -> dict[type[Expr], tuple[ir.Bui
1962
2701
  pass
1963
2702
  case _:
1964
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"))
1965
2728
  match meaning.concat_ws:
1966
2729
  case "strict":
1967
2730
  builtins[exp.ConcatWs] = (
@@ -1989,7 +2752,7 @@ def _disjuncts(predicate: Expr) -> list[Expr]:
1989
2752
  """The operands of a predicate's top-level ORs, parentheses removed."""
1990
2753
  while isinstance(predicate, exp.Paren):
1991
2754
  predicate = predicate.this
1992
- if isinstance(predicate, exp.Or) and not is_ambiguous_pipes(predicate):
2755
+ if isinstance(predicate, exp.Or):
1993
2756
  return _disjuncts(predicate.this) + _disjuncts(predicate.expression)
1994
2757
  return [predicate]
1995
2758
 
@@ -2014,9 +2777,90 @@ def _conjuncts(predicate: Expr) -> list[Expr]:
2014
2777
  return [predicate]
2015
2778
 
2016
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
+
2017
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."""
2018
2796
  source = _from_source(select)
2019
- return ([] if source is None else [source]) + [join.this for join in select.args.get("joins") or ()]
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))]
2020
2864
 
2021
2865
 
2022
2866
  def _asserted_joins(ast: ParsedProgram) -> list[exp.Join]:
@@ -2027,11 +2871,11 @@ def _asserted_joins(ast: ParsedProgram) -> list[exp.Join]:
2027
2871
  ]
2028
2872
 
2029
2873
 
2030
- def _asserted_selects(ast: ParsedProgram) -> list[exp.Select]:
2874
+ def _asserted_selects(ast: ParsedProgram) -> list[exp.Query]:
2031
2875
  statements = (*ast.create_statements, ast.root_select)
2032
2876
  return [
2033
2877
  select for statement in statements if statement is not None
2034
- for select in statement.find_all(exp.Select) if column_markers(select)
2878
+ for select in statement.find_all(exp.Select, exp.SetOperation) if column_markers(select)
2035
2879
  ]
2036
2880
 
2037
2881
 
@@ -2070,7 +2914,10 @@ def _unwrap_constraints(constraints: Iterable[Expr]) -> list[Expr]:
2070
2914
 
2071
2915
 
2072
2916
  def _is_added_constraint(constraint: Expr) -> bool:
2073
- return isinstance(constraint, exp.PrimaryKey | exp.ForeignKey) or _table_level_unique_columns(constraint) is not None
2917
+ return (
2918
+ isinstance(constraint, exp.PrimaryKey | exp.ForeignKey | exp.CheckColumnConstraint)
2919
+ or _table_level_unique_columns(constraint) is not None
2920
+ )
2074
2921
 
2075
2922
 
2076
2923
  def _references(symbol: _Symbol) -> list[tuple[tuple[str, ...], exp.Table, tuple[str, ...] | None, Expr]]:
@@ -2134,6 +2981,19 @@ def _created_table(statement: exp.Create) -> exp.Table | None:
2134
2981
  return target if isinstance(target, exp.Table) else None
2135
2982
 
2136
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
+
2137
2997
  def _qualified_name(table: exp.Table) -> str:
2138
2998
  return ".".join(part for part in (table.catalog, table.db, table.name) if part)
2139
2999
 
@@ -2153,8 +3013,95 @@ def _from_source(select: exp.Query) -> Expr | None:
2153
3013
  return source.this if isinstance(source, exp.From) else None
2154
3014
 
2155
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
+
2156
3060
  # A scalar subquery's value binding: no SQL name can match it.
2157
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
2158
3105
 
2159
3106
 
2160
3107
  def _scalar_subqueries(expression: Expr) -> list[exp.Subquery]:
@@ -2196,7 +3143,7 @@ def _schema_path(node: exp.Table | exp.Column) -> str:
2196
3143
 
2197
3144
 
2198
3145
  def _star_only(select: exp.Select) -> bool:
2199
- return len(select.expressions) == 1 and isinstance(select.expressions[0], exp.Star)
3146
+ return len(select.expressions) == 1 and isinstance(select.expressions[0], exp.Star) and not any(select.expressions[0].args.values())
2200
3147
 
2201
3148
 
2202
3149
  def _selected_output_names(select: exp.Select) -> tuple[str, ...]:
@@ -2210,6 +3157,35 @@ def _matching_output(group_expression: Expr, items: list[Expr]) -> Expr | None:
2210
3157
  )
2211
3158
 
2212
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
+
2213
3189
  def _matching_grouping_output(group_expression: Expr, items: list[Expr]) -> Expr | None:
2214
3190
  if isinstance(group_expression, exp.Literal) and group_expression.is_int:
2215
3191
  position = int(group_expression.this)
@@ -2217,10 +3193,87 @@ def _matching_grouping_output(group_expression: Expr, items: list[Expr]) -> Expr
2217
3193
  return _matching_output(group_expression, items)
2218
3194
 
2219
3195
 
2220
- def _is_bare_aggregate_expression(expression: Expr) -> bool:
2221
- return any(isinstance(node, exp.Column) for node in expression.walk()) and not any(
2222
- isinstance(node, exp.AggFunc) for node in expression.walk()
2223
- )
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
2224
3277
 
2225
3278
 
2226
3279
  def _row_number_equals_one(predicate: Expr) -> exp.Window | None:
@@ -2273,16 +3326,61 @@ _JSON_TYPES = {exp.DataType.Type.JSON, exp.DataType.Type.JSONB, exp.DataType.Typ
2273
3326
  _COMPOSITE_TYPES = {exp.DataType.Type.ARRAY, exp.DataType.Type.LIST, exp.DataType.Type.STRUCT, exp.DataType.Type.MAP, exp.DataType.Type.NESTED}
2274
3327
 
2275
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)
2276
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))
2277
3347
 
2278
3348
  # Comparisons, whose operands a zoned timestamp's text may be.
2279
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)
2280
3350
 
2281
3351
  _EXACT_NUMERIC_TYPES = {*exp.DataType.INTEGER_TYPES, exp.DataType.Type.DECIMAL}
2282
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
+
2283
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
+
2284
3382
  _NOT_A_FUNCTION_OF_ITS_COLUMNS = (
2285
- exp.Anonymous, exp.Rand, exp.Randn, exp.Uuid, exp.AggFunc, exp.Window, exp.Query, exp.Subquery,
3383
+ exp.Anonymous, exp.Rand, exp.Randn, exp.Uuid, exp.AggFunc, exp.Filter, exp.WithinGroup, exp.Window, exp.Query, exp.Subquery,
2286
3384
  exp.CurrentDate, exp.CurrentDatetime, exp.CurrentTime, exp.CurrentTimestamp, exp.Placeholder, exp.Parameter, exp.Star,
2287
3385
  )
2288
3386
 
@@ -2302,6 +3400,36 @@ def _enum_type_values(definition: exp.ColumnDef, meaning: DialectSemantics) -> f
2302
3400
  return frozenset(members)
2303
3401
 
2304
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
+
2305
3433
  def _engine(symbol: _Symbol) -> str | None:
2306
3434
  """The storage ENGINE a CREATE TABLE names (lower-cased), if any."""
2307
3435
  assert symbol.statement is not None
@@ -2317,6 +3445,8 @@ def _aggregate_arguments(call: exp.AggFunc) -> list[Expr]:
2317
3445
  return []
2318
3446
  if isinstance(this, exp.Distinct):
2319
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)
2320
3450
  return [this, *call.expressions]
2321
3451
 
2322
3452
 
@@ -2354,12 +3484,14 @@ def _join_kind(join: exp.Join, dialect: str) -> ir.JoinKind | None:
2354
3484
  def _join_label(join: exp.Join, dialect: str) -> str:
2355
3485
  keywords = " ".join(part for part in (join.side, join.kind, "JOIN") if part)
2356
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]))})"
2357
3489
  if isinstance(source, exp.Subquery):
2358
3490
  return f"{keywords} subquery {source.alias}".rstrip()
2359
3491
  return f"{keywords} {source.sql(dialect=dialect)}"
2360
3492
 
2361
3493
 
2362
- def _select_label(select: exp.Select) -> str:
3494
+ def _select_label(select: exp.Query) -> str:
2363
3495
  node = select.parent
2364
3496
  while node is not None:
2365
3497
  match node: