|
| 1 | +import contextlib |
| 2 | +import logging |
| 3 | +from typing import Any, AsyncIterator |
| 4 | + |
| 5 | +from sqlalchemy.ext.asyncio import ( |
| 6 | + AsyncConnection, |
| 7 | + AsyncEngine, |
| 8 | + AsyncSession, |
| 9 | + async_sessionmaker, |
| 10 | + create_async_engine, |
| 11 | +) |
| 12 | + |
| 13 | +__all__ = [ |
| 14 | + "AsyncConnection", |
| 15 | + "AsyncSession", |
| 16 | + "AsyncDatabaseSessionManager", |
| 17 | +] |
| 18 | + |
| 19 | + |
| 20 | +LOG = logging.getLogger(__name__) |
| 21 | + |
| 22 | + |
| 23 | +# Heavily inspired by https://praciano.com.br/fastapi-and-async-sqlalchemy-20-with-pytest-done-right.html |
| 24 | + |
| 25 | + |
| 26 | +class AsyncDatabaseSessionManager: |
| 27 | + def __init__(self, host: str, engine_kwargs: dict[str, Any] = {}, session_kwargs: dict[str, Any] = {}): |
| 28 | + session_kwargs.setdefault("autocommit", False) |
| 29 | + session_kwargs.setdefault("expire_on_commit", False) |
| 30 | + |
| 31 | + self._engine: AsyncEngine = create_async_engine(host, **engine_kwargs) |
| 32 | + self._sessionmaker: async_sessionmaker[AsyncSession] = async_sessionmaker(bind=self._engine, **session_kwargs) |
| 33 | + |
| 34 | + async def close(self): |
| 35 | + await self._engine.dispose() |
| 36 | + |
| 37 | + async def __aenter__(self): |
| 38 | + return self |
| 39 | + |
| 40 | + async def __aexit__(self, exc_type, exc_val, exc_tb): |
| 41 | + await self.close() |
| 42 | + |
| 43 | + @contextlib.asynccontextmanager |
| 44 | + async def connect(self) -> AsyncIterator[AsyncConnection]: |
| 45 | + async with self._engine.begin() as connection: |
| 46 | + try: |
| 47 | + yield connection |
| 48 | + except Exception: |
| 49 | + LOG.exception("DB connection was rolled back due to an exception:") |
| 50 | + await connection.rollback() |
| 51 | + raise |
| 52 | + |
| 53 | + @contextlib.asynccontextmanager |
| 54 | + async def session(self) -> AsyncIterator[AsyncSession]: |
| 55 | + async with self._sessionmaker() as sess: |
| 56 | + yield sess |
| 57 | + # try: |
| 58 | + # except Exception: |
| 59 | + # LOG.exception("DB transaction was rolled back due to an exception:") |
| 60 | + # # TODO: Not sure if this is needed. Test if it does auto-rollback |
| 61 | + # await sess.rollback() |
| 62 | + # raise |
0 commit comments