#!/usr/bin/env python3 """ Normalize a schema document that contains multiple CREATE TABLE blocks but may miss semicolons between statements. Usage: python fix_schema_sql.py input.sql > fixed.sql python fix_schema_sql.py input.sql output.sql """ from __future__ import annotations import re import sys from pathlib import Path CREATE_TABLE_RE = re.compile(r"(^|\n)(\s*CREATE\s+TABLE\b)", re.IGNORECASE) def normalize_schema(text: str) -> str: text = text.replace("\r\n", "\n") pieces = [] last = 0 first = True for match in CREATE_TABLE_RE.finditer(text): start = match.start(2) if first: first = False last = start continue chunk = text[last:start] stripped = chunk.rstrip() if stripped and not stripped.endswith(";"): chunk = stripped + ";\n\n" pieces.append(chunk) last = start tail = text[last:] pieces.append(tail) return "".join(pieces) def main() -> int: if len(sys.argv) not in (2, 3): print("usage: fix_schema_sql.py [output.sql]", file=sys.stderr) return 2 src = Path(sys.argv[1]) fixed = normalize_schema(src.read_text(encoding="utf-8")) if len(sys.argv) == 3: Path(sys.argv[2]).write_text(fixed, encoding="utf-8") else: sys.stdout.write(fixed) return 0 if __name__ == "__main__": raise SystemExit(main())