sqlalign 1.0.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.
@@ -0,0 +1,523 @@
1
+ """SELECT-statement layout: SELECT list, FROM, and orchestration of the clause
2
+ handlers (WHERE/HAVING via conditions, GROUP BY/ORDER BY/LIMIT via grouporder).
3
+
4
+ SELECT list geometry: the first item rides the `SELECT ` line; every later item
5
+ gets its own line with a leading comma two columns before the item column
6
+ (`anchor + len("SELECT ")`). Aliased items emit the expression and an `AS`-tagged
7
+ segment (`kind="as"`) so the resolver aligns the AS column across items. A
8
+ **scalar subquery** item (`(SELECT ...)`, optionally `AS alias`: Task 10)
9
+ expands to multiple lines instead: `SELECT (`/`, (` opens inline, the body
10
+ recurses at its own `SELECT` column via subquery.py, and the closing `)` --
11
+ plus `AS alias`, tagged into this SAME scope like any other item's alias --
12
+ lands on the body's last line.
13
+
14
+ `_guard` declines: via `Unsupported`, i.e. a byte-identical passthrough — every
15
+ construct this task does not yet render exactly (DISTINCT-on, embedded
16
+ comments, derived-table FROM). This keeps the formatter a safe identity
17
+ transform on everything outside its proven subset. Scalar subqueries in the
18
+ select list, derived-table JOINs, and `IN`/`EXISTS (SELECT ...)` in
19
+ WHERE/HAVING are the three shapes Task 10 adds; `_guard`'s tree walk exempts
20
+ (prunes) exactly those three attachment points: see `_subquery_roots` --
21
+ while still declining a `Subquery`/`Select` anywhere else (e.g. one nested
22
+ inside an arithmetic expression), and the inner query itself gets its OWN
23
+ independent `_guard` call when `layout_statement` recurses into it.
24
+
25
+ A select-list item whose value is exactly `exp.Case`/`exp.Window` (Task 11)
26
+ is a third exemption, see `_case_window_roots` -- but, unlike the
27
+ subquery exemption above, `_guard`'s walk does NOT prune into a Case/Window
28
+ root's children: case.py/window.py never re-`_guard` their own contents the
29
+ way a recursed subquery does, so the walk still descends and validates a
30
+ CASE's WHEN/THEN/ELSE or a window's PARTITION BY/ORDER BY/frame for
31
+ embedded comments or a nested, non-root Case/Window/Subquery: only the
32
+ exempted root node itself is spared the blanket `_UNSUPPORTED_NODES` check.
33
+ A CASE/window value buried inside some OTHER expression (e.g.
34
+ `COALESCE(SUM(CASE ...))`, sample 21) is never a "root" and stays declined,
35
+ exactly as before this task.
36
+ `with_` (a CTE-bearing statement) never reaches here: layout/__init__.py's
37
+ dispatch routes it to layout/cte.py first, which recurses back into this
38
+ module on a `with_`-stripped copy of the node.
39
+ """
40
+ from sqlglot import exp
41
+
42
+ from sqlalign.casing import active_style, render_expr
43
+ from sqlalign.commas import COMMA_KIND
44
+ from sqlalign.ir import Line, Seg, comment_seg
45
+ from sqlalign.layout import (
46
+ Unsupported,
47
+ attach_comments,
48
+ clause_head,
49
+ column_alias,
50
+ guard_args,
51
+ select_item_col,
52
+ table_alias,
53
+ table_name,
54
+ )
55
+ from sqlalign.layout.case import case_lines
56
+ from sqlalign.layout.conditions import condition_block
57
+ from sqlalign.layout.expr import nested_break_body, nested_break_case
58
+ from sqlalign.layout.fromjoin import from_join_lines
59
+ from sqlalign.layout.grouporder import group_lines, order_limit_lines
60
+ from sqlalign.layout.subquery import guard_subquery, subquery_body
61
+ from sqlalign.layout.window import named_window_lines, window_lines
62
+
63
+ # Clause args this task lays out. Any other truthy Select arg (with_, qualify,
64
+ # windows, laterals, distinct, ...) means "not yet handled" -> passthrough.
65
+ # DISTINCT is deliberately excluded: a later task implements it properly
66
+ # (multi-item DISTINCT currently misaligns). `joins` is allowed here but is
67
+ # itself further gated by fromjoin.py's own guard (derived-table joins,
68
+ # NATURAL/CROSS, join hints, ... stay Unsupported until later tasks).
69
+ _ALLOWED_ARGS = {
70
+ "expressions", "from_", "joins", "where", "group", "having", "order", "limit", "offset",
71
+ # `distinct` is `SELECT DISTINCT` / `SELECT DISTINCT ON (...)`; it rides the
72
+ # SELECT head, exactly like T-SQL's TOP.
73
+ "distinct",
74
+ # `QUALIFY <predicate>` filters on a window function, and is the same
75
+ # shape as HAVING, a keyword and a predicate, so it reuses the same
76
+ # block. Redshift and Snowflake have it; Postgres does not, but the
77
+ # author wrote it, so preserving it is not the same as introducing it.
78
+ "qualify",
79
+ # `WINDOW w AS (...)`: a named spec that `OVER w` refers to.
80
+ "windows",
81
+ # `FOR UPDATE [OF t] [SKIP LOCKED|NOWAIT]` and the SHARE variants: a
82
+ # trailing clause of its own, rendered whole by sqlglot's generator rather
83
+ # than re-derived here: the update/wait flags spell four keyword pairs and
84
+ # getting one backwards would change the locking behaviour silently.
85
+ "locks",
86
+ # `into` is `SELECT ... INTO target`: in a plpgsql body this assigns the row
87
+ # to a variable (spec §3.5); rendered inline after the last select item. Only a
88
+ # plain (non-temporary, non-unlogged) target is handled; anything else declines.
89
+ "into",
90
+ }
91
+
92
+ # Node kinds whose presence anywhere in the statement forces a passthrough.
93
+ #
94
+ # Case, Window, Subquery and Select are not here: `render_expr` renders a nested
95
+ # one inline, which is the only sane answer for it: the multi-line geometry
96
+ # belongs to a select item that owns its row, and a CASE buried in an argument
97
+ # list has none.
98
+ #
99
+ # - exp.Pivot: a table's `pivots` arg. Declined per dialect, detected by
100
+ # rendering the node rather than by a hardcoded list. See `_guard`.
101
+ _UNSUPPORTED_NODES: tuple = ()
102
+
103
+
104
+ def layout_select(select, dialect, width, anchor=0):
105
+ _guard(select, anchor, dialect, width)
106
+ # Scope strings are namespaced by id(select), not just anchor: a CTE body
107
+ # or a set-operation arm can call layout_select more than once at the same
108
+ # anchor within one render() (e.g. sample 10's three UNION ALL arms all
109
+ # sit at anchor 0), and align.py's resolver aligns everything sharing one
110
+ # (scope, kind) pair regardless of which call produced it. Anchor alone
111
+ # would wrongly merge, say, every arm's "AS" column into one; id(select)
112
+ # (unique for the lifetime of this still-referenced node) keeps each call
113
+ # its own alignment group. Anchor stays in the string purely for
114
+ # debug-readability: it plays no role in uniqueness.
115
+ tag = f"{anchor}:{id(select)}"
116
+ # T-SQL expresses a row limit as `SELECT TOP n`, not a trailing LIMIT clause,
117
+ # so it rides the SELECT head. Author's ruling: continuation commas keep their
118
+ # usual column 7: the comma column is a fixed house constant, not derived
119
+ # from where the first item happens to start.
120
+ head_extra = _distinct_text(select, dialect)
121
+ top_text = None
122
+ if dialect == "tsql":
123
+ # Only an `exp.Limit` becomes TOP. `OFFSET n ROWS FETCH NEXT m ROWS
124
+ # ONLY` also lands in the `limit` arg, as an `exp.Fetch` whose count is
125
+ # in `count` rather than `expression`; it is T-SQL's own paging syntax
126
+ # and goes through the shared FETCH path.
127
+ limit = select.args.get("limit")
128
+ if isinstance(limit, exp.Limit):
129
+ # `TOP n PERCENT` and `TOP n WITH TIES`. The modifiers live on a
130
+ # `limit_options` node beside the count, and dropping them yields a
131
+ # different query.
132
+ top_text = "TOP " + render_expr(limit.expression, dialect)
133
+ opts = limit.args.get("limit_options")
134
+ if opts is not None:
135
+ if opts.args.get("percent"):
136
+ top_text += " PERCENT"
137
+ if opts.args.get("with_ties"):
138
+ top_text += " WITH TIES"
139
+ if select.args.get("offset") is not None:
140
+ # `SELECT TOP n ... OFFSET m` is not valid T-SQL: paging is
141
+ # spelled OFFSET/FETCH, which is the branch above.
142
+ raise Unsupported("tsql: TOP with OFFSET")
143
+ # DISTINCT precedes TOP: `SELECT DISTINCT TOP 10 ...`.
144
+ head_extra = " ".join(p for p in (head_extra, top_text) if p) or None
145
+ lines = list(select_items(select, f"sel@{tag}", anchor, dialect, width, head_extra))
146
+
147
+ into = select.args.get("into")
148
+ if into is not None:
149
+ # `SELECT <items> INTO <target>`: the target rides on the last select-item
150
+ # line, before FROM (render()'s inter-seg space supplies the gap). _guard has
151
+ # already declined temporary/unlogged/non-table targets.
152
+ lines[-1].segs.append(Seg("INTO " + render_expr(into.this, dialect)))
153
+
154
+ frm = select.args.get("from_")
155
+ joins = select.args.get("joins")
156
+ if joins:
157
+ lines += from_join_lines(select, anchor, dialect, width)
158
+ elif frm is not None:
159
+ lines += _from_lines(frm, anchor, dialect, tag, width)
160
+
161
+ where = select.args.get("where")
162
+ if where is not None:
163
+ lines += condition_block("WHERE", where.this, f"where@{tag}", anchor, dialect, width)
164
+
165
+ lines += group_lines(select, anchor, dialect)
166
+
167
+ having = select.args.get("having")
168
+ if having is not None:
169
+ lines += condition_block("HAVING", having.this, f"having@{tag}", anchor, dialect, width)
170
+
171
+ windows = select.args.get("windows")
172
+ if windows:
173
+ lines += named_window_lines(windows, anchor, dialect)
174
+
175
+ qualify = select.args.get("qualify")
176
+ if qualify is not None:
177
+ lines += condition_block("QUALIFY", qualify.this, f"qualify@{tag}", anchor,
178
+ dialect, width)
179
+
180
+ lines += order_limit_lines(select, anchor, dialect, width)
181
+
182
+ # `FOR UPDATE …` closes the statement, after LIMIT/OFFSET. Each lock is
183
+ # rendered whole by sqlglot's own generator: the update/wait flags spell four
184
+ # different keyword pairs (FOR UPDATE / FOR SHARE / FOR NO KEY UPDATE /
185
+ # FOR KEY SHARE, each optionally SKIP LOCKED or NOWAIT), and getting one
186
+ # backwards would change the locking behaviour with nothing to catch it.
187
+ for lock in select.args.get("locks") or []:
188
+ kw_anchor, kw_text = clause_head("FOR", anchor)
189
+ text = render_expr(lock, dialect)
190
+ lines.append(Line(kw_anchor, [Seg(kw_text + text[len("FOR"):])]))
191
+ return lines
192
+
193
+
194
+ def select_items(select, scope, anchor, dialect, width, head_extra=None):
195
+ """One line per select item; leading commas two columns before the item
196
+ column. `head_seg` (`SELECT`/`, `, no trailing space) is a separate Seg
197
+ from the expression -- render()'s automatic one-space inter-seg separator
198
+ supplies the space between them, the same convention conditions.py and
199
+ fromjoin.py use, so a scalar-subquery item's merged `(` seg (see
200
+ subquery.py's `_open_inline`) composes without a hand-counted space.
201
+ """
202
+ keyword = "SELECT" if head_extra is None else f"SELECT {head_extra}"
203
+ style = active_style()
204
+ own_line = style.select_placement == "own_line"
205
+ item_col = select_item_col(anchor)
206
+ kw_anchor, kw_text = clause_head(keyword, anchor)
207
+ # The comma hangs two columns before the item column, wherever that is.
208
+ comma_lead = " " * (item_col - anchor - 2)
209
+
210
+ lines = []
211
+ if own_line:
212
+ lines.append(Line(kw_anchor, [Seg(kw_text)]))
213
+
214
+ for i, item in enumerate(select.expressions):
215
+ # Inline, the lead-in carries its own left padding and every row sits at
216
+ # `anchor`. On its own line the list has no lead-in to pad with, so the
217
+ # ROW carries the indent instead and a leading comma hangs two columns
218
+ # back: the same two columns it hangs back by inline.
219
+ if own_line:
220
+ head_seg = Seg("") if i == 0 else Seg(",", kind=COMMA_KIND)
221
+ row_anchor = item_col if i == 0 else item_col - 2
222
+ else:
223
+ head_seg = (Seg(kw_text) if i == 0
224
+ else Seg(comma_lead + ",", kind=COMMA_KIND))
225
+ row_anchor = kw_anchor if i == 0 else anchor
226
+ target = item.this if isinstance(item, exp.Alias) else item
227
+ if isinstance(target, exp.Subquery):
228
+ lines += _scalar_subquery_lines(item, target, head_seg, anchor, scope,
229
+ dialect, width, row_anchor)
230
+ continue
231
+ if isinstance(target, exp.Case):
232
+ lines += _multiline_item_lines(item, head_seg, scope,
233
+ case_lines(target, anchor, dialect, width),
234
+ row_anchor, dialect)
235
+ continue
236
+ if isinstance(target, exp.Window):
237
+ lines += _multiline_item_lines(item, head_seg, scope,
238
+ window_lines(target, anchor, dialect, width),
239
+ row_anchor, dialect)
240
+ continue
241
+ # An over-width item wrapping a breakable CASE (sample 21) breaks AT the
242
+ # CASE; expr.py returns the body Lines (or None if the item isn't that
243
+ # shape, in which case we fall through to the plain one-line path). The
244
+ # wrapped CASE is not a select-list ROOT, so `_guard` would decline it
245
+ # unless it is in `_nested_break_roots` below.
246
+ break_body = nested_break_body(item, anchor, dialect, width)
247
+ if break_body is not None:
248
+ lines += _multiline_item_lines(item, head_seg, scope, break_body, row_anchor,
249
+ dialect)
250
+ continue
251
+ target = item.this if isinstance(item, exp.Alias) else item
252
+ expr_text = render_expr(target, dialect)
253
+ # Comment engine annotations (comments.py): a LEADING comment is a plain
254
+ # Seg before the expression: part of the content the resolver measures
255
+ # for the `AS` column (so #12's widest, comment-bearing item sets it); a
256
+ # TRAILING comment is appended AFTER the alias, UNTAGGED: one space
257
+ # after the content, never in an alignment column (spec §3.3).
258
+ lead = item.meta.get("sqlalign_lead")
259
+ trail = item.meta.get("sqlalign_trail")
260
+ segs = [head_seg]
261
+ if lead is not None and ("\n" in lead or lead.startswith("--")):
262
+ # A line comment runs to end of line, so anything after it on that
263
+ # line is inside it: emitted inline the way a block comment is, it
264
+ # would swallow the item it annotates. It goes at the end of the
265
+ # previous row, which is both where the author wrote it and the only
266
+ # idempotent placement: on its own line it re-parses as trailing the
267
+ # row above.
268
+ if lines:
269
+ lines[-1].segs.append(comment_seg(lead))
270
+ else:
271
+ # Nothing precedes the first item, so the comment takes the row
272
+ # above SELECT: at the statement's own column, not the item
273
+ # column, which would leave it floating in mid-air.
274
+ lines.append(Line(anchor, [comment_seg(lead)]))
275
+ lead = None
276
+ if lead is not None:
277
+ segs.append(comment_seg(lead))
278
+ segs.append(Seg(expr_text))
279
+ if isinstance(item, exp.Alias):
280
+ segs.append(Seg("AS " + column_alias(item, dialect), scope=scope, kind="as"))
281
+ if trail is not None:
282
+ segs.append(comment_seg(trail))
283
+ lines.append(Line(row_anchor, segs))
284
+ return lines
285
+
286
+
287
+ def _multiline_item_lines(item, head_seg, scope, body, row_anchor, dialect):
288
+ """Splice a CASE/window item's own `body` (from `case_lines`/
289
+ `window_lines`, both `list[Line]` with line 0's `indent` already set to
290
+ this select's own `anchor` -- see either module's docstring) into a
291
+ select-list row: `head_seg` (the `SELECT`/leading-comma lead-in) fronts
292
+ line 0 exactly like a plain item's expression segment, and -- if
293
+ aliased -- `AS alias` lands on the body's LAST line, tagged into this
294
+ select's own `as` scope, exactly like a scalar-subquery item's alias
295
+ (`_scalar_subquery_lines`) or any plain item's.
296
+ """
297
+ body[0].segs.insert(0, head_seg)
298
+ body[0].indent = row_anchor
299
+ if isinstance(item, exp.Alias):
300
+ body[-1].segs.append(Seg("AS " + column_alias(item, dialect), scope=scope, kind="as"))
301
+ return body
302
+
303
+
304
+ def _scalar_subquery_lines(item, subquery, head_seg, anchor, scope, dialect, width,
305
+ row_anchor):
306
+ """A select-list item whose value is a scalar subquery (`item.this` when
307
+ `item` is `exp.Alias`, else `item` itself). `(` opens exactly at the item
308
+ column every other item's expression starts at (`anchor + len("SELECT ")`
309
+ -- `head_seg`'s own text is 6 chars either way, `"SELECT"` or the leading
310
+ comma, plus render()'s one automatic separator space = 7); the body
311
+ recurses there via subquery.py's `subquery_body`, which also glues the
312
+ closing `)` onto the last body line (spec: subqueries in a select list
313
+ close inline). If aliased, `AS alias` is tagged into THIS select's `as`
314
+ scope on that same last line, exactly like a non-subquery item's alias.
315
+ """
316
+ guard_subquery(subquery, allow_alias=False)
317
+ inner_anchor = select_item_col(anchor) + 1
318
+ open_segs, trailing = subquery_body(subquery.this, dialect, width, inner_anchor)
319
+ segs = [head_seg, *open_segs]
320
+ if isinstance(item, exp.Alias):
321
+ as_seg = Seg("AS " + column_alias(item, dialect), scope=scope, kind="as")
322
+ (trailing[-1].segs if trailing else segs).append(as_seg)
323
+ return [Line(row_anchor, segs), *trailing]
324
+
325
+
326
+ def _distinct_text(select, dialect):
327
+ """`"DISTINCT"` / `"DISTINCT ON (a, b)"` for `select`, or None.
328
+
329
+ It rides the SELECT head rather than getting a line of its own, which is
330
+ also where T-SQL's TOP goes. The continuation commas do NOT move to follow
331
+ it: the comma column is a fixed house constant, not derived from wherever
332
+ the first item happens to start (the ruling `TOP` already established).
333
+
334
+ SELECT DISTINCT ON (cust.id) cust.id
335
+ , cust.email
336
+ FROM customers cust
337
+ """
338
+ distinct = select.args.get("distinct")
339
+ if distinct is None:
340
+ return None
341
+ guard_args(distinct, {"on"}, "DISTINCT")
342
+ on = distinct.args.get("on")
343
+ if on is None:
344
+ return "DISTINCT"
345
+ if not isinstance(on, exp.Tuple):
346
+ raise Unsupported("DISTINCT ON: unexpected form")
347
+ return "DISTINCT ON (" + ", ".join(render_expr(e, dialect) for e in on.expressions) + ")"
348
+
349
+
350
+ def _from_lines(frm, anchor, dialect, tag, width=None):
351
+ # Every branch below routes through `attach_comments`, because a branch that
352
+ # forgets to does not decline: it DROPS the comment, which `ast_equal`
353
+ # cannot see. The derived-table branch did exactly that.
354
+ kw_anchor, _ = clause_head("FROM", anchor)
355
+ return attach_comments(_from_body(frm, anchor, dialect, tag, width),
356
+ frm.this, kw_anchor)
357
+
358
+
359
+ def _from_body(frm, anchor, dialect, tag, width):
360
+ if isinstance(frm.this, exp.Values):
361
+ # `FROM (VALUES (1, 2), (3, 4)) AS v(a, b)`: an inline lookup table.
362
+ # It stays on one line: the rows are a literal list, not a query with
363
+ # clauses, so there is no body to recurse and nothing to align against.
364
+ kw_anchor, kw_text = clause_head("FROM", anchor)
365
+ return [Line(kw_anchor, [Seg(kw_text), Seg(render_expr(frm.this, dialect))])]
366
+ if isinstance(frm.this, exp.Subquery): # FROM (SELECT ...) d
367
+ from sqlalign.layout.subquery import derived_from_lines
368
+ return derived_from_lines(frm, anchor, dialect, width)
369
+ table = frm.this # exp.Table (enforced by _guard)
370
+ kw_anchor, kw_text = clause_head("FROM", anchor)
371
+ segs = [Seg(kw_text), Seg(table_name(table, dialect), scope=f"from@{tag}", kind="table")]
372
+ alias = table_alias(table, dialect)
373
+ if alias is not None:
374
+ segs.append(Seg(alias, scope=f"from@{tag}", kind="alias"))
375
+ return [Line(kw_anchor, segs)]
376
+
377
+
378
+ def _guard(select, anchor, dialect, width):
379
+ for name, value in select.args.items():
380
+ if value in (None, [], False):
381
+ continue
382
+ if name not in _ALLOWED_ARGS:
383
+ raise Unsupported(f"select arg: {name}")
384
+
385
+ frm = select.args.get("from_")
386
+ # A derived table (`FROM (SELECT ...) d`) is laid out by subquery.py, the
387
+ # same shape a derived-table JOIN already had; anything else in the FROM
388
+ # position is still unmodelled.
389
+ if frm is not None and not isinstance(frm.this, (exp.Table, exp.Subquery, exp.Values)):
390
+ raise Unsupported("from: non-table")
391
+
392
+ into = select.args.get("into")
393
+ if into is not None:
394
+ # Only a bare-variable/table target is modeled. `INTO TEMPORARY`/`UNLOGGED`
395
+ # (a CREATE-TABLE-AS spelling with a different meaning) is declined so it is
396
+ # never silently mis-rendered as a plpgsql assignment.
397
+ if into.args.get("temporary") or into.args.get("unlogged"):
398
+ raise Unsupported("select into: temporary/unlogged")
399
+ if not isinstance(into.this, (exp.Table, exp.Column, exp.Identifier)):
400
+ raise Unsupported("select into: non-simple target")
401
+ # Only a single target is rendered; decline multi-target `INTO x, y`
402
+ # explicitly rather than silently dropping the extras (the safety net
403
+ # would passthrough anyway, but an explicit decline is the house rule).
404
+ if into.args.get("expressions"):
405
+ raise Unsupported("select into: multiple targets")
406
+
407
+ exempt = _subquery_roots(select)
408
+ case_window_exempt = _case_window_roots(select)
409
+ # A CASE wrapped inside an over-width select item (sample 21) is broken by
410
+ # expr.py; like the Case/Window roots it is exempted from the blanket
411
+ # `_UNSUPPORTED_NODES` rejection but NOT pruned: its WHEN/THEN contents are
412
+ # still validated below (expr.py, like case.py, does not re-`_guard` them).
413
+ nested_break_exempt = {
414
+ id(case_node)
415
+ for item in select.expressions
416
+ if (case_node := nested_break_case(item, anchor, dialect, width)) is not None
417
+ }
418
+
419
+ def prune(node):
420
+ # Stop descending at a recognized subquery attachment point: its
421
+ # inner Select/SetOperation gets its OWN independent `_guard` call
422
+ # when layout_statement recurses into it (select.py's
423
+ # _scalar_subquery_lines, fromjoin.py's derived_table_lines,
424
+ # conditions.py's _render_in_subquery/_render_exists), so re-walking
425
+ # it here would both be redundant and wrongly reject its own
426
+ # Select/Subquery node against _UNSUPPORTED_NODES below. Case/Window
427
+ # roots (`case_window_exempt`) are deliberately NOT pruned here --
428
+ # see the module docstring: their own contents still need the
429
+ # comment/nested-unsupported check below since case.py/window.py
430
+ # never independently re-`_guard` them.
431
+ return id(node) in exempt
432
+
433
+ for node in select.walk(prune=prune):
434
+ # Comment check FIRST: before the `node is select` skip — so a comment
435
+ # attached to the Select node itself (e.g. `SELECT /* c */ a`) is not
436
+ # silently dropped but forces a passthrough like any other embedded comment.
437
+ if node.comments:
438
+ raise Unsupported("embedded comment")
439
+ if node is select:
440
+ continue
441
+ if id(node) in exempt or id(node) in case_window_exempt or id(node) in nested_break_exempt:
442
+ continue
443
+ if isinstance(node, _UNSUPPORTED_NODES):
444
+ raise Unsupported(type(node).__name__)
445
+ if isinstance(node, exp.Pivot) and not render_expr(node, dialect).strip():
446
+ # PIVOT/UNPIVOT declined for years on the grounds that `exp.Pivot`
447
+ # carries fifteen args and the syntax diverges across dialects. True,
448
+ # and beside the point: nothing here has to REBUILD it. It hangs off
449
+ # a table's `pivots` arg, so `table_name` renders it with the table
450
+ # and sqlglot spells each dialect's own form.
451
+ #
452
+ # What does have to be checked is that the dialect HAS the form.
453
+ # sqlglot's postgres generator drops a pivot silently: PIVOT is not
454
+ # Postgres syntax, and `SELECT * FROM t PIVOT(...)` comes back as
455
+ # `SELECT * FROM t`, the entire clause gone, with only the re-parse
456
+ # guard between that and shipping. Detected by rendering rather than
457
+ # by a hardcoded dialect list, so this stops declining by itself if
458
+ # sqlglot ever grows the support.
459
+ raise Unsupported("PIVOT: this dialect has no such syntax")
460
+
461
+
462
+
463
+ def _subquery_roots(select):
464
+ """id()s of the `exp.Subquery`/`exp.Select` nodes that anchor one of
465
+ Task 10's three recognized subquery shapes: a scalar subquery in the
466
+ select list, a derived-table JOIN, or `IN`/`EXISTS (SELECT ...)` inside
467
+ WHERE/HAVING (searched with a plain `.walk()`, not just the top
468
+ conjunction level, so one nested inside a parenthesized group is found
469
+ too -- conditions.py's `_render_condition` handles that generically).
470
+ `_guard` prunes its own walk at exactly these ids; layout downstream
471
+ (this module, fromjoin.py, conditions.py) declines: via `Unsupported`
472
+ , anything within them this task does not model, so under-collecting
473
+ here is safe (falls back to the blanket Subquery/Select rejection
474
+ below); the risk is only in OVER-collecting a shape nothing downstream
475
+ actually knows how to render.
476
+ """
477
+ roots = set()
478
+ for item in select.expressions:
479
+ target = item.this if isinstance(item, exp.Alias) else item
480
+ if isinstance(target, exp.Subquery):
481
+ roots.add(id(target))
482
+ for join in select.args.get("joins") or []:
483
+ # A derived table, directly or wrapped in a LATERAL: both get
484
+ # subquery.py's derived-table geometry, so both are roots.
485
+ inner = join.this.this if isinstance(join.this, exp.Lateral) else join.this
486
+ if isinstance(inner, exp.Subquery):
487
+ roots.add(id(inner))
488
+ for clause_name in ("where", "having"):
489
+ clause = select.args.get(clause_name)
490
+ if clause is None:
491
+ continue
492
+ for node in clause.walk():
493
+ if isinstance(node, exp.In) and node.args.get("query") is not None:
494
+ roots.add(id(node.args["query"]))
495
+ elif isinstance(node, exp.Exists):
496
+ roots.add(id(node.this))
497
+ return roots
498
+
499
+
500
+ def _case_window_roots(select):
501
+ """id()s of the `exp.Case`/`exp.Window` nodes that are a select-list
502
+ item's own value (optionally under an `exp.Alias`), Task 11's third
503
+ exemption from the blanket `_UNSUPPORTED_NODES` check: see the module
504
+ docstring for why, unlike `_subquery_roots`, `_guard` does NOT prune
505
+ into these. A Case/Window buried inside some OTHER expression (e.g.
506
+ `COALESCE(SUM(CASE ...))`, sample 21) is not a "root" and is not
507
+ collected here, so it still hits the blanket rejection below,
508
+ unchanged from pre-Task-11 behavior.
509
+ """
510
+ roots = set()
511
+ for item in select.expressions:
512
+ target = item.this if isinstance(item, exp.Alias) else item
513
+ if isinstance(target, (exp.Case, exp.Window)):
514
+ roots.add(id(target))
515
+ # A named window in the `WINDOW w AS (...)` clause is a fourth root: it is
516
+ # not a select-list item at all, but it IS laid out (by
517
+ # `window.named_window_lines`) rather than being an unmodelled node hiding
518
+ # somewhere in an expression. `SUM(x) OVER w`, the REFERENCE to it -- is
519
+ # itself an exp.Window whose spec is the bare name, and is a select-list
520
+ # root already collected above.
521
+ for win in select.args.get("windows") or []:
522
+ roots.add(id(win))
523
+ return roots
@@ -0,0 +1,78 @@
1
+ """Set-operation (UNION / INTERSECT / EXCEPT) layout.
2
+
3
+ sqlglot parses `A op B op C` left-associatively into nested `SetOperation`
4
+ nodes: the outermost node's `this` is itself a `SetOperation` over the earlier
5
+ arms, and `expression` is the last arm. Recursing `layout_statement` over both
6
+ `this` and `expression` therefore naturally unrolls an N-way chain: each level
7
+ contributes one more (blank / OPERATOR / blank) separator between the arm it
8
+ adds and the ones already laid out, so a 3-way union comes out as
9
+ arm / blank / op / blank / arm / blank / op / blank / arm with no special-casing.
10
+
11
+ Each arm is formatted independently at the same `anchor` ; the operator line sits alone at `anchor`
12
+ between two blank lines.
13
+ """
14
+ from sqlglot import exp
15
+
16
+ from sqlalign.ir import Line, Seg
17
+ from sqlalign.layout import Unsupported
18
+
19
+ # op keyword per SetOperation subclass (verified empirically against pinned
20
+ # sqlglot v30.14). `distinct=True` is the default (no ALL) for all three;
21
+ # `distinct` is falsy only when the source said "... ALL".
22
+ _OP_KEYWORD = {exp.Union: "UNION", exp.Intersect: "INTERSECT", exp.Except: "EXCEPT"}
23
+
24
+ # SetOperation args this layer lays out. Any other truthy arg (by_name, side,
25
+ # kind, on, order, limit, offset, with_, ...) means "not yet handled" ->
26
+ # passthrough: a combining ORDER BY/LIMIT that applies to the whole set
27
+ # operation (rather than one arm), a BY NAME/CORRESPONDING match, or an
28
+ # ASOF-style ON are all outside this task's scope. `with_` is excluded here on
29
+ # purpose: it is intercepted earlier by layout/__init__.py's dispatch, so it
30
+ # would only appear here on a malformed/unexpected call.
31
+ _ALLOWED_ARGS = {"this", "expression", "distinct"}
32
+
33
+
34
+ def layout_setop(node: exp.SetOperation, dialect: str, width, anchor: int = 0) -> list[Line]:
35
+
36
+ _guard(node)
37
+ keyword = _op_text(node)
38
+
39
+ left = _arm_lines(node.this, dialect, width, anchor)
40
+ right = _arm_lines(node.expression, dialect, width, anchor)
41
+ return [*left, Line(anchor, []), Line(anchor, [Seg(keyword)]), Line(anchor, []), *right]
42
+
43
+
44
+ def _arm_lines(arm, dialect, width, anchor):
45
+ """One side of a set operation.
46
+
47
+ Usually a bare SELECT. It may also be PARENTHESISED, and there the parens
48
+ are load-bearing rather than decorative: in
49
+ `SELECT a FROM t1 UNION ALL (SELECT b FROM t2 ORDER BY 1)` they scope the
50
+ ORDER BY to the second arm, where without them it orders the whole union.
51
+ `layout_statement` has no case for `exp.Subquery`, so the parenthesised arm
52
+ is laid out here.
53
+ """
54
+ from sqlalign.layout import layout_statement
55
+ from sqlalign.layout.subquery import guard_subquery, subquery_body
56
+
57
+ if not isinstance(arm, exp.Subquery):
58
+ return layout_statement(arm, dialect, width, anchor)
59
+ guard_subquery(arm, allow_alias=False)
60
+ open_segs, trailing = subquery_body(arm.this, dialect, width, anchor + 1)
61
+ return [Line(anchor, open_segs), *trailing]
62
+
63
+
64
+ def _op_text(node: exp.SetOperation) -> str:
65
+ base = _OP_KEYWORD.get(type(node))
66
+ if base is None:
67
+ raise Unsupported(type(node).__name__)
68
+ return base if node.args.get("distinct") else f"{base} ALL"
69
+
70
+
71
+ def _guard(node: exp.SetOperation) -> None:
72
+ for name, value in node.args.items():
73
+ if value in (None, [], False):
74
+ continue
75
+ if name not in _ALLOWED_ARGS:
76
+ raise Unsupported(f"setop arg: {name}")
77
+ if node.comments:
78
+ raise Unsupported("embedded comment")