Files
hk4e-gm-clone/core/db.py
T

131 lines
4.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""MySQL 访问 —— 复刻 hk4eGM.Helpers.MySqlHelper + MysqlViewModel。
原程序用到的两张表:
t_player_uid 玩家 UID 列表
t_activity_schedule_config 活动排期(schedule_id, begin_time, end_time, activity_desc)
"""
from __future__ import annotations
import datetime as _dt
from typing import Callable, Dict, List, Optional, Sequence, Tuple
try:
import pymysql
except Exception: # pragma: no cover
pymysql = None
class DbError(Exception):
pass
class DbClient:
def __init__(self, cfg, log: Optional[Callable[[str], None]] = None):
self.cfg = cfg
self.log = log or (lambda m: None)
self._conn = None
# ------------------------------------------------------------------ 连接
def _params(self, database: str) -> dict:
return dict(
host=self.cfg.get("MySQL", "IP地址", "127.0.0.1"),
port=self.cfg.get_int("MySQL", "端口", 3306),
user=self.cfg.get("MySQL", "用户名", "root"),
password=self.cfg.get("MySQL", "密码", ""),
database=database,
charset="utf8mb4",
connect_timeout=6,
read_timeout=20,
autocommit=True,
)
@property
def config_db(self) -> str:
return self.cfg.get("MySQL", "Config数据库名", "db_hk4e_config_gio")
@property
def user_db(self) -> str:
return self.cfg.get("MySQL", "User数据库名", "db_hk4e_user_gio")
@property
def connected(self) -> bool:
try:
if self._conn is None:
return False
self._conn.ping(reconnect=False)
return True
except Exception:
return False
def connect(self, database: Optional[str] = None) -> str:
if pymysql is None:
raise DbError("未安装 pymysql:pip install pymysql")
self.close()
db = database or self.user_db
try:
self._conn = pymysql.connect(**self._params(db))
except Exception as exc:
raise DbError(f"MySQL 连接失败:{exc}")
return "MySQL 连接成功"
def close(self) -> None:
if self._conn is not None:
try:
self._conn.close()
except Exception:
pass
self._conn = None
def _ensure(self) -> None:
if not self.connected:
self.connect()
# ------------------------------------------------------------------ 查询
def query(self, sql: str, args: Optional[Sequence] = None) -> Tuple[List[str], List[tuple]]:
if not self.cfg.mysql_enabled:
raise DbError("MySQL 未启用:在「设置」或 config.ini 里把 启用MySQL 改为 true")
self._ensure()
assert self._conn is not None
with self._conn.cursor() as cur:
cur.execute(sql, args or ())
rows = cur.fetchall()
cols = [d[0] for d in cur.description] if cur.description else []
return cols, list(rows)
def execute(self, sql: str, args: Optional[Sequence] = None) -> int:
if not self.cfg.mysql_enabled:
raise DbError("MySQL 未启用:在「设置」或 config.ini 里把 启用MySQL 改为 true")
self._ensure()
assert self._conn is not None
with self._conn.cursor() as cur:
return cur.execute(sql, args or ())
# ------------------------------------------------------------------ 业务
def player_uids(self) -> List[str]:
_, rows = self.query("select uid from t_player_uid")
return [str(r[0]) for r in rows]
def activities(self) -> List[Dict[str, str]]:
cols, rows = self.query("select * from t_activity_schedule_config")
out = []
for row in rows:
rec = dict(zip(cols, row))
out.append({k: ("" if v is None else str(v)) for k, v in rec.items()})
return out
def save_activity(self, schedule_id: str, begin: str, end: str, desc: str) -> int:
"""原程序 SQL:INSERT ... ON DUPLICATE KEY UPDATE"""
sql = ("INSERT INTO t_activity_schedule_config (schedule_id, begin_time, end_time, activity_desc) "
"VALUES (%s, %s, %s, %s) "
"ON DUPLICATE KEY UPDATE begin_time = VALUES(begin_time), "
"end_time = VALUES(end_time), activity_desc = VALUES(activity_desc)")
return self.execute(sql, (schedule_id, begin, end, desc))
def delete_activity(self, schedule_id: str) -> int:
return self.execute("DELETE FROM t_activity_schedule_config WHERE schedule_id = %s", (schedule_id,))
def update_all_begin_time(self) -> int:
"""把全部活动开始时间设为当天 0 点(原程序 UpdateAllBeginTime)。"""
today = _dt.datetime.now().strftime("%Y-%m-%d 00:00:00")
return self.execute("UPDATE t_activity_schedule_config SET begin_time = %s", (today,))