36 lines
1.0 KiB
Python
36 lines
1.0 KiB
Python
"""Generic data-access base. Repositories hold queries only — never business rules."""
|
|
|
|
import uuid
|
|
from typing import Generic, TypeVar
|
|
|
|
from sqlalchemy import select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.common.exceptions import NotFoundError
|
|
from app.database.base import Base
|
|
|
|
ModelT = TypeVar("ModelT", bound=Base)
|
|
|
|
|
|
class BaseRepository(Generic[ModelT]):
|
|
model: type[ModelT]
|
|
|
|
def __init__(self, db: AsyncSession) -> None:
|
|
self.db = db
|
|
|
|
async def get(self, entity_id: uuid.UUID) -> ModelT | None:
|
|
return await self.db.get(self.model, entity_id)
|
|
|
|
async def get_or_404(self, entity_id: uuid.UUID) -> ModelT:
|
|
entity = await self.get(entity_id)
|
|
if entity is None:
|
|
raise NotFoundError(f"{self.model.__name__} not found", {"id": str(entity_id)})
|
|
return entity
|
|
|
|
async def list_all(self) -> list[ModelT]:
|
|
return list((await self.db.execute(select(self.model))).scalars().all())
|
|
|
|
def add(self, entity: ModelT) -> ModelT:
|
|
self.db.add(entity)
|
|
return entity
|