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,344 @@
|
|
|
1
|
+
"""WHERE / HAVING / ON / QUALIFY geometry.
|
|
2
|
+
|
|
3
|
+
A boolean predicate is flattened at its top level into one condition per line.
|
|
4
|
+
The clause keyword and the AND/OR joiners form a right-aligned family (all end at
|
|
5
|
+
the same column); the operator of each condition is tagged `kind="op"` so the
|
|
6
|
+
resolver right-aligns operators too. Parenthesized groups recurse under a child
|
|
7
|
+
scope so their operator column is independent of the parent's.
|
|
8
|
+
|
|
9
|
+
Column model (all columns absolute, 0-based):
|
|
10
|
+
key_col the block keyword starts here (== Line.indent for every row)
|
|
11
|
+
body_col = key_col + max_kw + 1, where max_kw is the widest keyword in the
|
|
12
|
+
family (clause keyword and joiners). Each condition body begins here,
|
|
13
|
+
so the keyword occupies [key_col, body_col-2] and one space follows.
|
|
14
|
+
A group hangs its first condition directly off "(" (that condition begins at the
|
|
15
|
+
group's key_col, hugging the paren) while later conditions get the joiner + body.
|
|
16
|
+
|
|
17
|
+
`IN (SELECT ...)` and `EXISTS (SELECT ...)` are two more shapes
|
|
18
|
+
`_render_condition` special-cases before falling through to `predicate_segs`:
|
|
19
|
+
like a group, both recurse a nested body off `body_col`/`key_col` and can
|
|
20
|
+
produce `trailing_lines` — but via subquery.py's `layout_statement` recursion
|
|
21
|
+
(the subquery's own `SELECT`/FROM/WHERE), not another flattened conjunction —
|
|
22
|
+
and both close inline, unlike a group's own `)`. Unlike every
|
|
23
|
+
other operator in this module, `IN`'s keyword in this shape is deliberately
|
|
24
|
+
UNTAGGED (no scope/kind): excluded from the operator right-alignment family
|
|
25
|
+
— matching `EXISTS`, which was always untagged. See `_render_in_subquery`'s
|
|
26
|
+
docstring and subquery.py's module docstring for why: the recursed body's
|
|
27
|
+
line indents are baked in from `IN`'s NATURAL column, so a resolver-padded
|
|
28
|
+
`IN` would silently detach the body from its own `(`. Plain `IN (list)`
|
|
29
|
+
(`predicate_segs`, below) is a different code path and still right-aligns.
|
|
30
|
+
"""
|
|
31
|
+
from sqlglot import exp
|
|
32
|
+
|
|
33
|
+
from sqlalign.casing import active_style, render_expr
|
|
34
|
+
from sqlalign.ir import Line, Seg, comment_seg, split_trailing_comments
|
|
35
|
+
from sqlalign.layout import Unsupported
|
|
36
|
+
|
|
37
|
+
# Binary comparison / pattern operators whose left and right operands both render
|
|
38
|
+
# cleanly via render_expr; the value here is the operator token laid out as the
|
|
39
|
+
# right-aligned `op` segment.
|
|
40
|
+
# NEQ canonicalizes to "!=" (the house form): sqlglot erases the "!=" vs "<>"
|
|
41
|
+
# source spelling at parse (both -> exp.NEQ), so "kept as written" is impossible
|
|
42
|
+
# through the AST; "!=" is what every in-house sample uses. Zero semantic
|
|
43
|
+
# difference, so this stays ast_equal-safe.
|
|
44
|
+
_CMP_OP = {
|
|
45
|
+
exp.EQ: "=", exp.NEQ: "!=", exp.GT: ">", exp.GTE: ">=",
|
|
46
|
+
exp.LT: "<", exp.LTE: "<=", exp.Like: "LIKE", exp.ILike: "ILIKE",
|
|
47
|
+
# The null-safe pair. They are comparison operators like any other: the
|
|
48
|
+
# only reason they declined is that they were missing from this table, and
|
|
49
|
+
# `IS DISTINCT FROM` is the standard way to compare nullable columns.
|
|
50
|
+
exp.NullSafeNEQ: "IS DISTINCT FROM", exp.NullSafeEQ: "IS NOT DISTINCT FROM",
|
|
51
|
+
# Pattern matching beyond LIKE. `!~` / `!~*` are `Not` wrapping these two,
|
|
52
|
+
# handled below: sqlglot prints those as `NOT b ~ 'x'`, but the author
|
|
53
|
+
# wrote an operator and it belongs in the operator column.
|
|
54
|
+
exp.SimilarTo: "SIMILAR TO", exp.RegexpLike: "~", exp.RegexpILike: "~*",
|
|
55
|
+
}
|
|
56
|
+
_NEGATED_OP = {exp.RegexpLike: "!~", exp.RegexpILike: "!~*"}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def condition_block(keyword, node, scope, anchor, dialect, width):
|
|
60
|
+
"""Lay out the predicate `node` introduced by `keyword` at column `anchor`."""
|
|
61
|
+
conditions, joiner = split_conjunction(node)
|
|
62
|
+
keywords = [keyword] + ([joiner] * (len(conditions) - 1) if joiner else [])
|
|
63
|
+
max_kw = max(len(k) for k in keywords)
|
|
64
|
+
style = active_style()
|
|
65
|
+
# In a river the whole keyword family right-aligns to the gutter rather than
|
|
66
|
+
# to its own widest member, so WHERE/AND land in the same column FROM and
|
|
67
|
+
# SELECT do. A JOIN's ON is not a root clause and keeps its local geometry.
|
|
68
|
+
if style.clause_keyword_align == "river" and keyword in ("WHERE", "HAVING"):
|
|
69
|
+
max_kw = max(max_kw, style.river_gutter)
|
|
70
|
+
# `body_col` is identical under either boolean position: only the AND/OR
|
|
71
|
+
# moves; see `joiner_head`.
|
|
72
|
+
body_col = anchor + max_kw + 1
|
|
73
|
+
group_counter = [0]
|
|
74
|
+
lines = []
|
|
75
|
+
for i, (kw, cond) in enumerate(zip(keywords, conditions, strict=False)):
|
|
76
|
+
segs, extra = _render_condition(cond, scope, body_col, group_counter, dialect, width)
|
|
77
|
+
# Comments the engine attached to this condition (comments.py). Same
|
|
78
|
+
# placement rule the select list uses, and for the same reason: a `--`
|
|
79
|
+
# or multi-line comment cannot share a row with content that follows it,
|
|
80
|
+
# so it takes the END of the row above, which is also where the author
|
|
81
|
+
# wrote it, and the only idempotent spelling.
|
|
82
|
+
lead = cond.meta.get("sqlalign_lead")
|
|
83
|
+
if lead is not None and ("\n" in lead or lead.startswith("--")):
|
|
84
|
+
if lines:
|
|
85
|
+
lines[-1].segs.append(comment_seg(lead))
|
|
86
|
+
else:
|
|
87
|
+
lines.append(Line(anchor, [comment_seg(lead)]))
|
|
88
|
+
lead = None
|
|
89
|
+
head = Seg(kw.rjust(max_kw)) if i == 0 else joiner_head(kw, max_kw, lines[-1].segs)
|
|
90
|
+
row = [head, *([comment_seg(lead)] if lead is not None else []), *segs]
|
|
91
|
+
lines.append(Line(anchor, row))
|
|
92
|
+
lines.extend(extra)
|
|
93
|
+
trail = cond.meta.get("sqlalign_trail")
|
|
94
|
+
if trail is not None:
|
|
95
|
+
lines[-1].segs.append(comment_seg(trail))
|
|
96
|
+
return lines
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def joiner_head(joiner, max_kw, prev_segs):
|
|
100
|
+
"""The head segment of a continuation (AND/OR) row, right-justified to
|
|
101
|
+
`max_kw` so every keyword in the family ends at the same column.
|
|
102
|
+
|
|
103
|
+
With trailing booleans the joiner instead rides the END of the preceding
|
|
104
|
+
row (`prev_segs`, appended to in place) and the head becomes blank of the
|
|
105
|
+
same width, so the condition column is identical in both modes: only the
|
|
106
|
+
operator moves. `prev_segs` must be the segs of whatever row ACTUALLY
|
|
107
|
+
precedes this one, never the block's keyword row: a condition that itself
|
|
108
|
+
spans rows (a group, an `IN (SELECT ...)`) leaves its own last row on top,
|
|
109
|
+
and that is where the joiner belongs.
|
|
110
|
+
|
|
111
|
+
Public: also used by case.py, whose long-form WHEN/AND/OR family is this
|
|
112
|
+
same geometry with "WHEN" standing in for the clause keyword.
|
|
113
|
+
"""
|
|
114
|
+
if active_style().boolean_operator_position == "trailing":
|
|
115
|
+
# Before any trailing comment, never after it: a `--` runs to end of
|
|
116
|
+
# line, so a joiner appended past one is INSIDE it and the condition
|
|
117
|
+
# below loses its AND/OR entirely.
|
|
118
|
+
content, comments = split_trailing_comments(prev_segs)
|
|
119
|
+
content[-1].text += " " + joiner
|
|
120
|
+
prev_segs[:] = [*content, *comments]
|
|
121
|
+
return Seg(" " * max_kw)
|
|
122
|
+
return Seg(joiner.rjust(max_kw))
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _render_condition(cond, scope, body_col, group_counter, dialect, width):
|
|
126
|
+
"""Return (inline_segs, trailing_lines) for one condition.
|
|
127
|
+
|
|
128
|
+
`inline_segs` are placed on the current row (after this block's keyword);
|
|
129
|
+
`trailing_lines` are any additional full rows (groups, and
|
|
130
|
+
`IN (SELECT ...)` / `EXISTS (SELECT ...)`, produce them). `body_col` is the
|
|
131
|
+
absolute column the inline content will start at — used to place the "("
|
|
132
|
+
of a nested group, or of an IN/EXISTS subquery's body (subquery.py).
|
|
133
|
+
"""
|
|
134
|
+
if isinstance(cond, exp.Paren):
|
|
135
|
+
return _render_group(cond, scope, body_col, group_counter, dialect, width)
|
|
136
|
+
if isinstance(cond, exp.In) and cond.args.get("query") is not None:
|
|
137
|
+
return _render_in_subquery(cond, body_col, dialect, width)
|
|
138
|
+
if isinstance(cond, exp.Exists):
|
|
139
|
+
return _render_exists(cond, body_col, dialect, width)
|
|
140
|
+
# The subquery forms of the same negation. They are peeled HERE rather than
|
|
141
|
+
# in `predicate_segs` because both emit trailing lines whose indents are
|
|
142
|
+
# baked in from the natural column, so `NOT ` has to widen `body_col` by
|
|
143
|
+
# its own length or the body detaches from its `(`.
|
|
144
|
+
if isinstance(cond, exp.Not) and isinstance(cond.this, exp.Exists):
|
|
145
|
+
segs, trailing = _render_exists(cond.this, body_col + len("NOT "), dialect, width)
|
|
146
|
+
return [Seg("NOT"), *segs], trailing
|
|
147
|
+
if (isinstance(cond, exp.Not) and isinstance(cond.this, exp.In)
|
|
148
|
+
and cond.this.args.get("query") is not None):
|
|
149
|
+
# `x NOT IN (SELECT ...)`, not `NOT x IN (SELECT ...)`: both are valid
|
|
150
|
+
# and mean the same thing, but only one is how anyone writes it. not
|
|
151
|
+
# goes on the keyword, which is also what keeps the body under its own
|
|
152
|
+
# paren, since the keyword's own width feeds `open_col`.
|
|
153
|
+
return _render_in_subquery(cond.this, body_col, dialect, width, negation="NOT ")
|
|
154
|
+
return predicate_segs(cond, scope, dialect), []
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _render_in_subquery(cond, body_col, dialect, width, negation=""):
|
|
158
|
+
"""`lhs IN (SELECT ...)`. `body_col` is where
|
|
159
|
+
`lhs` itself starts; the subquery's body recurses one column past its own
|
|
160
|
+
"(", which — per the natural (unpadded) flow every segment here composes
|
|
161
|
+
under, see subquery.py's module docstring — sits at
|
|
162
|
+
`body_col + len(lhs) + 1 (space) + len("IN") + 1 (space)`.
|
|
163
|
+
|
|
164
|
+
The `IN` keyword is deliberately emitted UNTAGGED (no scope/kind), unlike
|
|
165
|
+
every other WHERE/HAVING operator: the derived-table exclusion
|
|
166
|
+
analogue. If `IN` were tagged into the shared `op` scope, a sibling
|
|
167
|
+
condition with a longer LHS would pad it rightward at render time, but
|
|
168
|
+
the subquery body's line indents are baked in here from the NATURAL
|
|
169
|
+
(unpadded) open-paren column (see subquery.py's module docstring on why
|
|
170
|
+
that's unavoidable) — so a padded `IN` would silently detach the body
|
|
171
|
+
from its own `(`. Leaving `IN` untagged keeps its natural column equal to
|
|
172
|
+
its rendered column, so the two can never diverge. Plain `IN (list)`
|
|
173
|
+
(`predicate_segs`, above) is unaffected and still right-aligns.
|
|
174
|
+
"""
|
|
175
|
+
from sqlalign.layout.subquery import guard_subquery, subquery_body
|
|
176
|
+
|
|
177
|
+
if any(cond.args.get(k) for k in ("unnest", "field")):
|
|
178
|
+
raise Unsupported("IN (non-list, non-query)")
|
|
179
|
+
subquery = cond.args["query"]
|
|
180
|
+
guard_subquery(subquery, allow_alias=False)
|
|
181
|
+
lhs = render_expr(cond.this, dialect)
|
|
182
|
+
keyword = negation + "IN"
|
|
183
|
+
lead = [Seg(lhs), Seg(keyword)]
|
|
184
|
+
open_col = body_col + len(lhs) + 1 + len(keyword) + 1
|
|
185
|
+
open_segs, trailing = subquery_body(subquery.this, dialect, width, open_col + 1)
|
|
186
|
+
return lead + open_segs, trailing
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _render_exists(cond, body_col, dialect, width):
|
|
190
|
+
"""`EXISTS (SELECT ...)`. Verified empirically
|
|
191
|
+
(pinned sqlglot v30.14): `exp.Exists.this` is the bare inner `Select` --
|
|
192
|
+
unlike `IN`'s `query` arg, there is no `exp.Subquery` wrapper to guard.
|
|
193
|
+
"""
|
|
194
|
+
from sqlalign.layout.subquery import subquery_body
|
|
195
|
+
|
|
196
|
+
if cond.args.get("expression") is not None:
|
|
197
|
+
raise Unsupported("EXISTS: expression arg")
|
|
198
|
+
open_col = body_col + len("EXISTS") + 1
|
|
199
|
+
open_segs, trailing = subquery_body(cond.this, dialect, width, open_col + 1)
|
|
200
|
+
return [Seg("EXISTS"), *open_segs], trailing
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _render_group(paren, parent_scope, open_col, group_counter, dialect, width):
|
|
204
|
+
"""Lay out a parenthesized group opening at column `open_col`.
|
|
205
|
+
|
|
206
|
+
The group's operators get their own child scope so they align independently
|
|
207
|
+
of the enclosing block.
|
|
208
|
+
"""
|
|
209
|
+
scope = f"{parent_scope}.g{group_counter[0]}"
|
|
210
|
+
group_counter[0] += 1
|
|
211
|
+
conditions, joiner = split_conjunction(paren.this)
|
|
212
|
+
key_col = open_col + 1 # first char after "("
|
|
213
|
+
keywords = [""] + ([joiner] * (len(conditions) - 1) if joiner else [])
|
|
214
|
+
max_kw = max(len(k) for k in keywords)
|
|
215
|
+
body_col = key_col + max_kw + 1
|
|
216
|
+
|
|
217
|
+
seg0, trail0 = _render_condition(conditions[0], scope, key_col, group_counter, dialect, width)
|
|
218
|
+
inline = [_prefixed(seg0[0], "("), *seg0[1:]] # first condition hugs "("
|
|
219
|
+
lines = list(trail0)
|
|
220
|
+
for cond in conditions[1:]:
|
|
221
|
+
segs, trailing = _render_condition(cond, scope, body_col, group_counter, dialect, width)
|
|
222
|
+
# The group's first condition lives INLINE on the caller's row, so the
|
|
223
|
+
# boolean for the first continuation belongs on that row: hence
|
|
224
|
+
# `inline` when no rows of our own exist yet.
|
|
225
|
+
head = joiner_head(joiner, max_kw, lines[-1].segs if lines else inline)
|
|
226
|
+
lines.append(Line(key_col, [head, *segs]))
|
|
227
|
+
lines.extend(trailing)
|
|
228
|
+
|
|
229
|
+
if lines:
|
|
230
|
+
lines[-1].segs[-1].text += ")"
|
|
231
|
+
else:
|
|
232
|
+
inline[-1].text += ")"
|
|
233
|
+
return inline, lines
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def predicate_segs(cond, scope, dialect):
|
|
237
|
+
"""Split one predicate into [lhs, op(tagged), rhs] segments.
|
|
238
|
+
|
|
239
|
+
Public: also used by fromjoin.py to render ON conditions, which share this
|
|
240
|
+
module's operator-comparison vocabulary (=, !=, BETWEEN, IN, IS, ...) but lay
|
|
241
|
+
out their keyword/joiner column very differently (block-global, alias-driven
|
|
242
|
+
rather than `condition_block`'s anchor-relative keyword rjust).
|
|
243
|
+
"""
|
|
244
|
+
if isinstance(cond, exp.Not) and isinstance(cond.this, exp.Is):
|
|
245
|
+
# `x IS NOT NULL` is one shape in postgres (Is with negate=True, handled
|
|
246
|
+
# below) and ANOTHER in T-SQL, which wraps it: Not(Is(...)). Without this
|
|
247
|
+
# the single most common predicate in SQL declined for T-SQL only.
|
|
248
|
+
# Deliberately narrow: only a Not directly wrapping an Is. Every other
|
|
249
|
+
# Not stays declined, which `test_not_exists_passes_through` depends on.
|
|
250
|
+
inner = cond.this
|
|
251
|
+
lhs = render_expr(inner.this, dialect)
|
|
252
|
+
rhs = "NOT " + render_expr(inner.expression, dialect)
|
|
253
|
+
return [Seg(lhs), Seg("IS", scope=scope, kind="op"), Seg(rhs)]
|
|
254
|
+
|
|
255
|
+
# `NOT IN (...)` and `NOT BETWEEN ... AND ...`: sqlglot wraps the inner
|
|
256
|
+
# predicate in a `Not`, so peeling it here puts NOT on the operator, where a
|
|
257
|
+
# reader looks for it and where the aligned operator column holds it.
|
|
258
|
+
negation = ""
|
|
259
|
+
if isinstance(cond, exp.Not) and isinstance(cond.this, (exp.In, exp.Between)):
|
|
260
|
+
cond, negation = cond.this, "NOT "
|
|
261
|
+
|
|
262
|
+
# `b !~ 'x'` is its own operator, not a negated one, so it keeps the
|
|
263
|
+
# operator column to itself rather than growing a `NOT ` prefix.
|
|
264
|
+
if isinstance(cond, exp.Not) and type(cond.this) in _NEGATED_OP:
|
|
265
|
+
inner = cond.this
|
|
266
|
+
return [Seg(render_expr(inner.this, dialect)),
|
|
267
|
+
Seg(_NEGATED_OP[type(inner)], scope=scope, kind="op"),
|
|
268
|
+
Seg(render_expr(inner.expression, dialect))]
|
|
269
|
+
|
|
270
|
+
if isinstance(cond, exp.Between):
|
|
271
|
+
# `BETWEEN SYMMETRIC 2 AND 1` means the same as `BETWEEN 1 AND 2` --
|
|
272
|
+
# the bounds may be given in either order. It is one keyword on the
|
|
273
|
+
# operator, and dropping it would change the meaning, which is why it
|
|
274
|
+
# declined rather than being ignored.
|
|
275
|
+
symmetric = " SYMMETRIC" if cond.args.get("symmetric") else ""
|
|
276
|
+
lhs = render_expr(cond.this, dialect)
|
|
277
|
+
low = render_expr(cond.args["low"], dialect)
|
|
278
|
+
high = render_expr(cond.args["high"], dialect)
|
|
279
|
+
return [Seg(lhs), Seg(negation + "BETWEEN" + symmetric, scope=scope,
|
|
280
|
+
kind="op"),
|
|
281
|
+
Seg(f"{low} AND {high}")]
|
|
282
|
+
|
|
283
|
+
if isinstance(cond, exp.In):
|
|
284
|
+
if any(cond.args.get(k) for k in ("query", "unnest", "field")):
|
|
285
|
+
raise Unsupported("IN (non-list)")
|
|
286
|
+
lhs = render_expr(cond.this, dialect)
|
|
287
|
+
vals = ", ".join(render_expr(e, dialect) for e in cond.args.get("expressions", []))
|
|
288
|
+
return [Seg(lhs), Seg(negation + "IN", scope=scope, kind="op"), Seg(f"({vals})")]
|
|
289
|
+
|
|
290
|
+
if isinstance(cond, exp.Is):
|
|
291
|
+
lhs = render_expr(cond.this, dialect)
|
|
292
|
+
rhs = ("NOT " if cond.args.get("negate") else "") + render_expr(cond.expression, dialect)
|
|
293
|
+
return [Seg(lhs), Seg("IS", scope=scope, kind="op"), Seg(rhs)]
|
|
294
|
+
|
|
295
|
+
if isinstance(cond, exp.Escape):
|
|
296
|
+
# `b LIKE 'x%' ESCAPE '!'` parses as Escape(Like(...)). The escape rides
|
|
297
|
+
# the right-hand segment rather than taking the operator column: it
|
|
298
|
+
# qualifies the pattern, and in the operator column it would align
|
|
299
|
+
# `ESCAPE` under a bare `=`.
|
|
300
|
+
inner = predicate_segs(cond.this, scope, dialect)
|
|
301
|
+
escape = render_expr(cond.expression, dialect)
|
|
302
|
+
return [*inner[:-1], Seg(f"{inner[-1].text} ESCAPE {escape}")]
|
|
303
|
+
|
|
304
|
+
op = _CMP_OP.get(type(cond))
|
|
305
|
+
if op is None:
|
|
306
|
+
# A predicate with no comparison operator to hold a column: a bare
|
|
307
|
+
# boolean column (`WHERE flag`), a literal (`WHERE false`), a call
|
|
308
|
+
# returning boolean (`WHERE my_check(a)`), a negated group
|
|
309
|
+
# (`WHERE NOT (a AND b)`). There is nothing to tag, so it is one
|
|
310
|
+
# untagged segment that does not participate in the operator column --
|
|
311
|
+
# the same treatment an unaliased table gets in the alias column.
|
|
312
|
+
return [Seg(negation + render_expr(cond, dialect))]
|
|
313
|
+
if isinstance(cond, exp.NEQ):
|
|
314
|
+
op = active_style().neq_style # `!=` (house) or `<>` -- see casing.py
|
|
315
|
+
if isinstance(cond, (exp.Like, exp.ILike)) and cond.args.get("negate"):
|
|
316
|
+
# `x NOT LIKE 'a'` is one node carrying a flag, not a wrapped `Not`.
|
|
317
|
+
op = "NOT " + op
|
|
318
|
+
lhs = render_expr(cond.this, dialect)
|
|
319
|
+
rhs = render_expr(cond.expression, dialect)
|
|
320
|
+
return [Seg(lhs), Seg(op, scope=scope, kind="op"), Seg(rhs)]
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def split_conjunction(node):
|
|
324
|
+
"""Flatten a top-level AND/OR chain into (conditions, joiner).
|
|
325
|
+
|
|
326
|
+
Public: shared with fromjoin.py for flattening ON conditions.
|
|
327
|
+
"""
|
|
328
|
+
if isinstance(node, exp.And):
|
|
329
|
+
return _flatten(node, exp.And), "AND"
|
|
330
|
+
if isinstance(node, exp.Or):
|
|
331
|
+
return _flatten(node, exp.Or), "OR"
|
|
332
|
+
return [node], None
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def _flatten(node, cls):
|
|
336
|
+
out = []
|
|
337
|
+
for side in (node.left, node.right):
|
|
338
|
+
out.extend(_flatten(side, cls) if isinstance(side, cls) else [side])
|
|
339
|
+
return out
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def _prefixed(seg, prefix):
|
|
343
|
+
"""A copy of `seg` with `prefix` glued to the front of its text."""
|
|
344
|
+
return Seg(prefix + seg.text, scope=seg.scope, kind=seg.kind)
|
sqlalign/layout/cte.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""WITH-clause (CTE) layout.
|
|
2
|
+
|
|
3
|
+
`WITH name AS (` opens the first CTE at column 0 (`, next AS (` for every CTE
|
|
4
|
+
after the first); the CTE body is a full statement, laid out via
|
|
5
|
+
`layout_statement` at `anchor=2`; the closing `)` returns to column 0. A blank
|
|
6
|
+
line follows every CTE's `)` -- both the ones before the next `, name AS (` and
|
|
7
|
+
the one before the final query, which is itself a full statement laid out via
|
|
8
|
+
`layout_statement` at `anchor=0` on a `with_`-stripped copy of `node`.
|
|
9
|
+
|
|
10
|
+
`layout_with` only ever runs at the top of a statement (anchor 0): a `with_` arg
|
|
11
|
+
can appear on the outermost Select/SetOperation, and layout/__init__.py's
|
|
12
|
+
dispatch checks for it before anything else, so this module never needs an
|
|
13
|
+
`anchor` parameter of its own: nested CTEs (a CTE body that is itself a
|
|
14
|
+
`WITH ...` statement) would recurse through `layout_statement` -> `layout_with`
|
|
15
|
+
again and restart at column 0/2, which is untested and out of scope here (no
|
|
16
|
+
sample nests a WITH inside a CTE).
|
|
17
|
+
"""
|
|
18
|
+
from sqlglot import exp
|
|
19
|
+
|
|
20
|
+
from sqlalign.casing import active_style
|
|
21
|
+
from sqlalign.commas import COMMA_KIND
|
|
22
|
+
from sqlalign.ir import Line, Seg
|
|
23
|
+
from sqlalign.layout import Unsupported
|
|
24
|
+
|
|
25
|
+
_BODY_ANCHOR = 2
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def layout_with(node: exp.Expression, dialect: str, width) -> list[Line]:
|
|
29
|
+
from sqlalign.layout import layout_statement
|
|
30
|
+
|
|
31
|
+
with_ = node.args["with_"]
|
|
32
|
+
_guard(with_)
|
|
33
|
+
|
|
34
|
+
keyword = "WITH RECURSIVE" if with_.args.get("recursive") else "WITH"
|
|
35
|
+
trailing = active_style().comma_position == "trailing"
|
|
36
|
+
lines: list[Line] = []
|
|
37
|
+
for i, cte in enumerate(with_.expressions):
|
|
38
|
+
# `AS MATERIALIZED (` / `AS NOT MATERIALIZED (`: Postgres's optimiser
|
|
39
|
+
# fence: one keyword between `AS` and the paren. It changes planning,
|
|
40
|
+
# so dropping it would change how the query runs.
|
|
41
|
+
materialized = cte.args.get("materialized")
|
|
42
|
+
hint = "" if materialized is None else (
|
|
43
|
+
"MATERIALIZED " if materialized else "NOT MATERIALIZED ")
|
|
44
|
+
body = f"{cte.alias} AS {hint}("
|
|
45
|
+
# This site applies comma position itself rather than going through
|
|
46
|
+
# commas.py's generic pass (like window.py). That pass blanks the comma
|
|
47
|
+
# while KEEPING its width, which is right where the comma head is as wide
|
|
48
|
+
# as the first item's head (`SELECT` vs ` ,`), but a CTE's head is
|
|
49
|
+
# a bare `,` against a `WITH ...` opener, so blanking would indent every
|
|
50
|
+
# later CTE by two columns instead of leaving it at column 0.
|
|
51
|
+
if i == 0:
|
|
52
|
+
segs = [Seg(f"{keyword} {body}")]
|
|
53
|
+
elif trailing:
|
|
54
|
+
segs = [Seg(body)] # comma went on the `)` above
|
|
55
|
+
else:
|
|
56
|
+
segs = [Seg(",", kind=COMMA_KIND), Seg(body)]
|
|
57
|
+
lines.append(Line(0, segs))
|
|
58
|
+
lines += layout_statement(cte.this, dialect, width, anchor=_BODY_ANCHOR)
|
|
59
|
+
close = ")" + ("," if trailing and i < len(with_.expressions) - 1 else "")
|
|
60
|
+
lines.append(Line(0, [Seg(close)]))
|
|
61
|
+
lines.append(Line(0, []))
|
|
62
|
+
|
|
63
|
+
query = node.copy()
|
|
64
|
+
query.set("with_", None)
|
|
65
|
+
lines += layout_statement(query, dialect, width, anchor=0)
|
|
66
|
+
return lines
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _guard(with_: exp.With) -> None:
|
|
70
|
+
if with_.args.get("search"):
|
|
71
|
+
raise Unsupported("WITH ... SEARCH")
|
|
72
|
+
if with_.comments:
|
|
73
|
+
raise Unsupported("embedded comment")
|
|
74
|
+
for cte in with_.expressions:
|
|
75
|
+
if cte.comments:
|
|
76
|
+
raise Unsupported("embedded comment")
|
|
77
|
+
if cte.args.get("key_expressions"):
|
|
78
|
+
raise Unsupported("WITH ... CYCLE")
|
|
79
|
+
alias = cte.args.get("alias")
|
|
80
|
+
if alias is not None and alias.args.get("columns"):
|
|
81
|
+
raise Unsupported("CTE column list")
|