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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. sqlassert/__init__.py +1 -2
  2. sqlassert/check.py +88 -13
  3. sqlassert/declared_types.py +158 -0
  4. sqlassert/diagnostics.py +15 -7
  5. sqlassert/dialects.py +259 -107
  6. sqlassert/discovery/bigquery.py +4 -2
  7. sqlassert/discovery/databricks.py +26 -5
  8. sqlassert/discovery/duckdb.py +49 -7
  9. sqlassert/discovery/fetcher.py +137 -58
  10. sqlassert/discovery/information_schema.py +31 -6
  11. sqlassert/discovery/mysql.py +21 -4
  12. sqlassert/discovery/postgres.py +28 -20
  13. sqlassert/discovery/redshift.py +3 -2
  14. sqlassert/discovery/snowflake.py +5 -2
  15. sqlassert/discovery/trino.py +2 -2
  16. sqlassert/functions/__init__.py +10 -0
  17. sqlassert/functions/load.py +375 -0
  18. sqlassert/functions/table.py +2721 -0
  19. sqlassert/hazards.py +249 -88
  20. sqlassert/ir/__init__.py +15 -4
  21. sqlassert/ir/convert/__init__.py +13 -0
  22. sqlassert/ir/convert/aggregation.py +438 -0
  23. sqlassert/ir/convert/expressions.py +581 -0
  24. sqlassert/ir/convert/joins.py +264 -0
  25. sqlassert/ir/convert/markers.py +249 -0
  26. sqlassert/ir/convert/parser.py +249 -0
  27. sqlassert/ir/convert/queries.py +259 -0
  28. sqlassert/ir/convert/schema.py +537 -0
  29. sqlassert/ir/convert/scopes.py +205 -0
  30. sqlassert/ir/convert/selects.py +352 -0
  31. sqlassert/ir/convert/shared.py +428 -0
  32. sqlassert/ir/convert/sources.py +433 -0
  33. sqlassert/ir/convert/subqueries.py +364 -0
  34. sqlassert/ir/convert/value_types.py +78 -0
  35. sqlassert/ir/convert/windows.py +275 -0
  36. sqlassert/ir/model.py +417 -146
  37. sqlassert/ir/names.py +63 -0
  38. sqlassert/main.py +7 -10
  39. sqlassert/properties.py +12 -1
  40. sqlassert/provenance.py +5 -1
  41. sqlassert/python_engine.py +104 -44
  42. sqlassert/reporting.py +33 -32
  43. sqlassert/rewrites.py +111 -61
  44. sqlassert/rules/STYLEGUIDE.md +3 -2
  45. sqlassert/rules/causes/__init__.py +41 -0
  46. sqlassert/rules/causes/coverage.py +113 -0
  47. sqlassert/rules/causes/domain.py +123 -0
  48. sqlassert/rules/causes/joins.py +73 -0
  49. sqlassert/rules/causes/nulls.py +154 -0
  50. sqlassert/rules/causes/unique.py +564 -0
  51. sqlassert/rules/domain.py +9 -8
  52. sqlassert/rules/equality.py +6 -147
  53. sqlassert/rules/exactly_one.py +2 -1
  54. sqlassert/rules/foreign_key.py +8 -9
  55. sqlassert/rules/join_cardinality.py +277 -43
  56. sqlassert/rules/nullability.py +8 -8
  57. sqlassert/rules/uniqueness.py +212 -87
  58. sqlassert/rules/value_typing.py +470 -0
  59. sqlassert/sql_parse.py +28 -1
  60. sqlassert/suggest.py +13 -17
  61. sqlassert-0.4.2.dist-info/METADATA +239 -0
  62. sqlassert-0.4.2.dist-info/RECORD +72 -0
  63. sqlassert/ir/convert.py +0 -3509
  64. sqlassert-0.3.3.dist-info/METADATA +0 -807
  65. sqlassert-0.3.3.dist-info/RECORD +0 -46
  66. {sqlassert-0.3.3.dist-info → sqlassert-0.4.2.dist-info}/WHEEL +0 -0
  67. {sqlassert-0.3.3.dist-info → sqlassert-0.4.2.dist-info}/entry_points.txt +0 -0
  68. {sqlassert-0.3.3.dist-info → sqlassert-0.4.2.dist-info}/licenses/LICENSE +0 -0
  69. {sqlassert-0.3.3.dist-info → sqlassert-0.4.2.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,433 @@
1
+ """FROM sources: named relations and their aliases, derived tables, recursive
2
+ references, VALUES lists, and table functions."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import re
7
+ from collections.abc import Iterable, Set
8
+ from dataclasses import replace
9
+ from typing import TYPE_CHECKING
10
+
11
+ from sqlglot import Expr, exp
12
+
13
+ from sqlassert import ir
14
+ from sqlassert.declared_types import declared_typing
15
+ from sqlassert.ir.names import repeated_names
16
+ from sqlassert.properties import EnumeratedDomain, NonNullColumn, UniqueSet
17
+ from sqlassert.provenance import Origin
18
+ from sqlassert.sql_parse import literal_value
19
+ from sqlassert.ir.convert.shared import (
20
+ _Symbol, _Binding, _Lowered, _nested_join, _aliased_join, _is_named_table, _column_aliases, _unlowered_query, _schema_path,
21
+ )
22
+
23
+ if TYPE_CHECKING:
24
+ from sqlassert.ir.convert.parser import IrParser
25
+
26
+
27
+ class _Sources:
28
+ def _lower_source(self: IrParser, source: Expr) -> _Lowered:
29
+ if any(source.args.get(key) for key in ("pivots", "sample", "version", "changes")):
30
+ relation = self._opaque_relation(source, self._source_required.get(id(source), set()))
31
+ self._unsupported.append((relation, _unsupported_modifier(source)))
32
+ return self._alias(relation, source.alias_or_name, self._placed(source))
33
+ if _is_named_table(source):
34
+ symbol = self._table_symbols[id(source)]
35
+ alias_name = source.alias or source.name
36
+ # An unaliased table may be named with its schema: `s1.t.k`.
37
+ schema = "" if source.alias else _schema_path(source)
38
+ if symbol in self._resolving:
39
+ if symbol.role is ir.RelationRole.VIEW:
40
+ self._report_cycle(symbol, source)
41
+ recursive = self._recursive_relation(symbol, source)
42
+ return self._alias(recursive, alias_name, self._placed(source), schema)
43
+ return self._alias(self._resolve_symbol(symbol), alias_name, self._placed(source), schema, _column_aliases(source))
44
+
45
+ nested = _nested_join(source) or _aliased_join(source)
46
+ if nested is not None:
47
+ first, joins = nested
48
+ lowered = self._lower_source(first)
49
+ for join in joins:
50
+ lowered = self._lower_join(lowered, join)
51
+ return lowered if source.alias == "" else self._alias_join(lowered, source)
52
+
53
+ if isinstance(source, exp.Subquery):
54
+ relation = self._lower_query(source)
55
+ if relation is not None:
56
+ # DuckDB allows an unaliased FROM subquery; nothing can qualify
57
+ # a column by its name, so a placeholder serves.
58
+ return self._alias(relation, source.alias or "subquery", self._placed(source), column_aliases=_column_aliases(source))
59
+
60
+ if isinstance(source, exp.Values):
61
+ values = self._lower_values(source)
62
+ if values is not None:
63
+ return self._alias(values, source.alias_or_name, self._placed(source))
64
+
65
+ columns = self._table_function_columns(source)
66
+ if columns is not None:
67
+ return self._lower_table_function(source, columns)
68
+ opaque = self._opaque_relation(source, self._source_required.get(id(source), set()))
69
+ self._unsupported.append((opaque, _unsupported_source(source) or _unlowered_source(source)))
70
+ return self._alias(opaque, source.alias_or_name or "opaque", self._placed(source))
71
+
72
+ def _table_function_columns(self: IrParser, source: Expr) -> tuple[str, ...] | None:
73
+ """The columns a table function or UNNEST in FROM returns, when the
74
+ dialect fixes them (`DialectSemantics.table_functions`); None for any
75
+ other source and for a call whose columns are not known."""
76
+ name = _table_function_name(source, self.dialect)
77
+ columns = None if name is None else dict(self.semantics.table_functions).get(name)
78
+ # An alias column list longer than the columns claimed says the call
79
+ # returns more (an UNNEST of a map, or of an array of rows).
80
+ return None if columns is None or len(_column_aliases(source)) > len(columns) else columns
81
+
82
+ def _lower_table_function(self: IrParser, source: Expr, columns: tuple[str, ...]) -> _Lowered:
83
+ """A table function or UNNEST in FROM with known columns: rows nothing
84
+ is known of (how many, or what they hold) under those columns, so
85
+ no key, dependency or type of theirs, and no fact of the input a join
86
+ repeats it onto, is lost. The alias's column list names the leading
87
+ columns; an alias alone names the one column of a function the dialect
88
+ says it names (`DialectSemantics.alias_named_table_functions`)."""
89
+ origin = self._placed(source)
90
+ name = _table_function_name(source, self.dialect)
91
+ assert name is not None
92
+ names = _column_aliases(source) or ((source.alias,) if name in self.semantics.alias_named_table_functions and source.alias else ())
93
+ relation = ir.OpaqueRelation(
94
+ origin=origin, is_schema_complete=True, description=source.sql(dialect=self.dialect),
95
+ output_columns=tuple(
96
+ ir.OutputColumn(origin=origin, name=column, scalar_expr=ir.OpaqueExpression(origin=origin, description=f"{name}() column {column}"))
97
+ for column in columns
98
+ ),
99
+ )
100
+ return self._alias(relation, source.alias_or_name or name, origin, column_aliases=names)
101
+
102
+ def _reads_left(self: IrParser, source: Expr, left: _Lowered) -> bool:
103
+ """Whether `source`, a table function or UNNEST, has an argument that
104
+ reads a column of `left`. Only a plain column counts: a subquery or
105
+ lambda in the call may name a column of its own, so it says nothing."""
106
+ if isinstance(source, exp.Unnest):
107
+ arguments = list(source.expressions)
108
+ elif isinstance(source, exp.Table) and isinstance(source.this, exp.Func):
109
+ arguments = [source.this]
110
+ else:
111
+ return False
112
+ if any(argument.find(exp.Lambda, exp.Query) is not None for argument in arguments):
113
+ return False
114
+ for argument in arguments:
115
+ for column in argument.find_all(exp.Column):
116
+ value = self._lower_expression(column, left.bindings, schema_complete=left.relation.is_schema_complete)
117
+ if isinstance(value, ir.ColumnRef) and value.column in left.relation.output_columns:
118
+ return True
119
+ return False
120
+
121
+ def _alias_join(self: IrParser, lowered: _Lowered, source: Expr) -> _Lowered:
122
+ """`(a JOIN b ...) AS x`: a relation of its own, which hides the names
123
+ of a and b and has each of their columns under its own name, in the
124
+ order of a star over the join (a USING column once). Like any derived
125
+ table it names the first of a repeated name only (`_aliased_outputs`);
126
+ every name is opaque when a source's columns are not all known."""
127
+ origin = self._origin(source)
128
+ join = lowered.relation
129
+ star = [binding.column for binding in lowered.bindings if not binding.shadowed]
130
+ relation = join
131
+ if not join.is_schema_complete:
132
+ outputs = tuple(
133
+ ir.OutputColumn(origin=origin, name=column.name, scalar_expr=ir.OpaqueExpression(origin=origin, description=f"{source.alias}.{column.name}"))
134
+ for column in join.output_columns
135
+ )
136
+ relation = ir.Project(origin=origin, output_columns=outputs, is_schema_complete=False, input=join)
137
+ elif len(star) != len(join.output_columns):
138
+ # A USING join: its columns are those a star selects.
139
+ outputs = tuple(ir.OutputColumn(origin=origin, name=column.name, scalar_expr=ir.ColumnRef(origin=origin, column=column)) for column in star)
140
+ relation = ir.Project(origin=origin, output_columns=outputs, is_schema_complete=True, input=join)
141
+ return self._alias(relation, source.alias, origin, column_aliases=_column_aliases(source))
142
+
143
+ def _lower_values(self: IrParser, values: exp.Values) -> ir.ValuesList | None:
144
+ """`(VALUES (...), ...) AS t (a, ...)`: rows of literals, stated as
145
+ Knowledge of its columns. A column is non-null when no row holds NULL
146
+ there; its Enumerated Domain is its values, up to `_VALUES_DOMAIN_ROWS`
147
+ rows (past that, a closed set is more noise than fact); it is a Unique
148
+ Set when no two of its values may compare equal (`1` and `1.0` may,
149
+ and `'a'` and `'A'` unless text compares by identity), and so are all
150
+ columns together when no two rows may. A column with any other
151
+ expression states nothing. A column of literals alone has the type
152
+ its literals give it (`_values_type`); one with an expression has
153
+ none. Without column names it stays opaque."""
154
+ from sqlassert.rules.domain import _may_coincide
155
+
156
+ alias = values.args.get("alias")
157
+ names = [column.name for column in alias.columns] if isinstance(alias, exp.TableAlias) else []
158
+ rows = [row.expressions if isinstance(row, exp.Tuple) else [row] for row in values.expressions]
159
+ if not names or not rows or any(len(row) != len(names) for row in rows):
160
+ return None
161
+ origin = self._origin(values)
162
+ literal_rows: list[list[ir.LiteralValue | None]] = [
163
+ [None if isinstance(item, exp.Null) else literal_value(item) for item in row] for row in rows
164
+ ]
165
+ literal_columns = [
166
+ all(isinstance(row[index], exp.Null) or literal_value(row[index]) is not None for row in rows) for index in range(len(names))
167
+ ]
168
+ columns = tuple(
169
+ self._values_column(
170
+ ir.OutputColumn(origin=origin, name=name, scalar_expr=ir.OpaqueExpression(origin=origin, description=f"VALUES column {name}")),
171
+ [row[index] for row in literal_rows] if literal_columns[index] else None,
172
+ )
173
+ for index, name in enumerate(names)
174
+ )
175
+ binary = self.semantics.text_is_binary
176
+
177
+ def distinct(items: list[ir.LiteralValue | None]) -> bool:
178
+ # NULL equals nothing, so it never repeats (a lax Unique Set).
179
+ known = [item for item in items if item is not None]
180
+ return all(not _may_coincide(first, second, binary) for index, first in enumerate(known) for second in known[index + 1:])
181
+
182
+ for index, column in enumerate(columns):
183
+ if not literal_columns[index]:
184
+ continue # Some value is an expression: nothing is stated.
185
+ written = [row[index] for row in rows]
186
+ items = [row[index] for row in literal_rows]
187
+ if not any(isinstance(item, exp.Null) for item in written):
188
+ self._knowledge.append(NonNullColumn(column=column))
189
+ present = frozenset(item for item in items if item is not None)
190
+ if present and len(rows) <= _VALUES_DOMAIN_ROWS:
191
+ self._knowledge.append(EnumeratedDomain(column=column, values=present))
192
+ if distinct(items):
193
+ self._knowledge.append(UniqueSet(columns=frozenset({column})))
194
+ if all(literal_columns) and len(columns) > 1 and all(
195
+ any(one is None or other is None or not _may_coincide(one, other, binary) for one, other in zip(first, second, strict=True))
196
+ for position, first in enumerate(literal_rows) for second in literal_rows[position + 1:]
197
+ ):
198
+ self._knowledge.append(UniqueSet(columns=frozenset(columns)))
199
+ return ir.ValuesList(origin=origin, output_columns=columns, is_schema_complete=True, description=values.sql(dialect=self.dialect))
200
+
201
+ def _values_column(self: IrParser, column: ir.OutputColumn, literals: list[ir.LiteralValue | None] | None) -> ir.OutputColumn:
202
+ """`column` of a VALUES list, typed as a column declared with the type
203
+ its literals give it (`literals`: None where a row is NULL, the whole
204
+ list None where some row is an expression), so equality binds it as it
205
+ binds a declared one: text by identity only where the dialect's text
206
+ does, an integer to any other integer."""
207
+ kind = None if literals is None else self._values_type(literals)
208
+ if kind is None:
209
+ return column
210
+ return replace(column, typing=declared_typing(kind, self.dialect))
211
+
212
+ def _values_type(self: IrParser, literals: list[ir.LiteralValue | None]) -> exp.DataType | None:
213
+ """The type a VALUES column of these literals (None for NULL) has in
214
+ the dialect (`DialectSemantics.values_types`), None when it is not
215
+ certain: no literal but NULL, literals of two kinds (the engine casts
216
+ one to the other, or raises), a boolean, an exponent, a number whose
217
+ type the engines spell apart (`0.5`, a whole part of 0, is DECIMAL(2, 1)
218
+ in DuckDB and MySQL, DECIMAL(1, 1) in Trino and Spark), or one beyond
219
+ BIGINT or 18 digits either side of the point (DOUBLE, DECIMAL or
220
+ HUGEINT, by engine)."""
221
+ types = dict(self.semantics.values_types)
222
+ present = [literal for literal in literals if literal is not None]
223
+ if not present:
224
+ return None
225
+ if all(literal.type == "string" for literal in present):
226
+ name = types.get("string")
227
+ elif all(literal.type == "numeric" and _VALUES_INTEGER.fullmatch(literal.text) for literal in present):
228
+ values = [int(literal.text) for literal in present]
229
+ if -(2**31) in values:
230
+ return None # INTEGER's least value is typed apart: DuckDB 2.0.1 negates 2147483648, a BIGINT.
231
+ if all(-(2**31) <= value < 2**31 for value in values):
232
+ name = types.get("integer")
233
+ elif all(-(2**63) <= value < 2**63 for value in values):
234
+ name = types.get("bigint")
235
+ else:
236
+ return None
237
+ elif all(literal.type == "numeric" and _VALUES_DECIMAL.fullmatch(literal.text) for literal in present):
238
+ # Each literal is DECIMAL(whole + scale, scale); a column holds the widest of both.
239
+ parts = [literal.text.removeprefix("-").split(".") for literal in present]
240
+ whole, scale = max(len(part[0]) for part in parts), max(len(part[1]) for part in parts)
241
+ name = f"{types['decimal']}({whole + scale}, {scale})" if "decimal" in types else None
242
+ else:
243
+ return None
244
+ return None if name is None else exp.DataType.build(name, dialect=self.dialect)
245
+
246
+ def _resolve_symbol(self: IrParser, symbol: _Symbol) -> ir.NamedRelation:
247
+ existing = self._named_relations.get(symbol)
248
+ if existing is not None:
249
+ return existing
250
+
251
+ if symbol.role is ir.RelationRole.TABLE:
252
+ output_columns, complete = self._table_output_columns(symbol)
253
+ named = ir.NamedRelation(
254
+ origin=symbol.origin, output_columns=output_columns, is_schema_complete=complete, name=symbol.name, role=symbol.role
255
+ )
256
+ self._named_relations[symbol] = named
257
+ self._table_knowledge(named, symbol)
258
+ return named
259
+
260
+ self._resolving.add(symbol)
261
+ try:
262
+ body = self._lower_query(symbol.body) if symbol.body is not None else None
263
+ finally:
264
+ self._resolving.discard(symbol)
265
+ self._recursion_bases.pop(symbol, None)
266
+ self._recursed.discard(symbol)
267
+ if body is None:
268
+ body = self._opaque_relation(symbol.body or exp.Table(this=symbol.name), symbol.required_columns)
269
+ written = symbol.body or (symbol.statement.args.get("expression") if symbol.statement is not None else None)
270
+ self._unsupported.append((body, _unlowered_query(written)))
271
+ output_columns = self._aliased_outputs(body, symbol.origin, symbol.column_aliases)
272
+ named = ir.NamedRelation(
273
+ origin=symbol.origin,
274
+ output_columns=output_columns,
275
+ is_schema_complete=body.is_schema_complete,
276
+ name=symbol.name,
277
+ role=symbol.role,
278
+ body=body,
279
+ )
280
+ self._named_relations[symbol] = named
281
+ return named
282
+
283
+ def _unresolved_named_relation(self: IrParser, symbol: _Symbol) -> ir.NamedRelation:
284
+ output_columns, complete = self._table_output_columns(symbol) if symbol.role is ir.RelationRole.TABLE else (self._opaque_output_columns(symbol.required_columns, symbol.origin), False)
285
+ named = ir.NamedRelation(
286
+ origin=symbol.origin, output_columns=output_columns, is_schema_complete=complete, name=symbol.name, role=symbol.role
287
+ )
288
+ self._named_relations[symbol] = named
289
+ if symbol.role is ir.RelationRole.TABLE:
290
+ self._table_knowledge(named, symbol)
291
+ return named
292
+
293
+ def _opaque_output_columns(self: IrParser, names: Iterable[str], origin: Origin) -> tuple[ir.OutputColumn, ...]:
294
+ if isinstance(names, Set):
295
+ names = sorted(names, key=lambda name: (name.lower(), name))
296
+ columns = tuple(
297
+ ir.OutputColumn(
298
+ origin=origin,
299
+ name=name,
300
+ scalar_expr=ir.OpaqueExpression(origin=origin, description=f"source column {name}"),
301
+ )
302
+ for name in names
303
+ )
304
+ self._guessed.update(columns)
305
+ return columns
306
+
307
+ def _recursive_relation(self: IrParser, symbol: _Symbol, source: Expr) -> ir.RecursiveRelation:
308
+ origin = self._origin(source)
309
+ output_columns = self._opaque_output_columns(symbol.required_columns, origin)
310
+ if symbol in self._recursion_bases:
311
+ self._recursed.add(symbol)
312
+ relation = ir.RecursiveRelation(
313
+ origin=origin,
314
+ output_columns=output_columns,
315
+ is_schema_complete=False,
316
+ description=source.sql(dialect=self.dialect),
317
+ relation_name=symbol.name,
318
+ typed_by=self._recursion_types(symbol, source, output_columns),
319
+ )
320
+ self._unsupported.append((relation, "a recursive CTE or view"))
321
+ return relation
322
+
323
+ def _recursion_types(
324
+ self: IrParser, symbol: _Symbol, source: Expr, output_columns: tuple[ir.OutputColumn, ...]
325
+ ) -> tuple[ir.OutputColumn | None, ...]:
326
+ """For each column a recursive reference reads, the base case's column
327
+ it is typed by: the engine fixes a recursive CTE's column types from the
328
+ base case (DuckDB casts the recursive arm to them; Postgres rejects a
329
+ mismatch). The CTE's names are its column aliases, else the base
330
+ case's names, matched by name; none where the base case is not known
331
+ (the reference sits in the base case) or its columns are not all known
332
+ (positions, and so aliases, are a guess), where the reference renames
333
+ the columns itself, or where a name is written twice."""
334
+ base = self._recursion_bases.get(symbol)
335
+ if base is None or not base.is_schema_complete or _column_aliases(source):
336
+ return (None,) * len(output_columns)
337
+ names = [
338
+ symbol.column_aliases[index].lower() if index < len(symbol.column_aliases) else column.name.lower()
339
+ for index, column in enumerate(base.output_columns)
340
+ ]
341
+ return tuple(
342
+ base.output_columns[names.index(column.name.lower())] if names.count(column.name.lower()) == 1 else None
343
+ for column in output_columns
344
+ )
345
+
346
+ def _aliased_outputs(self: IrParser, source: ir.RelationExpr, origin: Origin, names: tuple[str, ...]) -> tuple[ir.OutputColumn, ...]:
347
+ """The columns of a derived table over `source`, named by `names`
348
+ (a column alias list) and then `source`'s own names, as written: a
349
+ name may repeat (`_alias` binds only its first column)."""
350
+ if names and not source.is_schema_complete:
351
+ # Guessed source columns have no reliable positions.
352
+ return self._opaque_output_columns(names, origin)
353
+ written = [names[index] if index < len(names) else column.name for index, column in enumerate(source.output_columns)]
354
+ return tuple(
355
+ ir.OutputColumn(origin=origin, name=name, scalar_expr=ir.ColumnRef(origin=origin, column=column))
356
+ for name, column in zip(written, source.output_columns)
357
+ )
358
+
359
+ def _alias(self: IrParser, source: ir.RelationExpr, name: str, origin: Origin, schema: str = "", column_aliases: tuple[str, ...] = ()) -> _Lowered:
360
+ output_columns = self._aliased_outputs(source, origin, column_aliases)
361
+ alias = ir.Alias(origin=origin, output_columns=output_columns, is_schema_complete=source.is_schema_complete, source=source, name=name)
362
+ # A column alias list replaces names, not the repeat the source had (the engine's renames: `ir/names.py`).
363
+ repeated = repeated_names(column.name for column in source.output_columns) | repeated_names(column.name for column in output_columns)
364
+ # A repeated name binds its first column only; a repeat is reached by a star, never by a name.
365
+ first: set[str] = set()
366
+ bindings = []
367
+ for output in output_columns:
368
+ spelled = output.name.lower()
369
+ bindings.append(_Binding(name.lower(), None if spelled in first else spelled, output, schema, repeated=repeated))
370
+ first.add(spelled)
371
+ return _Lowered(alias, tuple(bindings))
372
+
373
+ def _opaque_relation(self: IrParser, source: Expr, names=()) -> ir.OpaqueRelation:
374
+ origin = self._origin(source)
375
+ return ir.OpaqueRelation(
376
+ origin=origin,
377
+ output_columns=self._opaque_output_columns(names, origin),
378
+ is_schema_complete=False,
379
+ description=source.sql(dialect=self.dialect),
380
+ )
381
+
382
+
383
+ def _table_function_name(source: Expr, dialect: str) -> str | None:
384
+ """The lower-case name a FROM source calls: a table function as the
385
+ dialect writes the call, `unnest` for an UNNEST of one argument without
386
+ ordinality. None for any other source, a qualified function (it may be the
387
+ user's own), and an UNNEST of several arguments or a call with ordinality
388
+ (its columns are not fixed)."""
389
+ if isinstance(source, exp.Unnest):
390
+ return "unnest" if len(source.expressions) == 1 and not source.args.get("offset") else None
391
+ if isinstance(source, exp.Table) and isinstance(source.this, exp.Func) and not (source.db or source.args.get("ordinality")):
392
+ call = re.match(r"\s*([A-Za-z_][A-Za-z0-9_]*)\s*\(", source.this.sql(dialect=dialect))
393
+ return call.group(1).lower() if call else None
394
+ return None
395
+
396
+
397
+ def _unsupported_modifier(source: Expr) -> str:
398
+ """The FROM modifier that changes `source`'s rows, which lowers it opaque."""
399
+ pivots = source.args.get("pivots")
400
+ if pivots:
401
+ return "UNPIVOT" if pivots[0].args.get("unpivot") else "PIVOT"
402
+ if source.args.get("sample"):
403
+ return "TABLESAMPLE"
404
+ if source.args.get("version"):
405
+ return "time travel (FOR SYSTEM_TIME or VERSION AS OF)"
406
+ return "CHANGES"
407
+
408
+
409
+ def _unlowered_source(source: Expr) -> str:
410
+ """Why a FROM source no other construct names lowers opaque."""
411
+ if isinstance(source, exp.Values):
412
+ return "a VALUES list without column names"
413
+ if isinstance(source, exp.Subquery):
414
+ return _unlowered_query(source)
415
+ return f"a {source.key.upper()} source in FROM"
416
+
417
+
418
+ def _unsupported_source(source: Expr) -> str | None:
419
+ """The FROM source construct that lowers opaque, if sqlassert does not support it yet."""
420
+ if isinstance(source, exp.Lateral) or source.find(exp.Lateral) is not None:
421
+ return "LATERAL"
422
+ if isinstance(source, exp.Unnest) or source.find(exp.Unnest) is not None:
423
+ return "UNNEST"
424
+ if isinstance(source, exp.Table) and isinstance(source.this, exp.Func):
425
+ return "a table function"
426
+ return None
427
+
428
+
429
+ # Rows of a VALUES list past which its columns get no Enumerated Domain.
430
+ _VALUES_DOMAIN_ROWS = 100
431
+ # The integers and decimals whose VALUES column type `_values_type` is certain of.
432
+ _VALUES_INTEGER = re.compile(r"-?[0-9]{1,19}")
433
+ _VALUES_DECIMAL = re.compile(r"-?[1-9][0-9]{0,17}\.[0-9]{1,18}")