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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. sqlassert/__init__.py +1 -2
  2. sqlassert/check.py +88 -13
  3. sqlassert/diagnostics.py +17 -6
  4. sqlassert/dialects.py +437 -7
  5. sqlassert/discovery/bigquery.py +3 -1
  6. sqlassert/discovery/databricks.py +25 -2
  7. sqlassert/discovery/duckdb.py +49 -7
  8. sqlassert/discovery/fetcher.py +130 -21
  9. sqlassert/discovery/information_schema.py +30 -2
  10. sqlassert/discovery/mysql.py +22 -1
  11. sqlassert/discovery/postgres.py +22 -5
  12. sqlassert/discovery/redshift.py +3 -2
  13. sqlassert/discovery/snowflake.py +3 -0
  14. sqlassert/discovery/trino.py +2 -2
  15. sqlassert/hazards.py +248 -87
  16. sqlassert/ir/__init__.py +4 -1
  17. sqlassert/ir/convert/__init__.py +13 -0
  18. sqlassert/ir/convert/aggregation.py +439 -0
  19. sqlassert/ir/convert/builtins.py +140 -0
  20. sqlassert/ir/convert/expressions.py +572 -0
  21. sqlassert/ir/convert/joins.py +264 -0
  22. sqlassert/ir/convert/markers.py +249 -0
  23. sqlassert/ir/convert/parser.py +253 -0
  24. sqlassert/ir/convert/queries.py +259 -0
  25. sqlassert/ir/convert/schema.py +606 -0
  26. sqlassert/ir/convert/scopes.py +205 -0
  27. sqlassert/ir/convert/selects.py +337 -0
  28. sqlassert/ir/convert/shared.py +429 -0
  29. sqlassert/ir/convert/sources.py +432 -0
  30. sqlassert/ir/convert/subqueries.py +364 -0
  31. sqlassert/ir/convert/value_types.py +223 -0
  32. sqlassert/ir/convert/windows.py +275 -0
  33. sqlassert/ir/model.py +125 -47
  34. sqlassert/ir/names.py +63 -0
  35. sqlassert/properties.py +12 -1
  36. sqlassert/provenance.py +5 -1
  37. sqlassert/python_engine.py +104 -44
  38. sqlassert/reporting.py +33 -32
  39. sqlassert/rewrites.py +111 -61
  40. sqlassert/rules/STYLEGUIDE.md +3 -2
  41. sqlassert/rules/causes/__init__.py +41 -0
  42. sqlassert/rules/causes/coverage.py +113 -0
  43. sqlassert/rules/causes/domain.py +123 -0
  44. sqlassert/rules/causes/joins.py +73 -0
  45. sqlassert/rules/causes/nulls.py +154 -0
  46. sqlassert/rules/causes/unique.py +523 -0
  47. sqlassert/rules/domain.py +8 -7
  48. sqlassert/rules/equality.py +6 -147
  49. sqlassert/rules/exactly_one.py +2 -1
  50. sqlassert/rules/foreign_key.py +8 -9
  51. sqlassert/rules/join_cardinality.py +282 -41
  52. sqlassert/rules/nullability.py +5 -5
  53. sqlassert/rules/uniqueness.py +171 -47
  54. sqlassert/rules/value_typing.py +337 -0
  55. sqlassert/sql_parse.py +28 -1
  56. sqlassert/suggest.py +11 -15
  57. sqlassert-0.4.1.dist-info/METADATA +235 -0
  58. sqlassert-0.4.1.dist-info/RECORD +69 -0
  59. sqlassert/ir/convert.py +0 -3509
  60. sqlassert-0.3.3.dist-info/METADATA +0 -807
  61. sqlassert-0.3.3.dist-info/RECORD +0 -46
  62. {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/WHEEL +0 -0
  63. {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/entry_points.txt +0 -0
  64. {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/licenses/LICENSE +0 -0
  65. {sqlassert-0.3.3.dist-info → sqlassert-0.4.1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,429 @@
1
+ """Symbols, bindings, and the syntax helpers more than one part of lowering reads."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterable
6
+ from dataclasses import dataclass, field, replace
7
+ from typing import Literal, TypeGuard
8
+
9
+ from sqlglot import Expr, exp
10
+
11
+ from sqlassert import ir
12
+ from sqlassert.ir.names import may_be_renamed
13
+ from sqlassert.provenance import Origin
14
+ from sqlassert.sql_parse import ColumnMarker, marker_position, written_at
15
+
16
+
17
+ @dataclass(eq=False)
18
+ class _Symbol:
19
+ name: str
20
+ role: ir.RelationRole
21
+ origin: Origin
22
+ body: exp.Query | None = None
23
+ statement: exp.Create | None = None
24
+ column_aliases: tuple[str, ...] = ()
25
+ required_columns: set[str] = field(default_factory=set)
26
+ # Table-level constraints added after CREATE TABLE (ALTER TABLE, CREATE
27
+ # UNIQUE INDEX), shaped like the CREATE TABLE's own, and columns set NOT NULL.
28
+ constraints: list[Expr] = field(default_factory=list)
29
+ not_null: set[str] = field(default_factory=set)
30
+ # Where the SQL first reads it: an undeclared table's warning points there.
31
+ first_line: int | None = None
32
+ # Each unique index with an expression key part: its parts and statement.
33
+ expression_keys: list[tuple[list[Expr], exp.Create]] = field(default_factory=list)
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class _Binding:
38
+ qualifier: str
39
+ # None for a repeat of a derived table's name: no reference reaches it, a star does.
40
+ name: str | None
41
+ column: ir.OutputColumn
42
+ # The schema (and catalog) of an unaliased table, as `s1` in `s1.t.k`.
43
+ schema: str = ""
44
+ # Hidden from unqualified names: a USING column's input sides, which an
45
+ # unqualified name reads merged (`_merge_using`).
46
+ shadowed: bool = False
47
+ # The lower-case names the derived table this column is of repeats
48
+ # (`ir/names.py`): a name `<repeated>_<digits>` may be one the engine gave
49
+ # a repeat, so no reference binds it.
50
+ repeated: frozenset[str] = frozenset()
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class _MarkerReference:
55
+ """A Foreign Key marker whose referencing columns are lowered, awaiting its referenced relation."""
56
+
57
+ marker: ColumnMarker
58
+ kind: Literal["foreign-key", "declared-foreign-key"]
59
+ origin: Origin
60
+ columns: tuple[ir.OutputColumn, ...]
61
+ target: _Symbol
62
+ position: int
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class _ConstraintReference:
67
+ """A `REFERENCES` constraint of a declared table onto a relation the program reaches."""
68
+
69
+ table: _Symbol
70
+ columns: tuple[str, ...]
71
+ target: _Symbol
72
+ target_columns: tuple[str, ...] | None
73
+ origin: Origin
74
+ # The `REFERENCES` or `FOREIGN KEY` constraint itself.
75
+ node: Expr
76
+
77
+
78
+ @dataclass(frozen=True)
79
+ class _Lowered:
80
+ relation: ir.RelationExpr
81
+ bindings: tuple[_Binding, ...]
82
+
83
+
84
+ def _placed(origin: Origin, node: Expr | None) -> Origin:
85
+ """`origin` with the span where `node` is written, when it has one."""
86
+ span = written_at(node) if node is not None else None
87
+ return origin if span is None else replace(origin, line=span.line, span=span)
88
+
89
+
90
+ def _pass_output_columns(inputs: tuple[ir.OutputColumn, ...], origin: Origin) -> tuple[ir.OutputColumn, ...]:
91
+ return tuple(
92
+ ir.OutputColumn(origin=origin, name=column.name, scalar_expr=ir.ColumnRef(origin=origin, column=column))
93
+ for column in inputs
94
+ )
95
+
96
+
97
+ def _source_line(node: Expr) -> int | None:
98
+ """The first source line of `node`, from the positions SQLGlot keeps on its tokens."""
99
+ lines = [descendant.meta["line"] for descendant in node.walk() if "line" in descendant.meta]
100
+ return min(lines, default=None)
101
+
102
+
103
+ def _subquery_conjunct(conjunct: Expr) -> tuple[ir.JoinKind, exp.Select, Expr | None] | None:
104
+ """A WHERE conjunct lowered as a filtering join: its kind, the subquery,
105
+ and the IN operand (None for EXISTS)."""
106
+ match conjunct:
107
+ case exp.Exists(this=exp.Select() as select):
108
+ return "semi", select, None
109
+ case exp.Not(this=exp.Exists(this=exp.Select() as select)):
110
+ return "anti", select, None
111
+ case exp.In(this=operand, args={"query": exp.Subquery() as subquery}) if not isinstance(operand, exp.Tuple):
112
+ body = _unwrap_query(subquery)
113
+ return ("semi", body, operand) if isinstance(body, exp.Select) else None
114
+ case _:
115
+ return None
116
+
117
+
118
+ def _and(parts: tuple[ir.ScalarExpr, ...], origin: Origin) -> ir.ScalarExpr | None:
119
+ """The AND of `parts`: None for none, the part itself for one."""
120
+ match parts:
121
+ case ():
122
+ return None
123
+ case (part,):
124
+ return part
125
+ case _:
126
+ return ir.And(origin=origin, parts=parts)
127
+
128
+
129
+ def _conjuncts(predicate: Expr) -> list[Expr]:
130
+ """The operands of a predicate's top-level ANDs, parentheses removed."""
131
+ while isinstance(predicate, exp.Paren):
132
+ predicate = predicate.this
133
+ if isinstance(predicate, exp.And):
134
+ return _conjuncts(predicate.this) + _conjuncts(predicate.expression)
135
+ return [predicate]
136
+
137
+
138
+ def _filter_conjuncts(predicate: Expr) -> list[Expr]:
139
+ """The conjuncts of a WHERE, ON or HAVING condition, each `p IS TRUE` as
140
+ `p`'s own: a filter keeps only the rows where its condition is TRUE, where
141
+ `p IS TRUE` is TRUE exactly when `p` is. Not in a value, where `p IS TRUE`
142
+ is FALSE, not NULL, on a NULL `p`."""
143
+ found: list[Expr] = []
144
+ for conjunct in _conjuncts(predicate):
145
+ if isinstance(conjunct, exp.Is) and isinstance(conjunct.expression, exp.Boolean) and conjunct.expression.this:
146
+ found.extend(_filter_conjuncts(conjunct.this))
147
+ else:
148
+ found.append(conjunct)
149
+ return found
150
+
151
+
152
+ def _direct_sources(select: exp.Select) -> list[Expr]:
153
+ """The sources of `select`'s FROM, those of a parenthesized join in place of it."""
154
+ source = _from_source(select)
155
+ return _flattened(([] if source is None else [source]) + [join.this for join in select.args.get("joins") or ()])
156
+
157
+
158
+ def _flattened(sources: list[Expr]) -> list[Expr]:
159
+ flat: list[Expr] = []
160
+ for source in sources:
161
+ nested = _nested_join(source)
162
+ flat.extend([source] if nested is None else _flattened([nested[0], *(join.this for join in nested[1])]))
163
+ return flat
164
+
165
+
166
+ def _all_joins(select: exp.Select) -> list[exp.Join]:
167
+ """The joins of `select`'s FROM, those inside a parenthesized join included."""
168
+ return [join for joins, _ in _join_levels(select) for join in joins]
169
+
170
+
171
+ def _join_levels(select: exp.Select) -> list[tuple[list[exp.Join], list[Expr]]]:
172
+ """The joins of `select`'s FROM and of each parenthesized join in it, each
173
+ list with the sources it joins, flattened: a USING column is one of theirs."""
174
+ source = _from_source(select)
175
+ levels: list[tuple[list[exp.Join], list[Expr]]] = [(list(select.args.get("joins") or ()), _direct_sources(select))]
176
+ pending: list[Expr | None] = [source, *(join.this for join in select.args.get("joins") or ())]
177
+ while pending:
178
+ source = pending.pop()
179
+ nested = _nested_join(source) or _aliased_join(source)
180
+ if nested is not None:
181
+ first, joins = nested
182
+ levels.append((joins, _flattened([first, *(join.this for join in joins)])))
183
+ pending.extend([first, *(join.this for join in joins)])
184
+ return levels
185
+
186
+
187
+ def _nested_join(source: Expr | None) -> tuple[Expr, list[exp.Join]] | None:
188
+ """A parenthesized join, `(a JOIN b ON ...)` without an alias: its first
189
+ source, which SQLGlot hangs the joins on, and those joins. Its columns keep
190
+ the names and qualifiers of its sources. Not with an alias, which DuckDB
191
+ reads as a subquery renaming repeated names (`x`, `x_1`) and other dialects
192
+ as names that may be ambiguous."""
193
+ if not isinstance(source, exp.Subquery) or any(value for key, value in source.args.items() if key not in {"this", "joins"}):
194
+ return None
195
+ first = source.this
196
+ if not isinstance(first, exp.Table | exp.Subquery) or not first.args.get("joins"):
197
+ return None
198
+ return first, list(first.args["joins"])
199
+
200
+
201
+ def _aliased_join(source: Expr | None) -> tuple[Expr, list[exp.Join]] | None:
202
+ """A parenthesized join with an alias, `(a JOIN b ON ...) AS x`, perhaps
203
+ naming its columns: its first source and its joins, as `_nested_join`."""
204
+ if not isinstance(source, exp.Subquery) or not source.alias or any(
205
+ value for key, value in source.args.items() if key not in {"this", "alias"}
206
+ ):
207
+ return None
208
+ first = source.this
209
+ if not isinstance(first, exp.Table | exp.Subquery) or not first.args.get("joins"):
210
+ return None
211
+ return first, list(first.args["joins"])
212
+
213
+
214
+ def _missing(relation: ir.RelationExpr, names: Iterable[str]) -> list[str]:
215
+ known = {column.name.lower() for column in relation.output_columns}
216
+ return [name for name in names if name.lower() not in known]
217
+
218
+ _TEXT_TYPES = {exp.DataType.Type.VARCHAR, exp.DataType.Type.TEXT}
219
+
220
+
221
+ def _is_named_table(source: Expr) -> TypeGuard[exp.Table]:
222
+ """A FROM source naming a table, view or CTE. SQLGlot parses a
223
+ table-valued function (`json_each(x)`, `read_parquet('f')`,
224
+ `generate_series(1, 3)`) as a Table whose `this` is the call: its rows
225
+ are opaque, like an UNNEST, and it names no relation."""
226
+ return isinstance(source, exp.Table) and isinstance(source.this, exp.Identifier)
227
+
228
+
229
+ def _column_aliases(source: Expr) -> tuple[str, ...]:
230
+ alias = source.args.get("alias")
231
+ return tuple(column.name for column in alias.columns) if isinstance(alias, exp.TableAlias) else ()
232
+
233
+
234
+ def _qualified_name(table: exp.Table) -> str:
235
+ return ".".join(part for part in (table.catalog, table.db, table.name) if part)
236
+
237
+
238
+ def _unwrap_query(body: Expr | None) -> exp.Query | None:
239
+ while isinstance(body, exp.Subquery):
240
+ body = body.this
241
+ return body if isinstance(body, exp.Query) else None
242
+
243
+
244
+ def _arg(node: Expr, name: str) -> Expr | None:
245
+ return node.args.get(f"{name}_") or node.args.get(name)
246
+
247
+
248
+ def _from_source(select: exp.Query) -> Expr | None:
249
+ source = _arg(select, "from")
250
+ return source.this if isinstance(source, exp.From) else None
251
+
252
+
253
+ def _unsupported_grouping(select: exp.Select) -> str | None:
254
+ """The grouping construct that makes `select` opaque, if any."""
255
+ group = select.args.get("group")
256
+ if group is None:
257
+ return None
258
+ if group.args.get("all") and any(_projection_star(item) is not None or item.find(exp.Subquery) for item in select.expressions):
259
+ return "GROUP BY ALL" # Its keys are the items, which a star or a subquery leaves unknown.
260
+ for key, name in (("grouping_sets", "GROUPING SETS"), ("rollup", "ROLLUP"), ("cube", "CUBE"), ("totals", "WITH TOTALS")):
261
+ if group.args.get(key):
262
+ return name
263
+ for node, name in ((exp.GroupingSets, "GROUPING SETS"), (exp.Rollup, "ROLLUP"), (exp.Cube, "CUBE")):
264
+ if any(isinstance(expression, node) for expression in group.expressions):
265
+ return name
266
+ return None
267
+
268
+
269
+ def _unlowered_query(body: Expr | None) -> str:
270
+ """What stands where a query body is expected but is not a SELECT or set
271
+ operation, which is not lowered."""
272
+ while isinstance(body, exp.Subquery):
273
+ body = body.this
274
+ if body is None:
275
+ return "a CTE or view body that is not a SELECT or set operation"
276
+ return "a VALUES list as a query body" if isinstance(body, exp.Values) else f"{body.key.upper()} as a query body"
277
+
278
+ # A USING column's merged binding (`_merge_using`): no qualifier can name it.
279
+ _USING_QUALIFIER = "\0using"
280
+
281
+ # A scalar subquery's value binding: no SQL name can match it.
282
+ _SCALAR_QUALIFIER = "\0scalar"
283
+
284
+ # Calls that return rows, not a value, in a select list: `unnest(arr)`,
285
+ # Spark's `explode(arr)`, Postgres's `generate_series(1, 3)`. Not DuckDB's
286
+ # `generate_series`, which there returns a list.
287
+ _SET_RETURNING = (exp.Explode, exp.Inline, exp.Stack, exp.ExplodingGenerateSeries, exp.Unnest)
288
+
289
+ # Set-returning functions SQLGlot parses as anonymous calls, by dialect.
290
+ _SET_RETURNING_NAMES: dict[str, frozenset[str]] = {
291
+ "postgres": frozenset({
292
+ "generate_subscripts", "json_array_elements", "json_array_elements_text", "json_each", "json_each_text",
293
+ "json_object_keys", "json_populate_recordset", "json_to_recordset", "jsonb_array_elements", "jsonb_array_elements_text",
294
+ "jsonb_each", "jsonb_each_text", "jsonb_object_keys", "jsonb_path_query", "jsonb_populate_recordset", "jsonb_to_recordset",
295
+ "regexp_matches", "regexp_split_to_table", "string_to_table",
296
+ }),
297
+ "spark": frozenset({"json_tuple", "inline_outer"}),
298
+ "databricks": frozenset({"json_tuple", "inline_outer"}),
299
+ "hive": frozenset({"json_tuple", "inline_outer"}),
300
+ }
301
+
302
+
303
+ def _set_returning_calls(item: Expr, dialect: str) -> list[Expr]:
304
+ """The outermost set-returning calls a select list item evaluates itself:
305
+ not one inside a subquery, which returns rows of its own."""
306
+ names = _SET_RETURNING_NAMES.get(dialect, frozenset())
307
+ calls: list[Expr] = []
308
+
309
+ def returns_rows(node: Expr) -> bool:
310
+ return isinstance(node, _SET_RETURNING) or (isinstance(node, exp.Anonymous) and node.name.lower() in names)
311
+
312
+ for node in item.walk(prune=lambda node: isinstance(node, exp.Query | exp.Subquery) or returns_rows(node)):
313
+ if returns_rows(node):
314
+ calls.append(node)
315
+ return calls
316
+
317
+
318
+ def _scalar_subqueries(expression: Expr) -> list[exp.Subquery]:
319
+ """The scalar subqueries `expression` evaluates itself: not one under
320
+ EXISTS, IN, ANY or ALL, nor inside another subquery."""
321
+ found = []
322
+ for node in expression.walk(prune=lambda node: isinstance(node, (exp.Subquery, exp.Query, exp.Exists))):
323
+ if isinstance(node, exp.Subquery) and not isinstance(node.parent, (exp.In, exp.Exists, exp.Any, exp.All)):
324
+ found.append(node)
325
+ return found
326
+
327
+
328
+ def _schema_path(node: exp.Table | exp.Column) -> str:
329
+ """The catalog and schema a table or column is written with, as `s1` or `c.s1`."""
330
+ return ".".join(part for part in (node.catalog, node.db) if part).lower()
331
+
332
+
333
+ def _projection_star(item: Expr) -> exp.Star | None:
334
+ star = item.this if isinstance(item, exp.Column) else item
335
+ return star if isinstance(star, exp.Star) else None
336
+
337
+
338
+ class _Carried:
339
+ """A star's column, in the meta of the item it expands to: SQLGlot's deep
340
+ copy keeps it as itself, so the item binds that column, not a name."""
341
+
342
+ def __init__(self, column: ir.OutputColumn):
343
+ self.column = column
344
+
345
+ def __deepcopy__(self, memo: object) -> _Carried:
346
+ return self
347
+
348
+
349
+ def _renamed(bindings: Iterable[_Binding], qualifier: str, schema: str, name: str) -> tuple[str, str] | None:
350
+ """The derived table's qualifier and the repeated name that `name` may
351
+ be a rename of, when a column written `schema.qualifier.name` (no
352
+ qualifier: of any source) is of the form `<repeated>_<digits>`, in a
353
+ derived table that repeats the name: which column it reads is then the
354
+ engine's (`ir/names.py`)."""
355
+ for binding in bindings:
356
+ if qualifier and (binding.qualifier != qualifier or (schema and binding.schema != schema)):
357
+ continue
358
+ base = next((base for base in sorted(binding.repeated) if may_be_renamed((base,), name)), None)
359
+ if base is not None:
360
+ return binding.qualifier, base
361
+ return None
362
+
363
+
364
+ def _star_only(select: exp.Select) -> bool:
365
+ return _only_star(select.expressions)
366
+
367
+
368
+ def _only_star(items: list[Expr]) -> bool:
369
+ """Whether `items` is a lone `*` with no modifier: all the input's columns, as they are."""
370
+ return len(items) == 1 and isinstance(items[0], exp.Star) and not any(items[0].args.values())
371
+
372
+
373
+ def _selected_output_names(select: exp.Select) -> tuple[str, ...]:
374
+ return tuple(item.alias_or_name for item in select.expressions if not isinstance(item, exp.Star))
375
+
376
+
377
+ def _matching_output(group_expression: Expr, items: list[Expr]) -> Expr | None:
378
+ return next(
379
+ (item for item in items if (item.this if isinstance(item, exp.Alias) else item) == group_expression),
380
+ None,
381
+ )
382
+
383
+
384
+ def _unaliased(item: Expr) -> Expr:
385
+ return item.this if isinstance(item, exp.Alias) else item
386
+
387
+
388
+ def _row_number_window(expression: Expr) -> exp.Window | None:
389
+ """`expression` when it is a `row_number()` window call, however it is partitioned."""
390
+ while isinstance(expression, exp.Paren):
391
+ expression = expression.this
392
+ return expression if isinstance(expression, exp.Window) and isinstance(expression.this, exp.RowNumber) else None
393
+
394
+
395
+ def _ended_set_operation(query: exp.Query, offset: int) -> exp.SetOperation | None:
396
+ """The outermost set operation that `query`, ending at `offset`, is the
397
+ last operand of (or the last operand of its last operand, ...) and that
398
+ ends there too. Parentheses cannot end there: they are only passed
399
+ through where INTERSECT, binding first, is regrouped in them."""
400
+ found, node = None, query
401
+ while isinstance(node.parent, exp.SetOperation | exp.Subquery):
402
+ node = node.parent
403
+ position = marker_position(node)
404
+ if isinstance(node, exp.SetOperation) and position is not None and position[0] == offset:
405
+ found = node
406
+ return found
407
+
408
+ _NOT_A_FUNCTION_OF_ITS_COLUMNS = (
409
+ exp.Anonymous, exp.Rand, exp.Randn, exp.Uuid, exp.AggFunc, exp.Filter, exp.WithinGroup, exp.Window, exp.Query, exp.Subquery,
410
+ exp.CurrentDate, exp.CurrentDatetime, exp.CurrentTime, exp.CurrentTimestamp, exp.Placeholder, exp.Parameter, exp.Star,
411
+ )
412
+
413
+
414
+ def _select_label(select: exp.Query) -> str:
415
+ node = select.parent
416
+ while node is not None:
417
+ match node:
418
+ case exp.CTE():
419
+ return f"CTE {node.alias}"
420
+ case exp.Create():
421
+ table = node.this.this if isinstance(node.this, exp.Schema) else node.this
422
+ return f"view {table.name}"
423
+ case exp.Subquery() if node.alias:
424
+ return f"subquery {node.alias}"
425
+ case exp.Subquery():
426
+ return "subquery"
427
+ case _:
428
+ node = node.parent
429
+ return "Root Select"