Files
gsfdc/server/scripts/ensure_database.py
T

36 lines
993 B
Python

"""Create the application database when it does not exist. Connection comes from the environment."""
from urllib.parse import unquote, urlparse
import pymysql
from app.core.config import get_settings
def main() -> None:
parsed = urlparse(get_settings().database_url)
name = parsed.path.lstrip("/")
if not name or not parsed.hostname:
raise SystemExit("DATABASE_URL 未配置")
connection = pymysql.connect(
host=parsed.hostname,
port=parsed.port or 3306,
user=unquote(parsed.username or ""),
password=unquote(parsed.password or ""),
charset="utf8mb4",
connect_timeout=15,
)
try:
with connection.cursor() as cursor:
cursor.execute(
f"CREATE DATABASE IF NOT EXISTS `{name}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"
)
connection.commit()
finally:
connection.close()
print("database ready")
if __name__ == "__main__":
main()