2024-03-04 13:15:28 +03:00
|
|
|
from contextlib import (AbstractContextManager, asynccontextmanager,
|
|
|
|
contextmanager)
|
|
|
|
from typing import Callable
|
|
|
|
|
|
|
|
from sqlalchemy.ext.asyncio import (AsyncSession, async_sessionmaker,
|
|
|
|
create_async_engine)
|
2024-03-04 07:12:29 +03:00
|
|
|
from sqlalchemy.ext.declarative import declarative_base
|
2024-03-04 13:15:28 +03:00
|
|
|
from sqlalchemy.orm import Session
|
2024-03-04 07:12:29 +03:00
|
|
|
|
|
|
|
Base = declarative_base()
|
|
|
|
|
|
|
|
|
|
|
|
class Database:
|
|
|
|
def __init__(self, db_url: str) -> None:
|
|
|
|
self._engine = create_async_engine(db_url, echo=True)
|
2024-03-04 13:15:28 +03:00
|
|
|
self._session_factory = async_sessionmaker(
|
2024-03-04 07:12:29 +03:00
|
|
|
self._engine,
|
|
|
|
class_=AsyncSession,
|
|
|
|
expire_on_commit=False,
|
|
|
|
)
|
|
|
|
|
2024-03-04 13:15:28 +03:00
|
|
|
@property
|
|
|
|
def session(self):
|
|
|
|
return self._session_factory()
|
|
|
|
|
2024-03-04 07:12:29 +03:00
|
|
|
async def __aenter__(self):
|
2024-03-04 13:15:28 +03:00
|
|
|
return self
|
2024-03-04 07:12:29 +03:00
|
|
|
|
|
|
|
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()
|