|
| 1 | +from collections.abc import AsyncGenerator, Sequence |
| 2 | +from contextlib import asynccontextmanager |
| 3 | +from typing import Any, Generic, Type, TypeVar |
| 4 | + |
| 5 | +from sqlalchemy import select |
| 6 | +from sqlalchemy.ext.asyncio import AsyncSession |
| 7 | + |
| 8 | +from app.database import Base, _session_ctx, async_session |
| 9 | + |
| 10 | +ModelType = TypeVar("ModelType", bound=Base) |
| 11 | + |
| 12 | + |
| 13 | +class BaseDAO(Generic[ModelType]): |
| 14 | + """Base class for data access objects, managing session context and basic CRUD.""" |
| 15 | + |
| 16 | + def __init__(self, model: Type[ModelType]): |
| 17 | + self.model = model |
| 18 | + |
| 19 | + @asynccontextmanager |
| 20 | + async def session(self) -> AsyncGenerator[AsyncSession, None]: |
| 21 | + """Context manager yielding the active context session or a new one.""" |
| 22 | + context_session = _session_ctx.get() |
| 23 | + if context_session is not None: |
| 24 | + yield context_session |
| 25 | + else: |
| 26 | + async with async_session() as session: |
| 27 | + yield session |
| 28 | + |
| 29 | + async def get(self, id: Any) -> ModelType | None: |
| 30 | + """Fetch a single record by its primary key ID.""" |
| 31 | + async with self.session() as db: |
| 32 | + if hasattr(db, "get"): |
| 33 | + return await db.get(self.model, id) |
| 34 | + # Fallback for custom mock DB clients in tests |
| 35 | + stmt = select(self.model).where(self.model.id == id) |
| 36 | + result = await db.execute(stmt) |
| 37 | + return result.scalar_one_or_none() |
| 38 | + |
| 39 | + async def is_empty(self) -> bool: |
| 40 | + """Check if the table is empty (no records).""" |
| 41 | + async with self.session() as db: |
| 42 | + stmt = select(self.model.id).limit(1) |
| 43 | + result = await db.execute(stmt) |
| 44 | + return result.scalar() is None |
| 45 | + |
| 46 | + async def get_all(self, skip: int = 0, limit: int = 100) -> Sequence[ModelType]: |
| 47 | + """Fetch all records with offset and limit.""" |
| 48 | + async with self.session() as db: |
| 49 | + stmt = select(self.model).offset(skip).limit(limit) |
| 50 | + result = await db.execute(stmt) |
| 51 | + return result.scalars().all() |
| 52 | + |
| 53 | + async def create(self, *, obj_in: dict[str, Any]) -> ModelType: |
| 54 | + """Create a new record.""" |
| 55 | + async with self.session() as db: |
| 56 | + db_obj = self.model(**obj_in) |
| 57 | + db.add(db_obj) |
| 58 | + await db.flush() |
| 59 | + return db_obj |
| 60 | + |
| 61 | + async def update(self, *, db_obj: ModelType, obj_in: dict[str, Any]) -> ModelType: |
| 62 | + """Update an existing record.""" |
| 63 | + async with self.session() as db: |
| 64 | + for field, value in obj_in.items(): |
| 65 | + if hasattr(db_obj, field): |
| 66 | + setattr(db_obj, field, value) |
| 67 | + db.add(db_obj) |
| 68 | + await db.flush() |
| 69 | + return db_obj |
| 70 | + |
| 71 | + async def delete(self, *, id: Any) -> ModelType | None: |
| 72 | + """Delete a record by ID.""" |
| 73 | + async with self.session() as db: |
| 74 | + obj = await self.get(id) |
| 75 | + if obj: |
| 76 | + if hasattr(db, "delete"): |
| 77 | + await db.delete(obj) |
| 78 | + await db.flush() |
| 79 | + return obj |
| 80 | + |
0 commit comments