52 lines
1.6 KiB
Python
52 lines
1.6 KiB
Python
#!/usr/bin/env python3
|
|
"""Check/create the configured DeerFlow MySQL database before Compose starts."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import re
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
import aiomysql
|
|
|
|
from render_runtime import load_env
|
|
|
|
|
|
async def check(path: Path) -> None:
|
|
env = load_env(path)
|
|
host = env["MYSQL_HOST"].strip()
|
|
port = int(env["MYSQL_PORT"])
|
|
user = env["MYSQL_USER"].strip()
|
|
password = env["MYSQL_PASSWORD"]
|
|
database = env["MYSQL_DATABASE"].strip()
|
|
if not re.fullmatch(r"[A-Za-z0-9_]+", database):
|
|
raise RuntimeError("MYSQL_DATABASE 只能包含字母、数字和下划线")
|
|
connection = await aiomysql.connect(host=host, port=port, user=user, password=password, autocommit=True)
|
|
try:
|
|
async with connection.cursor() as cursor:
|
|
await cursor.execute(
|
|
f"CREATE DATABASE IF NOT EXISTS `{database}` "
|
|
"CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"
|
|
)
|
|
await connection.select_db(database)
|
|
async with connection.cursor() as cursor:
|
|
await cursor.execute("SELECT 1")
|
|
assert (await cursor.fetchone())[0] == 1
|
|
finally:
|
|
connection.close()
|
|
|
|
|
|
def main() -> int:
|
|
try:
|
|
asyncio.run(check(Path(sys.argv[1])))
|
|
print("DeerFlow 外部 MySQL 连接检查通过。")
|
|
return 0
|
|
except Exception:
|
|
print("MySQL 预检失败:无法连接或自动创建 DeerFlow 数据库;请检查地址、端口、账号权限和防火墙。", file=sys.stderr)
|
|
return 3
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|