|
| 1 | +from contextlib import asynccontextmanager |
| 2 | +from typing import Any, TypedDict |
| 3 | + |
| 4 | +import sqlalchemy as sa |
| 5 | +from sqlalchemy.ext.asyncio import AsyncConnection, AsyncEngine |
| 6 | + |
| 7 | + |
| 8 | +@asynccontextmanager |
| 9 | +async def get_or_create_connection( |
| 10 | + engine: AsyncEngine, connection: AsyncConnection | None = None |
| 11 | +): |
| 12 | + close_conn = False |
| 13 | + if connection is None: |
| 14 | + connection = await engine.connect() |
| 15 | + close_conn = True |
| 16 | + try: |
| 17 | + yield connection |
| 18 | + finally: |
| 19 | + if close_conn: |
| 20 | + await connection.close() |
| 21 | + |
| 22 | + |
| 23 | +@asynccontextmanager |
| 24 | +async def transaction_context( |
| 25 | + engine: AsyncEngine, connection: AsyncConnection | None = None |
| 26 | +): |
| 27 | + async with get_or_create_connection(engine, connection) as conn: |
| 28 | + if conn.in_transaction(): |
| 29 | + async with conn.begin_nested(): |
| 30 | + yield conn |
| 31 | + else: |
| 32 | + async with conn.begin(): |
| 33 | + yield conn |
| 34 | + |
| 35 | + |
| 36 | +class _PageDict(TypedDict): |
| 37 | + total_count: int |
| 38 | + rows: list[dict[str, Any]] |
| 39 | + |
| 40 | + |
| 41 | +class MinimalRepo: |
| 42 | + def __init__(self, engine: AsyncEngine, table: sa.Table): |
| 43 | + self.engine = engine |
| 44 | + self.table = table |
| 45 | + |
| 46 | + async def create(self, connection: AsyncConnection | None = None, **kwargs) -> int: |
| 47 | + async with get_or_create_connection(self.engine, connection) as conn: |
| 48 | + result = await conn.execute(self.table.insert().values(**kwargs)) |
| 49 | + await conn.commit() |
| 50 | + assert result # nosec |
| 51 | + return result.inserted_primary_key[0] |
| 52 | + |
| 53 | + async def get_by_id( |
| 54 | + self, record_id: int, connection: AsyncConnection | None = None |
| 55 | + ) -> dict[str, Any] | None: |
| 56 | + async with get_or_create_connection(self.engine, connection) as conn: |
| 57 | + result = await conn.execute( |
| 58 | + sa.select(self.table).where(self.table.c.id == record_id) |
| 59 | + ) |
| 60 | + record = result.fetchone() |
| 61 | + return dict(record) if record else None |
| 62 | + |
| 63 | + async def get_page( |
| 64 | + self, limit: int, offset: int, connection: AsyncConnection | None = None |
| 65 | + ) -> _PageDict: |
| 66 | + async with get_or_create_connection(self.engine, connection) as conn: |
| 67 | + # Compute total count |
| 68 | + total_count_query = sa.select(sa.func.count()).select_from(self.table) |
| 69 | + total_count_result = await conn.execute(total_count_query) |
| 70 | + total_count = total_count_result.scalar() |
| 71 | + |
| 72 | + # Fetch paginated results |
| 73 | + query = sa.select(self.table).limit(limit).offset(offset) |
| 74 | + result = await conn.execute(query) |
| 75 | + records = [dict(row) for row in result.fetchall()] |
| 76 | + |
| 77 | + return _PageDict(total_count=total_count or 0, rows=records) |
| 78 | + |
| 79 | + async def update( |
| 80 | + self, record_id: int, connection: AsyncConnection | None = None, **values |
| 81 | + ) -> bool: |
| 82 | + async with get_or_create_connection(self.engine, connection) as conn: |
| 83 | + result = await conn.execute( |
| 84 | + self.table.update().where(self.table.c.id == record_id).values(**values) |
| 85 | + ) |
| 86 | + await conn.commit() |
| 87 | + return result.rowcount > 0 |
| 88 | + |
| 89 | + async def delete( |
| 90 | + self, record_id: int, connection: AsyncConnection | None = None |
| 91 | + ) -> bool: |
| 92 | + async with get_or_create_connection(self.engine, connection) as conn: |
| 93 | + result = await conn.execute( |
| 94 | + self.table.delete().where(self.table.c.id == record_id) |
| 95 | + ) |
| 96 | + await conn.commit() |
| 97 | + return result.rowcount > 0 |
0 commit comments