apply_sql_file.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/env python3
  2. """Apply one UpdateScripts SQL file against aidopdev."""
  3. from __future__ import annotations
  4. import argparse
  5. import re
  6. from pathlib import Path
  7. import pymysql
  8. from pymysql.constants import CLIENT
  9. ROOT = Path(__file__).resolve().parents[4]
  10. CONFIG = ROOT / "server" / "Admin.NET.Application" / "Configuration" / "Database.json"
  11. def connect() -> pymysql.Connection:
  12. raw = CONFIG.read_text(encoding="utf-8-sig")
  13. value = next(
  14. item
  15. for item in re.findall(r'(?m)^\s*"ConnectionString"\s*:\s*"([^"]+)"', raw)
  16. if "Database=aidopdev" in item
  17. )
  18. parts = {
  19. item.split("=", 1)[0].strip().lower(): item.split("=", 1)[1].strip()
  20. for item in value.split(";")
  21. if "=" in item
  22. }
  23. return pymysql.connect(
  24. host=parts["server"],
  25. port=int(parts["port"]),
  26. user=parts["uid"],
  27. password=parts["pwd"],
  28. database=parts["database"],
  29. charset="utf8mb4",
  30. autocommit=True,
  31. client_flag=CLIENT.MULTI_STATEMENTS,
  32. cursorclass=pymysql.cursors.DictCursor,
  33. )
  34. def main() -> None:
  35. parser = argparse.ArgumentParser()
  36. parser.add_argument("sql_file")
  37. args = parser.parse_args()
  38. path = Path(args.sql_file)
  39. if not path.is_absolute():
  40. path = ROOT / path
  41. sql = path.read_text(encoding="utf-8")
  42. conn = connect()
  43. try:
  44. with conn.cursor() as cur:
  45. cur.execute(sql)
  46. while True:
  47. rows = cur.fetchall()
  48. if rows:
  49. print(rows)
  50. if not cur.nextset():
  51. break
  52. finally:
  53. conn.close()
  54. if __name__ == "__main__":
  55. main()