chat_back/app/unit_of_work.py
2024-07-12 16:29:31 +04:00

32 lines
786 B
Python

from sqlalchemy.exc import SQLAlchemyError
from app.dao.chat import ChatDAO
from app.database import async_session_maker
from app.dao.user import UserDAO
from app.exceptions import BlackPhoenixException
class UnitOfWork:
def __init__(self):
self.session_factory = async_session_maker
async def __aenter__(self):
self.session = self.session_factory()
self.user = UserDAO(self.session)
self.chat = ChatDAO(self.session)
async def __aexit__(self, exc_type, exc, tb):
try:
await self.rollback()
await self.session.close()
except SQLAlchemyError:
raise BlackPhoenixException
if isinstance(exc, SQLAlchemyError):
raise BlackPhoenixException
async def commit(self):
await self.session.commit()
async def rollback(self):
await self.session.rollback()