refactor(db): 修正SQLAlchemy异步操作调用方式
移除session.add()方法的不必要await调用,修正异步数据库操作模式。主要变更包括: - 将 `await session.add()` 统一改为 `session.add()` - 修正部分函数调用为异步版本(如消息查询函数) - 重构SQLAlchemyTransaction为完全异步实现 - 重写napcat_adapter_plugin数据库层以符合异步规范 - 添加aiomysql和aiosqlite依赖支持
This commit is contained in:
@@ -32,21 +32,32 @@ class DatabaseProxy:
|
||||
|
||||
|
||||
class SQLAlchemyTransaction:
|
||||
"""SQLAlchemy事务上下文管理器"""
|
||||
"""SQLAlchemy 异步事务上下文管理器 (兼容旧代码示例,推荐直接使用 get_db_session)。"""
|
||||
|
||||
def __init__(self):
|
||||
self._ctx = None
|
||||
self.session = None
|
||||
|
||||
def __enter__(self):
|
||||
self.session = get_db_session()
|
||||
async def __aenter__(self):
|
||||
# get_db_session 是一个 async contextmanager
|
||||
self._ctx = get_db_session()
|
||||
self.session = await self._ctx.__aenter__()
|
||||
return self.session
|
||||
|
||||
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||
if exc_type is None:
|
||||
self.await session.commit()
|
||||
else:
|
||||
self.session.rollback()
|
||||
self.session.close()
|
||||
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
||||
try:
|
||||
if self.session:
|
||||
if exc_type is None:
|
||||
try:
|
||||
await self.session.commit()
|
||||
except Exception:
|
||||
await self.session.rollback()
|
||||
raise
|
||||
else:
|
||||
await self.session.rollback()
|
||||
finally:
|
||||
if self._ctx:
|
||||
await self._ctx.__aexit__(exc_type, exc_val, exc_tb)
|
||||
|
||||
|
||||
# 创建全局数据库代理实例
|
||||
|
||||
@@ -168,7 +168,7 @@ async def db_query(
|
||||
|
||||
# 创建新记录
|
||||
new_record = model_class(**data)
|
||||
await session.add(new_record)
|
||||
session.add(new_record)
|
||||
await session.flush() # 获取自动生成的ID
|
||||
|
||||
# 转换为字典格式返回
|
||||
@@ -295,7 +295,7 @@ async def db_save(
|
||||
|
||||
# 创建新记录
|
||||
new_record = model_class(**data)
|
||||
await session.add(new_record)
|
||||
session.add(new_record)
|
||||
await session.flush()
|
||||
|
||||
# 转换为字典格式返回
|
||||
|
||||
Reference in New Issue
Block a user