Files
aiData/DbKit/TransactionContext.py
HuangHai b66f683dfb 'commit'
2026-01-12 07:49:18 +08:00

41 lines
1.1 KiB
Python
Raw Permalink 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.

class TransactionContext:
"""
事务上下文管理器类(异步版本)
支持异步事务管理配合异步Db类使用
"""
def __init__(self, db_instance):
"""
初始化事务上下文管理器
Args:
db_instance: 异步Db实例
"""
self.db = db_instance
self.session = None
async def __aenter__(self):
"""
进入异步上下文时创建会话
"""
self.session = await self.db.get_session()
return self.session
async def __aexit__(self, exc_type, exc_val, exc_tb):
"""
退出异步上下文时提交或回滚事务
"""
try:
if exc_type is None:
# 如果没有异常,提交事务
await self.session.commit()
else:
# 如果有异常,回滚事务
await self.session.rollback()
finally:
# 无论如何都关闭会话
if self.session:
await self.session.close()
# 返回False表示不抑制异常
return False