sqlalign 1.1.0__py3-none-any.whl → 1.3.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/casing.py CHANGED
@@ -1,6 +1,6 @@
1
1
  import contextvars
2
2
  from contextlib import contextmanager
3
- from typing import ClassVar
3
+ from typing import ClassVar, NamedTuple
4
4
 
5
5
  from sqlglot import exp
6
6
  from sqlglot.dialects.postgres import Postgres
@@ -31,6 +31,59 @@ def render_style(style: Style):
31
31
  _RENDER_STYLE.reset(token)
32
32
 
33
33
 
34
+ class Source(NamedTuple):
35
+ """The statement being rendered, as the author wrote it."""
36
+
37
+ sql: str
38
+ dialect: str
39
+ literals: dict[str, str] # uppercase form -> spelling, see `as_written`
40
+
41
+
42
+ # What sqlglot normalised away is still in the source, and this is how the
43
+ # renderer reaches it. `INTERVAL '14 days'` parses to `Var(this=DAYS)`, so the
44
+ # author's spelling is gone by the time the generator runs; `SET x TO y` has no
45
+ # node recording that `TO` was written rather than `=`.
46
+ #
47
+ # Ambient for the same reason the style is: the generator is reached through
48
+ # ~57 `render_expr` sites, none of which have the source to pass down.
49
+ _SOURCE: contextvars.ContextVar[Source | None] = contextvars.ContextVar(
50
+ "sqlalign_source", default=None)
51
+
52
+
53
+ def set_source(sql: str, dialect: str):
54
+ """Make `sql` the statement `as_written` and `source_sql` answer for.
55
+
56
+ A set/reset pair rather than a context manager: the caller is the
57
+ per-statement loop in `_format_all`, which already has the `finally` that
58
+ advances its position, and threading a `with` through that block would
59
+ reindent it without making anything clearer.
60
+ """
61
+ from sqlalign.spelling import literal_spellings
62
+ return _SOURCE.set(Source(sql, dialect, literal_spellings(sql, dialect)))
63
+
64
+
65
+ def reset_source(token) -> None:
66
+ _SOURCE.reset(token)
67
+
68
+
69
+ def source_sql() -> str | None:
70
+ """The source of the statement being rendered, when one is set."""
71
+ source = _SOURCE.get()
72
+ return source.sql if source is not None else None
73
+
74
+
75
+ def as_written(literal: str) -> str:
76
+ """`literal` respelt as the source spelt it, when the source spelt it.
77
+
78
+ Case only: the lookup is by uppercase form, so a literal the source does not
79
+ contain comes back unchanged and a substitution can never introduce content
80
+ that was not written. A statement writing one literal two ways offers
81
+ neither spelling, so this returns such a literal unchanged.
82
+ """
83
+ source = _SOURCE.get()
84
+ return literal if source is None else source.literals.get(literal.upper(), literal)
85
+
86
+
34
87
  # Cast-form discriminator (v30.14, version-pinned; revisit on sqlglot upgrade):
35
88
  # `::` sources parse to a Cast node carrying only {'this', 'to'}. CAST()/
36
89
  # TRY_CAST() sources always carry these four CAST-specific keys too, even
@@ -65,6 +118,22 @@ class _HouseCastMixin:
65
118
  return target + sql[len("DECIMAL"):]
66
119
  return sql
67
120
 
121
+ def interval_sql(self, expression: exp.Interval) -> str:
122
+ """`INTERVAL '14 days'`, not `INTERVAL '14 DAYS'`.
123
+
124
+ sqlglot uppercases the unit while parsing, so rendering from the node
125
+ alone always respells a lowercase interval. Since 1.2's token census
126
+ compares string literals byte-for-byte, that respelling is caught -- and
127
+ `interval '14 days'` is common enough that catching it means the whole
128
+ statement stops formatting. The source spelling is put back instead.
129
+ """
130
+ sql = super().interval_sql(expression)
131
+ head, quote, rest = sql.partition("'")
132
+ if not quote:
133
+ return sql
134
+ body, quote, tail = rest.rpartition("'")
135
+ return f"{head}'{as_written(body)}'{tail}"
136
+
68
137
  def neq_sql(self, expression: exp.NEQ) -> str:
69
138
  # sqlglot erases the source `<>`/`!=` spelling at parse, so a form must be
70
139
  # chosen when printing: Style.neq_style (house: `!=`). conditions.py's
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 ALL_ALIGN_TARGETS, PRESETS, SUPPORTED_DIALECTS, Style
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,17 @@ 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
- p.add_argument("--dialect", choices=sorted(SUPPORTED_DIALECTS), default="postgres",
196
- help="the SQL dialect to parse and print (default: postgres)")
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)")
208
+ p.add_argument("--lines", action="append", metavar="START:END", default=None,
209
+ help="format only statements overlapping these 1-based, "
210
+ "inclusive line numbers; the rest of the file is left "
211
+ "byte-identical. Repeatable. Applies to one file (or "
212
+ "stdin), since line numbers mean nothing across several")
197
213
  p.add_argument("--line-ending", choices=["auto", "lf", "crlf"], default="auto",
198
214
  help="line endings to write: auto preserves the file's own (default)")
199
215
  # Config-file plumbing.
@@ -224,6 +240,11 @@ def build_parser() -> argparse.ArgumentParser:
224
240
  p.add_argument("--lint", action="store_true",
225
241
  help="after formatting, run sqlfluff over the result "
226
242
  "(needs the optional `sqlalign[lint]` extra)")
243
+ p.add_argument("--sqlfluff-config", metavar="PATH", type=Path,
244
+ help="lint with this sqlfluff config instead of the one "
245
+ "discovered next to each file. For a shared config that "
246
+ "lives outside the repository, which discovery cannot "
247
+ "reach. Requires --lint")
227
248
  p.add_argument("--print-sqlfluff-config", action="store_true",
228
249
  help="print a .sqlfluff that lets sqlfluff run alongside "
229
250
  "sqlalign without fighting it, and exit")
@@ -283,7 +304,48 @@ def build_parser() -> argparse.ArgumentParser:
283
304
  return p
284
305
 
285
306
 
307
+ def _quiet_sqlglot_fallbacks() -> None:
308
+ """Stop sqlglot narrating its own parser fallbacks on our stderr.
309
+
310
+ A statement sqlglot cannot model logs `'SET ROLE reporting' contains
311
+ unsupported syntax. Falling back to parsing as a 'Command'.` -- unprefixed,
312
+ interleaved with sqlalign's output, and about an internal detail of the
313
+ parser. sqlalign reports the same statement itself, by name and with the
314
+ text it passed through, so the warning is a second and worse copy of a
315
+ message the user already gets.
316
+
317
+ Done in the CLI rather than the library: `sqlalign.format` runs inside
318
+ someone else's program, and silencing a dependency's logger there is not a
319
+ formatter's business.
320
+ """
321
+ import logging
322
+ logging.getLogger("sqlglot").setLevel(logging.ERROR)
323
+
324
+
325
+ def parse_line_ranges(values: list[str]) -> tuple[tuple[int, int], ...]:
326
+ """`["3:9", "20"]` as 1-based inclusive spans.
327
+
328
+ A bare number is the single line, so `--lines 12` is the obvious thing and
329
+ does not have to be written `--lines 12:12`.
330
+ """
331
+ ranges = []
332
+ for value in values:
333
+ start, sep, end = value.partition(":")
334
+ try:
335
+ first = int(start)
336
+ last = int(end) if sep else first
337
+ except ValueError:
338
+ raise ValueError(f"expected START:END, got {value!r}") from None
339
+ if first < 1:
340
+ raise ValueError(f"line numbers start at 1, got {value!r}")
341
+ if last < first:
342
+ raise ValueError(f"range ends before it starts: {value!r}")
343
+ ranges.append((first, last))
344
+ return tuple(ranges)
345
+
346
+
286
347
  def main(argv: list[str] | None = None) -> int:
348
+ _quiet_sqlglot_fallbacks()
287
349
  p = build_parser()
288
350
  args = p.parse_args(argv)
289
351
 
@@ -309,6 +371,22 @@ def main(argv: list[str] | None = None) -> int:
309
371
  "on_placement": args.on_placement,
310
372
  }
311
373
 
374
+ def dialect_for(path: Path) -> str:
375
+ """The dialect for one input file: flag, then config, then postgres.
376
+
377
+ The flag wins so a one-off run can override a committed config, which is
378
+ the same precedence every style setting already follows.
379
+ """
380
+ if args.dialect is not None:
381
+ return args.dialect
382
+ if args.isolated:
383
+ return DEFAULT_DIALECT
384
+ config = args.config if args.config is not None else configfile.find_config(path)
385
+ if config is None:
386
+ return DEFAULT_DIALECT
387
+ return configfile.load_dialect(
388
+ config, strict=not args.no_strict_config) or DEFAULT_DIALECT
389
+
312
390
  def style_for(path: Path) -> Style:
313
391
  """Settings for one input file: house defaults < config file < flags.
314
392
  Resolved per file so one invocation can span repos with different
@@ -320,6 +398,14 @@ def main(argv: list[str] | None = None) -> int:
320
398
  print(f"sqlalign: {w}", file=sys.stderr)
321
399
  return style
322
400
 
401
+ if args.sqlfluff_config is not None:
402
+ if not args.lint:
403
+ # Accepting it silently would leave a reader believing their config
404
+ # was used, which is worse than the flag being unavailable.
405
+ p.error("--sqlfluff-config only applies to --lint")
406
+ if not args.sqlfluff_config.is_file():
407
+ p.error(f"--sqlfluff-config: no such file: {args.sqlfluff_config}")
408
+
323
409
  if args.init:
324
410
  # Refuses to overwrite: a config is a decision a team already made, and
325
411
  # a starter is only ever the first one.
@@ -345,7 +431,7 @@ def main(argv: list[str] | None = None) -> int:
345
431
 
346
432
  if args.gui:
347
433
  from sqlalign.gui import run
348
- return run(args.dialect)
434
+ return run(dialect_for(Path(".")))
349
435
 
350
436
  if not args.files and not (args.print_sqlfluff_config or args.gui or args.init):
351
437
  p.error("the following arguments are required: files")
@@ -355,6 +441,19 @@ def main(argv: list[str] | None = None) -> int:
355
441
  if "-" in args.files and len(args.files) > 1:
356
442
  p.error("`-` reads stdin and cannot be combined with file arguments")
357
443
 
444
+ line_ranges = None
445
+ if args.lines is not None:
446
+ try:
447
+ line_ranges = parse_line_ranges(args.lines)
448
+ except ValueError as e:
449
+ p.error(f"--lines: {e}")
450
+ # One range against many files would mean "line 12 of each", which
451
+ # nobody wants and which would silently reformat the wrong thing. A
452
+ # directory is the same mistake spelled shorter -- it expands to every
453
+ # .sql file under it.
454
+ if len(args.files) != 1 or Path(args.files[0]).is_dir():
455
+ p.error("--lines applies to a single file (or `-`)")
456
+
358
457
  if args.print_sqlfluff_config:
359
458
  # Resolved against the first file like --show-config, so the generated
360
459
  # config reflects the style that actually applies there rather than the
@@ -367,7 +466,7 @@ def main(argv: list[str] | None = None) -> int:
367
466
  if args.files else configfile.build_style({}, overrides))
368
467
  except configfile.ConfigError as e:
369
468
  p.error(str(e))
370
- print(sqlfluff_config(style, args.dialect), end="")
469
+ print(sqlfluff_config(style, dialect_for(Path("."))), end="")
371
470
  return 0
372
471
 
373
472
  if args.show_config:
@@ -380,6 +479,12 @@ def main(argv: list[str] | None = None) -> int:
380
479
  for w in warns:
381
480
  print(f"sqlalign: {w}", file=sys.stderr)
382
481
  print(f"# {source}" if source else "# built-in defaults (no config file found)")
482
+ # Printed with the settings because it IS one, and this output is
483
+ # documented as TOML a reader could paste back -- omitting a key would
484
+ # make the pasted config mean something different. Kept above the style
485
+ # block, and out of Style, because it selects the grammar rather than
486
+ # the layout.
487
+ print(f'dialect = "{dialect_for(Path(args.files[0]))}"')
383
488
  print(configfile.describe(style))
384
489
  return 0
385
490
 
@@ -448,7 +553,7 @@ def main(argv: list[str] | None = None) -> int:
448
553
  sys.stdout.write(original)
449
554
  continue
450
555
  try:
451
- result = format_sql(normalized, args.dialect, style)
556
+ result = format_sql(normalized, dialect_for(path), style, line_ranges)
452
557
  except Exception as e: # parse/safety failures surface as exit 2, file untouched
453
558
  print(f"sqlalign: {name}: {e}", file=sys.stderr)
454
559
  rc = 2
@@ -496,7 +601,8 @@ def main(argv: list[str] | None = None) -> int:
496
601
  if args.lint:
497
602
  # Lint what would be written, so --check and --stdout report on the
498
603
  # formatted result rather than on whatever is currently on disk.
499
- code, out, err = lint(path, formatted, style, args.dialect)
604
+ code, out, err = lint(path, formatted, style, dialect_for(path),
605
+ args.sqlfluff_config)
500
606
  sys.stdout.write(out)
501
607
  sys.stderr.write(err)
502
608
  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
- # `exclude` selects FILES rather than style, so it is read separately and never
48
- # reaches Style. Kept in KNOWN_KEYS so a config carrying it is still valid.
49
- _NON_STYLE_KEYS = frozenset({"exclude"})
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
@@ -4,10 +4,11 @@ from collections import namedtuple
4
4
  import sqlglot
5
5
  from sqlglot import exp
6
6
  from sqlglot.errors import TokenError
7
+ from sqlglot.tokens import TokenType
7
8
 
8
- from sqlalign import keywordcase, plpgsql, templating
9
+ from sqlalign import keywordcase, plpgsql, sourcecase, spelling, templating
9
10
  from sqlalign.align import apply_align_targets, render
10
- from sqlalign.casing import parse_dialect, render_style
11
+ from sqlalign.casing import parse_dialect, render_style, reset_source, set_source
11
12
  from sqlalign.commas import apply_comma_position
12
13
  from sqlalign.layout import Unsupported, layout_statement
13
14
  from sqlalign.layout import comments as _comments
@@ -39,6 +40,16 @@ class SafetyError(RuntimeError):
39
40
  pass
40
41
 
41
42
 
43
+ class Rewrite(SafetyError):
44
+ """The output spells something differently from the input.
45
+
46
+ A sibling of `CommentLoss` for the same reason: it shares the
47
+ upstream-round-trip branch while being reported as its own cause. Losing a
48
+ comment, changing an expression, and respelling a construct are three
49
+ different bugs.
50
+ """
51
+
52
+
42
53
  class CommentLoss(SafetyError):
43
54
  """The output does not carry the same comments as the input.
44
55
 
@@ -281,10 +292,35 @@ def comment_text(sql: str, dialect: str) -> list[str]:
281
292
  sqlglot hangs a comment off the token it precedes rather than putting it in
282
293
  the tree, which is why the AST check cannot see one:
283
294
  `ast_equal("SELECT a -- note", "SELECT a", ...)` is True.
295
+
296
+ A `$$ ... $$` body is ONE token, so its comments are not among that token's
297
+ own -- this returned `[]` for an entire procedure. `comments_equal` was then
298
+ trivially true for anything inside one, and `DECLARE n int; -- count from
299
+ the source table` shipped as `-- count FROM the source TABLE;`, keyword-cased
300
+ with a semicolon inside the comment, no decline. Descending into the body
301
+ puts those comments back under the guard.
284
302
  """
285
303
  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 [])]
304
+ comments = []
305
+ for token in tokenizer.tokenize(sql):
306
+ comments += [c.strip() for c in (token.comments or [])]
307
+ if (token.token_type is TokenType.HEREDOC_STRING
308
+ and len(token.text) < len(sql)
309
+ and _maybe_comment(token.text)):
310
+ comments += comment_text(token.text, dialect)
311
+ return comments
312
+
313
+
314
+ def _maybe_comment(text: str) -> bool:
315
+ """Whether `text` is worth tokenizing a second time to look for comments.
316
+
317
+ Descending into every body doubled the tokenizing work for every procedure
318
+ in a tree, and most bodies hold no comment at all. Two substring scans
319
+ decide it: a body with neither marker cannot contain one, and a body with a
320
+ marker is tokenized properly rather than pattern-matched, so a `--` inside a
321
+ string literal still does not count as a comment.
322
+ """
323
+ return "--" in text or "/*" in text
288
324
 
289
325
 
290
326
  def comments_equal(a: str, b: str, dialect: str) -> bool:
@@ -294,9 +330,9 @@ def comments_equal(a: str, b: str, dialect: str) -> bool:
294
330
  the end of the row above -- where it sits is expected to change, what it
295
331
  says is not.
296
332
 
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.
333
+ Comments inside a `$$` body are included: the body is one token to the
334
+ tokenizer, and `comment_text` descends into it rather than leaving those
335
+ comments to a structural check that casefolds them away.
300
336
  """
301
337
  try:
302
338
  return comment_text(a, dialect) == comment_text(b, dialect)
@@ -308,6 +344,110 @@ def comments_equal(a: str, b: str, dialect: str) -> bool:
308
344
  return False
309
345
 
310
346
 
347
+ def _overlaps(text: str, pos: int, stmt: str, lines: tuple[tuple[int, int], ...]) -> bool:
348
+ """Whether `stmt`, sitting at `pos` in `text`, touches any of `lines`.
349
+
350
+ Measured over the statement's content rather than the raw slice: a slice
351
+ carries the blank lines that separated it from the one before, and counting
352
+ those would make an empty line above a statement select it.
353
+ """
354
+ lead = len(stmt) - len(stmt.lstrip("\n"))
355
+ body = stmt.strip("\n")
356
+ if not body.strip():
357
+ return False
358
+ first = text.count("\n", 0, pos + lead) + 1
359
+ last = first + body.count("\n")
360
+ return any(start <= last and first <= end for start, end in lines)
361
+
362
+
363
+ def _cased_from_source(stmt: str, node, dialect: str, style, snippet: str) -> str:
364
+ """The statement cased from its own source, or `Rewrite` if that is unsafe.
365
+
366
+ Reached only when the render respelt something. The generator has already
367
+ proved it cannot print this statement as written, so the choice is between
368
+ passing it through untouched and formatting it the one way that cannot lose
369
+ a spelling: from the source, changing nothing but keyword case.
370
+
371
+ Every check the render had to pass is re-run here, because this output is
372
+ not the one they were run against. A `Command` has no parse to tell grammar
373
+ from content, so it is not eligible and falls straight through.
374
+ """
375
+ if _has_body(stmt, dialect) or not sourcecase.renders_from_source(node):
376
+ # A body is excluded deliberately. Casing a whole procedure from source
377
+ # would trade the layout of every clause in it for the one clause that
378
+ # respelt, which is a worse outcome than passing it through.
379
+ raise Rewrite(f"formatting respelled the statement near: {snippet}")
380
+ cased = sourcecase.recase(stmt, node, dialect, style.keyword_case)
381
+ if (ast_equal(stmt, cased, dialect)
382
+ and comments_equal(stmt, cased, dialect)
383
+ and spelling_equal(stmt, cased, dialect)):
384
+ return cased
385
+ raise Rewrite(f"formatting respelled the statement near: {snippet}")
386
+
387
+
388
+ def _has_body(sql: str, dialect: str) -> bool:
389
+ """Whether the statement carries a body sqlalign reformats internally.
390
+
391
+ A `$$` body is one string literal to the tokenizer, and a T-SQL
392
+ `CREATE PROCEDURE ... AS BEGIN ... END` is the same shape spelled
393
+ differently, so laying either out changes tokens for a reason that is not a
394
+ rewrite. Both are already compared structurally.
395
+ """
396
+ if plpgsql.split_body(sql) is not None:
397
+ return True
398
+ try:
399
+ node = sqlglot.parse_one(sql, dialect=dialect)
400
+ except Exception:
401
+ return False
402
+ return (isinstance(node, exp.Create)
403
+ and str(node.args.get("kind") or "").upper() in {"PROCEDURE", "FUNCTION"})
404
+
405
+
406
+ def spelling_equal(a: str, b: str, dialect: str) -> bool:
407
+ """Whether `b` spells everything the way `a` did.
408
+
409
+ Compared after normalizing the three things sqlalign's settings choose --
410
+ keyword case, optional `AS`, and synonym spellings -- so an ordinary
411
+ reformat is equal and only a change the author did not ask for is not.
412
+ """
413
+ try:
414
+ parts_a = plpgsql.split_body(a)
415
+ parts_b = plpgsql.split_body(b)
416
+ if parts_a is not None and parts_b is not None:
417
+ return _plpgsql_spelling_equal(parts_a, parts_b, dialect)
418
+ return (spelling.token_census(a, dialect)
419
+ == spelling.token_census(b, dialect))
420
+ except TokenError:
421
+ return True # unreadable input declines earlier; do not invent a reason
422
+
423
+
424
+ def _plpgsql_spelling_equal(parts_a, parts_b, dialect: str) -> bool:
425
+ """The census for a statement with a `$$` body, clause against clause.
426
+
427
+ A whole-statement census cannot do this. The tokenizer sees a body as one
428
+ token, so it compares as opaque and sees nothing inside; descending into it
429
+ compares a laid-out body against an unformatted one, and that differs for
430
+ reasons which are not rewrites -- 102 tests said so. Clause by clause,
431
+ against the clause it was rendered from, is the comparison that means
432
+ something, and `body_clauses` splits both sides the same way by design.
433
+
434
+ Until this existed, `_has_body` excluded these statements from the census
435
+ outright, so a respelling inside a procedure had nothing catching it -- which
436
+ is how `INTERVAL '14 days'` shipped as `'14 DAYS'` from inside one.
437
+ """
438
+ head_a, body_a, tail_a = parts_a
439
+ head_b, body_b, tail_b = parts_b
440
+ if (spelling.token_census(head_a + tail_a, dialect)
441
+ != spelling.token_census(head_b + tail_b, dialect)):
442
+ return False
443
+ clauses_a = plpgsql.body_clauses(body_a)
444
+ clauses_b = plpgsql.body_clauses(body_b)
445
+ if len(clauses_a) != len(clauses_b):
446
+ return False
447
+ return all(spelling.token_census(x, dialect) == spelling.token_census(y, dialect)
448
+ for x, y in zip(clauses_a, clauses_b, strict=False))
449
+
450
+
311
451
  def ast_equal(a: str, b: str, dialect: str) -> bool:
312
452
  """AST-equality safety check. sqlglot sees a `$$…$$` body as one opaque
313
453
  string, so raw AST comparison would reject any body reformatting. When both
@@ -513,11 +653,18 @@ def _join_statements(entries, blanks=None):
513
653
  return "".join(pieces)
514
654
 
515
655
 
516
- def format_sql(text: str, dialect: str = "postgres", style: Style = HOUSE) -> FormatResult:
656
+ def format_sql(text: str, dialect: str = "postgres", style: Style = HOUSE,
657
+ lines: tuple[tuple[int, int], ...] | None = None) -> FormatResult:
517
658
  """Format `text`. `style` carries every knob; it is also published as the
518
659
  ambient render style for the duration of the call so `render_expr` (called
519
660
  from ~57 handler sites) can read output-spelling knobs without every handler
520
- signature having to carry them."""
661
+ signature having to carry them.
662
+
663
+ `lines` narrows the work to statements overlapping the given 1-based
664
+ inclusive line ranges; everything else comes back byte-identical. Whole
665
+ statements, because half a statement does not parse -- a range that starts
666
+ mid-statement formats that statement entire.
667
+ """
521
668
  if dialect not in SUPPORTED_DIALECTS:
522
669
  # Refuse rather than mis-format. The handlers emit keywords chosen for
523
670
  # the verified dialects, and the AST check cannot catch one that is
@@ -527,7 +674,7 @@ def format_sql(text: str, dialect: str = "postgres", style: Style = HOUSE) -> Fo
527
674
  f"{', '.join(sorted(SUPPORTED_DIALECTS))}")
528
675
  with render_style(style):
529
676
  if not style.protect_templating or not templating.has_templating(text):
530
- return _format_all(text, dialect, style)
677
+ return _format_all(text, dialect, style, lines)
531
678
  # Templated SQL (dbt/Jinja) does not parse. Mask each expression with a
532
679
  # same-WIDTH placeholder so every alignment column is computed against the
533
680
  # real width, format normally, then restore. The whole pipeline: layout,
@@ -542,7 +689,10 @@ def format_sql(text: str, dialect: str = "postgres", style: Style = HOUSE) -> Fo
542
689
  # exactly the way --report exists to prevent.
543
690
  return FormatResult(text, [f"templating not maskable, passed through: {e}"],
544
691
  1, (Decline("unsupported", "templating not maskable"),))
545
- result = _format_all(masked, dialect, style)
692
+ # Masking replaces each template expression with a placeholder of the
693
+ # same width, so line numbers are the same on both sides and a range
694
+ # given against the real file still selects the right statements.
695
+ result = _format_all(masked, dialect, style, lines)
546
696
  # Rebuilt for the unmasked text only; the counts ride through unchanged.
547
697
  # Dropping them blinded --report and --max-declines for every templated
548
698
  # file, which is most of a dbt project.
@@ -550,7 +700,8 @@ def format_sql(text: str, dialect: str = "postgres", style: Style = HOUSE) -> Fo
550
700
  result.warnings, result.statements, result.declines)
551
701
 
552
702
 
553
- def _format_all(text: str, dialect: str, style: Style) -> FormatResult:
703
+ def _format_all(text: str, dialect: str, style: Style,
704
+ lines: tuple[tuple[int, int], ...] | None = None) -> FormatResult:
554
705
  warnings, out, declines = [], [], []
555
706
  statements = 0
556
707
  pos = 0
@@ -559,7 +710,15 @@ def _format_all(text: str, dialect: str, style: Style) -> FormatResult:
559
710
  out.append((piece, is_statement, _body_is_multiline(piece)))
560
711
 
561
712
  for stmt in split_statements(text, dialect):
713
+ literals = None
562
714
  try:
715
+ if lines is not None and not _overlaps(text, pos, stmt, lines):
716
+ # Outside the requested range: byte-identical, and not counted.
717
+ # Emitted as trivia rather than as a statement so the blank-line
718
+ # rule does not adjust the space around something the caller did
719
+ # not ask to have touched.
720
+ emit(stmt, False)
721
+ continue
563
722
  if not stmt.strip().rstrip(";").strip():
564
723
  emit(stmt, False)
565
724
  continue
@@ -600,6 +759,9 @@ def _format_all(text: str, dialect: str, style: Style) -> FormatResult:
600
759
  # Distinct wording per class so a real bug is visible in stderr, not
601
760
  # silently indistinguishable from an expected decline.
602
761
  try:
762
+ # Scoped to the statement: a spelling may only be restored from
763
+ # the statement it was written in.
764
+ literals = set_source(stmt, dialect)
603
765
  if dialect == "tsql" and _TSQL_LOSSY_TYPES.search(stmt):
604
766
  raise Unsupported("tsql: type whose spelling sqlglot cannot preserve")
605
767
  node0 = _first_expression(parsed)
@@ -626,6 +788,14 @@ def _format_all(text: str, dialect: str, style: Style) -> FormatResult:
626
788
  # invisible to every safety check in the engine.
627
789
  if not comments_equal(stmt, formatted, dialect):
628
790
  raise CommentLoss(f"formatting changed a comment near: {snippet}")
791
+ # The AST check cannot see a rewrite sqlglot's own parser makes:
792
+ # both sides go through it and collapse to one tree, so
793
+ # `ALTER COLUMN x TYPE t` printed as `SET DATA TYPE t` compares
794
+ # equal. Comparing tokens catches it. A statement with a `$$`
795
+ # body is compared clause by clause rather than as one token
796
+ # stream -- see `_plpgsql_spelling_equal`.
797
+ if not spelling_equal(stmt, formatted, dialect):
798
+ formatted = _cased_from_source(stmt, node0, dialect, style, snippet)
629
799
  except Unsupported as exc:
630
800
  # The reason rides in the message so `--report` can name the
631
801
  # construct, not just count the declines.
@@ -646,7 +816,11 @@ def _format_all(text: str, dialect: str, style: Style) -> FormatResult:
646
816
  declines.append(Decline("upstream", "sqlglot round-trip is unstable"))
647
817
  emit(stmt, True)
648
818
  continue
649
- if isinstance(safety, CommentLoss):
819
+ if isinstance(safety, Rewrite):
820
+ warnings.append("formatting would respell this statement, passed "
821
+ f"through unformatted: {snippet}")
822
+ declines.append(Decline("safety", "output would respell the statement"))
823
+ elif isinstance(safety, CommentLoss):
650
824
  warnings.append("formatting would change a comment, passed through "
651
825
  f"unformatted: {snippet}")
652
826
  declines.append(Decline("safety", "output would change a comment"))
@@ -665,6 +839,8 @@ def _format_all(text: str, dialect: str, style: Style) -> FormatResult:
665
839
  continue
666
840
  emit(formatted, True)
667
841
  finally:
842
+ if literals is not None:
843
+ reset_source(literals)
668
844
  pos += len(stmt)
669
845
  return FormatResult(_join_statements(out, style.blank_lines_between_statements),
670
846
  warnings, statements, tuple(declines))