sqlalign 1.2.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
@@ -205,6 +205,11 @@ def build_parser() -> argparse.ArgumentParser:
205
205
  p.add_argument("--dialect", choices=sorted(SUPPORTED_DIALECTS), default=None,
206
206
  help="the SQL dialect to parse and print. Overrides a "
207
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")
208
213
  p.add_argument("--line-ending", choices=["auto", "lf", "crlf"], default="auto",
209
214
  help="line endings to write: auto preserves the file's own (default)")
210
215
  # Config-file plumbing.
@@ -235,6 +240,11 @@ def build_parser() -> argparse.ArgumentParser:
235
240
  p.add_argument("--lint", action="store_true",
236
241
  help="after formatting, run sqlfluff over the result "
237
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")
238
248
  p.add_argument("--print-sqlfluff-config", action="store_true",
239
249
  help="print a .sqlfluff that lets sqlfluff run alongside "
240
250
  "sqlalign without fighting it, and exit")
@@ -294,7 +304,48 @@ def build_parser() -> argparse.ArgumentParser:
294
304
  return p
295
305
 
296
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
+
297
347
  def main(argv: list[str] | None = None) -> int:
348
+ _quiet_sqlglot_fallbacks()
298
349
  p = build_parser()
299
350
  args = p.parse_args(argv)
300
351
 
@@ -347,6 +398,14 @@ def main(argv: list[str] | None = None) -> int:
347
398
  print(f"sqlalign: {w}", file=sys.stderr)
348
399
  return style
349
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
+
350
409
  if args.init:
351
410
  # Refuses to overwrite: a config is a decision a team already made, and
352
411
  # a starter is only ever the first one.
@@ -382,6 +441,19 @@ def main(argv: list[str] | None = None) -> int:
382
441
  if "-" in args.files and len(args.files) > 1:
383
442
  p.error("`-` reads stdin and cannot be combined with file arguments")
384
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
+
385
457
  if args.print_sqlfluff_config:
386
458
  # Resolved against the first file like --show-config, so the generated
387
459
  # config reflects the style that actually applies there rather than the
@@ -481,7 +553,7 @@ def main(argv: list[str] | None = None) -> int:
481
553
  sys.stdout.write(original)
482
554
  continue
483
555
  try:
484
- result = format_sql(normalized, dialect_for(path), style)
556
+ result = format_sql(normalized, dialect_for(path), style, line_ranges)
485
557
  except Exception as e: # parse/safety failures surface as exit 2, file untouched
486
558
  print(f"sqlalign: {name}: {e}", file=sys.stderr)
487
559
  rc = 2
@@ -529,7 +601,8 @@ def main(argv: list[str] | None = None) -> int:
529
601
  if args.lint:
530
602
  # Lint what would be written, so --check and --stdout report on the
531
603
  # formatted result rather than on whatever is currently on disk.
532
- code, out, err = lint(path, formatted, style, dialect_for(path))
604
+ code, out, err = lint(path, formatted, style, dialect_for(path),
605
+ args.sqlfluff_config)
533
606
  sys.stdout.write(out)
534
607
  sys.stderr.write(err)
535
608
  if code:
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, spelling, 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
@@ -291,10 +292,35 @@ def comment_text(sql: str, dialect: str) -> list[str]:
291
292
  sqlglot hangs a comment off the token it precedes rather than putting it in
292
293
  the tree, which is why the AST check cannot see one:
293
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.
294
302
  """
295
303
  tokenizer = sqlglot.Dialect.get_or_raise(dialect).tokenizer_class()
296
- return [c.strip() for token in tokenizer.tokenize(sql)
297
- 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
298
324
 
299
325
 
300
326
  def comments_equal(a: str, b: str, dialect: str) -> bool:
@@ -304,9 +330,9 @@ def comments_equal(a: str, b: str, dialect: str) -> bool:
304
330
  the end of the row above -- where it sits is expected to change, what it
305
331
  says is not.
306
332
 
307
- A `$$` body is a single string literal to the tokenizer, so comments inside
308
- one are invisible here. Those statements are covered structurally by
309
- `_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.
310
336
  """
311
337
  try:
312
338
  return comment_text(a, dialect) == comment_text(b, dialect)
@@ -318,6 +344,47 @@ def comments_equal(a: str, b: str, dialect: str) -> bool:
318
344
  return False
319
345
 
320
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
+
321
388
  def _has_body(sql: str, dialect: str) -> bool:
322
389
  """Whether the statement carries a body sqlalign reformats internally.
323
390
 
@@ -344,12 +411,43 @@ def spelling_equal(a: str, b: str, dialect: str) -> bool:
344
411
  reformat is equal and only a change the author did not ask for is not.
345
412
  """
346
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)
347
418
  return (spelling.token_census(a, dialect)
348
419
  == spelling.token_census(b, dialect))
349
420
  except TokenError:
350
421
  return True # unreadable input declines earlier; do not invent a reason
351
422
 
352
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
+
353
451
  def ast_equal(a: str, b: str, dialect: str) -> bool:
354
452
  """AST-equality safety check. sqlglot sees a `$$…$$` body as one opaque
355
453
  string, so raw AST comparison would reject any body reformatting. When both
@@ -555,11 +653,18 @@ def _join_statements(entries, blanks=None):
555
653
  return "".join(pieces)
556
654
 
557
655
 
558
- 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:
559
658
  """Format `text`. `style` carries every knob; it is also published as the
560
659
  ambient render style for the duration of the call so `render_expr` (called
561
660
  from ~57 handler sites) can read output-spelling knobs without every handler
562
- 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
+ """
563
668
  if dialect not in SUPPORTED_DIALECTS:
564
669
  # Refuse rather than mis-format. The handlers emit keywords chosen for
565
670
  # the verified dialects, and the AST check cannot catch one that is
@@ -569,7 +674,7 @@ def format_sql(text: str, dialect: str = "postgres", style: Style = HOUSE) -> Fo
569
674
  f"{', '.join(sorted(SUPPORTED_DIALECTS))}")
570
675
  with render_style(style):
571
676
  if not style.protect_templating or not templating.has_templating(text):
572
- return _format_all(text, dialect, style)
677
+ return _format_all(text, dialect, style, lines)
573
678
  # Templated SQL (dbt/Jinja) does not parse. Mask each expression with a
574
679
  # same-WIDTH placeholder so every alignment column is computed against the
575
680
  # real width, format normally, then restore. The whole pipeline: layout,
@@ -584,7 +689,10 @@ def format_sql(text: str, dialect: str = "postgres", style: Style = HOUSE) -> Fo
584
689
  # exactly the way --report exists to prevent.
585
690
  return FormatResult(text, [f"templating not maskable, passed through: {e}"],
586
691
  1, (Decline("unsupported", "templating not maskable"),))
587
- 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)
588
696
  # Rebuilt for the unmasked text only; the counts ride through unchanged.
589
697
  # Dropping them blinded --report and --max-declines for every templated
590
698
  # file, which is most of a dbt project.
@@ -592,7 +700,8 @@ def format_sql(text: str, dialect: str = "postgres", style: Style = HOUSE) -> Fo
592
700
  result.warnings, result.statements, result.declines)
593
701
 
594
702
 
595
- 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:
596
705
  warnings, out, declines = [], [], []
597
706
  statements = 0
598
707
  pos = 0
@@ -601,7 +710,15 @@ def _format_all(text: str, dialect: str, style: Style) -> FormatResult:
601
710
  out.append((piece, is_statement, _body_is_multiline(piece)))
602
711
 
603
712
  for stmt in split_statements(text, dialect):
713
+ literals = None
604
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
605
722
  if not stmt.strip().rstrip(";").strip():
606
723
  emit(stmt, False)
607
724
  continue
@@ -642,6 +759,9 @@ def _format_all(text: str, dialect: str, style: Style) -> FormatResult:
642
759
  # Distinct wording per class so a real bug is visible in stderr, not
643
760
  # silently indistinguishable from an expected decline.
644
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)
645
765
  if dialect == "tsql" and _TSQL_LOSSY_TYPES.search(stmt):
646
766
  raise Unsupported("tsql: type whose spelling sqlglot cannot preserve")
647
767
  node0 = _first_expression(parsed)
@@ -671,13 +791,11 @@ def _format_all(text: str, dialect: str, style: Style) -> FormatResult:
671
791
  # The AST check cannot see a rewrite sqlglot's own parser makes:
672
792
  # both sides go through it and collapse to one tree, so
673
793
  # `ALTER COLUMN x TYPE t` printed as `SET DATA TYPE t` compares
674
- # equal. Comparing tokens catches it. Statements with a body are
675
- # excluded -- the tokenizer sees a `$$` body as one string
676
- # literal, so reformatting inside one reads as a changed token,
677
- # and those are compared structurally by `_plpgsql_ast_equal`.
678
- if not _has_body(stmt, dialect) and not spelling_equal(
679
- stmt, formatted, dialect):
680
- raise Rewrite(f"formatting respelled the statement near: {snippet}")
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)
681
799
  except Unsupported as exc:
682
800
  # The reason rides in the message so `--report` can name the
683
801
  # construct, not just count the declines.
@@ -721,6 +839,8 @@ def _format_all(text: str, dialect: str, style: Style) -> FormatResult:
721
839
  continue
722
840
  emit(formatted, True)
723
841
  finally:
842
+ if literals is not None:
843
+ reset_source(literals)
724
844
  pos += len(stmt)
725
845
  return FormatResult(_join_statements(out, style.blank_lines_between_statements),
726
846
  warnings, statements, tuple(declines))
sqlalign/keywordcase.py CHANGED
@@ -27,6 +27,8 @@ import re
27
27
  import sqlglot
28
28
  from sqlglot import exp
29
29
 
30
+ from sqlalign.splitter import DOLLAR_TAG
31
+
30
32
  # A bare word: identifier-shaped, and UNICODE-aware on purpose. `apply` enters
31
33
  # this pattern on any `ch.isalpha()`, which is true of `é`: an ASCII-only
32
34
  # pattern then fails to match there and crashes the pass, which formatter's
@@ -89,8 +91,8 @@ def _body_identifiers(body: str, dialect: str) -> set[str]:
89
91
 
90
92
 
91
93
  def apply(text: str, names: set[str], case: str) -> str:
92
- """Case every bare word outside strings, quoted identifiers, and comments,
93
- leaving anything in `names` exactly as written."""
94
+ """Case every bare word outside strings, quoted identifiers, comments and
95
+ dollar-quote delimiters, leaving anything in `names` exactly as written."""
94
96
  if case == "upper":
95
97
  return text # what the handlers already emit
96
98
  out: list[str] = []
@@ -123,6 +125,19 @@ def apply(text: str, names: set[str], case: str) -> str:
123
125
  end = n if end == -1 else end + 2
124
126
  out.append(text[i:end])
125
127
  i = end
128
+ elif ch == "$" and (m := DOLLAR_TAG.match(text, i)):
129
+ # A dollar-quote delimiter is not a keyword. Its case is part of the
130
+ # delimiter -- Postgres matches `$BODY$` against `$BODY$` and not
131
+ # against `$body$` -- so lowering it respells the author's text, and
132
+ # neither safety layer could object: sqlglot's `exp.Heredoc` does not
133
+ # record the tag, and the token census emits the body's content with
134
+ # the tag excluded. It came out silently as `$body$` at both ends
135
+ # under `keyword_case = "lower"`, which the `dbt` preset sets.
136
+ #
137
+ # Only the delimiter is skipped, not the region: a `$$` body's own
138
+ # statements are SQL and are cased like any other.
139
+ out.append(m.group(0))
140
+ i = m.end()
126
141
  elif ch.isalpha() or ch == "_":
127
142
  word = _WORD.match(text, i).group(0)
128
143
  out.append(word if word in names else word.lower())
@@ -56,13 +56,15 @@ def layout_statement(node: exp.Expression, dialect: str, width, anchor: int = 0)
56
56
 
57
57
  if node.args.get("with_") is not None:
58
58
  return _cte.layout_with(node, dialect, width)
59
- if isinstance(node, (exp.Create, exp.TruncateTable, exp.Grant, exp.Alter,
60
- exp.Drop, exp.Comment, exp.Declare, exp.Copy)):
59
+ if isinstance(node, (exp.Create, exp.TruncateTable, exp.Grant, exp.Revoke,
60
+ exp.Alter, exp.Drop, exp.Comment, exp.Declare, exp.Copy)):
61
61
  return _ddl.ddl_lines(node, dialect, width, anchor)
62
62
  # A GRANT sqlglot could only parse as an unsupported-syntax Command
63
63
  # (e.g. GRANT ... ON ALL TABLES IN SCHEMA ...) still gets keyword casing.
64
64
  if isinstance(node, exp.Command) and str(node.this).upper() == "GRANT":
65
65
  return _ddl.ddl_lines(node, dialect, width, anchor)
66
+ if isinstance(node, exp.Set):
67
+ return _source_lines(node, dialect, anchor)
66
68
  if isinstance(node, exp.Values):
67
69
  return _dml.values_lines(node, dialect, anchor)
68
70
  if isinstance(node, (exp.Insert, exp.Update, exp.Delete, exp.Merge)):
@@ -71,7 +73,56 @@ def layout_statement(node: exp.Expression, dialect: str, width, anchor: int = 0)
71
73
  return _setop.layout_setop(node, dialect, width, anchor)
72
74
  if isinstance(node, exp.Select):
73
75
  return _select.layout_select(node, dialect, width, anchor)
74
- raise Unsupported(type(node).__name__)
76
+ raise Unsupported(construct_name(node, dialect))
77
+
78
+
79
+ def _source_lines(node, dialect: str, anchor: int):
80
+ """A statement the generator cannot print as written, cased from its source.
81
+
82
+ `SET x TO y` is the case this exists for: sqlglot records the assignment but
83
+ not which spelling made it, so its generator always prints `=`, and under
84
+ T-SQL it drops `LOCAL` and `SESSION` outright. There is no layout to
85
+ compute either -- SET is one line -- so the whole statement is the source
86
+ with its keywords cased.
87
+
88
+ Declines when the source is unavailable (nothing set it) or when the node is
89
+ one `sourcecase` cannot separate grammar from content in.
90
+ """
91
+ from sqlalign import sourcecase
92
+ from sqlalign.casing import source_sql
93
+
94
+ source = source_sql()
95
+ if source is None or not sourcecase.renders_from_source(node):
96
+ raise Unsupported(construct_name(node, dialect))
97
+ cased = sourcecase.recase(source.strip().rstrip(";").strip(), node, dialect,
98
+ active_style().keyword_case)
99
+ return [Line(anchor, [Seg(cased)])]
100
+
101
+
102
+ def construct_name(node, dialect: str) -> str:
103
+ """What to call `node` in a decline the user reads.
104
+
105
+ Both branches turn a sqlglot class name into something the user can find in
106
+ their own file, which is what CONTRIBUTING asks of every decline.
107
+
108
+ `exp.Command` is the catch-all for syntax sqlglot's parser does not model at
109
+ all, so its class name is the same word for every unrelated statement that
110
+ lands there: `SET ROLE reporting` and `RESET ROLE` both read as
111
+ `unsupported construct (Command)`, which describes neither. The keyword
112
+ sqlglot kept on the node is the statement's own name.
113
+
114
+ Otherwise, a class named after a SQL keyword is reported as that keyword --
115
+ `Set` as `SET`. Checked against the dialect's own vocabulary rather than a
116
+ list here, so this uppercases `SET` and `PIVOT` while leaving a name that
117
+ only looks like one (`Semicolon`, `Refresh`) alone.
118
+ """
119
+ if isinstance(node, exp.Command) and node.this:
120
+ return str(node.this).strip().upper()
121
+ name = type(node).__name__
122
+ from sqlglot.tokens import Tokenizer
123
+ if name.upper() in Tokenizer(dialect=dialect).KEYWORDS:
124
+ return name.upper()
125
+ return name
75
126
 
76
127
 
77
128
  def join_keyword(join: exp.Join) -> str:
@@ -68,9 +68,12 @@ from dataclasses import dataclass
68
68
  from sqlglot import exp
69
69
 
70
70
  from sqlalign.layout import Unsupported
71
+ from sqlalign.splitter import DOLLAR_TAG
71
72
 
72
- # Dollar-quote tag (mirrors splitter.py): bare `$$` or `$tag$`.
73
- _DOLLAR = re.compile(r"\$(?:[A-Za-z_][A-Za-z0-9_]*)?\$")
73
+ # Imported rather than mirrored. The copy this replaces was a second ASCII-only
74
+ # regex that had to be found and widened separately, which is exactly how the
75
+ # two drift.
76
+ _DOLLAR = DOLLAR_TAG
74
77
  _IDENT_CHARS = re.compile(r"[A-Za-z0-9_]")
75
78
 
76
79
  # SELECT-list terminators: the first depth-0 occurrence of any of these (as a
sqlalign/layout/ddl.py CHANGED
@@ -32,7 +32,7 @@ def ddl_lines(node, dialect, width, anchor=0):
32
32
  return _create_lines(node, dialect, width, anchor)
33
33
  if isinstance(node, exp.TruncateTable):
34
34
  return _truncate_lines(node, dialect, anchor)
35
- if isinstance(node, (exp.Grant, exp.Command)):
35
+ if isinstance(node, (exp.Grant, exp.Revoke, exp.Command)):
36
36
  return _grant_lines(node, dialect, anchor)
37
37
  if isinstance(node, exp.Alter):
38
38
  return _alter_lines(node, dialect, anchor)
@@ -308,6 +308,13 @@ def _create_index_lines(node, dialect, width, anchor):
308
308
 
309
309
 
310
310
  def _grant_lines(node, dialect, anchor):
311
+ """GRANT and REVOKE, one line each, spelled by sqlglot.
312
+
313
+ REVOKE was reachable here for a year before it was routed in: it parses to
314
+ its own node and renders on one line exactly as GRANT does, but was absent
315
+ from the dispatch, so every REVOKE in a permissions script declined while
316
+ the GRANT above it formatted.
317
+ """
311
318
  if isinstance(node, exp.Command):
312
319
  return [Line(anchor, [Seg(_uppercase_keywords(node, dialect))])]
313
320
  return [Line(anchor, [Seg(render_expr(node, dialect))])]
sqlalign/lint.py CHANGED
@@ -65,17 +65,24 @@ def discovered_config(path: Path) -> Path | None:
65
65
  return None
66
66
 
67
67
 
68
- def lint(path: Path, text: str, style, dialect: str) -> tuple[int, str, str]:
68
+ def lint(path: Path, text: str, style, dialect: str,
69
+ explicit_config: Path | None = None) -> tuple[int, str, str]:
69
70
  """Lint `text` as though it were `path`. Returns (returncode, stdout, stderr).
70
71
 
71
72
  The text is linted rather than the file, so `--check` and `--stdout` lint
72
73
  what would be written instead of what is currently on disk. It goes into a
73
74
  temporary file beside the original so sqlfluff's own config discovery still
74
75
  walks the real directory tree.
76
+
77
+ `explicit_config` names a sqlfluff config to use instead of that discovery --
78
+ a team's shared file that lives outside the repository, which discovery
79
+ cannot reach because it only ever walks upwards from the file being linted.
75
80
  """
76
- config = discovered_config(path)
81
+ config = explicit_config if explicit_config is not None else discovered_config(path)
77
82
  args = ["lint"]
78
83
  generated = None
84
+ if explicit_config is not None:
85
+ args += ["--config", str(explicit_config)]
79
86
  if config is None:
80
87
  # Nothing to respect: fall back to the config that keeps the two tools
81
88
  # from contradicting each other.
sqlalign/plpgsql.py CHANGED
@@ -199,6 +199,37 @@ 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 _own_line_comments(text: str) -> tuple[list[str], str]:
203
+ """Leading comment lines peeled off `text`, and what remains.
204
+
205
+ The clause splitter glues an own-line comment to the statement below it, so
206
+ a body that reads
207
+
208
+ -- clear the staging table
209
+ delete from staging;
210
+
211
+ arrives here as one clause. Those two lines are exactly what the author
212
+ wrote and exactly what should come out, so the comment is kept as its own
213
+ line rather than merged into the statement or declined.
214
+ """
215
+ leading: list[str] = []
216
+ lines = text.splitlines()
217
+ index = 0
218
+ for index, line in enumerate(lines): # noqa: B007 - index is used after
219
+ stripped = line.strip()
220
+ if not stripped:
221
+ continue
222
+ if stripped.startswith("--"):
223
+ leading.append(stripped)
224
+ continue
225
+ break
226
+ else:
227
+ return leading, ""
228
+ # Stripped: `_take_comments` writes this back as the clause, and the leading
229
+ # indent left `head[len("if"):]` slicing off two spaces instead of the `IF`.
230
+ return leading, "\n".join(lines[index:]).strip()
231
+
232
+
202
233
  def _split_comment(text: str) -> tuple[str, str | None]:
203
234
  """`text` as (code, trailing comment or None), split outside string literals.
204
235
 
@@ -207,10 +238,12 @@ def _split_comment(text: str) -> tuple[str, str | None]:
207
238
  as `-- LOG it FOR the user;`, semicolon and all, with nothing declining.
208
239
  Comments are not code and never go through casing.
209
240
 
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.
241
+ Leading own-line comments are peeled off before this by
242
+ `_own_line_comments`, so what reaches here is a single line of code with at
243
+ most a comment after it. A comment with code following it ON THE SAME LINE
244
+ -- a closed `/* ... */` mid-statement -- has no faithful one-line rendering
245
+ and declines rather than guessing, which is the contract the SQL comment
246
+ engine follows.
214
247
  """
215
248
  in_string = False
216
249
  i = 0
@@ -234,11 +267,18 @@ def _split_comment(text: str) -> tuple[str, str | None]:
234
267
 
235
268
 
236
269
  def _render_plain(text: str, dialect: str) -> str:
270
+ leading, text = _own_line_comments(text.strip())
271
+ if not text:
272
+ # The clause is nothing but comments -- verbatim, and no terminator:
273
+ # a `;` after `--` becomes part of the comment.
274
+ return "\n".join(leading)
237
275
  text, comment = _split_comment(text.strip())
238
276
  if text.lower().startswith("get diagnostics"):
239
277
  rendered = _render_get_diagnostics(text)
240
278
  else:
241
279
  rendered = _upper_kw(text, dialect)
280
+ if leading:
281
+ rendered = "\n".join([*leading, rendered]) if rendered else "\n".join(leading)
242
282
  if comment is None:
243
283
  return rendered
244
284
  if not rendered:
@@ -297,7 +337,13 @@ def _header_lines(node, dialect: str, tag: str) -> list[str]:
297
337
  lang = body_language(node)
298
338
  if lang is None:
299
339
  raise Unsupported(f"plpgsql: language {_language_name(node)!r}")
300
- lines.append(f"LANGUAGE {lang}") # canonical bare form
340
+ # `LANGUAGE 'plpgsql'` (quoted, legacy) and `LANGUAGE plpgsql` are the same
341
+ # to Postgres, and this used to normalise the first into the second. That is
342
+ # a respelling, which since 1.2 sqlalign does not do on the author's behalf
343
+ # -- and once the census reached inside bodies it said so. sqlglot records
344
+ # which was written (a Literal against a Var), so it is given back.
345
+ quoted = isinstance(language.this, exp.Literal) and language.this.is_string
346
+ lines.append(f"LANGUAGE '{lang}'" if quoted else f"LANGUAGE {lang}")
301
347
  lines.append("AS " + tag)
302
348
  return lines
303
349
 
@@ -319,12 +365,28 @@ def _norm(clause: str) -> str:
319
365
  def _render_sql_stmt(raw: str, dialect: str, style) -> str:
320
366
  """Route an embedded SQL statement through the main engine (identical
321
367
  formatting to top level). A construct the engine declines passes through
322
- verbatim per §6 — the whole body's safety check still validates it."""
368
+ verbatim per §6 — the whole body's safety check still validates it.
369
+
370
+ Comments come off first, for the same reason `_terminate` takes them off:
371
+ `raw + ";"` put the terminator INSIDE a trailing comment, so
372
+ `select 1 -- why` shipped as `SELECT 1 -- why;` and the statement was no
373
+ longer terminated. Nothing caught it until `comment_text` learned to look
374
+ inside a body.
375
+ """
323
376
  from sqlalign.formatter import _format_statement # lazy: breaks import cycle
377
+
378
+ leading, code = _own_line_comments(raw.strip())
379
+ if not code:
380
+ return "\n".join(leading)
381
+ code, comment = _split_comment(code)
382
+ code = code.rstrip().rstrip(";").rstrip()
324
383
  try:
325
- return _format_statement(raw + ";", dialect, style)
384
+ rendered = _format_statement(code + ";", dialect, style)
326
385
  except Unsupported:
327
- return raw.strip() + ";"
386
+ rendered = code + ";"
387
+ if comment:
388
+ rendered = f"{rendered} {comment}"
389
+ return _above(leading, rendered)
328
390
 
329
391
 
330
392
  def _is_sql(raw: str, dialect: str) -> bool:
@@ -349,10 +411,26 @@ def _render_stmt(raw: str, dialect: str, style) -> str:
349
411
  def _terminate(rendered: str) -> str:
350
412
  """`rendered` with its `;` in the right place: after the code, before any
351
413
  trailing comment, and not at all when the clause is only a comment --
352
- anything after `--` is part of the comment, including a semicolon."""
414
+ anything after `--` is part of the comment, including a semicolon.
415
+
416
+ Leading own-line comments are set aside first. They are already rendered by
417
+ this point, and re-reading them as "a comment with code after it" is what
418
+ made an ordinary commented statement decline.
419
+ """
420
+ leading, rendered = _own_line_comments(rendered)
421
+ if not rendered:
422
+ return "\n".join(leading)
353
423
  code, comment = _split_comment(rendered)
424
+ if leading:
425
+ joined = _terminate_one(code, comment)
426
+ return "\n".join([*leading, joined])
427
+ return _terminate_one(code, comment)
428
+
429
+
430
+ def _terminate_one(code: str, comment: str | None) -> str:
431
+ """One line of code plus its trailing comment, terminated."""
354
432
  if not code:
355
- return rendered
433
+ return comment or ""
356
434
  if not code.endswith(";"):
357
435
  code += ";"
358
436
  return f"{code} {comment}" if comment else code
@@ -375,7 +453,17 @@ def _render_declare(decls: list[str], dialect: str) -> str:
375
453
  if len(parts) != 2:
376
454
  raise Unsupported("plpgsql DECLARE: unrecognized declaration")
377
455
  name, rest = parts
378
- return f"DECLARE {name} {_upper_kw(rest, dialect)};"
456
+ # The comment comes off before casing, exactly as `_render_plain` does it.
457
+ # Without this, `_upper_kw` whitespace-tokenized the comment along with the
458
+ # declaration -- `-- count from the source table` shipped as
459
+ # `-- count FROM the source TABLE`, and `_terminate`'s `;` landed inside it.
460
+ rest, comment = _split_comment(rest.strip())
461
+ # The clause splitter keeps a trailing comment with the statement it follows,
462
+ # so the terminator arrives here in the middle: `int; -- note`. It is dropped
463
+ # and re-added after the code, which is where it belongs.
464
+ rest = rest.rstrip().rstrip(";").rstrip()
465
+ declared = f"DECLARE {name} {_upper_kw(rest, dialect)};"
466
+ return f"{declared} {comment}" if comment else declared
379
467
 
380
468
 
381
469
  def _consume_if(stmts: list[str], j: int, dialect: str):
@@ -425,6 +513,37 @@ def _consume_if(stmts: list[str], j: int, dialect: str):
425
513
  return "\n".join(lines), j
426
514
 
427
515
 
516
+ def _take_comments(clauses: list[str], k: int) -> tuple[int, list[str]]:
517
+ """Own-line comments leading `clauses[k]`, and where the code starts.
518
+
519
+ The clause splitter glues an own-line comment to whatever follows it, which
520
+ hides the keyword the body parser is looking for: `-- guard` before an `IF`
521
+ made `_first_word` read `--`, and the block was neither recognised as an IF
522
+ nor found as the `END`. Peeling the comments off before every structural
523
+ decision means a commented body parses exactly like the same body without
524
+ the comments.
525
+
526
+ They are returned rather than emitted so the caller can put them back on top
527
+ of the element they introduce. Emitting them as elements of their own looks
528
+ right until `body_blank_lines` is applied, which then separates a comment
529
+ from the statement it is about.
530
+ """
531
+ comments: list[str] = []
532
+ while k < len(clauses):
533
+ leading, code = _own_line_comments(clauses[k])
534
+ comments.extend(leading)
535
+ if code:
536
+ clauses[k] = code
537
+ break
538
+ k += 1 # the clause was comments and nothing else
539
+ return k, comments
540
+
541
+
542
+ def _above(comments: list[str], element: str) -> str:
543
+ """`element` with its own-line comments restored above it."""
544
+ return "\n".join([*comments, element]) if comments else element
545
+
546
+
428
547
  def _parse_body_elements(body: str, dialect: str, style, language="plpgsql") -> list[str]:
429
548
  cls = body_clauses(body)
430
549
  if language == "sql":
@@ -434,32 +553,46 @@ def _parse_body_elements(body: str, dialect: str, style, language="plpgsql") ->
434
553
  return [_render_stmt(c, dialect, style) for c in cls]
435
554
  elements: list[str] = []
436
555
  i, n = 0, len(cls)
556
+ i, comments = _take_comments(cls, i)
437
557
  if i < n and _first_word(cls[i]) == "declare":
438
558
  decls = [cls[i][len("declare"):].strip()]
439
559
  i += 1
440
560
  while i < n and _first_word(cls[i]) != "begin":
441
561
  decls.append(cls[i].strip())
442
562
  i += 1
443
- elements.append(_render_declare(decls, dialect))
563
+ elements.append(_above(comments, _render_declare(decls, dialect)))
564
+ comments = []
565
+ i, more = _take_comments(cls, i)
566
+ comments += more
444
567
  if i >= n or _first_word(cls[i]) != "begin":
445
568
  raise Unsupported("plpgsql: expected BEGIN")
446
- elements.append("BEGIN")
569
+ elements.append(_above(comments, "BEGIN"))
447
570
  begin_rest = cls[i][len("begin"):].strip()
448
571
  i += 1
449
572
  stmts = ([begin_rest] if begin_rest else []) + cls[i:]
450
573
  j, m = 0, len(stmts)
451
- while j < m and _first_word(stmts[j]) != "end":
574
+ while True:
575
+ j, comments = _take_comments(stmts, j)
576
+ if j >= m or _first_word(stmts[j]) == "end":
577
+ break
452
578
  if _first_word(stmts[j]) == "if":
453
579
  block, j = _consume_if(stmts, j, dialect)
454
- elements.append(block)
580
+ elements.append(_above(comments, block))
455
581
  else:
456
- elements.append(_render_stmt(stmts[j], dialect, style))
582
+ elements.append(_above(comments, _render_stmt(stmts[j], dialect, style)))
457
583
  j += 1
458
584
  if j >= m or _norm(stmts[j]) != "end": # bare END only (no label/args)
459
585
  raise Unsupported("plpgsql: expected END")
460
- if j != m - 1:
586
+ j, trailing = _take_comments(stmts, j + 1)
587
+ if j != m:
461
588
  raise Unsupported("plpgsql: statements after END")
462
- elements.append("END;")
589
+ elements.append(_above(comments, "END;"))
590
+ if trailing:
591
+ # A comment written after END stays after END. Folding it into that
592
+ # element would read better with `body_blank_lines` set, and would move
593
+ # a comment past the statement it follows, which is not a formatter's
594
+ # call to make.
595
+ elements.append("\n".join(trailing))
463
596
  return elements
464
597
 
465
598
 
sqlalign/sourcecase.py ADDED
@@ -0,0 +1,90 @@
1
+ """Case a statement's keywords without rebuilding it from its syntax tree.
2
+
3
+ The layout engine renders by handing nodes to sqlglot's generator. For most
4
+ statements that is right and it is what makes the columnar style possible. For a
5
+ handful it is lossy: two spellings collapse to one node, so the generator prints
6
+ whichever it prefers and the author's is gone. `ALTER COLUMN x TYPE text` comes
7
+ back as `SET DATA TYPE`, `ADD COLUMN c integer array` loses the `ARRAY`, and
8
+ `SET search_path TO public` has its `TO` respelt as `=`.
9
+
10
+ Since 1.2 those are caught and passed through rather than shipped changed, which
11
+ is honest but means they do not format at all. This module formats them the only
12
+ way that cannot lose a spelling: by starting from the source text and changing
13
+ nothing but the case of its keywords.
14
+
15
+ **Telling a keyword from an identifier is the whole problem.** The tokenizer
16
+ alone cannot: it types `add`, `to` and `local` as `VAR` in the statements above,
17
+ and a column genuinely named `year` the same way. Uppercasing every word that
18
+ appears in the keyword table turns `ADD COLUMN year INT` into `ADD COLUMN YEAR
19
+ INT`.
20
+
21
+ The parse tree answers it. Every identifier, literal and bare `Var` the author
22
+ wrote is a node in the tree; the grammar words around them -- `ADD`, `COLUMN`,
23
+ `TO`, `SET DATA TYPE` -- are not, because they live in sqlglot's generator
24
+ rather than on any node. So a source word absent from the tree's content is
25
+ grammar, and a word present in it is the author's and is left alone. A statement
26
+ that uses one word both ways keeps both as written, which is the safe direction.
27
+
28
+ This needs a parse. `exp.Command` -- sqlglot's fallback for syntax it cannot
29
+ model -- carries raw text and no content nodes, so every word in it would read
30
+ as grammar and a role name would be uppercased. Those still pass through.
31
+ """
32
+ from __future__ import annotations
33
+
34
+ import sqlglot
35
+ from sqlglot import exp
36
+ from sqlglot.tokens import TokenType
37
+
38
+ # Tokens that are content by their type alone, whatever the tree says. A quoted
39
+ # identifier is the point: `"Order"` is a name the engine stores case-sensitively
40
+ # and casing it changes which column is meant.
41
+ _CONTENT_TOKENS = frozenset({
42
+ TokenType.STRING, TokenType.IDENTIFIER, TokenType.NUMBER,
43
+ TokenType.HEREDOC_STRING, TokenType.RAW_STRING, TokenType.NATIONAL_STRING,
44
+ TokenType.BYTE_STRING, TokenType.HEX_STRING, TokenType.UNICODE_STRING,
45
+ TokenType.PARAMETER, TokenType.SESSION_PARAMETER,
46
+ })
47
+
48
+
49
+ def renders_from_source(node: exp.Expression) -> bool:
50
+ """Whether `node` can be cased this way at all.
51
+
52
+ A `Command` is raw text with no content nodes to protect, so every word in
53
+ it would be taken for grammar.
54
+ """
55
+ return not isinstance(node, exp.Command) and node.find(exp.Command) is None
56
+
57
+
58
+ def content_words(node: exp.Expression) -> set[str]:
59
+ """Casefolded words the author wrote as names or values, not as grammar."""
60
+ words = set()
61
+ for child in node.walk():
62
+ if isinstance(child, (exp.Identifier, exp.Var, exp.Literal)) and isinstance(
63
+ child.this, str):
64
+ words.add(child.this.casefold())
65
+ return words
66
+
67
+
68
+ def recase(sql: str, node: exp.Expression, dialect: str, keyword_case: str) -> str:
69
+ """`sql` with its grammar words cased, byte-identical everywhere else.
70
+
71
+ Whitespace, comments and every content token come through from the source
72
+ untouched -- only the spans the tokenizer reported for grammar words are
73
+ rewritten, and only in case. That is what makes this safe to reach for when
74
+ the generator would have respelt something: there is nothing here that can
75
+ change a statement's meaning, only its capitalisation.
76
+ """
77
+ fold = str.upper if keyword_case == "upper" else str.lower
78
+ words = content_words(node)
79
+ tokenizer = sqlglot.Dialect.get_or_raise(dialect).tokenizer_class()
80
+ out: list[str] = []
81
+ cursor = 0
82
+ for token in tokenizer.tokenize(sql):
83
+ out.append(sql[cursor:token.start])
84
+ span = sql[token.start:token.end + 1]
85
+ grammar = (token.token_type not in _CONTENT_TOKENS
86
+ and span.casefold() not in words)
87
+ out.append(fold(span) if grammar else span)
88
+ cursor = token.end + 1
89
+ out.append(sql[cursor:])
90
+ return "".join(out)
sqlalign/spelling.py CHANGED
@@ -26,11 +26,27 @@ import sqlglot
26
26
  from sqlglot import exp
27
27
  from sqlglot.tokens import TokenType
28
28
 
29
+ # Tokens whose text is CONTENT rather than syntax: a string literal, a quoted
30
+ # identifier, a `$$ ... $$` body. Casefolding these before comparing made the
31
+ # census blind to a change inside one -- `INTERVAL '14 days'` came back as
32
+ # `INTERVAL '14 DAYS'` and every check passed, because sqlglot normalises the
33
+ # unit to `Var(DAYS)` in the tree (so `ast_equal` cannot see it either) and the
34
+ # census had uppercased both sides. Compared byte-for-byte instead.
35
+ _VERBATIM = frozenset({TokenType.STRING, TokenType.IDENTIFIER,
36
+ TokenType.HEREDOC_STRING, TokenType.RAW_STRING,
37
+ TokenType.NATIONAL_STRING, TokenType.BYTE_STRING,
38
+ TokenType.HEX_STRING, TokenType.UNICODE_STRING})
39
+
29
40
  # `AS` before a table alias is `Style.table_alias_style`, which exists to add or
30
41
  # remove exactly this token. It carries no meaning of its own -- `FROM t a` and
31
42
  # `FROM t AS a` are the same tree -- so it is dropped from both sides rather
32
43
  # than compared.
33
- _OPTIONAL = frozenset({"AS"})
44
+ # `;` joins it for the same reason: the formatter terminates statements that
45
+ # arrived without one -- a T-SQL `CREATE PROCEDURE ... END` comes back as
46
+ # `END;` -- so counting terminators reports every such statement as rewritten.
47
+ # Losing one cannot hide here: it changes where statements begin and end, and
48
+ # both the splitter and the per-statement tree comparison see that.
49
+ _OPTIONAL = frozenset({"AS", ";"})
34
50
 
35
51
  # `!=` / `<>` is `Style.neq_style`; the two are one operator to every engine
36
52
  # sqlalign supports. Written here because it is an operator rather than a type,
@@ -71,6 +87,45 @@ def type_synonyms(dialect: str) -> dict[str, str]:
71
87
  for group in by_node.values() for spelling in group}
72
88
 
73
89
 
90
+ def literal_spellings(sql: str, dialect: str) -> dict[str, str]:
91
+ """`sql`'s string literals, keyed by their uppercase form.
92
+
93
+ The renderer's way back to a spelling sqlglot normalised out of the tree.
94
+ Uppercase keys because case is the only thing that can be recovered this
95
+ way: two literals differing by anything else are different literals, and one
96
+ of them must not be printed for the other.
97
+
98
+ A statement that writes one literal two ways offers neither.
99
+ """
100
+ tokenizer = sqlglot.Dialect.get_or_raise(dialect).tokenizer_class()
101
+ spellings: dict[str, str] = {}
102
+ ambiguous: set[str] = set()
103
+ for token in tokenizer.tokenize(sql):
104
+ if token.token_type is TokenType.STRING:
105
+ key = token.text.upper()
106
+ if spellings.setdefault(key, token.text) != token.text:
107
+ # The same literal written two ways in one statement. There is
108
+ # no spelling to restore -- either choice respells the other --
109
+ # so neither is offered and sqlglot's own output stands. It
110
+ # matters here because a `$$` body is exempt from the token
111
+ # census, so a wrong substitution inside one has nothing
112
+ # downstream to catch it.
113
+ ambiguous.add(key)
114
+ elif token.token_type is TokenType.HEREDOC_STRING:
115
+ # A `$$ ... $$` body is ONE token here, so its own literals are
116
+ # invisible from outside it -- and the statements inside a body are
117
+ # laid out by the same engine, through the same generator, with the
118
+ # same spelling to lose. Descend rather than tokenize the body
119
+ # separately: the body is part of the statement, and its literals
120
+ # are the statement's.
121
+ for key, text in literal_spellings(token.text, dialect).items():
122
+ if spellings.setdefault(key, text) != text:
123
+ ambiguous.add(key)
124
+ for key in ambiguous:
125
+ del spellings[key]
126
+ return spellings
127
+
128
+
74
129
  def token_census(sql: str, dialect: str) -> collections.Counter:
75
130
  """`sql`'s significant tokens counted, order discarded.
76
131
 
@@ -94,15 +149,33 @@ def token_census(sql: str, dialect: str) -> collections.Counter:
94
149
  def significant_tokens(sql: str, dialect: str) -> list[str]:
95
150
  """`sql` as the tokens that carry the author's intent.
96
151
 
97
- Case is normalized because `Style.keyword_case` chooses it, optional `AS` is
98
- dropped, and a spelling with a synonym is replaced by its canonical form.
99
- What survives is what sqlalign has no licence to change: identifiers,
100
- literals, operators, and every keyword that is not one of its settings.
152
+ Case is normalized for syntax because `Style.keyword_case` chooses it,
153
+ optional `AS` is dropped, and a spelling with a synonym is replaced by its
154
+ canonical form. Content -- string literals, quoted identifiers, `$$` bodies
155
+ -- is compared as written, since nothing sqlalign does may change a byte
156
+ inside one. What survives is what sqlalign has no licence to change.
101
157
  """
102
158
  tokenizer = sqlglot.Dialect.get_or_raise(dialect).tokenizer_class()
103
159
  synonyms = type_synonyms(dialect)
104
160
  tokens = []
161
+ previous = None
105
162
  for token in tokenizer.tokenize(sql):
163
+ if (token.token_type is TokenType.STRING
164
+ and previous is TokenType.COMMAND
165
+ and len(token.text) < len(sql)):
166
+ # Not a literal. After a keyword it cannot parse -- `DECLARE`, `SET`
167
+ # -- the tokenizer stops and hands back the rest of the statement as
168
+ # one STRING, so `declare row_count int` arrives here as the "string"
169
+ # `row_count int`. Comparing that as content made keyword casing look
170
+ # like a rewrite, and every procedure with a DECLARE declined.
171
+ # Tokenizing into it keeps real literals inside verbatim.
172
+ tokens.extend(significant_tokens(token.text, dialect))
173
+ previous = token.token_type
174
+ continue
175
+ previous = token.token_type
176
+ if token.token_type in _VERBATIM:
177
+ tokens.append(f"{token.token_type.name}:{token.text}")
178
+ continue
106
179
  word = token.text.strip().upper()
107
180
  if not word or word in _OPTIONAL:
108
181
  continue
sqlalign/splitter.py CHANGED
@@ -11,7 +11,21 @@ import re
11
11
  # and may contain digits thereafter (e.g. `$fn1$`): matches Postgres's identifier
12
12
  # rules for dollar-quote tags, which allow digits after the first character.
13
13
  # Public because plpgsql.py splits the same bodies and must agree exactly.
14
- DOLLAR_TAG = re.compile(r"\$(?:[A-Za-z_][A-Za-z0-9_]*)?\$")
14
+ # A dollar-quote delimiter: bare `$$` or `$tag$`. Postgres says a tag follows
15
+ # the rules for an unquoted identifier, and those are NOT ASCII-only -- `$café$`
16
+ # and `$ñ$` are legal tags. `[^\W\d]` is "a word character that is not a digit",
17
+ # which is a Unicode letter or underscore, so the leading-character rule holds
18
+ # for every alphabet rather than just the Latin one.
19
+ #
20
+ # Getting this wrong is not a cosmetic miss. A tag this does not recognise is a
21
+ # region nobody treats as opaque, so the file is cut at a `;` INSIDE the literal
22
+ # and the fragments are formatted as if they were SQL -- `<>` inside a
23
+ # `$ñ$ ... $ñ$` string came back as `!=`, changing stored data, with the
24
+ # warnings still saying "passthrough".
25
+ #
26
+ # A digit cannot lead, which is what keeps a positional parameter (`$1`, `$2`)
27
+ # from ever being read as a quote opener.
28
+ DOLLAR_TAG = re.compile(r"\$(?:[^\W\d]\w*)?\$")
15
29
 
16
30
  _IDENT_CHARS = re.compile(r"[A-Za-z0-9_]")
17
31
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: sqlalign
3
- Version: 1.2.0
3
+ Version: 1.3.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/
@@ -370,11 +370,14 @@ would otherwise mean a team believes it has a setting it doesn't have.
370
370
  | `--isolated` | off | ignore any config file |
371
371
  | `--print-sqlfluff-config` | — | print a `.sqlfluff` that lets sqlfluff run alongside sqlalign, and exit |
372
372
  | `--lint` | off | after formatting, run sqlfluff over the result (needs `pip install 'sqlalign[lint]'`) |
373
+ | `--sqlfluff-config PATH` | discovered | point `--lint` at a config outside the repository — one shared ruleset, many checkouts |
374
+ | `--lines START:END` | off | format only statements overlapping these 1-based, inclusive lines; the rest of the file stays byte-identical. Repeatable; one file or `-` |
373
375
  | `--body-blank-lines N` | `1` | blank lines between the elements of a `$$` body |
374
376
  | `--gui` | — | *(experimental)* open a settings panel with a live preview, and exit |
375
377
  | `--report` | off | print a coverage summary: how many statements formatted, and what the rest declined on. Adds output without changing the mode — pair with `--check` to survey without writing |
376
378
  | `--max-declines N` | — | exit 1 if more than N statements pass through unformatted (implies `--report`) |
377
379
  | `--show-config` | off | print effective settings as TOML and exit |
380
+ | `--init` | — | write a starter `.sqlalign.toml` beside the file and exit |
378
381
  | `--no-strict-config` | off | warn on unknown config keys instead of failing |
379
382
 
380
383
  `--neq-style` and `--decimal-style` exist because sqlglot's parser collapses each
@@ -1,29 +1,30 @@
1
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
- sqlalign/casing.py,sha256=w97se03KoCe7V5y6UzKyepjxWZtSucGoBCpVBN0kb40,7866
5
- sqlalign/cli.py,sha256=fzk8Ab_iXPQ4qmfPyxZ4RaiiTPtleSPAi5QsEn37340,27594
4
+ sqlalign/casing.py,sha256=LnukO7XO5FNLAY5GfDdZq4R6KK2fj0RpVJBTLA-a2BA,10711
5
+ sqlalign/cli.py,sha256=7pDlYcP8r4LBIP62igJImB9gHpHkf5lSF56jkUwrqbw,31036
6
6
  sqlalign/commas.py,sha256=vJ0CXVpAvCrhrnkwk6o5U6y6o1TeJZ-mhKaz-w2xJdA,2855
7
7
  sqlalign/config.py,sha256=VVfP9jPKAkRjim6ydUY4LhZTUv3lvKIrKU2McPR8faU,1063
8
8
  sqlalign/configfile.py,sha256=sfB7kGO1NBMJkjgpIQa7BYSwNMuPPSSMiBGiUVfSVFQ,11864
9
- sqlalign/formatter.py,sha256=mxqfBy5fTf9dtcDg-b4nMOCZa50ySnFz-mQe4_8xbj8,36935
9
+ sqlalign/formatter.py,sha256=a-GGATF3sbRzU_CNYYLhHBf7DmYC9RBmQwEFejcCUe4,43083
10
10
  sqlalign/gui.py,sha256=99MvlQuX5TazUo9W2Myh7Kov14m3zWgFHUOgwi7W_Vw,34675
11
11
  sqlalign/ir.py,sha256=cHKTXgGOuOJgFQwsO7lTzVtca1ZKP-PFZYxybhKgmrY,1161
12
- sqlalign/keywordcase.py,sha256=1skBJ0aiw2yIcoDdW_4jjwUVBgpLRAs19AKfHE7Qspg,5914
13
- sqlalign/lint.py,sha256=JLf-vdtaFyQBHLtr3qFpPpkEJwOOuRzNdzJ_ahutK6k,8214
14
- sqlalign/plpgsql.py,sha256=77FQCTdKVFqhuU3aHJkyHcXOTwL9s7GG5_USzPyvHZI,19946
12
+ sqlalign/keywordcase.py,sha256=18y22842QarltaXl1PHt80LPZsihautni76aF103ISo,6812
13
+ sqlalign/lint.py,sha256=gXnCh_Ll9IWDbrIJJYTpaZg0dgzQbdstywK8FmFstq0,8638
14
+ sqlalign/plpgsql.py,sha256=qN7dJkVJDrkMkV5ifF4MeWf87fNqku9OpMRZeskwSqc,25880
15
15
  sqlalign/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
16
- sqlalign/spelling.py,sha256=wkrZ0s_fwM-6DiylzNAhVZpDQpMWTJa6pRlKpKj8UVo,5212
17
- sqlalign/splitter.py,sha256=gkp-yU9HNkC1lT7c3OwLYnFZUSAoyfihpaFxD3dhS0A,9821
16
+ sqlalign/sourcecase.py,sha256=u9Rz9fN0oEje0HlB33l3STJBXj31NxkebhmKI6pUDoI,4267
17
+ sqlalign/spelling.py,sha256=OqPiByOPBWCe7LPKtaIve-BnZ-UxXiXLQiZ4sHXW6Q4,9355
18
+ sqlalign/splitter.py,sha256=LAtxNGdGPzBuyq-z3pgMFSMbDsBcuL1JkVaclg2Ju44,10654
18
19
  sqlalign/sqlfluffconfig.py,sha256=-mixGe5K5duFPfzPcQOi0urExVlXPTYlQKFTvHsHB3s,4802
19
20
  sqlalign/style.py,sha256=v9L697KI0BBMTFJP4KmNjpi3O-xz2XKLQLCBNRuzYWM,13321
20
21
  sqlalign/templating.py,sha256=o8J83gYH1PoabmbLjOSYIVLOpUrimzmPsd-oGp_pt6U,3793
21
- sqlalign/layout/__init__.py,sha256=kp0W4_A3plKs3vcS9K-Cb9uUs56emdindN-cyzTJsR8,15300
22
+ sqlalign/layout/__init__.py,sha256=METYPalg-oO7Q7HfaTgDCo5e1_FJn2QFwp7knsSmtRw,17640
22
23
  sqlalign/layout/case.py,sha256=3iBR05sL9QIEb3NtO482BM0sRLSKGOkrKTNT8LCJnaE,12468
23
- sqlalign/layout/comments.py,sha256=PwvrR-SQZOIs85-o-CslwAR6nH-DwkAiDBYBNJuIZfI,21348
24
+ sqlalign/layout/comments.py,sha256=T-vRzgUrqT0uR42AUr30zz97IUwSSaTYteYfnTXvUOg,21460
24
25
  sqlalign/layout/conditions.py,sha256=J6BbFzWsaJq1DkzVe011RBT1Ti161gHKkDcEIqJnm4Q,20535
25
26
  sqlalign/layout/cte.py,sha256=XBl7tF8P0q8yajkxibgTDjna57qiKYHugDzQ93QpcL8,4064
26
- sqlalign/layout/ddl.py,sha256=eGgPj1zcDQ-H2-pYivNzza9biji_1HIxZqVeF7H4SLo,19358
27
+ sqlalign/layout/ddl.py,sha256=jwEwjnd2V9vaHwEQntOxkJq-XsF_X4otGRKrY2reGPc,19709
27
28
  sqlalign/layout/dml.py,sha256=eDLTG2Os1B_s385mRGplyag8Z5mB3fUNCKF66yx3Baw,12906
28
29
  sqlalign/layout/expr.py,sha256=Uh7JvZ7rKc-oH5GAfChd2Wl3DaEUdU5bFA-fyuvVjrs,5754
29
30
  sqlalign/layout/fromjoin.py,sha256=J5MLQClX6ajqMVIwmC4vrwkFex9b99JO19lIJqhlVw4,16422
@@ -32,8 +33,8 @@ sqlalign/layout/select.py,sha256=PHE4wuTScaJCpkZehvqaFLk_EqRlZYH7PdNTBFYk7bo,273
32
33
  sqlalign/layout/setop.py,sha256=hjve3Qxi2CsaFEwijg6srhfMdEUlv2b9MmOUp6BNip0,3427
33
34
  sqlalign/layout/subquery.py,sha256=IIi4Cy8ZQ3WNBmPvmifuTRofXcWibakHCaaj9Uh2MfA,12496
34
35
  sqlalign/layout/window.py,sha256=X8YJ32hQGriwRQsDM2ZDvmaU6YHunJvcMi7UShmGJrU,9943
35
- sqlalign-1.2.0.dist-info/METADATA,sha256=6GfDZ4SyOUYjRQ8dmeVIxlYs7DxaxRDJr944LzAwOdw,23305
36
- sqlalign-1.2.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
37
- sqlalign-1.2.0.dist-info/entry_points.txt,sha256=hfughgpq-gK-8TKgvhw1mDbhlHbBQvPeTc96Jh6-efY,50
38
- sqlalign-1.2.0.dist-info/licenses/LICENSE,sha256=qvo2BvsFUcC3_3LOk36ZKcaMp_j1AFMfBoCNRFcyrco,1076
39
- sqlalign-1.2.0.dist-info/RECORD,,
36
+ sqlalign-1.3.0.dist-info/METADATA,sha256=9nzw-hgM8QvLq42gbNZ450iGMbN3iuG1lKOUuNuMXNY,23687
37
+ sqlalign-1.3.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
38
+ sqlalign-1.3.0.dist-info/entry_points.txt,sha256=hfughgpq-gK-8TKgvhw1mDbhlHbBQvPeTc96Jh6-efY,50
39
+ sqlalign-1.3.0.dist-info/licenses/LICENSE,sha256=qvo2BvsFUcC3_3LOk36ZKcaMp_j1AFMfBoCNRFcyrco,1076
40
+ sqlalign-1.3.0.dist-info/RECORD,,