service_man/api/uow/database.py

30 lines
843 B
Python

from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Database:
def __init__(self, db_url: str) -> None:
self._engine = create_async_engine(db_url, echo=True)
self._async_session = async_sessionmaker(
self._engine,
class_=AsyncSession,
expire_on_commit=False,
)
async def __aenter__(self):
async with self._async_session() as session:
self.session = session
return self
async def __aexit__(self, *args):
await self.session.rollback()
await self.session.close()
async def commit(self):
await self.session.commit()
async def rollback(self):
await self.session.rollback()