"""Generic data access written once. Module repositories subclass it and add only their own queries.""" from collections.abc import Sequence from typing import Any, ClassVar, Generic, TypeVar from uuid import UUID from sqlalchemy import exists, select from sqlalchemy.ext.asyncio import AsyncSession from app.common.base_model import Base from app.core.errors import NotFound ModelT = TypeVar("ModelT", bound=Base) class BaseRepository(Generic[ModelT]): model: ClassVar[type[Base]] def __init__(self, session: AsyncSession): self.session = session async def get(self, id_: UUID) -> ModelT | None: return await self.session.get(self.model, id_) # type: ignore[return-value] async def get_or_404(self, id_: UUID) -> ModelT: obj = await self.get(id_) if obj is None: raise NotFound() return obj async def first_by(self, **filters: Any) -> ModelT | None: result = await self.session.execute(select(self.model).filter_by(**filters).limit(1)) return result.scalars().first() # type: ignore[return-value] async def list_by(self, **filters: Any) -> Sequence[ModelT]: result = await self.session.execute(select(self.model).filter_by(**filters)) return result.scalars().all() # type: ignore[return-value] async def exists_by(self, **filters: Any) -> bool: return bool(await self.session.scalar(select(exists().where( *(getattr(self.model, k) == v for k, v in filters.items()))))) async def create(self, **values: Any) -> ModelT: obj = self.model(**values) self.session.add(obj) await self.session.flush() await self.session.refresh(obj) return obj # type: ignore[return-value] async def update(self, obj: ModelT, **values: Any) -> ModelT: for key, value in values.items(): setattr(obj, key, value) await self.session.flush() await self.session.refresh(obj) return obj async def delete(self, obj: ModelT) -> None: await self.session.delete(obj) await self.session.flush()