sql-sp-harness 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sql_sp_harness/__init__.py +4 -0
- sql_sp_harness/__main__.py +4 -0
- sql_sp_harness/cli.py +297 -0
- sql_sp_harness/console.py +45 -0
- sql_sp_harness/dml_preview.py +277 -0
- sql_sp_harness/emit.py +25 -0
- sql_sp_harness/inventory.py +512 -0
- sql_sp_harness/parse.py +118 -0
- sql_sp_harness/t_sql_scan.py +286 -0
- sql_sp_harness/transform.py +292 -0
- sql_sp_harness-1.0.0.dist-info/METADATA +120 -0
- sql_sp_harness-1.0.0.dist-info/RECORD +16 -0
- sql_sp_harness-1.0.0.dist-info/WHEEL +5 -0
- sql_sp_harness-1.0.0.dist-info/entry_points.txt +3 -0
- sql_sp_harness-1.0.0.dist-info/licenses/LICENSE +21 -0
- sql_sp_harness-1.0.0.dist-info/top_level.txt +1 -0
sql_sp_harness/cli.py
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
"""CLI for sql-sp-harness."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import sys
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Optional
|
|
8
|
+
|
|
9
|
+
import typer
|
|
10
|
+
|
|
11
|
+
from sql_sp_harness import __version__
|
|
12
|
+
from sql_sp_harness.console import supports_color
|
|
13
|
+
from sql_sp_harness.inventory import inventory_from_sql
|
|
14
|
+
from sql_sp_harness.transform import transform_sql
|
|
15
|
+
|
|
16
|
+
APP_HELP = """
|
|
17
|
+
Turn T-SQL stored procedures into safe, runnable debug scripts.
|
|
18
|
+
|
|
19
|
+
\b
|
|
20
|
+
Commands:
|
|
21
|
+
analyze See what a procedure does (DML, TRY/CATCH, loops, variables)
|
|
22
|
+
generate Create a debug harness script safe to run on a dev database
|
|
23
|
+
|
|
24
|
+
\b
|
|
25
|
+
Quick start:
|
|
26
|
+
sql-sp-harness analyze -i MyProc.sql
|
|
27
|
+
sql-sp-harness generate -i MyProc.sql -o MyProc_debug.sql
|
|
28
|
+
|
|
29
|
+
\b
|
|
30
|
+
More help:
|
|
31
|
+
sql-sp-harness analyze --help
|
|
32
|
+
sql-sp-harness generate --help
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
app = typer.Typer(
|
|
36
|
+
name="sql-sp-harness",
|
|
37
|
+
help=APP_HELP,
|
|
38
|
+
no_args_is_help=True,
|
|
39
|
+
add_completion=False,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@app.command("version")
|
|
44
|
+
def cmd_version() -> None:
|
|
45
|
+
"""Print package version."""
|
|
46
|
+
typer.echo(__version__)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _version() -> str:
|
|
50
|
+
try:
|
|
51
|
+
from importlib.metadata import version
|
|
52
|
+
|
|
53
|
+
return version("sql-sp-harness")
|
|
54
|
+
except Exception:
|
|
55
|
+
return __version__
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@app.callback()
|
|
59
|
+
def _root_callback(
|
|
60
|
+
ctx: typer.Context,
|
|
61
|
+
version: Optional[bool] = typer.Option(
|
|
62
|
+
None,
|
|
63
|
+
"--version",
|
|
64
|
+
"-V",
|
|
65
|
+
help="Show version and exit.",
|
|
66
|
+
is_eager=True,
|
|
67
|
+
),
|
|
68
|
+
) -> None:
|
|
69
|
+
"""T-SQL stored procedure debug harness generator."""
|
|
70
|
+
if version:
|
|
71
|
+
typer.echo(f"sql-sp-harness {_version()}")
|
|
72
|
+
raise typer.Exit()
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _read_input(path: Optional[Path]) -> str:
|
|
76
|
+
if path is None or str(path) == "-":
|
|
77
|
+
return sys.stdin.read()
|
|
78
|
+
return path.read_text(encoding="utf-8")
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _write_output(path: Optional[Path], content: str) -> None:
|
|
82
|
+
if path is None or str(path) == "-":
|
|
83
|
+
sys.stdout.write(content)
|
|
84
|
+
return
|
|
85
|
+
path.write_text(content, encoding="utf-8")
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _run_analyze(
|
|
89
|
+
input: Path,
|
|
90
|
+
report: Optional[Path],
|
|
91
|
+
plain: bool,
|
|
92
|
+
full: bool,
|
|
93
|
+
) -> None:
|
|
94
|
+
sql = _read_input(input)
|
|
95
|
+
inv = inventory_from_sql(sql)
|
|
96
|
+
colorize = supports_color() and not plain and report is None
|
|
97
|
+
text = inv.to_text(colorize=colorize, non_zero_only=not full)
|
|
98
|
+
if report:
|
|
99
|
+
report.write_text(text + "\n", encoding="utf-8")
|
|
100
|
+
typer.echo(f"Report written to {report}")
|
|
101
|
+
else:
|
|
102
|
+
typer.echo(text)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@app.command("analyze")
|
|
106
|
+
def analyze_cmd(
|
|
107
|
+
input: Path = typer.Option(
|
|
108
|
+
...,
|
|
109
|
+
"--input",
|
|
110
|
+
"-i",
|
|
111
|
+
help="Input .sql file (use - for stdin).",
|
|
112
|
+
),
|
|
113
|
+
report: Optional[Path] = typer.Option(
|
|
114
|
+
None,
|
|
115
|
+
"--report",
|
|
116
|
+
"-r",
|
|
117
|
+
help="Write plain-text report to file (no ANSI colors).",
|
|
118
|
+
),
|
|
119
|
+
plain: bool = typer.Option(
|
|
120
|
+
False,
|
|
121
|
+
"--plain",
|
|
122
|
+
help="Disable ANSI colors on terminal output.",
|
|
123
|
+
),
|
|
124
|
+
full: bool = typer.Option(
|
|
125
|
+
False,
|
|
126
|
+
"--full",
|
|
127
|
+
help="Show all sections, including zero counts.",
|
|
128
|
+
),
|
|
129
|
+
) -> None:
|
|
130
|
+
"""
|
|
131
|
+
Analyze a stored procedure and show what it does.
|
|
132
|
+
|
|
133
|
+
Summarizes DML against real tables, TRY/CATCH blocks, loops, SET statements,
|
|
134
|
+
and other structural detail — useful before generating a debug harness.
|
|
135
|
+
"""
|
|
136
|
+
_run_analyze(input, report, plain, full)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
@app.command("inventory", hidden=True)
|
|
140
|
+
def inventory_cmd(
|
|
141
|
+
input: Path = typer.Option(
|
|
142
|
+
...,
|
|
143
|
+
"--input",
|
|
144
|
+
"-i",
|
|
145
|
+
help="Input .sql file (use - for stdin).",
|
|
146
|
+
),
|
|
147
|
+
report: Optional[Path] = typer.Option(
|
|
148
|
+
None,
|
|
149
|
+
"--report",
|
|
150
|
+
"-r",
|
|
151
|
+
help="Write plain-text report to file (no ANSI colors).",
|
|
152
|
+
),
|
|
153
|
+
plain: bool = typer.Option(
|
|
154
|
+
False,
|
|
155
|
+
"--plain",
|
|
156
|
+
help="Disable ANSI colors on terminal output.",
|
|
157
|
+
),
|
|
158
|
+
full: bool = typer.Option(
|
|
159
|
+
False,
|
|
160
|
+
"--full",
|
|
161
|
+
help="Show all sections, including zero counts.",
|
|
162
|
+
),
|
|
163
|
+
) -> None:
|
|
164
|
+
"""Deprecated alias for analyze."""
|
|
165
|
+
_run_analyze(input, report, plain, full)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _run_generate(
|
|
169
|
+
input: Path,
|
|
170
|
+
output: Optional[Path],
|
|
171
|
+
trace_style: str,
|
|
172
|
+
no_stub_dml: bool,
|
|
173
|
+
block_markers: bool,
|
|
174
|
+
quiet: bool,
|
|
175
|
+
) -> None:
|
|
176
|
+
if trace_style not in ("raiserror", "print"):
|
|
177
|
+
typer.echo("trace-style must be 'raiserror' or 'print'", err=True)
|
|
178
|
+
raise typer.Exit(1)
|
|
179
|
+
|
|
180
|
+
sql = _read_input(input)
|
|
181
|
+
progress = None if quiet else lambda msg: typer.echo(msg, err=True)
|
|
182
|
+
|
|
183
|
+
result = transform_sql(
|
|
184
|
+
sql,
|
|
185
|
+
trace_style=trace_style,
|
|
186
|
+
stub_dml=not no_stub_dml,
|
|
187
|
+
add_block_markers=block_markers,
|
|
188
|
+
on_progress=progress,
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
out_path = output
|
|
192
|
+
if out_path is None and str(input) != "-":
|
|
193
|
+
out_path = input.with_name(f"{input.stem}_debug{input.suffix}")
|
|
194
|
+
|
|
195
|
+
_write_output(out_path, result.sql)
|
|
196
|
+
|
|
197
|
+
summary = (
|
|
198
|
+
f"Done: {result.stats.dml_stubbed} DML stubbed, "
|
|
199
|
+
f"{result.stats.traces_added} traces added."
|
|
200
|
+
)
|
|
201
|
+
if out_path and str(out_path) != "-":
|
|
202
|
+
typer.echo(f"{summary} Written to {out_path}")
|
|
203
|
+
else:
|
|
204
|
+
typer.echo(summary)
|
|
205
|
+
|
|
206
|
+
if result.parse_errors:
|
|
207
|
+
typer.echo("Parse warnings present — review banner in output.", err=True)
|
|
208
|
+
raise typer.Exit(2)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
@app.command("generate")
|
|
212
|
+
def generate_cmd(
|
|
213
|
+
input: Path = typer.Option(
|
|
214
|
+
...,
|
|
215
|
+
"--input",
|
|
216
|
+
"-i",
|
|
217
|
+
help="Input .sql file (use - for stdin).",
|
|
218
|
+
),
|
|
219
|
+
output: Optional[Path] = typer.Option(
|
|
220
|
+
None,
|
|
221
|
+
"--output",
|
|
222
|
+
"-o",
|
|
223
|
+
help="Output path (default: <input>_debug.sql).",
|
|
224
|
+
),
|
|
225
|
+
trace_style: str = typer.Option(
|
|
226
|
+
"print",
|
|
227
|
+
"--trace-style",
|
|
228
|
+
help="Trace style: print (default) or raiserror (NOWAIT).",
|
|
229
|
+
),
|
|
230
|
+
no_stub_dml: bool = typer.Option(
|
|
231
|
+
False, "--no-stub-dml", help="Skip DML stubbing; only add traces."
|
|
232
|
+
),
|
|
233
|
+
block_markers: bool = typer.Option(
|
|
234
|
+
False,
|
|
235
|
+
"--block-markers",
|
|
236
|
+
help="Insert -- [DBG] Step N markers before IF/WHILE.",
|
|
237
|
+
),
|
|
238
|
+
quiet: bool = typer.Option(
|
|
239
|
+
False,
|
|
240
|
+
"--quiet",
|
|
241
|
+
"-q",
|
|
242
|
+
help="Suppress progress messages on stderr.",
|
|
243
|
+
),
|
|
244
|
+
) -> None:
|
|
245
|
+
"""
|
|
246
|
+
Generate a debug harness script from a stored procedure.
|
|
247
|
+
|
|
248
|
+
Replaces writes to real tables with SELECT previews and adds PRINT traces on
|
|
249
|
+
variables so you can run the script on a dev database without side effects.
|
|
250
|
+
"""
|
|
251
|
+
_run_generate(input, output, trace_style, no_stub_dml, block_markers, quiet)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
@app.command("transform", hidden=True)
|
|
255
|
+
def transform_cmd(
|
|
256
|
+
input: Path = typer.Option(
|
|
257
|
+
...,
|
|
258
|
+
"--input",
|
|
259
|
+
"-i",
|
|
260
|
+
help="Input .sql file (use - for stdin).",
|
|
261
|
+
),
|
|
262
|
+
output: Optional[Path] = typer.Option(
|
|
263
|
+
None,
|
|
264
|
+
"--output",
|
|
265
|
+
"-o",
|
|
266
|
+
help="Output path (default: <input>_debug.sql).",
|
|
267
|
+
),
|
|
268
|
+
trace_style: str = typer.Option(
|
|
269
|
+
"print",
|
|
270
|
+
"--trace-style",
|
|
271
|
+
help="Trace style: print (default) or raiserror (NOWAIT).",
|
|
272
|
+
),
|
|
273
|
+
no_stub_dml: bool = typer.Option(
|
|
274
|
+
False, "--no-stub-dml", help="Skip DML stubbing; only add traces."
|
|
275
|
+
),
|
|
276
|
+
block_markers: bool = typer.Option(
|
|
277
|
+
False,
|
|
278
|
+
"--block-markers",
|
|
279
|
+
help="Insert -- [DBG] Step N markers before IF/WHILE.",
|
|
280
|
+
),
|
|
281
|
+
quiet: bool = typer.Option(
|
|
282
|
+
False,
|
|
283
|
+
"--quiet",
|
|
284
|
+
"-q",
|
|
285
|
+
help="Suppress progress messages on stderr.",
|
|
286
|
+
),
|
|
287
|
+
) -> None:
|
|
288
|
+
"""Deprecated alias for generate."""
|
|
289
|
+
_run_generate(input, output, trace_style, no_stub_dml, block_markers, quiet)
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def main() -> None:
|
|
293
|
+
app()
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
if __name__ == "__main__":
|
|
297
|
+
main()
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Terminal styling helpers for CLI output."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
RESET = "\033[0m"
|
|
9
|
+
GREEN = "\033[32m"
|
|
10
|
+
RED = "\033[31m"
|
|
11
|
+
YELLOW = "\033[33m"
|
|
12
|
+
CYAN = "\033[36m"
|
|
13
|
+
BOLD = "\033[1m"
|
|
14
|
+
ITALIC = "\033[3m"
|
|
15
|
+
DIM = "\033[2m"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def supports_color() -> bool:
|
|
19
|
+
return sys.stdout.isatty() and os.environ.get("NO_COLOR") is None
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def style(text: str, color: str, *, enabled: bool = True) -> str:
|
|
23
|
+
if not enabled:
|
|
24
|
+
return text
|
|
25
|
+
return f"{color}{text}{RESET}"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def success(text: str, *, enabled: bool = True) -> str:
|
|
29
|
+
return style(text, GREEN, enabled=enabled)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def failure(text: str, *, enabled: bool = True) -> str:
|
|
33
|
+
return style(text, RED, enabled=enabled)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def warning(text: str, *, enabled: bool = True) -> str:
|
|
37
|
+
return style(text, YELLOW, enabled=enabled)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def heading(text: str, *, enabled: bool = True) -> str:
|
|
41
|
+
return style(text, CYAN + BOLD, enabled=enabled)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def dim(text: str, *, enabled: bool = True) -> str:
|
|
45
|
+
return style(text, DIM, enabled=enabled)
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
"""Convert DML statements into safe SELECT previews for debug harness scripts."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
CLAUSE_FROM = re.compile(r"\bFROM\b", re.IGNORECASE)
|
|
8
|
+
CLAUSE_WHERE = re.compile(r"\bWHERE\b", re.IGNORECASE)
|
|
9
|
+
CLAUSE_SET = re.compile(r"\bSET\b", re.IGNORECASE)
|
|
10
|
+
INSERT_INTO = re.compile(r"^\s*INSERT\s+INTO\s+(\S+)", re.IGNORECASE)
|
|
11
|
+
DELETE_FROM = re.compile(
|
|
12
|
+
r"^\s*DELETE\s+FROM\s+(\S+)(?:\s+WHERE\s+(.+))?\s*;?\s*$",
|
|
13
|
+
re.IGNORECASE | re.DOTALL,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _extract_paren_content(text: str, open_index: int) -> tuple[str, int] | None:
|
|
18
|
+
if open_index >= len(text) or text[open_index] != "(":
|
|
19
|
+
return None
|
|
20
|
+
depth = 0
|
|
21
|
+
for i in range(open_index, len(text)):
|
|
22
|
+
ch = text[i]
|
|
23
|
+
if ch == "(":
|
|
24
|
+
depth += 1
|
|
25
|
+
elif ch == ")":
|
|
26
|
+
depth -= 1
|
|
27
|
+
if depth == 0:
|
|
28
|
+
return text[open_index + 1 : i], i + 1
|
|
29
|
+
return None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _block_sql(block_lines: list[str]) -> str:
|
|
33
|
+
parts = [ln.strip() for ln in block_lines if ln.strip()]
|
|
34
|
+
return re.sub(r"\s+", " ", " ".join(parts)).strip()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _find_clause(text: str, pattern: re.Pattern[str]) -> int | None:
|
|
38
|
+
match = pattern.search(text)
|
|
39
|
+
return match.start() if match else None
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _split_expressions(text: str) -> list[str]:
|
|
43
|
+
parts: list[str] = []
|
|
44
|
+
depth = 0
|
|
45
|
+
current: list[str] = []
|
|
46
|
+
for ch in text:
|
|
47
|
+
if ch == "(":
|
|
48
|
+
depth += 1
|
|
49
|
+
elif ch == ")":
|
|
50
|
+
depth -= 1
|
|
51
|
+
elif ch == "," and depth == 0:
|
|
52
|
+
part = "".join(current).strip()
|
|
53
|
+
if part:
|
|
54
|
+
parts.append(part)
|
|
55
|
+
current = []
|
|
56
|
+
continue
|
|
57
|
+
current.append(ch)
|
|
58
|
+
tail = "".join(current).strip()
|
|
59
|
+
if tail:
|
|
60
|
+
parts.append(tail)
|
|
61
|
+
return parts
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _parse_assignments(set_clause: str) -> list[tuple[str, str]]:
|
|
65
|
+
assignments: list[tuple[str, str]] = []
|
|
66
|
+
for part in _split_expressions(set_clause):
|
|
67
|
+
if "=" not in part:
|
|
68
|
+
continue
|
|
69
|
+
lhs, rhs = part.split("=", 1)
|
|
70
|
+
assignments.append((lhs.strip(), rhs.strip()))
|
|
71
|
+
return assignments
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _column_alias(name: str) -> str:
|
|
75
|
+
base = name.split(".")[-1].strip("[]")
|
|
76
|
+
return f"[{base}]"
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
_BARE_VAR = re.compile(r"^@\w+$", re.IGNORECASE)
|
|
80
|
+
_QUOTED_LITERAL = re.compile(r"^(N?'([^']|'')*'|\d+(\.\d+)?)$", re.IGNORECASE)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _lhs_column_name(lhs: str) -> str:
|
|
84
|
+
return lhs.split(".")[-1].strip("[]")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _is_calculation(expr: str) -> bool:
|
|
88
|
+
"""True when RHS is an expression, not a bare variable or simple literal."""
|
|
89
|
+
text = expr.strip()
|
|
90
|
+
if _BARE_VAR.match(text):
|
|
91
|
+
return False
|
|
92
|
+
if _QUOTED_LITERAL.match(text):
|
|
93
|
+
return False
|
|
94
|
+
if re.search(r"[\+\-\*/%]|^\w+\(", text, re.IGNORECASE):
|
|
95
|
+
return True
|
|
96
|
+
return False
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _preview_column_alias(lhs: str, rhs: str) -> str:
|
|
100
|
+
"""Choose preview column alias based on SET/VALUES expression shape."""
|
|
101
|
+
rhs = rhs.strip()
|
|
102
|
+
if _BARE_VAR.match(rhs):
|
|
103
|
+
return f"[{rhs}]"
|
|
104
|
+
col = _lhs_column_name(lhs)
|
|
105
|
+
if _is_calculation(rhs):
|
|
106
|
+
return f"[calculated-{col}]"
|
|
107
|
+
return f"[{col}]"
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _parse_update(sql: str) -> dict[str, str | list[tuple[str, str]]] | None:
|
|
111
|
+
text = sql.strip().rstrip(";")
|
|
112
|
+
if not re.match(r"UPDATE\b", text, re.I):
|
|
113
|
+
return None
|
|
114
|
+
|
|
115
|
+
rest = re.sub(r"^UPDATE\s+", "", text, flags=re.I).strip()
|
|
116
|
+
set_match = CLAUSE_SET.search(rest)
|
|
117
|
+
if not set_match:
|
|
118
|
+
return None
|
|
119
|
+
|
|
120
|
+
target = rest[: set_match.start()].strip()
|
|
121
|
+
after_set = rest[set_match.end() :].strip()
|
|
122
|
+
from_pos = _find_clause(after_set, CLAUSE_FROM)
|
|
123
|
+
where_pos = _find_clause(after_set, CLAUSE_WHERE)
|
|
124
|
+
stops = [pos for pos in (from_pos, where_pos) if pos is not None]
|
|
125
|
+
assign_end = min(stops) if stops else len(after_set)
|
|
126
|
+
|
|
127
|
+
assignments = _parse_assignments(after_set[:assign_end])
|
|
128
|
+
if not assignments:
|
|
129
|
+
return None
|
|
130
|
+
|
|
131
|
+
from_clause = ""
|
|
132
|
+
if from_pos is not None:
|
|
133
|
+
from_end = where_pos if where_pos is not None and where_pos > from_pos else len(after_set)
|
|
134
|
+
from_clause = after_set[from_pos:from_end].strip()
|
|
135
|
+
|
|
136
|
+
where_clause = ""
|
|
137
|
+
if where_pos is not None:
|
|
138
|
+
where_clause = after_set[where_pos:].strip()
|
|
139
|
+
|
|
140
|
+
return {
|
|
141
|
+
"kind": "UPDATE",
|
|
142
|
+
"target": target,
|
|
143
|
+
"assignments": assignments,
|
|
144
|
+
"from_clause": from_clause,
|
|
145
|
+
"where_clause": where_clause,
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _parse_insert(sql: str) -> dict[str, str | list[str]] | None:
|
|
150
|
+
one_line = re.sub(r"\s+", " ", sql.strip().rstrip(";"))
|
|
151
|
+
head = INSERT_INTO.match(one_line)
|
|
152
|
+
if not head:
|
|
153
|
+
return None
|
|
154
|
+
|
|
155
|
+
table = head.group(1)
|
|
156
|
+
pos = head.end()
|
|
157
|
+
while pos < len(one_line) and one_line[pos].isspace():
|
|
158
|
+
pos += 1
|
|
159
|
+
columns: list[str] = []
|
|
160
|
+
|
|
161
|
+
if pos < len(one_line) and one_line[pos] == "(":
|
|
162
|
+
col_content, pos = _extract_paren_content(one_line, pos) or ("", pos)
|
|
163
|
+
columns = [c.strip() for c in col_content.split(",") if c.strip()]
|
|
164
|
+
|
|
165
|
+
values_match = re.search(r"\bVALUES\b", one_line[pos:], re.I)
|
|
166
|
+
if not values_match:
|
|
167
|
+
return None
|
|
168
|
+
pos += values_match.end()
|
|
169
|
+
while pos < len(one_line) and one_line[pos].isspace():
|
|
170
|
+
pos += 1
|
|
171
|
+
|
|
172
|
+
values_content, _end = _extract_paren_content(one_line, pos) or ("", pos)
|
|
173
|
+
values = _split_expressions(values_content)
|
|
174
|
+
if not values:
|
|
175
|
+
return None
|
|
176
|
+
if columns and len(columns) != len(values):
|
|
177
|
+
return None
|
|
178
|
+
if not columns:
|
|
179
|
+
columns = [f"col{i + 1}" for i in range(len(values))]
|
|
180
|
+
|
|
181
|
+
return {
|
|
182
|
+
"kind": "INSERT",
|
|
183
|
+
"target": table,
|
|
184
|
+
"columns": columns,
|
|
185
|
+
"values": values,
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _parse_delete(sql: str) -> dict[str, str] | None:
|
|
190
|
+
one_line = re.sub(r"\s+", " ", sql.strip().rstrip(";"))
|
|
191
|
+
match = DELETE_FROM.match(one_line)
|
|
192
|
+
if not match:
|
|
193
|
+
return None
|
|
194
|
+
return {
|
|
195
|
+
"kind": "DELETE",
|
|
196
|
+
"target": match.group(1),
|
|
197
|
+
"where_clause": (match.group(2) or "").strip(),
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _format_multiline(indent: str, sql: str) -> list[str]:
|
|
202
|
+
return [f"{indent}{line}" if line else "" for line in sql.splitlines()]
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def build_dml_preview(block_lines: list[str], indent: str) -> list[str] | None:
|
|
206
|
+
"""Return SELECT preview lines replacing a DML block, or None if unsupported."""
|
|
207
|
+
sql = _block_sql(block_lines)
|
|
208
|
+
first = block_lines[0].strip().split()[0].upper()
|
|
209
|
+
|
|
210
|
+
if first == "UPDATE":
|
|
211
|
+
parsed = _parse_update(sql)
|
|
212
|
+
if parsed is None:
|
|
213
|
+
return None
|
|
214
|
+
target = str(parsed["target"])
|
|
215
|
+
assignments = parsed["assignments"]
|
|
216
|
+
assert isinstance(assignments, list)
|
|
217
|
+
|
|
218
|
+
select_cols = [f"N'UPDATE to table {target}' AS [DBG_Action]"]
|
|
219
|
+
for lhs, rhs in assignments:
|
|
220
|
+
select_cols.append(f"{rhs} AS {_preview_column_alias(str(lhs), str(rhs))}")
|
|
221
|
+
|
|
222
|
+
from_clause = str(parsed.get("from_clause") or "")
|
|
223
|
+
if from_clause:
|
|
224
|
+
from_sql = from_clause
|
|
225
|
+
else:
|
|
226
|
+
from_sql = f"FROM {target}"
|
|
227
|
+
|
|
228
|
+
where_clause = str(parsed.get("where_clause") or "").strip()
|
|
229
|
+
preview = (
|
|
230
|
+
f"SELECT {', '.join(select_cols)}\n"
|
|
231
|
+
f"{from_sql}"
|
|
232
|
+
+ (f"\n{where_clause}" if where_clause else "")
|
|
233
|
+
+ ";"
|
|
234
|
+
)
|
|
235
|
+
return [
|
|
236
|
+
f"{indent}-- [DBG-PREVIEW] Would have executed:",
|
|
237
|
+
*_format_multiline(indent, preview),
|
|
238
|
+
]
|
|
239
|
+
|
|
240
|
+
if first == "INSERT":
|
|
241
|
+
parsed = _parse_insert(sql)
|
|
242
|
+
if parsed is None:
|
|
243
|
+
return None
|
|
244
|
+
target = str(parsed["target"])
|
|
245
|
+
columns = parsed["columns"]
|
|
246
|
+
values = parsed["values"]
|
|
247
|
+
assert isinstance(columns, list) and isinstance(values, list)
|
|
248
|
+
|
|
249
|
+
select_cols = [f"N'INSERT to table {target}' AS [DBG_Action]"]
|
|
250
|
+
for col, val in zip(columns, values, strict=True):
|
|
251
|
+
select_cols.append(f"{val} AS {_preview_column_alias(str(col), str(val))}")
|
|
252
|
+
|
|
253
|
+
preview = f"SELECT {', '.join(select_cols)};"
|
|
254
|
+
return [
|
|
255
|
+
f"{indent}-- [DBG-PREVIEW] Would have executed:",
|
|
256
|
+
*_format_multiline(indent, preview),
|
|
257
|
+
]
|
|
258
|
+
|
|
259
|
+
if first == "DELETE":
|
|
260
|
+
parsed = _parse_delete(sql)
|
|
261
|
+
if parsed is None:
|
|
262
|
+
return None
|
|
263
|
+
target = str(parsed["target"])
|
|
264
|
+
where_clause = str(parsed.get("where_clause") or "").strip()
|
|
265
|
+
select_cols = [f"N'DELETE from table {target}' AS [DBG_Action]", "*"]
|
|
266
|
+
preview = (
|
|
267
|
+
f"SELECT {', '.join(select_cols)}\n"
|
|
268
|
+
f"FROM {target}"
|
|
269
|
+
+ (f"\nWHERE {where_clause}" if where_clause else "")
|
|
270
|
+
+ ";"
|
|
271
|
+
)
|
|
272
|
+
return [
|
|
273
|
+
f"{indent}-- [DBG-PREVIEW] Would have executed:",
|
|
274
|
+
*_format_multiline(indent, preview),
|
|
275
|
+
]
|
|
276
|
+
|
|
277
|
+
return None
|
sql_sp_harness/emit.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Format output files with safety banners and summaries."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from sql_sp_harness.transform import TransformStats
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def debug_banner(parse_errors: list[str], stats: TransformStats) -> str:
|
|
9
|
+
lines = [
|
|
10
|
+
"-- ============================================================================",
|
|
11
|
+
"-- DEBUG HARNESS — DO NOT RUN ON PRODUCTION",
|
|
12
|
+
"-- Generated by sql-sp-harness. DML replaced with SELECT previews; variable traces injected.",
|
|
13
|
+
"-- ============================================================================",
|
|
14
|
+
f"-- DML statements stubbed: {stats.dml_stubbed}",
|
|
15
|
+
f"-- Trace lines added: {stats.traces_added}",
|
|
16
|
+
]
|
|
17
|
+
if parse_errors:
|
|
18
|
+
lines.append("-- PARSE WARNINGS (review manually):")
|
|
19
|
+
for err in parse_errors:
|
|
20
|
+
lines.append(f"-- {err}")
|
|
21
|
+
for w in stats.warnings:
|
|
22
|
+
lines.append(f"-- {w}")
|
|
23
|
+
lines.append("-- ============================================================================")
|
|
24
|
+
lines.append("")
|
|
25
|
+
return "\n".join(lines) + "\n"
|