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/ir.py ADDED
@@ -0,0 +1,38 @@
1
+ from dataclasses import dataclass, field
2
+
3
+
4
+ @dataclass
5
+ class Seg:
6
+ text: str
7
+ scope: str | None = None
8
+ kind: str | None = None # item|op|alias|on|as|table|type|constraint|then
9
+
10
+
11
+ @dataclass
12
+ class Line:
13
+ indent: int
14
+ segs: list[Seg] = field(default_factory=list)
15
+
16
+
17
+ RIGHT_ALIGNED = {"op", "on"}
18
+
19
+ # A comment segment. Tagged so the sites that glue punctuation onto the END of a
20
+ # row: `joiner_head` under trailing booleans, commas.py under trailing commas --
21
+ # can place it before the comment. Appending blindly to the last segment puts
22
+ # the punctuation inside a `--` comment, so the row loses its separator.
23
+ #
24
+ # `kind` alone is inert for alignment: align.py only aligns a segment carrying
25
+ # BOTH a scope and a kind, and a comment never gets a scope.
26
+ COMMENT_KIND = "comment"
27
+
28
+
29
+ def comment_seg(text: str) -> "Seg":
30
+ return Seg(text, kind=COMMENT_KIND)
31
+
32
+
33
+ def split_trailing_comments(segs: list["Seg"]) -> tuple[list["Seg"], list["Seg"]]:
34
+ """`(content, trailing comments)` -- the comment run at the end of a row."""
35
+ cut = len(segs)
36
+ while cut and segs[cut - 1].kind == COMMENT_KIND:
37
+ cut -= 1
38
+ return segs[:cut], segs[cut:]
@@ -0,0 +1,127 @@
1
+ """Keyword casing (`Style.keyword_case`) — driven by the AST, not a word list.
2
+
3
+ House style renders every keyword, function name, and type name in upper case.
4
+ `lower` renders them in lower case, which is what most published SQL style guides
5
+ and the dbt ecosystem use.
6
+
7
+ **Why this is AST-driven.** The obvious implementation: lowercase any word that
8
+ appears in a keyword list: is both unsafe and incomplete:
9
+
10
+ * *Unsafe*: `COMMENT`, `END`, `FILTER`, `FORMAT`, `RANGE` and `ROWS` are all real
11
+ column names AND tokenizer keywords. Lowercasing an identifier changes it, which
12
+ the safety net then rejects, passing the whole file through unformatted.
13
+ * *Incomplete*: `BY`, `CAST`, `GROUP`, `ORDER`, `PRIMARY` and `KEY` are keywords
14
+ that are NOT in sqlglot's single-word keyword set, so a list-based pass leaves
15
+ them upper while lowering everything around them.
16
+
17
+ The parse tree already knows precisely which words are identifiers. So the rule
18
+ inverts: lowercase every bare word EXCEPT the ones the AST names as identifiers.
19
+ That is complete by construction (anything the formatter emitted that is not your
20
+ identifier is something sqlalign chose to write) and safe by construction (an
21
+ identifier is never touched, whatever it is called).
22
+
23
+ Casing never changes a string's width, so no alignment column moves.
24
+ """
25
+ import re
26
+
27
+ import sqlglot
28
+ from sqlglot import exp
29
+
30
+ # A bare word: identifier-shaped, and UNICODE-aware on purpose. `apply` enters
31
+ # this pattern on any `ch.isalpha()`, which is true of `é`: an ASCII-only
32
+ # pattern then fails to match there and crashes the pass, which formatter's
33
+ # catch-all turns into an "internal error" passthrough for the whole statement.
34
+ # `[^\W\d]\w*` is exactly `[A-Za-z_][A-Za-z0-9_]*` over ASCII, so nothing else
35
+ # changes: it only extends the same shape to non-ASCII letters (`café` is one
36
+ # word, matching the Identifier the parse tree recorded, so it is preserved).
37
+ _WORD = re.compile(r"[^\W\d]\w*")
38
+
39
+
40
+ def identifier_names(statement: str, dialect: str) -> set[str]:
41
+ """Every identifier the parse tree knows about in `statement`.
42
+
43
+ A dollar-quoted plpgsql body parses as one opaque string, so its identifiers
44
+ are invisible here — the body's own statements are parsed separately and
45
+ folded in, otherwise a variable inside a procedure would be treated as a
46
+ keyword and lowered.
47
+ """
48
+ names: set[str] = set()
49
+ try:
50
+ trees = [t for t in sqlglot.parse(statement, read=dialect) if t is not None]
51
+ except (sqlglot.errors.ParseError, sqlglot.errors.TokenError):
52
+ return names
53
+
54
+ for tree in trees:
55
+ for ident in tree.find_all(exp.Identifier):
56
+ names.add(ident.this)
57
+ for heredoc in tree.find_all(exp.Heredoc): # plpgsql body
58
+ body = heredoc.this
59
+ if isinstance(body, str):
60
+ names |= _body_identifiers(body, dialect)
61
+ return names
62
+
63
+
64
+ def _body_identifiers(body: str, dialect: str) -> set[str]:
65
+ from sqlalign.plpgsql import body_clauses, strip_struct
66
+
67
+ names: set[str] = set()
68
+ for clause in body_clauses(body):
69
+ try:
70
+ parsed = sqlglot.parse(strip_struct(clause), read=dialect)
71
+ except (sqlglot.errors.ParseError, sqlglot.errors.TokenError):
72
+ # An unparseable clause (RAISE, GET DIAGNOSTICS, `:=`) contributes its
73
+ # bare words defensively: better to leave a keyword upper than to
74
+ # lower a variable name.
75
+ names |= set(_WORD.findall(clause))
76
+ continue
77
+ for tree in parsed:
78
+ if tree is None:
79
+ continue
80
+ for ident in tree.find_all(exp.Identifier):
81
+ names.add(ident.this)
82
+ return names
83
+
84
+
85
+ def apply(text: str, names: set[str], case: str) -> str:
86
+ """Case every bare word outside strings, quoted identifiers, and comments,
87
+ leaving anything in `names` exactly as written."""
88
+ if case == "upper":
89
+ return text # what the handlers already emit
90
+ out: list[str] = []
91
+ i, n = 0, len(text)
92
+ while i < n:
93
+ ch = text[i]
94
+ if ch in ("'", '"'): # string literal / quoted identifier
95
+ end = text.find(ch, i + 1)
96
+ end = n if end == -1 else end + 1
97
+ out.append(text[i:end])
98
+ i = end
99
+ elif ch == "[":
100
+ # T-SQL bracket-quoted identifier. Its inner words are not separate
101
+ # identifiers in the parse tree (`[Order Id]` is one Identifier named
102
+ # "Order Id"), so without this they would be cased individually --
103
+ # changing a quoted identifier, which the safety net then rejects,
104
+ # leaving the whole statement unformatted.
105
+ end = text.find("]", i + 1)
106
+ end = n if end == -1 else end + 1
107
+ out.append(text[i:end])
108
+ i = end
109
+ elif text.startswith("--", i):
110
+ end = text.find("\n", i) # the newline itself is cased normally
111
+ if end == -1:
112
+ end = n
113
+ out.append(text[i:end])
114
+ i = end
115
+ elif text.startswith("/*", i):
116
+ end = text.find("*/", i)
117
+ end = n if end == -1 else end + 2
118
+ out.append(text[i:end])
119
+ i = end
120
+ elif ch.isalpha() or ch == "_":
121
+ word = _WORD.match(text, i).group(0)
122
+ out.append(word if word in names else word.lower())
123
+ i += len(word)
124
+ else:
125
+ out.append(ch)
126
+ i += 1
127
+ return "".join(out)
@@ -0,0 +1,312 @@
1
+ """Layout dispatch.
2
+
3
+ `layout_statement` is the single entry point every later task extends: it maps a
4
+ parsed sqlglot expression to a list of `Line`s (the alignment resolver then turns
5
+ those into text). Node types this layer does not yet lay out raise `Unsupported`,
6
+ which the formatter catches and turns into a byte-identical passthrough + warning.
7
+
8
+ Dispatch order matters: a `with_` arg (a CTE-bearing statement) can sit on either
9
+ a Select or a SetOperation (Union/Intersect/Except), so that check runs first and
10
+ routes to layout/cte.py, which strips `with_` and recurses back into this same
11
+ function for the bare query underneath. SetOperation is checked before Select
12
+ since Union et al. are not Select subclasses.
13
+
14
+ `Unsupported` and `guard_args` (the arg-level form of the same decline, shared by
15
+ ddl.py and dml.py) live here because declining is the contract every layout
16
+ module is written against, not a detail of any one of them.
17
+ """
18
+ from sqlglot import exp
19
+
20
+ from sqlalign.casing import active_style, render_expr
21
+ from sqlalign.commas import COMMA_KIND
22
+ from sqlalign.ir import Line, Seg, comment_seg
23
+
24
+
25
+ class Unsupported(Exception):
26
+ """Raised for any construct this layout layer cannot render byte-exactly.
27
+
28
+ Always caught by the formatter, which then passes the statement through
29
+ verbatim. Raising it is therefore the safe way to *decline* a construct;
30
+ never emit a partial/guessed layout for something we do not fully handle.
31
+ """
32
+
33
+
34
+ def guard_args(node: exp.Expression, allowed: set[str], label: str | None = None) -> None:
35
+ """Decline `node` if it carries any arg outside `allowed`.
36
+
37
+ A statement's shape is modeled arg by arg, so an arg we do not read (INSERT
38
+ ... ON CONFLICT, UPDATE ... FROM, a CREATE TABLE option, ...) would be
39
+ silently dropped from the output. Raising instead turns it into a
40
+ byte-identical passthrough. An arg that is present but empty (None/[]/False)
41
+ carries nothing, so it never trips the guard. `label` names the construct in
42
+ the message where the node type alone is too coarse (`CREATE TABLE` and
43
+ `CREATE PROCEDURE` are both `Create`).
44
+ """
45
+ for name, value in node.args.items():
46
+ if value not in (None, [], False) and name not in allowed:
47
+ raise Unsupported(f"{label or type(node).__name__} arg: {name}")
48
+
49
+
50
+ def layout_statement(node: exp.Expression, dialect: str, width, anchor: int = 0) -> list[Line]:
51
+ from sqlalign.layout import cte as _cte
52
+ from sqlalign.layout import ddl as _ddl
53
+ from sqlalign.layout import dml as _dml
54
+ from sqlalign.layout import select as _select
55
+ from sqlalign.layout import setop as _setop
56
+
57
+ if node.args.get("with_") is not None:
58
+ return _cte.layout_with(node, dialect, width)
59
+ if isinstance(node, (exp.Create, exp.TruncateTable, exp.Grant, exp.Alter,
60
+ exp.Drop, exp.Comment, exp.Declare, exp.Copy)):
61
+ return _ddl.ddl_lines(node, dialect, width, anchor)
62
+ # A GRANT sqlglot could only parse as an unsupported-syntax Command
63
+ # (e.g. GRANT ... ON ALL TABLES IN SCHEMA ...) still gets keyword casing.
64
+ if isinstance(node, exp.Command) and str(node.this).upper() == "GRANT":
65
+ return _ddl.ddl_lines(node, dialect, width, anchor)
66
+ if isinstance(node, exp.Values):
67
+ return _dml.values_lines(node, dialect, anchor)
68
+ if isinstance(node, (exp.Insert, exp.Update, exp.Delete, exp.Merge)):
69
+ return _dml.dml_lines(node, dialect, width, anchor)
70
+ if isinstance(node, exp.SetOperation):
71
+ return _setop.layout_setop(node, dialect, width, anchor)
72
+ if isinstance(node, exp.Select):
73
+ return _select.layout_select(node, dialect, width, anchor)
74
+ raise Unsupported(type(node).__name__)
75
+
76
+
77
+ def join_keyword(join: exp.Join) -> str:
78
+ """The join keyword rebuilt from `method`/`side`/`kind` ("NATURAL", "LEFT",
79
+ "INNER", "LEFT OUTER"), ordered the way sqlglot's own generator orders it:
80
+ method, side, kind, "JOIN" -- so `NATURAL LEFT JOIN` comes out in that order
81
+ (verified empirically against pinned sqlglot v30.14).
82
+
83
+ Lives here rather than in fromjoin.py because subquery.py needs it too and
84
+ fromjoin.py already imports FROM subquery.py: a shared home is what breaks
85
+ that cycle, and it previously cost a duplicated copy in each module.
86
+ """
87
+ parts = [join.args.get("method"), join.args.get("side"), join.args.get("kind"), "JOIN"]
88
+ return " ".join(p for p in parts if p)
89
+
90
+
91
+ COMMA_ROW = object() # sentinel: this row is the legacy comma form
92
+
93
+
94
+ def row_keyword(join):
95
+ """The keyword that opens a join's row, or `COMMA_ROW` for the legacy form.
96
+
97
+ `FROM a, b` parses as a join with no condition and no kind: structurally
98
+ identical to `CROSS JOIN`, so rebuilding it through `join_keyword` would
99
+ emit `FROM a JOIN b`, which Postgres rejects. sqlglot prints the comma form
100
+ instead, and so do we: it is the author's own syntax, and the alternative is
101
+ invalid SQL the re-parse check cannot catch (sqlglot reads its own lenient
102
+ output back happily).
103
+
104
+ `FROM a JOIN b` with no condition is itself a syntax error, so nothing that
105
+ parses this way in practice is anything BUT the comma form.
106
+ """
107
+ if (join.args.get("on") is None and not join.args.get("using")
108
+ and not join.args.get("kind") and not join.args.get("method")):
109
+ return COMMA_ROW
110
+ return join_keyword(join)
111
+
112
+
113
+
114
+ def table_name(table: exp.Expression, dialect: str) -> str:
115
+ """A table reference rendered WITHOUT its alias, which the callers position
116
+ in their own alignment column. Shared by select.py and fromjoin.py for the
117
+ same cycle-breaking reason as `join_keyword`."""
118
+ bare = table.copy()
119
+ bare.set("alias", None)
120
+ return render_expr(bare, dialect)
121
+
122
+
123
+ def comma_clause(keyword, texts, anchor, comments=None):
124
+ """Keyword + comma-stacked terms, one per line with a leading comma two
125
+ columns before the term; a single term stays inline.
126
+
127
+ Shared by grouporder.py (GROUP BY / ORDER BY) and dml.py (an INSERT's VALUES
128
+ rows), which is why it lives here rather than in either: the same reason
129
+ `join_keyword` and `table_name` do.
130
+
131
+ `comments` is an optional `[(lead, trail)]`, one pair per term, from the
132
+ comment engine. It is passed rather than read off the nodes because this
133
+ function is handed rendered TEXT: the terms arrive as strings, which is
134
+ exactly why comments in these clauses declined until the pair came with
135
+ them.
136
+ """
137
+ kw_anchor, kw_text = clause_head(keyword, anchor)
138
+ pairs = list(comments or [(None, None)] * len(texts))
139
+ # Nothing precedes the FIRST term inside this clause, so an off-row comment
140
+ # leading it takes the row above the keyword. Without this it rode the
141
+ # keyword row and a `--` swallowed the term after it.
142
+ lines = []
143
+ first_lead = pairs[0][0]
144
+ if _off_row(first_lead):
145
+ lines.append(Line(anchor, [comment_seg(first_lead)]))
146
+ first_lead = None
147
+ head = Line(kw_anchor, [Seg(kw_text), *_lead_segs(first_lead), Seg(texts[0])])
148
+ if len(texts) <= 1:
149
+ return _with_trail([*lines, head], pairs[0][1], kw_anchor, first_lead)
150
+ # The comma sits two columns before the term, wherever the keyword put it.
151
+ term_col = kw_anchor + len(kw_text) + 1
152
+ lead = " " * (term_col - anchor - 2)
153
+ lines.append(head)
154
+ lines = _with_trail(lines, pairs[0][1], kw_anchor, first_lead)
155
+ for t, (item_lead, item_trail) in zip(texts[1:], pairs[1:], strict=False):
156
+ # A `--` or multi-line comment cannot share a row with what follows it,
157
+ # so it takes the end of the row above: the same rule select.py and
158
+ # conditions.py use, and the only idempotent one.
159
+ if _off_row(item_lead):
160
+ lines[-1].segs.append(comment_seg(item_lead))
161
+ item_lead = None
162
+ # Comma as its own Seg (relocatable by commas.py); render's inter-seg
163
+ # space reproduces the house `lead + ", " + term` exactly.
164
+ lines.append(Line(anchor, [Seg(lead + ",", kind=COMMA_KIND),
165
+ *_lead_segs(item_lead), Seg(t)]))
166
+ lines = _with_trail(lines, item_trail, anchor, item_lead)
167
+ return lines
168
+
169
+
170
+ def attach_comments(lines, node, anchor, before=None):
171
+ """Apply `node`'s comment-engine annotations to the rows just emitted.
172
+
173
+ `lines` are this row's own lines; `before` is whatever precedes them, so an
174
+ off-row comment can take the end of the row above: the placement every
175
+ other site uses, and the only idempotent one. With nothing above, it takes a
176
+ row of its own at `anchor`.
177
+ """
178
+ lead = node.meta.get("sqlalign_lead")
179
+ trail = node.meta.get("sqlalign_trail")
180
+ out = list(lines)
181
+ if lead is not None:
182
+ if _off_row(lead):
183
+ if before:
184
+ before[-1].segs.append(comment_seg(lead))
185
+ else:
186
+ out.insert(0, Line(anchor, [comment_seg(lead)]))
187
+ else:
188
+ out[0].segs.insert(1, comment_seg(lead))
189
+ if trail is not None:
190
+ out[-1].segs.append(comment_seg(trail))
191
+ return out
192
+
193
+
194
+ def _off_row(comment) -> bool:
195
+ """Whether `comment` must take a row of its own rather than ride one."""
196
+ return comment is not None and ("\n" in comment or comment.startswith("--"))
197
+
198
+
199
+ def _lead_segs(comment):
200
+ return [comment_seg(comment)] if comment is not None else []
201
+
202
+
203
+ def _with_trail(lines, trail, anchor, lead_used):
204
+ """Append a trailing comment to the row just emitted."""
205
+ if trail is not None:
206
+ lines[-1].segs.append(comment_seg(trail))
207
+ return lines
208
+
209
+
210
+ def clause_head(keyword: str, anchor: int, *, hang: bool = False) -> tuple[int, str]:
211
+ """`(line indent, keyword text)` for a ROOT clause keyword.
212
+
213
+ Left-aligned (house) this is just `(anchor, keyword)`. In a river the
214
+ keyword is right-aligned so its last character lands on the gutter, which
215
+ puts every clause body in one column:
216
+
217
+ SELECT a.foo
218
+ FROM apple a
219
+ WHERE a.id > 0
220
+
221
+ Two things do not fit that, and they are not the same case:
222
+
223
+ - A **JOIN** goes on the far side of the river, at `gutter + 1`, whatever its
224
+ width (`hang=True`). This is Holywell's own documented rule, and it is
225
+ about joins rather than about long keywords: a bare 4-character `JOIN`
226
+ sitting in the gutter beside a hanging `LEFT JOIN` would read as a
227
+ different clause.
228
+ - An over-long **root** keyword: `GROUP BY` and `ORDER BY` are 8 against a
229
+ gutter of 6: stays at the margin and overhangs the gutter. Sending those
230
+ to the far side too would indent them past `WHERE`, which reads as though
231
+ they were subordinate to it. They are not; they are root clauses, and no
232
+ river guide prints them any other way.
233
+
234
+ The gutter is FIXED rather than resolved from the widest keyword present.
235
+ That matters: every clause handler computes its body column at layout time,
236
+ so a resolver-determined keyword width would leave those columns stale --
237
+ the detachment bug subquery.py's docstring records. A constant keeps the
238
+ whole thing layout-time knowable.
239
+ """
240
+ style = active_style()
241
+ if style.clause_keyword_align != "river":
242
+ return anchor, keyword
243
+ gutter = style.river_gutter
244
+ if hang:
245
+ return anchor + gutter + 1, keyword
246
+ if len(keyword) > gutter:
247
+ return anchor, keyword # overhangs the gutter, stays a root clause
248
+ return anchor, keyword.rjust(gutter)
249
+
250
+
251
+ def select_item_col(anchor: int) -> int:
252
+ """The column every select item's own content starts at.
253
+
254
+ Shared by case.py, window.py, expr.py and select.py, which all need the column
255
+ a select-list item starts at.
256
+ """
257
+ style = active_style()
258
+ if style.select_placement == "own_line":
259
+ return anchor + style.select_indent
260
+ if style.clause_keyword_align == "river":
261
+ return anchor + style.river_gutter + 1
262
+ return anchor + len("SELECT ")
263
+
264
+
265
+ def column_alias(item: exp.Alias, dialect: str) -> str:
266
+ """`item`'s alias as it should be PRINTED, quoting included.
267
+
268
+ Same bug `table_alias` documents, one node type over and found much later:
269
+ sqlglot's `.alias` returns the identifier's NAME, so `AS "Total Revenue"`
270
+ came out as bare `AS Total Revenue`. Every quoted column alias: ordinary
271
+ reporting SQL: was rejected by the re-parse guard and passed through
272
+ untouched, which is a silent decline behind the safety net where the house
273
+ rule is to decline explicitly or not at all.
274
+
275
+ Quoting is not cosmetic here: unquoted, `Total Revenue` is a syntax error,
276
+ and `"b"` and `b` are different columns in Postgres. The guard was right to
277
+ reject the output; the renderer was the thing that was wrong.
278
+ """
279
+ return render_expr(item.args["alias"], dialect)
280
+
281
+
282
+ def table_alias(table: exp.Expression, dialect: str) -> str | None:
283
+ """`table`'s alias as it should be PRINTED, or None if it has none.
284
+
285
+ `FROM t AS a` and `FROM t a` parse to an identical AST, so which spelling
286
+ comes out is sqlalign's decision rather than the author's -- see
287
+ `Style.table_alias_style`. Every site that prints a table alias goes through
288
+ here so the two spellings cannot drift apart between FROM, JOIN, a derived
289
+ table, and the DML verbs.
290
+
291
+ Rendered through `render_expr` rather than read off `.name`, which returns
292
+ the identifier UNQUOTED: `FROM a "My Alias"` came out as bare `My Alias`, and
293
+ the only thing that caught it was the re-parse guard noticing the quoting had
294
+ changed: a silent decline behind the safety net, where the house rule is to
295
+ decline explicitly or not at all. Rendering keeps the quotes, so those
296
+ statements now format instead of passing through.
297
+
298
+ Returning the `AS` inside the string (rather than as its own segment) keeps
299
+ the alias column aligning on whatever actually starts the alias, which is
300
+ what a reader tracks down the block.
301
+ """
302
+ alias = table.args.get("alias")
303
+ if alias is None:
304
+ return None
305
+ if isinstance(alias, exp.TableAlias) and alias.this is None:
306
+ return None
307
+ # The whole TableAlias, not just its identifier, so `AS g(n)` keeps its
308
+ # alias list, which `generate_series(1, 10) AS g(n)` and
309
+ # `(VALUES (1, 2)) AS v(a, b)` both need.
310
+ name = render_expr(alias, dialect) if isinstance(alias, exp.TableAlias) else \
311
+ render_expr(alias.this, dialect)
312
+ return f"AS {name}" if active_style().table_alias_style == "as" else name