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,530 @@
1
+ """Faithful comment engine.
2
+
3
+ sqlglot's AST is lossy for comments: it discards the `--` vs `/* */` **style**,
4
+ strips the delimiters from the text, and attaches every comment to a node by raw
5
+ source *proximity* rather than authorial position (#12's `/* legacy field … */`
6
+ binds to `signup_date` but authorially leads `ltv`). The safety net cannot catch
7
+ any of this: `ast_equal` excludes comments (formatter.py `_normalize` sets
8
+ `comments=None`) — so a dropped, restyled, or relocated comment is INVISIBLE to
9
+ it and the golden byte-comparison is the only guard. This engine therefore
10
+ reproduces comments faithfully or DECLINES (`Unsupported` → byte-identical
11
+ passthrough); it never emits a best-effort comment.
12
+
13
+ `process(node, source, dialect)` runs once, before layout, as a pre-pass over the
14
+ parsed statement:
15
+
16
+ 1. **Style/text recovery**: `scan_comments` re-scans the RAW statement (a
17
+ comment/string/dollar-quote-aware scanner mirroring splitter.py) for every
18
+ comment token in source order, capturing exact style (`line`|`block`), exact
19
+ inner text, the verbatim rendered form, and source offsets. sqlglot is used
20
+ only as a cross-check (its stored, delimiter-stripped texts must match the
21
+ scanned inner texts as a multiset, else decline).
22
+ 2. **Authorial reattachment** — instead of trusting sqlglot's proximity binding,
23
+ each comment is placed against the SELECT list's own source geometry: the
24
+ top-level (depth-0) commas partition the list into one slot per item, and a
25
+ comment falls in exactly one slot. Within its slot a comment is **leading**
26
+ (only whitespace/other-comments before it) or **trailing** (only
27
+ whitespace/other-comments after it). This makes the `/* legacy … */` case
28
+ fall in `ltv`'s slot (after `signup_date`'s comma, before `round(`), i.e.
29
+ leading `ltv`, with no dependence on sqlglot's wrong binding.
30
+ 3. **Emission map + strip** — each item node is annotated (`meta["sqlalign_lead"]`
31
+ / `meta["sqlalign_trail"]` = the verbatim comment) and ALL `node.comments` are
32
+ stripped, so `render_expr` can never re-emit sqlglot's wrong-styled version.
33
+ select.py's `select_items` reads the meta and emits the comment Segs (leading
34
+ before the expression: measured for the `AS` column; trailing after the alias
35
+ — untagged, one space after content, never in an alignment column).
36
+
37
+ The same treatment now covers `WHERE`/`HAVING`/`QUALIFY`, because they have the
38
+ property that made the select list modellable at all: the source geometry lines
39
+ up with the layout. Depth-0 commas partition the select list into one slot per
40
+ item and the layout puts one ROW per item; depth-0 `AND`/`OR` partition a
41
+ predicate the same way, and `condition_block` puts one row per condition. So a
42
+ comment lands on the row the author wrote it against, and `_slots_from` takes
43
+ the separator as a parameter rather than the two being written twice.
44
+
45
+ `GROUP BY` / `ORDER BY` and `FROM` came next, each needing only its own
46
+ separator: commas for the first pair, and for FROM a comma OR the start of a
47
+ join clause: at `LEFT`, not at `JOIN`, so a comment written before `LEFT JOIN`
48
+ stays with the row above rather than jumping a line. GROUP BY and ORDER BY are
49
+ laid out from rendered TEXT rather than from nodes, so grouporder.py lifts the
50
+ annotations off and hands them to `comma_clause`.
51
+
52
+ What still raises: a comment BURIED inside an expression (it sits between two
53
+ things the layout renders as one segment, so there is no row for it), and a
54
+ POSITIONAL `GROUP BY 1, 2`, whose terms share a single line. As before, every
55
+ position this engine does not model raises `Unsupported`, so the tool only ever
56
+ claims positions it reproduces byte-exact.
57
+
58
+ The emission rule is the same everywhere and worth stating once: a `--` or
59
+ multi-line comment cannot share a row with content that FOLLOWS it, so it takes
60
+ the end of the row above. That is both where the author wrote it and the only
61
+ idempotent placement: on a row of its own it re-parses as trailing the row
62
+ above, and would move on a second run.
63
+ """
64
+ import re
65
+ from collections import Counter
66
+ from dataclasses import dataclass
67
+
68
+ from sqlglot import exp
69
+
70
+ from sqlalign.layout import Unsupported
71
+
72
+ # Dollar-quote tag (mirrors splitter.py): bare `$$` or `$tag$`.
73
+ _DOLLAR = re.compile(r"\$(?:[A-Za-z_][A-Za-z0-9_]*)?\$")
74
+ _IDENT_CHARS = re.compile(r"[A-Za-z0-9_]")
75
+
76
+ # SELECT-list terminators: the first depth-0 occurrence of any of these (as a
77
+ # whole word) ends the select list. Bounds the last item's slot so a comment in
78
+ # a following clause is correctly seen as OUTSIDE the select list.
79
+ _CLAUSE_KEYWORDS = frozenset({
80
+ "from", "where", "group", "having", "order", "limit", "offset", "window",
81
+ "union", "intersect", "except", "fetch", "into", "qualify", "for",
82
+ })
83
+
84
+
85
+ @dataclass(frozen=True)
86
+ class Comment:
87
+ style: str # "line" (`--`) | "block" (`/* */`)
88
+ text: str # inner text, delimiters stripped (matches sqlglot's node.comments)
89
+ verbatim: str # exact source form, e.g. "-- rounded for reporting"
90
+ start: int # source offset of the first delimiter char
91
+ end: int # source offset one past the comment
92
+
93
+
94
+ def scan_comments(text: str) -> list[Comment]:
95
+ """Every comment token in `text`, in source order, with style/text/verbatim.
96
+
97
+ String-, quoted-identifier-, and dollar-quote-aware (a `--`/`/* */` inside a
98
+ literal is not a comment), mirroring splitter.py's scanner so the two never
99
+ disagree about where a comment begins.
100
+ """
101
+ out: list[Comment] = []
102
+ i, n = 0, len(text)
103
+ while i < n:
104
+ ch = text[i]
105
+ if ch == "'": # standard or E-prefixed string
106
+ i = _skip_string(text, i)
107
+ elif ch == '"': # quoted identifier
108
+ i = text.find('"', i + 1) + 1 or n
109
+ elif text.startswith("--", i):
110
+ nl = text.find("\n", i)
111
+ end = n if nl == -1 else nl
112
+ out.append(Comment("line", text[i + 2:end], text[i:end], i, end))
113
+ i = end
114
+ elif text.startswith("/*", i):
115
+ end = _skip_block(text, i)
116
+ out.append(Comment("block", text[i + 2:end - 2], text[i:end], i, end))
117
+ i = end
118
+ elif ch == "$" and (m := _DOLLAR.match(text, i)):
119
+ i = _skip_dollar(text, m)
120
+ else:
121
+ i += 1
122
+ return out
123
+
124
+
125
+ def process(node: exp.Expression, source: str, dialect: str) -> None:
126
+ """Recover, reattach, and strip `source`'s comments (see module docstring).
127
+
128
+ Mutates `node`: annotates each select-list item with its leading/trailing
129
+ verbatim comment via `meta`, then strips every `node.comments`. Raises
130
+ `Unsupported` for any comment position this engine does not model, so the
131
+ caller passes the whole statement through byte-identical.
132
+ """
133
+ attached = [c for n in node.walk() if n.comments for c in n.comments]
134
+ if not attached:
135
+ return
136
+
137
+ scanned = scan_comments(source)
138
+ # Cross-check against sqlglot: the scanned inner texts and the attached texts
139
+ # must be the same multiset. A mismatch means a comment sits somewhere the
140
+ # scan and sqlglot disagree about (or one dropped it): decline rather than
141
+ # risk a wrong reproduction.
142
+ if Counter(c.text for c in scanned) != Counter(attached):
143
+ raise Unsupported("comment recovery mismatch")
144
+
145
+ if not isinstance(node, exp.Select):
146
+ raise Unsupported("comments outside a plain SELECT")
147
+
148
+ groups = _comment_groups(node, source)
149
+
150
+ lead: dict[int, str] = {}
151
+ trail: dict[int, str] = {}
152
+ for c in scanned:
153
+ slots, targets, label = _group_of(c, groups)
154
+ if slots is None:
155
+ raise Unsupported("comment outside a modelled clause")
156
+ idx = _slot_of(c, slots)
157
+ before = _only_trivia(source, slots[idx][0], c.start, scanned)
158
+ after = _only_trivia(source, c.end, slots[idx][1], scanned)
159
+ # A Seg carrying a newline would corrupt align.py's column math, but
160
+ # only where the comment sits inside a row's content. Both placements
161
+ # this engine produces put it at the end of a row, after every segment
162
+ # in an alignment column, so nothing measurable follows the newline.
163
+ key = (label, idx)
164
+ if before:
165
+ if key in lead:
166
+ raise Unsupported("comment: multiple leading comments")
167
+ lead[key] = c.verbatim
168
+ elif after:
169
+ if key in trail:
170
+ raise Unsupported("comment: multiple trailing comments")
171
+ trail[key] = c.verbatim
172
+ else:
173
+ raise Unsupported("comment buried in expression")
174
+
175
+ for _slots, targets, label in groups:
176
+ for i, target in enumerate(targets):
177
+ if (label, i) in lead:
178
+ target.meta["sqlalign_lead"] = lead[(label, i)]
179
+ if (label, i) in trail:
180
+ target.meta["sqlalign_trail"] = trail[(label, i)]
181
+ for n in node.walk():
182
+ n.comments = None
183
+
184
+
185
+ # The clauses whose rows a comment can be attached to. The select list splits on
186
+ # commas and the predicate clauses on their AND/OR boundaries: in both cases
187
+ # exactly the boundaries the layout puts one ROW per, which is what makes a
188
+ # comment reproducible: it lands on the row the author wrote it against.
189
+ _PREDICATE_CLAUSES = ("where", "having", "qualify")
190
+
191
+
192
+ def _comment_groups(node, source):
193
+ """`[(slots, target_nodes, label)]` for every clause a comment may sit in.
194
+
195
+ A group is only offered when its slot count matches its node count. Where it
196
+ does not, the source geometry and the parsed shape disagree and there is no
197
+ safe mapping: the group is dropped, and a comment inside it then finds no
198
+ home and declines, which is the whole contract of this module.
199
+ """
200
+ from sqlalign.layout.conditions import split_conjunction
201
+
202
+ groups = []
203
+ slots = _select_list_slots(source)
204
+ if len(slots) == len(node.expressions):
205
+ groups.append((slots, list(node.expressions), "select"))
206
+
207
+ for keyword in _PREDICATE_CLAUSES:
208
+ clause = node.args.get(keyword)
209
+ if clause is None:
210
+ continue
211
+ conditions, _joiner = split_conjunction(clause.this)
212
+ slots = _where_slots(source, keyword)
213
+ if len(slots) == len(conditions):
214
+ groups.append((slots, conditions, keyword))
215
+
216
+ # GROUP BY / ORDER BY are comma lists like the select list. Their terms are
217
+ # laid out from rendered TEXT rather than from nodes, so grouporder.py lifts
218
+ # the annotations off and hands them to `comma_clause`: the nodes are
219
+ # still where they are carried.
220
+ for keyword, arg, terms in (
221
+ ("group by", "group", _group_terms(node)),
222
+ ("order by", "order", _order_terms(node))):
223
+ if not terms:
224
+ continue
225
+ slots = _comma_clause_slots(source, keyword)
226
+ if len(slots) == len(terms):
227
+ groups.append((slots, terms, arg))
228
+
229
+ # FROM is one row per table reference, split on commas and on the START of a
230
+ # join clause: at `LEFT`, not at `JOIN`, so a comment written before
231
+ # `LEFT JOIN` stays with the row above it rather than jumping a line.
232
+ refs = _from_refs(node)
233
+ if refs:
234
+ slots = _from_slots(source)
235
+ if len(slots) == len(refs):
236
+ groups.append((slots, refs, "from"))
237
+ return groups
238
+
239
+
240
+ def _from_refs(node):
241
+ """The FROM clause's table references, in the order they are laid out."""
242
+ frm = node.args.get("from_")
243
+ if frm is None:
244
+ return []
245
+ return [frm.this, *(j.this for j in node.args.get("joins") or [])]
246
+
247
+
248
+ def _from_slots(source: str) -> list[tuple[int, int]]:
249
+ i = _skip_ws_comments(source, 0)
250
+ n = len(source)
251
+ while i < n:
252
+ if (_IDENT_CHARS.match(source[i]) and _word_at(source, i, "from")
253
+ and (i == 0 or not _IDENT_CHARS.match(source[i - 1]))):
254
+ return _slots_from(source, i + len("from"), _join_split)
255
+ i = _advance(source, i)
256
+ return []
257
+
258
+
259
+ def _group_terms(node):
260
+ """A GROUP BY's terms in the order grouporder.py renders them: the plain
261
+ expressions, then GROUPING SETS / CUBE / ROLLUP."""
262
+ group = node.args.get("group")
263
+ if group is None or group.args.get("all"):
264
+ return []
265
+ terms = list(group.expressions)
266
+ for key in ("grouping_sets", "cube", "rollup"):
267
+ terms += list(group.args.get(key) or [])
268
+ return terms
269
+
270
+
271
+ def _order_terms(node):
272
+ order = node.args.get("order")
273
+ return list(order.expressions) if order is not None else []
274
+
275
+
276
+ def _comma_clause_slots(source: str, keyword: str) -> list[tuple[int, int]]:
277
+ """Slots for a two-word clause keyword (`GROUP BY` / `ORDER BY`), split on
278
+ depth-0 commas."""
279
+ head, tail = keyword.split()
280
+ i = _skip_ws_comments(source, 0)
281
+ n = len(source)
282
+ while i < n:
283
+ if (_IDENT_CHARS.match(source[i]) and _word_at(source, i, head)
284
+ and (i == 0 or not _IDENT_CHARS.match(source[i - 1]))):
285
+ j = _skip_ws_comments(source, i + len(head))
286
+ if _word_at(source, j, tail):
287
+ return _slots_from(source, j + len(tail), _comma_split)
288
+ i = _advance(source, i)
289
+ return []
290
+
291
+
292
+ def _group_of(c: Comment, groups):
293
+ """The group whose slots contain `c`, or `(None, None, None)`."""
294
+ for slots, targets, label in groups:
295
+ if _slot_of(c, slots) is not None:
296
+ return slots, targets, label
297
+ return None, None, None
298
+
299
+
300
+ def _select_list_slots(source: str) -> list[tuple[int, int]]:
301
+ """Partition the SELECT list into (start, end) source ranges, one per item.
302
+
303
+ Scans past the leading `SELECT` keyword, then walks to the first depth-0
304
+ clause keyword (or `;`/end), splitting on depth-0 commas. String/quoted-id/
305
+ comment/dollar-quote-aware so a comma inside a literal or nested call is not
306
+ a boundary.
307
+ """
308
+ i = _skip_ws_comments(source, 0)
309
+ if not _word_at(source, i, "select"):
310
+ return []
311
+ return _slots_from(source, i + len("select"), _comma_split)
312
+
313
+
314
+ def _where_slots(source: str, keyword: str) -> list[tuple[int, int]]:
315
+ """The same partition for a `WHERE`/`HAVING`/`QUALIFY` clause, split on its
316
+ depth-0 `AND`/`OR` boundaries instead of on commas.
317
+
318
+ Those are exactly the boundaries `condition_block` lays out one row per, so
319
+ a comment lands on the row the author wrote it against: the whole reason
320
+ the select list could be modelled at all.
321
+ """
322
+ i = _skip_ws_comments(source, 0)
323
+ n = len(source)
324
+ while i < n:
325
+ if _IDENT_CHARS.match(source[i]) and _word_at(source, i, keyword) and (
326
+ i == 0 or not _IDENT_CHARS.match(source[i - 1])):
327
+ return _slots_from(source, i + len(keyword), _boolean_split)
328
+ i = _advance(source, i)
329
+ return []
330
+
331
+
332
+ # The words that may precede JOIN in a join clause. A comment written before
333
+ # `LEFT JOIN` belongs to the row ABOVE it, so the slot must break at `LEFT`,
334
+ # not at `JOIN`: otherwise the modifiers land in the previous slot and the
335
+ # comment lands on the wrong row.
336
+ _JOIN_MODIFIERS = frozenset({"natural", "cross", "inner", "outer",
337
+ "left", "right", "full", "lateral", "positional"})
338
+
339
+
340
+ def _join_split(source: str, i: int, depth: int) -> int:
341
+ """The width of a FROM-list separator at `i`: a comma, or the start of a
342
+ join clause (its first modifier word, or `JOIN` itself)."""
343
+ if depth:
344
+ return 0
345
+ if source[i] == ",":
346
+ return 1
347
+ if not _IDENT_CHARS.match(source[i]) or (i and _IDENT_CHARS.match(source[i - 1])):
348
+ return 0
349
+ j, words = i, 0
350
+ while j < len(source):
351
+ k = j
352
+ while k < len(source) and _IDENT_CHARS.match(source[k]):
353
+ k += 1
354
+ word = source[j:k].lower()
355
+ if word == "join":
356
+ return k - i # consume through JOIN itself
357
+ if word not in _JOIN_MODIFIERS or words > 3:
358
+ return 0
359
+ words += 1
360
+ j = _skip_ws_comments(source, k)
361
+ if j == k: # no separator after the word
362
+ return 0
363
+ return 0
364
+
365
+
366
+ def _comma_split(source: str, i: int, depth: int) -> int:
367
+ """Length of the separator at `i`, or 0. Commas separate select items."""
368
+ return 1 if depth == 0 and source[i] == "," else 0
369
+
370
+
371
+ def _boolean_split(source: str, i: int, depth: int) -> int:
372
+ """`AND` / `OR` at depth 0, as whole words."""
373
+ if depth or not _IDENT_CHARS.match(source[i]):
374
+ return 0
375
+ if i and _IDENT_CHARS.match(source[i - 1]):
376
+ return 0
377
+ for word in ("and", "or"):
378
+ if _word_at(source, i, word):
379
+ return len(word)
380
+ return 0
381
+
382
+
383
+ def _advance(source: str, i: int) -> int:
384
+ """Step past whatever token starts at `i`, skipping over strings, quoted
385
+ identifiers, comments and dollar-quoted bodies as single units."""
386
+ ch = source[i]
387
+ if ch == "'":
388
+ return _skip_string(source, i)
389
+ if ch == '"':
390
+ return source.find('"', i + 1) + 1 or len(source)
391
+ if source.startswith("--", i):
392
+ nl = source.find("\n", i)
393
+ return len(source) if nl == -1 else nl
394
+ if source.startswith("/*", i):
395
+ return _skip_block(source, i)
396
+ if ch == "$" and (m := _DOLLAR.match(source, i)):
397
+ return _skip_dollar(source, m)
398
+ return i + 1
399
+
400
+
401
+ def _slots_from(source, list_start, separator):
402
+ """Split `source[list_start:]` on `separator` until the first depth-0 clause
403
+ keyword (or `;`/end), returning one (start, end) range per slot."""
404
+ n = len(source)
405
+ i = list_start
406
+ depth = 0
407
+ cuts: list[tuple[int, int]] = [] # (separator start, separator end)
408
+ list_end = n
409
+ while i < n:
410
+ ch = source[i]
411
+ if ch == "(":
412
+ depth += 1
413
+ i += 1
414
+ continue
415
+ if ch == ")":
416
+ depth -= 1
417
+ i += 1
418
+ continue
419
+ if depth == 0 and (ch == ";" or (_IDENT_CHARS.match(ch)
420
+ and _clause_word_at(source, i))):
421
+ list_end = i
422
+ break
423
+ width = separator(source, i, depth)
424
+ if width:
425
+ cuts.append((i, i + width))
426
+ i += width
427
+ continue
428
+ nxt = _advance(source, i)
429
+ i = nxt if nxt > i else i + 1
430
+
431
+ bounds = [list_start, *(end for _, end in cuts)]
432
+ ends = [*(start for start, _ in cuts), list_end]
433
+ return list(zip(bounds, ends, strict=False))
434
+
435
+
436
+ def _clause_word_at(source: str, i: int) -> bool:
437
+ """True iff a `_CLAUSE_KEYWORDS` word begins at `i` (whole-word, and `i` is
438
+ itself a word start: the caller only reaches here at a fresh identifier
439
+ char, but guard the left boundary too)."""
440
+ if i > 0 and _IDENT_CHARS.match(source[i - 1]):
441
+ return False
442
+ j = i
443
+ while j < len(source) and _IDENT_CHARS.match(source[j]):
444
+ j += 1
445
+ return source[i:j].lower() in _CLAUSE_KEYWORDS
446
+
447
+
448
+ def _word_at(source: str, i: int, word: str) -> bool:
449
+ seg = source[i:i + len(word)]
450
+ if seg.lower() != word:
451
+ return False
452
+ after = i + len(word)
453
+ return after >= len(source) or not _IDENT_CHARS.match(source[after])
454
+
455
+
456
+ def _slot_of(c: Comment, slots: list[tuple[int, int]]) -> int | None:
457
+ for idx, (s, e) in enumerate(slots):
458
+ if s <= c.start < e:
459
+ return idx
460
+ return None
461
+
462
+
463
+ def _only_trivia(source: str, lo: int, hi: int, comments: list[Comment]) -> bool:
464
+ """True iff `source[lo:hi]` is only whitespace and (other) comment spans."""
465
+ i = lo
466
+ while i < hi:
467
+ inside = next((c for c in comments if c.start <= i < c.end), None)
468
+ if inside is not None:
469
+ i = inside.end
470
+ continue
471
+ if not source[i].isspace():
472
+ return False
473
+ i += 1
474
+ return True
475
+
476
+
477
+ def _skip_ws_comments(source: str, i: int) -> int:
478
+ n = len(source)
479
+ while i < n:
480
+ if source[i] in " \t\r\n":
481
+ i += 1
482
+ elif source.startswith("--", i):
483
+ nl = source.find("\n", i)
484
+ i = n if nl == -1 else nl + 1
485
+ elif source.startswith("/*", i):
486
+ i = _skip_block(source, i)
487
+ else:
488
+ break
489
+ return i
490
+
491
+
492
+ def _skip_string(source: str, i: int) -> int:
493
+ """Offset one past the string literal opening at `i`.
494
+
495
+ Handles both `''` escaping and, for an E-prefixed string, backslash escapes.
496
+ """
497
+ n = len(source)
498
+ prev = source[i - 1] if i > 0 else ""
499
+ prev2 = source[i - 2] if i > 1 else ""
500
+ is_estring = prev in "eE" and not _IDENT_CHARS.match(prev2)
501
+ i += 1
502
+ while i < n:
503
+ if is_estring and source[i] == "\\" and i + 1 < n:
504
+ i += 2
505
+ continue
506
+ if source[i] == "'" and not (i + 1 < n and source[i + 1] == "'"):
507
+ break
508
+ i += 2 if source[i] == "'" else 1
509
+ return i + 1
510
+
511
+
512
+ def _skip_block(source: str, i: int) -> int:
513
+ """Offset one past the `*/` closing the block comment at `i` (nesting-aware)."""
514
+ n = len(source)
515
+ depth, i = 1, i + 2
516
+ while i < n and depth:
517
+ if source.startswith("/*", i):
518
+ depth, i = depth + 1, i + 2
519
+ elif source.startswith("*/", i):
520
+ depth, i = depth - 1, i + 2
521
+ else:
522
+ i += 1
523
+ return i
524
+
525
+
526
+ def _skip_dollar(source: str, m: re.Match) -> int:
527
+ """Offset one past the dollar-quoted body opened by the `$tag$` match `m`."""
528
+ tag = m.group(0)
529
+ end = source.find(tag, m.end())
530
+ return len(source) if end == -1 else end + len(tag)