sqlalign 1.0.2__py3-none-any.whl → 1.1.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/__init__.py CHANGED
@@ -1,10 +1,90 @@
1
- """sqlalign -- a SQL formatter for the house columnar-alignment style."""
2
- from importlib.metadata import PackageNotFoundError, version
3
-
4
- # Read from the installed distribution rather than written here: the literal this
5
- # replaces still said "0.1.0" at release 1.1.0, because nothing forces the two to
6
- # be edited together. pyproject.toml is now the single place a release bumps.
7
- try:
8
- __version__ = version("sqlalign")
9
- except PackageNotFoundError: # a source tree that was never installed
10
- __version__ = "0.0.0+unknown"
1
+ """sqlalign -- a SQL formatter for the house columnar-alignment style.
2
+
3
+ The supported Python entry points are the two functions below. Everything under
4
+ `sqlalign.*` beyond them is internal and moves between releases.
5
+
6
+ >>> import sqlalign
7
+ >>> print(sqlalign.format("select a,b from t;"))
8
+ SELECT a
9
+ , b
10
+ FROM t;
11
+
12
+ Imports are deferred into the function bodies so that `import sqlalign` stays
13
+ cheap. Pulling in sqlglot costs most of the startup time of a run, and a
14
+ `--version` or a `__version__` read should not pay for it.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ from typing import TYPE_CHECKING
19
+
20
+ if TYPE_CHECKING: # imported for annotations only
21
+ from sqlalign.formatter import FormatResult
22
+ from sqlalign.style import Style
23
+
24
+ __all__ = ["format", "format_result"]
25
+
26
+
27
+ def format(sql: str, *, dialect: str = "postgres",
28
+ style: Style | None = None) -> str:
29
+ """Format `sql` and return the result.
30
+
31
+ A statement sqlalign cannot model is returned byte-identical rather than
32
+ raising: passing through is the contract, not a failure. That does mean this
33
+ function cannot tell you it happened -- use `format_result` when you need to
34
+ know, which is most of the time in a pipeline that gates on something.
35
+
36
+ `dialect` is one of `postgres`, `redshift` or `tsql`; anything else raises
37
+ `ValueError` rather than being formatted with keywords the target engine may
38
+ not accept. `style` defaults to the house style; build one with
39
+ `sqlalign.style.Style` or `sqlalign.style.preset_style("compact")`.
40
+
41
+ Named `format` because that is what it does. It shadows the builtin inside
42
+ this module and nowhere else, since callers reach it as `sqlalign.format`.
43
+ """
44
+ return format_result(sql, dialect=dialect, style=style).text
45
+
46
+
47
+ def format_result(sql: str, *, dialect: str = "postgres",
48
+ style: Style | None = None) -> FormatResult:
49
+ """Format `sql` and return the text together with what happened to it.
50
+
51
+ The result carries `text`, `warnings`, `statements` and `declines`. A
52
+ decline names the construct that was passed through and why, which is what
53
+ `--report` counts; reading it is how an embedding tells "formatted" apart
54
+ from "left alone", since both come back as valid SQL.
55
+ """
56
+ from sqlalign.formatter import format_sql
57
+ from sqlalign.style import HOUSE
58
+
59
+ # The same line-ending handling the CLI does, so the API is not a second,
60
+ # subtly different tool: the engine is LF-only, CRLF is normalized in and
61
+ # restored on the way out, and a lone CR -- which the engine does not
62
+ # model -- passes through with a warning rather than surfacing as a
63
+ # baffling per-statement decline.
64
+ ending = "\r\n" if "\r\n" in sql else "\n"
65
+ normalized = sql.replace("\r\n", "\n")
66
+ if "\r" in normalized:
67
+ from sqlalign.formatter import FormatResult
68
+ return FormatResult(sql, ["lone CR line endings — passed through untouched"])
69
+
70
+ result = format_sql(normalized, dialect, HOUSE if style is None else style)
71
+ if ending == "\r\n":
72
+ result = result._replace(text=result.text.replace("\n", "\r\n"))
73
+ return result
74
+
75
+
76
+ def __getattr__(name: str) -> str:
77
+ """Resolve `__version__` on first access rather than at import.
78
+
79
+ Read from the installed distribution rather than written here: the literal
80
+ this replaces still said "0.1.0" at release 1.1.0, because nothing forces
81
+ the two to be edited together. pyproject.toml is now the single place a
82
+ release bumps.
83
+ """
84
+ if name == "__version__":
85
+ from importlib.metadata import PackageNotFoundError, version
86
+ try:
87
+ return version("sqlalign")
88
+ except PackageNotFoundError: # a source tree that was never installed
89
+ return "0.0.0+unknown"
90
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
sqlalign/cli.py CHANGED
@@ -5,6 +5,7 @@ import os
5
5
  import shutil
6
6
  import sys
7
7
  import tempfile
8
+ import urllib.parse
8
9
  from fnmatch import fnmatch
9
10
  from pathlib import Path
10
11
 
@@ -12,7 +13,7 @@ from sqlalign import configfile
12
13
  from sqlalign.formatter import format_sql
13
14
  from sqlalign.lint import LintUnavailable, lint, version_warning
14
15
  from sqlalign.sqlfluffconfig import sqlfluff_config
15
- from sqlalign.style import PRESETS, SUPPORTED_DIALECTS, Style
16
+ from sqlalign.style import ALL_ALIGN_TARGETS, PRESETS, SUPPORTED_DIALECTS, Style
16
17
 
17
18
 
18
19
  def _write_atomically(path: Path, text: str) -> None:
@@ -109,9 +110,60 @@ def _report(seen: int, declined: int, causes: dict[tuple[str, str], int]) -> str
109
110
  width = max(len(kind) for kind, _ in causes)
110
111
  for (kind, reason), count in sorted(causes.items(), key=lambda kv: (-kv[1], kv[0])):
111
112
  lines.append(f" {count:>4} {kind:<{width}} {reason}")
113
+ ask = _ask_for_construct(causes)
114
+ if ask:
115
+ lines += ["", ask]
112
116
  return "\n".join(lines)
113
117
 
114
118
 
119
+ def _issue_url() -> str | None:
120
+ """Where to report a missing construct, from the package metadata.
121
+
122
+ Read rather than written here, so the address exists in exactly one place --
123
+ pyproject, which is also what PyPI shows.
124
+ """
125
+ from importlib.metadata import PackageNotFoundError, metadata
126
+ try:
127
+ entries = metadata("sqlalign").get_all("Project-URL") or []
128
+ except PackageNotFoundError: # a source tree that was never installed
129
+ return None
130
+ for entry in entries:
131
+ label, _, url = entry.partition(", ")
132
+ if label.strip().lower() == "issues":
133
+ return url.strip()
134
+ return None
135
+
136
+
137
+ def _ask_for_construct(causes: dict[tuple[str, str], int]) -> str | None:
138
+ """An invitation to ask for the construct that declined most often.
139
+
140
+ A decline is a gap measured on the team's own SQL rather than guessed at,
141
+ which makes it the most useful thing a user could tell this project. Left as
142
+ a count it is a dead end; with somewhere to send it, the report becomes a
143
+ demand-ranked backlog.
144
+
145
+ Only `unsupported`, and only the top one. A parse error or an upstream
146
+ round-trip failure is not sqlalign's to implement, and a URL per cause would
147
+ turn a summary into a wall of links.
148
+ """
149
+ unsupported = {reason: count for (kind, reason), count in causes.items()
150
+ if kind == "unsupported"}
151
+ if not unsupported:
152
+ return None
153
+ base = _issue_url()
154
+ if base is None:
155
+ return None
156
+ top = max(unsupported.items(), key=lambda kv: (kv[1], kv[0]))[0]
157
+ # A reason reads "PIVOT: this dialect has no such syntax". The construct is
158
+ # the part before the colon; the rest is the explanation, and splicing it
159
+ # into a sentence or an issue title reads like a machine wrote it.
160
+ construct = top.split(":", 1)[0].strip()
161
+ query = urllib.parse.urlencode({"title": f"Support {construct}",
162
+ "labels": "construct"})
163
+ return (f" {construct} is the construct declining most often here. If it "
164
+ f"matters to you, ask for it:\n {base}/new?{query}")
165
+
166
+
115
167
  def _version() -> str:
116
168
  """The installed version, or a marker when running from a source tree that
117
169
  was never installed."""
@@ -154,6 +206,10 @@ def build_parser() -> argparse.ArgumentParser:
154
206
  help="ignore any config file and use the built-in defaults")
155
207
  p.add_argument("--show-config", action="store_true",
156
208
  help="print the effective settings as TOML and exit")
209
+ p.add_argument("--init", action="store_true",
210
+ help="write a commented .sqlalign.toml in the current directory "
211
+ "and exit; every setting is commented out, so the file "
212
+ "changes nothing until you edit it")
157
213
  p.add_argument("--gui", action="store_true",
158
214
  help="(experimental) open the settings panel with a live preview, and exit")
159
215
  p.add_argument("--report", action="store_true",
@@ -193,11 +249,12 @@ def build_parser() -> argparse.ArgumentParser:
193
249
  dest="format_dollar_bodies",
194
250
  help="leave dollar-quoted ($$) procedure and function bodies untouched")
195
251
  p.add_argument("--align-targets",
252
+ # The valid list is derived, not typed: the typed version had
253
+ # drifted to seven names while the set held nine.
196
254
  help="comma-separated alignment targets to keep. Default is every "
197
255
  "target except table_names, which is opt-in because it pads "
198
256
  "the FROM/JOIN keyword out to a shared table column. "
199
- "Valid: aliases, table_names, operators, join_conditions, "
200
- "case_results, column_types, column_constraints")
257
+ f"Valid: {', '.join(sorted(ALL_ALIGN_TARGETS))}")
201
258
  p.add_argument("--comma-position", choices=["leading", "trailing"],
202
259
  help="where the separator comma sits in a stacked list (default: leading)")
203
260
  p.add_argument("--boolean-operator-position", choices=["leading", "trailing"],
@@ -263,13 +320,41 @@ def main(argv: list[str] | None = None) -> int:
263
320
  print(f"sqlalign: {w}", file=sys.stderr)
264
321
  return style
265
322
 
323
+ if args.init:
324
+ # Refuses to overwrite: a config is a decision a team already made, and
325
+ # a starter is only ever the first one.
326
+ target = Path(".sqlalign.toml")
327
+ if target.exists():
328
+ print(f"sqlalign: {target} already exists — nothing written",
329
+ file=sys.stderr)
330
+ return 2
331
+ try:
332
+ starter = configfile.starter(style_for(Path(".")), args.preset)
333
+ except configfile.ConfigError as e:
334
+ # The starter shows the settings currently in effect, so it resolves
335
+ # config like any other mode -- and fails like one: message, exit 2.
336
+ print(f"sqlalign: {e}", file=sys.stderr)
337
+ return 2
338
+ try:
339
+ target.write_text(starter)
340
+ except OSError as e:
341
+ print(f"sqlalign: {e}", file=sys.stderr)
342
+ return 2
343
+ print(f"wrote {target}")
344
+ return 0
345
+
266
346
  if args.gui:
267
347
  from sqlalign.gui import run
268
348
  return run(args.dialect)
269
349
 
270
- if not args.files and not (args.print_sqlfluff_config or args.gui):
350
+ if not args.files and not (args.print_sqlfluff_config or args.gui or args.init):
271
351
  p.error("the following arguments are required: files")
272
352
 
353
+ # stdin is read once, so `-` alongside paths has no sensible reading: it
354
+ # would either format one input twice or silently drop the others.
355
+ if "-" in args.files and len(args.files) > 1:
356
+ p.error("`-` reads stdin and cannot be combined with file arguments")
357
+
273
358
  if args.print_sqlfluff_config:
274
359
  # Resolved against the first file like --show-config, so the generated
275
360
  # config reflects the style that actually applies there rather than the
@@ -319,10 +404,16 @@ def main(argv: list[str] | None = None) -> int:
319
404
  for path in targets:
320
405
  name = str(path)
321
406
  try:
322
- # newline="" disables universal-newline translation so CRLF/CR bytes
323
- # survive into `original` and can be detected below (v1 is LF-only).
324
- with path.open(newline="") as f:
325
- original = f.read()
407
+ if name == "-":
408
+ # Read the raw buffer rather than sys.stdin, whose universal
409
+ # newline translation would rewrite CRLF before the code below
410
+ # gets to notice it.
411
+ original = sys.stdin.buffer.read().decode()
412
+ else:
413
+ # newline="" disables universal-newline translation so CRLF/CR bytes
414
+ # survive into `original` and can be detected below (v1 is LF-only).
415
+ with path.open(newline="") as f:
416
+ original = f.read()
326
417
  except OSError as e:
327
418
  print(f"sqlalign: {e}", file=sys.stderr)
328
419
  rc = 2
@@ -350,7 +441,10 @@ def main(argv: list[str] | None = None) -> int:
350
441
  if "\r" in normalized:
351
442
  print(f"sqlalign: {name}: lone CR line endings — passed through untouched",
352
443
  file=sys.stderr)
353
- if args.stdout:
444
+ # `-` has no file for the caller to fall back to: an editor filter
445
+ # replaces the buffer with whatever comes out, so passing through
446
+ # must mean echoing the input, never emitting nothing.
447
+ if args.stdout or name == "-":
354
448
  sys.stdout.write(original)
355
449
  continue
356
450
  try:
@@ -370,13 +464,12 @@ def main(argv: list[str] | None = None) -> int:
370
464
  # diff on every line) instead of differing purely by "\r".
371
465
  target_ending = source_ending if args.line_ending == "auto" else args.line_ending
372
466
  formatted = result.text.replace("\n", "\r\n") if target_ending == "crlf" else result.text
373
- if args.stdout:
374
- sys.stdout.write(formatted)
375
- elif args.check or args.diff:
467
+ if args.check or args.diff:
376
468
  # Both write nothing and report through the exit code; they differ in
377
469
  # what they print. --check names the files that would change (enough
378
470
  # for CI to be actionable without burying the log in diffs); --diff
379
- # shows the change itself.
471
+ # shows the change itself. For `-` the name printed is `-`, which is
472
+ # what the reader passed.
380
473
  if formatted != original:
381
474
  if args.diff:
382
475
  sys.stdout.writelines(difflib.unified_diff(
@@ -386,6 +479,10 @@ def main(argv: list[str] | None = None) -> int:
386
479
  else:
387
480
  print(f"would reformat {name}")
388
481
  rc = max(rc, 1)
482
+ # `-` has no file to rewrite, so the formatted text IS the output. Ordered
483
+ # after --check/--diff so those still report on stdin rather than writing.
484
+ elif args.stdout or name == "-":
485
+ sys.stdout.write(formatted)
389
486
  elif formatted != original:
390
487
  try:
391
488
  _write_atomically(path, formatted)
@@ -414,5 +511,31 @@ def main(argv: list[str] | None = None) -> int:
414
511
  return rc
415
512
 
416
513
 
514
+ def console() -> int:
515
+ """The installed command. `main` stays exception-transparent for callers
516
+ that embed it; this wrapper owns the one failure that belongs to being a
517
+ process in a pipeline.
518
+
519
+ `sqlalign - | head -3` closes stdout after three lines. Dying quietly is
520
+ the pipeline contract -- every coreutils tool does -- and 141 is how a
521
+ shell spells death-by-SIGPIPE, so scripts that check for it keep working.
522
+ stdout is detached first, or the interpreter's exit flush raises the same
523
+ error a second time as an ignored-exception message on stderr.
524
+ """
525
+ import os
526
+
527
+ try:
528
+ return main()
529
+ except BrokenPipeError:
530
+ # Best-effort: under a captured stdout (tests, some embedders) there is
531
+ # no file descriptor to detach, and nothing to protect either.
532
+ try:
533
+ devnull = os.open(os.devnull, os.O_WRONLY)
534
+ os.dup2(devnull, sys.stdout.fileno())
535
+ except (OSError, ValueError):
536
+ pass
537
+ return 141
538
+
539
+
417
540
  if __name__ == "__main__":
418
- sys.exit(main())
541
+ sys.exit(console())
sqlalign/configfile.py CHANGED
@@ -17,11 +17,14 @@ not have, and would only discover it from a surprising diff. `--no-strict-config
17
17
  downgrades that to a warning for the case where a config is shared with a newer
18
18
  sqlalign that knows keys this one does not.
19
19
  """
20
- import tomllib
20
+ try:
21
+ import tomllib
22
+ except ModuleNotFoundError: # Python 3.10
23
+ import tomli as tomllib
21
24
  from pathlib import Path
22
25
 
23
26
  from sqlalign.config import Width
24
- from sqlalign.style import PRESETS, Style
27
+ from sqlalign.style import PRESETS, SETTING_SUMMARIES, Style
25
28
 
26
29
  FILENAME = ".sqlalign.toml"
27
30
  PYPROJECT = "pyproject.toml"
@@ -162,6 +165,57 @@ def resolve(path: Path, overrides: dict | None = None, *,
162
165
  return build_style(settings, overrides), config_path, warnings
163
166
 
164
167
 
168
+ def starter(style: Style, preset: str | None = None) -> str:
169
+ """A commented `.sqlalign.toml` for a project that has none.
170
+
171
+ Every setting is emitted COMMENTED OUT, showing the value currently in
172
+ effect. The file therefore changes nothing until something is uncommented,
173
+ which is the property that makes it safe to write into a repository: a
174
+ starter that pinned eighteen settings would freeze a team on today's
175
+ defaults and call it a choice.
176
+
177
+ A `--preset` is the exception and is written live, because choosing one is
178
+ the decision the reader just made. The settings below it then show what that
179
+ preset does, so the file doubles as the answer to "what did I just pick".
180
+
181
+ Values come from `describe`, so what a starter shows and what
182
+ `--show-config` reports cannot drift apart.
183
+ """
184
+ rendered = {}
185
+ for line in describe(style).splitlines():
186
+ if line.startswith("#") or " = " not in line:
187
+ continue
188
+ rendered[line.split(" = ", 1)[0]] = line
189
+
190
+ out = [
191
+ "# sqlalign configuration.",
192
+ "#",
193
+ "# Written by `sqlalign --init`. Every setting is commented out and shows the",
194
+ "# value currently in effect, so this file changes nothing until you uncomment",
195
+ "# something.",
196
+ "#",
197
+ "# Reference: https://sqlalign.lumaru.app/v1/settings.html",
198
+ "",
199
+ ]
200
+ if preset:
201
+ out += [
202
+ '# The base every setting below starts from. Flags and any setting you',
203
+ '# uncomment layer on top of it.',
204
+ f'preset = "{preset}"',
205
+ "",
206
+ ]
207
+ for name, summary in SETTING_SUMMARIES.items():
208
+ line = rendered.get(name)
209
+ out.append(f"# {summary}")
210
+ if line is None:
211
+ # `blank_lines_between_statements` has no TOML spelling when unset.
212
+ out.append(f"# {name} =")
213
+ else:
214
+ out.append(f"# {line}")
215
+ out.append("")
216
+ return "\n".join(out).rstrip() + "\n"
217
+
218
+
165
219
  def describe(style: Style) -> str:
166
220
  """The effective settings, as the TOML a user could paste into a config."""
167
221
  lines = [
sqlalign/formatter.py CHANGED
@@ -3,6 +3,7 @@ from collections import namedtuple
3
3
 
4
4
  import sqlglot
5
5
  from sqlglot import exp
6
+ from sqlglot.errors import TokenError
6
7
 
7
8
  from sqlalign import keywordcase, plpgsql, templating
8
9
  from sqlalign.align import apply_align_targets, render
@@ -38,6 +39,15 @@ class SafetyError(RuntimeError):
38
39
  pass
39
40
 
40
41
 
42
+ class CommentLoss(SafetyError):
43
+ """The output does not carry the same comments as the input.
44
+
45
+ A subclass so it shares the upstream-round-trip branch with the AST check
46
+ while still being reported as its own cause: losing a comment and changing
47
+ an expression are both renderer bugs, but they are not the same bug.
48
+ """
49
+
50
+
41
51
  # Types whose distinction sqlglot destroys at parse time for T-SQL, where the two
42
52
  # spellings are not synonyms:
43
53
  # REAL is FLOAT(24), FLOAT is FLOAT(53) , rewriting one widens precision
@@ -265,6 +275,39 @@ def _dollar_create_parts(text: str, dialect: str):
265
275
  return parts if plpgsql.is_dollar_create(node, dialect) else None
266
276
 
267
277
 
278
+ def comment_text(sql: str, dialect: str) -> list[str]:
279
+ """Every comment in `sql`, in order, stripped of surrounding whitespace.
280
+
281
+ sqlglot hangs a comment off the token it precedes rather than putting it in
282
+ the tree, which is why the AST check cannot see one:
283
+ `ast_equal("SELECT a -- note", "SELECT a", ...)` is True.
284
+ """
285
+ tokenizer = sqlglot.Dialect.get_or_raise(dialect).tokenizer_class()
286
+ return [c.strip() for token in tokenizer.tokenize(sql)
287
+ for c in (token.comments or [])]
288
+
289
+
290
+ def comments_equal(a: str, b: str, dialect: str) -> bool:
291
+ """Whether `b` carries the same comments as `a`, in the same order.
292
+
293
+ Text is compared, not position. The layout deliberately MOVES a comment to
294
+ the end of the row above -- where it sits is expected to change, what it
295
+ says is not.
296
+
297
+ A `$$` body is a single string literal to the tokenizer, so comments inside
298
+ one are invisible here. Those statements are covered structurally by
299
+ `_plpgsql_ast_equal`, which compares each embedded statement in turn.
300
+ """
301
+ try:
302
+ return comment_text(a, dialect) == comment_text(b, dialect)
303
+ except TokenError:
304
+ # Unreachable through `format_sql`: input the tokenizer rejects fails to
305
+ # parse first and is declined before this runs. Kept so a direct caller
306
+ # gets a refusal rather than an exception -- if the comments cannot be
307
+ # compared, the honest answer is that they were not verified.
308
+ return False
309
+
310
+
268
311
  def ast_equal(a: str, b: str, dialect: str) -> bool:
269
312
  """AST-equality safety check. sqlglot sees a `$$…$$` body as one opaque
270
313
  string, so raw AST comparison would reject any body reformatting. When both
@@ -494,9 +537,17 @@ def format_sql(text: str, dialect: str = "postgres", style: Style = HOUSE) -> Fo
494
537
  try:
495
538
  masked, replacements = templating.mask(text)
496
539
  except ValueError as e:
497
- return FormatResult(text, [f"templating not maskable, passed through: {e}"])
540
+ # Counted as one declined statement: the whole file is one opaque
541
+ # unit here, and a passthrough --report cannot see is invisible in
542
+ # exactly the way --report exists to prevent.
543
+ return FormatResult(text, [f"templating not maskable, passed through: {e}"],
544
+ 1, (Decline("unsupported", "templating not maskable"),))
498
545
  result = _format_all(masked, dialect, style)
499
- return FormatResult(templating.unmask(result.text, replacements), result.warnings)
546
+ # Rebuilt for the unmasked text only; the counts ride through unchanged.
547
+ # Dropping them blinded --report and --max-declines for every templated
548
+ # file, which is most of a dbt project.
549
+ return FormatResult(templating.unmask(result.text, replacements),
550
+ result.warnings, result.statements, result.declines)
500
551
 
501
552
 
502
553
  def _format_all(text: str, dialect: str, style: Style) -> FormatResult:
@@ -570,6 +621,11 @@ def _format_all(text: str, dialect: str, style: Style) -> FormatResult:
570
621
  style.keyword_case)
571
622
  if not ast_equal(stmt, formatted, dialect):
572
623
  raise SafetyError(f"formatting changed semantics near: {snippet}")
624
+ # Comments are not in the AST, so the check above passes whether
625
+ # or not they survived. Without this one, dropping a comment is
626
+ # invisible to every safety check in the engine.
627
+ if not comments_equal(stmt, formatted, dialect):
628
+ raise CommentLoss(f"formatting changed a comment near: {snippet}")
573
629
  except Unsupported as exc:
574
630
  # The reason rides in the message so `--report` can name the
575
631
  # construct, not just count the declines.
@@ -578,7 +634,7 @@ def _format_all(text: str, dialect: str, style: Style) -> FormatResult:
578
634
  declines.append(Decline("unsupported", str(exc)))
579
635
  emit(stmt, True)
580
636
  continue
581
- except SafetyError:
637
+ except SafetyError as safety:
582
638
  # If sqlglot cannot round-trip the input through its own
583
639
  # generator, no formatter could satisfy the check and the fault
584
640
  # is upstream: report it as such rather than as a semantic
@@ -590,9 +646,14 @@ def _format_all(text: str, dialect: str, style: Style) -> FormatResult:
590
646
  declines.append(Decline("upstream", "sqlglot round-trip is unstable"))
591
647
  emit(stmt, True)
592
648
  continue
593
- warnings.append(
594
- f"formatting would change semantics, passed through unformatted: {snippet}")
595
- declines.append(Decline("safety", "output would differ semantically"))
649
+ if isinstance(safety, CommentLoss):
650
+ warnings.append("formatting would change a comment, passed through "
651
+ f"unformatted: {snippet}")
652
+ declines.append(Decline("safety", "output would change a comment"))
653
+ else:
654
+ warnings.append("formatting would change semantics, passed through "
655
+ f"unformatted: {snippet}")
656
+ declines.append(Decline("safety", "output would differ semantically"))
596
657
  emit(stmt, True)
597
658
  continue
598
659
  except Exception as exc: # a real bug: surface it, but keep formatting the file
sqlalign/gui.py CHANGED
@@ -229,11 +229,79 @@ def preview(sql: str, values: dict, dialect: str) -> tuple[str, str]:
229
229
  return result.text, status
230
230
 
231
231
 
232
- def as_toml(values: dict) -> str:
233
- """The panel's settings as a `.sqlalign.toml` — the same text
234
- `--show-config` prints, so what the GUI saves is what the CLI reads."""
232
+ def _exactly_a_preset(values: dict) -> str | None:
233
+ """The preset `values` exactly is, or None.
234
+
235
+ Stricter than `preset_named`, deliberately. That compares the formatted
236
+ output of one sample, which is the right question for the panel's dropdown:
237
+ two settings that format identically are the same choice to a reader.
238
+
239
+ It is the wrong question for a claim written into a file. `width` does not
240
+ change that sample, so a project that set width to 71 would still be told it
241
+ had the preset's values -- which is a sentence in their repository that is
242
+ not true.
243
+ """
244
+ for name in sorted(PRESETS):
245
+ if settings_from(preset_style(name)) == values:
246
+ return name
247
+ return None
248
+
249
+
250
+ def disabled_reason(name: str, values: dict) -> str | None:
251
+ """Why the control named `name` is inert right now, or None if it is not.
252
+
253
+ A greyed-out control with no explanation reads as a bug in the panel. The
254
+ setting is real and will do something -- just not until the control it
255
+ depends on says so, and that is a sentence the panel can say.
256
+
257
+ Kept a plain function so it can be tested without a display; the whole
258
+ module is otherwise only reachable through tkinter.
259
+ """
260
+ for control in CONTROLS:
261
+ if control["name"] != name:
262
+ continue
263
+ need = control.get("needs")
264
+ if need is None:
265
+ return None
266
+ depends_on, wanted = need
267
+ if values.get(depends_on) == wanted:
268
+ return None
269
+ spelled = str(wanted).lower() if isinstance(wanted, bool) else f"{wanted}"
270
+ return f"needs {depends_on} = {spelled}"
271
+ return None
272
+
273
+
274
+ def as_toml(values: dict, *, dialect: str | None = None) -> str:
275
+ """The panel's settings as a `.sqlalign.toml`.
276
+
277
+ The values are written LIVE rather than commented out, which is the opposite
278
+ of what `--init` writes and for the opposite reason: these are choices
279
+ someone just made in the panel, not a menu they have yet to read.
280
+
281
+ The body is `describe`, the same text `--show-config` prints, so what the
282
+ GUI saves is what the CLI reads. The header exists because this file lands
283
+ in a repository where the next person to open it did not choose any of it.
284
+ """
235
285
  from sqlalign.configfile import describe
236
- return describe(style_from(values)) + "\n"
286
+
287
+ header = [
288
+ "# sqlalign configuration, written from the settings panel (`sqlalign --gui`).",
289
+ "#",
290
+ "# Every setting is written out, so this pins the style as it was chosen.",
291
+ "# `sqlalign --init` writes the same settings commented out instead, if you",
292
+ "# would rather follow a preset as it changes.",
293
+ "#",
294
+ "# Reference: https://sqlalign.lumaru.app/v1/settings.html",
295
+ ]
296
+ preset = _exactly_a_preset(values)
297
+ if preset is not None:
298
+ header.insert(1, f"# These are the `{preset}` preset's values.")
299
+ if dialect:
300
+ # `dialect` is CLI-only and has no config key, so it is recorded as a
301
+ # comment rather than written as a setting that would fail to load.
302
+ header.append("#")
303
+ header.append(f"# Previewed with --dialect {dialect}, which has no config key.")
304
+ return "\n".join(header) + "\n\n" + describe(style_from(values)) + "\n"
237
305
 
238
306
 
239
307
  def run(dialect: str = "postgres") -> int: # pragma: no cover - needs a display
@@ -476,6 +544,7 @@ def build(root, dialect: str = "postgres") -> dict:
476
544
 
477
545
  widgets: dict = {}
478
546
  boxes: dict = {} # name -> the actual widgets, for enabling/disabling
547
+ notes: dict = {} # name -> the label that says why it is greyed out
479
548
 
480
549
  def refresh_enabled():
481
550
  """Grey out every control whose `needs` is not currently satisfied."""
@@ -488,6 +557,10 @@ def build(root, dialect: str = "postgres") -> dict:
488
557
  for widget in boxes.get(control["name"], ()):
489
558
  widget.configure(state=state if state == "normal"
490
559
  or control["kind"] != "choice" else "disabled")
560
+ # Say WHY, rather than leaving a greyed control looking broken.
561
+ note = notes.get(control["name"])
562
+ if note is not None:
563
+ note.configure(text=disabled_reason(control["name"], values) or "")
491
564
 
492
565
  def refresh_widgets():
493
566
  """Push `values` back into the controls, after a preset or a file load."""
@@ -535,6 +608,11 @@ def build(root, dialect: str = "postgres") -> dict:
535
608
 
536
609
  for control in CONTROLS:
537
610
  name, kind = control["name"], control["kind"]
611
+ if control.get("needs"):
612
+ # One label per dependent control, filled in by refresh_enabled. Packed
613
+ # before the control itself so the reason sits above what it explains.
614
+ notes[name] = ttk.Label(settings, text="", foreground="grey")
615
+ notes[name].pack(anchor="w")
538
616
  if kind == "flag":
539
617
  var = tk.BooleanVar(value=values[name])
540
618
  box = ttk.Checkbutton(settings, text=control["label"], variable=var)
@@ -651,7 +729,7 @@ def build(root, dialect: str = "postgres") -> dict:
651
729
  if not path:
652
730
  return
653
731
  try:
654
- pathlib.Path(path).write_text(as_toml(values))
732
+ pathlib.Path(path).write_text(as_toml(values, dialect=dialect))
655
733
  except OSError as e:
656
734
  report("save there", e)
657
735
 
sqlalign/keywordcase.py CHANGED
@@ -53,7 +53,12 @@ def identifier_names(statement: str, dialect: str) -> set[str]:
53
53
 
54
54
  for tree in trees:
55
55
  for ident in tree.find_all(exp.Identifier):
56
- names.add(ident.this)
56
+ # Only bare identifiers. A quoted one renders inside quotes, which
57
+ # `apply`'s scanner never enters -- adding its text here did nothing
58
+ # for it and immunised every KEYWORD spelled the same way, so
59
+ # `SELECT a AS "FROM"` left the real FROM upper in a lowercase file.
60
+ if not ident.args.get("quoted"):
61
+ names.add(ident.this)
57
62
  for heredoc in tree.find_all(exp.Heredoc): # plpgsql body
58
63
  body = heredoc.this
59
64
  if isinstance(body, str):
@@ -78,7 +83,8 @@ def _body_identifiers(body: str, dialect: str) -> set[str]:
78
83
  if tree is None:
79
84
  continue
80
85
  for ident in tree.find_all(exp.Identifier):
81
- names.add(ident.this)
86
+ if not ident.args.get("quoted"):
87
+ names.add(ident.this)
82
88
  return names
83
89
 
84
90
 
@@ -279,6 +279,25 @@ def column_alias(item: exp.Alias, dialect: str) -> str:
279
279
  return render_expr(item.args["alias"], dialect)
280
280
 
281
281
 
282
+ def cte_name(cte: exp.CTE, dialect: str) -> str:
283
+ """`cte`'s name as it should be PRINTED, quoting included.
284
+
285
+ The third node type to have this bug, after `table_alias` and
286
+ `column_alias`. `.alias` returns the identifier's NAME, so `WITH "cte" AS`
287
+ came out as bare `WITH cte AS` -- and in Postgres those are two different
288
+ relations, quite apart from the names that are a syntax error unquoted.
289
+
290
+ Any tool that generates SQL tends to quote every identifier it emits --
291
+ sqlglot's own optimizer does -- so this is not a rare spelling. It is what
292
+ a whole class of machine-written SQL looks like.
293
+
294
+ The name alone, not the whole `TableAlias`: rendering that node would splice
295
+ a column list back in, and `WITH cte(a, b)` declines as unsupported before
296
+ this point.
297
+ """
298
+ return render_expr(cte.args["alias"].this, dialect)
299
+
300
+
282
301
  def table_alias(table: exp.Expression, dialect: str) -> str | None:
283
302
  """`table`'s alias as it should be PRINTED, or None if it has none.
284
303
 
@@ -28,6 +28,9 @@ line indents are baked in from `IN`'s NATURAL column, so a resolver-padded
28
28
  `IN` would silently detach the body from its own `(`. Plain `IN (list)`
29
29
  (`predicate_segs`, below) is a different code path and still right-aligns.
30
30
  """
31
+ import functools
32
+
33
+ import sqlglot
31
34
  from sqlglot import exp
32
35
 
33
36
  from sqlalign.casing import active_style, render_expr
@@ -233,6 +236,32 @@ def _render_group(paren, parent_scope, open_col, group_counter, dialect, width):
233
236
  return inline, lines
234
237
 
235
238
 
239
+ @functools.cache
240
+ def _keeps_negated_is_apart(dialect: str) -> bool:
241
+ """Whether `dialect` still distinguishes `x IS NOT NULL` from `NOT x IS NULL`.
242
+
243
+ Postgres parses the first as `Is(negate=True)` and the second as
244
+ `Not(Is(...))`, so a `Not(Is(...))` is the author's `NOT ... IS NULL`, and
245
+ printing it as `IS NOT NULL` rewrites SQL they did not write. T-SQL and
246
+ Redshift collapse both spellings onto `Not(Is(...))`; the distinction is gone
247
+ before the layout sees it, and the idiomatic spelling is then the only
248
+ sensible choice.
249
+
250
+ The probe uses the NULL spelling and its answer applies ONLY to a NULL (or
251
+ UNKNOWN, which sqlglot folds to NULL) right-hand side. The boolean forms
252
+ collapse even in Postgres -- `x IS NOT TRUE` and `NOT x IS TRUE` are one
253
+ tree -- so for those the idiomatic spelling is the only sensible choice in
254
+ every dialect, and treating them like NULL rewrote `x IS NOT TRUE` into
255
+ `NOT x IS TRUE` with nothing able to notice.
256
+
257
+ Probed rather than listed against dialect names, so a parser change upstream
258
+ is followed instead of silently disagreed with.
259
+ """
260
+ where = sqlglot.parse_one("SELECT 1 FROM t WHERE x IS NOT NULL",
261
+ dialect=dialect).args["where"].this
262
+ return isinstance(where, exp.Is)
263
+
264
+
236
265
  def predicate_segs(cond, scope, dialect):
237
266
  """Split one predicate into [lhs, op(tagged), rhs] segments.
238
267
 
@@ -248,9 +277,27 @@ def predicate_segs(cond, scope, dialect):
248
277
  # Deliberately narrow: only a Not directly wrapping an Is. Every other
249
278
  # Not stays declined, which `test_not_exists_passes_through` depends on.
250
279
  inner = cond.this
251
- lhs = render_expr(inner.this, dialect)
252
- rhs = "NOT " + render_expr(inner.expression, dialect)
253
- return [Seg(lhs), Seg("IS", scope=scope, kind="op"), Seg(rhs)]
280
+ inner_negated = bool(inner.args.get("negate"))
281
+ if _keeps_negated_is_apart(dialect) and isinstance(inner.expression, exp.Null):
282
+ # Here -- and only here -- the tree still says which spelling the
283
+ # author wrote: `x IS NOT NULL` parses to Is(negate), so a Not
284
+ # wrapping an Is is their `NOT ... IS [NOT] NULL` and is preserved.
285
+ # The inner negate rides along; dropping it turned
286
+ # `NOT x IS NOT NULL` into its logical inverse, which only the
287
+ # re-parse guard stopped from shipping.
288
+ rhs = ("NOT " if inner_negated else "") + render_expr(inner.expression, dialect)
289
+ return [Seg("NOT " + render_expr(inner.this, dialect)),
290
+ Seg("IS", scope=scope, kind="op"),
291
+ Seg(rhs)]
292
+ if not inner_negated:
293
+ # One tree serves both spellings here (T-SQL and Redshift for NULL,
294
+ # every dialect for the boolean forms), so which comes out is
295
+ # sqlalign's to pick, and `IS NOT x` is the idiomatic pick.
296
+ lhs = render_expr(inner.this, dialect)
297
+ rhs = "NOT " + render_expr(inner.expression, dialect)
298
+ return [Seg(lhs), Seg("IS", scope=scope, kind="op"), Seg(rhs)]
299
+ # Not(Is(negate)) in a dialect that collapses the spellings has no
300
+ # faithful single-IS rendering; fall through to the decline paths.
254
301
 
255
302
  # `NOT IN (...)` and `NOT BETWEEN ... AND ...`: sqlglot wraps the inner
256
303
  # predicate in a `Not`, so peeling it here puts NOT on the operator, where a
sqlalign/layout/cte.py CHANGED
@@ -20,7 +20,7 @@ from sqlglot import exp
20
20
  from sqlalign.casing import active_style
21
21
  from sqlalign.commas import COMMA_KIND
22
22
  from sqlalign.ir import Line, Seg
23
- from sqlalign.layout import Unsupported
23
+ from sqlalign.layout import Unsupported, cte_name
24
24
 
25
25
  _BODY_ANCHOR = 2
26
26
 
@@ -41,7 +41,12 @@ def layout_with(node: exp.Expression, dialect: str, width) -> list[Line]:
41
41
  materialized = cte.args.get("materialized")
42
42
  hint = "" if materialized is None else (
43
43
  "MATERIALIZED " if materialized else "NOT MATERIALIZED ")
44
- body = f"{cte.alias} AS {hint}("
44
+ # `.alias` returns the identifier's NAME, unquoted, so `WITH "cte" AS`
45
+ # came out as bare `WITH cte AS` -- a different relation in Postgres, and
46
+ # a syntax error whenever the name needs quoting at all. The re-parse
47
+ # guard caught it and passed the statement through, which is the silent
48
+ # decline `column_alias` and `table_alias` document one node type over.
49
+ body = f"{cte_name(cte, dialect)} AS {hint}("
45
50
  # This site applies comma position itself rather than going through
46
51
  # commas.py's generic pass (like window.py). That pass blanks the comma
47
52
  # while KEEPING its width, which is right where the comma head is as wide
sqlalign/plpgsql.py CHANGED
@@ -199,11 +199,54 @@ def _upper_kw(text: str, dialect: str) -> str:
199
199
  return " ".join(t.upper() if t.upper() in kw else t for t in _tokenize_ws(text))
200
200
 
201
201
 
202
+ def _split_comment(text: str) -> tuple[str, str | None]:
203
+ """`text` as (code, trailing comment or None), split outside string literals.
204
+
205
+ `_upper_kw` whitespace-tokenizes whatever it is given, so a comment left in
206
+ the clause had its words keyword-cased -- `-- log it for the user` shipped
207
+ as `-- LOG it FOR the user;`, semicolon and all, with nothing declining.
208
+ Comments are not code and never go through casing.
209
+
210
+ Only a comment that runs to the end of the clause is split off. One with
211
+ code after it (a closed `/* ... */` mid-clause, or code on the line after a
212
+ `--`) has no faithful single-line rendering here, so the clause declines
213
+ rather than guessing -- the same contract the SQL comment engine follows.
214
+ """
215
+ in_string = False
216
+ i = 0
217
+ while i < len(text):
218
+ ch = text[i]
219
+ if ch == "'":
220
+ in_string = not in_string
221
+ elif not in_string and ch == "-" and text.startswith("--", i):
222
+ comment = text[i:]
223
+ rest = comment.split("\n", 1)
224
+ if len(rest) > 1 and rest[1].strip():
225
+ raise Unsupported("comment inside a procedural clause")
226
+ return text[:i].rstrip(), comment.rstrip()
227
+ elif not in_string and ch == "/" and text.startswith("/*", i):
228
+ close = text.find("*/", i + 2)
229
+ if close == -1 or text[close + 2:].strip():
230
+ raise Unsupported("comment inside a procedural clause")
231
+ return text[:i].rstrip(), text[i:].rstrip()
232
+ i += 1
233
+ return text, None
234
+
235
+
202
236
  def _render_plain(text: str, dialect: str) -> str:
203
- text = text.strip()
237
+ text, comment = _split_comment(text.strip())
204
238
  if text.lower().startswith("get diagnostics"):
205
- return _render_get_diagnostics(text)
206
- return _upper_kw(text, dialect)
239
+ rendered = _render_get_diagnostics(text)
240
+ else:
241
+ rendered = _upper_kw(text, dialect)
242
+ if comment is None:
243
+ return rendered
244
+ if not rendered:
245
+ # A clause that IS a comment: verbatim, and no semicolon -- `;` after
246
+ # `--` becomes part of the comment, which is how one line comment
247
+ # swallowed the statement terminator once before.
248
+ return comment
249
+ return f"{rendered} {comment}"
207
250
 
208
251
 
209
252
  def _render_get_diagnostics(text: str) -> str:
@@ -300,7 +343,19 @@ def _render_stmt(raw: str, dialect: str, style) -> str:
300
343
  # the final backstop). No fixture exercises those constructs.
301
344
  if _is_sql(raw, dialect):
302
345
  return _render_sql_stmt(raw, dialect, style)
303
- return _render_plain(raw, dialect) + ";"
346
+ return _terminate(_render_plain(raw, dialect))
347
+
348
+
349
+ def _terminate(rendered: str) -> str:
350
+ """`rendered` with its `;` in the right place: after the code, before any
351
+ trailing comment, and not at all when the clause is only a comment --
352
+ anything after `--` is part of the comment, including a semicolon."""
353
+ code, comment = _split_comment(rendered)
354
+ if not code:
355
+ return rendered
356
+ if not code.endswith(";"):
357
+ code += ";"
358
+ return f"{code} {comment}" if comment else code
304
359
 
305
360
 
306
361
  def _render_branch(raw: str, dialect: str) -> str:
@@ -308,7 +363,7 @@ def _render_branch(raw: str, dialect: str) -> str:
308
363
  the keyword. A SQL statement there (multi-line geometry) is declined."""
309
364
  if _is_sql(raw, dialect):
310
365
  raise Unsupported("plpgsql IF branch: SQL statement")
311
- return _render_plain(raw, dialect) + ";"
366
+ return _terminate(_render_plain(raw, dialect))
312
367
 
313
368
 
314
369
  def _render_declare(decls: list[str], dialect: str) -> str:
sqlalign/style.py CHANGED
@@ -155,6 +155,32 @@ class Style:
155
155
 
156
156
 
157
157
  HOUSE = Style()
158
+
159
+ # One line per setting, in the order a starter config presents them. Lives in the
160
+ # package rather than in the docs tooling because two things read it: the config
161
+ # `--init` writes, and the settings reference on the site. A second copy would
162
+ # drift, and the drift would be invisible -- a config comment nobody rereads.
163
+ SETTING_SUMMARIES: dict[str, str] = {
164
+ "keyword_case": "Whether SQL keywords are upper- or lowercase.",
165
+ "align": "The master switch for columnar alignment.",
166
+ "align_targets": "Which columns are aligned, when `align` is on.",
167
+ "comma_position": "Whether a list's commas lead or trail their line.",
168
+ "boolean_operator_position": "Whether `AND` / `OR` lead or trail their line.",
169
+ "on_placement": "Whether a join's `ON` rides the join line or takes its own.",
170
+ "select_placement": "Whether the first select item rides the `SELECT` line.",
171
+ "select_indent": "How far the select list is indented under `SELECT`.",
172
+ "clause_keyword_align": "Whether root clause keywords are left-aligned or form a river.",
173
+ "river_gutter": "How wide the river's gutter is.",
174
+ "table_alias_style": "Whether a table alias is written bare or with `AS`.",
175
+ "neq_style": "How the not-equal operator is spelled.",
176
+ "decimal_style": "How the fixed-point type is spelled.",
177
+ "width": "The column the formatter tries to stay inside.",
178
+ "blank_lines_between_statements": "How many blank lines separate two statements.",
179
+ "body_blank_lines": "How many blank lines separate statements inside a `$$` body.",
180
+ "format_dollar_bodies": "Whether `$$ … $$` procedure bodies are formatted at all.",
181
+ "protect_templating": "Whether Jinja / dbt templating is masked before parsing.",
182
+ }
183
+
158
184
  COMPACT = Style(align=False)
159
185
 
160
186
  # Named starting points, so a team picks one word instead of reading nine knobs.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: sqlalign
3
- Version: 1.0.2
3
+ Version: 1.1.0
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/
@@ -14,6 +14,8 @@ Classifier: Development Status :: 5 - Production/Stable
14
14
  Classifier: Environment :: Console
15
15
  Classifier: Intended Audience :: Developers
16
16
  Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
17
19
  Classifier: Programming Language :: Python :: 3.12
18
20
  Classifier: Programming Language :: Python :: 3.13
19
21
  Classifier: Programming Language :: SQL
@@ -21,27 +23,36 @@ Classifier: Topic :: Database
21
23
  Classifier: Topic :: Software Development :: Quality Assurance
22
24
  Classifier: Topic :: Text Processing :: Filters
23
25
  Classifier: Typing :: Typed
24
- Requires-Python: >=3.12
25
- Requires-Dist: sqlglot<30.15,>=30.14
26
+ Requires-Python: >=3.10
27
+ Requires-Dist: sqlglot<31,>=30.14
28
+ Requires-Dist: tomli>=2; python_version < '3.11'
26
29
  Provides-Extra: lint
27
30
  Requires-Dist: sqlfluff<5,>=4.2; extra == 'lint'
28
31
  Description-Content-Type: text/markdown
29
32
 
30
33
  # sqlalign
31
34
 
32
- A SQL formatter for **Postgres**, **Redshift** and **SQL Server** that **cannot change what your
33
- SQL means**. Every statement it formats is re-parsed and AST-compared against the
34
- input; if the output would differ semantically — or if the engine doesn't fully
35
- model the construct — the statement is passed through **byte-identical** with a
36
- warning instead. It reformats presentation and nothing else: identifiers, string
37
- literals, cast form (`::` vs `CAST`), `GROUP BY` references, and alias choices all
38
- survive exactly as written.
35
+ A SQL formatter for **Postgres**, **Redshift** and **SQL Server** that **cannot
36
+ change what your SQL means**. Every statement it formats is re-parsed and
37
+ compared against the input as a syntax tree, and that tree is what "means" is
38
+ measured by here. If the output would differ, or would carry different comments,
39
+ or if the engine doesn't fully model the construct, the statement is passed
40
+ through **byte-identical** with a warning instead.
41
+
42
+ It reformats presentation and nothing else: identifiers, string literals, cast
43
+ form (`::` vs `CAST`), `GROUP BY` references, comments, and alias choices all
44
+ survive exactly as written. Two spellings do collapse at parse time and are
45
+ therefore sqlalign's to pick rather than yours — `!=` against `<>`, and
46
+ `decimal` against `numeric` — so both are settings rather than accidents.
47
+
48
+ It formats *inside* dollar-quoted (`$$`) plpgsql procedure and function bodies,
49
+ and **`--lint` reads inside them too, which sqlfluff cannot**: to its parser a
50
+ body is a single string literal, so nothing within one is ever linted.
39
51
 
40
52
  Its layout is **columnar alignment**: operators, aliases, `AS` clauses, and
41
53
  `ON`/`AND` conditions are padded into vertical columns by a fixpoint resolver —
42
- alignment is the layout engine itself, not a post-pass over already-printed text.
43
- It applies that same engine *inside* dollar-quoted (`$$`) plpgsql procedure and
44
- function bodies.
54
+ alignment is the layout engine itself, not a post-pass over already-printed
55
+ text.
45
56
 
46
57
  ```sql
47
58
  FROM customers cust
@@ -142,8 +153,19 @@ LEFT JOIN shipping_addresses addr ON addr.order_id = ord.order_id
142
153
  pip install sqlalign
143
154
  ```
144
155
 
145
- That puts a `sqlalign` command on your PATH. To keep it out of a project's
146
- environment, `uv tool install sqlalign` does the same thing in isolation.
156
+ That puts a `sqlalign` command on your PATH.
157
+
158
+ If your environment already carries sqlglot — a dbt or SQLMesh project usually
159
+ does — install sqlalign in isolation instead, so the two version ranges cannot
160
+ collide:
161
+
162
+ ```sh
163
+ uv tool install sqlalign
164
+ ```
165
+
166
+ Releases are published from CI with [signed provenance](https://pypi.org/project/sqlalign/),
167
+ so PyPI records which repository and workflow built each artifact. For a tool
168
+ that rewrites your source files, that is worth checking.
147
169
 
148
170
  `--lint` runs sqlfluff over the formatted result and needs the optional extra:
149
171
 
@@ -151,8 +173,10 @@ environment, `uv tool install sqlalign` does the same thing in isolation.
151
173
  pip install 'sqlalign[lint]'
152
174
  ```
153
175
 
154
- Requires Python ≥ 3.12. Runtime dependency: `sqlglot` (pinned to the 30.14.x
155
- line — the layout engine depends on exact AST shapes; see `pyproject.toml`).
176
+ Requires Python ≥ 3.10. Runtime dependency: `sqlglot` (`>=30.14,<31` — the
177
+ layout engine reads exact AST shapes, which a test suite asserts by name across
178
+ the range; see `pyproject.toml`), plus `tomli` on 3.10, which later versions ship
179
+ as `tomllib`.
156
180
 
157
181
  To work on sqlalign itself, install from a clone instead — that adds the dev
158
182
  tools (`pytest`, `ruff`, `sqlfluff`):
@@ -164,11 +188,21 @@ uv sync
164
188
 
165
189
  ## Usage
166
190
 
191
+ Look before you leap — this is a formatter with an opinion, and the first thing
192
+ worth knowing is what it would do to your SQL:
193
+
194
+ ```sh
195
+ sqlalign --diff . # show what would change, write nothing
196
+ sqlalign --check . # exit non-zero if anything would change
197
+ ```
198
+
199
+ Then, once you have seen it:
200
+
167
201
  ```sh
168
202
  sqlalign query.sql # format in place (rewrites the file)
169
203
  sqlalign . # every *.sql under here, recursively
170
204
  sqlalign --stdout query.sql # print the formatted result, leave the file
171
- sqlalign --check *.sql # exit non-zero if any file is not formatted
205
+ cat query.sql | sqlalign - # read stdin, write stdout
172
206
  sqlalign --dialect redshift ddl.sql
173
207
  sqlalign --dialect tsql query.sql # SQL Server: TOP, [brackets]
174
208
  sqlalign --width 120 query.sql
@@ -203,8 +237,26 @@ WHERE ord.order_date >= '2026-07-01'
203
237
  AND cust.segment = 'enterprise';
204
238
  ```
205
239
 
240
+ ## In a pipeline
241
+
242
+ ```yaml
243
+ # .pre-commit-config.yaml # GitHub Actions
244
+ repos: - uses: pua2/sqlalign@v1.1.0
245
+ - repo: https://github.com/pua2/sqlalign # defaults to --check: a gate,
246
+ rev: v1.1.0 # not a formatter
247
+ hooks:
248
+ - id: sqlalign # or sqlalign-check to report only
249
+ ```
250
+
251
+ Details and editor recipes are in the [guide](docs/guide/getting-started.md).
252
+
206
253
  ## dbt / Jinja
207
254
 
255
+ **Scope first:** the templating is handled, the warehouses mostly are not.
256
+ sqlalign parses Postgres, Redshift and SQL Server, so a dbt project on Snowflake
257
+ or BigQuery will parse some models and decline others. Snowflake is the next
258
+ dialect. If your warehouse is one of the three, read on.
259
+
208
260
  Templated SQL isn't valid SQL, so most formatters decline it. sqlalign masks each
209
261
  template expression with a **same-width** placeholder, formats normally, then puts
210
262
  the original back — so alignment is computed against the real text width:
@@ -251,17 +303,26 @@ body_blank_lines = 1 # inside a $$ body
251
303
  river_gutter = 6
252
304
  ```
253
305
 
254
- Start from a **preset** and override what you want:
306
+ Start from a **preset** and override what you want. If your team already follows
307
+ a published style guide, start at `compact` or the guide's own preset rather than
308
+ at `house` — the alignment is the house opinion, not a prerequisite:
255
309
 
256
310
  | Preset | What it is |
257
311
  |---|---|
258
312
  | `house` | the columnar default — aligned, leading separators, `ON` inline |
259
- | `compact` | same line structure, no alignment padding (9 of 10 style guides are unpadded) |
313
+ | `compact` | **the one to start from if you follow a published guide** — same line structure, no alignment padding, which is what 9 of 10 of them ask for |
260
314
  | `trailing` | keeps the alignment, moves commas and `AND`/`OR` to end of line |
261
315
  | `dbt` | lowercase keywords, list stacked under a bare `select` at 4, trailing commas, no padding (one deviation: a CTE body indents 2, not 4) |
262
316
  | `river` | [Holywell's guide](https://www.sqlstyle.guide/) — root keywords right-aligned to a 6-column gutter, joins on the far side of it, otherwise unpadded |
263
317
  | `gitlab` | [GitLab's published guide](https://handbook.gitlab.com/handbook/enterprise-data/platform/sql-style-guide/) — list stacked at 2, trailing commas, `ON` on its own line, `AS` on table aliases, and column aliases the only thing aligned |
264
318
 
319
+ One consequence worth knowing before you adopt `house`: **alignment padding means
320
+ a diff is wider than the line you edited.** Rename a column to something longer
321
+ and every row in that block shifts to keep the column, so a one-token change can
322
+ touch twenty lines. That is inherent to columnar alignment rather than a bug in
323
+ this implementation — `compact` and `--no-align` keep the line structure and drop
324
+ the padding, and both make a diff show only what changed.
325
+
265
326
  ```toml
266
327
  preset = "compact"
267
328
  comma_position = "trailing" # layers on top of the preset
@@ -345,7 +406,7 @@ not cover.
345
406
 
346
407
  ## Guarantees & scope
347
408
 
348
- - **Byte-for-byte golden fixtures** — 25 hand-formatted samples in
409
+ - **Byte-for-byte golden fixtures** — 29 hand-formatted samples in
349
410
  `tests/fixtures/expected/` are the executable specification of the style; the
350
411
  suite asserts `format(input) == expected` for every one, plus idempotency
351
412
  (`format(expected) == expected`) and AST-equivalence.
@@ -414,6 +475,12 @@ See [CONTRIBUTING.md](CONTRIBUTING.md). In short: `uv sync`, then `uv run pytest
414
475
  every pull request. The goldens in `tests/fixtures/expected/` are the
415
476
  specification, not snapshots.
416
477
 
478
+ **The style does not change in a patch release.** The goldens in
479
+ `tests/fixtures/expected/` are compared byte for byte in their own CI job, so an
480
+ unintended layout change cannot reach a release; an intended one waits for a
481
+ minor version and is named in the changelog. See
482
+ [Stability](docs/guide/style.md).
483
+
417
484
  Release notes are in [CHANGELOG.md](CHANGELOG.md).
418
485
 
419
486
  ## Reference
@@ -1,27 +1,27 @@
1
- sqlalign/__init__.py,sha256=f0XHp1fXFgh6edJswAhQ9IBQl1TsI_BvQZZKBV3kH6Y,536
1
+ 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=LLDlIZM77D6By8MXbTFDkBMEvUmHfGOAw6HlXGI-SZA,20565
5
+ sqlalign/cli.py,sha256=kcaCiIV0PDynPwQIVJrhYY_wZ8ScBncUeG99voa2g0g,26182
6
6
  sqlalign/commas.py,sha256=vJ0CXVpAvCrhrnkwk6o5U6y6o1TeJZ-mhKaz-w2xJdA,2855
7
7
  sqlalign/config.py,sha256=VVfP9jPKAkRjim6ydUY4LhZTUv3lvKIrKU2McPR8faU,1063
8
- sqlalign/configfile.py,sha256=74rjIl5mGJSyIn7bwO0aeKe7HOm-qN6pB4byz-L2JRE,8672
9
- sqlalign/formatter.py,sha256=hgPKbqgCqhBFUKf_AKluUiJIFeMLApinemy1wxnyoYg,31079
10
- sqlalign/gui.py,sha256=PVikAiZcgia6JtYONMg0fGYqNJLfh4AIck-a0ryVlvE,31081
8
+ sqlalign/configfile.py,sha256=f_yQCEJoEZHNk9gn_kXvS1gIxQgDkYb029TaB0skc1Y,10766
9
+ sqlalign/formatter.py,sha256=XwmfjMRIiQc-9_VxtnfU0kOIctr6l7kTrey-77wYLiA,34251
10
+ sqlalign/gui.py,sha256=99MvlQuX5TazUo9W2Myh7Kov14m3zWgFHUOgwi7W_Vw,34675
11
11
  sqlalign/ir.py,sha256=cHKTXgGOuOJgFQwsO7lTzVtca1ZKP-PFZYxybhKgmrY,1161
12
- sqlalign/keywordcase.py,sha256=UA054AOnLVvVZCw6J4nzOKC73CY2xP6kOAUFCG-pgf4,5497
12
+ sqlalign/keywordcase.py,sha256=1skBJ0aiw2yIcoDdW_4jjwUVBgpLRAs19AKfHE7Qspg,5914
13
13
  sqlalign/lint.py,sha256=JLf-vdtaFyQBHLtr3qFpPpkEJwOOuRzNdzJ_ahutK6k,8214
14
- sqlalign/plpgsql.py,sha256=OPUo1rusB_HwH59jaHVfkp41S1C4wMWav9--3GeSu20,17547
14
+ sqlalign/plpgsql.py,sha256=77FQCTdKVFqhuU3aHJkyHcXOTwL9s7GG5_USzPyvHZI,19946
15
15
  sqlalign/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
16
16
  sqlalign/splitter.py,sha256=gkp-yU9HNkC1lT7c3OwLYnFZUSAoyfihpaFxD3dhS0A,9821
17
17
  sqlalign/sqlfluffconfig.py,sha256=-mixGe5K5duFPfzPcQOi0urExVlXPTYlQKFTvHsHB3s,4802
18
- sqlalign/style.py,sha256=LjCxfOD--GVyDus1h99WyGJfQr1yDjIDVXntabvHJM0,11599
18
+ sqlalign/style.py,sha256=v9L697KI0BBMTFJP4KmNjpi3O-xz2XKLQLCBNRuzYWM,13321
19
19
  sqlalign/templating.py,sha256=o8J83gYH1PoabmbLjOSYIVLOpUrimzmPsd-oGp_pt6U,3793
20
- sqlalign/layout/__init__.py,sha256=579cugPzcjKLruNwX8SbkUyWNu-r_t1s1eJJzPTf7cE,14436
20
+ sqlalign/layout/__init__.py,sha256=kp0W4_A3plKs3vcS9K-Cb9uUs56emdindN-cyzTJsR8,15300
21
21
  sqlalign/layout/case.py,sha256=3iBR05sL9QIEb3NtO482BM0sRLSKGOkrKTNT8LCJnaE,12468
22
22
  sqlalign/layout/comments.py,sha256=PwvrR-SQZOIs85-o-CslwAR6nH-DwkAiDBYBNJuIZfI,21348
23
- sqlalign/layout/conditions.py,sha256=jf2filUbE6k-6BFrSYpN1tNnxtz-rC7oZlwC6bb0unw,17964
24
- sqlalign/layout/cte.py,sha256=C1XUvtkVBKQDpL7j1i2wY0hXwl7ejNCtn34MAa9MnY0,3642
23
+ sqlalign/layout/conditions.py,sha256=J6BbFzWsaJq1DkzVe011RBT1Ti161gHKkDcEIqJnm4Q,20535
24
+ sqlalign/layout/cte.py,sha256=XBl7tF8P0q8yajkxibgTDjna57qiKYHugDzQ93QpcL8,4064
25
25
  sqlalign/layout/ddl.py,sha256=i7dG57-1grXteshg9fnbVQYGDj92OgrVB5QT9hP6TqU,18469
26
26
  sqlalign/layout/dml.py,sha256=eDLTG2Os1B_s385mRGplyag8Z5mB3fUNCKF66yx3Baw,12906
27
27
  sqlalign/layout/expr.py,sha256=Uh7JvZ7rKc-oH5GAfChd2Wl3DaEUdU5bFA-fyuvVjrs,5754
@@ -31,8 +31,8 @@ sqlalign/layout/select.py,sha256=PHE4wuTScaJCpkZehvqaFLk_EqRlZYH7PdNTBFYk7bo,273
31
31
  sqlalign/layout/setop.py,sha256=hjve3Qxi2CsaFEwijg6srhfMdEUlv2b9MmOUp6BNip0,3427
32
32
  sqlalign/layout/subquery.py,sha256=IIi4Cy8ZQ3WNBmPvmifuTRofXcWibakHCaaj9Uh2MfA,12496
33
33
  sqlalign/layout/window.py,sha256=X8YJ32hQGriwRQsDM2ZDvmaU6YHunJvcMi7UShmGJrU,9943
34
- sqlalign-1.0.2.dist-info/METADATA,sha256=-tBM0XfrbhQjLYpE3WF1fayau8aVmZIQ98b2hJ7V5qw,20224
35
- sqlalign-1.0.2.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
36
- sqlalign-1.0.2.dist-info/entry_points.txt,sha256=pHPkRH7HQwwvx1mdDjdvGZ_xMXMg0gaWtTOmvrONPuc,47
37
- sqlalign-1.0.2.dist-info/licenses/LICENSE,sha256=qvo2BvsFUcC3_3LOk36ZKcaMp_j1AFMfBoCNRFcyrco,1076
38
- sqlalign-1.0.2.dist-info/RECORD,,
34
+ sqlalign-1.1.0.dist-info/METADATA,sha256=Ulysk4XBvaA7rKLZ8HB5OmOI5Xnkl4YRPylIZ99TF-c,23305
35
+ sqlalign-1.1.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
36
+ sqlalign-1.1.0.dist-info/entry_points.txt,sha256=hfughgpq-gK-8TKgvhw1mDbhlHbBQvPeTc96Jh6-efY,50
37
+ sqlalign-1.1.0.dist-info/licenses/LICENSE,sha256=qvo2BvsFUcC3_3LOk36ZKcaMp_j1AFMfBoCNRFcyrco,1076
38
+ sqlalign-1.1.0.dist-info/RECORD,,
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ sqlalign = sqlalign.cli:console
@@ -1,2 +0,0 @@
1
- [console_scripts]
2
- sqlalign = sqlalign.cli:main