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
sqlalign/formatter.py
ADDED
|
@@ -0,0 +1,609 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from collections import namedtuple
|
|
3
|
+
|
|
4
|
+
import sqlglot
|
|
5
|
+
from sqlglot import exp
|
|
6
|
+
|
|
7
|
+
from sqlalign import keywordcase, plpgsql, templating
|
|
8
|
+
from sqlalign.align import apply_align_targets, render
|
|
9
|
+
from sqlalign.casing import parse_dialect, render_style
|
|
10
|
+
from sqlalign.commas import apply_comma_position
|
|
11
|
+
from sqlalign.layout import Unsupported, layout_statement
|
|
12
|
+
from sqlalign.layout import comments as _comments
|
|
13
|
+
from sqlalign.splitter import split_statements
|
|
14
|
+
from sqlalign.style import HOUSE, SUPPORTED_DIALECTS, Style
|
|
15
|
+
|
|
16
|
+
# `statements` is every top-level statement seen; `declines` is one Decline per
|
|
17
|
+
# statement passed through unformatted. Both carry defaults so the two-field
|
|
18
|
+
# construction used throughout still works.
|
|
19
|
+
Decline = namedtuple("Decline", "kind reason")
|
|
20
|
+
FormatResult = namedtuple("FormatResult", "text warnings statements declines",
|
|
21
|
+
defaults=(0, ()))
|
|
22
|
+
|
|
23
|
+
# `-- sqlalign: skip` passes the whole statement through byte-identical, with no
|
|
24
|
+
# parse and no warning. Recognised both in a statement's leading comment block
|
|
25
|
+
# and as a trailing same-line comment after the terminating ';'.
|
|
26
|
+
_SKIP_RE = re.compile(r"--\s*sqlalign:\s*skip", re.IGNORECASE)
|
|
27
|
+
|
|
28
|
+
# A trailing same-line comment after a statement's terminating ';': the ';', any
|
|
29
|
+
# whitespace, one `--`-to-EOL or `/* ... */` comment, then only whitespace to the
|
|
30
|
+
# end of the statement text. Anchoring to the ';' keeps a `--`/`;` that lives
|
|
31
|
+
# inside a string literal from being mistaken for a trailing comment. Used to
|
|
32
|
+
# peel the comment off so the body formats and re-attach it verbatim, and to
|
|
33
|
+
# recognise a trailing `-- sqlalign: skip`.
|
|
34
|
+
_TRAILING_COMMENT_RE = re.compile(r";\s*(?:--[^\n]*|/\*.*?\*/)\s*\Z", re.DOTALL)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class SafetyError(RuntimeError):
|
|
38
|
+
pass
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
# Types whose distinction sqlglot destroys at parse time for T-SQL, where the two
|
|
42
|
+
# spellings are not synonyms:
|
|
43
|
+
# REAL is FLOAT(24), FLOAT is FLOAT(53) , rewriting one widens precision
|
|
44
|
+
# NTEXT is Unicode, TEXT is not
|
|
45
|
+
# Both collapse to a single node before any generator runs, so `ast_equal` compares
|
|
46
|
+
# the two spellings EQUAL and cannot catch the change. The AST is useless here; the
|
|
47
|
+
# only defence is to spot the type in the RAW SOURCE and decline the statement.
|
|
48
|
+
# (INT/INTEGER, DECIMAL/NUMERIC and TIMESTAMP/ROWVERSION also collapse but are true
|
|
49
|
+
# synonyms, so their canonicalisation is harmless: the same call the house style
|
|
50
|
+
# already makes for DECIMAL->NUMERIC.)
|
|
51
|
+
_TSQL_LOSSY_TYPES = re.compile(r"\b(REAL|NTEXT)\b", re.IGNORECASE)
|
|
52
|
+
|
|
53
|
+
# A lone T-SQL batch separator, once the splitter has isolated it.
|
|
54
|
+
_GO_ONLY = re.compile(r"GO(?:\s+\d+)?", re.IGNORECASE)
|
|
55
|
+
|
|
56
|
+
# A GO line in context, used to split a file into batches for the safety check.
|
|
57
|
+
_GO_LINE_RE = re.compile(r"^[ \t]*GO(?:[ \t]+\d+)?[ \t]*$", re.IGNORECASE | re.MULTILINE)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _split_go_batches(text: str) -> tuple[list[str], list[str]]:
|
|
61
|
+
"""`(batches, separators)` for a T-SQL file. Separators are normalised so a
|
|
62
|
+
reformatted `go` still matches a source `GO`, while a MISSING one does not."""
|
|
63
|
+
batches, separators, pos = [], [], 0
|
|
64
|
+
for match in _GO_LINE_RE.finditer(text):
|
|
65
|
+
batches.append(text[pos:match.start()])
|
|
66
|
+
separators.append(match.group(0).strip().upper())
|
|
67
|
+
pos = match.end()
|
|
68
|
+
batches.append(text[pos:])
|
|
69
|
+
return batches, separators
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
# Node/arg shapes (verified empirically against pinned sqlglot v30.14) that hold
|
|
73
|
+
# raw, case-preserved *keyword* text rather than user data, and are therefore safe
|
|
74
|
+
# to casefold before AST-equality comparison. Keyword casing is semantically inert
|
|
75
|
+
# in SQL; string/identifier casing is not, so those are deliberately excluded below.
|
|
76
|
+
# - exp.Command: unsupported-syntax fallback (e.g. `GRANT ... ON ALL TABLES IN
|
|
77
|
+
# SCHEMA ...` in postgres). Both `this` (the command keyword, e.g. "grant") and
|
|
78
|
+
# `expression` (the entire remainder of the statement, verbatim) are plain str
|
|
79
|
+
# holding the *raw, half-parsed source text*, which can itself embed quoted
|
|
80
|
+
# identifiers (`"Analytics"`) or string literals (`'Admin'`) whose casing IS
|
|
81
|
+
# semantically significant. Casefolding this wholesale would silently mask
|
|
82
|
+
# real case changes inside those quoted regions, so it is handled separately
|
|
83
|
+
# below via `_casefold_outside_quotes`, not through this str-arg table.
|
|
84
|
+
# - exp.Var: generic keyword-value wrapper. Deliberately not casefolded here as
|
|
85
|
+
# a blanket rule (see `_CASEFOLD_VAR_ARGS` below): a bare Var can also hold
|
|
86
|
+
# semantically significant, case-preserved user data. For example
|
|
87
|
+
# `SET search_path = "MySchema"` parses to `Var(this="MySchema")` with the
|
|
88
|
+
# quotes stripped by the parser; folding all Var.this globally would make
|
|
89
|
+
# that quoted-identifier case change invisible to ast_equal.
|
|
90
|
+
# - exp.WindowSpec: frame clause, e.g. `ROWS BETWEEN UNBOUNDED PRECEDING AND
|
|
91
|
+
# CURRENT ROW`. `kind` ("ROWS"/"RANGE") and `start_side`/`end_side`
|
|
92
|
+
# ("PRECEDING"/"FOLLOWING") are plain str with source-preserved casing; `start`/
|
|
93
|
+
# `end` are hardcoded-casing str (e.g. always "UNBOUNDED") or Literal nodes, and
|
|
94
|
+
# `exclude` is an exp.Var (already covered), so none of those three need entries.
|
|
95
|
+
# - exp.TruncateTable: `identity` (e.g. "RESTART") and `option` (e.g. "CASCADE")
|
|
96
|
+
# are plain str with source-preserved casing.
|
|
97
|
+
# - exp.Anonymous: a function sqlglot has no node for, i.e. any
|
|
98
|
+
# user-defined function and any builtin outside its dialect table. Its `this` is the
|
|
99
|
+
# function NAME as a case-preserved plain str. sqlalign cases function names
|
|
100
|
+
# like any other keyword, so `my_udf(x)` renders as `MY_UDF(x)` and the two
|
|
101
|
+
# strings differ. Unquoted SQL function names are case-insensitive (Postgres
|
|
102
|
+
# folds them), so that is not a semantic change, but without this entry
|
|
103
|
+
# ast_equal saw one and passed the statement through. Every lowercase call to
|
|
104
|
+
# unknown function would otherwise be declined.
|
|
105
|
+
# - exp.Comment: `kind` is the commented object's type ("TABLE" / "COLUMN") as
|
|
106
|
+
# a case-preserved plain str, which sqlglot echoes back verbatim: so
|
|
107
|
+
# `comment on table t` renders `COMMENT ON table t`, one lowercase keyword
|
|
108
|
+
# stranded in an uppercased statement. Casing it is right; without this entry
|
|
109
|
+
# the cased output compares unequal and the statement declines instead.
|
|
110
|
+
_CASEFOLD_STR_ARGS = {
|
|
111
|
+
exp.WindowSpec: ("kind", "start_side", "end_side"),
|
|
112
|
+
exp.TruncateTable: ("identity", "option"),
|
|
113
|
+
exp.Anonymous: ("this",),
|
|
114
|
+
exp.Comment: ("kind",),
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
# Narrow, node-scoped exception to the "no bare Var casefold" rule above.
|
|
118
|
+
# Empirically (pinned sqlglot v30.14), redshift `DISTSTYLE {KEY|EVEN|ALL|AUTO}`
|
|
119
|
+
# is the one Var shape found in this codebase's fixtures whose casing is both
|
|
120
|
+
# (a) source-preserved rather than parser-normalized (unlike, e.g.,
|
|
121
|
+
# `GrantPrivilege`'s Var, which sqlglot uppercases at parse time regardless of
|
|
122
|
+
# source case) and (b) drawn from a fixed, closed keyword set rather than
|
|
123
|
+
# arbitrary user data, so it is safe to casefold, but only when it appears as
|
|
124
|
+
# the named arg of one of these specific parent node types, never as a global
|
|
125
|
+
# Var.this rule. See test_ast_equal_rejects_quoted_var_case for the case this
|
|
126
|
+
# guards against.
|
|
127
|
+
_CASEFOLD_VAR_ARGS = {
|
|
128
|
+
exp.DistStyleProperty: ("this",),
|
|
129
|
+
# `WHEN MATCHED THEN DELETE`: the whole action is a keyword, and sqlglot
|
|
130
|
+
# keeps it as a Var carrying the case it was written in. sqlalign cases it
|
|
131
|
+
# like any other keyword, so without this the cased output compares unequal
|
|
132
|
+
# and every MERGE with a DELETE branch declined.
|
|
133
|
+
exp.When: ("then",),
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _casefold_outside_quotes(text: str) -> str:
|
|
138
|
+
"""Casefold `text`, leaving the contents of '...'- and "..."-quoted regions
|
|
139
|
+
(with '' / "" doubling as the escape) untouched.
|
|
140
|
+
|
|
141
|
+
Used for exp.Command's raw fallback text: unsupported-syntax statements
|
|
142
|
+
keep their entire remainder as verbatim source text, which can itself
|
|
143
|
+
contain quoted identifiers or string literals whose casing is
|
|
144
|
+
semantically meaningful even though the surrounding keyword text isn't.
|
|
145
|
+
"""
|
|
146
|
+
out = []
|
|
147
|
+
i, n = 0, len(text)
|
|
148
|
+
while i < n:
|
|
149
|
+
ch = text[i]
|
|
150
|
+
if ch in ("'", '"'):
|
|
151
|
+
quote = ch
|
|
152
|
+
out.append(ch)
|
|
153
|
+
i += 1
|
|
154
|
+
while i < n:
|
|
155
|
+
out.append(text[i])
|
|
156
|
+
if text[i] == quote:
|
|
157
|
+
if i + 1 < n and text[i + 1] == quote: # doubled quote: escaped, stay inside
|
|
158
|
+
out.append(text[i + 1])
|
|
159
|
+
i += 2
|
|
160
|
+
continue
|
|
161
|
+
i += 1 # unescaped: closes the quoted region
|
|
162
|
+
break
|
|
163
|
+
i += 1
|
|
164
|
+
else:
|
|
165
|
+
out.append(ch.casefold())
|
|
166
|
+
i += 1
|
|
167
|
+
return "".join(out)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _normalize(node):
|
|
171
|
+
for e in node.walk():
|
|
172
|
+
e.comments = None
|
|
173
|
+
# `ast_equal` compares `repr`, which is stricter than sqlglot's own `==`
|
|
174
|
+
#: deliberately, so a token-level difference cannot slip past. But
|
|
175
|
+
# `repr` also reflects the args dict's INSERTION order, which is an
|
|
176
|
+
# artefact of how a statement was written rather than what it means:
|
|
177
|
+
# `GROUP BY ROLLUP(a, b), CUBE(c)` and `GROUP BY CUBE(c), ROLLUP(a, b)`
|
|
178
|
+
# parse to `{rollup, cube}` and `{cube, rollup}`, and sqlglot itself
|
|
179
|
+
# reports them equal. Sorting the keys removes exactly that sensitivity
|
|
180
|
+
# and nothing else: the strictness stays, the false decline goes.
|
|
181
|
+
e.args = dict(sorted(e.args.items()))
|
|
182
|
+
if isinstance(e, exp.LanguageProperty):
|
|
183
|
+
# `LANGUAGE plpgsql` and `LANGUAGE 'plpgsql'` are semantically
|
|
184
|
+
# identical (the quotes are optional legacy syntax) but parse to a
|
|
185
|
+
# Var vs a Literal. Canonicalize to a casefolded Var so the house
|
|
186
|
+
# form (bare, lowercase: ) compares equal to a quoted input.
|
|
187
|
+
name = e.this.name if e.this is not None else ""
|
|
188
|
+
e.set("this", exp.var(name.casefold()))
|
|
189
|
+
continue
|
|
190
|
+
if isinstance(e, exp.Command):
|
|
191
|
+
for arg_name in ("this", "expression"):
|
|
192
|
+
value = e.args.get(arg_name)
|
|
193
|
+
if isinstance(value, str):
|
|
194
|
+
e.set(arg_name, _casefold_outside_quotes(value))
|
|
195
|
+
continue
|
|
196
|
+
arg_names = _CASEFOLD_STR_ARGS.get(type(e))
|
|
197
|
+
if arg_names:
|
|
198
|
+
for arg_name in arg_names:
|
|
199
|
+
value = e.args.get(arg_name)
|
|
200
|
+
if isinstance(value, str):
|
|
201
|
+
e.set(arg_name, value.casefold())
|
|
202
|
+
var_arg_names = _CASEFOLD_VAR_ARGS.get(type(e))
|
|
203
|
+
if var_arg_names:
|
|
204
|
+
for arg_name in var_arg_names:
|
|
205
|
+
value = e.args.get(arg_name)
|
|
206
|
+
if isinstance(value, exp.Var) and isinstance(value.this, str):
|
|
207
|
+
value.set("this", value.this.casefold())
|
|
208
|
+
return node
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _statements(sql: str, dialect: str):
|
|
212
|
+
"""The normalized statements of `sql`, for comparison.
|
|
213
|
+
|
|
214
|
+
`exp.Semicolon` is dropped. It is what sqlglot yields for an empty statement
|
|
215
|
+
-- and, crucially, for a comment that follows the final `;`, which it hangs
|
|
216
|
+
on one of these. `_normalize` strips comments, so such a node normalizes to
|
|
217
|
+
nothing at all; counting it would make `SELECT a;: note` unequal to
|
|
218
|
+
`select a: note ;` purely because the comment moved to the other side of
|
|
219
|
+
the terminator. Since a terminator has to precede a line comment (a `;` after
|
|
220
|
+
one is INSIDE it), that difference is unavoidable and it is not semantics.
|
|
221
|
+
"""
|
|
222
|
+
return [_normalize(e) for e in sqlglot.parse(sql, read=dialect)
|
|
223
|
+
if e is not None and not isinstance(e, exp.Semicolon)]
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _raw_ast_equal(a: str, b: str, dialect: str) -> bool:
|
|
227
|
+
nodes_a = _statements(a, dialect)
|
|
228
|
+
try:
|
|
229
|
+
nodes_b = _statements(b, dialect)
|
|
230
|
+
except (sqlglot.errors.ParseError, sqlglot.errors.TokenError):
|
|
231
|
+
return False # unparseable output is by definition not semantically equal
|
|
232
|
+
return [repr(e) for e in nodes_a] == [repr(e) for e in nodes_b]
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _round_trips(sql: str, dialect: str) -> bool:
|
|
236
|
+
"""Whether sqlglot's own generator output re-parses to the same tree.
|
|
237
|
+
|
|
238
|
+
When it does not, `ast_equal` can never pass for that statement no matter
|
|
239
|
+
what sqlalign emits, so the decline is upstream rather than a renderer bug.
|
|
240
|
+
"""
|
|
241
|
+
try:
|
|
242
|
+
parsed = sqlglot.parse_one(sql, read=dialect)
|
|
243
|
+
return ast_equal(sql, parsed.sql(dialect), dialect)
|
|
244
|
+
except Exception:
|
|
245
|
+
return True # cannot tell; assume the fault is ours
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _first_expression(parsed):
|
|
249
|
+
"""The first real expression of a `sqlglot.parse` result. sqlglot yields a
|
|
250
|
+
`None` entry for a statement that is only a comment or whitespace, so the
|
|
251
|
+
list can be all-None even when the parse itself succeeded."""
|
|
252
|
+
return next((e for e in parsed if e is not None), None)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _dollar_create_parts(text: str, dialect: str):
|
|
256
|
+
"""If `text` is a single dollar-quoted CREATE FUNCTION/PROCEDURE, return its
|
|
257
|
+
`(header, body, tail)` split; else None. Gates the dollar-quote-aware path."""
|
|
258
|
+
parts = plpgsql.split_body(text)
|
|
259
|
+
if parts is None:
|
|
260
|
+
return None
|
|
261
|
+
try:
|
|
262
|
+
node = _first_expression(sqlglot.parse(text, read=dialect))
|
|
263
|
+
except (sqlglot.errors.ParseError, sqlglot.errors.TokenError):
|
|
264
|
+
return None
|
|
265
|
+
return parts if plpgsql.is_dollar_create(node, dialect) else None
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def ast_equal(a: str, b: str, dialect: str) -> bool:
|
|
269
|
+
"""AST-equality safety check. sqlglot sees a `$$…$$` body as one opaque
|
|
270
|
+
string, so raw AST comparison would reject any body reformatting. When both
|
|
271
|
+
sides are dollar-quoted function/procedure bodies, compare structurally
|
|
272
|
+
instead: header+tail as AST, each embedded SQL statement as AST,
|
|
273
|
+
and skeleton statements whitespace/case-insensitively."""
|
|
274
|
+
if dialect == "tsql" and (_GO_LINE_RE.search(a) or _GO_LINE_RE.search(b)):
|
|
275
|
+
# `GO` is a batch separator, not SQL, and sqlglot swallows the FOLLOWING
|
|
276
|
+
# statement into it as a string literal, so a whole-file parse compares
|
|
277
|
+
# nonsense. Compare batch by batch instead, and compare the separators
|
|
278
|
+
# themselves so a dropped or added GO is still caught.
|
|
279
|
+
batches_a, seps_a = _split_go_batches(a)
|
|
280
|
+
batches_b, seps_b = _split_go_batches(b)
|
|
281
|
+
if seps_a != seps_b or len(batches_a) != len(batches_b):
|
|
282
|
+
return False
|
|
283
|
+
return all(_raw_ast_equal(x, y, dialect)
|
|
284
|
+
for x, y in zip(batches_a, batches_b, strict=False))
|
|
285
|
+
|
|
286
|
+
parts_a = _dollar_create_parts(a, dialect)
|
|
287
|
+
parts_b = _dollar_create_parts(b, dialect)
|
|
288
|
+
if parts_a is not None and parts_b is not None:
|
|
289
|
+
return _plpgsql_ast_equal(parts_a, parts_b, dialect)
|
|
290
|
+
return _raw_ast_equal(a, b, dialect)
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _plpgsql_ast_equal(parts_a, parts_b, dialect: str) -> bool:
|
|
294
|
+
head_a, body_a, tail_a = parts_a
|
|
295
|
+
head_b, body_b, tail_b = parts_b
|
|
296
|
+
# header + tail form an empty-body CREATE that parses: compares signature,
|
|
297
|
+
# RETURNS and LANGUAGE while ignoring the (reformatted) body.
|
|
298
|
+
if not _raw_ast_equal(head_a + tail_a, head_b + tail_b, dialect):
|
|
299
|
+
return False
|
|
300
|
+
clauses_a = plpgsql.body_clauses(body_a)
|
|
301
|
+
clauses_b = plpgsql.body_clauses(body_b)
|
|
302
|
+
if len(clauses_a) != len(clauses_b):
|
|
303
|
+
return False
|
|
304
|
+
for x, y in zip(clauses_a, clauses_b, strict=False):
|
|
305
|
+
# Skeleton/plain statements differ only by keyword case + whitespace.
|
|
306
|
+
if plpgsql.norm_skeleton(x) == plpgsql.norm_skeleton(y):
|
|
307
|
+
continue
|
|
308
|
+
# Otherwise it is a reformatted SQL statement (token-level changes such
|
|
309
|
+
# as `<>`→`!=`): compare as ASTs, dropping any leading BEGIN/DECLARE.
|
|
310
|
+
if _raw_ast_equal(plpgsql.strip_struct(x), plpgsql.strip_struct(y), dialect):
|
|
311
|
+
continue
|
|
312
|
+
return False
|
|
313
|
+
return True
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def _split_prefix(text: str) -> tuple[str, str]:
|
|
317
|
+
"""Split leading trivia (whitespace + full comment lines/blocks) from the body.
|
|
318
|
+
|
|
319
|
+
The prefix is everything before the first real SQL token; it is preserved
|
|
320
|
+
verbatim across formatting so leading comments and blank lines survive --
|
|
321
|
+
EXCEPT the horizontal whitespace immediately before that token, which the
|
|
322
|
+
layout owns and re-creates. Keeping it made formatting non-idempotent for
|
|
323
|
+
any style whose first line is indented: `clause_keyword_align="river"` emits
|
|
324
|
+
` SELECT`, and re-formatting that output preserved those two columns as
|
|
325
|
+
prefix and then indented the river on top of them, two columns further right
|
|
326
|
+
every pass. House output starts at column 0, which is why it never showed.
|
|
327
|
+
"""
|
|
328
|
+
i, n = 0, len(text)
|
|
329
|
+
while i < n:
|
|
330
|
+
ch = text[i]
|
|
331
|
+
if ch in " \t\r\n":
|
|
332
|
+
i += 1
|
|
333
|
+
elif text.startswith("--", i):
|
|
334
|
+
nl = text.find("\n", i)
|
|
335
|
+
i = n if nl == -1 else nl + 1
|
|
336
|
+
elif text.startswith("/*", i):
|
|
337
|
+
depth, i = 1, i + 2
|
|
338
|
+
while i < n and depth:
|
|
339
|
+
if text.startswith("/*", i):
|
|
340
|
+
depth, i = depth + 1, i + 2
|
|
341
|
+
elif text.startswith("*/", i):
|
|
342
|
+
depth, i = depth - 1, i + 2
|
|
343
|
+
else:
|
|
344
|
+
i += 1
|
|
345
|
+
else:
|
|
346
|
+
break
|
|
347
|
+
# Give back the indent on the first token's own line: the layout re-creates
|
|
348
|
+
# it, and keeping it here would compound it on every pass.
|
|
349
|
+
indent = len(text[:i]) - len(text[:i].rstrip(" \t"))
|
|
350
|
+
return text[:i - indent], text[i - indent:]
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def _split_trailing_comment(stmt: str) -> tuple[str, str]:
|
|
354
|
+
"""Split a trailing `; <comment>` suffix off `stmt`.
|
|
355
|
+
|
|
356
|
+
Returns (head, suffix) where `head` runs through the terminating ';' and
|
|
357
|
+
`suffix` is everything after it (whitespace + the same-line comment),
|
|
358
|
+
preserved verbatim. If there is no such trailing comment, returns (stmt, "").
|
|
359
|
+
Peeling the comment lets the statement body format cleanly instead of the
|
|
360
|
+
comment (which parses as a stray node) tripping the safety net.
|
|
361
|
+
"""
|
|
362
|
+
m = _TRAILING_COMMENT_RE.search(stmt)
|
|
363
|
+
if not m:
|
|
364
|
+
return stmt, ""
|
|
365
|
+
semi = m.start() # index of the ';'
|
|
366
|
+
return stmt[:semi + 1], stmt[semi + 1:]
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def _format_statement(stmt: str, dialect: str, style: Style) -> str:
|
|
370
|
+
"""Lay out one statement. Raises Unsupported for constructs we pass through."""
|
|
371
|
+
stmt_head, suffix = _split_trailing_comment(stmt)
|
|
372
|
+
prefix, body = _split_prefix(stmt_head)
|
|
373
|
+
# `parse_dialect` layers house parse-time overrides (e.g. DATE_TRUNC's
|
|
374
|
+
# case-preserving unit: see casing.py) on top of the stock dialect; only
|
|
375
|
+
# this one parse (which builds the tree layout_statement renders) uses it.
|
|
376
|
+
node = _first_expression(sqlglot.parse(body, read=parse_dialect(dialect)))
|
|
377
|
+
if node is None:
|
|
378
|
+
return stmt
|
|
379
|
+
|
|
380
|
+
# Comment pre-pass: recover each embedded comment's original
|
|
381
|
+
# style+text from `body`, reattach it to the select-list item it authorially
|
|
382
|
+
# leads/trails (annotating that item's `meta` for select.py to emit), and
|
|
383
|
+
# strip every `node.comments` so render_expr can't re-emit sqlglot's
|
|
384
|
+
# wrong-styled version. Declines (Unsupported) any comment position it does
|
|
385
|
+
# not model -> whole-statement passthrough. A no-op when there are none.
|
|
386
|
+
_comments.process(node, body, dialect)
|
|
387
|
+
|
|
388
|
+
# Layout handlers take the Width knob only; `align` is a pure emit-time
|
|
389
|
+
# choice, so it is applied in render() and never threaded through handlers.
|
|
390
|
+
# Comma position is relocated on the IR (each separator comma is its own
|
|
391
|
+
# tagged Seg) after layout and before render, so alignment resolves against
|
|
392
|
+
# the final segment text: see commas.py for why this is not a text pass.
|
|
393
|
+
lines = layout_statement(node, dialect, style.width)
|
|
394
|
+
lines = apply_comma_position(lines, style.comma_position)
|
|
395
|
+
lines = apply_align_targets(lines, style.align_targets)
|
|
396
|
+
core = render(lines, align=style.align)
|
|
397
|
+
if core.endswith("\n"):
|
|
398
|
+
core = core[:-1] # render always appends one newline
|
|
399
|
+
|
|
400
|
+
body_stripped = body.rstrip()
|
|
401
|
+
trailing_ws = body[len(body_stripped):]
|
|
402
|
+
# A layout may terminate its own statement: T-SQL's BEGIN/END block closes
|
|
403
|
+
# with `END;` whatever the source wrote, so appending unconditionally would
|
|
404
|
+
# produce `END;;`.
|
|
405
|
+
terminator = ";" if body_stripped.endswith(";") and not core.endswith(";") else ""
|
|
406
|
+
if terminator:
|
|
407
|
+
# A `--` comment runs to end of line, so a terminator placed after one
|
|
408
|
+
# is inside it and the statement is left unterminated.
|
|
409
|
+
cut = _terminator_column(core)
|
|
410
|
+
return prefix + core[:cut] + terminator + core[cut:] + trailing_ws + suffix
|
|
411
|
+
return prefix + core + terminator + trailing_ws + suffix
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
def _terminator_column(core: str) -> int:
|
|
415
|
+
"""Where the statement terminator belongs in `core` -- the end, unless the
|
|
416
|
+
text ends INSIDE a line comment, in which case just before it."""
|
|
417
|
+
from sqlalign.layout.comments import scan_comments
|
|
418
|
+
|
|
419
|
+
for c in scan_comments(core):
|
|
420
|
+
if c.style == "line" and c.end >= len(core):
|
|
421
|
+
return len(core[:c.start].rstrip())
|
|
422
|
+
return len(core)
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def _body_is_multiline(piece: str) -> bool:
|
|
426
|
+
"""Whether a statement's own body spans more than one line, ignoring any
|
|
427
|
+
leading blank/comment lines (a single-line statement with a leading `--`
|
|
428
|
+
header is still single-line) and inline trailing comments."""
|
|
429
|
+
lines = piece.split("\n")
|
|
430
|
+
i = 0
|
|
431
|
+
while i < len(lines) and (not lines[i].strip() or lines[i].lstrip().startswith(("--", "/*"))):
|
|
432
|
+
i += 1
|
|
433
|
+
return sum(1 for line in lines[i:] if line.strip()) > 1
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def _join_statements(entries, blanks=None):
|
|
437
|
+
"""Concatenate formatted statement pieces, normalizing the vertical gap
|
|
438
|
+
between them. Inter-statement whitespace
|
|
439
|
+
lives in each statement's own leading prefix (the splitter keeps the
|
|
440
|
+
newline after a `;` with the *following* statement), so the gap before
|
|
441
|
+
statement N is its leading run of newlines. Rule: put exactly one blank
|
|
442
|
+
line between two statements only when BOTH are multi-line (#11's INSERT +
|
|
443
|
+
UPDATE); otherwise preserve the input's adjacency — a single-line
|
|
444
|
+
statement beside anything stays adjacent (#23–#25's grouped utility
|
|
445
|
+
statements, incl. a single-line index next to a wrapped one). `entries` is
|
|
446
|
+
`(text, is_statement, is_multiline)`; trivia (comment-only/whitespace,
|
|
447
|
+
`is_statement` False) neither carries spacing rules nor updates the
|
|
448
|
+
previous-statement state.
|
|
449
|
+
|
|
450
|
+
An explicit `Style.blank_lines_between_statements` (`blanks`) overrides that
|
|
451
|
+
rule with a fixed count between EVERY pair, regardless of shape."""
|
|
452
|
+
pieces = []
|
|
453
|
+
prev_seen = False # a real statement has been emitted
|
|
454
|
+
prev_ml = None # multi-line-ness of the previous real statement
|
|
455
|
+
for text, is_stmt, is_ml in entries:
|
|
456
|
+
if is_stmt and prev_seen:
|
|
457
|
+
lead = len(text) - len(text.lstrip("\n"))
|
|
458
|
+
if lead > 0:
|
|
459
|
+
# The gap can sit on either side: a statement whose final line
|
|
460
|
+
# is a trailing comment ends with its own newline.
|
|
461
|
+
sep = ("\n" * (blanks + 1) if blanks is not None
|
|
462
|
+
else "\n\n" if prev_ml and is_ml else None)
|
|
463
|
+
if sep is not None:
|
|
464
|
+
# `\n` ends the previous line; each further one is a blank line.
|
|
465
|
+
pieces[-1] = pieces[-1].rstrip("\n")
|
|
466
|
+
text = sep + text[lead:]
|
|
467
|
+
pieces.append(text)
|
|
468
|
+
if is_stmt:
|
|
469
|
+
prev_ml, prev_seen = is_ml, True
|
|
470
|
+
return "".join(pieces)
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
def format_sql(text: str, dialect: str = "postgres", style: Style = HOUSE) -> FormatResult:
|
|
474
|
+
"""Format `text`. `style` carries every knob; it is also published as the
|
|
475
|
+
ambient render style for the duration of the call so `render_expr` (called
|
|
476
|
+
from ~57 handler sites) can read output-spelling knobs without every handler
|
|
477
|
+
signature having to carry them."""
|
|
478
|
+
if dialect not in SUPPORTED_DIALECTS:
|
|
479
|
+
# Refuse rather than mis-format. The handlers emit keywords chosen for
|
|
480
|
+
# the verified dialects, and the AST check cannot catch one that is
|
|
481
|
+
# invalid for the target engine: see SUPPORTED_DIALECTS.
|
|
482
|
+
raise ValueError(
|
|
483
|
+
f"unsupported dialect {dialect!r}; sqlalign supports "
|
|
484
|
+
f"{', '.join(sorted(SUPPORTED_DIALECTS))}")
|
|
485
|
+
with render_style(style):
|
|
486
|
+
if not style.protect_templating or not templating.has_templating(text):
|
|
487
|
+
return _format_all(text, dialect, style)
|
|
488
|
+
# Templated SQL (dbt/Jinja) does not parse. Mask each expression with a
|
|
489
|
+
# same-WIDTH placeholder so every alignment column is computed against the
|
|
490
|
+
# real width, format normally, then restore. The whole pipeline: layout,
|
|
491
|
+
# alignment, and the AST safety check: runs on the masked text, which is
|
|
492
|
+
# ordinary SQL; masking is a bijection over identical character positions,
|
|
493
|
+
# so equality of the masked forms is equality of the originals.
|
|
494
|
+
try:
|
|
495
|
+
masked, replacements = templating.mask(text)
|
|
496
|
+
except ValueError as e:
|
|
497
|
+
return FormatResult(text, [f"templating not maskable, passed through: {e}"])
|
|
498
|
+
result = _format_all(masked, dialect, style)
|
|
499
|
+
return FormatResult(templating.unmask(result.text, replacements), result.warnings)
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
def _format_all(text: str, dialect: str, style: Style) -> FormatResult:
|
|
503
|
+
warnings, out, declines = [], [], []
|
|
504
|
+
statements = 0
|
|
505
|
+
pos = 0
|
|
506
|
+
|
|
507
|
+
def emit(piece, is_statement):
|
|
508
|
+
out.append((piece, is_statement, _body_is_multiline(piece)))
|
|
509
|
+
|
|
510
|
+
for stmt in split_statements(text, dialect):
|
|
511
|
+
try:
|
|
512
|
+
if not stmt.strip().rstrip(";").strip():
|
|
513
|
+
emit(stmt, False)
|
|
514
|
+
continue
|
|
515
|
+
if dialect == "tsql" and _GO_ONLY.fullmatch(stmt.strip()):
|
|
516
|
+
emit(stmt, False) # batch separator: trivia, preserved verbatim
|
|
517
|
+
continue
|
|
518
|
+
prefix, _ = _split_prefix(stmt)
|
|
519
|
+
_, skip_suffix = _split_trailing_comment(stmt)
|
|
520
|
+
if _SKIP_RE.search(prefix) or _SKIP_RE.search(skip_suffix):
|
|
521
|
+
# Skip directive: byte-identical, no parse, no layout, no
|
|
522
|
+
# warning. Counted as a decline under its own `kind`, so a report
|
|
523
|
+
# can tell an opt-out from a gap in the tool.
|
|
524
|
+
statements += 1
|
|
525
|
+
declines.append(Decline("skipped", "-- sqlalign: skip"))
|
|
526
|
+
emit(stmt, True)
|
|
527
|
+
continue
|
|
528
|
+
statements += 1
|
|
529
|
+
snippet = stmt.strip()[:40] # how a statement is named in a warning
|
|
530
|
+
try:
|
|
531
|
+
parsed = sqlglot.parse(stmt, read=dialect)
|
|
532
|
+
except (sqlglot.errors.ParseError, sqlglot.errors.TokenError):
|
|
533
|
+
content_off = len(stmt) - len(stmt.lstrip())
|
|
534
|
+
line = text[: pos + content_off].count("\n") + 1
|
|
535
|
+
warnings.append(f"passthrough (parse error line {line}): {snippet}")
|
|
536
|
+
declines.append(Decline("parse", "parse error"))
|
|
537
|
+
emit(stmt, True)
|
|
538
|
+
continue
|
|
539
|
+
else:
|
|
540
|
+
if _first_expression(parsed) is None:
|
|
541
|
+
emit(stmt, False) # comment-only / trivia: silent passthrough
|
|
542
|
+
continue
|
|
543
|
+
# Defense-in-depth (FIX 1): NOTHING a single statement does may abort
|
|
544
|
+
# the file. Layout + render + the AST-equality safety check are wrapped
|
|
545
|
+
# so an unsupported construct, a would-change-semantics render, or an
|
|
546
|
+
# outright bug each degrade to a byte-identical passthrough + a warning.
|
|
547
|
+
# The safety net's guarantee (never emit semantically-changed output)
|
|
548
|
+
# is preserved: a changed/failed render is passed through, never written.
|
|
549
|
+
# Distinct wording per class so a real bug is visible in stderr, not
|
|
550
|
+
# silently indistinguishable from an expected decline.
|
|
551
|
+
try:
|
|
552
|
+
if dialect == "tsql" and _TSQL_LOSSY_TYPES.search(stmt):
|
|
553
|
+
raise Unsupported("tsql: type whose spelling sqlglot cannot preserve")
|
|
554
|
+
node0 = _first_expression(parsed)
|
|
555
|
+
is_dollar = (plpgsql.is_dollar_create(node0, dialect)
|
|
556
|
+
and plpgsql.split_body(stmt) is not None)
|
|
557
|
+
if is_dollar and not style.format_dollar_bodies:
|
|
558
|
+
# Opted out (--no-format-bodies): leave the whole procedure
|
|
559
|
+
# byte-identical. Not a decline, so no warning is emitted.
|
|
560
|
+
emit(stmt, True)
|
|
561
|
+
continue
|
|
562
|
+
if is_dollar:
|
|
563
|
+
formatted = plpgsql.format_create(stmt, node0, dialect, style)
|
|
564
|
+
else:
|
|
565
|
+
formatted = _format_statement(stmt, dialect, style)
|
|
566
|
+
if style.keyword_case != "upper":
|
|
567
|
+
formatted = keywordcase.apply(
|
|
568
|
+
formatted,
|
|
569
|
+
keywordcase.identifier_names(stmt, dialect),
|
|
570
|
+
style.keyword_case)
|
|
571
|
+
if not ast_equal(stmt, formatted, dialect):
|
|
572
|
+
raise SafetyError(f"formatting changed semantics near: {snippet}")
|
|
573
|
+
except Unsupported as exc:
|
|
574
|
+
# The reason rides in the message so `--report` can name the
|
|
575
|
+
# construct, not just count the declines.
|
|
576
|
+
warnings.append(
|
|
577
|
+
f"unsupported construct ({exc}), passed through: {snippet}")
|
|
578
|
+
declines.append(Decline("unsupported", str(exc)))
|
|
579
|
+
emit(stmt, True)
|
|
580
|
+
continue
|
|
581
|
+
except SafetyError:
|
|
582
|
+
# If sqlglot cannot round-trip the input through its own
|
|
583
|
+
# generator, no formatter could satisfy the check and the fault
|
|
584
|
+
# is upstream: report it as such rather than as a semantic
|
|
585
|
+
# change, which means sqlalign's renderer is wrong.
|
|
586
|
+
if not _round_trips(stmt, dialect):
|
|
587
|
+
warnings.append(
|
|
588
|
+
"sqlglot cannot round-trip this statement, passed through "
|
|
589
|
+
f"unformatted: {snippet}")
|
|
590
|
+
declines.append(Decline("upstream", "sqlglot round-trip is unstable"))
|
|
591
|
+
emit(stmt, True)
|
|
592
|
+
continue
|
|
593
|
+
warnings.append(
|
|
594
|
+
f"formatting would change semantics, passed through unformatted: {snippet}")
|
|
595
|
+
declines.append(Decline("safety", "output would differ semantically"))
|
|
596
|
+
emit(stmt, True)
|
|
597
|
+
continue
|
|
598
|
+
except Exception as exc: # a real bug: surface it, but keep formatting the file
|
|
599
|
+
warnings.append(
|
|
600
|
+
"internal formatter error, passed through (please report): "
|
|
601
|
+
f"{type(exc).__name__}: {exc}")
|
|
602
|
+
declines.append(Decline("error", type(exc).__name__))
|
|
603
|
+
emit(stmt, True)
|
|
604
|
+
continue
|
|
605
|
+
emit(formatted, True)
|
|
606
|
+
finally:
|
|
607
|
+
pos += len(stmt)
|
|
608
|
+
return FormatResult(_join_statements(out, style.blank_lines_between_statements),
|
|
609
|
+
warnings, statements, tuple(declines))
|