|
| 1 | +import logging |
| 2 | +from collections.abc import AsyncIterator |
| 3 | +from contextlib import asynccontextmanager |
| 4 | + |
| 5 | +from sqlalchemy.ext.asyncio import AsyncConnection, AsyncEngine |
| 6 | + |
| 7 | +_logger = logging.getLogger(__name__) |
| 8 | + |
| 9 | + |
| 10 | +@asynccontextmanager |
| 11 | +async def get_or_create_connection( |
| 12 | + engine: AsyncEngine, connection: AsyncConnection | None = None |
| 13 | +) -> AsyncIterator[AsyncConnection]: |
| 14 | + # NOTE: When connection is passed, the engine is actually not needed |
| 15 | + # NOTE: Creator is responsible of closing connection |
| 16 | + is_connection_created = connection is None |
| 17 | + if is_connection_created: |
| 18 | + connection = await engine.connect() |
| 19 | + try: |
| 20 | + assert connection # nosec |
| 21 | + yield connection |
| 22 | + finally: |
| 23 | + assert connection # nosec |
| 24 | + assert not connection.closed # nosec |
| 25 | + if is_connection_created and connection: |
| 26 | + await connection.close() |
| 27 | + |
| 28 | + |
| 29 | +@asynccontextmanager |
| 30 | +async def transaction_context( |
| 31 | + engine: AsyncEngine, connection: AsyncConnection | None = None |
| 32 | +): |
| 33 | + async with get_or_create_connection(engine, connection) as conn: |
| 34 | + if conn.in_transaction(): |
| 35 | + async with conn.begin_nested(): # inner transaction (savepoint) |
| 36 | + yield conn |
| 37 | + else: |
| 38 | + try: |
| 39 | + async with conn.begin(): # outer transaction (savepoint) |
| 40 | + yield conn |
| 41 | + finally: |
| 42 | + assert not conn.closed # nosec |
| 43 | + assert not conn.in_transaction() # nosec |
0 commit comments