sqlalign 1.0.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/__init__.py ADDED
@@ -0,0 +1,10 @@
1
+ """sqlalign -- a SQL formatter for the house columnar-alignment style."""
2
+ from importlib.metadata import PackageNotFoundError, version
3
+
4
+ # Read from the installed distribution rather than written here: the literal this
5
+ # replaces still said "0.1.0" at release 1.1.0, because nothing forces the two to
6
+ # be edited together. pyproject.toml is now the single place a release bumps.
7
+ try:
8
+ __version__ = version("sqlalign")
9
+ except PackageNotFoundError: # a source tree that was never installed
10
+ __version__ = "0.0.0+unknown"
sqlalign/align.py ADDED
@@ -0,0 +1,145 @@
1
+ from sqlalign.ir import RIGHT_ALIGNED, Line, Seg
2
+ from sqlalign.style import ALIGN_TARGETS, ALL_ALIGN_TARGETS
3
+
4
+
5
+ def apply_align_targets(lines: list[Line], targets: frozenset[str]) -> list[Line]:
6
+ """Untag every segment whose alignment target is disabled.
7
+
8
+ One mechanism serves all of them: a segment only participates in alignment
9
+ when it carries BOTH a scope and a kind (see `_resolve_targets`), so
10
+ switching a target off is just clearing those two fields. The column then
11
+ collapses to render()'s ordinary single space -- no separate code path, and
12
+ no way for a disabled target to still influence a column.
13
+ """
14
+ if targets == ALL_ALIGN_TARGETS:
15
+ return lines
16
+ enabled = frozenset().union(*(ALIGN_TARGETS[t] for t in targets)) if targets else frozenset()
17
+ for line in lines:
18
+ for seg in line.segs:
19
+ if seg.kind is not None and seg.scope is not None and seg.kind not in enabled:
20
+ seg.scope = seg.kind = None
21
+ return lines
22
+
23
+
24
+ def _placed(line: Line) -> list[Seg]:
25
+ """The segments of `line` that actually occupy a column.
26
+
27
+ A zero-width segment is dropped unless it is TAGGED. The distinction is real:
28
+ a handler emits `Seg("", scope, kind=...)` deliberately, to hold a column with
29
+ nothing in it: fromjoin.py heads a trailing-boolean continuation that way so
30
+ the resolver right-aligns its zero-width end into the ON column. An UNTAGGED
31
+ empty segment holds no column and renders nothing, yet the one-space
32
+ inter-segment separator would still emit a space in front of it.
33
+
34
+ Those are not two separate cases: `apply_align_targets` turns the first into
35
+ the second by clearing scope and kind, so a disabled target leaves no
36
+ phantom space where its column was and `align_targets=frozenset()` agrees
37
+ with `align=False`.
38
+
39
+ Both passes below must filter identically, or the resolver counts a separator
40
+ the emitter does not write and every target shifts by one.
41
+ """
42
+ return [seg for seg in line.segs if seg.text or (seg.scope and seg.kind)]
43
+
44
+
45
+ def _resolve_targets(lines: list[Line]) -> dict[tuple[str, str], int]:
46
+ """Per (scope, kind) group, find the target column, dependency-aware.
47
+
48
+ A tag's target is the max, over the group's segments, of where that segment
49
+ *lands*: its start column for a left-aligned kind, its end column for a
50
+ RIGHT_ALIGNED one. Landing is not the same as the segment's naive
51
+ single-space position: an EARLIER tagged segment on the same line may itself
52
+ be padded rightward (out to its own group target) in the emit pass, which
53
+ shifts everything after it. So a tag's position depends on the targets of
54
+ the tags to its left, which is why a single left-to-right sweep (as the
55
+ original resolver did) under-computes a column whenever two dependent tagged
56
+ columns share a line and their maxima are driven by different rows.
57
+
58
+ We iterate to a fixpoint. Each sweep recomputes every target by replaying
59
+ the emit pass's padding with the *previous* sweep's targets: when the
60
+ running column reaches a tagged segment, place it at
61
+ `max(natural, targets_so_far)` and advance past the placed (not natural)
62
+ position. Targets are monotonically non-decreasing across sweeps and bounded
63
+ by total line length, so the iteration converges; we stop as soon as a full
64
+ sweep changes nothing.
65
+
66
+ Convergence is exact and cheap for the common case: the FIRST sweep starts
67
+ from all-zero targets, so every `max(natural, 0)` is just `natural` and the
68
+ result is byte-identical to the original single-sweep resolver. A second
69
+ sweep only raises a target when some tagged segment actually sat behind an
70
+ earlier padded tagged segment on its line; lines with at most one tagged
71
+ column (01/02/04 and every non-FROM/JOIN scope) never trigger that, so they
72
+ fix in one sweep at exactly the original targets. The enhancement can only
73
+ raise an under-computed column, never lower or alter a correct one.
74
+ """
75
+ targets: dict[tuple[str, str], int] = {}
76
+ num_keys = len({(s.scope, s.kind) for ln in lines for s in ln.segs
77
+ if s.scope and s.kind})
78
+ # Monotone, bounded targets converge; this cap only guards a logic error.
79
+ cap = len(lines) * num_keys + 8
80
+ for _ in range(cap):
81
+ swept: dict[tuple[str, str], int] = {}
82
+ for line in lines:
83
+ col = line.indent
84
+ for i, seg in enumerate(_placed(line)):
85
+ if i:
86
+ col += 1 # one separating space
87
+ if seg.scope and seg.kind:
88
+ key = (seg.scope, seg.kind)
89
+ if seg.kind in RIGHT_ALIGNED:
90
+ placed_end = max(col + len(seg.text), targets.get(key, 0))
91
+ swept[key] = max(swept.get(key, 0), placed_end)
92
+ col = placed_end
93
+ else:
94
+ placed_start = max(col, targets.get(key, 0))
95
+ swept[key] = max(swept.get(key, 0), placed_start)
96
+ col = placed_start + len(seg.text)
97
+ else:
98
+ col += len(seg.text)
99
+ if swept == targets:
100
+ return targets
101
+ targets = swept
102
+ raise AssertionError("alignment resolver did not converge to a fixpoint")
103
+
104
+
105
+ def render(lines: list[Line], align: bool = True) -> str:
106
+ """Emit `lines` as text. With `align` False the column-resolution pass is
107
+ skipped entirely and segments are emitted one space apart: line breaks and
108
+ indents are already fixed by the layout handlers, so this yields the same
109
+ line structure without the alignment padding (Style.align).
110
+
111
+ every empty segment is dropped here, including a tagged one: a stronger rule
112
+ than `_placed`'s, and deliberately so. A handler emits `Seg("", kind="on")`
113
+ purely to hold a column (fromjoin.py heads a trailing-boolean continuation
114
+ that way), and with alignment off there are no columns for it to hold. Joining
115
+ it like any other segment contributed a separator space with no text in front
116
+ of it, so an unaligned continuation indented THREE where the structure calls
117
+ for two."""
118
+ if not align:
119
+ return "\n".join(
120
+ (" " * line.indent + " ".join(seg.text for seg in line.segs if seg.text)).rstrip()
121
+ for line in lines
122
+ ) + "\n"
123
+
124
+ # Pass 1: per (scope, kind) group, find the target column (dependency-aware).
125
+ targets = _resolve_targets(lines)
126
+
127
+ # Pass 2: emit, padding tagged segments out to their group target.
128
+ out = []
129
+ for line in lines:
130
+ buf, col = [" " * line.indent], line.indent
131
+ for i, seg in enumerate(_placed(line)):
132
+ if i:
133
+ buf.append(" ")
134
+ col += 1
135
+ if seg.scope and seg.kind:
136
+ t = targets[(seg.scope, seg.kind)]
137
+ start = t - len(seg.text) if seg.kind in RIGHT_ALIGNED else t
138
+ pad = start - col
139
+ if pad > 0:
140
+ buf.append(" " * pad)
141
+ col += pad
142
+ buf.append(seg.text)
143
+ col += len(seg.text)
144
+ out.append("".join(buf).rstrip())
145
+ return "\n".join(out) + "\n"
sqlalign/bodylint.py ADDED
@@ -0,0 +1,125 @@
1
+ """Expose the SQL inside a `$$ … $$` body to a linter.
2
+
3
+ sqlfluff parses a plpgsql body as a single string literal, so nothing inside it
4
+ is ever linted. `lint_view` returns the file with everything that is not
5
+ lintable SQL replaced by spaces, leaving every line and column where it was, so
6
+ a position the linter reports is a position in the original file.
7
+
8
+ Blanking rather than deleting is what preserves the columns. The cost is that
9
+ the view carries whitespace the source did not, so whitespace rules fire on
10
+ padding lines; `artifact_lines` identifies those. sqlalign's own coexistence
11
+ config excludes the whole `layout` group, which covers them.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import re
16
+
17
+ from sqlalign import plpgsql
18
+ from sqlalign.splitter import split_statements
19
+
20
+ # A control keyword the splitter leaves glued to the front of the statement
21
+ # after it (see `plpgsql.body_clauses`). The statement behind it is still SQL,
22
+ # so the keyword is skipped rather than the whole clause being discarded.
23
+ _GLUED = re.compile(r"^\s*(?:begin|declare|then|else|loop)\b", re.I)
24
+
25
+
26
+ def lint_view(source: str, dialect: str = "postgres") -> str:
27
+ """`source` with only its lintable SQL left standing, at its own coordinates.
28
+
29
+ Statements outside a `$$` body are untouched: a linter could already see
30
+ those, and rewriting them would risk changing what it reports about them.
31
+ """
32
+ out = list(source)
33
+ for start, end in _body_spans(source, dialect):
34
+ _blank(out, start, end)
35
+ for keep_start, keep_end in _sql_spans(source, start, end, dialect):
36
+ out[keep_start:keep_end] = list(source[keep_start:keep_end])
37
+ return "".join(out)
38
+
39
+
40
+ def artifact_lines(source: str, dialect: str = "postgres") -> set[int]:
41
+ """1-based line numbers that carry no real content in the view.
42
+
43
+ A finding on one of these is about padding this module introduced, not
44
+ about the author's SQL.
45
+ """
46
+ view = lint_view(source, dialect)
47
+ return {i for i, line in enumerate(view.split("\n"), 1) if not line.strip()}
48
+
49
+
50
+ def body_lines(source: str, dialect: str = "postgres") -> set[int]:
51
+ """1-based line numbers holding SQL that ONLY the view can see.
52
+
53
+ A caller lints twice, once the real file, once the view, and keeps the
54
+ view's findings only for these lines, which makes the two sets disjoint so
55
+ they merge without having to recognise the same finding twice.
56
+
57
+ Derived from the kept SQL spans rather than from the whole `CREATE`
58
+ statement. A statement piece carries the blank line before it, so a span
59
+ starts on the PREVIOUS statement's line -- and using that would have
60
+ claimed a top-level statement as body content, reporting its findings
61
+ twice.
62
+ """
63
+ lines: set[int] = set()
64
+ for start, end in _body_spans(source, dialect):
65
+ for sql_start, sql_end in _sql_spans(source, start, end, dialect):
66
+ first = source.count("\n", 0, sql_start) + 1
67
+ last = source.count("\n", 0, sql_end) + 1
68
+ lines.update(range(first, last + 1))
69
+ return lines
70
+
71
+
72
+ def has_bodies(source: str, dialect: str = "postgres") -> bool:
73
+ """Whether `source` holds a dollar-quoted body worth looking inside."""
74
+ return bool(_body_spans(source, dialect))
75
+
76
+
77
+ def _body_spans(source: str, dialect: str) -> list[tuple[int, int]]:
78
+ """`(start, end)` of every dollar-quoted CREATE in `source`, whole statement.
79
+
80
+ Found by walking the same splitter the formatter uses, so a `$$` inside a
81
+ string literal cannot be mistaken for a body.
82
+ """
83
+ spans = []
84
+ cursor = 0
85
+ for piece in split_statements(source, dialect):
86
+ start, end = cursor, cursor + len(piece)
87
+ cursor = end
88
+ if plpgsql.split_body(piece.strip()) is not None:
89
+ spans.append((start, end))
90
+ return spans
91
+
92
+
93
+ def _sql_spans(source: str, start: int, end: int, dialect: str) -> list[tuple[int, int]]:
94
+ """The spans inside one body statement that are lintable SQL."""
95
+ statement = source[start:end]
96
+ parts = plpgsql.split_body(statement.strip())
97
+ if parts is None:
98
+ return []
99
+ header, body, _tail = parts
100
+ if not body:
101
+ return []
102
+ # `statement.strip()` may have dropped leading whitespace, so locate the
103
+ # body in the UNSTRIPPED slice to keep the offsets true.
104
+ offset = statement.index(body, len(header) - 1 if header else 0)
105
+
106
+ spans = []
107
+ cursor = start + offset
108
+ for piece in split_statements(body, dialect):
109
+ piece_start, piece_end = cursor, cursor + len(piece)
110
+ cursor = piece_end
111
+ if not piece.strip():
112
+ continue
113
+ glued = _GLUED.match(piece)
114
+ skip = glued.end() if glued else 0
115
+ candidate = piece[skip:].strip().rstrip(";").strip()
116
+ if candidate and plpgsql._is_sql(candidate, dialect):
117
+ spans.append((piece_start + skip, piece_end))
118
+ return spans
119
+
120
+
121
+ def _blank(chars: list[str], start: int, end: int) -> None:
122
+ """Replace a span with spaces, keeping every newline where it was."""
123
+ for i in range(start, end):
124
+ if chars[i] != "\n":
125
+ chars[i] = " "
sqlalign/casing.py ADDED
@@ -0,0 +1,182 @@
1
+ import contextvars
2
+ from contextlib import contextmanager
3
+ from typing import ClassVar
4
+
5
+ from sqlglot import exp
6
+ from sqlglot.dialects.postgres import Postgres
7
+ from sqlglot.dialects.redshift import Redshift
8
+ from sqlglot.dialects.tsql import TSQL
9
+
10
+ from sqlalign.style import HOUSE, Style
11
+
12
+ # The ambient render style. `render_expr` is called from ~57 sites across every
13
+ # layout handler, all of which care only about LAYOUT knobs (width), so the two
14
+ # pure OUTPUT-SPELLING knobs (neq_style, decimal_style) are read from here rather
15
+ # than threaded through every handler signature. `format_sql` sets it once per
16
+ # call; nesting and recursion are safe because the token is reset on exit.
17
+ _RENDER_STYLE: contextvars.ContextVar[Style] = contextvars.ContextVar("sqlalign_render_style")
18
+
19
+
20
+ def active_style() -> Style:
21
+ """The style in effect for rendering; HOUSE when nothing set it."""
22
+ return _RENDER_STYLE.get(HOUSE)
23
+
24
+
25
+ @contextmanager
26
+ def render_style(style: Style):
27
+ token = _RENDER_STYLE.set(style)
28
+ try:
29
+ yield
30
+ finally:
31
+ _RENDER_STYLE.reset(token)
32
+
33
+
34
+ # Cast-form discriminator (v30.14, version-pinned; revisit on sqlglot upgrade):
35
+ # `::` sources parse to a Cast node carrying only {'this', 'to'}. CAST()/
36
+ # TRY_CAST() sources always carry these four CAST-specific keys too, even
37
+ # when their values are None. Key PRESENCE: not len(node.args) and not
38
+ # truthiness is the reliable discriminator. Under the redshift dialect
39
+ # every Cast node (including `::`-form ones) additionally carries an
40
+ # incidental 'join_mark' key, which breaks a raw `len(args) <= 2` check.
41
+ _CAST_FORM_KEYS = ("format", "safe", "action", "default")
42
+
43
+
44
+ class _HouseCastMixin:
45
+ """Cast/type-name house rules, applied at every AST nesting depth.
46
+
47
+ Mixed into dialect-specific Generator subclasses (below) so the dialect's
48
+ own cast_sql/datatype_sql overrides (e.g. Postgres's superfluous-DIV()-
49
+ cast unwrap, Redshift's JSON-cast noop and TEXT->VARCHAR(MAX)) still run
50
+ via super(), with the house rules layered on top.
51
+ """
52
+
53
+ def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str:
54
+ if any(key in expression.args for key in _CAST_FORM_KEYS):
55
+ return super().cast_sql(expression, safe_prefix=safe_prefix)
56
+ return f"{self.sql(expression, 'this')}::{self.sql(expression, 'to')}"
57
+
58
+ def datatype_sql(self, expression: exp.DataType) -> str:
59
+ sql = super().datatype_sql(expression)
60
+ # DECIMAL and NUMERIC are exact synonyms in postgres/redshift; sqlglot
61
+ # parses both to one node, erasing the source spelling, so one of them
62
+ # has to be printed: Style.decimal_style picks which (house: NUMERIC).
63
+ target = active_style().decimal_style
64
+ if sql == "DECIMAL" or sql.startswith("DECIMAL("):
65
+ return target + sql[len("DECIMAL"):]
66
+ return sql
67
+
68
+ def neq_sql(self, expression: exp.NEQ) -> str:
69
+ # sqlglot erases the source `<>`/`!=` spelling at parse, so a form must be
70
+ # chosen when printing: Style.neq_style (house: `!=`). conditions.py's
71
+ # laid-out path reads the same knob, so both stay consistent.
72
+ return self.binary(expression, active_style().neq_style)
73
+
74
+
75
+ class _HousePostgresGenerator(_HouseCastMixin, Postgres.Generator):
76
+ pass
77
+
78
+
79
+ class _HouseRedshiftGenerator(_HouseCastMixin, Redshift.Generator):
80
+ pass
81
+
82
+
83
+ class _HouseTSQLGenerator(_HouseCastMixin, TSQL.Generator):
84
+ """T-SQL wants the mixin's neq/decimal handling but NOT its cast form.
85
+
86
+ `_HouseCastMixin.cast_sql` emits the `::` shorthand when the source used it —
87
+ correct for postgres/redshift, and INVALID T-SQL, which has no `::` operator at
88
+ all. Restoring the dialect's own cast_sql means every cast renders as
89
+ `CAST(x AS T)`, the only form SQL Server accepts. There is correspondingly no
90
+ "preserve the source cast form" behaviour here: T-SQL only has one form.
91
+ """
92
+
93
+ def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str:
94
+ return TSQL.Generator.cast_sql(self, expression, safe_prefix=safe_prefix)
95
+
96
+
97
+ # dialect name (lowercase) -> (Dialect class, house Generator class)
98
+ _HOUSE_GENERATORS = {
99
+ "postgres": (Postgres, _HousePostgresGenerator),
100
+ "redshift": (Redshift, _HouseRedshiftGenerator),
101
+ "tsql": (TSQL, _HouseTSQLGenerator),
102
+ }
103
+
104
+
105
+ def _house_date_trunc(args):
106
+ """DATE_TRUNC('unit', expr) -> exp.Anonymous, not exp.TimestampTrunc.
107
+
108
+ Empirically (pinned sqlglot v30.14): TimestampTrunc's base mixin, TimeUnit,
109
+ unconditionally re-cases its `unit` arg to an uppercase exp.Var the instant
110
+ the node is CONSTRUCTED (TimeUnit.__init__) -- 'month'/'MONTH'/'Month' all
111
+ collapse to Var(this=MONTH), destroying the source spelling before any
112
+ renderer ever sees the node. House style is "identifiers, aliases, string
113
+ literals: untouched", so parsing DATE_TRUNC as a plain function
114
+ call instead sidesteps TimeUnit entirely: the unit stays the literal
115
+ sqlglot tokenized, case intact, and render_expr's normal Anonymous path
116
+ renders it verbatim (the function name itself is hardcoded upper here,
117
+ matching house function-name casing regardless of source spelling).
118
+
119
+ Used only by `parse_dialect`'s house dialects, which formatter.py's
120
+ `_format_statement` uses for the ONE parse that builds the layout tree.
121
+ The plain "postgres"/"redshift" dialect strings used elsewhere (ast_equal,
122
+ CLI, tests) are untouched: both sides of an ast_equal comparison still
123
+ parse DATE_TRUNC the stock (TimestampTrunc) way, so case-insensitive unit
124
+ equivalence there is unaffected either way.
125
+ """
126
+ return exp.Anonymous(this="DATE_TRUNC", expressions=list(args))
127
+
128
+
129
+ class _HousePostgresParser(Postgres.Parser):
130
+ FUNCTIONS: ClassVar[dict] = {**Postgres.Parser.FUNCTIONS, "DATE_TRUNC": _house_date_trunc}
131
+
132
+
133
+ class _HouseRedshiftParser(Redshift.Parser):
134
+ FUNCTIONS: ClassVar[dict] = {**Redshift.Parser.FUNCTIONS, "DATE_TRUNC": _house_date_trunc}
135
+
136
+
137
+ class _HousePostgresParseDialect(Postgres):
138
+ Parser = _HousePostgresParser
139
+
140
+
141
+ class _HouseRedshiftParseDialect(Redshift):
142
+ Parser = _HouseRedshiftParser
143
+
144
+
145
+ # dialect name (lowercase) -> house Dialect class carrying parse-time overrides
146
+ _HOUSE_PARSE_DIALECTS = {
147
+ "postgres": _HousePostgresParseDialect,
148
+ "redshift": _HouseRedshiftParseDialect,
149
+ # T-SQL has no DATE_TRUNC, so it needs no parse-time override: the stock
150
+ # dialect is used, which parse_dialect falls back to for any unlisted name.
151
+ }
152
+
153
+
154
+ def parse_dialect(dialect: str):
155
+ """Resolve a plain dialect string to the house Dialect instance that
156
+ carries parse-time house rules (see `_house_date_trunc`) on top of the
157
+ stock dialect's own parsing. Falls back to the bare string for any
158
+ dialect without a house override, so
159
+ `sqlglot.parse(text, read=parse_dialect(d))` is always a safe drop-in for
160
+ `sqlglot.parse(text, read=d)`.
161
+ """
162
+ cls = _HOUSE_PARSE_DIALECTS.get(dialect.lower())
163
+ return cls() if cls is not None else dialect
164
+
165
+
166
+ # Generator settings both render paths below must share: function names upper,
167
+ # never add quotes an identifier did not have, and no sqlglot line breaking --
168
+ # layout owns every newline.
169
+ _RENDER_OPTIONS = {"normalize_functions": "upper", "identify": False, "pretty": False}
170
+
171
+
172
+ def render_expr(node: exp.Expression, dialect: str) -> str:
173
+ """Render an inline expression with house casing; layout does NOT re-wrap this."""
174
+ house = _HOUSE_GENERATORS.get(dialect.lower())
175
+ if house is not None:
176
+ dialect_cls, generator_cls = house
177
+ generator = generator_cls(dialect=dialect_cls(), **_RENDER_OPTIONS)
178
+ return generator.generate(node, copy=True)
179
+
180
+ # Any dialect without a house Generator (none ship today) still renders,
181
+ # just without the cast/decimal/neq house rules.
182
+ return node.sql(dialect=dialect, **_RENDER_OPTIONS)