sqlalign 1.0.2__py3-none-any.whl → 1.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sqlalign/__init__.py +90 -10
- sqlalign/cli.py +176 -20
- sqlalign/configfile.py +83 -6
- sqlalign/formatter.py +124 -7
- sqlalign/gui.py +83 -5
- sqlalign/keywordcase.py +8 -2
- sqlalign/layout/__init__.py +19 -0
- sqlalign/layout/conditions.py +50 -3
- sqlalign/layout/cte.py +7 -2
- sqlalign/layout/ddl.py +22 -1
- sqlalign/layout/grouporder.py +28 -3
- sqlalign/plpgsql.py +60 -5
- sqlalign/spelling.py +110 -0
- sqlalign/style.py +26 -0
- {sqlalign-1.0.2.dist-info → sqlalign-1.2.0.dist-info}/METADATA +88 -21
- {sqlalign-1.0.2.dist-info → sqlalign-1.2.0.dist-info}/RECORD +19 -18
- sqlalign-1.2.0.dist-info/entry_points.txt +2 -0
- sqlalign-1.0.2.dist-info/entry_points.txt +0 -2
- {sqlalign-1.0.2.dist-info → sqlalign-1.2.0.dist-info}/WHEEL +0 -0
- {sqlalign-1.0.2.dist-info → sqlalign-1.2.0.dist-info}/licenses/LICENSE +0 -0
sqlalign/__init__.py
CHANGED
|
@@ -1,10 +1,90 @@
|
|
|
1
|
-
"""sqlalign -- a SQL formatter for the house columnar-alignment style.
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
1
|
+
"""sqlalign -- a SQL formatter for the house columnar-alignment style.
|
|
2
|
+
|
|
3
|
+
The supported Python entry points are the two functions below. Everything under
|
|
4
|
+
`sqlalign.*` beyond them is internal and moves between releases.
|
|
5
|
+
|
|
6
|
+
>>> import sqlalign
|
|
7
|
+
>>> print(sqlalign.format("select a,b from t;"))
|
|
8
|
+
SELECT a
|
|
9
|
+
, b
|
|
10
|
+
FROM t;
|
|
11
|
+
|
|
12
|
+
Imports are deferred into the function bodies so that `import sqlalign` stays
|
|
13
|
+
cheap. Pulling in sqlglot costs most of the startup time of a run, and a
|
|
14
|
+
`--version` or a `__version__` read should not pay for it.
|
|
15
|
+
"""
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from typing import TYPE_CHECKING
|
|
19
|
+
|
|
20
|
+
if TYPE_CHECKING: # imported for annotations only
|
|
21
|
+
from sqlalign.formatter import FormatResult
|
|
22
|
+
from sqlalign.style import Style
|
|
23
|
+
|
|
24
|
+
__all__ = ["format", "format_result"]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def format(sql: str, *, dialect: str = "postgres",
|
|
28
|
+
style: Style | None = None) -> str:
|
|
29
|
+
"""Format `sql` and return the result.
|
|
30
|
+
|
|
31
|
+
A statement sqlalign cannot model is returned byte-identical rather than
|
|
32
|
+
raising: passing through is the contract, not a failure. That does mean this
|
|
33
|
+
function cannot tell you it happened -- use `format_result` when you need to
|
|
34
|
+
know, which is most of the time in a pipeline that gates on something.
|
|
35
|
+
|
|
36
|
+
`dialect` is one of `postgres`, `redshift` or `tsql`; anything else raises
|
|
37
|
+
`ValueError` rather than being formatted with keywords the target engine may
|
|
38
|
+
not accept. `style` defaults to the house style; build one with
|
|
39
|
+
`sqlalign.style.Style` or `sqlalign.style.preset_style("compact")`.
|
|
40
|
+
|
|
41
|
+
Named `format` because that is what it does. It shadows the builtin inside
|
|
42
|
+
this module and nowhere else, since callers reach it as `sqlalign.format`.
|
|
43
|
+
"""
|
|
44
|
+
return format_result(sql, dialect=dialect, style=style).text
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def format_result(sql: str, *, dialect: str = "postgres",
|
|
48
|
+
style: Style | None = None) -> FormatResult:
|
|
49
|
+
"""Format `sql` and return the text together with what happened to it.
|
|
50
|
+
|
|
51
|
+
The result carries `text`, `warnings`, `statements` and `declines`. A
|
|
52
|
+
decline names the construct that was passed through and why, which is what
|
|
53
|
+
`--report` counts; reading it is how an embedding tells "formatted" apart
|
|
54
|
+
from "left alone", since both come back as valid SQL.
|
|
55
|
+
"""
|
|
56
|
+
from sqlalign.formatter import format_sql
|
|
57
|
+
from sqlalign.style import HOUSE
|
|
58
|
+
|
|
59
|
+
# The same line-ending handling the CLI does, so the API is not a second,
|
|
60
|
+
# subtly different tool: the engine is LF-only, CRLF is normalized in and
|
|
61
|
+
# restored on the way out, and a lone CR -- which the engine does not
|
|
62
|
+
# model -- passes through with a warning rather than surfacing as a
|
|
63
|
+
# baffling per-statement decline.
|
|
64
|
+
ending = "\r\n" if "\r\n" in sql else "\n"
|
|
65
|
+
normalized = sql.replace("\r\n", "\n")
|
|
66
|
+
if "\r" in normalized:
|
|
67
|
+
from sqlalign.formatter import FormatResult
|
|
68
|
+
return FormatResult(sql, ["lone CR line endings — passed through untouched"])
|
|
69
|
+
|
|
70
|
+
result = format_sql(normalized, dialect, HOUSE if style is None else style)
|
|
71
|
+
if ending == "\r\n":
|
|
72
|
+
result = result._replace(text=result.text.replace("\n", "\r\n"))
|
|
73
|
+
return result
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def __getattr__(name: str) -> str:
|
|
77
|
+
"""Resolve `__version__` on first access rather than at import.
|
|
78
|
+
|
|
79
|
+
Read from the installed distribution rather than written here: the literal
|
|
80
|
+
this replaces still said "0.1.0" at release 1.1.0, because nothing forces
|
|
81
|
+
the two to be edited together. pyproject.toml is now the single place a
|
|
82
|
+
release bumps.
|
|
83
|
+
"""
|
|
84
|
+
if name == "__version__":
|
|
85
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
86
|
+
try:
|
|
87
|
+
return version("sqlalign")
|
|
88
|
+
except PackageNotFoundError: # a source tree that was never installed
|
|
89
|
+
return "0.0.0+unknown"
|
|
90
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
sqlalign/cli.py
CHANGED
|
@@ -5,6 +5,7 @@ import os
|
|
|
5
5
|
import shutil
|
|
6
6
|
import sys
|
|
7
7
|
import tempfile
|
|
8
|
+
import urllib.parse
|
|
8
9
|
from fnmatch import fnmatch
|
|
9
10
|
from pathlib import Path
|
|
10
11
|
|
|
@@ -12,7 +13,14 @@ from sqlalign import configfile
|
|
|
12
13
|
from sqlalign.formatter import format_sql
|
|
13
14
|
from sqlalign.lint import LintUnavailable, lint, version_warning
|
|
14
15
|
from sqlalign.sqlfluffconfig import sqlfluff_config
|
|
15
|
-
from sqlalign.style import
|
|
16
|
+
from sqlalign.style import (
|
|
17
|
+
ALL_ALIGN_TARGETS,
|
|
18
|
+
PRESETS,
|
|
19
|
+
SUPPORTED_DIALECTS,
|
|
20
|
+
Style,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
DEFAULT_DIALECT = "postgres"
|
|
16
24
|
|
|
17
25
|
|
|
18
26
|
def _write_atomically(path: Path, text: str) -> None:
|
|
@@ -109,9 +117,60 @@ def _report(seen: int, declined: int, causes: dict[tuple[str, str], int]) -> str
|
|
|
109
117
|
width = max(len(kind) for kind, _ in causes)
|
|
110
118
|
for (kind, reason), count in sorted(causes.items(), key=lambda kv: (-kv[1], kv[0])):
|
|
111
119
|
lines.append(f" {count:>4} {kind:<{width}} {reason}")
|
|
120
|
+
ask = _ask_for_construct(causes)
|
|
121
|
+
if ask:
|
|
122
|
+
lines += ["", ask]
|
|
112
123
|
return "\n".join(lines)
|
|
113
124
|
|
|
114
125
|
|
|
126
|
+
def _issue_url() -> str | None:
|
|
127
|
+
"""Where to report a missing construct, from the package metadata.
|
|
128
|
+
|
|
129
|
+
Read rather than written here, so the address exists in exactly one place --
|
|
130
|
+
pyproject, which is also what PyPI shows.
|
|
131
|
+
"""
|
|
132
|
+
from importlib.metadata import PackageNotFoundError, metadata
|
|
133
|
+
try:
|
|
134
|
+
entries = metadata("sqlalign").get_all("Project-URL") or []
|
|
135
|
+
except PackageNotFoundError: # a source tree that was never installed
|
|
136
|
+
return None
|
|
137
|
+
for entry in entries:
|
|
138
|
+
label, _, url = entry.partition(", ")
|
|
139
|
+
if label.strip().lower() == "issues":
|
|
140
|
+
return url.strip()
|
|
141
|
+
return None
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _ask_for_construct(causes: dict[tuple[str, str], int]) -> str | None:
|
|
145
|
+
"""An invitation to ask for the construct that declined most often.
|
|
146
|
+
|
|
147
|
+
A decline is a gap measured on the team's own SQL rather than guessed at,
|
|
148
|
+
which makes it the most useful thing a user could tell this project. Left as
|
|
149
|
+
a count it is a dead end; with somewhere to send it, the report becomes a
|
|
150
|
+
demand-ranked backlog.
|
|
151
|
+
|
|
152
|
+
Only `unsupported`, and only the top one. A parse error or an upstream
|
|
153
|
+
round-trip failure is not sqlalign's to implement, and a URL per cause would
|
|
154
|
+
turn a summary into a wall of links.
|
|
155
|
+
"""
|
|
156
|
+
unsupported = {reason: count for (kind, reason), count in causes.items()
|
|
157
|
+
if kind == "unsupported"}
|
|
158
|
+
if not unsupported:
|
|
159
|
+
return None
|
|
160
|
+
base = _issue_url()
|
|
161
|
+
if base is None:
|
|
162
|
+
return None
|
|
163
|
+
top = max(unsupported.items(), key=lambda kv: (kv[1], kv[0]))[0]
|
|
164
|
+
# A reason reads "PIVOT: this dialect has no such syntax". The construct is
|
|
165
|
+
# the part before the colon; the rest is the explanation, and splicing it
|
|
166
|
+
# into a sentence or an issue title reads like a machine wrote it.
|
|
167
|
+
construct = top.split(":", 1)[0].strip()
|
|
168
|
+
query = urllib.parse.urlencode({"title": f"Support {construct}",
|
|
169
|
+
"labels": "construct"})
|
|
170
|
+
return (f" {construct} is the construct declining most often here. If it "
|
|
171
|
+
f"matters to you, ask for it:\n {base}/new?{query}")
|
|
172
|
+
|
|
173
|
+
|
|
115
174
|
def _version() -> str:
|
|
116
175
|
"""The installed version, or a marker when running from a source tree that
|
|
117
176
|
was never installed."""
|
|
@@ -140,8 +199,12 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
140
199
|
output_mode.add_argument("--diff", action="store_true",
|
|
141
200
|
help="write nothing; print a unified diff of what would "
|
|
142
201
|
"change (exit 1 if anything would)")
|
|
143
|
-
|
|
144
|
-
|
|
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)")
|
|
145
208
|
p.add_argument("--line-ending", choices=["auto", "lf", "crlf"], default="auto",
|
|
146
209
|
help="line endings to write: auto preserves the file's own (default)")
|
|
147
210
|
# Config-file plumbing.
|
|
@@ -154,6 +217,10 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
154
217
|
help="ignore any config file and use the built-in defaults")
|
|
155
218
|
p.add_argument("--show-config", action="store_true",
|
|
156
219
|
help="print the effective settings as TOML and exit")
|
|
220
|
+
p.add_argument("--init", action="store_true",
|
|
221
|
+
help="write a commented .sqlalign.toml in the current directory "
|
|
222
|
+
"and exit; every setting is commented out, so the file "
|
|
223
|
+
"changes nothing until you edit it")
|
|
157
224
|
p.add_argument("--gui", action="store_true",
|
|
158
225
|
help="(experimental) open the settings panel with a live preview, and exit")
|
|
159
226
|
p.add_argument("--report", action="store_true",
|
|
@@ -193,11 +260,12 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
193
260
|
dest="format_dollar_bodies",
|
|
194
261
|
help="leave dollar-quoted ($$) procedure and function bodies untouched")
|
|
195
262
|
p.add_argument("--align-targets",
|
|
263
|
+
# The valid list is derived, not typed: the typed version had
|
|
264
|
+
# drifted to seven names while the set held nine.
|
|
196
265
|
help="comma-separated alignment targets to keep. Default is every "
|
|
197
266
|
"target except table_names, which is opt-in because it pads "
|
|
198
267
|
"the FROM/JOIN keyword out to a shared table column. "
|
|
199
|
-
"Valid:
|
|
200
|
-
"case_results, column_types, column_constraints")
|
|
268
|
+
f"Valid: {', '.join(sorted(ALL_ALIGN_TARGETS))}")
|
|
201
269
|
p.add_argument("--comma-position", choices=["leading", "trailing"],
|
|
202
270
|
help="where the separator comma sits in a stacked list (default: leading)")
|
|
203
271
|
p.add_argument("--boolean-operator-position", choices=["leading", "trailing"],
|
|
@@ -252,6 +320,22 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
252
320
|
"on_placement": args.on_placement,
|
|
253
321
|
}
|
|
254
322
|
|
|
323
|
+
def dialect_for(path: Path) -> str:
|
|
324
|
+
"""The dialect for one input file: flag, then config, then postgres.
|
|
325
|
+
|
|
326
|
+
The flag wins so a one-off run can override a committed config, which is
|
|
327
|
+
the same precedence every style setting already follows.
|
|
328
|
+
"""
|
|
329
|
+
if args.dialect is not None:
|
|
330
|
+
return args.dialect
|
|
331
|
+
if args.isolated:
|
|
332
|
+
return DEFAULT_DIALECT
|
|
333
|
+
config = args.config if args.config is not None else configfile.find_config(path)
|
|
334
|
+
if config is None:
|
|
335
|
+
return DEFAULT_DIALECT
|
|
336
|
+
return configfile.load_dialect(
|
|
337
|
+
config, strict=not args.no_strict_config) or DEFAULT_DIALECT
|
|
338
|
+
|
|
255
339
|
def style_for(path: Path) -> Style:
|
|
256
340
|
"""Settings for one input file: house defaults < config file < flags.
|
|
257
341
|
Resolved per file so one invocation can span repos with different
|
|
@@ -263,13 +347,41 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
263
347
|
print(f"sqlalign: {w}", file=sys.stderr)
|
|
264
348
|
return style
|
|
265
349
|
|
|
350
|
+
if args.init:
|
|
351
|
+
# Refuses to overwrite: a config is a decision a team already made, and
|
|
352
|
+
# a starter is only ever the first one.
|
|
353
|
+
target = Path(".sqlalign.toml")
|
|
354
|
+
if target.exists():
|
|
355
|
+
print(f"sqlalign: {target} already exists — nothing written",
|
|
356
|
+
file=sys.stderr)
|
|
357
|
+
return 2
|
|
358
|
+
try:
|
|
359
|
+
starter = configfile.starter(style_for(Path(".")), args.preset)
|
|
360
|
+
except configfile.ConfigError as e:
|
|
361
|
+
# The starter shows the settings currently in effect, so it resolves
|
|
362
|
+
# config like any other mode -- and fails like one: message, exit 2.
|
|
363
|
+
print(f"sqlalign: {e}", file=sys.stderr)
|
|
364
|
+
return 2
|
|
365
|
+
try:
|
|
366
|
+
target.write_text(starter)
|
|
367
|
+
except OSError as e:
|
|
368
|
+
print(f"sqlalign: {e}", file=sys.stderr)
|
|
369
|
+
return 2
|
|
370
|
+
print(f"wrote {target}")
|
|
371
|
+
return 0
|
|
372
|
+
|
|
266
373
|
if args.gui:
|
|
267
374
|
from sqlalign.gui import run
|
|
268
|
-
return run(
|
|
375
|
+
return run(dialect_for(Path(".")))
|
|
269
376
|
|
|
270
|
-
if not args.files and not (args.print_sqlfluff_config or args.gui):
|
|
377
|
+
if not args.files and not (args.print_sqlfluff_config or args.gui or args.init):
|
|
271
378
|
p.error("the following arguments are required: files")
|
|
272
379
|
|
|
380
|
+
# stdin is read once, so `-` alongside paths has no sensible reading: it
|
|
381
|
+
# would either format one input twice or silently drop the others.
|
|
382
|
+
if "-" in args.files and len(args.files) > 1:
|
|
383
|
+
p.error("`-` reads stdin and cannot be combined with file arguments")
|
|
384
|
+
|
|
273
385
|
if args.print_sqlfluff_config:
|
|
274
386
|
# Resolved against the first file like --show-config, so the generated
|
|
275
387
|
# config reflects the style that actually applies there rather than the
|
|
@@ -282,7 +394,7 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
282
394
|
if args.files else configfile.build_style({}, overrides))
|
|
283
395
|
except configfile.ConfigError as e:
|
|
284
396
|
p.error(str(e))
|
|
285
|
-
print(sqlfluff_config(style,
|
|
397
|
+
print(sqlfluff_config(style, dialect_for(Path("."))), end="")
|
|
286
398
|
return 0
|
|
287
399
|
|
|
288
400
|
if args.show_config:
|
|
@@ -295,6 +407,12 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
295
407
|
for w in warns:
|
|
296
408
|
print(f"sqlalign: {w}", file=sys.stderr)
|
|
297
409
|
print(f"# {source}" if source else "# built-in defaults (no config file found)")
|
|
410
|
+
# Printed with the settings because it IS one, and this output is
|
|
411
|
+
# documented as TOML a reader could paste back -- omitting a key would
|
|
412
|
+
# make the pasted config mean something different. Kept above the style
|
|
413
|
+
# block, and out of Style, because it selects the grammar rather than
|
|
414
|
+
# the layout.
|
|
415
|
+
print(f'dialect = "{dialect_for(Path(args.files[0]))}"')
|
|
298
416
|
print(configfile.describe(style))
|
|
299
417
|
return 0
|
|
300
418
|
|
|
@@ -319,10 +437,16 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
319
437
|
for path in targets:
|
|
320
438
|
name = str(path)
|
|
321
439
|
try:
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
440
|
+
if name == "-":
|
|
441
|
+
# Read the raw buffer rather than sys.stdin, whose universal
|
|
442
|
+
# newline translation would rewrite CRLF before the code below
|
|
443
|
+
# gets to notice it.
|
|
444
|
+
original = sys.stdin.buffer.read().decode()
|
|
445
|
+
else:
|
|
446
|
+
# newline="" disables universal-newline translation so CRLF/CR bytes
|
|
447
|
+
# survive into `original` and can be detected below (v1 is LF-only).
|
|
448
|
+
with path.open(newline="") as f:
|
|
449
|
+
original = f.read()
|
|
326
450
|
except OSError as e:
|
|
327
451
|
print(f"sqlalign: {e}", file=sys.stderr)
|
|
328
452
|
rc = 2
|
|
@@ -350,11 +474,14 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
350
474
|
if "\r" in normalized:
|
|
351
475
|
print(f"sqlalign: {name}: lone CR line endings — passed through untouched",
|
|
352
476
|
file=sys.stderr)
|
|
353
|
-
|
|
477
|
+
# `-` has no file for the caller to fall back to: an editor filter
|
|
478
|
+
# replaces the buffer with whatever comes out, so passing through
|
|
479
|
+
# must mean echoing the input, never emitting nothing.
|
|
480
|
+
if args.stdout or name == "-":
|
|
354
481
|
sys.stdout.write(original)
|
|
355
482
|
continue
|
|
356
483
|
try:
|
|
357
|
-
result = format_sql(normalized,
|
|
484
|
+
result = format_sql(normalized, dialect_for(path), style)
|
|
358
485
|
except Exception as e: # parse/safety failures surface as exit 2, file untouched
|
|
359
486
|
print(f"sqlalign: {name}: {e}", file=sys.stderr)
|
|
360
487
|
rc = 2
|
|
@@ -370,13 +497,12 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
370
497
|
# diff on every line) instead of differing purely by "\r".
|
|
371
498
|
target_ending = source_ending if args.line_ending == "auto" else args.line_ending
|
|
372
499
|
formatted = result.text.replace("\n", "\r\n") if target_ending == "crlf" else result.text
|
|
373
|
-
if args.
|
|
374
|
-
sys.stdout.write(formatted)
|
|
375
|
-
elif args.check or args.diff:
|
|
500
|
+
if args.check or args.diff:
|
|
376
501
|
# Both write nothing and report through the exit code; they differ in
|
|
377
502
|
# what they print. --check names the files that would change (enough
|
|
378
503
|
# for CI to be actionable without burying the log in diffs); --diff
|
|
379
|
-
# shows the change itself.
|
|
504
|
+
# shows the change itself. For `-` the name printed is `-`, which is
|
|
505
|
+
# what the reader passed.
|
|
380
506
|
if formatted != original:
|
|
381
507
|
if args.diff:
|
|
382
508
|
sys.stdout.writelines(difflib.unified_diff(
|
|
@@ -386,6 +512,10 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
386
512
|
else:
|
|
387
513
|
print(f"would reformat {name}")
|
|
388
514
|
rc = max(rc, 1)
|
|
515
|
+
# `-` has no file to rewrite, so the formatted text IS the output. Ordered
|
|
516
|
+
# after --check/--diff so those still report on stdin rather than writing.
|
|
517
|
+
elif args.stdout or name == "-":
|
|
518
|
+
sys.stdout.write(formatted)
|
|
389
519
|
elif formatted != original:
|
|
390
520
|
try:
|
|
391
521
|
_write_atomically(path, formatted)
|
|
@@ -399,7 +529,7 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
399
529
|
if args.lint:
|
|
400
530
|
# Lint what would be written, so --check and --stdout report on the
|
|
401
531
|
# formatted result rather than on whatever is currently on disk.
|
|
402
|
-
code, out, err = lint(path, formatted, style,
|
|
532
|
+
code, out, err = lint(path, formatted, style, dialect_for(path))
|
|
403
533
|
sys.stdout.write(out)
|
|
404
534
|
sys.stderr.write(err)
|
|
405
535
|
if code:
|
|
@@ -414,5 +544,31 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
414
544
|
return rc
|
|
415
545
|
|
|
416
546
|
|
|
547
|
+
def console() -> int:
|
|
548
|
+
"""The installed command. `main` stays exception-transparent for callers
|
|
549
|
+
that embed it; this wrapper owns the one failure that belongs to being a
|
|
550
|
+
process in a pipeline.
|
|
551
|
+
|
|
552
|
+
`sqlalign - | head -3` closes stdout after three lines. Dying quietly is
|
|
553
|
+
the pipeline contract -- every coreutils tool does -- and 141 is how a
|
|
554
|
+
shell spells death-by-SIGPIPE, so scripts that check for it keep working.
|
|
555
|
+
stdout is detached first, or the interpreter's exit flush raises the same
|
|
556
|
+
error a second time as an ignored-exception message on stderr.
|
|
557
|
+
"""
|
|
558
|
+
import os
|
|
559
|
+
|
|
560
|
+
try:
|
|
561
|
+
return main()
|
|
562
|
+
except BrokenPipeError:
|
|
563
|
+
# Best-effort: under a captured stdout (tests, some embedders) there is
|
|
564
|
+
# no file descriptor to detach, and nothing to protect either.
|
|
565
|
+
try:
|
|
566
|
+
devnull = os.open(os.devnull, os.O_WRONLY)
|
|
567
|
+
os.dup2(devnull, sys.stdout.fileno())
|
|
568
|
+
except (OSError, ValueError):
|
|
569
|
+
pass
|
|
570
|
+
return 141
|
|
571
|
+
|
|
572
|
+
|
|
417
573
|
if __name__ == "__main__":
|
|
418
|
-
sys.exit(
|
|
574
|
+
sys.exit(console())
|
sqlalign/configfile.py
CHANGED
|
@@ -17,11 +17,14 @@ not have, and would only discover it from a surprising diff. `--no-strict-config
|
|
|
17
17
|
downgrades that to a warning for the case where a config is shared with a newer
|
|
18
18
|
sqlalign that knows keys this one does not.
|
|
19
19
|
"""
|
|
20
|
-
|
|
20
|
+
try:
|
|
21
|
+
import tomllib
|
|
22
|
+
except ModuleNotFoundError: # Python 3.10
|
|
23
|
+
import tomli as tomllib
|
|
21
24
|
from pathlib import Path
|
|
22
25
|
|
|
23
26
|
from sqlalign.config import Width
|
|
24
|
-
from sqlalign.style import PRESETS, Style
|
|
27
|
+
from sqlalign.style import PRESETS, SETTING_SUMMARIES, Style
|
|
25
28
|
|
|
26
29
|
FILENAME = ".sqlalign.toml"
|
|
27
30
|
PYPROJECT = "pyproject.toml"
|
|
@@ -39,11 +42,34 @@ _SCALAR_KEYS = frozenset({
|
|
|
39
42
|
"keyword_case",
|
|
40
43
|
})
|
|
41
44
|
KNOWN_KEYS = _SCALAR_KEYS | {"width", "align_targets", "preset", "exclude",
|
|
42
|
-
"blank_lines_between_statements"}
|
|
45
|
+
"dialect", "blank_lines_between_statements"}
|
|
43
46
|
|
|
44
|
-
#
|
|
45
|
-
#
|
|
46
|
-
|
|
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
|
|
47
73
|
|
|
48
74
|
|
|
49
75
|
def load_excludes(path: Path, *, strict: bool = True) -> list[str]:
|
|
@@ -162,6 +188,57 @@ def resolve(path: Path, overrides: dict | None = None, *,
|
|
|
162
188
|
return build_style(settings, overrides), config_path, warnings
|
|
163
189
|
|
|
164
190
|
|
|
191
|
+
def starter(style: Style, preset: str | None = None) -> str:
|
|
192
|
+
"""A commented `.sqlalign.toml` for a project that has none.
|
|
193
|
+
|
|
194
|
+
Every setting is emitted COMMENTED OUT, showing the value currently in
|
|
195
|
+
effect. The file therefore changes nothing until something is uncommented,
|
|
196
|
+
which is the property that makes it safe to write into a repository: a
|
|
197
|
+
starter that pinned eighteen settings would freeze a team on today's
|
|
198
|
+
defaults and call it a choice.
|
|
199
|
+
|
|
200
|
+
A `--preset` is the exception and is written live, because choosing one is
|
|
201
|
+
the decision the reader just made. The settings below it then show what that
|
|
202
|
+
preset does, so the file doubles as the answer to "what did I just pick".
|
|
203
|
+
|
|
204
|
+
Values come from `describe`, so what a starter shows and what
|
|
205
|
+
`--show-config` reports cannot drift apart.
|
|
206
|
+
"""
|
|
207
|
+
rendered = {}
|
|
208
|
+
for line in describe(style).splitlines():
|
|
209
|
+
if line.startswith("#") or " = " not in line:
|
|
210
|
+
continue
|
|
211
|
+
rendered[line.split(" = ", 1)[0]] = line
|
|
212
|
+
|
|
213
|
+
out = [
|
|
214
|
+
"# sqlalign configuration.",
|
|
215
|
+
"#",
|
|
216
|
+
"# Written by `sqlalign --init`. Every setting is commented out and shows the",
|
|
217
|
+
"# value currently in effect, so this file changes nothing until you uncomment",
|
|
218
|
+
"# something.",
|
|
219
|
+
"#",
|
|
220
|
+
"# Reference: https://sqlalign.lumaru.app/v1/settings.html",
|
|
221
|
+
"",
|
|
222
|
+
]
|
|
223
|
+
if preset:
|
|
224
|
+
out += [
|
|
225
|
+
'# The base every setting below starts from. Flags and any setting you',
|
|
226
|
+
'# uncomment layer on top of it.',
|
|
227
|
+
f'preset = "{preset}"',
|
|
228
|
+
"",
|
|
229
|
+
]
|
|
230
|
+
for name, summary in SETTING_SUMMARIES.items():
|
|
231
|
+
line = rendered.get(name)
|
|
232
|
+
out.append(f"# {summary}")
|
|
233
|
+
if line is None:
|
|
234
|
+
# `blank_lines_between_statements` has no TOML spelling when unset.
|
|
235
|
+
out.append(f"# {name} =")
|
|
236
|
+
else:
|
|
237
|
+
out.append(f"# {line}")
|
|
238
|
+
out.append("")
|
|
239
|
+
return "\n".join(out).rstrip() + "\n"
|
|
240
|
+
|
|
241
|
+
|
|
165
242
|
def describe(style: Style) -> str:
|
|
166
243
|
"""The effective settings, as the TOML a user could paste into a config."""
|
|
167
244
|
lines = [
|