sqlalign 1.2.0__py3-none-any.whl → 1.3.1__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
@@ -1,4 +1,5 @@
1
1
  import argparse
2
+ import contextlib
2
3
  import difflib
3
4
  import errno
4
5
  import os
@@ -51,7 +52,7 @@ def _write_atomically(path: Path, text: str) -> None:
51
52
  raise OSError(e.errno, e.strerror, str(target)) from e
52
53
  temp = Path(name)
53
54
  try:
54
- with os.fdopen(handle, "w", newline="") as f:
55
+ with os.fdopen(handle, "w", encoding="utf-8", newline="") as f:
55
56
  f.write(text)
56
57
  shutil.copymode(target, temp)
57
58
  os.replace(temp, target)
@@ -205,6 +206,11 @@ def build_parser() -> argparse.ArgumentParser:
205
206
  p.add_argument("--dialect", choices=sorted(SUPPORTED_DIALECTS), default=None,
206
207
  help="the SQL dialect to parse and print. Overrides a "
207
208
  "`dialect` in the config file (default: postgres)")
209
+ p.add_argument("--lines", action="append", metavar="START:END", default=None,
210
+ help="format only statements overlapping these 1-based, "
211
+ "inclusive line numbers; the rest of the file is left "
212
+ "byte-identical. Repeatable. Applies to one file (or "
213
+ "stdin), since line numbers mean nothing across several")
208
214
  p.add_argument("--line-ending", choices=["auto", "lf", "crlf"], default="auto",
209
215
  help="line endings to write: auto preserves the file's own (default)")
210
216
  # Config-file plumbing.
@@ -235,6 +241,11 @@ def build_parser() -> argparse.ArgumentParser:
235
241
  p.add_argument("--lint", action="store_true",
236
242
  help="after formatting, run sqlfluff over the result "
237
243
  "(needs the optional `sqlalign[lint]` extra)")
244
+ p.add_argument("--sqlfluff-config", metavar="PATH", type=Path,
245
+ help="lint with this sqlfluff config instead of the one "
246
+ "discovered next to each file. For a shared config that "
247
+ "lives outside the repository, which discovery cannot "
248
+ "reach. Requires --lint")
238
249
  p.add_argument("--print-sqlfluff-config", action="store_true",
239
250
  help="print a .sqlfluff that lets sqlfluff run alongside "
240
251
  "sqlalign without fighting it, and exit")
@@ -294,7 +305,48 @@ def build_parser() -> argparse.ArgumentParser:
294
305
  return p
295
306
 
296
307
 
308
+ def _quiet_sqlglot_fallbacks() -> None:
309
+ """Stop sqlglot narrating its own parser fallbacks on our stderr.
310
+
311
+ A statement sqlglot cannot model logs `'SET ROLE reporting' contains
312
+ unsupported syntax. Falling back to parsing as a 'Command'.` -- unprefixed,
313
+ interleaved with sqlalign's output, and about an internal detail of the
314
+ parser. sqlalign reports the same statement itself, by name and with the
315
+ text it passed through, so the warning is a second and worse copy of a
316
+ message the user already gets.
317
+
318
+ Done in the CLI rather than the library: `sqlalign.format` runs inside
319
+ someone else's program, and silencing a dependency's logger there is not a
320
+ formatter's business.
321
+ """
322
+ import logging
323
+ logging.getLogger("sqlglot").setLevel(logging.ERROR)
324
+
325
+
326
+ def parse_line_ranges(values: list[str]) -> tuple[tuple[int, int], ...]:
327
+ """`["3:9", "20"]` as 1-based inclusive spans.
328
+
329
+ A bare number is the single line, so `--lines 12` is the obvious thing and
330
+ does not have to be written `--lines 12:12`.
331
+ """
332
+ ranges = []
333
+ for value in values:
334
+ start, sep, end = value.partition(":")
335
+ try:
336
+ first = int(start)
337
+ last = int(end) if sep else first
338
+ except ValueError:
339
+ raise ValueError(f"expected START:END, got {value!r}") from None
340
+ if first < 1:
341
+ raise ValueError(f"line numbers start at 1, got {value!r}")
342
+ if last < first:
343
+ raise ValueError(f"range ends before it starts: {value!r}")
344
+ ranges.append((first, last))
345
+ return tuple(ranges)
346
+
347
+
297
348
  def main(argv: list[str] | None = None) -> int:
349
+ _quiet_sqlglot_fallbacks()
298
350
  p = build_parser()
299
351
  args = p.parse_args(argv)
300
352
 
@@ -347,6 +399,14 @@ def main(argv: list[str] | None = None) -> int:
347
399
  print(f"sqlalign: {w}", file=sys.stderr)
348
400
  return style
349
401
 
402
+ if args.sqlfluff_config is not None:
403
+ if not args.lint:
404
+ # Accepting it silently would leave a reader believing their config
405
+ # was used, which is worse than the flag being unavailable.
406
+ p.error("--sqlfluff-config only applies to --lint")
407
+ if not args.sqlfluff_config.is_file():
408
+ p.error(f"--sqlfluff-config: no such file: {args.sqlfluff_config}")
409
+
350
410
  if args.init:
351
411
  # Refuses to overwrite: a config is a decision a team already made, and
352
412
  # a starter is only ever the first one.
@@ -363,7 +423,7 @@ def main(argv: list[str] | None = None) -> int:
363
423
  print(f"sqlalign: {e}", file=sys.stderr)
364
424
  return 2
365
425
  try:
366
- target.write_text(starter)
426
+ target.write_text(starter, encoding="utf-8")
367
427
  except OSError as e:
368
428
  print(f"sqlalign: {e}", file=sys.stderr)
369
429
  return 2
@@ -382,6 +442,19 @@ def main(argv: list[str] | None = None) -> int:
382
442
  if "-" in args.files and len(args.files) > 1:
383
443
  p.error("`-` reads stdin and cannot be combined with file arguments")
384
444
 
445
+ line_ranges = None
446
+ if args.lines is not None:
447
+ try:
448
+ line_ranges = parse_line_ranges(args.lines)
449
+ except ValueError as e:
450
+ p.error(f"--lines: {e}")
451
+ # One range against many files would mean "line 12 of each", which
452
+ # nobody wants and which would silently reformat the wrong thing. A
453
+ # directory is the same mistake spelled shorter -- it expands to every
454
+ # .sql file under it.
455
+ if len(args.files) != 1 or Path(args.files[0]).is_dir():
456
+ p.error("--lines applies to a single file (or `-`)")
457
+
385
458
  if args.print_sqlfluff_config:
386
459
  # Resolved against the first file like --show-config, so the generated
387
460
  # config reflects the style that actually applies there rather than the
@@ -441,11 +514,11 @@ def main(argv: list[str] | None = None) -> int:
441
514
  # Read the raw buffer rather than sys.stdin, whose universal
442
515
  # newline translation would rewrite CRLF before the code below
443
516
  # gets to notice it.
444
- original = sys.stdin.buffer.read().decode()
517
+ original = sys.stdin.buffer.read().decode("utf-8")
445
518
  else:
446
519
  # newline="" disables universal-newline translation so CRLF/CR bytes
447
520
  # survive into `original` and can be detected below (v1 is LF-only).
448
- with path.open(newline="") as f:
521
+ with path.open(encoding="utf-8", newline="") as f:
449
522
  original = f.read()
450
523
  except OSError as e:
451
524
  print(f"sqlalign: {e}", file=sys.stderr)
@@ -481,7 +554,7 @@ def main(argv: list[str] | None = None) -> int:
481
554
  sys.stdout.write(original)
482
555
  continue
483
556
  try:
484
- result = format_sql(normalized, dialect_for(path), style)
557
+ result = format_sql(normalized, dialect_for(path), style, line_ranges)
485
558
  except Exception as e: # parse/safety failures surface as exit 2, file untouched
486
559
  print(f"sqlalign: {name}: {e}", file=sys.stderr)
487
560
  rc = 2
@@ -529,7 +602,8 @@ def main(argv: list[str] | None = None) -> int:
529
602
  if args.lint:
530
603
  # Lint what would be written, so --check and --stdout report on the
531
604
  # formatted result rather than on whatever is currently on disk.
532
- code, out, err = lint(path, formatted, style, dialect_for(path))
605
+ code, out, err = lint(path, formatted, style, dialect_for(path),
606
+ args.sqlfluff_config)
533
607
  sys.stdout.write(out)
534
608
  sys.stderr.write(err)
535
609
  if code:
@@ -544,6 +618,24 @@ def main(argv: list[str] | None = None) -> int:
544
618
  return rc
545
619
 
546
620
 
621
+ def _utf8_streams() -> None:
622
+ """Write stdout as UTF-8 with no newline translation, the way files are read.
623
+
624
+ Otherwise stdout uses the locale's encoding and, on Windows, turns every
625
+ `\\n` into `\\r\\n`. `sqlalign -` then reads UTF-8 and writes cp1252 (any
626
+ character cp1252 lacks raises), and an LF file comes back CRLF, so an
627
+ editor filter rewrites every line ending. stderr keeps its line endings
628
+ but is UTF-8 too, so a file name or message cp1252 cannot spell is escaped
629
+ rather than raising.
630
+ """
631
+ # A replaced stream (an embedder's, a test's) may not be a TextIOWrapper,
632
+ # and a closed or detached one refuses: either way it is left as it is.
633
+ for stream, options in ((sys.stdout, {"newline": ""}),
634
+ (sys.stderr, {"errors": "backslashreplace"})):
635
+ with contextlib.suppress(AttributeError, ValueError):
636
+ stream.reconfigure(encoding="utf-8", **options)
637
+
638
+
547
639
  def console() -> int:
548
640
  """The installed command. `main` stays exception-transparent for callers
549
641
  that embed it; this wrapper owns the one failure that belongs to being a
@@ -557,6 +649,7 @@ def console() -> int:
557
649
  """
558
650
  import os
559
651
 
652
+ _utf8_streams()
560
653
  try:
561
654
  return main()
562
655
  except BrokenPipeError: