sqlalign 1.3.0__py3-none-any.whl → 1.3.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/cli.py +24 -4
- sqlalign/formatter.py +103 -17
- sqlalign/gui.py +2 -2
- sqlalign/keywordcase.py +1 -1
- sqlalign/layout/__init__.py +13 -2
- sqlalign/lint.py +21 -9
- sqlalign/plpgsql.py +34 -14
- sqlalign/splitter.py +163 -151
- {sqlalign-1.3.0.dist-info → sqlalign-1.3.1.dist-info}/METADATA +5 -1
- {sqlalign-1.3.0.dist-info → sqlalign-1.3.1.dist-info}/RECORD +13 -13
- {sqlalign-1.3.0.dist-info → sqlalign-1.3.1.dist-info}/WHEEL +1 -1
- {sqlalign-1.3.0.dist-info → sqlalign-1.3.1.dist-info}/entry_points.txt +0 -0
- {sqlalign-1.3.0.dist-info → sqlalign-1.3.1.dist-info}/licenses/LICENSE +0 -0
sqlalign/cli.py
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import argparse
|
|
2
|
+
import contextlib
|
|
2
3
|
import difflib
|
|
3
4
|
import errno
|
|
4
5
|
import os
|
|
@@ -51,7 +52,7 @@ def _write_atomically(path: Path, text: str) -> None:
|
|
|
51
52
|
raise OSError(e.errno, e.strerror, str(target)) from e
|
|
52
53
|
temp = Path(name)
|
|
53
54
|
try:
|
|
54
|
-
with os.fdopen(handle, "w", newline="") as f:
|
|
55
|
+
with os.fdopen(handle, "w", encoding="utf-8", newline="") as f:
|
|
55
56
|
f.write(text)
|
|
56
57
|
shutil.copymode(target, temp)
|
|
57
58
|
os.replace(temp, target)
|
|
@@ -422,7 +423,7 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
422
423
|
print(f"sqlalign: {e}", file=sys.stderr)
|
|
423
424
|
return 2
|
|
424
425
|
try:
|
|
425
|
-
target.write_text(starter)
|
|
426
|
+
target.write_text(starter, encoding="utf-8")
|
|
426
427
|
except OSError as e:
|
|
427
428
|
print(f"sqlalign: {e}", file=sys.stderr)
|
|
428
429
|
return 2
|
|
@@ -513,11 +514,11 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
513
514
|
# Read the raw buffer rather than sys.stdin, whose universal
|
|
514
515
|
# newline translation would rewrite CRLF before the code below
|
|
515
516
|
# gets to notice it.
|
|
516
|
-
original = sys.stdin.buffer.read().decode()
|
|
517
|
+
original = sys.stdin.buffer.read().decode("utf-8")
|
|
517
518
|
else:
|
|
518
519
|
# newline="" disables universal-newline translation so CRLF/CR bytes
|
|
519
520
|
# survive into `original` and can be detected below (v1 is LF-only).
|
|
520
|
-
with path.open(newline="") as f:
|
|
521
|
+
with path.open(encoding="utf-8", newline="") as f:
|
|
521
522
|
original = f.read()
|
|
522
523
|
except OSError as e:
|
|
523
524
|
print(f"sqlalign: {e}", file=sys.stderr)
|
|
@@ -617,6 +618,24 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
617
618
|
return rc
|
|
618
619
|
|
|
619
620
|
|
|
621
|
+
def _utf8_streams() -> None:
|
|
622
|
+
"""Write stdout as UTF-8 with no newline translation, the way files are read.
|
|
623
|
+
|
|
624
|
+
Otherwise stdout uses the locale's encoding and, on Windows, turns every
|
|
625
|
+
`\\n` into `\\r\\n`. `sqlalign -` then reads UTF-8 and writes cp1252 (any
|
|
626
|
+
character cp1252 lacks raises), and an LF file comes back CRLF, so an
|
|
627
|
+
editor filter rewrites every line ending. stderr keeps its line endings
|
|
628
|
+
but is UTF-8 too, so a file name or message cp1252 cannot spell is escaped
|
|
629
|
+
rather than raising.
|
|
630
|
+
"""
|
|
631
|
+
# A replaced stream (an embedder's, a test's) may not be a TextIOWrapper,
|
|
632
|
+
# and a closed or detached one refuses: either way it is left as it is.
|
|
633
|
+
for stream, options in ((sys.stdout, {"newline": ""}),
|
|
634
|
+
(sys.stderr, {"errors": "backslashreplace"})):
|
|
635
|
+
with contextlib.suppress(AttributeError, ValueError):
|
|
636
|
+
stream.reconfigure(encoding="utf-8", **options)
|
|
637
|
+
|
|
638
|
+
|
|
620
639
|
def console() -> int:
|
|
621
640
|
"""The installed command. `main` stays exception-transparent for callers
|
|
622
641
|
that embed it; this wrapper owns the one failure that belongs to being a
|
|
@@ -630,6 +649,7 @@ def console() -> int:
|
|
|
630
649
|
"""
|
|
631
650
|
import os
|
|
632
651
|
|
|
652
|
+
_utf8_streams()
|
|
633
653
|
try:
|
|
634
654
|
return main()
|
|
635
655
|
except BrokenPipeError:
|
sqlalign/formatter.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import re
|
|
2
2
|
from collections import namedtuple
|
|
3
|
+
from functools import cache
|
|
3
4
|
|
|
4
5
|
import sqlglot
|
|
5
6
|
from sqlglot import exp
|
|
@@ -12,12 +13,13 @@ from sqlalign.casing import parse_dialect, render_style, reset_source, set_sourc
|
|
|
12
13
|
from sqlalign.commas import apply_comma_position
|
|
13
14
|
from sqlalign.layout import Unsupported, layout_statement
|
|
14
15
|
from sqlalign.layout import comments as _comments
|
|
15
|
-
from sqlalign.splitter import split_statements
|
|
16
|
+
from sqlalign.splitter import go_lines, split_statements
|
|
16
17
|
from sqlalign.style import HOUSE, SUPPORTED_DIALECTS, Style
|
|
17
18
|
|
|
18
19
|
# `statements` is every top-level statement seen; `declines` is one Decline per
|
|
19
20
|
# statement passed through unformatted. Both carry defaults so the two-field
|
|
20
21
|
# construction used throughout still works.
|
|
22
|
+
BOM = ""
|
|
21
23
|
Decline = namedtuple("Decline", "kind reason")
|
|
22
24
|
FormatResult = namedtuple("FormatResult", "text warnings statements declines",
|
|
23
25
|
defaults=(0, ()))
|
|
@@ -74,18 +76,16 @@ _TSQL_LOSSY_TYPES = re.compile(r"\b(REAL|NTEXT)\b", re.IGNORECASE)
|
|
|
74
76
|
# A lone T-SQL batch separator, once the splitter has isolated it.
|
|
75
77
|
_GO_ONLY = re.compile(r"GO(?:\s+\d+)?", re.IGNORECASE)
|
|
76
78
|
|
|
77
|
-
# A GO line in context, used to split a file into batches for the safety check.
|
|
78
|
-
_GO_LINE_RE = re.compile(r"^[ \t]*GO(?:[ \t]+\d+)?[ \t]*$", re.IGNORECASE | re.MULTILINE)
|
|
79
|
-
|
|
80
|
-
|
|
81
79
|
def _split_go_batches(text: str) -> tuple[list[str], list[str]]:
|
|
82
80
|
"""`(batches, separators)` for a T-SQL file. Separators are normalised so a
|
|
83
|
-
reformatted `go` still matches a source `GO`, while a MISSING one does not.
|
|
81
|
+
reformatted `go` still matches a source `GO`, while a MISSING one does not.
|
|
82
|
+
Cut where the splitter cuts (`go_lines`), so a `GO` inside a string literal
|
|
83
|
+
is content on both sides of the comparison."""
|
|
84
84
|
batches, separators, pos = [], [], 0
|
|
85
|
-
for
|
|
86
|
-
batches.append(text[pos:
|
|
87
|
-
separators.append(
|
|
88
|
-
pos =
|
|
85
|
+
for start, end in go_lines(text):
|
|
86
|
+
batches.append(text[pos:start])
|
|
87
|
+
separators.append(text[start:end].strip().upper())
|
|
88
|
+
pos = end
|
|
89
89
|
batches.append(text[pos:])
|
|
90
90
|
return batches, separators
|
|
91
91
|
|
|
@@ -323,6 +323,80 @@ def _maybe_comment(text: str) -> bool:
|
|
|
323
323
|
return "--" in text or "/*" in text
|
|
324
324
|
|
|
325
325
|
|
|
326
|
+
# String literal tokens, by every prefix sqlglot knows (`N'`, `E'`, `B'`, `X'`,
|
|
327
|
+
# `U&'`).
|
|
328
|
+
_LITERAL_TOKENS = frozenset({
|
|
329
|
+
TokenType.STRING, TokenType.NATIONAL_STRING, TokenType.RAW_STRING,
|
|
330
|
+
TokenType.BYTE_STRING, TokenType.HEX_STRING, TokenType.BIT_STRING,
|
|
331
|
+
TokenType.UNICODE_STRING})
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
@cache
|
|
335
|
+
def _guard_tokenizer(dialect: str):
|
|
336
|
+
"""The dialect's tokenizer with no COMMANDS.
|
|
337
|
+
|
|
338
|
+
After a command keyword (`EXEC`, `CALL`, `GO`, `VACUUM`...) sqlglot hands
|
|
339
|
+
the rest of the statement over as one quoteless STRING token, so the
|
|
340
|
+
literals and comments inside it are not tokens at all. That is where a
|
|
341
|
+
T-SQL job step's `N'...'` lives. Without commands, those words are ordinary
|
|
342
|
+
tokens and everything after them is tokenized like any other SQL.
|
|
343
|
+
"""
|
|
344
|
+
base = sqlglot.Dialect.get_or_raise(dialect).tokenizer_class
|
|
345
|
+
return type(f"Guard{base.__name__}", (base,), {"COMMANDS": set()})
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def opaque_text(sql: str, dialect: str) -> tuple[list[str], list[str]]:
|
|
349
|
+
"""Every string literal and every comment in `sql`, in order, exactly as
|
|
350
|
+
written. Only a literal's prefix letter is case-folded, because keyword
|
|
351
|
+
casing may legitimately turn `n'x'` into `N'x'`.
|
|
352
|
+
|
|
353
|
+
A `$$` body is laid out by the formatter, so it is not compared whole: its
|
|
354
|
+
own literals and comments are, by tokenizing the body in turn. A body that
|
|
355
|
+
does not tokenize (another language) counts as one opaque item, equal on
|
|
356
|
+
both sides when both fail.
|
|
357
|
+
"""
|
|
358
|
+
literals: list[str] = []
|
|
359
|
+
comments: list[str] = []
|
|
360
|
+
for token in _guard_tokenizer(dialect)().tokenize(sql):
|
|
361
|
+
comments += [c.strip() for c in (token.comments or [])]
|
|
362
|
+
if token.token_type is TokenType.HEREDOC_STRING and len(token.text) < len(sql):
|
|
363
|
+
try:
|
|
364
|
+
inner = opaque_text(token.text, dialect)
|
|
365
|
+
except TokenError:
|
|
366
|
+
inner = (["<untokenizable body>"], [])
|
|
367
|
+
literals += inner[0]
|
|
368
|
+
comments += inner[1]
|
|
369
|
+
elif token.token_type in _LITERAL_TOKENS:
|
|
370
|
+
raw = sql[token.start:token.end + 1]
|
|
371
|
+
quote = raw.find("'")
|
|
372
|
+
literals.append(raw[:quote].upper() + raw[quote:])
|
|
373
|
+
return literals, comments
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def file_opaque_equal(a: str, b: str, dialect: str) -> bool:
|
|
377
|
+
"""Whether `b` carries the same string literals and comments as `a`, the
|
|
378
|
+
whole file at once.
|
|
379
|
+
|
|
380
|
+
Every other check runs per statement, on the pieces the splitter cut. A
|
|
381
|
+
wrong cut is invisible to all of them: both sides are cut at the same wrong
|
|
382
|
+
place, and whatever the joiner then puts between the pieces is compared by
|
|
383
|
+
nobody. That is how a `GO` inside a string literal shipped with blank lines
|
|
384
|
+
added inside the literal. This one tokenizes the files whole, with sqlglot
|
|
385
|
+
rather than with the splitter, so it does not share the splitter's mistakes.
|
|
386
|
+
|
|
387
|
+
Input sqlglot cannot tokenize as a whole cannot be checked this way and is
|
|
388
|
+
reported equal: the per-statement checks still apply to it.
|
|
389
|
+
"""
|
|
390
|
+
try:
|
|
391
|
+
before = opaque_text(a, dialect)
|
|
392
|
+
except TokenError:
|
|
393
|
+
return True
|
|
394
|
+
try:
|
|
395
|
+
return before == opaque_text(b, dialect)
|
|
396
|
+
except TokenError:
|
|
397
|
+
return False
|
|
398
|
+
|
|
399
|
+
|
|
326
400
|
def comments_equal(a: str, b: str, dialect: str) -> bool:
|
|
327
401
|
"""Whether `b` carries the same comments as `a`, in the same order.
|
|
328
402
|
|
|
@@ -440,8 +514,8 @@ def _plpgsql_spelling_equal(parts_a, parts_b, dialect: str) -> bool:
|
|
|
440
514
|
if (spelling.token_census(head_a + tail_a, dialect)
|
|
441
515
|
!= spelling.token_census(head_b + tail_b, dialect)):
|
|
442
516
|
return False
|
|
443
|
-
clauses_a = plpgsql.body_clauses(body_a)
|
|
444
|
-
clauses_b = plpgsql.body_clauses(body_b)
|
|
517
|
+
clauses_a = plpgsql.body_clauses(body_a, dialect)
|
|
518
|
+
clauses_b = plpgsql.body_clauses(body_b, dialect)
|
|
445
519
|
if len(clauses_a) != len(clauses_b):
|
|
446
520
|
return False
|
|
447
521
|
return all(spelling.token_census(x, dialect) == spelling.token_census(y, dialect)
|
|
@@ -454,7 +528,7 @@ def ast_equal(a: str, b: str, dialect: str) -> bool:
|
|
|
454
528
|
sides are dollar-quoted function/procedure bodies, compare structurally
|
|
455
529
|
instead: header+tail as AST, each embedded SQL statement as AST,
|
|
456
530
|
and skeleton statements whitespace/case-insensitively."""
|
|
457
|
-
if dialect == "tsql" and (
|
|
531
|
+
if dialect == "tsql" and (go_lines(a) or go_lines(b)):
|
|
458
532
|
# `GO` is a batch separator, not SQL, and sqlglot swallows the FOLLOWING
|
|
459
533
|
# statement into it as a string literal, so a whole-file parse compares
|
|
460
534
|
# nonsense. Compare batch by batch instead, and compare the separators
|
|
@@ -480,8 +554,8 @@ def _plpgsql_ast_equal(parts_a, parts_b, dialect: str) -> bool:
|
|
|
480
554
|
# RETURNS and LANGUAGE while ignoring the (reformatted) body.
|
|
481
555
|
if not _raw_ast_equal(head_a + tail_a, head_b + tail_b, dialect):
|
|
482
556
|
return False
|
|
483
|
-
clauses_a = plpgsql.body_clauses(body_a)
|
|
484
|
-
clauses_b = plpgsql.body_clauses(body_b)
|
|
557
|
+
clauses_a = plpgsql.body_clauses(body_a, dialect)
|
|
558
|
+
clauses_b = plpgsql.body_clauses(body_b, dialect)
|
|
485
559
|
if len(clauses_a) != len(clauses_b):
|
|
486
560
|
return False
|
|
487
561
|
for x, y in zip(clauses_a, clauses_b, strict=False):
|
|
@@ -672,6 +746,12 @@ def format_sql(text: str, dialect: str = "postgres", style: Style = HOUSE,
|
|
|
672
746
|
raise ValueError(
|
|
673
747
|
f"unsupported dialect {dialect!r}; sqlalign supports "
|
|
674
748
|
f"{', '.join(sorted(SUPPORTED_DIALECTS))}")
|
|
749
|
+
if text.startswith(BOM):
|
|
750
|
+
# SSMS saves UTF-8 with a byte-order mark. Left in, it reaches the parser
|
|
751
|
+
# as part of the first statement, which then fails to parse in every such
|
|
752
|
+
# file. It is not SQL, so it is set aside and put back exactly as found.
|
|
753
|
+
result = format_sql(text[len(BOM):], dialect, style, lines)
|
|
754
|
+
return result._replace(text=BOM + result.text)
|
|
675
755
|
with render_style(style):
|
|
676
756
|
if not style.protect_templating or not templating.has_templating(text):
|
|
677
757
|
return _format_all(text, dialect, style, lines)
|
|
@@ -842,5 +922,11 @@ def _format_all(text: str, dialect: str, style: Style,
|
|
|
842
922
|
if literals is not None:
|
|
843
923
|
reset_source(literals)
|
|
844
924
|
pos += len(stmt)
|
|
845
|
-
|
|
846
|
-
|
|
925
|
+
joined = _join_statements(out, style.blank_lines_between_statements)
|
|
926
|
+
if joined != text and not file_opaque_equal(text, joined, dialect):
|
|
927
|
+
reason = "output would change a string literal or comment"
|
|
928
|
+
warnings.append("formatting would change a string literal or comment, file "
|
|
929
|
+
"passed through unformatted (please report)")
|
|
930
|
+
return FormatResult(text, warnings, statements,
|
|
931
|
+
(Decline("safety", reason),) * statements)
|
|
932
|
+
return FormatResult(joined, warnings, statements, tuple(declines))
|
sqlalign/gui.py
CHANGED
|
@@ -717,7 +717,7 @@ def build(root, dialect: str = "postgres") -> dict:
|
|
|
717
717
|
if not path:
|
|
718
718
|
return
|
|
719
719
|
try:
|
|
720
|
-
pathlib.Path(path).write_text(output.get("1.0", "end-1c"))
|
|
720
|
+
pathlib.Path(path).write_text(output.get("1.0", "end-1c"), encoding="utf-8")
|
|
721
721
|
except OSError as e:
|
|
722
722
|
report("save there", e)
|
|
723
723
|
return
|
|
@@ -729,7 +729,7 @@ def build(root, dialect: str = "postgres") -> dict:
|
|
|
729
729
|
if not path:
|
|
730
730
|
return
|
|
731
731
|
try:
|
|
732
|
-
pathlib.Path(path).write_text(as_toml(values, dialect=dialect))
|
|
732
|
+
pathlib.Path(path).write_text(as_toml(values, dialect=dialect), encoding="utf-8")
|
|
733
733
|
except OSError as e:
|
|
734
734
|
report("save there", e)
|
|
735
735
|
|
sqlalign/keywordcase.py
CHANGED
|
@@ -72,7 +72,7 @@ def _body_identifiers(body: str, dialect: str) -> set[str]:
|
|
|
72
72
|
from sqlalign.plpgsql import body_clauses, strip_struct
|
|
73
73
|
|
|
74
74
|
names: set[str] = set()
|
|
75
|
-
for clause in body_clauses(body):
|
|
75
|
+
for clause in body_clauses(body, dialect):
|
|
76
76
|
try:
|
|
77
77
|
parsed = sqlglot.parse(strip_struct(clause), read=dialect)
|
|
78
78
|
except (sqlglot.errors.ParseError, sqlglot.errors.TokenError):
|
sqlalign/layout/__init__.py
CHANGED
|
@@ -82,19 +82,30 @@ def _source_lines(node, dialect: str, anchor: int):
|
|
|
82
82
|
`SET x TO y` is the case this exists for: sqlglot records the assignment but
|
|
83
83
|
not which spelling made it, so its generator always prints `=`, and under
|
|
84
84
|
T-SQL it drops `LOCAL` and `SESSION` outright. There is no layout to
|
|
85
|
-
compute either -- SET is one line -- so the
|
|
85
|
+
compute either -- SET is one line -- so the statement is its own source
|
|
86
86
|
with its keywords cased.
|
|
87
87
|
|
|
88
|
+
Its own source is the statement without the comments around it: the
|
|
89
|
+
caller keeps those and puts them back, so including them here printed
|
|
90
|
+
them twice. A SET inside a procedure body has no source of its own (sqlglot
|
|
91
|
+
records no span for it), so it is printed by the generator, which for the
|
|
92
|
+
T-SQL forms a body holds (`SET NOCOUNT ON`, `SET @x = ...`) is what was
|
|
93
|
+
written; the safety checks decline any case where it is not.
|
|
94
|
+
|
|
88
95
|
Declines when the source is unavailable (nothing set it) or when the node is
|
|
89
96
|
one `sourcecase` cannot separate grammar from content in.
|
|
90
97
|
"""
|
|
91
98
|
from sqlalign import sourcecase
|
|
92
99
|
from sqlalign.casing import source_sql
|
|
100
|
+
from sqlalign.formatter import _split_prefix, _split_trailing_comment
|
|
93
101
|
|
|
102
|
+
if node.parent is not None:
|
|
103
|
+
return [Line(anchor, [Seg(render_expr(node, dialect))])]
|
|
94
104
|
source = source_sql()
|
|
95
105
|
if source is None or not sourcecase.renders_from_source(node):
|
|
96
106
|
raise Unsupported(construct_name(node, dialect))
|
|
97
|
-
|
|
107
|
+
own = _split_trailing_comment(_split_prefix(source)[1])[0]
|
|
108
|
+
cased = sourcecase.recase(own.strip().rstrip(";").strip(), node, dialect,
|
|
98
109
|
active_style().keyword_case)
|
|
99
110
|
return [Line(anchor, [Seg(cased)])]
|
|
100
111
|
|
sqlalign/lint.py
CHANGED
|
@@ -16,6 +16,7 @@ the wrong kind of helpful. The generated config is the fallback for when there
|
|
|
16
16
|
is nothing to respect, and it says so on stderr the first time.
|
|
17
17
|
"""
|
|
18
18
|
import json
|
|
19
|
+
import os
|
|
19
20
|
import subprocess
|
|
20
21
|
import sys
|
|
21
22
|
import tempfile
|
|
@@ -58,13 +59,25 @@ def discovered_config(path: Path) -> Path | None:
|
|
|
58
59
|
if name == ".sqlfluff" or name == ".sqlfluffignore":
|
|
59
60
|
return candidate
|
|
60
61
|
try:
|
|
61
|
-
if "sqlfluff" in candidate.read_text():
|
|
62
|
+
if "sqlfluff" in candidate.read_text(encoding="utf-8", errors="replace"):
|
|
62
63
|
return candidate
|
|
63
64
|
except OSError:
|
|
64
65
|
continue
|
|
65
66
|
return None
|
|
66
67
|
|
|
67
68
|
|
|
69
|
+
def _sqlfluff(*args: str) -> subprocess.CompletedProcess:
|
|
70
|
+
"""Run sqlfluff in UTF-8 mode and read its output as UTF-8.
|
|
71
|
+
|
|
72
|
+
The scratch files are written as UTF-8. Without UTF-8 mode a Windows child
|
|
73
|
+
reads them, and prints its findings, in the locale's code page, so a
|
|
74
|
+
non-ASCII name in a finding would come back garbled or not at all.
|
|
75
|
+
"""
|
|
76
|
+
env = {**os.environ, "PYTHONUTF8": "1", "PYTHONIOENCODING": "utf-8"}
|
|
77
|
+
return subprocess.run([sys.executable, "-m", "sqlfluff", *args], capture_output=True,
|
|
78
|
+
encoding="utf-8", errors="replace", env=env)
|
|
79
|
+
|
|
80
|
+
|
|
68
81
|
def lint(path: Path, text: str, style, dialect: str,
|
|
69
82
|
explicit_config: Path | None = None) -> tuple[int, str, str]:
|
|
70
83
|
"""Lint `text` as though it were `path`. Returns (returncode, stdout, stderr).
|
|
@@ -87,19 +100,19 @@ def lint(path: Path, text: str, style, dialect: str,
|
|
|
87
100
|
# Nothing to respect: fall back to the config that keeps the two tools
|
|
88
101
|
# from contradicting each other.
|
|
89
102
|
generated = tempfile.NamedTemporaryFile( # noqa: SIM115 - closed below
|
|
90
|
-
"w", suffix=".sqlfluff", delete=False)
|
|
103
|
+
"w", encoding="utf-8", suffix=".sqlfluff", delete=False)
|
|
91
104
|
generated.write(sqlfluff_config(style, dialect))
|
|
92
105
|
generated.close()
|
|
93
106
|
args += ["--config", generated.name]
|
|
94
107
|
|
|
95
108
|
tmp = None
|
|
96
109
|
try:
|
|
97
|
-
with tempfile.NamedTemporaryFile("w",
|
|
110
|
+
with tempfile.NamedTemporaryFile("w", encoding="utf-8", newline="",
|
|
111
|
+
dir=path.parent, suffix=".sql",
|
|
98
112
|
prefix=f".{path.stem}.sqlalign-", delete=False) as f:
|
|
99
113
|
f.write(text)
|
|
100
114
|
tmp = Path(f.name)
|
|
101
|
-
result =
|
|
102
|
-
capture_output=True, text=True)
|
|
115
|
+
result = _sqlfluff(*args, str(tmp))
|
|
103
116
|
code, out, err = result.returncode, result.stdout, result.stderr
|
|
104
117
|
|
|
105
118
|
# sqlfluff cannot see inside a `$$` body: to its parser the whole
|
|
@@ -141,14 +154,13 @@ def _lint_bodies(text: str, args: list[str], path: Path, dialect: str) -> str:
|
|
|
141
154
|
view = bodylint.lint_view(text, dialect)
|
|
142
155
|
tmp = None
|
|
143
156
|
try:
|
|
144
|
-
with tempfile.NamedTemporaryFile("w",
|
|
157
|
+
with tempfile.NamedTemporaryFile("w", encoding="utf-8", newline="",
|
|
158
|
+
dir=path.parent, suffix=".sql",
|
|
145
159
|
prefix=f".{path.stem}.sqlalign-body-",
|
|
146
160
|
delete=False) as f:
|
|
147
161
|
f.write(view)
|
|
148
162
|
tmp = Path(f.name)
|
|
149
|
-
result =
|
|
150
|
-
[sys.executable, "-m", "sqlfluff", *args, "--format", "json", str(tmp)],
|
|
151
|
-
capture_output=True, text=True)
|
|
163
|
+
result = _sqlfluff(*args, "--format", "json", str(tmp))
|
|
152
164
|
try:
|
|
153
165
|
payload = json.loads(result.stdout or "[]")
|
|
154
166
|
except json.JSONDecodeError: # sqlfluff failed before linting
|
sqlalign/plpgsql.py
CHANGED
|
@@ -89,14 +89,14 @@ def is_dollar_create(node, dialect: str) -> bool:
|
|
|
89
89
|
and isinstance(node.args.get("expression"), exp.Heredoc))
|
|
90
90
|
|
|
91
91
|
|
|
92
|
-
def body_clauses(body: str) -> list[str]:
|
|
92
|
+
def body_clauses(body: str, dialect: str) -> list[str]:
|
|
93
93
|
"""Split a plpgsql body into `;`-terminated clauses (string/comment/dollar
|
|
94
94
|
aware, via the shared splitter), stripped and with the `;` removed; empty
|
|
95
95
|
clauses dropped. `BEGIN`/`IF … THEN` keywords stay glued to the statement
|
|
96
96
|
that follows them, so the input body and the formatted body split into the
|
|
97
97
|
same clause sequence — which the safety net relies on."""
|
|
98
98
|
out = []
|
|
99
|
-
for part in split_statements(body):
|
|
99
|
+
for part in split_statements(body, dialect):
|
|
100
100
|
c = part.strip()
|
|
101
101
|
if c.endswith(";"):
|
|
102
102
|
c = c[:-1].strip()
|
|
@@ -160,17 +160,20 @@ def _keywords(dialect: str) -> frozenset[str]:
|
|
|
160
160
|
return frozenset(k for k in Tokenizer(dialect=dialect).KEYWORDS if " " not in k) | _PLPGSQL_KW
|
|
161
161
|
|
|
162
162
|
|
|
163
|
-
def
|
|
164
|
-
"""
|
|
165
|
-
inside it),
|
|
166
|
-
|
|
163
|
+
def _ws_pieces(text: str) -> list[str]:
|
|
164
|
+
"""`text` cut into whitespace runs and the tokens between them, treating a
|
|
165
|
+
quoted span as opaque (never split inside it). Joined, they are `text`."""
|
|
166
|
+
pieces, cur, i, n = [], [], 0, len(text)
|
|
167
167
|
while i < n:
|
|
168
168
|
ch = text[i]
|
|
169
169
|
if ch.isspace():
|
|
170
170
|
if cur:
|
|
171
|
-
|
|
171
|
+
pieces.append("".join(cur))
|
|
172
172
|
cur = []
|
|
173
|
-
|
|
173
|
+
start = i
|
|
174
|
+
while i < n and text[i].isspace():
|
|
175
|
+
i += 1
|
|
176
|
+
pieces.append(text[start:i])
|
|
174
177
|
elif ch in ("'", '"'):
|
|
175
178
|
cur.append(ch)
|
|
176
179
|
i += 1
|
|
@@ -188,8 +191,14 @@ def _tokenize_ws(text: str) -> list[str]:
|
|
|
188
191
|
cur.append(ch)
|
|
189
192
|
i += 1
|
|
190
193
|
if cur:
|
|
191
|
-
|
|
192
|
-
return
|
|
194
|
+
pieces.append("".join(cur))
|
|
195
|
+
return pieces
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _tokenize_ws(text: str) -> list[str]:
|
|
199
|
+
"""Whitespace-split `text`, treating a quoted span as opaque (never split
|
|
200
|
+
inside it), so string literals survive keyword casing intact."""
|
|
201
|
+
return [p for p in _ws_pieces(text) if not p.isspace()]
|
|
193
202
|
|
|
194
203
|
|
|
195
204
|
def _upper_kw(text: str, dialect: str) -> str:
|
|
@@ -199,6 +208,14 @@ def _upper_kw(text: str, dialect: str) -> str:
|
|
|
199
208
|
return " ".join(t.upper() if t.upper() in kw else t for t in _tokenize_ws(text))
|
|
200
209
|
|
|
201
210
|
|
|
211
|
+
def _upper_kw_in_place(text: str, dialect: str) -> str:
|
|
212
|
+
"""`_upper_kw`'s casing with the author's whitespace kept: line breaks,
|
|
213
|
+
indentation and all. A body statement the engine does not lay out is the
|
|
214
|
+
author's layout, so it is cased and never re-flowed."""
|
|
215
|
+
kw = _keywords(dialect)
|
|
216
|
+
return "".join(p.upper() if p.upper() in kw else p for p in _ws_pieces(text))
|
|
217
|
+
|
|
218
|
+
|
|
202
219
|
def _own_line_comments(text: str) -> tuple[list[str], str]:
|
|
203
220
|
"""Leading comment lines peeled off `text`, and what remains.
|
|
204
221
|
|
|
@@ -266,7 +283,10 @@ def _split_comment(text: str) -> tuple[str, str | None]:
|
|
|
266
283
|
return text, None
|
|
267
284
|
|
|
268
285
|
|
|
269
|
-
def _render_plain(text: str, dialect: str) -> str:
|
|
286
|
+
def _render_plain(text: str, dialect: str, *, keep_layout: bool = False) -> str:
|
|
287
|
+
"""A clause the engine does not lay out, keyword-cased. Joined onto one line
|
|
288
|
+
where the caller lays it out (an IF condition, a branch); with `keep_layout`,
|
|
289
|
+
a statement of its own, it keeps the author's line breaks."""
|
|
270
290
|
leading, text = _own_line_comments(text.strip())
|
|
271
291
|
if not text:
|
|
272
292
|
# The clause is nothing but comments -- verbatim, and no terminator:
|
|
@@ -276,7 +296,7 @@ def _render_plain(text: str, dialect: str) -> str:
|
|
|
276
296
|
if text.lower().startswith("get diagnostics"):
|
|
277
297
|
rendered = _render_get_diagnostics(text)
|
|
278
298
|
else:
|
|
279
|
-
rendered = _upper_kw(text, dialect)
|
|
299
|
+
rendered = (_upper_kw_in_place if keep_layout else _upper_kw)(text, dialect)
|
|
280
300
|
if leading:
|
|
281
301
|
rendered = "\n".join([*leading, rendered]) if rendered else "\n".join(leading)
|
|
282
302
|
if comment is None:
|
|
@@ -405,7 +425,7 @@ def _render_stmt(raw: str, dialect: str, style) -> str:
|
|
|
405
425
|
# the final backstop). No fixture exercises those constructs.
|
|
406
426
|
if _is_sql(raw, dialect):
|
|
407
427
|
return _render_sql_stmt(raw, dialect, style)
|
|
408
|
-
return _terminate(_render_plain(raw, dialect))
|
|
428
|
+
return _terminate(_render_plain(raw, dialect, keep_layout=True))
|
|
409
429
|
|
|
410
430
|
|
|
411
431
|
def _terminate(rendered: str) -> str:
|
|
@@ -545,7 +565,7 @@ def _above(comments: list[str], element: str) -> str:
|
|
|
545
565
|
|
|
546
566
|
|
|
547
567
|
def _parse_body_elements(body: str, dialect: str, style, language="plpgsql") -> list[str]:
|
|
548
|
-
cls = body_clauses(body)
|
|
568
|
+
cls = body_clauses(body, dialect)
|
|
549
569
|
if language == "sql":
|
|
550
570
|
# A `LANGUAGE sql` body is a statement list and nothing else: no
|
|
551
571
|
# DECLARE, no BEGIN, no END. Each statement goes through the same
|
sqlalign/splitter.py
CHANGED
|
@@ -6,6 +6,9 @@ engine declines is emitted from its part verbatim, so a part that lost
|
|
|
6
6
|
a character would corrupt the passthrough.
|
|
7
7
|
"""
|
|
8
8
|
import re
|
|
9
|
+
from functools import cache
|
|
10
|
+
|
|
11
|
+
import sqlglot
|
|
9
12
|
|
|
10
13
|
# Dollar-quote tag: bare `$$`, or `$tag$` where tag starts with a letter/underscore
|
|
11
14
|
# and may contain digits thereafter (e.g. `$fn1$`): matches Postgres's identifier
|
|
@@ -44,194 +47,203 @@ def split_statements(text: str, dialect: str = "postgres") -> list[str]:
|
|
|
44
47
|
Under T-SQL a standalone `GO` line additionally ends a batch, and is returned
|
|
45
48
|
as its own part so the caller can pass it through verbatim.
|
|
46
49
|
"""
|
|
47
|
-
if dialect
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
parts.extend(split_statements(text[pos:]))
|
|
62
|
-
return parts
|
|
63
|
-
return _split_on_semicolons(text)
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
# The routine-defining statements whose body is a BEGIN...END block. Only these
|
|
67
|
-
# get block tracking, deliberately: a general "count BEGIN and END" scan is unsafe
|
|
68
|
-
# because `CASE ... END` shares the END keyword, and `BEGIN TRANSACTION` opens a
|
|
69
|
-
# block that never has a matching END at all. Confining the scan to a routine body
|
|
70
|
-
# keeps both hazards out of ordinary statements.
|
|
71
|
-
_ROUTINE_START = re.compile(
|
|
72
|
-
r"\bCREATE\s+(?:OR\s+ALTER\s+)?(?:PROCEDURE|PROC|FUNCTION|TRIGGER)\b", re.IGNORECASE)
|
|
73
|
-
_WORD_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
|
|
74
|
-
|
|
50
|
+
if dialect != "tsql":
|
|
51
|
+
return _split_on_semicolons(text, backslash=backslash_escapes(dialect),
|
|
52
|
+
brackets=False)
|
|
53
|
+
# `GO` ends a batch before anything else is decided: a routine never spans
|
|
54
|
+
# one, and the SSMS header (`SET ANSI_NULLS ON` / `GO` / ...) is its own
|
|
55
|
+
# batches, not the start of the procedure below it.
|
|
56
|
+
parts: list[str] = []
|
|
57
|
+
pos = 0
|
|
58
|
+
for start, end in go_lines(text):
|
|
59
|
+
parts.extend(_split_tsql_batch(text[pos:start]))
|
|
60
|
+
parts.append(text[start:end]) # the GO line itself
|
|
61
|
+
pos = end
|
|
62
|
+
parts.extend(_split_tsql_batch(text[pos:]))
|
|
63
|
+
return parts
|
|
75
64
|
|
|
76
|
-
def _split_tsql_blocks(text: str) -> list[str] | None:
|
|
77
|
-
"""Split `text` keeping each `CREATE PROCEDURE ... BEGIN ... END` whole.
|
|
78
65
|
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
66
|
+
@cache
|
|
67
|
+
def backslash_escapes(dialect: str) -> bool:
|
|
68
|
+
"""Whether a backslash escapes a quote inside an ordinary `'...'` string.
|
|
82
69
|
|
|
83
|
-
|
|
84
|
-
|
|
70
|
+
Redshift says yes and Postgres says no (standard_conforming_strings), so
|
|
71
|
+
`'it\\'s'` is one string in the first and a closed string plus a stray
|
|
72
|
+
quote in the second. Asked of sqlglot's tokenizer rather than listed here, so
|
|
73
|
+
the splitter and the parser cannot disagree about where a string ends.
|
|
85
74
|
"""
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
parts: list[str] = []
|
|
89
|
-
pos = 0
|
|
90
|
-
while True:
|
|
91
|
-
match = _ROUTINE_START.search(text, pos)
|
|
92
|
-
if match is None:
|
|
93
|
-
if pos < len(text):
|
|
94
|
-
parts.extend(_split_on_semicolons(text[pos:]))
|
|
95
|
-
return parts
|
|
96
|
-
if match.start() > pos:
|
|
97
|
-
parts.extend(_split_on_semicolons(text[pos:match.start()]))
|
|
98
|
-
end = _routine_end(text, match.start())
|
|
99
|
-
parts.append(text[match.start():end])
|
|
100
|
-
pos = end
|
|
75
|
+
return "\\" in sqlglot.Dialect.get_or_raise(dialect).tokenizer_class.STRING_ESCAPES
|
|
76
|
+
|
|
101
77
|
|
|
78
|
+
def go_lines(text: str) -> list[tuple[int, int]]:
|
|
79
|
+
"""`(start, end)` of every T-SQL `GO` line that is not inside a string,
|
|
80
|
+
quoted identifier or comment.
|
|
102
81
|
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
82
|
+
SQL Agent job steps and dynamic SQL carry whole multi-batch scripts in
|
|
83
|
+
`N'...'` literals, `GO` lines included. A line-anchored regex over the raw
|
|
84
|
+
text cut the file there, and the blank-line rule between the fragments then
|
|
85
|
+
added newlines inside the literal: changed data. The splitter and the
|
|
86
|
+
safety check both ask this function, so neither can see a `GO` the other
|
|
87
|
+
does not.
|
|
88
|
+
"""
|
|
89
|
+
spans: list[tuple[int, int]] = []
|
|
90
|
+
i, n = 0, len(text)
|
|
110
91
|
while i < n:
|
|
111
|
-
|
|
112
|
-
if
|
|
113
|
-
i =
|
|
92
|
+
end = _region_end(text, i, backslash=False, brackets=True)
|
|
93
|
+
if end is not None:
|
|
94
|
+
i = end
|
|
114
95
|
continue
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
i
|
|
96
|
+
if (i == 0 or text[i - 1] == "\n") and (match := _GO_LINE.match(text, i)):
|
|
97
|
+
spans.append(match.span())
|
|
98
|
+
i = match.end()
|
|
118
99
|
continue
|
|
119
|
-
word = word_match.group(0).upper()
|
|
120
|
-
i = word_match.end()
|
|
121
|
-
if word == "CASE":
|
|
122
|
-
stack.append("CASE")
|
|
123
|
-
elif word == "BEGIN":
|
|
124
|
-
# BEGIN TRANSACTION/TRAN opens no block that an END will close.
|
|
125
|
-
following = _WORD_RE.match(text, _skip_spaces(text, i))
|
|
126
|
-
if following and following.group(0).upper() in ("TRANSACTION", "TRAN"):
|
|
127
|
-
continue
|
|
128
|
-
stack.append("BEGIN")
|
|
129
|
-
elif word == "END" and stack:
|
|
130
|
-
closed = stack.pop()
|
|
131
|
-
# Only the OUTERMOST BEGIN ends the routine; an END that closed a
|
|
132
|
-
# CASE, or one that leaves the stack non-empty, is interior.
|
|
133
|
-
if closed == "BEGIN" and not stack:
|
|
134
|
-
tail = _skip_spaces(text, i)
|
|
135
|
-
return tail + 1 if tail < n and text[tail] == ";" else i
|
|
136
|
-
return n
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
def _skip_spaces(text: str, i: int) -> int:
|
|
140
|
-
while i < len(text) and text[i] in " \t\r\n":
|
|
141
100
|
i += 1
|
|
142
|
-
return
|
|
101
|
+
return spans
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
# The statements that must start a T-SQL batch and run to its end: everything
|
|
105
|
+
# after `CREATE PROCEDURE` up to the next `GO` is the procedure, `;` or not.
|
|
106
|
+
# CREATE VIEW has the same rule but no `;` inside, so the plain scan already
|
|
107
|
+
# keeps it whole.
|
|
108
|
+
_ROUTINE_START = re.compile(
|
|
109
|
+
r"CREATE\s+(?:OR\s+ALTER\s+)?(?:PROCEDURE|PROC|FUNCTION|TRIGGER)\b", re.IGNORECASE)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _split_tsql_batch(batch: str) -> list[str]:
|
|
113
|
+
"""Split one T-SQL batch. A routine is the rest of its batch.
|
|
114
|
+
|
|
115
|
+
That is how SQL Server reads it, and it is the only reading that does not
|
|
116
|
+
need to know where the body ends: an `END` that empties a BEGIN stack is
|
|
117
|
+
not it (`AS BEGIN TRY ... END TRY BEGIN CATCH ... END CATCH` has no outer
|
|
118
|
+
BEGIN), and neither is any `;`. The comments above the routine stay with
|
|
119
|
+
it, as they do with any statement, so `-- sqlalign: skip` covers it.
|
|
120
|
+
"""
|
|
121
|
+
start = _routine_start(batch)
|
|
122
|
+
if start is None:
|
|
123
|
+
return _split_on_semicolons(batch, backslash=False, brackets=True)
|
|
124
|
+
before = _split_on_semicolons(batch[:start], backslash=False, brackets=True)
|
|
125
|
+
if before and not _has_semicolon(before[-1]):
|
|
126
|
+
start -= len(before.pop()) # only comments: they lead the routine
|
|
127
|
+
return [*before, batch[start:]]
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _routine_start(batch: str) -> int | None:
|
|
131
|
+
"""Where a statement opening with `CREATE PROCEDURE|FUNCTION|TRIGGER`
|
|
132
|
+
starts in the batch, or None.
|
|
133
|
+
|
|
134
|
+
Only at the start of a statement -- after the batch start or a `;`, with
|
|
135
|
+
nothing but whitespace and comments between -- so `GRANT CREATE PROCEDURE`
|
|
136
|
+
is not one, and neither is the phrase inside a comment or a string.
|
|
137
|
+
"""
|
|
138
|
+
at_start = True
|
|
139
|
+
i, n = 0, len(batch)
|
|
140
|
+
while i < n:
|
|
141
|
+
end = _region_end(batch, i, backslash=False, brackets=True)
|
|
142
|
+
if end is not None:
|
|
143
|
+
if not batch.startswith(("--", "/*"), i):
|
|
144
|
+
at_start = False # a string or quoted name is statement text
|
|
145
|
+
i = end
|
|
146
|
+
continue
|
|
147
|
+
ch = batch[i]
|
|
148
|
+
if ch == ";":
|
|
149
|
+
at_start = True
|
|
150
|
+
elif not ch.isspace():
|
|
151
|
+
if at_start and _ROUTINE_START.match(batch, i):
|
|
152
|
+
return i
|
|
153
|
+
at_start = False
|
|
154
|
+
i += 1
|
|
155
|
+
return None
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _has_semicolon(text: str) -> bool:
|
|
159
|
+
"""Whether `text` holds a `;` outside strings, quoted names and comments."""
|
|
160
|
+
i, n = 0, len(text)
|
|
161
|
+
while i < n:
|
|
162
|
+
end = _region_end(text, i, backslash=False, brackets=True)
|
|
163
|
+
if end is not None:
|
|
164
|
+
i = end
|
|
165
|
+
elif text[i] == ";":
|
|
166
|
+
return True
|
|
167
|
+
else:
|
|
168
|
+
i += 1
|
|
169
|
+
return False
|
|
170
|
+
|
|
143
171
|
|
|
172
|
+
def _region_end(text: str, i: int, *, backslash: bool, brackets: bool) -> int | None:
|
|
173
|
+
"""Index just past the string, quoted identifier, comment or dollar quote
|
|
174
|
+
that opens at `i`, or None when nothing opaque opens there. An unterminated
|
|
175
|
+
region runs to the end of the text.
|
|
144
176
|
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
177
|
+
The one definition of where these regions are, so splitting on `;`, finding
|
|
178
|
+
`GO` lines and finding a routine's `END` all agree. `backslash` says whether
|
|
179
|
+
`\\'` escapes a quote in an ordinary string (see `backslash_escapes`); an
|
|
180
|
+
`E'...'` string honours it in every dialect. `brackets` says whether `[`
|
|
181
|
+
opens a quoted identifier, which is T-SQL only: elsewhere it is an array
|
|
182
|
+
subscript or constructor, and `a[b[1]]` would read `]]` as an escape.
|
|
183
|
+
"""
|
|
148
184
|
n = len(text)
|
|
149
185
|
ch = text[i]
|
|
150
|
-
if ch == "'":
|
|
186
|
+
if ch == "'": # standard or E-prefixed string
|
|
187
|
+
# Only treat a preceding e/E as the E-prefix if it isn't itself the
|
|
188
|
+
# tail of a longer identifier (e.g. `CASE'x'` is CASE, not E'x').
|
|
189
|
+
prev2 = text[i - 2] if i > 1 else ""
|
|
190
|
+
escapes = backslash or (i > 0 and text[i - 1] in "eE"
|
|
191
|
+
and not _IDENT_CHARS.match(prev2))
|
|
151
192
|
i += 1
|
|
152
193
|
while i < n:
|
|
194
|
+
if escapes and text[i] == "\\" and i + 1 < n:
|
|
195
|
+
i += 2
|
|
196
|
+
continue
|
|
153
197
|
if text[i] == "'" and not (i + 1 < n and text[i + 1] == "'"):
|
|
154
198
|
return i + 1
|
|
155
199
|
i += 2 if text[i] == "'" else 1
|
|
156
200
|
return n
|
|
157
|
-
if ch == '"':
|
|
158
|
-
|
|
159
|
-
return n if
|
|
160
|
-
if ch == "[":
|
|
201
|
+
if ch == '"': # quoted identifier
|
|
202
|
+
close = text.find('"', i + 1)
|
|
203
|
+
return n if close == -1 else close + 1
|
|
204
|
+
if ch == "[" and brackets:
|
|
205
|
+
# T-SQL bracket-quoted identifier: [my col], and `]]` escapes a literal
|
|
206
|
+
# `]` inside one. Without this a bracketed name containing a semicolon
|
|
207
|
+
# (`[my;col]`) splits mid-identifier: lossless, so the file survives,
|
|
208
|
+
# but every fragment then fails to parse and the file goes unformatted.
|
|
161
209
|
i += 1
|
|
162
210
|
while i < n:
|
|
163
211
|
if text[i] == "]":
|
|
164
|
-
if i + 1 < n and text[i + 1] == "]":
|
|
212
|
+
if i + 1 < n and text[i + 1] == "]": # ]] -> escaped
|
|
165
213
|
i += 2
|
|
166
214
|
continue
|
|
167
215
|
return i + 1
|
|
168
216
|
i += 1
|
|
169
217
|
return n
|
|
170
218
|
if text.startswith("--", i):
|
|
171
|
-
|
|
172
|
-
return n if
|
|
219
|
+
nl = text.find("\n", i)
|
|
220
|
+
return n if nl == -1 else nl
|
|
173
221
|
if text.startswith("/*", i):
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
222
|
+
depth, i = 1, i + 2
|
|
223
|
+
while i < n and depth:
|
|
224
|
+
if text.startswith("/*", i):
|
|
225
|
+
depth, i = depth + 1, i + 2
|
|
226
|
+
elif text.startswith("*/", i):
|
|
227
|
+
depth, i = depth - 1, i + 2
|
|
228
|
+
else:
|
|
229
|
+
i += 1
|
|
230
|
+
return i
|
|
231
|
+
if ch == "$" and (m := DOLLAR_TAG.match(text, i)):
|
|
232
|
+
tag = m.group(0)
|
|
233
|
+
end = text.find(tag, m.end())
|
|
234
|
+
return n if end == -1 else end + len(tag)
|
|
235
|
+
return None
|
|
177
236
|
|
|
178
237
|
|
|
179
|
-
def _split_on_semicolons(text: str) -> list[str]:
|
|
238
|
+
def _split_on_semicolons(text: str, *, backslash: bool, brackets: bool) -> list[str]:
|
|
180
239
|
parts: list[str] = []
|
|
181
240
|
start = i = 0
|
|
182
241
|
n = len(text)
|
|
183
242
|
while i < n:
|
|
184
243
|
ch = text[i]
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
# Only treat a preceding e/E as the E-prefix if it isn't itself the
|
|
189
|
-
# tail of a longer identifier (e.g. `CASE'x'` is CASE, not E'x').
|
|
190
|
-
prev = text[i - 1] if i > 0 else ""
|
|
191
|
-
prev2 = text[i - 2] if i > 1 else ""
|
|
192
|
-
is_estring = prev in "eE" and not _IDENT_CHARS.match(prev2)
|
|
193
|
-
i += 1
|
|
194
|
-
while i < n:
|
|
195
|
-
if is_estring and text[i] == "\\" and i + 1 < n:
|
|
196
|
-
i += 2
|
|
197
|
-
continue
|
|
198
|
-
if text[i] == "'" and not (i + 1 < n and text[i + 1] == "'"):
|
|
199
|
-
break
|
|
200
|
-
i += 2 if text[i] == "'" else 1
|
|
201
|
-
i += 1
|
|
202
|
-
elif ch == '"': # quoted identifier
|
|
203
|
-
close = text.find('"', i + 1)
|
|
204
|
-
i = n if close == -1 else close + 1
|
|
205
|
-
elif ch == "[":
|
|
206
|
-
# T-SQL bracket-quoted identifier: [my col], and `]]` escapes a literal
|
|
207
|
-
# `]` inside one. Without this a bracketed name containing a semicolon
|
|
208
|
-
# (`[my;col]`) splits mid-identifier: lossless, so the file survives,
|
|
209
|
-
# but every fragment then fails to parse and the file goes unformatted.
|
|
210
|
-
i += 1
|
|
211
|
-
while i < n:
|
|
212
|
-
if text[i] == "]":
|
|
213
|
-
if i + 1 < n and text[i + 1] == "]": # ]] -> escaped
|
|
214
|
-
i += 2
|
|
215
|
-
continue
|
|
216
|
-
i += 1
|
|
217
|
-
break
|
|
218
|
-
i += 1
|
|
219
|
-
elif text.startswith("--", i):
|
|
220
|
-
nl = text.find("\n", i)
|
|
221
|
-
i = n if nl == -1 else nl + 1
|
|
222
|
-
elif text.startswith("/*", i):
|
|
223
|
-
depth, i = 1, i + 2
|
|
224
|
-
while i < n and depth:
|
|
225
|
-
if text.startswith("/*", i):
|
|
226
|
-
depth, i = depth + 1, i + 2
|
|
227
|
-
elif text.startswith("*/", i):
|
|
228
|
-
depth, i = depth - 1, i + 2
|
|
229
|
-
else:
|
|
230
|
-
i += 1
|
|
231
|
-
elif ch == "$" and (m := DOLLAR_TAG.match(text, i)):
|
|
232
|
-
tag = m.group(0)
|
|
233
|
-
end = text.find(tag, m.end())
|
|
234
|
-
i = n if end == -1 else end + len(tag)
|
|
244
|
+
opaque_end = _region_end(text, i, backslash=backslash, brackets=brackets)
|
|
245
|
+
if opaque_end is not None:
|
|
246
|
+
i = opaque_end
|
|
235
247
|
elif ch == ";":
|
|
236
248
|
i += 1
|
|
237
249
|
while i < n and text[i] in " \t": # keep same-line trailer with the statement
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: sqlalign
|
|
3
|
-
Version: 1.3.
|
|
3
|
+
Version: 1.3.1
|
|
4
4
|
Summary: A SQL formatter that cannot change what your SQL means
|
|
5
5
|
Project-URL: Homepage, https://sqlalign.lumaru.app/
|
|
6
6
|
Project-URL: Documentation, https://sqlalign.lumaru.app/v1/
|
|
@@ -425,6 +425,10 @@ not cover.
|
|
|
425
425
|
variants, cursors/`FOR` loops in plpgsql bodies, comments buried inside an
|
|
426
426
|
expression) pass through byte-identical with a warning rather than being
|
|
427
427
|
reformatted. This is by design: correctness over coverage.
|
|
428
|
+
- **T-SQL procedures are partial.** A procedure with `IF` or `WHILE` in its
|
|
429
|
+
body, a `TRY`/`CATCH` block, or header options such as `WITH EXECUTE AS`
|
|
430
|
+
passes through unformatted with a warning. Procedures holding plain DML,
|
|
431
|
+
`SELECT`, `SET` and `DECLARE` format.
|
|
428
432
|
|
|
429
433
|
## Adding a new golden sample
|
|
430
434
|
|
|
@@ -2,24 +2,24 @@ sqlalign/__init__.py,sha256=YqnsnmaiNosSKm-Ec4kYXBYvcGFx5bmBDmgTHGu9Jvk,3887
|
|
|
2
2
|
sqlalign/align.py,sha256=RzjlWERxjq9aNGhPA-E_TjS-5ntnOFEKiXzwBqFEfk4,7236
|
|
3
3
|
sqlalign/bodylint.py,sha256=lBmEIOkAQNWov8X4O9T4ynH4nOUiAsWrFomWSQkc6VQ,5085
|
|
4
4
|
sqlalign/casing.py,sha256=LnukO7XO5FNLAY5GfDdZq4R6KK2fj0RpVJBTLA-a2BA,10711
|
|
5
|
-
sqlalign/cli.py,sha256=
|
|
5
|
+
sqlalign/cli.py,sha256=P3zwa2oHWj0FNIOlXWfvdky-zHCKFiusgxwVptQM3bM,32076
|
|
6
6
|
sqlalign/commas.py,sha256=vJ0CXVpAvCrhrnkwk6o5U6y6o1TeJZ-mhKaz-w2xJdA,2855
|
|
7
7
|
sqlalign/config.py,sha256=VVfP9jPKAkRjim6ydUY4LhZTUv3lvKIrKU2McPR8faU,1063
|
|
8
8
|
sqlalign/configfile.py,sha256=sfB7kGO1NBMJkjgpIQa7BYSwNMuPPSSMiBGiUVfSVFQ,11864
|
|
9
|
-
sqlalign/formatter.py,sha256=
|
|
10
|
-
sqlalign/gui.py,sha256=
|
|
9
|
+
sqlalign/formatter.py,sha256=u2wDfP3XQWNQupLVh18GsZ3IKy-rNjcTgmjVZRbxXEw,47071
|
|
10
|
+
sqlalign/gui.py,sha256=CLvfiHLr404SW-ND9T9S2xpgXXkNbhMEGav_S4sjsg0,34711
|
|
11
11
|
sqlalign/ir.py,sha256=cHKTXgGOuOJgFQwsO7lTzVtca1ZKP-PFZYxybhKgmrY,1161
|
|
12
|
-
sqlalign/keywordcase.py,sha256=
|
|
13
|
-
sqlalign/lint.py,sha256=
|
|
14
|
-
sqlalign/plpgsql.py,sha256=
|
|
12
|
+
sqlalign/keywordcase.py,sha256=vUIYEHMjPGvBMxhVGYNmnU4_kOVR7yW2-quzNGqTHE0,6821
|
|
13
|
+
sqlalign/lint.py,sha256=kVOaOERB-gCOQ52MeNJMRBi73ne_0Jp6ovJRRHtCwCI,9229
|
|
14
|
+
sqlalign/plpgsql.py,sha256=50HCOPADBYtgZHShrXuQ-zdifvRzeQGN5I2rAFRUcHU,26985
|
|
15
15
|
sqlalign/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
16
16
|
sqlalign/sourcecase.py,sha256=u9Rz9fN0oEje0HlB33l3STJBXj31NxkebhmKI6pUDoI,4267
|
|
17
17
|
sqlalign/spelling.py,sha256=OqPiByOPBWCe7LPKtaIve-BnZ-UxXiXLQiZ4sHXW6Q4,9355
|
|
18
|
-
sqlalign/splitter.py,sha256=
|
|
18
|
+
sqlalign/splitter.py,sha256=yaePjbRbWD9AQG4daPO44R16wLMKqI6UqlzST2Q-74E,11190
|
|
19
19
|
sqlalign/sqlfluffconfig.py,sha256=-mixGe5K5duFPfzPcQOi0urExVlXPTYlQKFTvHsHB3s,4802
|
|
20
20
|
sqlalign/style.py,sha256=v9L697KI0BBMTFJP4KmNjpi3O-xz2XKLQLCBNRuzYWM,13321
|
|
21
21
|
sqlalign/templating.py,sha256=o8J83gYH1PoabmbLjOSYIVLOpUrimzmPsd-oGp_pt6U,3793
|
|
22
|
-
sqlalign/layout/__init__.py,sha256=
|
|
22
|
+
sqlalign/layout/__init__.py,sha256=8vWujQQQenPgMkcBnZsgciG1trnNhUO3c7A031UT_xk,18315
|
|
23
23
|
sqlalign/layout/case.py,sha256=3iBR05sL9QIEb3NtO482BM0sRLSKGOkrKTNT8LCJnaE,12468
|
|
24
24
|
sqlalign/layout/comments.py,sha256=T-vRzgUrqT0uR42AUr30zz97IUwSSaTYteYfnTXvUOg,21460
|
|
25
25
|
sqlalign/layout/conditions.py,sha256=J6BbFzWsaJq1DkzVe011RBT1Ti161gHKkDcEIqJnm4Q,20535
|
|
@@ -33,8 +33,8 @@ sqlalign/layout/select.py,sha256=PHE4wuTScaJCpkZehvqaFLk_EqRlZYH7PdNTBFYk7bo,273
|
|
|
33
33
|
sqlalign/layout/setop.py,sha256=hjve3Qxi2CsaFEwijg6srhfMdEUlv2b9MmOUp6BNip0,3427
|
|
34
34
|
sqlalign/layout/subquery.py,sha256=IIi4Cy8ZQ3WNBmPvmifuTRofXcWibakHCaaj9Uh2MfA,12496
|
|
35
35
|
sqlalign/layout/window.py,sha256=X8YJ32hQGriwRQsDM2ZDvmaU6YHunJvcMi7UShmGJrU,9943
|
|
36
|
-
sqlalign-1.3.
|
|
37
|
-
sqlalign-1.3.
|
|
38
|
-
sqlalign-1.3.
|
|
39
|
-
sqlalign-1.3.
|
|
40
|
-
sqlalign-1.3.
|
|
36
|
+
sqlalign-1.3.1.dist-info/METADATA,sha256=eea1tTlC8k1nScqRRPZ2E47CAMB5Gv1gp8UH_dtmY5g,23953
|
|
37
|
+
sqlalign-1.3.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
38
|
+
sqlalign-1.3.1.dist-info/entry_points.txt,sha256=hfughgpq-gK-8TKgvhw1mDbhlHbBQvPeTc96Jh6-efY,50
|
|
39
|
+
sqlalign-1.3.1.dist-info/licenses/LICENSE,sha256=qvo2BvsFUcC3_3LOk36ZKcaMp_j1AFMfBoCNRFcyrco,1076
|
|
40
|
+
sqlalign-1.3.1.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|