refactor(room_store): 将上次马名存储从内存迁移至数据库
- 移除内存字典 `_last_horse_names`,改为使用 SQLite 表 `user_horse_names` - 修改 `get_last_horse_name` 和 `set_last_horse_name` 方法以操作数据库 - 提升数据持久化能力,防止重启后数据丢失
This commit is contained in:
@@ -13,7 +13,6 @@ class RoomStore:
|
||||
self.config = config
|
||||
self.rooms: dict[str, Room] = {}
|
||||
self._locks: dict[str, asyncio.Lock] = {}
|
||||
self._last_horse_names: dict[str, str] = {}
|
||||
self.db_path = Path(config.RACE_DB_FILE)
|
||||
self.db_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self._init_db()
|
||||
@@ -48,6 +47,13 @@ class RoomStore:
|
||||
)
|
||||
""")
|
||||
|
||||
cursor.execute("""
|
||||
CREATE TABLE IF NOT EXISTS user_horse_names (
|
||||
user_id TEXT PRIMARY KEY,
|
||||
horse_name TEXT NOT NULL
|
||||
)
|
||||
""")
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
@@ -74,10 +80,22 @@ class RoomStore:
|
||||
del self.rooms[scope]
|
||||
|
||||
def get_last_horse_name(self, user_id: str) -> Optional[str]:
|
||||
return self._last_horse_names.get(user_id)
|
||||
conn = sqlite3.connect(self.db_path)
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("SELECT horse_name FROM user_horse_names WHERE user_id = ?", (user_id,))
|
||||
row = cursor.fetchone()
|
||||
conn.close()
|
||||
return row[0] if row else None
|
||||
|
||||
def set_last_horse_name(self, user_id: str, horse_name: str):
|
||||
self._last_horse_names[user_id] = horse_name
|
||||
conn = sqlite3.connect(self.db_path)
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(
|
||||
"INSERT OR REPLACE INTO user_horse_names (user_id, horse_name) VALUES (?, ?)",
|
||||
(user_id, horse_name),
|
||||
)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
def _save_snapshot(self, room: Room):
|
||||
"""Save room snapshot to database."""
|
||||
|
||||
Reference in New Issue
Block a user