52 lines
1.6 KiB
Python
52 lines
1.6 KiB
Python
"""Execute a UTF-8 SQL file via mysql CLI (avoids Windows pipe encoding loss)."""
|
|||
|
|
|
||
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
import subprocess
|
||
|
|
import sys
|
||
|
|
from pathlib import Path
|
||
|
|
|
||
|
|
ROOT = Path(__file__).resolve().parents[2]
|
||
|
|
|
||
|
|
|
||
|
|
def _load_env_password() -> tuple[str, str, str]:
|
||
|
|
host, user, password = "127.0.0.1", "root", ""
|
||
|
|
env_path = ROOT / ".env"
|
||
|
|
if env_path.exists():
|
||
|
|
for line in env_path.read_text(encoding="utf-8").splitlines():
|
||
|
|
line = line.strip()
|
||
|
|
if line.startswith("MYSQL_HOST="):
|
||
|
|
host = line.split("=", 1)[1].strip()
|
||
|
|
elif line.startswith("MYSQL_USER="):
|
||
|
|
user = line.split("=", 1)[1].strip()
|
||
|
|
elif line.startswith("MYSQL_PASSWORD="):
|
||
|
|
password = line.split("=", 1)[1].strip()
|
||
|
|
return host, user, password
|
||
|
|
|
||
|
|
|
||
|
|
def main() -> None:
|
||
|
|
if len(sys.argv) != 2:
|
||
|
|
raise SystemExit("usage: run_sql_file.py <path.sql>")
|
||
|
|
path = Path(sys.argv[1]).resolve()
|
||
|
|
if not path.is_file():
|
||
|
|
raise SystemExit(f"file not found: {path}")
|
||
|
|
host, user, password = _load_env_password()
|
||
|
|
if not password:
|
||
|
|
raise SystemExit("MYSQL_PASSWORD missing in .env")
|
||
|
|
sql = path.read_text(encoding="utf-8")
|
||
|
|
proc = subprocess.run(
|
||
|
|
["mysql", "-h", host, "-u", user, f"-p{password}", "--default-character-set=utf8mb4"],
|
||
|
|
input=sql.encode("utf-8"),
|
||
|
|
capture_output=True,
|
||
|
|
)
|
||
|
|
if proc.stdout:
|
||
|
|
sys.stdout.buffer.write(proc.stdout)
|
||
|
|
if proc.returncode != 0:
|
||
|
|
if proc.stderr:
|
||
|
|
sys.stderr.buffer.write(proc.stderr)
|
||
|
|
raise SystemExit(proc.returncode)
|
||
|
|
|
||
|
|
|
||
|
|
if __name__ == "__main__":
|
||
|
|
main()
|