44 lines
1.4 KiB
Python
44 lines
1.4 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
from sql_guard import validate_sql
|
|
|
|
|
|
def read_sql(args: argparse.Namespace) -> str:
|
|
if args.file:
|
|
return Path(args.file).read_text(encoding="utf-8")
|
|
if args.sql:
|
|
return " ".join(args.sql)
|
|
if not sys.stdin.isatty():
|
|
return sys.stdin.read()
|
|
raise SystemExit("Provide SQL as arguments, --file, or stdin")
|
|
|
|
|
|
def main() -> int:
|
|
parser = argparse.ArgumentParser(description="Validate Spark SQL against a safe allowlist.")
|
|
parser.add_argument("sql", nargs="*", help="SQL string; omitted when using --file or stdin")
|
|
parser.add_argument("--file", help="Read SQL from a UTF-8 file")
|
|
parser.add_argument("--json", action="store_true", help="Emit machine-readable JSON")
|
|
parser.add_argument("--allow-overwrite", action="store_true", help="Allow INSERT OVERWRITE ... SELECT")
|
|
args = parser.parse_args()
|
|
|
|
result = validate_sql(read_sql(args), allow_overwrite=args.allow_overwrite)
|
|
if args.json:
|
|
print(json.dumps(result.as_dict(), ensure_ascii=False))
|
|
elif result.status == "PASS":
|
|
print(f"PASS - first_keyword={result.first_keyword}")
|
|
else:
|
|
print(f"FAIL - first_keyword={result.first_keyword} reason={result.reason}")
|
|
return 0 if result.status == "PASS" else 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|