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/plpgsql.py ADDED
@@ -0,0 +1,437 @@
1
+ """Dollar-quoted plpgsql function/procedure bodies.
2
+
3
+ sqlglot parses a `CREATE FUNCTION … AS $$ … $$` as an `exp.Create` whose
4
+ `expression` is one opaque `exp.Heredoc` string: it does not look inside the
5
+ body. This module formats that body: the `CREATE` header is rebuilt from the
6
+ AST (signature, `RETURNS`, `LANGUAGE`), while the body between the `$$` tags is
7
+ split into plpgsql statements and laid out per §3.5: `DECLARE`/`BEGIN`/`END`
8
+ skeleton, `IF … THEN … [ELSE …] END IF` geometry, embedded SQL statements
9
+ routed back through the main engine, and `RAISE`/`GET DIAGNOSTICS`/`:=`/`RETURN`
10
+ as plain keyword-cased statements. Anything unmodeled raises `Unsupported`, so
11
+ the whole statement degrades to a byte-identical passthrough.
12
+
13
+ To avoid an import cycle, this module never imports `formatter` at module
14
+ scope: the safety helpers (`split_body`, `body_clauses`, `norm_skeleton`,
15
+ `strip_struct`) are pure text functions `formatter.ast_equal` calls, and the
16
+ one place that needs the main engine (`_render_sql_stmt`) imports it lazily.
17
+ """
18
+ import re
19
+ from functools import cache
20
+
21
+ import sqlglot
22
+ from sqlglot import exp
23
+
24
+ from sqlalign.casing import render_expr
25
+ from sqlalign.layout import Unsupported
26
+ from sqlalign.splitter import DOLLAR_TAG, split_statements
27
+
28
+ # `DOLLAR_TAG` is imported, not re-declared: this module and the splitter cut the
29
+ # same bodies, so a drift between two copies of the tag pattern would split a
30
+ # body at a point the other side does not treat as opaque.
31
+
32
+ # Body statements that route through the main SQL engine; everything else in a
33
+ # plpgsql body is a "plain" statement rendered by keyword-casing.
34
+ _SQL_STMT_TYPES = (exp.Select, exp.Insert, exp.Update, exp.Delete, exp.Merge, exp.SetOperation)
35
+
36
+ # plpgsql keywords sqlglot's tokenizer does not list as single-word keywords
37
+ # (verified against pinned v30.14); union'd with the tokenizer set for casing.
38
+ _PLPGSQL_KW = {"RETURN", "RAISE", "NOTICE", "WARNING", "EXCEPTION", "INFO", "LOG",
39
+ "DEBUG", "GET", "DIAGNOSTICS", "PERFORM", "ASSERT"}
40
+
41
+ # Create args this module models; any other truthy arg declines to passthrough.
42
+ _CREATE_FN_OK = {"this", "kind", "replace", "expression", "properties"}
43
+
44
+
45
+ # ---- dollar-quote scanning (pure text; used by layout AND the safety net) ----
46
+
47
+ def split_body(stmt: str):
48
+ """Split `stmt` at its dollar-quoted body into `(header, body, tail)`.
49
+
50
+ `header` runs through the opening `$tag$`, `body` is the text between the
51
+ tags, `tail` is the closing `$tag$` onward. Lossless: the three concatenate
52
+ back to `stmt`. Returns `None` when there is no dollar-quoted region.
53
+ """
54
+ m = DOLLAR_TAG.search(stmt)
55
+ if not m:
56
+ return None
57
+ tag = m.group(0)
58
+ close = stmt.find(tag, m.end())
59
+ if close == -1:
60
+ return None
61
+ return stmt[:m.end()], stmt[m.end():close], stmt[close:]
62
+
63
+
64
+ # The two body languages whose contents sqlalign lays out. `plpgsql` is a
65
+ # DECLARE/BEGIN/END block; `sql` is a bare statement list with no block at all,
66
+ # which is why it needs its own branch rather than a wider guard. Everything
67
+ # else (plpython, plperl, ...) is not SQL and is declined at the header.
68
+ _BODY_LANGUAGES = ("plpgsql", "sql")
69
+
70
+
71
+ def _language_name(node) -> str:
72
+ props = node.args.get("properties")
73
+ for p in (props.expressions if props else []):
74
+ if isinstance(p, exp.LanguageProperty):
75
+ return p.this.name if hasattr(p.this, "name") else str(p.this)
76
+ return ""
77
+
78
+
79
+ def body_language(node) -> str | None:
80
+ """`"plpgsql"` / `"sql"` for a body this module lays out, else None."""
81
+ lang = _language_name(node).lower()
82
+ return lang if lang in _BODY_LANGUAGES else None
83
+
84
+
85
+ def is_dollar_create(node, dialect: str) -> bool:
86
+ """Whether `node` is a `CREATE FUNCTION/PROCEDURE` with a dollar-quoted body."""
87
+ return (isinstance(node, exp.Create)
88
+ and (node.args.get("kind") or "").upper() in ("FUNCTION", "PROCEDURE")
89
+ and isinstance(node.args.get("expression"), exp.Heredoc))
90
+
91
+
92
+ def body_clauses(body: str) -> list[str]:
93
+ """Split a plpgsql body into `;`-terminated clauses (string/comment/dollar
94
+ aware, via the shared splitter), stripped and with the `;` removed; empty
95
+ clauses dropped. `BEGIN`/`IF … THEN` keywords stay glued to the statement
96
+ that follows them, so the input body and the formatted body split into the
97
+ same clause sequence — which the safety net relies on."""
98
+ out = []
99
+ for part in split_statements(body):
100
+ c = part.strip()
101
+ if c.endswith(";"):
102
+ c = c[:-1].strip()
103
+ if c:
104
+ out.append(c)
105
+ return out
106
+
107
+
108
+ # ---- safety-net text normalization ----
109
+
110
+ def norm_skeleton(text: str) -> str:
111
+ """Casefold and collapse whitespace, both only OUTSIDE quoted regions, so
112
+ string-literal interiors stay byte-exact. Two clauses equal under this norm
113
+ differ by at most keyword casing and whitespace: a semantically inert
114
+ difference the formatter is allowed to make to a skeleton statement."""
115
+ out, i, n, prev_space = [], 0, len(text), False
116
+ while i < n:
117
+ ch = text[i]
118
+ if ch in ("'", '"'):
119
+ prev_space = False
120
+ out.append(ch)
121
+ i += 1
122
+ while i < n:
123
+ out.append(text[i])
124
+ if text[i] == ch:
125
+ if i + 1 < n and text[i + 1] == ch: # doubled quote: escaped
126
+ out.append(text[i + 1])
127
+ i += 2
128
+ continue
129
+ i += 1
130
+ break
131
+ i += 1
132
+ elif ch.isspace():
133
+ if not prev_space:
134
+ out.append(" ")
135
+ prev_space = True
136
+ i += 1
137
+ else:
138
+ out.append(ch.casefold())
139
+ prev_space = False
140
+ i += 1
141
+ return "".join(out).strip()
142
+
143
+
144
+ _STRUCT_LEAD = re.compile(r"^(?:declare|begin)\b\s*", re.IGNORECASE)
145
+
146
+
147
+ def strip_struct(text: str) -> str:
148
+ """Drop a leading `DECLARE`/`BEGIN` keyword (the only skeleton words that
149
+ glue to a following statement) so the remainder can be AST-compared."""
150
+ return _STRUCT_LEAD.sub("", text, count=1)
151
+
152
+
153
+ # ---- keyword casing for plain statements ----
154
+
155
+ @cache
156
+ def _keywords(dialect: str) -> frozenset[str]:
157
+ """Every single-word keyword of `dialect`. Cached: building it instantiates
158
+ a Tokenizer, and every plain body statement asks for it."""
159
+ from sqlglot.tokens import Tokenizer
160
+ return frozenset(k for k in Tokenizer(dialect=dialect).KEYWORDS if " " not in k) | _PLPGSQL_KW
161
+
162
+
163
+ def _tokenize_ws(text: str) -> list[str]:
164
+ """Whitespace-split `text`, treating a quoted span as opaque (never split
165
+ inside it), so string literals survive keyword casing intact."""
166
+ tokens, cur, i, n = [], [], 0, len(text)
167
+ while i < n:
168
+ ch = text[i]
169
+ if ch.isspace():
170
+ if cur:
171
+ tokens.append("".join(cur))
172
+ cur = []
173
+ i += 1
174
+ elif ch in ("'", '"'):
175
+ cur.append(ch)
176
+ i += 1
177
+ while i < n:
178
+ cur.append(text[i])
179
+ if text[i] == ch:
180
+ if i + 1 < n and text[i + 1] == ch:
181
+ cur.append(text[i + 1])
182
+ i += 2
183
+ continue
184
+ i += 1
185
+ break
186
+ i += 1
187
+ else:
188
+ cur.append(ch)
189
+ i += 1
190
+ if cur:
191
+ tokens.append("".join(cur))
192
+ return tokens
193
+
194
+
195
+ def _upper_kw(text: str, dialect: str) -> str:
196
+ """Uppercase keyword tokens (identifiers and string literals preserved),
197
+ normalizing runs of whitespace to single spaces."""
198
+ kw = _keywords(dialect)
199
+ return " ".join(t.upper() if t.upper() in kw else t for t in _tokenize_ws(text))
200
+
201
+
202
+ def _render_plain(text: str, dialect: str) -> str:
203
+ text = text.strip()
204
+ if text.lower().startswith("get diagnostics"):
205
+ return _render_get_diagnostics(text)
206
+ return _upper_kw(text, dialect)
207
+
208
+
209
+ def _render_get_diagnostics(text: str) -> str:
210
+ """`get diagnostics <var> = <item>` → `GET DIAGNOSTICS <var> = <ITEM>`: the
211
+ assignment target is a variable (preserved) but the right side is a
212
+ diagnostic keyword (uppercased). The two can be the same word (`row_count`
213
+ vs `ROW_COUNT`), so this cannot go through generic keyword casing."""
214
+ body = text[len("get diagnostics"):].strip()
215
+ if body.count("=") != 1:
216
+ raise Unsupported("plpgsql GET DIAGNOSTICS: unexpected form")
217
+ lhs, rhs = body.split("=")
218
+ return "GET DIAGNOSTICS " + lhs.strip() + " = " + rhs.strip().upper()
219
+
220
+
221
+ # ---- CREATE header (rebuilt from the AST) ----
222
+
223
+ def _guard_create(node) -> None:
224
+ for name, value in node.args.items():
225
+ if value in (None, [], False):
226
+ continue
227
+ if name not in _CREATE_FN_OK:
228
+ raise Unsupported(f"plpgsql CREATE arg: {name}")
229
+ if not isinstance(node.this, exp.UserDefinedFunction):
230
+ raise Unsupported("plpgsql: non-UDF signature")
231
+
232
+
233
+ def _header_lines(node, dialect: str, tag: str) -> list[str]:
234
+ _guard_create(node)
235
+ kind = node.args["kind"].upper() # FUNCTION | PROCEDURE
236
+ head = "CREATE"
237
+ if node.args.get("replace"):
238
+ head += " OR REPLACE"
239
+ head += f" {kind} " + render_expr(node.this, dialect)
240
+ lines = [head]
241
+ props = node.args.get("properties")
242
+ returns = language = None
243
+ for p in (props.expressions if props else []):
244
+ if isinstance(p, exp.ReturnsProperty):
245
+ returns = p
246
+ elif isinstance(p, exp.LanguageProperty):
247
+ language = p
248
+ else:
249
+ raise Unsupported(f"plpgsql: property {type(p).__name__}")
250
+ if returns is not None:
251
+ lines.append("RETURNS " + render_expr(returns.this, dialect))
252
+ if language is None:
253
+ raise Unsupported("plpgsql: missing LANGUAGE")
254
+ lang = body_language(node)
255
+ if lang is None:
256
+ raise Unsupported(f"plpgsql: language {_language_name(node)!r}")
257
+ lines.append(f"LANGUAGE {lang}") # canonical bare form
258
+ lines.append("AS " + tag)
259
+ return lines
260
+
261
+
262
+ # ---- body layout ----
263
+
264
+ def _first_word(clause: str) -> str:
265
+ """The clause's leading keyword, lowercased (`""` for a blank clause)."""
266
+ words = clause.split(None, 1)
267
+ return words[0].lower() if words else ""
268
+
269
+
270
+ def _norm(clause: str) -> str:
271
+ """Lowercased with whitespace runs collapsed, for comparing a whole clause
272
+ against a fixed skeleton word (`end`, `end if`)."""
273
+ return " ".join(clause.lower().split())
274
+
275
+
276
+ def _render_sql_stmt(raw: str, dialect: str, style) -> str:
277
+ """Route an embedded SQL statement through the main engine (identical
278
+ formatting to top level). A construct the engine declines passes through
279
+ verbatim per §6 — the whole body's safety check still validates it."""
280
+ from sqlalign.formatter import _format_statement # lazy: breaks import cycle
281
+ try:
282
+ return _format_statement(raw + ";", dialect, style)
283
+ except Unsupported:
284
+ return raw.strip() + ";"
285
+
286
+
287
+ def _is_sql(raw: str, dialect: str) -> bool:
288
+ try:
289
+ node = sqlglot.parse_one(raw, read=dialect)
290
+ except (sqlglot.errors.ParseError, sqlglot.errors.TokenError):
291
+ return False
292
+ return isinstance(node, _SQL_STMT_TYPES)
293
+
294
+
295
+ def _render_stmt(raw: str, dialect: str, style) -> str:
296
+ # A non-SQL statement is keyword-cased as a plain statement. An unmodeled
297
+ # control construct (e.g. `FOR … LOOP`) is plain-rendered here but declined
298
+ # downstream: its `END LOOP`/etc. fails the bare-END / END-IF structural
299
+ # guards, so the whole body degrades to passthrough (and the safety net is
300
+ # the final backstop). No fixture exercises those constructs.
301
+ if _is_sql(raw, dialect):
302
+ return _render_sql_stmt(raw, dialect, style)
303
+ return _render_plain(raw, dialect) + ";"
304
+
305
+
306
+ def _render_branch(raw: str, dialect: str) -> str:
307
+ """A THEN/ELSE branch body: a single plain statement on the same line as
308
+ the keyword. A SQL statement there (multi-line geometry) is declined."""
309
+ if _is_sql(raw, dialect):
310
+ raise Unsupported("plpgsql IF branch: SQL statement")
311
+ return _render_plain(raw, dialect) + ";"
312
+
313
+
314
+ def _render_declare(decls: list[str], dialect: str) -> str:
315
+ # v1 models a single declaration (both fixtures). Multi-declaration column
316
+ # alignment is unexercised, so it declines rather than guess.
317
+ if len(decls) != 1:
318
+ raise Unsupported("plpgsql: multiple DECLARE entries")
319
+ parts = decls[0].split(None, 1)
320
+ if len(parts) != 2:
321
+ raise Unsupported("plpgsql DECLARE: unrecognized declaration")
322
+ name, rest = parts
323
+ return f"DECLARE {name} {_upper_kw(rest, dialect)};"
324
+
325
+
326
+ def _consume_if(stmts: list[str], j: int, dialect: str):
327
+ """Parse an `IF … THEN … [ELSE …] END IF` starting at `stmts[j]`; return
328
+ the rendered block and the index just past `END IF`.
329
+
330
+ Takes no `style`: every branch body here is a plain (non-SQL) statement --
331
+ a SQL statement inside a branch is declined by `_render_branch`: so
332
+ nothing in a rendered IF block goes back through the layout engine.
333
+ """
334
+ head = stmts[j]
335
+ mt = re.search(r"\bthen\b", head, re.IGNORECASE)
336
+ if not mt:
337
+ raise Unsupported("plpgsql IF: no THEN")
338
+ cond = head[len("if"):mt.start()].strip()
339
+ first = head[mt.end():].strip()
340
+ then_stmts = [first] if first else []
341
+ j += 1
342
+ m = len(stmts)
343
+ while j < m and _first_word(stmts[j]) not in ("else", "elsif", "end"):
344
+ then_stmts.append(stmts[j])
345
+ j += 1
346
+ else_stmts = []
347
+ if j < m and _first_word(stmts[j]) == "else":
348
+ rest = stmts[j][len("else"):].strip()
349
+ if rest:
350
+ else_stmts.append(rest)
351
+ j += 1
352
+ while j < m and _first_word(stmts[j]) not in ("elsif", "end"):
353
+ else_stmts.append(stmts[j])
354
+ j += 1
355
+ if j < m and _first_word(stmts[j]) == "elsif":
356
+ raise Unsupported("plpgsql ELSIF")
357
+ if j >= m or _norm(stmts[j]) != "end if":
358
+ raise Unsupported("plpgsql IF: no END IF")
359
+ j += 1
360
+ if len(then_stmts) != 1 or len(else_stmts) > 1:
361
+ raise Unsupported("plpgsql IF: multi-statement branch")
362
+ for s in then_stmts + else_stmts:
363
+ if _first_word(s) in ("if", "begin", "declare"):
364
+ raise Unsupported("plpgsql: nested block in IF")
365
+ lines = ["IF " + _render_plain(cond, dialect),
366
+ " THEN " + _render_branch(then_stmts[0], dialect)]
367
+ if else_stmts:
368
+ lines.append(" ELSE " + _render_branch(else_stmts[0], dialect))
369
+ lines.append("END IF;")
370
+ return "\n".join(lines), j
371
+
372
+
373
+ def _parse_body_elements(body: str, dialect: str, style, language="plpgsql") -> list[str]:
374
+ cls = body_clauses(body)
375
+ if language == "sql":
376
+ # A `LANGUAGE sql` body is a statement list and nothing else: no
377
+ # DECLARE, no BEGIN, no END. Each statement goes through the same
378
+ # renderer a plpgsql body's statements do, so the two cannot drift.
379
+ return [_render_stmt(c, dialect, style) for c in cls]
380
+ elements: list[str] = []
381
+ i, n = 0, len(cls)
382
+ if i < n and _first_word(cls[i]) == "declare":
383
+ decls = [cls[i][len("declare"):].strip()]
384
+ i += 1
385
+ while i < n and _first_word(cls[i]) != "begin":
386
+ decls.append(cls[i].strip())
387
+ i += 1
388
+ elements.append(_render_declare(decls, dialect))
389
+ if i >= n or _first_word(cls[i]) != "begin":
390
+ raise Unsupported("plpgsql: expected BEGIN")
391
+ elements.append("BEGIN")
392
+ begin_rest = cls[i][len("begin"):].strip()
393
+ i += 1
394
+ stmts = ([begin_rest] if begin_rest else []) + cls[i:]
395
+ j, m = 0, len(stmts)
396
+ while j < m and _first_word(stmts[j]) != "end":
397
+ if _first_word(stmts[j]) == "if":
398
+ block, j = _consume_if(stmts, j, dialect)
399
+ elements.append(block)
400
+ else:
401
+ elements.append(_render_stmt(stmts[j], dialect, style))
402
+ j += 1
403
+ if j >= m or _norm(stmts[j]) != "end": # bare END only (no label/args)
404
+ raise Unsupported("plpgsql: expected END")
405
+ if j != m - 1:
406
+ raise Unsupported("plpgsql: statements after END")
407
+ elements.append("END;")
408
+ return elements
409
+
410
+
411
+ def layout_body(body: str, dialect: str, style, language="plpgsql") -> str:
412
+ """Format a plpgsql body: elements at column 1, `body_blank_lines` between.
413
+
414
+ The body has its own vertical rhythm, separate from the one BETWEEN
415
+ statements: `blank_lines_between_statements` never reached in here, so this
416
+ was a hardcoded single blank line whatever that was set to.
417
+ """
418
+ separator = "\n" + "\n" * max(style.body_blank_lines, 0) if style else "\n\n"
419
+ return separator.join(_parse_body_elements(body, dialect, style, language))
420
+
421
+
422
+ def format_create(stmt: str, node, dialect: str, style) -> str:
423
+ """Format a whole `CREATE FUNCTION/PROCEDURE … $$body$$;` statement,
424
+ preserving any leading comment/whitespace prefix and trailing whitespace."""
425
+ from sqlalign.formatter import _split_prefix # lazy: breaks import cycle
426
+ prefix, rest = _split_prefix(stmt)
427
+ core_stmt = rest.rstrip()
428
+ trailing_ws = rest[len(core_stmt):]
429
+ parts = split_body(core_stmt)
430
+ if parts is None:
431
+ raise Unsupported("plpgsql: no dollar-quoted body")
432
+ tag = DOLLAR_TAG.search(core_stmt).group(0)
433
+ _, body_raw, _tail = parts
434
+ header = "\n".join(_header_lines(node, dialect, tag))
435
+ body = layout_body(body_raw, dialect, style, body_language(node) or "plpgsql")
436
+ core = f"{header}\n\n{body}\n{tag};"
437
+ return prefix + core + trailing_ws
sqlalign/splitter.py ADDED
@@ -0,0 +1,241 @@
1
+ """Statement splitting: the one place a file is cut into statements.
2
+
3
+ Every split here is LOSSLESS: the returned parts concatenate back to the input
4
+ byte for byte, whitespace and comments included, because a statement the
5
+ engine declines is emitted from its part verbatim, so a part that lost
6
+ a character would corrupt the passthrough.
7
+ """
8
+ import re
9
+
10
+ # Dollar-quote tag: bare `$$`, or `$tag$` where tag starts with a letter/underscore
11
+ # and may contain digits thereafter (e.g. `$fn1$`): matches Postgres's identifier
12
+ # rules for dollar-quote tags, which allow digits after the first character.
13
+ # Public because plpgsql.py splits the same bodies and must agree exactly.
14
+ DOLLAR_TAG = re.compile(r"\$(?:[A-Za-z_][A-Za-z0-9_]*)?\$")
15
+
16
+ _IDENT_CHARS = re.compile(r"[A-Za-z0-9_]")
17
+
18
+
19
+ # A T-SQL batch separator: a line whose entire content is `GO`, optionally with a
20
+ # repeat count. It is a client-tool directive, not SQL: sqlglot cannot parse it,
21
+ # and worse, it SWALLOWS the following statement into the GO command as a string
22
+ # literal (`GO\nSELECT 2` parses as one Command). Batches must therefore be split
23
+ # before anything is parsed.
24
+ _GO_LINE = re.compile(r"^[ \t]*GO(?:[ \t]+\d+)?[ \t]*$", re.IGNORECASE | re.MULTILINE)
25
+
26
+
27
+ def split_statements(text: str, dialect: str = "postgres") -> list[str]:
28
+ """Split on top-level semicolons; lossless (parts concatenate to the input).
29
+
30
+ Under T-SQL a standalone `GO` line additionally ends a batch, and is returned
31
+ as its own part so the caller can pass it through verbatim.
32
+ """
33
+ if dialect == "tsql":
34
+ text_parts = _split_tsql_blocks(text)
35
+ if text_parts is not None:
36
+ return text_parts
37
+ if _GO_LINE.search(text):
38
+ parts: list[str] = []
39
+ pos = 0
40
+ for match in _GO_LINE.finditer(text):
41
+ before = text[pos:match.start()]
42
+ if before:
43
+ parts.extend(split_statements(before))
44
+ parts.append(text[match.start():match.end()]) # the GO line itself
45
+ pos = match.end()
46
+ if pos < len(text):
47
+ parts.extend(split_statements(text[pos:]))
48
+ return parts
49
+ return _split_on_semicolons(text)
50
+
51
+
52
+ # The routine-defining statements whose body is a BEGIN...END block. Only these
53
+ # get block tracking, deliberately: a general "count BEGIN and END" scan is unsafe
54
+ # because `CASE ... END` shares the END keyword, and `BEGIN TRANSACTION` opens a
55
+ # block that never has a matching END at all. Confining the scan to a routine body
56
+ # keeps both hazards out of ordinary statements.
57
+ _ROUTINE_START = re.compile(
58
+ r"\bCREATE\s+(?:OR\s+ALTER\s+)?(?:PROCEDURE|PROC|FUNCTION|TRIGGER)\b", re.IGNORECASE)
59
+ _WORD_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
60
+
61
+
62
+ def _split_tsql_blocks(text: str) -> list[str] | None:
63
+ """Split `text` keeping each `CREATE PROCEDURE ... BEGIN ... END` whole.
64
+
65
+ Returns None when there is no routine definition, so the ordinary scanner
66
+ handles the text unchanged. A routine's body contains semicolons that must NOT
67
+ end the statement, which is exactly what the plain scanner would do.
68
+
69
+ `END` is ambiguous: it also closes `CASE` — so a small stack records what each
70
+ opener was and only a `BEGIN` popped off it ends the block.
71
+ """
72
+ if not _ROUTINE_START.search(text):
73
+ return None
74
+ parts: list[str] = []
75
+ pos = 0
76
+ while True:
77
+ match = _ROUTINE_START.search(text, pos)
78
+ if match is None:
79
+ if pos < len(text):
80
+ parts.extend(_split_on_semicolons(text[pos:]))
81
+ return parts
82
+ if match.start() > pos:
83
+ parts.extend(_split_on_semicolons(text[pos:match.start()]))
84
+ end = _routine_end(text, match.start())
85
+ parts.append(text[match.start():end])
86
+ pos = end
87
+
88
+
89
+ def _routine_end(text: str, start: int) -> int:
90
+ """Index just past the routine beginning at `start`: the `END` that closes its
91
+ outermost `BEGIN`, plus a trailing `;` if present. Falls back to end-of-text
92
+ for an unterminated routine, which then simply fails to parse and passes
93
+ through."""
94
+ stack: list[str] = []
95
+ i, n = start, len(text)
96
+ while i < n:
97
+ ch = text[i]
98
+ if ch in ("'", '"', "[") or text.startswith("--", i) or text.startswith("/*", i):
99
+ i = _skip_opaque(text, i) # never read keywords out of these
100
+ continue
101
+ word_match = _WORD_RE.match(text, i)
102
+ if word_match is None:
103
+ i += 1
104
+ continue
105
+ word = word_match.group(0).upper()
106
+ i = word_match.end()
107
+ if word == "CASE":
108
+ stack.append("CASE")
109
+ elif word == "BEGIN":
110
+ # BEGIN TRANSACTION/TRAN opens no block that an END will close.
111
+ following = _WORD_RE.match(text, _skip_spaces(text, i))
112
+ if following and following.group(0).upper() in ("TRANSACTION", "TRAN"):
113
+ continue
114
+ stack.append("BEGIN")
115
+ elif word == "END" and stack:
116
+ closed = stack.pop()
117
+ # Only the OUTERMOST BEGIN ends the routine; an END that closed a
118
+ # CASE, or one that leaves the stack non-empty, is interior.
119
+ if closed == "BEGIN" and not stack:
120
+ tail = _skip_spaces(text, i)
121
+ return tail + 1 if tail < n and text[tail] == ";" else i
122
+ return n
123
+
124
+
125
+ def _skip_spaces(text: str, i: int) -> int:
126
+ while i < len(text) and text[i] in " \t\r\n":
127
+ i += 1
128
+ return i
129
+
130
+
131
+ def _skip_opaque(text: str, i: int) -> int:
132
+ """Advance past a string, quoted/bracketed identifier, or comment, so a
133
+ keyword-looking word inside one is never mistaken for a BEGIN/END/CASE."""
134
+ n = len(text)
135
+ ch = text[i]
136
+ if ch == "'":
137
+ i += 1
138
+ while i < n:
139
+ if text[i] == "'" and not (i + 1 < n and text[i + 1] == "'"):
140
+ return i + 1
141
+ i += 2 if text[i] == "'" else 1
142
+ return n
143
+ if ch == '"':
144
+ j = text.find('"', i + 1)
145
+ return n if j == -1 else j + 1
146
+ if ch == "[":
147
+ i += 1
148
+ while i < n:
149
+ if text[i] == "]":
150
+ if i + 1 < n and text[i + 1] == "]":
151
+ i += 2
152
+ continue
153
+ return i + 1
154
+ i += 1
155
+ return n
156
+ if text.startswith("--", i):
157
+ j = text.find("\n", i)
158
+ return n if j == -1 else j
159
+ if text.startswith("/*", i):
160
+ j = text.find("*/", i)
161
+ return n if j == -1 else j + 2
162
+ return i + 1
163
+
164
+
165
+ def _split_on_semicolons(text: str) -> list[str]:
166
+ parts: list[str] = []
167
+ start = i = 0
168
+ n = len(text)
169
+ while i < n:
170
+ ch = text[i]
171
+ if ch == "'": # standard or E-prefixed string
172
+ # An E-string (`E'...'` / `e'...'`) additionally honors backslash
173
+ # escapes (`\'`, `\\`); a bare string only understands `''` doubling.
174
+ # Only treat a preceding e/E as the E-prefix if it isn't itself the
175
+ # tail of a longer identifier (e.g. `CASE'x'` is CASE, not E'x').
176
+ prev = text[i - 1] if i > 0 else ""
177
+ prev2 = text[i - 2] if i > 1 else ""
178
+ is_estring = prev in "eE" and not _IDENT_CHARS.match(prev2)
179
+ i += 1
180
+ while i < n:
181
+ if is_estring and text[i] == "\\" and i + 1 < n:
182
+ i += 2
183
+ continue
184
+ if text[i] == "'" and not (i + 1 < n and text[i + 1] == "'"):
185
+ break
186
+ i += 2 if text[i] == "'" else 1
187
+ i += 1
188
+ elif ch == '"': # quoted identifier
189
+ close = text.find('"', i + 1)
190
+ i = n if close == -1 else close + 1
191
+ elif ch == "[":
192
+ # T-SQL bracket-quoted identifier: [my col], and `]]` escapes a literal
193
+ # `]` inside one. Without this a bracketed name containing a semicolon
194
+ # (`[my;col]`) splits mid-identifier: lossless, so the file survives,
195
+ # but every fragment then fails to parse and the file goes unformatted.
196
+ i += 1
197
+ while i < n:
198
+ if text[i] == "]":
199
+ if i + 1 < n and text[i + 1] == "]": # ]] -> escaped
200
+ i += 2
201
+ continue
202
+ i += 1
203
+ break
204
+ i += 1
205
+ elif text.startswith("--", i):
206
+ nl = text.find("\n", i)
207
+ i = n if nl == -1 else nl + 1
208
+ elif text.startswith("/*", i):
209
+ depth, i = 1, i + 2
210
+ while i < n and depth:
211
+ if text.startswith("/*", i):
212
+ depth, i = depth + 1, i + 2
213
+ elif text.startswith("*/", i):
214
+ depth, i = depth - 1, i + 2
215
+ else:
216
+ i += 1
217
+ elif ch == "$" and (m := DOLLAR_TAG.match(text, i)):
218
+ tag = m.group(0)
219
+ end = text.find(tag, m.end())
220
+ i = n if end == -1 else end + len(tag)
221
+ elif ch == ";":
222
+ i += 1
223
+ while i < n and text[i] in " \t": # keep same-line trailer with the statement
224
+ i += 1
225
+ if i < n and text.startswith("--", i):
226
+ nl = text.find("\n", i)
227
+ i = n if nl == -1 else nl + 1
228
+ parts.append(text[start:i])
229
+ start = i
230
+ else:
231
+ i += 1
232
+ if start < n:
233
+ remainder = text[start:]
234
+ # Trailing whitespace after the last `;` belongs to the statement before
235
+ # it, not to a part of its own: a whitespace-only part parses to nothing
236
+ # and would be emitted as a spurious empty statement.
237
+ if remainder.strip() or not parts:
238
+ parts.append(remainder)
239
+ else:
240
+ parts[-1] += remainder
241
+ return parts