@vstlmkh/designing-databases 0.0.0-stage → 1.3.0

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,481 @@
1
+ #!/usr/bin/env python3
2
+ """Audit a SQL schema (DDL) for structural defects that cost performance or integrity.
3
+
4
+ Input: one or more files containing CREATE TABLE / CREATE INDEX / ALTER TABLE
5
+ statements — a `pg_dump --schema-only`, a `mysqldump --no-data`, or plain
6
+ migration SQL. Reads stdin when no file is given.
7
+
8
+ Usage:
9
+ python3 schema_audit.py schema.sql [more.sql ...] [--engine postgres|mysql]
10
+ [--format text|json] [--min-severity info|warn|error]
11
+
12
+ Exit codes: 0 = no ERROR findings, 1 = at least one ERROR, 2 = usage/parse error.
13
+ Findings go to stdout; diagnostics to stderr.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import argparse
18
+ import json
19
+ import re
20
+ import sys
21
+ from dataclasses import dataclass, field, asdict
22
+
23
+ from sqlparse_lite import paren_body, split_columns, split_statements, unquote
24
+
25
+ SEVERITY_ORDER = {"info": 0, "warn": 1, "error": 2}
26
+
27
+ # Column-name heuristics. Kept explicit so a reader can see exactly what fires.
28
+ MONEY_WORDS = ("price", "amount", "total", "balance", "cost", "fee", "salary", "sum")
29
+ APPROX_TYPES = ("float", "double", "real")
30
+ SOFT_DELETE_COLS = ("deleted_at", "is_deleted", "deleted", "archived_at")
31
+ EAV_VALUE_COLS = ("value", "attribute_value", "val", "attr_value")
32
+ EAV_KEY_COLS = ("attribute", "attribute_name", "attr", "attr_name", "key", "property")
33
+
34
+
35
+ @dataclass
36
+ class Column:
37
+ name: str
38
+ type: str
39
+ raw: str
40
+ not_null: bool
41
+ line: int
42
+
43
+
44
+ @dataclass
45
+ class Table:
46
+ name: str
47
+ line: int
48
+ columns: dict[str, Column] = field(default_factory=dict)
49
+ pk: list[str] = field(default_factory=list)
50
+ fks: list[dict] = field(default_factory=list)
51
+ indexes: list[dict] = field(default_factory=list)
52
+ uniques: list[list[str]] = field(default_factory=list)
53
+
54
+
55
+ @dataclass
56
+ class Finding:
57
+ id: str
58
+ severity: str
59
+ table: str
60
+ object: str
61
+ message: str
62
+ fix: str
63
+ line: int
64
+
65
+
66
+ # --------------------------------------------------------------------------- parse
67
+
68
+ CREATE_TABLE_RE = re.compile(
69
+ r"^\s*CREATE\s+(?:UNLOGGED\s+|TEMP(?:ORARY)?\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?([^\s(]+)",
70
+ re.I,
71
+ )
72
+ CREATE_INDEX_RE = re.compile(
73
+ r"^\s*CREATE\s+(UNIQUE\s+)?INDEX\s+(?:CONCURRENTLY\s+)?(?:IF\s+NOT\s+EXISTS\s+)?"
74
+ r"([^\s(]+)?\s*ON\s+(?:ONLY\s+)?([^\s(]+)",
75
+ re.I,
76
+ )
77
+ ALTER_TABLE_RE = re.compile(r"^\s*ALTER\s+TABLE\s+(?:ONLY\s+)?([^\s]+)", re.I)
78
+ FK_RE = re.compile(
79
+ r"FOREIGN\s+KEY\s*\(([^)]*)\)\s*REFERENCES\s+([^\s(]+)\s*\(([^)]*)\)", re.I
80
+ )
81
+ INLINE_REF_RE = re.compile(r"\bREFERENCES\s+([^\s(]+)\s*\(([^)]*)\)", re.I)
82
+ PK_INLINE_RE = re.compile(r"\bPRIMARY\s+KEY\b", re.I)
83
+ PK_TABLE_RE = re.compile(r"^\s*(?:CONSTRAINT\s+\S+\s+)?PRIMARY\s+KEY\s*\(([^)]*)\)", re.I)
84
+ UNIQUE_TABLE_RE = re.compile(r"^\s*(?:CONSTRAINT\s+\S+\s+)?UNIQUE\s*\(([^)]*)\)", re.I)
85
+ # A type expression: base word, optional modifier words (double precision,
86
+ # character varying, int unsigned), optional (n[,m]), optional time-zone tail,
87
+ # optional array suffix. Anything after that is constraints/defaults.
88
+ TYPE_RE = re.compile(
89
+ r"^\s*([A-Za-z_][\w\.]*"
90
+ r"(?:\s+(?:precision|varying|unsigned|signed|zerofill))*"
91
+ r"(?:\s*\([^)]*\))?"
92
+ r"(?:\s+(?:with|without)\s+time\s+zone)?"
93
+ r"(?:\s*\[\s*\])*)",
94
+ re.I,
95
+ )
96
+ CONSTRAINT_KEYWORDS = ("primary", "unique", "foreign", "constraint", "check", "key", "index", "exclude")
97
+
98
+
99
+ def norm_name(raw: str) -> str:
100
+ """`public.users` / "Users" / `users` -> users (lowercased, schema dropped)."""
101
+ parts = [unquote(p) for p in raw.strip().rstrip(",").split(".")]
102
+ return parts[-1].lower()
103
+
104
+
105
+ def col_list(raw: str) -> list[str]:
106
+ cols = []
107
+ for part in split_columns(raw):
108
+ part = part.strip()
109
+ part = re.sub(r"\s+(ASC|DESC|NULLS\s+FIRST|NULLS\s+LAST)$", "", part, flags=re.I)
110
+ part = re.sub(r"\s+\S+_ops$", "", part) # PostgreSQL opclass
111
+ part = re.sub(r"\(\d+\)$", "", part) # MySQL prefix length
112
+ if part:
113
+ cols.append(unquote(part).lower())
114
+ return cols
115
+
116
+
117
+ def parse(sql: str, line_offset: int, tables: dict[str, Table]) -> None:
118
+ for stmt in split_statements(sql):
119
+ line = stmt.line + line_offset
120
+ head = stmt.text.lstrip()
121
+ m = CREATE_TABLE_RE.match(head)
122
+ if m:
123
+ name = norm_name(m.group(1))
124
+ body, _ = paren_body(stmt.text, m.end(1))
125
+ table = tables.setdefault(name, Table(name=name, line=line))
126
+ table.line = line
127
+ for item in split_columns(body):
128
+ low = item.lstrip().lower()
129
+ first = low.split()[0] if low.split() else ""
130
+ if first in CONSTRAINT_KEYWORDS:
131
+ pk = PK_TABLE_RE.match(item)
132
+ if pk:
133
+ table.pk = col_list(pk.group(1))
134
+ uq = UNIQUE_TABLE_RE.match(item)
135
+ if uq:
136
+ table.uniques.append(col_list(uq.group(1)))
137
+ fk = FK_RE.search(item)
138
+ if fk:
139
+ table.fks.append(
140
+ {
141
+ "columns": col_list(fk.group(1)),
142
+ "ref_table": norm_name(fk.group(2)),
143
+ "ref_columns": col_list(fk.group(3)),
144
+ "line": line,
145
+ }
146
+ )
147
+ continue
148
+ parts = item.split(None, 1)
149
+ if len(parts) < 2:
150
+ continue
151
+ cname = unquote(parts[0]).lower()
152
+ tmatch = TYPE_RE.match(parts[1])
153
+ ctype = (tmatch.group(1) if tmatch else parts[1]).strip().lower()
154
+ column = Column(
155
+ name=cname,
156
+ type=ctype,
157
+ raw=item,
158
+ not_null=bool(re.search(r"\bNOT\s+NULL\b", item, re.I)),
159
+ line=line,
160
+ )
161
+ table.columns[cname] = column
162
+ if PK_INLINE_RE.search(item):
163
+ table.pk = [cname]
164
+ if re.search(r"\bUNIQUE\b", item, re.I):
165
+ table.uniques.append([cname])
166
+ ref = INLINE_REF_RE.search(item)
167
+ if ref:
168
+ table.fks.append(
169
+ {
170
+ "columns": [cname],
171
+ "ref_table": norm_name(ref.group(1)),
172
+ "ref_columns": col_list(ref.group(2)),
173
+ "line": line,
174
+ }
175
+ )
176
+ continue
177
+
178
+ m = CREATE_INDEX_RE.match(head)
179
+ if m:
180
+ tname = norm_name(m.group(3))
181
+ body, _ = paren_body(stmt.text, m.end(3))
182
+ table = tables.setdefault(tname, Table(name=tname, line=line))
183
+ cols = col_list(body)
184
+ where = re.search(r"\)\s*(?:INCLUDE\s*\([^)]*\)\s*)?WHERE\s+(.+)$", stmt.text, re.I | re.S)
185
+ idx = {
186
+ "name": norm_name(m.group(2) or "(unnamed)"),
187
+ "columns": cols,
188
+ "unique": bool(m.group(1)),
189
+ "partial": bool(where),
190
+ "method": (re.search(r"USING\s+(\w+)", stmt.text, re.I).group(1).lower()
191
+ if re.search(r"USING\s+(\w+)", stmt.text, re.I) else "btree"),
192
+ "line": line,
193
+ }
194
+ table.indexes.append(idx)
195
+ if idx["unique"]:
196
+ table.uniques.append(cols)
197
+ continue
198
+
199
+ m = ALTER_TABLE_RE.match(head)
200
+ if m:
201
+ tname = norm_name(m.group(1))
202
+ table = tables.setdefault(tname, Table(name=tname, line=line))
203
+ for fk in FK_RE.finditer(stmt.text):
204
+ table.fks.append(
205
+ {
206
+ "columns": col_list(fk.group(1)),
207
+ "ref_table": norm_name(fk.group(2)),
208
+ "ref_columns": col_list(fk.group(3)),
209
+ "line": line,
210
+ }
211
+ )
212
+ pk = re.search(r"ADD\s+(?:CONSTRAINT\s+\S+\s+)?PRIMARY\s+KEY\s*\(([^)]*)\)", stmt.text, re.I)
213
+ if pk:
214
+ table.pk = col_list(pk.group(1))
215
+ uq = re.search(r"ADD\s+(?:CONSTRAINT\s+\S+\s+)?UNIQUE\s*\(([^)]*)\)", stmt.text, re.I)
216
+ if uq:
217
+ table.uniques.append(col_list(uq.group(1)))
218
+ for add_col in re.finditer(r"ADD\s+COLUMN\s+(\S+)\s+([^,;]+)", stmt.text, re.I):
219
+ cname = unquote(add_col.group(1)).lower()
220
+ tmatch = TYPE_RE.match(add_col.group(2))
221
+ table.columns.setdefault(
222
+ cname,
223
+ Column(
224
+ name=cname,
225
+ type=(tmatch.group(1) if tmatch else add_col.group(2)).strip().lower(),
226
+ raw=add_col.group(0),
227
+ not_null=bool(re.search(r"\bNOT\s+NULL\b", add_col.group(2), re.I)),
228
+ line=line,
229
+ ),
230
+ )
231
+
232
+
233
+ # --------------------------------------------------------------------------- checks
234
+
235
+
236
+ def index_covers(table: Table, column: str) -> bool:
237
+ """True when some index/unique/PK can drive a lookup on `column` (leftmost)."""
238
+ if table.pk and table.pk[0] == column:
239
+ return True
240
+ for cols in table.uniques:
241
+ if cols and cols[0] == column:
242
+ return True
243
+ for idx in table.indexes:
244
+ if idx["columns"] and idx["columns"][0] == column and not idx["partial"]:
245
+ return True
246
+ return False
247
+
248
+
249
+ def is_random_uuid_pk(col: Column) -> bool:
250
+ t = col.type.replace(" ", "")
251
+ if t.startswith(("char(36)", "varchar(36)", "character(36)", "charactervarying(36)")):
252
+ return True
253
+ if t in ("uuid", "binary(16)"):
254
+ return True
255
+ return False
256
+
257
+
258
+ def audit(tables: dict[str, Table], engine: str) -> list[Finding]:
259
+ out: list[Finding] = []
260
+
261
+ def add(fid, sev, table, obj, msg, fix, line):
262
+ out.append(Finding(fid, sev, table, obj, msg, fix, line))
263
+
264
+ for name, t in sorted(tables.items()):
265
+ if not t.columns:
266
+ continue # index-only reference to a table defined elsewhere
267
+
268
+ # --- primary keys
269
+ if not t.pk:
270
+ add("PK001", "error", name, "", "Table has no PRIMARY KEY.",
271
+ "InnoDB builds a hidden 6-byte clustered key you cannot use; PostgreSQL "
272
+ "loses replica identity for logical replication. Add an explicit key.", t.line)
273
+ else:
274
+ pk_cols = [t.columns.get(c) for c in t.pk if t.columns.get(c)]
275
+ if len(pk_cols) == 1:
276
+ c = pk_cols[0]
277
+ if is_random_uuid_pk(c) and "default" in c.raw.lower() and re.search(
278
+ r"uuid_generate_v4|gen_random_uuid|uuid\(\)", c.raw, re.I
279
+ ):
280
+ add("PK002", "error", name, c.name,
281
+ f"Primary key `{c.name}` defaults to a random UUIDv4.",
282
+ "Random keys split B+tree leaf pages on every insert (InnoDB: the "
283
+ "clustered index IS the table). Use BIGINT identity, or UUIDv7/ULID "
284
+ "stored as uuid/BINARY(16) if IDs must be non-enumerable.", c.line)
285
+ elif is_random_uuid_pk(c):
286
+ add("PK003", "warn", name, c.name,
287
+ f"Primary key `{c.name}` is a UUID-shaped type.",
288
+ "Confirm the generator is time-ordered (UUIDv7/ULID). UUIDv4 causes "
289
+ "page splits and inflates every secondary index.", c.line)
290
+ if c.type.replace(" ", "").startswith(("char(36)", "varchar(36)", "charactervarying(36)")):
291
+ add("PK004", "warn", name, c.name,
292
+ f"Primary key `{c.name}` is a 36-byte text UUID.",
293
+ "Every secondary index stores the PK (InnoDB) — 36 bytes vs 16 for "
294
+ "uuid/BINARY(16). Store UUIDs in a native binary type.", c.line)
295
+ if re.match(r"^(int|integer|int4|serial|mediumint|smallint)\b", c.type):
296
+ add("PK005", "info", name, c.name,
297
+ f"Primary key `{c.name}` is 32-bit ({c.type}); ceiling ~2.1e9 rows.",
298
+ "Widening a PK later rewrites the table and every FK. Use BIGINT now "
299
+ "unless the row count is provably bounded.", c.line)
300
+
301
+ # --- foreign keys
302
+ for fk in t.fks:
303
+ child = fk["columns"][0] if fk["columns"] else ""
304
+ if child and not index_covers(t, child):
305
+ if engine == "mysql":
306
+ msg_fix = (f"InnoDB will silently create a single-column index named after "
307
+ f"the constraint — rarely the one the queries need. Declare it "
308
+ f"explicitly, widened for the real access path: "
309
+ f"ALTER TABLE {name} ADD INDEX idx_{name}_{child} ({child}), "
310
+ f"ALGORITHM=INPLACE, LOCK=NONE;")
311
+ else:
312
+ msg_fix = (f"PostgreSQL does not index FK children. Every parent DELETE or "
313
+ f"key UPDATE then scans {name} while holding locks. "
314
+ f"CREATE INDEX CONCURRENTLY idx_{name}_{child} ON {name} ({child});")
315
+ add("FK001", "error" if engine == "postgres" else "warn", name, child,
316
+ f"Foreign key column `{child}` has no index with it as the leftmost column.",
317
+ msg_fix, fk["line"])
318
+ parent = tables.get(fk["ref_table"])
319
+ if parent and fk["ref_columns"]:
320
+ pcol = parent.columns.get(fk["ref_columns"][0])
321
+ ccol = t.columns.get(child)
322
+ if pcol and ccol:
323
+ pbase = re.split(r"[ (]", pcol.type)[0]
324
+ cbase = re.split(r"[ (]", ccol.type)[0]
325
+ ints = {"int", "integer", "int4", "serial", "bigint", "int8", "bigserial", "smallint"}
326
+ if pbase != cbase and not (pbase in ints and cbase in ints and pbase == cbase):
327
+ if pbase in ints and cbase in ints:
328
+ add("FK002", "error", name, child,
329
+ f"FK `{name}.{child}` is {ccol.type} but "
330
+ f"{parent.name}.{pcol.name} is {pcol.type}.",
331
+ "Width mismatch overflows on large parents and can force an "
332
+ "implicit cast that disables index-driven joins. Match the types.",
333
+ fk["line"])
334
+ else:
335
+ add("FK003", "warn", name, child,
336
+ f"FK `{name}.{child}` ({ccol.type}) and parent "
337
+ f"{parent.name}.{pcol.name} ({pcol.type}) have different types.",
338
+ "Mismatched join types prevent index seeks. Align them.", fk["line"])
339
+
340
+ # --- indexes
341
+ all_keys = [(i["name"], i["columns"], i["partial"], i["line"]) for i in t.indexes]
342
+ for i, (n1, c1, p1, l1) in enumerate(all_keys):
343
+ for n2, c2, p2, _ in all_keys:
344
+ if n1 == n2 or p1 or p2 or not c1 or not c2:
345
+ continue
346
+ if c1 == c2 and n1 > n2:
347
+ add("IDX001", "warn", name, n1,
348
+ f"Index `{n1}` duplicates `{n2}` ({', '.join(c1)}).",
349
+ "Drop one. Every write maintains both.", l1)
350
+ elif len(c1) < len(c2) and c2[: len(c1)] == c1:
351
+ add("IDX002", "warn", name, n1,
352
+ f"Index `{n1}` ({', '.join(c1)}) is a leftmost prefix of "
353
+ f"`{n2}` ({', '.join(c2)}).",
354
+ f"The wider index already serves those queries. Drop `{n1}` after "
355
+ "confirming zero scans on primary AND replicas.", l1)
356
+
357
+ # --- columns
358
+ non_pk = [c for c in t.columns.values() if c.name not in t.pk]
359
+ nullable = [c for c in non_pk if not c.not_null]
360
+ if non_pk and len(nullable) == len(non_pk) and len(non_pk) >= 3:
361
+ add("COL001", "warn", name, "",
362
+ "No column on this table is NOT NULL.",
363
+ "Nullability is a business statement. Mandate NOT NULL unless a requirement "
364
+ "explicitly allows the unknown value; NULLs break = comparisons and aggregates.",
365
+ t.line)
366
+
367
+ for c in t.columns.values():
368
+ base = re.split(r"[ (]", c.type)[0]
369
+ if base in APPROX_TYPES and any(w in c.name for w in MONEY_WORDS):
370
+ add("COL002", "error", name, c.name,
371
+ f"Money-like column `{c.name}` uses approximate type {c.type}.",
372
+ "Binary floats cannot represent 0.10 exactly; sums drift. Use "
373
+ "NUMERIC/DECIMAL(p,s), or an integer count of minor units.", c.line)
374
+ if engine == "postgres" and base in ("timestamp", "datetime") and "with time zone" not in c.type:
375
+ add("COL003", "warn", name, c.name,
376
+ f"`{c.name}` is {c.type} (no time zone).",
377
+ "timestamp without time zone silently reinterprets values per session "
378
+ "TimeZone. Use TIMESTAMPTZ.", c.line)
379
+ if engine == "mysql" and base == "datetime":
380
+ add("COL004", "info", name, c.name,
381
+ f"`{c.name}` is DATETIME.",
382
+ "DATETIME has no time-zone conversion; TIMESTAMP converts to/from UTC "
383
+ "with the session zone. Pick deliberately and store UTC.", c.line)
384
+ if base in ("json", "jsonb") and not any(
385
+ c.name in idx["columns"] or idx["method"] in ("gin", "gist") for idx in t.indexes
386
+ ):
387
+ add("COL005", "info", name, c.name,
388
+ f"`{c.name}` is {base} with no supporting index.",
389
+ "Filtering inside a document is a full scan. Add a GIN index for "
390
+ "containment (@>) or an expression index on the hot path.", c.line)
391
+ if base == "enum":
392
+ add("COL006", "info", name, c.name,
393
+ f"`{c.name}` is an ENUM.",
394
+ "Adding a value is a schema migration, and MySQL reorders silently on "
395
+ "mid-list inserts. A lookup table or a CHECK constraint is cheaper to evolve.",
396
+ c.line)
397
+
398
+ # --- antipatterns
399
+ cols_lower = set(t.columns)
400
+ if cols_lower & set(EAV_KEY_COLS) and cols_lower & set(EAV_VALUE_COLS) and len(t.columns) <= 7:
401
+ add("AP001", "warn", name, "",
402
+ "Table shape looks like Entity-Attribute-Value.",
403
+ "EAV cannot carry foreign keys, types or ranges; reading one entity needs N "
404
+ "self-joins. Use real columns, or a JSONB/JSON column with an index on the "
405
+ "queried paths.", t.line)
406
+
407
+ for sd in SOFT_DELETE_COLS:
408
+ if sd in t.columns:
409
+ has_partial = any(i["partial"] for i in t.indexes)
410
+ add("AP002", "info", name, sd,
411
+ f"Soft-delete column `{sd}` present.",
412
+ ("Every query must filter it, and full indexes carry dead rows. Consider "
413
+ f"partial indexes (… WHERE {sd} IS NULL) on the hot paths."
414
+ if not has_partial else
415
+ f"Confirm all hot-path indexes are partial on {sd} and that the ORM "
416
+ "default scope actually applies."), t.columns[sd].line)
417
+ break
418
+
419
+ return out
420
+
421
+
422
+ # --------------------------------------------------------------------------- output
423
+
424
+
425
+ def render_text(findings: list[Finding], tables: dict[str, Table]) -> str:
426
+ lines = [f"Parsed {len(tables)} table(s); {len(findings)} finding(s).", ""]
427
+ if not findings:
428
+ lines.append("No findings at the requested severity.")
429
+ return "\n".join(lines)
430
+ order = {"error": 0, "warn": 1, "info": 2}
431
+ for f in sorted(findings, key=lambda x: (order[x.severity], x.table, x.id)):
432
+ target = f"{f.table}.{f.object}" if f.object else f.table
433
+ lines.append(f"[{f.severity.upper():5}] {f.id} line {f.line} {target}")
434
+ lines.append(f" {f.message}")
435
+ lines.append(f" FIX: {f.fix}")
436
+ lines.append("")
437
+ return "\n".join(lines)
438
+
439
+
440
+ def main(argv=None) -> int:
441
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
442
+ ap.add_argument("files", nargs="*", help="SQL DDL files; omit to read stdin")
443
+ ap.add_argument("--engine", choices=["postgres", "mysql"], default="postgres")
444
+ ap.add_argument("--format", choices=["text", "json"], default="text")
445
+ ap.add_argument("--min-severity", choices=["info", "warn", "error"], default="info")
446
+ args = ap.parse_args(argv)
447
+
448
+ tables: dict[str, Table] = {}
449
+ try:
450
+ if args.files:
451
+ for path in args.files:
452
+ with open(path, encoding="utf-8", errors="replace") as fh:
453
+ parse(fh.read(), 0, tables)
454
+ else:
455
+ parse(sys.stdin.read(), 0, tables)
456
+ except OSError as exc:
457
+ print(f"ERROR: cannot read input: {exc}", file=sys.stderr)
458
+ return 2
459
+
460
+ if not tables:
461
+ print("ERROR: no CREATE TABLE / CREATE INDEX / ALTER TABLE statements found. "
462
+ "Pass a schema dump (pg_dump --schema-only or mysqldump --no-data).", file=sys.stderr)
463
+ return 2
464
+
465
+ findings = [f for f in audit(tables, args.engine)
466
+ if SEVERITY_ORDER[f.severity] >= SEVERITY_ORDER[args.min_severity]]
467
+
468
+ if args.format == "json":
469
+ print(json.dumps(
470
+ {"engine": args.engine,
471
+ "tables": sorted(tables),
472
+ "findings": [asdict(f) for f in findings]},
473
+ indent=2))
474
+ else:
475
+ print(render_text(findings, tables))
476
+
477
+ return 1 if any(f.severity == "error" for f in findings) else 0
478
+
479
+
480
+ if __name__ == "__main__":
481
+ sys.exit(main())
@@ -0,0 +1,148 @@
1
+ #!/usr/bin/env python3
2
+ """Tolerant SQL statement splitter shared by the bundled auditors.
3
+
4
+ Standard library only. Not a real parser: it strips comments, respects string
5
+ literals, dollar-quoting, backtick/double-quote identifiers and parentheses,
6
+ then yields top-level statements with the line number they start on.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from typing import Iterator, NamedTuple
12
+
13
+
14
+ class Statement(NamedTuple):
15
+ text: str
16
+ line: int
17
+
18
+
19
+ def _strip_comments(sql: str) -> str:
20
+ out = []
21
+ i, n = 0, len(sql)
22
+ while i < n:
23
+ ch = sql[i]
24
+ nxt = sql[i + 1] if i + 1 < n else ""
25
+ if ch in "'\"`":
26
+ quote = ch
27
+ out.append(ch)
28
+ i += 1
29
+ while i < n:
30
+ out.append(sql[i])
31
+ if sql[i] == "\\" and quote == "'":
32
+ if i + 1 < n:
33
+ out.append(sql[i + 1])
34
+ i += 2
35
+ continue
36
+ if sql[i] == quote:
37
+ i += 1
38
+ break
39
+ i += 1
40
+ continue
41
+ if ch == "$": # dollar-quoted body ($$ ... $$ or $tag$ ... $tag$)
42
+ m = re.match(r"\$[A-Za-z_0-9]*\$", sql[i:])
43
+ if m:
44
+ tag = m.group(0)
45
+ end = sql.find(tag, i + len(tag))
46
+ end = n if end == -1 else end + len(tag)
47
+ out.append(sql[i:end])
48
+ i = end
49
+ continue
50
+ if ch == "-" and nxt == "-":
51
+ end = sql.find("\n", i)
52
+ end = n if end == -1 else end
53
+ out.append(" " * (end - i)) # keep line numbering intact
54
+ i = end
55
+ continue
56
+ if ch == "/" and nxt == "*":
57
+ end = sql.find("*/", i + 2)
58
+ end = n if end == -1 else end + 2
59
+ out.append(re.sub(r"[^\n]", " ", sql[i:end]))
60
+ i = end
61
+ continue
62
+ out.append(ch)
63
+ i += 1
64
+ return "".join(out)
65
+
66
+
67
+ def split_statements(sql: str) -> Iterator[Statement]:
68
+ """Yield top-level `;`-terminated statements with their 1-based start line."""
69
+ clean = _strip_comments(sql)
70
+ depth = 0
71
+ buf: list[str] = []
72
+ line = 1
73
+ start_line = 1
74
+ i, n = 0, len(clean)
75
+ while i < n:
76
+ ch = clean[i]
77
+ if ch == "\n":
78
+ line += 1
79
+ if not buf or buf == [""] or "".join(buf).strip() == "":
80
+ start_line = line
81
+ if ch in "'\"`":
82
+ quote = ch
83
+ buf.append(ch)
84
+ i += 1
85
+ while i < n:
86
+ buf.append(clean[i])
87
+ if clean[i] == "\n":
88
+ line += 1
89
+ if clean[i] == quote:
90
+ i += 1
91
+ break
92
+ i += 1
93
+ continue
94
+ if ch == "(":
95
+ depth += 1
96
+ elif ch == ")":
97
+ depth = max(0, depth - 1)
98
+ elif ch == ";" and depth == 0:
99
+ text = "".join(buf).strip()
100
+ if text:
101
+ yield Statement(text, start_line)
102
+ buf = []
103
+ i += 1
104
+ continue
105
+ buf.append(ch)
106
+ i += 1
107
+ tail = "".join(buf).strip()
108
+ if tail:
109
+ yield Statement(tail, start_line)
110
+
111
+
112
+ def split_columns(body: str) -> list[str]:
113
+ """Split the inside of a CREATE TABLE (...) on top-level commas."""
114
+ parts, depth, buf = [], 0, []
115
+ for ch in body:
116
+ if ch == "(":
117
+ depth += 1
118
+ elif ch == ")":
119
+ depth -= 1
120
+ if ch == "," and depth == 0:
121
+ parts.append("".join(buf).strip())
122
+ buf = []
123
+ continue
124
+ buf.append(ch)
125
+ if "".join(buf).strip():
126
+ parts.append("".join(buf).strip())
127
+ return parts
128
+
129
+
130
+ def unquote(ident: str) -> str:
131
+ return ident.strip().strip('`"[]').strip()
132
+
133
+
134
+ def paren_body(text: str, start: int) -> tuple[str, int]:
135
+ """Return the contents of the parenthesis group opening at/after `start`."""
136
+ open_at = text.find("(", start)
137
+ if open_at == -1:
138
+ return "", start
139
+ depth, i = 0, open_at
140
+ while i < len(text):
141
+ if text[i] == "(":
142
+ depth += 1
143
+ elif text[i] == ")":
144
+ depth -= 1
145
+ if depth == 0:
146
+ return text[open_at + 1 : i], i + 1
147
+ i += 1
148
+ return text[open_at + 1 :], len(text)