sqlalign 1.0.1__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
@@ -1,6 +1,11 @@
1
1
  import argparse
2
2
  import difflib
3
+ import errno
4
+ import os
5
+ import shutil
3
6
  import sys
7
+ import tempfile
8
+ import urllib.parse
4
9
  from fnmatch import fnmatch
5
10
  from pathlib import Path
6
11
 
@@ -8,7 +13,44 @@ from sqlalign import configfile
8
13
  from sqlalign.formatter import format_sql
9
14
  from sqlalign.lint import LintUnavailable, lint, version_warning
10
15
  from sqlalign.sqlfluffconfig import sqlfluff_config
11
- from sqlalign.style import PRESETS, SUPPORTED_DIALECTS, Style
16
+ from sqlalign.style import ALL_ALIGN_TARGETS, PRESETS, SUPPORTED_DIALECTS, Style
17
+
18
+
19
+ def _write_atomically(path: Path, text: str) -> None:
20
+ """Replace the contents of `path` in a single step.
21
+
22
+ `open(path, "w")` truncates before it writes, so an interrupted run leaves
23
+ the file short: the input is destroyed and the replacement never arrives.
24
+ Writing a neighbour and renaming it means what is on disk is either the
25
+ whole old file or the whole new one, and a run that is cut off half way
26
+ through a repository has changed nothing it did not finish.
27
+
28
+ The temp file is created in the target's own directory so the rename cannot
29
+ cross a filesystem, and the symlink is resolved first so a linked file is
30
+ written THROUGH rather than replaced by a regular file.
31
+ """
32
+ target = path.resolve()
33
+ # `os.replace` only needs a writable directory, so a read-only file would
34
+ # otherwise be silently overwritten -- which `open(path, "w")` refused.
35
+ if not os.access(target, os.W_OK):
36
+ raise PermissionError(errno.EACCES, os.strerror(errno.EACCES), str(target))
37
+
38
+ try:
39
+ handle, name = tempfile.mkstemp(dir=target.parent,
40
+ prefix=f".{target.name}.", suffix=".tmp")
41
+ except OSError as e:
42
+ # An unwritable DIRECTORY fails here. Reported against the file the user
43
+ # named rather than the temp file they have never heard of.
44
+ raise OSError(e.errno, e.strerror, str(target)) from e
45
+ temp = Path(name)
46
+ try:
47
+ with os.fdopen(handle, "w", newline="") as f:
48
+ f.write(text)
49
+ shutil.copymode(target, temp)
50
+ os.replace(temp, target)
51
+ except BaseException:
52
+ temp.unlink(missing_ok=True)
53
+ raise
12
54
 
13
55
 
14
56
  def _is_excluded(path: Path, root: Path, patterns: list[str]) -> bool:
@@ -68,9 +110,60 @@ def _report(seen: int, declined: int, causes: dict[tuple[str, str], int]) -> str
68
110
  width = max(len(kind) for kind, _ in causes)
69
111
  for (kind, reason), count in sorted(causes.items(), key=lambda kv: (-kv[1], kv[0])):
70
112
  lines.append(f" {count:>4} {kind:<{width}} {reason}")
113
+ ask = _ask_for_construct(causes)
114
+ if ask:
115
+ lines += ["", ask]
71
116
  return "\n".join(lines)
72
117
 
73
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
+
74
167
  def _version() -> str:
75
168
  """The installed version, or a marker when running from a source tree that
76
169
  was never installed."""
@@ -113,11 +206,18 @@ def build_parser() -> argparse.ArgumentParser:
113
206
  help="ignore any config file and use the built-in defaults")
114
207
  p.add_argument("--show-config", action="store_true",
115
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")
116
213
  p.add_argument("--gui", action="store_true",
117
214
  help="(experimental) open the settings panel with a live preview, and exit")
118
215
  p.add_argument("--report", action="store_true",
119
216
  help="print a coverage summary: how many statements were "
120
- "formatted, and what the rest declined on")
217
+ "formatted, and what the rest declined on. Adds output "
218
+ "without changing the mode, so on its own it still "
219
+ "rewrites; pair it with `--check` to survey without "
220
+ "writing")
121
221
  p.add_argument("--max-declines", type=int, metavar="N",
122
222
  help="exit 1 if more than N statements are passed through "
123
223
  "unformatted (implies --report)")
@@ -149,11 +249,12 @@ def build_parser() -> argparse.ArgumentParser:
149
249
  dest="format_dollar_bodies",
150
250
  help="leave dollar-quoted ($$) procedure and function bodies untouched")
151
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.
152
254
  help="comma-separated alignment targets to keep. Default is every "
153
255
  "target except table_names, which is opt-in because it pads "
154
256
  "the FROM/JOIN keyword out to a shared table column. "
155
- "Valid: aliases, table_names, operators, join_conditions, "
156
- "case_results, column_types, column_constraints")
257
+ f"Valid: {', '.join(sorted(ALL_ALIGN_TARGETS))}")
157
258
  p.add_argument("--comma-position", choices=["leading", "trailing"],
158
259
  help="where the separator comma sits in a stacked list (default: leading)")
159
260
  p.add_argument("--boolean-operator-position", choices=["leading", "trailing"],
@@ -219,13 +320,41 @@ def main(argv: list[str] | None = None) -> int:
219
320
  print(f"sqlalign: {w}", file=sys.stderr)
220
321
  return style
221
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
+
222
346
  if args.gui:
223
347
  from sqlalign.gui import run
224
348
  return run(args.dialect)
225
349
 
226
- 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):
227
351
  p.error("the following arguments are required: files")
228
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
+
229
358
  if args.print_sqlfluff_config:
230
359
  # Resolved against the first file like --show-config, so the generated
231
360
  # config reflects the style that actually applies there rather than the
@@ -275,14 +404,28 @@ def main(argv: list[str] | None = None) -> int:
275
404
  for path in targets:
276
405
  name = str(path)
277
406
  try:
278
- # newline="" disables universal-newline translation so CRLF/CR bytes
279
- # survive into `original` and can be detected below (v1 is LF-only).
280
- with path.open(newline="") as f:
281
- 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()
282
417
  except OSError as e:
283
418
  print(f"sqlalign: {e}", file=sys.stderr)
284
419
  rc = 2
285
420
  continue
421
+ except UnicodeDecodeError:
422
+ # Guessing at an encoding would mean writing the file back in a
423
+ # different one, which is precisely the kind of change sqlalign
424
+ # exists not to make. The file is reported and left exactly as it is.
425
+ print(f"sqlalign: {name}: not valid UTF-8 — left unchanged",
426
+ file=sys.stderr)
427
+ rc = 2
428
+ continue
286
429
  try:
287
430
  style = style_for(path)
288
431
  except configfile.ConfigError as e: # a broken config must not be guessed past
@@ -298,7 +441,10 @@ def main(argv: list[str] | None = None) -> int:
298
441
  if "\r" in normalized:
299
442
  print(f"sqlalign: {name}: lone CR line endings — passed through untouched",
300
443
  file=sys.stderr)
301
- 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 == "-":
302
448
  sys.stdout.write(original)
303
449
  continue
304
450
  try:
@@ -318,13 +464,12 @@ def main(argv: list[str] | None = None) -> int:
318
464
  # diff on every line) instead of differing purely by "\r".
319
465
  target_ending = source_ending if args.line_ending == "auto" else args.line_ending
320
466
  formatted = result.text.replace("\n", "\r\n") if target_ending == "crlf" else result.text
321
- if args.stdout:
322
- sys.stdout.write(formatted)
323
- elif args.check or args.diff:
467
+ if args.check or args.diff:
324
468
  # Both write nothing and report through the exit code; they differ in
325
469
  # what they print. --check names the files that would change (enough
326
470
  # for CI to be actionable without burying the log in diffs); --diff
327
- # shows the change itself.
471
+ # shows the change itself. For `-` the name printed is `-`, which is
472
+ # what the reader passed.
328
473
  if formatted != original:
329
474
  if args.diff:
330
475
  sys.stdout.writelines(difflib.unified_diff(
@@ -334,9 +479,19 @@ def main(argv: list[str] | None = None) -> int:
334
479
  else:
335
480
  print(f"would reformat {name}")
336
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)
337
486
  elif formatted != original:
338
- with open(path, "w", newline="") as f:
339
- f.write(formatted)
487
+ try:
488
+ _write_atomically(path, formatted)
489
+ except OSError as e:
490
+ # A per-file failure is reported and skipped, like an unreadable
491
+ # file above -- one unwritable file must not abort the run.
492
+ print(f"sqlalign: {e}", file=sys.stderr)
493
+ rc = 2
494
+ continue
340
495
 
341
496
  if args.lint:
342
497
  # Lint what would be written, so --check and --stdout report on the
@@ -356,5 +511,31 @@ def main(argv: list[str] | None = None) -> int:
356
511
  return rc
357
512
 
358
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
+
359
540
  if __name__ == "__main__":
360
- 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