Files
main_plugin_farm/core/dbService.py
T

116 lines
2.6 KiB
Python
Raw Normal View History

2025-11-30 16:45:13 +08:00
import asyncio
from typing import Any
from zhenxun.services.log import logger
from .database import (
CPlantManager,
CUserDB,
CUserItemDB,
CUserPlantCountDB,
CUserPlantDB,
CUserSeedDB,
CUserSignDB,
CUserSoilDB,
CUserStealDB,
g_pDBlocator,
)
2025-10-20 23:24:33 +08:00
class CDBService:
2025-11-30 16:45:13 +08:00
"""
数据库服务管理器
负责初始化和协调所有数据库服务
"""
def __init__(self):
self.m_manager: dict[str, Any] = {}
self.m_bInitialized = False
2025-10-20 23:24:33 +08:00
async def init(self):
2025-11-30 16:45:13 +08:00
if self.m_bInitialized:
logger.warning("真寻农场数据库服务已初始化")
return
m_manager = {
"plant": CPlantManager(),
"user": CUserDB(),
"userSoil": CUserSoilDB(),
"userPlant": CUserPlantDB(),
"userSeed": CUserSeedDB(),
"userItem": CUserItemDB(),
"userSteal": CUserStealDB(),
"userSign": CUserSignDB(),
"userPlantCount": CUserPlantCountDB(),
}
2025-10-20 23:24:33 +08:00
2025-11-30 16:45:13 +08:00
for name, manager in m_manager.items():
g_pDBlocator.register(name, manager)
self.m_manager[name] = manager
2025-10-20 23:24:33 +08:00
2025-11-30 16:45:13 +08:00
tasks = []
for name, manager in self.m_manager.items():
tasks.append(manager.init())
tasks.append(manager.initDB())
2025-10-20 23:24:33 +08:00
2025-11-30 16:45:13 +08:00
await asyncio.gather(*tasks)
2025-10-20 23:24:33 +08:00
2025-11-30 16:45:13 +08:00
g_pDBlocator.markInitialized()
self.m_bInitialized = True
2025-10-20 23:24:33 +08:00
2025-11-30 16:45:13 +08:00
logger.debug("真寻农场数据库服务初始化完成")
2025-10-20 23:24:33 +08:00
2025-11-30 16:45:13 +08:00
async def cleanup(self):
task = []
2025-10-20 23:24:33 +08:00
2025-11-30 16:45:13 +08:00
for manager in self.m_manager.values():
if hasattr(manager, "cleanup"):
task.append(manager.cleanup())
2025-10-20 23:24:33 +08:00
2025-11-30 16:45:13 +08:00
await asyncio.gather(*task)
self.m_manager.clear()
self.m_bInitialized = False
2025-10-20 23:24:33 +08:00
2025-11-30 16:45:13 +08:00
@property
def plant(self):
return self.m_manager["plant"]
2025-11-30 16:45:13 +08:00
@property
def user(self):
return self.m_manager["user"]
@property
def userSoil(self):
return self.m_manager["userSoil"]
@property
def userPlant(self):
return self.m_manager["userPlant"]
@property
def userSeed(self):
return self.m_manager["userSeed"]
@property
def userItem(self):
return self.m_manager["userItem"]
@property
def userSteal(self):
return self.m_manager["userSteal"]
@property
def userSign(self):
return self.m_manager["userSign"]
@property
def userPlantCount(self):
return self.m_manager["userPlantCount"]
@property
def initialized(self) -> bool:
return self.m_bInitialized
2025-10-20 23:24:33 +08:00
g_pDBService = CDBService()