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.
- sqlalign/__init__.py +10 -0
- sqlalign/align.py +145 -0
- sqlalign/bodylint.py +125 -0
- sqlalign/casing.py +182 -0
- sqlalign/cli.py +360 -0
- sqlalign/commas.py +58 -0
- sqlalign/config.py +28 -0
- sqlalign/configfile.py +194 -0
- sqlalign/formatter.py +609 -0
- sqlalign/gui.py +721 -0
- sqlalign/ir.py +38 -0
- sqlalign/keywordcase.py +127 -0
- sqlalign/layout/__init__.py +312 -0
- sqlalign/layout/case.py +222 -0
- sqlalign/layout/comments.py +530 -0
- sqlalign/layout/conditions.py +344 -0
- sqlalign/layout/cte.py +81 -0
- sqlalign/layout/ddl.py +424 -0
- sqlalign/layout/dml.py +287 -0
- sqlalign/layout/expr.py +119 -0
- sqlalign/layout/fromjoin.py +310 -0
- sqlalign/layout/grouporder.py +135 -0
- sqlalign/layout/select.py +523 -0
- sqlalign/layout/setop.py +78 -0
- sqlalign/layout/subquery.py +245 -0
- sqlalign/layout/window.py +207 -0
- sqlalign/lint.py +173 -0
- sqlalign/plpgsql.py +437 -0
- sqlalign/splitter.py +241 -0
- sqlalign/sqlfluffconfig.py +88 -0
- sqlalign/style.py +215 -0
- sqlalign/templating.py +87 -0
- sqlalign-1.0.1.dist-info/METADATA +404 -0
- sqlalign-1.0.1.dist-info/RECORD +37 -0
- sqlalign-1.0.1.dist-info/WHEEL +4 -0
- sqlalign-1.0.1.dist-info/entry_points.txt +2 -0
- sqlalign-1.0.1.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
"""FROM/JOIN block geometry: a FROM table followed by one or more JOINs.
|
|
2
|
+
|
|
3
|
+
Three alignment columns are GLOBAL across the whole block: one shared scope id
|
|
4
|
+
(`f"fj@{id(select)}"`) spans every table-ref row and every ON/AND condition row:
|
|
5
|
+
|
|
6
|
+
1. `alias` table aliases align at (longest "FROM/JOIN + table" prefix) + 1.
|
|
7
|
+
2. `on` ON keywords align at (longest alias) + 1; continuation AND lines
|
|
8
|
+
are tagged the SAME kind="on" so the resolver right-aligns them
|
|
9
|
+
to end at the same column ON ends at (2 vs 3 chars).
|
|
10
|
+
3. `op` comparison operators in every ON condition (first condition AND
|
|
11
|
+
every continuation AND, across ALL joins) share one block-global
|
|
12
|
+
END column.
|
|
13
|
+
|
|
14
|
+
Composition note: these three columns chain: `on` sits after the (padded)
|
|
15
|
+
`alias`, and `op` sits after the (padded) `on`/`AND`. The resolver (align.py)
|
|
16
|
+
composes dependent same-line tags: it iterates its target computation to a
|
|
17
|
+
fixpoint, so scoring `on` accounts for the `alias` before it being padded
|
|
18
|
+
rightward, and scoring `op` accounts for the `on`/`AND` before it. This module
|
|
19
|
+
therefore emits each segment with its NATURAL text and does no column math of
|
|
20
|
+
its own: no manual padding, no space counting — per the house convention that
|
|
21
|
+
all alignment lives in align.py. The prefix segment is untagged (single-space
|
|
22
|
+
joined); the `alias` tag left-aligns it into the block's alias column, the `on`
|
|
23
|
+
tag right-aligns ON/AND to a common end column, and the `op` tag right-aligns
|
|
24
|
+
every comparison operator to the block-global operator column.
|
|
25
|
+
|
|
26
|
+
`JOIN ... USING (col)` has no comparison operator: emitted as a single
|
|
27
|
+
`Seg("USING (...)", scope, kind="on")` (no continuation, no `op` tag).
|
|
28
|
+
|
|
29
|
+
Derived-table joins (subquery as a table, `join.this` is `exp.Subquery`) are
|
|
30
|
+
laid out via subquery.py's `derived_table_lines` instead of this
|
|
31
|
+
module's shared-scope geometry above: excludes them from the
|
|
32
|
+
FROM-block's alias/`ON`/operator scopes entirely — their alias and `ON` sit on
|
|
33
|
+
the closing-paren line, in a scope namespaced by `id(join)`, never padded into
|
|
34
|
+
this block's columns. `from_join_lines` below therefore builds `alias`/`op`
|
|
35
|
+
scope membership only from the REGULAR (non-derived) rows, and splices each
|
|
36
|
+
derived-table join's independently-produced lines back in at its original
|
|
37
|
+
position. `LATERAL` derived tables (`join.this` is `exp.Lateral`, wrapping the
|
|
38
|
+
`Subquery`) are a distinct, un-modeled shape: `_guard_joins` declines them
|
|
39
|
+
the same as any other non-Table/non-Subquery `join.this`.
|
|
40
|
+
Single-table FROM (no joins) never reaches this module: select.py keeps
|
|
41
|
+
handling that case directly so samples 01/02/04 are untouched.
|
|
42
|
+
"""
|
|
43
|
+
from sqlglot import exp
|
|
44
|
+
|
|
45
|
+
from sqlalign.casing import active_style, render_expr
|
|
46
|
+
from sqlalign.commas import COMMA_KIND
|
|
47
|
+
from sqlalign.ir import Line, Seg
|
|
48
|
+
from sqlalign.layout import (
|
|
49
|
+
COMMA_ROW,
|
|
50
|
+
Unsupported,
|
|
51
|
+
attach_comments,
|
|
52
|
+
clause_head,
|
|
53
|
+
guard_args,
|
|
54
|
+
row_keyword,
|
|
55
|
+
table_alias,
|
|
56
|
+
table_name,
|
|
57
|
+
)
|
|
58
|
+
from sqlalign.layout.conditions import predicate_segs, split_conjunction
|
|
59
|
+
from sqlalign.layout.subquery import derived_from_lines, derived_table_lines
|
|
60
|
+
|
|
61
|
+
# Join args (verified empirically against pinned sqlglot v30.14, exp.Join.arg_types)
|
|
62
|
+
# this task's block geometry does not model: NATURAL/hash-join methods, join
|
|
63
|
+
# hints, ASOF match conditions, CROSS-JOIN-LATERAL directionality, multiple
|
|
64
|
+
# comma-joined tables in one clause (`expressions`), and table PIVOT/UNPIVOT.
|
|
65
|
+
# Any of these forces a passthrough rather than a guessed/wrong layout.
|
|
66
|
+
_EXOTIC_JOIN_ARGS = ("global_", "hint", "match_condition", "directed",
|
|
67
|
+
"expressions", "pivots")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def from_join_lines(select, anchor, dialect, width):
|
|
71
|
+
"""All FROM+JOIN rows for `select`: one line per table ref, plus one line
|
|
72
|
+
per continuation AND/OR condition. `select.args["from_"]` and `["joins"]`
|
|
73
|
+
are both guaranteed present and well-formed by the caller (select.py only
|
|
74
|
+
routes here when `joins` is non-empty; a bare single-table FROM stays with
|
|
75
|
+
select.py's own `_from_lines`).
|
|
76
|
+
|
|
77
|
+
The scope id is namespaced by id(select), not just anchor: a CTE body or a
|
|
78
|
+
set-operation arm can call this at the same anchor as a sibling within one
|
|
79
|
+
render() call (e.g. two CTE bodies both at anchor 2), and align.py groups
|
|
80
|
+
purely by (scope, kind): anchor alone would wrongly merge their columns.
|
|
81
|
+
|
|
82
|
+
Derived-table joins (`join.this` is `exp.Subquery`) are excluded from the
|
|
83
|
+
`regular` rows below -- and thus from this block's shared alias/ON/op
|
|
84
|
+
scope entirely, and laid out independently via
|
|
85
|
+
`derived_table_lines`; `lines` is reassembled in the original FROM/JOIN
|
|
86
|
+
order so a derived-table join interleaves correctly with regular ones.
|
|
87
|
+
"""
|
|
88
|
+
scope = f"fj@{id(select)}"
|
|
89
|
+
frm = select.args["from_"]
|
|
90
|
+
joins = select.args.get("joins") or []
|
|
91
|
+
_guard_joins(joins)
|
|
92
|
+
|
|
93
|
+
# A derived table in the FROM position is excluded from `regular` for the
|
|
94
|
+
# same reason a derived-table JOIN is: it is laid out on its own
|
|
95
|
+
# lines by subquery.py and takes no part in this block's shared alias/ON
|
|
96
|
+
# scope. Without this it fell through to `_ref_text` and came out flattened
|
|
97
|
+
# onto one line: the same statement laid out two different ways depending
|
|
98
|
+
# on whether it happened to have a JOIN.
|
|
99
|
+
from_derived = isinstance(frm.this, exp.Subquery)
|
|
100
|
+
# `FROM (VALUES ...) AS v(a, b)` beside a JOIN. `_ref_text` renders the
|
|
101
|
+
# Values node without its parens, which Postgres rejects, and `ast_equal`
|
|
102
|
+
# cannot see it, since sqlglot reads its own lenient output back happily.
|
|
103
|
+
from_values = isinstance(frm.this, exp.Values)
|
|
104
|
+
|
|
105
|
+
# (join_keyword_or_"FROM", table_node, join_node_or_None) per REGULAR row.
|
|
106
|
+
regular = [] if (from_derived or from_values) else [("FROM", frm.this, None)]
|
|
107
|
+
regular += [(row_keyword(j), j.this, j)
|
|
108
|
+
for j in joins if not _is_derived(j)]
|
|
109
|
+
|
|
110
|
+
prefixes = [(kw, _ref_text(table, dialect)) for kw, table, _ in regular]
|
|
111
|
+
aliases = [table_alias(table, dialect) for _, table, _ in regular]
|
|
112
|
+
|
|
113
|
+
# Regular rows' lines, keyed by their join's id() (None for the FROM row).
|
|
114
|
+
by_id = {}
|
|
115
|
+
for (_, _, join), prefix, alias in zip(regular, prefixes, aliases, strict=False):
|
|
116
|
+
# An unaliased table contributes NO alias segment rather than an empty
|
|
117
|
+
# one. It has nothing to place in the alias column, so it simply does not
|
|
118
|
+
# participate: the column is still resolved from the rows that do have an
|
|
119
|
+
# alias, and this row's ON lands wherever the right-aligned `on` column
|
|
120
|
+
# puts it. An empty Seg would align identically but leave a stray
|
|
121
|
+
# separator space behind it whenever alignment is off.
|
|
122
|
+
keyword, name = prefix
|
|
123
|
+
if keyword is COMMA_ROW:
|
|
124
|
+
# The legacy comma form. It hangs two columns before the table
|
|
125
|
+
# column, the way every other stacked list in the house style does,
|
|
126
|
+
# and carries COMMA_KIND so `comma_position` can move it.
|
|
127
|
+
row_anchor, keyword = _table_col(anchor) - 2, ","
|
|
128
|
+
else:
|
|
129
|
+
# A river right-aligns FROM into the gutter and puts every JOIN on
|
|
130
|
+
# the far side of it (Holywell's rule is about joins, not about long
|
|
131
|
+
# keywords: a bare `JOIN` beside a hanging `LEFT JOIN` would read
|
|
132
|
+
# as a different clause).
|
|
133
|
+
row_anchor, keyword = clause_head(keyword, anchor, hang=join is not None)
|
|
134
|
+
# The keyword and the table name are SEPARATE segments so the name can
|
|
135
|
+
# hold the `table_names` column. Untagged they render exactly as the
|
|
136
|
+
# single fused segment they replaced: one space between them.
|
|
137
|
+
head = Seg(keyword, kind=COMMA_KIND) if keyword == "," else Seg(keyword)
|
|
138
|
+
lead = [head, Seg(name, scope=scope, kind="table")]
|
|
139
|
+
if alias is not None:
|
|
140
|
+
lead.append(Seg(alias, scope=scope, kind="alias"))
|
|
141
|
+
if join is None:
|
|
142
|
+
by_id[None] = [Line(row_anchor, lead)]
|
|
143
|
+
continue
|
|
144
|
+
if join.args.get("on") is None and not join.args.get("using"):
|
|
145
|
+
# CROSS/NATURAL: the table reference IS the whole row.
|
|
146
|
+
by_id[id(join)] = [Line(row_anchor, lead)]
|
|
147
|
+
continue
|
|
148
|
+
using = join.args.get("using")
|
|
149
|
+
if using:
|
|
150
|
+
cols = ", ".join(render_expr(c, dialect) for c in using)
|
|
151
|
+
if active_style().on_placement == "own_line":
|
|
152
|
+
by_id[id(join)] = [Line(row_anchor, list(lead)),
|
|
153
|
+
Line(row_anchor + 2, [Seg(f"USING ({cols})")])]
|
|
154
|
+
else:
|
|
155
|
+
using_seg = Seg(f"USING ({cols})", scope=scope, kind="on")
|
|
156
|
+
by_id[id(join)] = [Line(row_anchor, [*lead, using_seg])]
|
|
157
|
+
continue
|
|
158
|
+
style = active_style()
|
|
159
|
+
bools_trail = style.boolean_operator_position == "trailing"
|
|
160
|
+
conditions, joiner = split_conjunction(join.args["on"])
|
|
161
|
+
if style.on_placement == "own_line":
|
|
162
|
+
# ON drops below the table reference. The block-global ON column is
|
|
163
|
+
# retired here by definition (nothing sits after each alias to align),
|
|
164
|
+
# so ON/AND are right-justified locally with plain arithmetic: the
|
|
165
|
+
# same treatment conditions.py gives WHERE/AND. Aliases and the
|
|
166
|
+
# operator column still align across the block.
|
|
167
|
+
by_id[id(join)] = _on_own_line_rows(
|
|
168
|
+
lead, conditions, joiner, scope, row_anchor, dialect, bools_trail,
|
|
169
|
+
_block_keyword_width(regular))
|
|
170
|
+
continue
|
|
171
|
+
rows = [Line(row_anchor, [*lead, Seg("ON", scope=scope, kind="on"),
|
|
172
|
+
*predicate_segs(conditions[0], scope, dialect)])]
|
|
173
|
+
# A continuation AND/OR row carries a base indent of anchor + 2 (the same
|
|
174
|
+
# 2-space continuation WHERE/HAVING use) rather than bare `anchor`. Its
|
|
175
|
+
# ON-column position still comes from the kind="on" tag, which the
|
|
176
|
+
# resolver right-aligns far past column 2, so aligned output is
|
|
177
|
+
# unchanged. The base indent matters when alignment is OFF
|
|
178
|
+
# (Style.align=False): without it the AND would emit at column 0 and read
|
|
179
|
+
# as a new top-level clause. Invariant: a line must be structurally
|
|
180
|
+
# correct at its natural position; alignment only refines it.
|
|
181
|
+
#
|
|
182
|
+
# With trailing booleans there is no AND at the row head to align, so the
|
|
183
|
+
# head becomes an EMPTY seg still tagged kind="on": the resolver
|
|
184
|
+
# right-aligns its (zero-width) end to the same ON column, which lands the
|
|
185
|
+
# continuation's condition in exactly the first condition's column. That
|
|
186
|
+
# keeps the FROM-block condition column intact under either setting --
|
|
187
|
+
# this row is why boolean position had to be settled before that column
|
|
188
|
+
# could be configured at all.
|
|
189
|
+
for cond in conditions[1:]:
|
|
190
|
+
if bools_trail:
|
|
191
|
+
rows[-1].segs[-1].text += " " + joiner
|
|
192
|
+
head = Seg("", scope=scope, kind="on")
|
|
193
|
+
else:
|
|
194
|
+
head = Seg(joiner, scope=scope, kind="on")
|
|
195
|
+
rows.append(Line(row_anchor + 2, [head, *predicate_segs(cond, scope, dialect)]))
|
|
196
|
+
by_id[id(join)] = rows
|
|
197
|
+
|
|
198
|
+
if from_derived:
|
|
199
|
+
lines = derived_from_lines(frm, anchor, dialect, width)
|
|
200
|
+
elif from_values:
|
|
201
|
+
kw_anchor, kw_text = clause_head("FROM", anchor)
|
|
202
|
+
lines = [Line(kw_anchor, [Seg(kw_text), Seg(render_expr(frm.this, dialect))])]
|
|
203
|
+
else:
|
|
204
|
+
lines = list(by_id[None])
|
|
205
|
+
if not from_derived and not from_values:
|
|
206
|
+
lines = attach_comments(lines, frm.this, anchor)
|
|
207
|
+
for j in joins:
|
|
208
|
+
rows = (derived_table_lines(j, anchor, dialect, width)
|
|
209
|
+
if _is_derived(j) else by_id[id(j)])
|
|
210
|
+
lines += attach_comments(rows, j.this, anchor, before=lines)
|
|
211
|
+
return lines
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _ref_text(table, dialect):
|
|
215
|
+
"""A table reference rendered without its alias.
|
|
216
|
+
|
|
217
|
+
`LATERAL f(x) AS e` is a table reference too: a set-returning function
|
|
218
|
+
that may reference columns from the rows to its left. It renders as one
|
|
219
|
+
piece with the `LATERAL` keyword attached, so the row reads the way every
|
|
220
|
+
other FROM row does and the alias still lands in the block's alias column.
|
|
221
|
+
"""
|
|
222
|
+
if isinstance(table, exp.Lateral):
|
|
223
|
+
bare = table.copy()
|
|
224
|
+
bare.set("alias", None)
|
|
225
|
+
return render_expr(bare, dialect)
|
|
226
|
+
return table_name(table, dialect)
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _is_derived(join):
|
|
230
|
+
"""True for a join whose table is a subquery — directly, or wrapped in a
|
|
231
|
+
LATERAL. Both get subquery.py's derived-table geometry rather than this
|
|
232
|
+
module's shared columns."""
|
|
233
|
+
inner = join.this.this if isinstance(join.this, exp.Lateral) else join.this
|
|
234
|
+
return isinstance(inner, exp.Subquery)
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _table_col(anchor):
|
|
238
|
+
"""The column the FROM row's table name starts at — where a comma row's
|
|
239
|
+
own table must line up."""
|
|
240
|
+
kw_anchor, kw_text = clause_head("FROM", anchor)
|
|
241
|
+
return kw_anchor + len(kw_text) + 1
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _block_keyword_width(regular):
|
|
245
|
+
"""Widest ON/AND/OR keyword anywhere in this FROM block, so every join's ON
|
|
246
|
+
lands in ONE column under `on_placement="own_line"` -- justifying per join
|
|
247
|
+
would put `ON` at a different column depending on whether that particular
|
|
248
|
+
join happens to have a continuation. Block-global columns are this module's
|
|
249
|
+
whole premise."""
|
|
250
|
+
widths = [len("ON")]
|
|
251
|
+
for _, _, join in regular:
|
|
252
|
+
if join is None or join.args.get("using") or join.args.get("on") is None:
|
|
253
|
+
continue
|
|
254
|
+
conds, joiner = split_conjunction(join.args["on"])
|
|
255
|
+
if len(conds) > 1:
|
|
256
|
+
widths.append(len(joiner))
|
|
257
|
+
return max(widths)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _on_own_line_rows(lead, conditions, joiner, scope, anchor, dialect, bools_trail, max_kw):
|
|
261
|
+
"""`Style.on_placement == "own_line"`: the table reference keeps its own row
|
|
262
|
+
and every ON/AND condition follows indented 2, keywords right-justified
|
|
263
|
+
against each other (`ON` ending where `AND` ends), which is exactly the
|
|
264
|
+
treatment conditions.py gives a WHERE and its ANDs."""
|
|
265
|
+
rows = [Line(anchor, list(lead))]
|
|
266
|
+
keywords = ["ON"] + [joiner] * (len(conditions) - 1)
|
|
267
|
+
# House drops the condition two columns in and right-justifies the keyword
|
|
268
|
+
# family. A river instead keeps ON at the join's own column and hangs each
|
|
269
|
+
# continuation under ON's OPERAND, which is the geometry Holywell prints.
|
|
270
|
+
river = active_style().clause_keyword_align == "river"
|
|
271
|
+
for i, (kw, cond) in enumerate(zip(keywords, conditions, strict=False)):
|
|
272
|
+
if bools_trail and i:
|
|
273
|
+
rows[-1].segs[-1].text += " " + kw
|
|
274
|
+
head = Seg(" " * max_kw)
|
|
275
|
+
else:
|
|
276
|
+
head = Seg(kw if river else kw.rjust(max_kw))
|
|
277
|
+
row_indent = anchor + (len("ON ") if river and i else 0) if river else anchor + 2
|
|
278
|
+
rows.append(Line(row_indent, [head, *predicate_segs(cond, scope, dialect)]))
|
|
279
|
+
return rows
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def _guard_joins(joins):
|
|
283
|
+
for j in joins:
|
|
284
|
+
for name in _EXOTIC_JOIN_ARGS:
|
|
285
|
+
if j.args.get(name):
|
|
286
|
+
raise Unsupported(f"join arg: {name}")
|
|
287
|
+
if isinstance(j.this, exp.Lateral):
|
|
288
|
+
# A LATERAL wrapping a set-returning function is a one-line table
|
|
289
|
+
# reference. One wrapping a SUBQUERY needs the derived-table layout,
|
|
290
|
+
# and its alias lives on the Lateral rather than on the subquery, so
|
|
291
|
+
# it is a distinct shape: declined until it is modelled.
|
|
292
|
+
guard_args(j.this, {"this", "alias"}, "LATERAL")
|
|
293
|
+
elif not isinstance(j.this, (exp.Table, exp.Subquery)):
|
|
294
|
+
raise Unsupported("join: non-table")
|
|
295
|
+
has_on = j.args.get("on") is not None
|
|
296
|
+
has_using = bool(j.args.get("using"))
|
|
297
|
+
if has_on and has_using: # both -> undefined here
|
|
298
|
+
raise Unsupported("join: both ON and USING")
|
|
299
|
+
# A join with no condition is only VALID SQL when it says so: `CROSS
|
|
300
|
+
# JOIN` or a `NATURAL` join. Everything else that parses this way is the
|
|
301
|
+
# legacy comma form (`FROM a, b`), which sqlglot also represents as a
|
|
302
|
+
# conditionless join, and rebuilding that as `JOIN b` would emit SQL
|
|
303
|
+
# Postgres rejects outright. The AST check cannot catch it (sqlglot
|
|
304
|
+
# re-parses its own lenient output), so this guard is the only thing
|
|
305
|
+
# standing between the two.
|
|
306
|
+
# A conditionless join is either CROSS/NATURAL (which say so) or the
|
|
307
|
+
# legacy comma form, which `_row_keyword` emits as a comma. Both are
|
|
308
|
+
# valid; neither needs declining.
|
|
309
|
+
|
|
310
|
+
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"""GROUP BY / ORDER BY / LIMIT / OFFSET geometry.
|
|
2
|
+
|
|
3
|
+
GROUP BY and ORDER BY share one comma-stacked shape: the first term rides the
|
|
4
|
+
keyword line, later terms hang under it with a leading comma two columns before
|
|
5
|
+
the term (the same relationship SELECT uses, but with the 9-wide "GROUP BY "/
|
|
6
|
+
"ORDER BY " keyword). A GROUP BY that is purely positional (`GROUP BY 1, 2`) or a
|
|
7
|
+
single term stays inline. LIMIT and OFFSET share one line (`LIMIT n OFFSET m`)
|
|
8
|
+
when both are present; each stays a single line on its own.
|
|
9
|
+
|
|
10
|
+
Split into `group_lines` and `order_limit_lines` (rather than one combined
|
|
11
|
+
function) so select.py can splice a HAVING block — via conditions.py's
|
|
12
|
+
`condition_block`: between GROUP BY and ORDER BY.
|
|
13
|
+
"""
|
|
14
|
+
from sqlglot import exp
|
|
15
|
+
|
|
16
|
+
from sqlalign.casing import render_expr
|
|
17
|
+
from sqlalign.ir import Line, Seg
|
|
18
|
+
from sqlalign.layout import Unsupported, clause_head, comma_clause, guard_args
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _clause_line(keyword, tail, anchor):
|
|
22
|
+
"""`(indent, segs)` for a one-line clause, honouring the river."""
|
|
23
|
+
kw_anchor, kw_text = clause_head(keyword, anchor)
|
|
24
|
+
return kw_anchor, [Seg(kw_text), Seg(tail)]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _fetch_tail(fetch, dialect):
|
|
28
|
+
"""Everything after `FETCH` in `FETCH FIRST n [PERCENT] ROWS {ONLY|WITH TIES}`.
|
|
29
|
+
|
|
30
|
+
Rebuilt from the parsed parts rather than passed through verbatim, so it
|
|
31
|
+
cases with the rest of the output. Every piece is a fixed keyword except the
|
|
32
|
+
count, so there is nothing here sqlalign could get wrong that the re-parse
|
|
33
|
+
check would not catch.
|
|
34
|
+
"""
|
|
35
|
+
opts = fetch.args.get("limit_options")
|
|
36
|
+
parts = [fetch.args.get("direction") or "FIRST"]
|
|
37
|
+
count = fetch.args.get("count")
|
|
38
|
+
if count is not None:
|
|
39
|
+
parts.append(render_expr(count, dialect))
|
|
40
|
+
if opts is not None and opts.args.get("percent"):
|
|
41
|
+
parts.append("PERCENT")
|
|
42
|
+
if opts is None or opts.args.get("rows"):
|
|
43
|
+
parts.append("ROWS")
|
|
44
|
+
parts.append("WITH TIES" if opts is not None and opts.args.get("with_ties") else "ONLY")
|
|
45
|
+
return " ".join(parts)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _comment_pairs(nodes):
|
|
49
|
+
"""`[(lead, trail)]` per node, from the comment engine's annotations.
|
|
50
|
+
|
|
51
|
+
These clauses are laid out from rendered TEXT rather than from nodes, so the
|
|
52
|
+
pairs have to be lifted off here and handed to `comma_clause`, which is
|
|
53
|
+
exactly why comments in GROUP BY / ORDER BY declined until now.
|
|
54
|
+
"""
|
|
55
|
+
return [(n.meta.get("sqlalign_lead"), n.meta.get("sqlalign_trail")) for n in nodes]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def group_lines(select, anchor, dialect):
|
|
59
|
+
"""GROUP BY lines for `select`, or [] if absent."""
|
|
60
|
+
group = select.args.get("group")
|
|
61
|
+
if group is None:
|
|
62
|
+
return []
|
|
63
|
+
guard_args(group, {"expressions", "grouping_sets", "cube", "rollup", "all"}, "GROUP BY")
|
|
64
|
+
# `GROUP BY ALL`: group by every non-aggregated select item, without
|
|
65
|
+
# naming them. A DuckDB/Snowflake/Databricks convenience that Redshift and
|
|
66
|
+
# Postgres do not have; it is one keyword and the whole clause.
|
|
67
|
+
if group.args.get("all"):
|
|
68
|
+
kw_anchor, kw_text = clause_head("GROUP BY", anchor)
|
|
69
|
+
return [Line(kw_anchor, [Seg(kw_text), Seg("ALL")])]
|
|
70
|
+
exprs = group.expressions
|
|
71
|
+
# GROUPING SETS / CUBE / ROLLUP are further terms of the same list, not
|
|
72
|
+
# separate clauses. sqlglot emits them after the plain expressions and in
|
|
73
|
+
# this order; reproducing that order matters because reordering the source
|
|
74
|
+
# would be a rewrite, even where it is semantically inert.
|
|
75
|
+
terms = list(exprs)
|
|
76
|
+
for key in ("grouping_sets", "cube", "rollup"):
|
|
77
|
+
terms += list(group.args.get(key) or [])
|
|
78
|
+
texts = [render_expr(t, dialect) for t in terms]
|
|
79
|
+
pairs = _comment_pairs(terms)
|
|
80
|
+
positional = bool(exprs) and all(isinstance(e, exp.Literal) and e.is_int for e in exprs)
|
|
81
|
+
if positional and len(texts) > 1:
|
|
82
|
+
# A positional GROUP BY keeps every term on one line, so a comment
|
|
83
|
+
# attached to a term has no row of its own to sit on. This engine
|
|
84
|
+
# reproduces a comment faithfully or declines; it never guesses.
|
|
85
|
+
# A SINGLE term is not this case: it is one term on one row, which
|
|
86
|
+
# `comma_clause` places a comment against exactly as ORDER BY does.
|
|
87
|
+
if any(c for pair in pairs for c in pair):
|
|
88
|
+
raise Unsupported("comment: positional GROUP BY is one line")
|
|
89
|
+
kw_anchor, kw_text = clause_head("GROUP BY", anchor)
|
|
90
|
+
return [Line(kw_anchor, [Seg(kw_text), Seg(", ".join(texts))])]
|
|
91
|
+
return comma_clause("GROUP BY", texts, anchor, pairs)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def order_limit_lines(select, anchor, dialect, width):
|
|
95
|
+
"""ORDER BY / LIMIT / OFFSET lines for `select`, in order."""
|
|
96
|
+
lines = []
|
|
97
|
+
order = select.args.get("order")
|
|
98
|
+
if order is not None:
|
|
99
|
+
texts = [render_expr(e, dialect) for e in order.expressions]
|
|
100
|
+
lines += comma_clause("ORDER BY", texts, anchor,
|
|
101
|
+
_comment_pairs(order.expressions))
|
|
102
|
+
# LIMIT and OFFSET share one line when both are present;
|
|
103
|
+
# LIMIT-only and OFFSET-only stay a single line each. The `limit` arg holds
|
|
104
|
+
# either an exp.Limit (`LIMIT n`) or an exp.Fetch (`FETCH FIRST n ROWS ONLY`,
|
|
105
|
+
# the ANSI spelling of the same thing).
|
|
106
|
+
limit = select.args.get("limit")
|
|
107
|
+
offset = select.args.get("offset")
|
|
108
|
+
segs = []
|
|
109
|
+
if isinstance(limit, exp.Fetch):
|
|
110
|
+
# A shop that writes FETCH writes it everywhere, so this is all-or-
|
|
111
|
+
# nothing rather than an edge case. It keeps its own line: OFFSET
|
|
112
|
+
# precedes it in the ANSI form (`OFFSET n ROWS FETCH NEXT m ROWS ONLY`)
|
|
113
|
+
# rather than following it the way it follows LIMIT.
|
|
114
|
+
if offset is not None:
|
|
115
|
+
lines.append(Line(*_clause_line("OFFSET", render_expr(offset.expression, dialect),
|
|
116
|
+
anchor)))
|
|
117
|
+
offset = None
|
|
118
|
+
lines.append(Line(*_clause_line("FETCH", _fetch_tail(limit, dialect), anchor)))
|
|
119
|
+
limit = None
|
|
120
|
+
if limit is not None and dialect != "tsql":
|
|
121
|
+
# T-SQL has no LIMIT: the row count is `SELECT TOP n`, emitted by
|
|
122
|
+
# select.py into the SELECT head instead. Emitting LIMIT here produced
|
|
123
|
+
# SQL that SQL Server rejects, and the AST safety net could not see it
|
|
124
|
+
# (sqlglot parses both spellings to the same Limit node): see
|
|
125
|
+
# docs/.../2026-08-11-tsql-findings.md.
|
|
126
|
+
segs += [Seg("LIMIT"), Seg(render_expr(limit.expression, dialect))]
|
|
127
|
+
if offset is not None:
|
|
128
|
+
segs += [Seg("OFFSET"), Seg(render_expr(offset.expression, dialect))]
|
|
129
|
+
if segs:
|
|
130
|
+
kw_anchor, kw_text = clause_head(segs[0].text, anchor)
|
|
131
|
+
segs[0] = Seg(kw_text)
|
|
132
|
+
lines.append(Line(kw_anchor, segs))
|
|
133
|
+
return lines
|
|
134
|
+
|
|
135
|
+
|