sqlalign 1.1.0__py3-none-any.whl → 1.2.0__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 +40 -7
- sqlalign/configfile.py +27 -4
- sqlalign/formatter.py +58 -2
- sqlalign/layout/ddl.py +22 -1
- sqlalign/layout/grouporder.py +28 -3
- sqlalign/spelling.py +110 -0
- {sqlalign-1.1.0.dist-info → sqlalign-1.2.0.dist-info}/METADATA +1 -1
- {sqlalign-1.1.0.dist-info → sqlalign-1.2.0.dist-info}/RECORD +11 -10
- {sqlalign-1.1.0.dist-info → sqlalign-1.2.0.dist-info}/WHEEL +0 -0
- {sqlalign-1.1.0.dist-info → sqlalign-1.2.0.dist-info}/entry_points.txt +0 -0
- {sqlalign-1.1.0.dist-info → sqlalign-1.2.0.dist-info}/licenses/LICENSE +0 -0
sqlalign/cli.py
CHANGED
|
@@ -13,7 +13,14 @@ from sqlalign import configfile
|
|
|
13
13
|
from sqlalign.formatter import format_sql
|
|
14
14
|
from sqlalign.lint import LintUnavailable, lint, version_warning
|
|
15
15
|
from sqlalign.sqlfluffconfig import sqlfluff_config
|
|
16
|
-
from sqlalign.style import
|
|
16
|
+
from sqlalign.style import (
|
|
17
|
+
ALL_ALIGN_TARGETS,
|
|
18
|
+
PRESETS,
|
|
19
|
+
SUPPORTED_DIALECTS,
|
|
20
|
+
Style,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
DEFAULT_DIALECT = "postgres"
|
|
17
24
|
|
|
18
25
|
|
|
19
26
|
def _write_atomically(path: Path, text: str) -> None:
|
|
@@ -192,8 +199,12 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
192
199
|
output_mode.add_argument("--diff", action="store_true",
|
|
193
200
|
help="write nothing; print a unified diff of what would "
|
|
194
201
|
"change (exit 1 if anything would)")
|
|
195
|
-
|
|
196
|
-
|
|
202
|
+
# No argparse default: it has to stay possible to tell "the user asked for
|
|
203
|
+
# postgres" from "the user said nothing", or a config `dialect` could never
|
|
204
|
+
# win over a default nobody chose.
|
|
205
|
+
p.add_argument("--dialect", choices=sorted(SUPPORTED_DIALECTS), default=None,
|
|
206
|
+
help="the SQL dialect to parse and print. Overrides a "
|
|
207
|
+
"`dialect` in the config file (default: postgres)")
|
|
197
208
|
p.add_argument("--line-ending", choices=["auto", "lf", "crlf"], default="auto",
|
|
198
209
|
help="line endings to write: auto preserves the file's own (default)")
|
|
199
210
|
# Config-file plumbing.
|
|
@@ -309,6 +320,22 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
309
320
|
"on_placement": args.on_placement,
|
|
310
321
|
}
|
|
311
322
|
|
|
323
|
+
def dialect_for(path: Path) -> str:
|
|
324
|
+
"""The dialect for one input file: flag, then config, then postgres.
|
|
325
|
+
|
|
326
|
+
The flag wins so a one-off run can override a committed config, which is
|
|
327
|
+
the same precedence every style setting already follows.
|
|
328
|
+
"""
|
|
329
|
+
if args.dialect is not None:
|
|
330
|
+
return args.dialect
|
|
331
|
+
if args.isolated:
|
|
332
|
+
return DEFAULT_DIALECT
|
|
333
|
+
config = args.config if args.config is not None else configfile.find_config(path)
|
|
334
|
+
if config is None:
|
|
335
|
+
return DEFAULT_DIALECT
|
|
336
|
+
return configfile.load_dialect(
|
|
337
|
+
config, strict=not args.no_strict_config) or DEFAULT_DIALECT
|
|
338
|
+
|
|
312
339
|
def style_for(path: Path) -> Style:
|
|
313
340
|
"""Settings for one input file: house defaults < config file < flags.
|
|
314
341
|
Resolved per file so one invocation can span repos with different
|
|
@@ -345,7 +372,7 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
345
372
|
|
|
346
373
|
if args.gui:
|
|
347
374
|
from sqlalign.gui import run
|
|
348
|
-
return run(
|
|
375
|
+
return run(dialect_for(Path(".")))
|
|
349
376
|
|
|
350
377
|
if not args.files and not (args.print_sqlfluff_config or args.gui or args.init):
|
|
351
378
|
p.error("the following arguments are required: files")
|
|
@@ -367,7 +394,7 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
367
394
|
if args.files else configfile.build_style({}, overrides))
|
|
368
395
|
except configfile.ConfigError as e:
|
|
369
396
|
p.error(str(e))
|
|
370
|
-
print(sqlfluff_config(style,
|
|
397
|
+
print(sqlfluff_config(style, dialect_for(Path("."))), end="")
|
|
371
398
|
return 0
|
|
372
399
|
|
|
373
400
|
if args.show_config:
|
|
@@ -380,6 +407,12 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
380
407
|
for w in warns:
|
|
381
408
|
print(f"sqlalign: {w}", file=sys.stderr)
|
|
382
409
|
print(f"# {source}" if source else "# built-in defaults (no config file found)")
|
|
410
|
+
# Printed with the settings because it IS one, and this output is
|
|
411
|
+
# documented as TOML a reader could paste back -- omitting a key would
|
|
412
|
+
# make the pasted config mean something different. Kept above the style
|
|
413
|
+
# block, and out of Style, because it selects the grammar rather than
|
|
414
|
+
# the layout.
|
|
415
|
+
print(f'dialect = "{dialect_for(Path(args.files[0]))}"')
|
|
383
416
|
print(configfile.describe(style))
|
|
384
417
|
return 0
|
|
385
418
|
|
|
@@ -448,7 +481,7 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
448
481
|
sys.stdout.write(original)
|
|
449
482
|
continue
|
|
450
483
|
try:
|
|
451
|
-
result = format_sql(normalized,
|
|
484
|
+
result = format_sql(normalized, dialect_for(path), style)
|
|
452
485
|
except Exception as e: # parse/safety failures surface as exit 2, file untouched
|
|
453
486
|
print(f"sqlalign: {name}: {e}", file=sys.stderr)
|
|
454
487
|
rc = 2
|
|
@@ -496,7 +529,7 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
496
529
|
if args.lint:
|
|
497
530
|
# Lint what would be written, so --check and --stdout report on the
|
|
498
531
|
# formatted result rather than on whatever is currently on disk.
|
|
499
|
-
code, out, err = lint(path, formatted, style,
|
|
532
|
+
code, out, err = lint(path, formatted, style, dialect_for(path))
|
|
500
533
|
sys.stdout.write(out)
|
|
501
534
|
sys.stderr.write(err)
|
|
502
535
|
if code:
|
sqlalign/configfile.py
CHANGED
|
@@ -42,11 +42,34 @@ _SCALAR_KEYS = frozenset({
|
|
|
42
42
|
"keyword_case",
|
|
43
43
|
})
|
|
44
44
|
KNOWN_KEYS = _SCALAR_KEYS | {"width", "align_targets", "preset", "exclude",
|
|
45
|
-
"blank_lines_between_statements"}
|
|
45
|
+
"dialect", "blank_lines_between_statements"}
|
|
46
46
|
|
|
47
|
-
#
|
|
48
|
-
#
|
|
49
|
-
|
|
47
|
+
# Keys that are read separately and never reach Style. `exclude` selects FILES
|
|
48
|
+
# rather than style; `dialect` is the grammar to parse and emit, which is not a
|
|
49
|
+
# style choice either -- putting it in Style would leak it into --show-config's
|
|
50
|
+
# style block and into the starter config as though it were a knob.
|
|
51
|
+
#
|
|
52
|
+
# `dialect` is a config key even though sqlalign refuses to GUESS a dialect.
|
|
53
|
+
# Those are different things: guessing means sniffing the file, which the safety
|
|
54
|
+
# guarantee cannot cover, while this is the author declaring the engine once, in
|
|
55
|
+
# a file their team reviews. It is more explicit than a flag typed into an
|
|
56
|
+
# editor's tool settings and never looked at again.
|
|
57
|
+
_NON_STYLE_KEYS = frozenset({"exclude", "dialect"})
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def load_dialect(path: Path, *, strict: bool = True) -> str | None:
|
|
61
|
+
"""The `dialect` from a config file, or None if it does not set one."""
|
|
62
|
+
from sqlalign.style import SUPPORTED_DIALECTS
|
|
63
|
+
|
|
64
|
+
settings, _ = load_settings(path, strict=strict)
|
|
65
|
+
dialect = settings.get("dialect")
|
|
66
|
+
if dialect is None:
|
|
67
|
+
return None
|
|
68
|
+
if not isinstance(dialect, str) or dialect not in SUPPORTED_DIALECTS:
|
|
69
|
+
raise ConfigError(
|
|
70
|
+
f"{path}: unknown dialect {dialect!r}; "
|
|
71
|
+
f"valid: {sorted(SUPPORTED_DIALECTS)}")
|
|
72
|
+
return dialect
|
|
50
73
|
|
|
51
74
|
|
|
52
75
|
def load_excludes(path: Path, *, strict: bool = True) -> list[str]:
|
sqlalign/formatter.py
CHANGED
|
@@ -5,7 +5,7 @@ import sqlglot
|
|
|
5
5
|
from sqlglot import exp
|
|
6
6
|
from sqlglot.errors import TokenError
|
|
7
7
|
|
|
8
|
-
from sqlalign import keywordcase, plpgsql, templating
|
|
8
|
+
from sqlalign import keywordcase, plpgsql, spelling, templating
|
|
9
9
|
from sqlalign.align import apply_align_targets, render
|
|
10
10
|
from sqlalign.casing import parse_dialect, render_style
|
|
11
11
|
from sqlalign.commas import apply_comma_position
|
|
@@ -39,6 +39,16 @@ class SafetyError(RuntimeError):
|
|
|
39
39
|
pass
|
|
40
40
|
|
|
41
41
|
|
|
42
|
+
class Rewrite(SafetyError):
|
|
43
|
+
"""The output spells something differently from the input.
|
|
44
|
+
|
|
45
|
+
A sibling of `CommentLoss` for the same reason: it shares the
|
|
46
|
+
upstream-round-trip branch while being reported as its own cause. Losing a
|
|
47
|
+
comment, changing an expression, and respelling a construct are three
|
|
48
|
+
different bugs.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
|
|
42
52
|
class CommentLoss(SafetyError):
|
|
43
53
|
"""The output does not carry the same comments as the input.
|
|
44
54
|
|
|
@@ -308,6 +318,38 @@ def comments_equal(a: str, b: str, dialect: str) -> bool:
|
|
|
308
318
|
return False
|
|
309
319
|
|
|
310
320
|
|
|
321
|
+
def _has_body(sql: str, dialect: str) -> bool:
|
|
322
|
+
"""Whether the statement carries a body sqlalign reformats internally.
|
|
323
|
+
|
|
324
|
+
A `$$` body is one string literal to the tokenizer, and a T-SQL
|
|
325
|
+
`CREATE PROCEDURE ... AS BEGIN ... END` is the same shape spelled
|
|
326
|
+
differently, so laying either out changes tokens for a reason that is not a
|
|
327
|
+
rewrite. Both are already compared structurally.
|
|
328
|
+
"""
|
|
329
|
+
if plpgsql.split_body(sql) is not None:
|
|
330
|
+
return True
|
|
331
|
+
try:
|
|
332
|
+
node = sqlglot.parse_one(sql, dialect=dialect)
|
|
333
|
+
except Exception:
|
|
334
|
+
return False
|
|
335
|
+
return (isinstance(node, exp.Create)
|
|
336
|
+
and str(node.args.get("kind") or "").upper() in {"PROCEDURE", "FUNCTION"})
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def spelling_equal(a: str, b: str, dialect: str) -> bool:
|
|
340
|
+
"""Whether `b` spells everything the way `a` did.
|
|
341
|
+
|
|
342
|
+
Compared after normalizing the three things sqlalign's settings choose --
|
|
343
|
+
keyword case, optional `AS`, and synonym spellings -- so an ordinary
|
|
344
|
+
reformat is equal and only a change the author did not ask for is not.
|
|
345
|
+
"""
|
|
346
|
+
try:
|
|
347
|
+
return (spelling.token_census(a, dialect)
|
|
348
|
+
== spelling.token_census(b, dialect))
|
|
349
|
+
except TokenError:
|
|
350
|
+
return True # unreadable input declines earlier; do not invent a reason
|
|
351
|
+
|
|
352
|
+
|
|
311
353
|
def ast_equal(a: str, b: str, dialect: str) -> bool:
|
|
312
354
|
"""AST-equality safety check. sqlglot sees a `$$…$$` body as one opaque
|
|
313
355
|
string, so raw AST comparison would reject any body reformatting. When both
|
|
@@ -626,6 +668,16 @@ def _format_all(text: str, dialect: str, style: Style) -> FormatResult:
|
|
|
626
668
|
# invisible to every safety check in the engine.
|
|
627
669
|
if not comments_equal(stmt, formatted, dialect):
|
|
628
670
|
raise CommentLoss(f"formatting changed a comment near: {snippet}")
|
|
671
|
+
# The AST check cannot see a rewrite sqlglot's own parser makes:
|
|
672
|
+
# both sides go through it and collapse to one tree, so
|
|
673
|
+
# `ALTER COLUMN x TYPE t` printed as `SET DATA TYPE t` compares
|
|
674
|
+
# equal. Comparing tokens catches it. Statements with a body are
|
|
675
|
+
# excluded -- the tokenizer sees a `$$` body as one string
|
|
676
|
+
# literal, so reformatting inside one reads as a changed token,
|
|
677
|
+
# and those are compared structurally by `_plpgsql_ast_equal`.
|
|
678
|
+
if not _has_body(stmt, dialect) and not spelling_equal(
|
|
679
|
+
stmt, formatted, dialect):
|
|
680
|
+
raise Rewrite(f"formatting respelled the statement near: {snippet}")
|
|
629
681
|
except Unsupported as exc:
|
|
630
682
|
# The reason rides in the message so `--report` can name the
|
|
631
683
|
# construct, not just count the declines.
|
|
@@ -646,7 +698,11 @@ def _format_all(text: str, dialect: str, style: Style) -> FormatResult:
|
|
|
646
698
|
declines.append(Decline("upstream", "sqlglot round-trip is unstable"))
|
|
647
699
|
emit(stmt, True)
|
|
648
700
|
continue
|
|
649
|
-
if isinstance(safety,
|
|
701
|
+
if isinstance(safety, Rewrite):
|
|
702
|
+
warnings.append("formatting would respell this statement, passed "
|
|
703
|
+
f"through unformatted: {snippet}")
|
|
704
|
+
declines.append(Decline("safety", "output would respell the statement"))
|
|
705
|
+
elif isinstance(safety, CommentLoss):
|
|
650
706
|
warnings.append("formatting would change a comment, passed through "
|
|
651
707
|
f"unformatted: {snippet}")
|
|
652
708
|
declines.append(Decline("safety", "output would change a comment"))
|
sqlalign/layout/ddl.py
CHANGED
|
@@ -13,6 +13,9 @@ reuse `layout_statement` for the SELECT body. TRUNCATE / CREATE INDEX / GRANT
|
|
|
13
13
|
are utility one-liners (INDEX breaks its partial `WHERE` when over width;
|
|
14
14
|
TRUNCATE drops its RESTART/CASCADE options to a second line).
|
|
15
15
|
"""
|
|
16
|
+
import functools
|
|
17
|
+
|
|
18
|
+
import sqlglot
|
|
16
19
|
from sqlglot import exp
|
|
17
20
|
|
|
18
21
|
from sqlalign.casing import render_expr
|
|
@@ -110,12 +113,30 @@ def _create_procedure_lines(node, dialect, width, anchor):
|
|
|
110
113
|
return lines
|
|
111
114
|
|
|
112
115
|
|
|
116
|
+
@functools.cache
|
|
117
|
+
def _replace_clause(dialect: str, kind: str) -> str:
|
|
118
|
+
"""How `dialect` spells the `replace` flag for a CREATE of this kind.
|
|
119
|
+
|
|
120
|
+
sqlglot records `CREATE OR REPLACE VIEW` and T-SQL's `CREATE OR ALTER VIEW`
|
|
121
|
+
as the same `replace=True`, so the source spelling is not in the tree and
|
|
122
|
+
printing a fixed "OR REPLACE" emitted Postgres syntax into a T-SQL file --
|
|
123
|
+
valid-looking output the AST check cannot reject, because both spellings
|
|
124
|
+
parse to that one flag.
|
|
125
|
+
|
|
126
|
+
Asked of sqlglot's own generator rather than listed here, so a dialect whose
|
|
127
|
+
spelling differs is followed rather than silently disagreed with.
|
|
128
|
+
"""
|
|
129
|
+
rendered = sqlglot.parse_one(
|
|
130
|
+
f"CREATE OR REPLACE {kind} x AS SELECT 1", dialect=dialect).sql(dialect)
|
|
131
|
+
return "OR ALTER" if "OR ALTER" in rendered.upper() else "OR REPLACE"
|
|
132
|
+
|
|
133
|
+
|
|
113
134
|
def _create_as_lines(node, dialect, width, anchor):
|
|
114
135
|
"""CTAS / CREATE [OR REPLACE] [MATERIALIZED] VIEW name AS <select>."""
|
|
115
136
|
kind = node.args.get("kind").upper()
|
|
116
137
|
parts = ["CREATE"]
|
|
117
138
|
if node.args.get("replace"):
|
|
118
|
-
parts.append(
|
|
139
|
+
parts.append(_replace_clause(dialect, kind))
|
|
119
140
|
if _has_property(node, exp.MaterializedProperty):
|
|
120
141
|
parts.append("MATERIALIZED")
|
|
121
142
|
parts.append(kind)
|
sqlalign/layout/grouporder.py
CHANGED
|
@@ -11,6 +11,9 @@ Split into `group_lines` and `order_limit_lines` (rather than one combined
|
|
|
11
11
|
function) so select.py can splice a HAVING block — via conditions.py's
|
|
12
12
|
`condition_block`: between GROUP BY and ORDER BY.
|
|
13
13
|
"""
|
|
14
|
+
import functools
|
|
15
|
+
|
|
16
|
+
import sqlglot
|
|
14
17
|
from sqlglot import exp
|
|
15
18
|
|
|
16
19
|
from sqlalign.casing import render_expr
|
|
@@ -24,6 +27,24 @@ def _clause_line(keyword, tail, anchor):
|
|
|
24
27
|
return kw_anchor, [Seg(kw_text), Seg(tail)]
|
|
25
28
|
|
|
26
29
|
|
|
30
|
+
@functools.cache
|
|
31
|
+
def _offset_rows(dialect: str) -> str:
|
|
32
|
+
"""` ROWS` where the dialect's OFFSET requires it, otherwise empty.
|
|
33
|
+
|
|
34
|
+
`Offset` records only the number -- whether the author wrote `OFFSET 10` or
|
|
35
|
+
`OFFSET 10 ROWS` is gone by the time the layout sees it. T-SQL requires the
|
|
36
|
+
keyword, so omitting it emitted SQL Server rejects, and the AST check could
|
|
37
|
+
not tell: both spellings parse to that same node.
|
|
38
|
+
|
|
39
|
+
Asked of sqlglot's generator rather than tested against a dialect name, so a
|
|
40
|
+
dialect whose grammar differs is followed.
|
|
41
|
+
"""
|
|
42
|
+
rendered = sqlglot.parse_one(
|
|
43
|
+
"SELECT a FROM t ORDER BY a OFFSET 1 ROWS FETCH NEXT 1 ROWS ONLY",
|
|
44
|
+
dialect=dialect).sql(dialect).upper()
|
|
45
|
+
return " ROWS" if "OFFSET 1 ROWS" in rendered else ""
|
|
46
|
+
|
|
47
|
+
|
|
27
48
|
def _fetch_tail(fetch, dialect):
|
|
28
49
|
"""Everything after `FETCH` in `FETCH FIRST n [PERCENT] ROWS {ONLY|WITH TIES}`.
|
|
29
50
|
|
|
@@ -112,8 +133,9 @@ def order_limit_lines(select, anchor, dialect, width):
|
|
|
112
133
|
# precedes it in the ANSI form (`OFFSET n ROWS FETCH NEXT m ROWS ONLY`)
|
|
113
134
|
# rather than following it the way it follows LIMIT.
|
|
114
135
|
if offset is not None:
|
|
115
|
-
lines.append(Line(*_clause_line(
|
|
116
|
-
|
|
136
|
+
lines.append(Line(*_clause_line(
|
|
137
|
+
"OFFSET", render_expr(offset.expression, dialect) + _offset_rows(dialect),
|
|
138
|
+
anchor)))
|
|
117
139
|
offset = None
|
|
118
140
|
lines.append(Line(*_clause_line("FETCH", _fetch_tail(limit, dialect), anchor)))
|
|
119
141
|
limit = None
|
|
@@ -125,7 +147,10 @@ def order_limit_lines(select, anchor, dialect, width):
|
|
|
125
147
|
# docs/.../2026-08-11-tsql-findings.md.
|
|
126
148
|
segs += [Seg("LIMIT"), Seg(render_expr(limit.expression, dialect))]
|
|
127
149
|
if offset is not None:
|
|
128
|
-
|
|
150
|
+
# Same requirement as the FETCH branch above: T-SQL's OFFSET needs ROWS
|
|
151
|
+
# whether or not a FETCH follows it.
|
|
152
|
+
segs += [Seg("OFFSET"),
|
|
153
|
+
Seg(render_expr(offset.expression, dialect) + _offset_rows(dialect))]
|
|
129
154
|
if segs:
|
|
130
155
|
kw_anchor, kw_text = clause_head(segs[0].text, anchor)
|
|
131
156
|
segs[0] = Seg(kw_text)
|
sqlalign/spelling.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""The spellings sqlalign is allowed to change, derived rather than listed.
|
|
2
|
+
|
|
3
|
+
The safety net compares sqlalign's output against its input as a syntax tree.
|
|
4
|
+
That cannot see a rewrite sqlglot's own parser performs, because both sides go
|
|
5
|
+
through the same parser and collapse to the same tree: `ALTER COLUMN x TYPE
|
|
6
|
+
text` and `ALTER COLUMN x SET DATA TYPE text` are one node, so printing the
|
|
7
|
+
second for the first is invisible to `ast_equal`.
|
|
8
|
+
|
|
9
|
+
Comparing the TOKENS either side of formatting closes that. The difficulty is
|
|
10
|
+
that some token differences are intended — sqlalign is a formatter, and three of
|
|
11
|
+
its settings exist precisely to choose between spellings. Those have to be
|
|
12
|
+
normalized away or every formatted file would be reported as rewritten.
|
|
13
|
+
|
|
14
|
+
Everything here is asked of sqlglot rather than written down. A hand-kept list of
|
|
15
|
+
"allowed differences" is the shape of thing this project has now watched rot
|
|
16
|
+
four times: it is correct on the day it is written, silently wrong afterwards,
|
|
17
|
+
and wrong in the direction of hiding bugs. Deriving it means a new dialect, or a
|
|
18
|
+
sqlglot release that renames a type, is followed rather than disagreed with.
|
|
19
|
+
"""
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import collections
|
|
23
|
+
import functools
|
|
24
|
+
|
|
25
|
+
import sqlglot
|
|
26
|
+
from sqlglot import exp
|
|
27
|
+
from sqlglot.tokens import TokenType
|
|
28
|
+
|
|
29
|
+
# `AS` before a table alias is `Style.table_alias_style`, which exists to add or
|
|
30
|
+
# remove exactly this token. It carries no meaning of its own -- `FROM t a` and
|
|
31
|
+
# `FROM t AS a` are the same tree -- so it is dropped from both sides rather
|
|
32
|
+
# than compared.
|
|
33
|
+
_OPTIONAL = frozenset({"AS"})
|
|
34
|
+
|
|
35
|
+
# `!=` / `<>` is `Style.neq_style`; the two are one operator to every engine
|
|
36
|
+
# sqlalign supports. Written here because it is an operator rather than a type,
|
|
37
|
+
# so the type derivation below cannot reach it -- but it is still a knob, not a
|
|
38
|
+
# guess: the pair is exactly the flag's own choices.
|
|
39
|
+
_OPERATOR_CLASSES = (frozenset({"!=", "<>"}),)
|
|
40
|
+
_OPERATOR_CANON = {spelling: sorted(group)[0]
|
|
41
|
+
for group in _OPERATOR_CLASSES for spelling in group}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@functools.cache
|
|
45
|
+
def type_synonyms(dialect: str) -> dict[str, str]:
|
|
46
|
+
"""Every type spelling `dialect` accepts, mapped to one canonical name.
|
|
47
|
+
|
|
48
|
+
Found by asking sqlglot twice: its tokenizer for the words it treats as
|
|
49
|
+
types, then its parser for which node each one produces. Two spellings that
|
|
50
|
+
parse to the same `DataType` are the same type, so a formatter printing one
|
|
51
|
+
where the author wrote the other has changed nothing that runs -- and
|
|
52
|
+
flagging it would be a false alarm on every `INT` the author spelled
|
|
53
|
+
`INTEGER`.
|
|
54
|
+
"""
|
|
55
|
+
resolved = sqlglot.Dialect.get_or_raise(dialect)
|
|
56
|
+
candidates = sorted(
|
|
57
|
+
word for word, token in resolved.tokenizer_class().KEYWORDS.items()
|
|
58
|
+
if isinstance(token, TokenType) and token.name in exp.DataType.Type.__members__)
|
|
59
|
+
|
|
60
|
+
by_node: dict[str, set[str]] = {}
|
|
61
|
+
for spelling in candidates:
|
|
62
|
+
try:
|
|
63
|
+
node = sqlglot.parse_one(
|
|
64
|
+
f"CREATE TABLE t (c {spelling})", dialect=dialect).find(exp.DataType)
|
|
65
|
+
except Exception: # not a type in this position
|
|
66
|
+
continue
|
|
67
|
+
if node is not None:
|
|
68
|
+
by_node.setdefault(node.this.name, set()).add(spelling)
|
|
69
|
+
|
|
70
|
+
return {spelling: sorted(group)[0]
|
|
71
|
+
for group in by_node.values() for spelling in group}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def token_census(sql: str, dialect: str) -> collections.Counter:
|
|
75
|
+
"""`sql`'s significant tokens counted, order discarded.
|
|
76
|
+
|
|
77
|
+
Order is deliberately not compared, and the reason is that something else
|
|
78
|
+
already compares it. `ast_equal` sees any reordering that changes meaning,
|
|
79
|
+
because a different order is a different tree. What it cannot see is a token
|
|
80
|
+
appearing or vanishing when sqlglot's parser collapsed two spellings -- a
|
|
81
|
+
dropped `ARRAY`, a dropped `ROWS`, an invented `WITH`.
|
|
82
|
+
|
|
83
|
+
So the two checks divide the space: the tree catches what moved, the census
|
|
84
|
+
catches what was added or lost. Comparing order here as well would flag
|
|
85
|
+
every benign normalisation sqlglot makes -- `GROUP BY ROLLUP(a, b), c`
|
|
86
|
+
printed as `GROUP BY c, ROLLUP(a, b)` is the same grouping sets, and
|
|
87
|
+
`NOT x IS NULL` printed as `x IS NOT NULL` is one tree in the dialects that
|
|
88
|
+
cannot tell them apart -- and a check that fires on correct output is one
|
|
89
|
+
that gets turned off.
|
|
90
|
+
"""
|
|
91
|
+
return collections.Counter(significant_tokens(sql, dialect))
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def significant_tokens(sql: str, dialect: str) -> list[str]:
|
|
95
|
+
"""`sql` as the tokens that carry the author's intent.
|
|
96
|
+
|
|
97
|
+
Case is normalized because `Style.keyword_case` chooses it, optional `AS` is
|
|
98
|
+
dropped, and a spelling with a synonym is replaced by its canonical form.
|
|
99
|
+
What survives is what sqlalign has no licence to change: identifiers,
|
|
100
|
+
literals, operators, and every keyword that is not one of its settings.
|
|
101
|
+
"""
|
|
102
|
+
tokenizer = sqlglot.Dialect.get_or_raise(dialect).tokenizer_class()
|
|
103
|
+
synonyms = type_synonyms(dialect)
|
|
104
|
+
tokens = []
|
|
105
|
+
for token in tokenizer.tokenize(sql):
|
|
106
|
+
word = token.text.strip().upper()
|
|
107
|
+
if not word or word in _OPTIONAL:
|
|
108
|
+
continue
|
|
109
|
+
tokens.append(synonyms.get(word, _OPERATOR_CANON.get(word, word)))
|
|
110
|
+
return tokens
|
|
@@ -2,17 +2,18 @@ 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=w97se03KoCe7V5y6UzKyepjxWZtSucGoBCpVBN0kb40,7866
|
|
5
|
-
sqlalign/cli.py,sha256=
|
|
5
|
+
sqlalign/cli.py,sha256=fzk8Ab_iXPQ4qmfPyxZ4RaiiTPtleSPAi5QsEn37340,27594
|
|
6
6
|
sqlalign/commas.py,sha256=vJ0CXVpAvCrhrnkwk6o5U6y6o1TeJZ-mhKaz-w2xJdA,2855
|
|
7
7
|
sqlalign/config.py,sha256=VVfP9jPKAkRjim6ydUY4LhZTUv3lvKIrKU2McPR8faU,1063
|
|
8
|
-
sqlalign/configfile.py,sha256=
|
|
9
|
-
sqlalign/formatter.py,sha256=
|
|
8
|
+
sqlalign/configfile.py,sha256=sfB7kGO1NBMJkjgpIQa7BYSwNMuPPSSMiBGiUVfSVFQ,11864
|
|
9
|
+
sqlalign/formatter.py,sha256=mxqfBy5fTf9dtcDg-b4nMOCZa50ySnFz-mQe4_8xbj8,36935
|
|
10
10
|
sqlalign/gui.py,sha256=99MvlQuX5TazUo9W2Myh7Kov14m3zWgFHUOgwi7W_Vw,34675
|
|
11
11
|
sqlalign/ir.py,sha256=cHKTXgGOuOJgFQwsO7lTzVtca1ZKP-PFZYxybhKgmrY,1161
|
|
12
12
|
sqlalign/keywordcase.py,sha256=1skBJ0aiw2yIcoDdW_4jjwUVBgpLRAs19AKfHE7Qspg,5914
|
|
13
13
|
sqlalign/lint.py,sha256=JLf-vdtaFyQBHLtr3qFpPpkEJwOOuRzNdzJ_ahutK6k,8214
|
|
14
14
|
sqlalign/plpgsql.py,sha256=77FQCTdKVFqhuU3aHJkyHcXOTwL9s7GG5_USzPyvHZI,19946
|
|
15
15
|
sqlalign/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
16
|
+
sqlalign/spelling.py,sha256=wkrZ0s_fwM-6DiylzNAhVZpDQpMWTJa6pRlKpKj8UVo,5212
|
|
16
17
|
sqlalign/splitter.py,sha256=gkp-yU9HNkC1lT7c3OwLYnFZUSAoyfihpaFxD3dhS0A,9821
|
|
17
18
|
sqlalign/sqlfluffconfig.py,sha256=-mixGe5K5duFPfzPcQOi0urExVlXPTYlQKFTvHsHB3s,4802
|
|
18
19
|
sqlalign/style.py,sha256=v9L697KI0BBMTFJP4KmNjpi3O-xz2XKLQLCBNRuzYWM,13321
|
|
@@ -22,17 +23,17 @@ sqlalign/layout/case.py,sha256=3iBR05sL9QIEb3NtO482BM0sRLSKGOkrKTNT8LCJnaE,12468
|
|
|
22
23
|
sqlalign/layout/comments.py,sha256=PwvrR-SQZOIs85-o-CslwAR6nH-DwkAiDBYBNJuIZfI,21348
|
|
23
24
|
sqlalign/layout/conditions.py,sha256=J6BbFzWsaJq1DkzVe011RBT1Ti161gHKkDcEIqJnm4Q,20535
|
|
24
25
|
sqlalign/layout/cte.py,sha256=XBl7tF8P0q8yajkxibgTDjna57qiKYHugDzQ93QpcL8,4064
|
|
25
|
-
sqlalign/layout/ddl.py,sha256=
|
|
26
|
+
sqlalign/layout/ddl.py,sha256=eGgPj1zcDQ-H2-pYivNzza9biji_1HIxZqVeF7H4SLo,19358
|
|
26
27
|
sqlalign/layout/dml.py,sha256=eDLTG2Os1B_s385mRGplyag8Z5mB3fUNCKF66yx3Baw,12906
|
|
27
28
|
sqlalign/layout/expr.py,sha256=Uh7JvZ7rKc-oH5GAfChd2Wl3DaEUdU5bFA-fyuvVjrs,5754
|
|
28
29
|
sqlalign/layout/fromjoin.py,sha256=J5MLQClX6ajqMVIwmC4vrwkFex9b99JO19lIJqhlVw4,16422
|
|
29
|
-
sqlalign/layout/grouporder.py,sha256=
|
|
30
|
+
sqlalign/layout/grouporder.py,sha256=a4CCv1IR4J2MVCJtqFJX7Az0y37Q5DFIGDOSk7f-pu8,7539
|
|
30
31
|
sqlalign/layout/select.py,sha256=PHE4wuTScaJCpkZehvqaFLk_EqRlZYH7PdNTBFYk7bo,27388
|
|
31
32
|
sqlalign/layout/setop.py,sha256=hjve3Qxi2CsaFEwijg6srhfMdEUlv2b9MmOUp6BNip0,3427
|
|
32
33
|
sqlalign/layout/subquery.py,sha256=IIi4Cy8ZQ3WNBmPvmifuTRofXcWibakHCaaj9Uh2MfA,12496
|
|
33
34
|
sqlalign/layout/window.py,sha256=X8YJ32hQGriwRQsDM2ZDvmaU6YHunJvcMi7UShmGJrU,9943
|
|
34
|
-
sqlalign-1.
|
|
35
|
-
sqlalign-1.
|
|
36
|
-
sqlalign-1.
|
|
37
|
-
sqlalign-1.
|
|
38
|
-
sqlalign-1.
|
|
35
|
+
sqlalign-1.2.0.dist-info/METADATA,sha256=6GfDZ4SyOUYjRQ8dmeVIxlYs7DxaxRDJr944LzAwOdw,23305
|
|
36
|
+
sqlalign-1.2.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
|
|
37
|
+
sqlalign-1.2.0.dist-info/entry_points.txt,sha256=hfughgpq-gK-8TKgvhw1mDbhlHbBQvPeTc96Jh6-efY,50
|
|
38
|
+
sqlalign-1.2.0.dist-info/licenses/LICENSE,sha256=qvo2BvsFUcC3_3LOk36ZKcaMp_j1AFMfBoCNRFcyrco,1076
|
|
39
|
+
sqlalign-1.2.0.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|