fix(critical): 修复SQLite事务未提交的严重bug - 在connection_pool.get_session()中添加自动commit
This commit is contained in:
@@ -274,6 +274,8 @@ class CRUDBase:
|
|||||||
session.add(instance)
|
session.add(instance)
|
||||||
await session.flush()
|
await session.flush()
|
||||||
await session.refresh(instance)
|
await session.refresh(instance)
|
||||||
|
# 注意:commit在get_db_session的context manager退出时自动执行
|
||||||
|
# 但为了明确性,这里不需要显式commit
|
||||||
return instance
|
return instance
|
||||||
|
|
||||||
async def update(
|
async def update(
|
||||||
@@ -329,6 +331,7 @@ class CRUDBase:
|
|||||||
await session.flush()
|
await session.flush()
|
||||||
await session.refresh(db_instance)
|
await session.refresh(db_instance)
|
||||||
instance = db_instance
|
instance = db_instance
|
||||||
|
# 注意:commit在get_db_session的context manager退出时自动执行
|
||||||
|
|
||||||
# 清除缓存
|
# 清除缓存
|
||||||
cache_key = f"{self.model_name}:id:{id}"
|
cache_key = f"{self.model_name}:id:{id}"
|
||||||
@@ -369,6 +372,7 @@ class CRUDBase:
|
|||||||
stmt = delete(self.model).where(self.model.id == id)
|
stmt = delete(self.model).where(self.model.id == id)
|
||||||
result = await session.execute(stmt)
|
result = await session.execute(stmt)
|
||||||
success = result.rowcount > 0
|
success = result.rowcount > 0
|
||||||
|
# 注意:commit在get_db_session的context manager退出时自动执行
|
||||||
|
|
||||||
# 清除缓存
|
# 清除缓存
|
||||||
if success:
|
if success:
|
||||||
|
|||||||
@@ -151,6 +151,16 @@ class ConnectionPoolManager:
|
|||||||
|
|
||||||
yield connection_info.session
|
yield connection_info.session
|
||||||
|
|
||||||
|
# 🔧 修复:正常退出时提交事务
|
||||||
|
# 这对SQLite至关重要,因为SQLite没有autocommit
|
||||||
|
if connection_info and connection_info.session:
|
||||||
|
try:
|
||||||
|
await connection_info.session.commit()
|
||||||
|
except Exception as commit_error:
|
||||||
|
logger.warning(f"提交事务时出错: {commit_error}")
|
||||||
|
await connection_info.session.rollback()
|
||||||
|
raise
|
||||||
|
|
||||||
except Exception:
|
except Exception:
|
||||||
# 发生错误时回滚连接
|
# 发生错误时回滚连接
|
||||||
if connection_info and connection_info.session:
|
if connection_info and connection_info.session:
|
||||||
|
|||||||
Reference in New Issue
Block a user