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.
@@ -0,0 +1,245 @@
1
+ """Subquery layout: the three shapes sample 07
2
+ exercises --
3
+
4
+ 1. a **scalar subquery** in a SELECT-list item (select.py),
5
+ 2. `IN (SELECT ...)` / `EXISTS (SELECT ...)` in a WHERE/HAVING predicate
6
+ (conditions.py), and
7
+ 3. a **derived table** (subquery as a FROM/JOIN table ref) (fromjoin.py) --
8
+
9
+ all recurse the subquery's body through `layout_statement` at the column one
10
+ past its opening `(`, then splice the result into the surrounding line. They
11
+ differ only in how the close reads: scalar/IN/EXISTS close
12
+ *inline*, glued (zero space) onto the last body line; a derived-table JOIN
13
+ closes on its *own* line, before the alias.
14
+
15
+ Geometry is precomputed, not resolver-driven: every inner-anchor column below
16
+ is derived from the caller's own *natural* (unpadded) layout, the same
17
+ simplification `conditions.py`'s `_render_group` already relies on for a
18
+ parenthesized condition group's `(` column. A tag's resolver-driven padding
19
+ (e.g. a WHERE clause's shared `op` column, when a subquery predicate shares
20
+ scope with siblings) can shift where a segment actually lands at render time,
21
+ but the inner body's own line *indents* are plain ints baked in at
22
+ layout-build time: they cannot depend on a later resolver pass. This is
23
+ only safe because every segment feeding into an inner-anchor calculation
24
+ above is itself untagged (no scope/kind), so its natural column IS its
25
+ rendered column: the SELECT-list `head_seg` (fixed-width keyword/comma), the
26
+ FROM/JOIN `keyword` for a derived table, and `conditions.py`'s `IN` keyword.
27
+ `IN` is deliberately untagged: in the WHERE clause's shared `op` scope, a
28
+ sibling condition with a longer LHS would pad it rightward at
29
+ render time while the subquery body's baked-in indent stayed at the
30
+ now-stale natural column: silently detaching the body from its own `(`
31
+ (caught on `WHERE a = <long> AND b IN (SELECT ...)`, ast_equal-safe so
32
+ invisible to the safety net). `conditions.py::_render_in_subquery` now emits
33
+ `IN` untagged, matching `EXISTS` (already untagged) and eliminating the
34
+ class: nothing an inner-anchor formula in this module depends on can ever be
35
+ resolver-padded, so natural and rendered can no longer diverge.
36
+
37
+ Alignment scopes are id(node)-namespaced (`f"dtjoin@{id(join)}"`, etc.) per
38
+ house convention -- see fromjoin.py's and select.py's module docstrings.
39
+ """
40
+ from sqlglot import exp
41
+
42
+ from sqlalign.casing import active_style, render_expr
43
+ from sqlalign.ir import Line, Seg
44
+ from sqlalign.layout import (
45
+ COMMA_ROW,
46
+ Unsupported,
47
+ clause_head,
48
+ row_keyword,
49
+ table_alias,
50
+ )
51
+ from sqlalign.layout.conditions import predicate_segs, split_conjunction
52
+
53
+
54
+ def guard_subquery(subquery: exp.Subquery, *, allow_alias: bool = False) -> None:
55
+ """Raise `Unsupported` for any `exp.Subquery` arg this layer does not
56
+ model. Verified empirically (pinned sqlglot v30.14): a plain
57
+ `(SELECT ...)` only ever populates `this` (always) and `alias` (derived
58
+ tables only): every other key in `exp.Subquery.arg_types` (`with_`,
59
+ `sample`, `for_`, `pivots`, ...) is exotic syntax outside this task's
60
+ scope. The wrapped `Select`/`SetOperation`/`With` itself is validated
61
+ separately, when `layout_statement` recurses into it.
62
+ """
63
+ if subquery.comments:
64
+ raise Unsupported("embedded comment")
65
+ # `pivots` is allowed alongside an alias because `FROM (SELECT …) s PIVOT(…)`
66
+ # is the ordinary way to write a pivot: you pivot a projection, not a bare
67
+ # table. The pivot carries its own alias and renders whole, so it is a
68
+ # suffix on the closing line rather than anything to lay out.
69
+ allowed = {"this", "alias", "pivots"} if allow_alias else {"this"}
70
+ for name, value in subquery.args.items():
71
+ if value in (None, [], False):
72
+ continue
73
+ if name not in allowed:
74
+ raise Unsupported(f"subquery arg: {name}")
75
+
76
+
77
+ def _open_inline(select, dialect, width, inner_anchor):
78
+ """Recurse `select`'s body at `inner_anchor` (one column past the open
79
+ paren) and return `(open_segs, trailing_lines)`, UNCLOSED:
80
+
81
+ - `open_segs` -- the body's first `Line`'s segs, with `(` glued (zero
82
+ space) onto the front of the first one. Meant to be appended, via
83
+ `render()`'s normal one-space inter-seg separator, right after
84
+ whatever precedes the paren on the caller's current row.
85
+ - `trailing_lines`: every remaining body `Line`, verbatim (already
86
+ indented at `inner_anchor` by `layout_statement`).
87
+
88
+ Callers close the `)` per their own shape: `subquery_body` glues it
89
+ inline (scalar/IN/EXISTS); `derived_table_lines` puts it on a new line.
90
+ """
91
+ from sqlalign.layout import layout_statement
92
+
93
+ body = layout_statement(select, dialect, width, anchor=inner_anchor)
94
+ first, trailing = body[0], body[1:]
95
+ open_segs = [_prefixed(first.segs[0], "("), *first.segs[1:]]
96
+ return open_segs, trailing
97
+
98
+
99
+ def subquery_body(select, dialect, width, inner_anchor):
100
+ """`_open_inline`, closed inline on its last line -- the scalar / `IN` /
101
+ `EXISTS` shape, and EXISTS (...)
102
+ subqueries close inline"). Returns `(open_segs, trailing_lines)`, the
103
+ same `(inline_segs, trailing_lines)` shape `conditions.py`'s
104
+ `_render_condition` uses, so callers there can return it directly.
105
+ """
106
+ open_segs, trailing = _open_inline(select, dialect, width, inner_anchor)
107
+ if trailing:
108
+ trailing[-1].segs[-1].text += ")"
109
+ else:
110
+ open_segs[-1].text += ")"
111
+ return open_segs, trailing
112
+
113
+
114
+ def derived_table_lines(join: exp.Join, anchor: int, dialect: str, width) -> list[Line]:
115
+ """A derived-table JOIN (`join.this` is `exp.Subquery`): `JOIN (` opens
116
+ inline, the body recurses at its own `SELECT` column, and the closing
117
+ `)` lands on its OWN line, unlike scalar/IN/EXISTS -- followed by the
118
+ alias and `ON`/`USING`.
119
+
120
+ Per the exclusion, the alias/`ON`/operator here are NOT part of
121
+ the enclosing FROM-block's shared scopes (`fj@{id(select)}` in
122
+ fromjoin.py): they get their own scope, namespaced by `id(join)` (unique
123
+ for this join's lifetime), so they align only with each other -- a
124
+ second derived-table join, or a multi-condition `ON`/`AND` on THIS join,
125
+ never bleeds into a sibling regular join's alias/ON/op columns, or vice
126
+ versa.
127
+ """
128
+ subquery = join.this
129
+ # `LATERAL (SELECT ...)` is a derived table that may reference columns from
130
+ # the rows to its left. Its geometry is identical; the only differences are
131
+ # the extra keyword and that the ALIAS hangs off the Lateral rather than off
132
+ # the subquery, which is why this could not simply fall through.
133
+ lateral = subquery if isinstance(subquery, exp.Lateral) else None
134
+ if lateral is not None:
135
+ subquery = lateral.this
136
+ guard_subquery(subquery, allow_alias=True)
137
+ alias = (lateral or subquery).args.get("alias")
138
+ if alias is None:
139
+ raise Unsupported("derived table: missing alias")
140
+
141
+ keyword = row_keyword(join)
142
+ if keyword is COMMA_ROW:
143
+ # The legacy comma form, which is how `LATERAL` is most often written.
144
+ # The comma hangs two columns before the FROM row's table column, the
145
+ # same place fromjoin.py puts it for a plain comma-joined table.
146
+ from_anchor, from_kw = clause_head("FROM", anchor)
147
+ anchor, keyword = from_anchor + len(from_kw) + 1 - 2, ","
148
+ else:
149
+ anchor, keyword = clause_head(keyword, anchor, hang=True)
150
+ if lateral is not None:
151
+ keyword = f"{keyword} LATERAL"
152
+ open_col = anchor + len(keyword) + 1 # column of the derived table's "("
153
+ inner_anchor = open_col + 1 # the subquery's own SELECT column
154
+ open_segs, body_lines = _open_inline(subquery.this, dialect, width, inner_anchor)
155
+ first_line = Line(anchor, [_prefixed(open_segs[0], f"{keyword} "), *open_segs[1:]])
156
+
157
+ scope = f"dtjoin@{id(join)}"
158
+ # The alias is untagged: excluded from the fj@ scope.
159
+ tail = [Seg(")"), Seg(table_alias(lateral or subquery, dialect))]
160
+ tail += [Seg(render_expr(pivot, dialect)) for pivot in subquery.args.get("pivots") or []]
161
+ using = join.args.get("using")
162
+ if join.args.get("on") is None and not using:
163
+ # No condition: a LATERAL, or a CROSS JOIN of a derived table. The
164
+ # closing paren and the alias are the whole row.
165
+ close_lines = [Line(open_col, tail)]
166
+ elif using:
167
+ cols = ", ".join(render_expr(c, dialect) for c in using)
168
+ close_lines = [Line(open_col, [*tail, Seg(f"USING ({cols})", scope=scope, kind="on")])]
169
+ else:
170
+ conditions, joiner = split_conjunction(join.args["on"])
171
+ # Same two knobs the regular-join path honours (fromjoin.py): a derived
172
+ # table's ON must not keep leading booleans (or an inline ON) while the
173
+ # rest of the file uses the other convention. No fixture exercises a
174
+ # derived join with a multi-condition ON, so this path is covered by its
175
+ # own tests rather than by the cross-golden invariants.
176
+ style = active_style()
177
+ bools_trail = style.boolean_operator_position == "trailing"
178
+ if style.on_placement == "own_line":
179
+ close_lines = [Line(open_col, list(tail))]
180
+ keywords = ["ON"] + [joiner] * (len(conditions) - 1)
181
+ max_kw = max(len(k) for k in keywords)
182
+ for i, (kw, cond) in enumerate(zip(keywords, conditions, strict=False)):
183
+ if bools_trail and i:
184
+ close_lines[-1].segs[-1].text += " " + kw
185
+ head = Seg(" " * max_kw)
186
+ else:
187
+ head = Seg(kw.rjust(max_kw))
188
+ close_lines.append(
189
+ Line(open_col + 2, [head, *predicate_segs(cond, scope, dialect)]))
190
+ else:
191
+ close_lines = [Line(open_col, [*tail, Seg("ON", scope=scope, kind="on"),
192
+ *predicate_segs(conditions[0], scope, dialect)])]
193
+ for cond in conditions[1:]:
194
+ if bools_trail:
195
+ close_lines[-1].segs[-1].text += " " + joiner
196
+ head = Seg("", scope=scope, kind="on")
197
+ else:
198
+ head = Seg(joiner, scope=scope, kind="on")
199
+ close_lines.append(
200
+ Line(open_col, [head, *predicate_segs(cond, scope, dialect)]))
201
+
202
+ return [first_line, *body_lines, *close_lines]
203
+
204
+
205
+ def _prefixed(seg: Seg, prefix: str) -> Seg:
206
+ """A copy of `seg` with `prefix` glued to the front of its text.
207
+
208
+ The body's first segment carries its own leading padding under
209
+ `clause_keyword_align="river"` -- the inner `SELECT` is right-aligned into
210
+ its gutter, and the `(` takes that space. Dropping it here keeps the paren
211
+ against the keyword (`(SELECT`, never `( SELECT`); the inner query's own
212
+ river is measured from `inner_anchor`, which is already the column after the
213
+ paren, so nothing downstream shifts.
214
+ """
215
+ return Seg(prefix + seg.text.lstrip(" "), scope=seg.scope, kind=seg.kind)
216
+
217
+
218
+ def derived_from_lines(frm: exp.From, anchor: int, dialect: str, width) -> list[Line]:
219
+ """`FROM (SELECT ...) d` -- a derived table in the FROM position.
220
+
221
+ Geometry identical to a derived-table JOIN, minus the join condition a FROM
222
+ cannot have: `FROM (` opens inline, the body recurses at its own SELECT
223
+ column, and the closing `)` lands on its own line followed by the alias.
224
+
225
+ It cannot simply call `derived_table_lines`, which is keyed to a `join` node
226
+ for both its keyword and its ON/USING tail. The part that actually matters --
227
+ where the body recurses and where the paren closes: is `_open_inline`,
228
+ shared verbatim, so the two shapes cannot drift apart.
229
+
230
+ The alias is untagged, exactly as it is for a derived-table JOIN:
231
+ a derived table does not join the enclosing FROM block's alias column.
232
+ """
233
+ subquery = frm.this
234
+ guard_subquery(subquery, allow_alias=True)
235
+ alias = subquery.args.get("alias")
236
+ if alias is None:
237
+ raise Unsupported("derived table: missing alias")
238
+
239
+ kw_anchor, kw_text = clause_head("FROM", anchor)
240
+ open_col = kw_anchor + len(kw_text) + 1
241
+ open_segs, body_lines = _open_inline(subquery.this, dialect, width, open_col + 1)
242
+ first = Line(kw_anchor, [_prefixed(open_segs[0], f"{kw_text} "), *open_segs[1:]])
243
+ tail = [Seg(")"), Seg(table_alias(subquery, dialect))]
244
+ tail += [Seg(render_expr(pivot, dialect)) for pivot in subquery.args.get("pivots") or []]
245
+ return [first, *body_lines, Line(open_col, tail)]
@@ -0,0 +1,207 @@
1
+ """Window-function layout: a select-list
2
+ item whose value is `exp.Window`: `FUNC(...) OVER (PARTITION BY ...
3
+ [ORDER BY ...] [frame])`. `OVER` gets a space before its paren (a keyword,
4
+ not a function name -- same family as `IN (...)`/`EXISTS (...)`; spec's
5
+ deliberate change from the raw samples' `OVER(`).
6
+
7
+ Geometry is precomputed, not resolver-driven: the same simplification
8
+ subquery.py's module docstring documents for a recursed body's baked-in
9
+ indent: `content_col` (where PARTITION/ORDER BY/the frame clause sit, and
10
+ where every continuation line aligns) is plain arithmetic off the function
11
+ call's own rendered length (`item_col + len(FUNC(...) OVER () )`), because
12
+ every segment feeding that arithmetic: the function call text, the literal
13
+ `" OVER ("` -- is itself untagged, so its natural column IS its rendered
14
+ column and can never be shifted by a later resolver pass. Verified
15
+ empirically against fixture #9 (pinned sqlglot v30.14): this formula lands
16
+ `PARTITION` at column 26/24/29 for the sample's three windows (inline,
17
+ frame-dropped, and inline again respectively) -- exactly the fixture's
18
+ columns, whether or not that window ends up breaking.
19
+
20
+ Breaking ladder (spec): (1) inline if `FUNC(...) OVER (...)` fits the width
21
+ limit; (2) else, break inside the parens at sub-clause boundaries, peeling
22
+ from the END of the fixed [PARTITION BY, ORDER BY, frame] priority order one
23
+ sub-clause at a time: the frame clause drops to its own line FIRST, and
24
+ only if PARTITION BY + ORDER BY still don't fit combined does ORDER BY also
25
+ get its own line; (3) if a single sub-clause's own column list is still too
26
+ long even alone on its line, it stacks like a GROUP BY (leading commas) --
27
+ this last rung is untested by any fixture (#9's sub-clauses are all short)
28
+ but is implemented as a defensive extension of the same ladder, documented
29
+ where it lives (`_stack_subclause`). The window always closes inline (`)`
30
+ glued onto the last line, like scalar/IN/EXISTS subqueries: ) and
31
+ the `AS` alias participates in the caller's (select.py's) own select-list
32
+ alignment scope, exactly like any other item.
33
+
34
+ `exp.WindowSpec`'s `kind`/`start_side`/`end_side` args hold RAW,
35
+ source-preserved-casing text (verified empirically; this is exactly why
36
+ formatter.py's `_CASEFOLD_STR_ARGS` table already lists them for
37
+ `ast_equal`'s casefold pass) -- `render_expr` on a bare spec node does NOT
38
+ uppercase them the way it uppercases function names, so `_frame_text` below
39
+ manually upper-cases those three fields on a COPY of the spec node before
40
+ rendering (house style: keywords upper, never touching a genuine string
41
+ literal: these three fields are never user data, only fixed keyword
42
+ vocabulary, so this is safe).
43
+ """
44
+ from sqlglot import exp
45
+
46
+ from sqlalign.casing import active_style, render_expr
47
+ from sqlalign.ir import Line, Seg
48
+ from sqlalign.layout import Unsupported, comma_clause, select_item_col
49
+
50
+ _PREFIX_TAIL = " OVER (" # space-before-paren: OVER is a keyword, not a function name
51
+
52
+
53
+ def window_lines(win_node: exp.Window, anchor: int, dialect: str, width) -> list[Line]:
54
+ """Lay out `win_node` (a select item's window-function value) at
55
+ select-statement anchor `anchor`. Line 0's `indent` is `anchor` itself
56
+ (not the item column) so the caller (select.py) can splice its own
57
+ lead-in segment onto the front, exactly like case.py's `case_lines`.
58
+ """
59
+ _guard_window(win_node)
60
+ # `SUM(x) OVER w`: a REFERENCE to a window named in the WINDOW clause.
61
+ # There is no spec to lay out here; the spec lives in that clause, and the
62
+ # whole item is one short line whatever the width.
63
+ named = win_node.args.get("alias")
64
+ if named is not None:
65
+ func = render_expr(win_node.this, dialect)
66
+ return [Line(anchor, [Seg(f"{func} OVER {render_expr(named, dialect)}")])]
67
+
68
+ item_col = select_item_col(anchor)
69
+ func_text = render_expr(win_node.this, dialect)
70
+ prefix = func_text + _PREFIX_TAIL
71
+ content_col = item_col + len(prefix)
72
+
73
+ partition = _partition_text(win_node, dialect)
74
+ order = _order_text(win_node, dialect)
75
+ frame = _frame_text(win_node, dialect)
76
+ subclauses = [s for s in (partition, order, frame) if s is not None]
77
+ if not subclauses:
78
+ # `COUNT(*) OVER ()`: the empty window, which means "the whole result
79
+ # set". It is ordinary SQL and there is nothing to lay out: an empty
80
+ # pair of parens on the function's own line.
81
+ return [Line(anchor, [Seg(prefix + ")")])]
82
+
83
+ limit = width.limit(item_col)
84
+ full = prefix + " ".join(subclauses) + ")"
85
+ if item_col + len(full) <= limit:
86
+ return [Line(anchor, [Seg(full)])]
87
+
88
+ rows = _break_rows(subclauses, content_col, limit)
89
+ lines = [Line(anchor, [Seg(prefix + rows[0])])]
90
+ lines += [Line(content_col, [Seg(r)]) for r in rows[1:]]
91
+ lines[-1].segs[-1].text += ")"
92
+ return lines
93
+
94
+
95
+ def named_window_lines(windows, anchor: int, dialect: str) -> list[Line]:
96
+ """The `WINDOW w AS (...)` clause: a named spec reused by `OVER w`.
97
+
98
+ Composed from the same three spec builders `window_lines` uses, rather than
99
+ from `render_expr`, which prints a named window as `w OVER (...)`: the
100
+ inline spelling. The clause form needs `AS`, and rewriting one into the other
101
+ with string surgery would be a guess about a shape sqlglot is free to change.
102
+ """
103
+ terms = []
104
+ for win in windows:
105
+ if win.comments:
106
+ raise Unsupported("embedded comment")
107
+ name = win.this
108
+ if name is None or win.args.get("alias"):
109
+ raise Unsupported("WINDOW clause: unexpected shape")
110
+ parts = [p for p in (_partition_text(win, dialect), _order_text(win, dialect),
111
+ _frame_text(win, dialect)) if p]
112
+ terms.append(f"{render_expr(name, dialect)} AS ({' '.join(parts)})")
113
+ return comma_clause("WINDOW", terms, anchor)
114
+
115
+
116
+ def _guard_window(win: exp.Window) -> None:
117
+ """Decline (`Unsupported`) window shapes this module does not model.
118
+ Verified empirically (pinned sqlglot v30.14, `exp.Window.arg_types`):
119
+ `alias` only populates for a named `WINDOW w AS (...)` clause (that
120
+ clause itself is already gated -- select.py's `_ALLOWED_ARGS` excludes
121
+ the Select `windows` arg entirely); `first` carries a FIRST/LAST
122
+ positional flag (e.g. `IGNORE NULLS` ordering) sample 09 never
123
+ exercises.
124
+ """
125
+ if win.comments:
126
+ raise Unsupported("embedded comment")
127
+ if win.args.get("alias") and any(
128
+ win.args.get(k) for k in ("partition_by", "order", "spec")):
129
+ # A reference carries only the name; a name PLUS an inline spec is
130
+ # `OVER w (ORDER BY ...)`, a shape this layer does not model.
131
+ raise Unsupported("window: named reference with an inline spec")
132
+ if win.args.get("first") is not None:
133
+ raise Unsupported("window: FIRST/LAST positional flag")
134
+
135
+
136
+ def _partition_text(win: exp.Window, dialect: str) -> str | None:
137
+ cols = win.args.get("partition_by")
138
+ if not cols:
139
+ return None
140
+ return "PARTITION BY " + ", ".join(render_expr(c, dialect) for c in cols)
141
+
142
+
143
+ def _order_text(win: exp.Window, dialect: str) -> str | None:
144
+ order = win.args.get("order")
145
+ if order is None:
146
+ return None
147
+ if order.args.get("this") is not None or order.args.get("siblings"):
148
+ raise Unsupported("window ORDER BY: exotic form")
149
+ return "ORDER BY " + ", ".join(render_expr(e, dialect) for e in order.expressions)
150
+
151
+
152
+ def _frame_text(win: exp.Window, dialect: str) -> str | None:
153
+ spec = win.args.get("spec")
154
+ if spec is None:
155
+ return None
156
+ spec = spec.copy()
157
+ for key in ("kind", "start_side", "end_side"):
158
+ val = spec.args.get(key)
159
+ if isinstance(val, str):
160
+ spec.set(key, val.upper())
161
+ return render_expr(spec, dialect)
162
+
163
+
164
+ def _break_rows(subclauses: list[str], content_col: int, limit: int) -> list[str]:
165
+ """Peel sub-clauses off the END of the fixed [PARTITION BY, ORDER BY,
166
+ frame] priority order, one at a time, until the first (leftmost)
167
+ combined row fits: the frame clause always peels before ORDER BY, per
168
+ spec. Each resulting row is then individually checked for its own
169
+ comma-stacking need (`_stack_subclause`): a no-op for any row that
170
+ already fits, which every row with `k > 1` sub-clauses combined does by
171
+ construction (the peel loop only stops once the combination fits).
172
+ """
173
+ k = len(subclauses)
174
+ while k > 1:
175
+ head = " ".join(subclauses[:k])
176
+ if content_col + len(head) <= limit:
177
+ break
178
+ k -= 1
179
+ grouped = [" ".join(subclauses[:k]), *subclauses[k:]]
180
+ rows = []
181
+ for g in grouped:
182
+ rows.extend(_stack_subclause(g, content_col, limit))
183
+ return rows
184
+
185
+
186
+ def _stack_subclause(text: str, content_col: int, limit: int) -> list[str]:
187
+ """If a single sub-clause (e.g. `"PARTITION BY a, b, c"`) still exceeds
188
+ the width alone on its own row, stack it like a GROUP BY:
189
+ keyword + first term open the row, later terms one per line with a
190
+ leading comma two columns before the term. Untested by any fixture
191
+ (#9's sub-clauses are all short) -- a defensive extension of the
192
+ ladder's last rung, not a golden-verified shape.
193
+ """
194
+ if content_col + len(text) <= limit:
195
+ return [text]
196
+ keyword, sep, rest = text.partition(" BY ")
197
+ if not sep:
198
+ return [text] # not a "KEYWORD BY a, b, ..." shape -- leave as-is
199
+ keyword += " BY"
200
+ terms = [t.strip() for t in rest.split(",")]
201
+ lead = " " * (len(keyword) - 1)
202
+ # This site builds finished text rather than Segs, so it applies the comma
203
+ # position itself instead of going through commas.py's IR pass.
204
+ if active_style().comma_position == "trailing":
205
+ rows = [f"{keyword} {terms[0]}"] + [f"{lead} {t}" for t in terms[1:]]
206
+ return [r + "," for r in rows[:-1]] + [rows[-1]]
207
+ return [f"{keyword} {terms[0]}"] + [f"{lead}, {t}" for t in terms[1:]]
sqlalign/lint.py ADDED
@@ -0,0 +1,173 @@
1
+ """`--lint`: run sqlfluff over the formatted result, in the same command.
2
+
3
+ Formatting and linting are separate jobs and this does not merge them: it just
4
+ saves running two tools over the same files. What it adds is the guarantee that
5
+ the two are not fighting: the linter never sees the layout sqlalign has just
6
+ produced as a finding, because it runs under the coexistence config
7
+ (`sqlfluffconfig.py`) unless the team has committed one of their own.
8
+
9
+ sqlfluff is an OPTIONAL dependency (`pip install 'sqlalign[lint]'`), imported
10
+ only when this runs. sqlalign's own guarantee does not depend on a linter, and
11
+ neither should its install.
12
+
13
+ Config resolution deliberately prefers the team's file. A committed `.sqlfluff`
14
+ is a decision someone made; silently overriding it with a generated one would be
15
+ the wrong kind of helpful. The generated config is the fallback for when there
16
+ is nothing to respect, and it says so on stderr the first time.
17
+ """
18
+ import json
19
+ import subprocess
20
+ import sys
21
+ import tempfile
22
+ from pathlib import Path
23
+
24
+ from sqlalign import bodylint
25
+ from sqlalign.sqlfluffconfig import TESTED_SQLFLUFF, sqlfluff_config
26
+
27
+ # sqlfluff config sources, in the order it searches them (walking up from the
28
+ # file). If any exists, it is the team's decision and we stay out of the way.
29
+ _CONFIG_NAMES = (".sqlfluff", "pyproject.toml", "setup.cfg", "tox.ini", ".sqlfluffignore")
30
+
31
+
32
+ class LintUnavailable(RuntimeError):
33
+ """sqlfluff is not installed. Actionable rather than a traceback."""
34
+
35
+
36
+ def sqlfluff_version() -> str:
37
+ try:
38
+ import sqlfluff
39
+ except ImportError as e: # pragma: no cover - env-dependent
40
+ raise LintUnavailable(
41
+ "--lint needs sqlfluff, which is an optional dependency. "
42
+ "Install it with: pip install 'sqlalign[lint]'") from e
43
+ return sqlfluff.__version__
44
+
45
+
46
+ def discovered_config(path: Path) -> Path | None:
47
+ """The sqlfluff config that applies to `path`, or None if there is none.
48
+
49
+ Only `.sqlfluff` is treated as decisive on sight; the shared files
50
+ (pyproject.toml, setup.cfg, tox.ini) count only when they actually carry a
51
+ sqlfluff section, since almost every Python project has a pyproject.
52
+ """
53
+ for parent in [path.parent, *path.parent.parents]:
54
+ for name in _CONFIG_NAMES:
55
+ candidate = parent / name
56
+ if not candidate.is_file():
57
+ continue
58
+ if name == ".sqlfluff" or name == ".sqlfluffignore":
59
+ return candidate
60
+ try:
61
+ if "sqlfluff" in candidate.read_text():
62
+ return candidate
63
+ except OSError:
64
+ continue
65
+ return None
66
+
67
+
68
+ def lint(path: Path, text: str, style, dialect: str) -> tuple[int, str, str]:
69
+ """Lint `text` as though it were `path`. Returns (returncode, stdout, stderr).
70
+
71
+ The text is linted rather than the file, so `--check` and `--stdout` lint
72
+ what would be written instead of what is currently on disk. It goes into a
73
+ temporary file beside the original so sqlfluff's own config discovery still
74
+ walks the real directory tree.
75
+ """
76
+ config = discovered_config(path)
77
+ args = ["lint"]
78
+ generated = None
79
+ if config is None:
80
+ # Nothing to respect: fall back to the config that keeps the two tools
81
+ # from contradicting each other.
82
+ generated = tempfile.NamedTemporaryFile( # noqa: SIM115 - closed below
83
+ "w", suffix=".sqlfluff", delete=False)
84
+ generated.write(sqlfluff_config(style, dialect))
85
+ generated.close()
86
+ args += ["--config", generated.name]
87
+
88
+ tmp = None
89
+ try:
90
+ with tempfile.NamedTemporaryFile("w", dir=path.parent, suffix=".sql",
91
+ prefix=f".{path.stem}.sqlalign-", delete=False) as f:
92
+ f.write(text)
93
+ tmp = Path(f.name)
94
+ result = subprocess.run([sys.executable, "-m", "sqlfluff", *args, str(tmp)],
95
+ capture_output=True, text=True)
96
+ code, out, err = result.returncode, result.stdout, result.stderr
97
+
98
+ # sqlfluff cannot see inside a `$$` body: to its parser the whole
99
+ # body is one string literal. sqlalign already locates those statements
100
+ # in order to format them, so it can lint them too: `bodylint.lint_view`
101
+ # is the file with the plpgsql scaffolding blanked and every line and
102
+ # column left where it was, so a finding's position is a position in
103
+ # the real file.
104
+ body = _lint_bodies(text, args, path, dialect)
105
+ if body:
106
+ out += body
107
+ code = code or 1
108
+
109
+ # Report against the real filename, never the scratch one.
110
+ return (code,
111
+ out.replace(str(tmp), str(path)).replace(tmp.name, path.name),
112
+ err.replace(str(tmp), str(path)).replace(tmp.name, path.name))
113
+ finally:
114
+ if tmp is not None:
115
+ tmp.unlink(missing_ok=True)
116
+ if generated is not None:
117
+ Path(generated.name).unlink(missing_ok=True)
118
+
119
+
120
+ def _lint_bodies(text: str, args: list[str], path: Path, dialect: str) -> str:
121
+ """Findings from inside `$$` bodies, rendered in sqlfluff's own line format.
122
+
123
+ Kept separate from the main run rather than merged into it. The two cover
124
+ disjoint regions -- a body's contents are invisible to the ordinary run --
125
+ so nothing is reported twice, and labelling the section says plainly that
126
+ these are findings no linter would have produced on its own.
127
+ """
128
+ if not bodylint.has_bodies(text, dialect):
129
+ return ""
130
+ wanted = bodylint.body_lines(text, dialect)
131
+ if not wanted:
132
+ return ""
133
+
134
+ view = bodylint.lint_view(text, dialect)
135
+ tmp = None
136
+ try:
137
+ with tempfile.NamedTemporaryFile("w", dir=path.parent, suffix=".sql",
138
+ prefix=f".{path.stem}.sqlalign-body-",
139
+ delete=False) as f:
140
+ f.write(view)
141
+ tmp = Path(f.name)
142
+ result = subprocess.run(
143
+ [sys.executable, "-m", "sqlfluff", *args, "--format", "json", str(tmp)],
144
+ capture_output=True, text=True)
145
+ try:
146
+ payload = json.loads(result.stdout or "[]")
147
+ except json.JSONDecodeError: # sqlfluff failed before linting
148
+ return ""
149
+ finally:
150
+ if tmp is not None:
151
+ tmp.unlink(missing_ok=True)
152
+
153
+ found = [v for entry in payload for v in entry.get("violations", [])
154
+ if v.get("start_line_no") in wanted]
155
+ if not found:
156
+ return ""
157
+ found.sort(key=lambda v: (v["start_line_no"], v["start_line_pos"]))
158
+ lines = [f"== [{path}] inside $$ bodies "
159
+ "(sqlfluff cannot reach these on its own)"]
160
+ lines += [f"L: {v['start_line_no']:>3} | P: {v['start_line_pos']:>3} | "
161
+ f"{v['code']} | {v['description']} [{v['name']}]" for v in found]
162
+ return "\n".join(lines) + "\n"
163
+
164
+
165
+ def version_warning() -> str | None:
166
+ """A note when the installed sqlfluff is not the one the mappings were
167
+ checked against: rule names and config keys are versioned surface, and a
168
+ silent mismatch reads as sqlalign generating a broken config."""
169
+ installed = sqlfluff_version()
170
+ if installed != TESTED_SQLFLUFF:
171
+ return (f"sqlfluff {installed} installed, coexistence config was checked "
172
+ f"against {TESTED_SQLFLUFF} — rules may have moved")
173
+ return None