from uuid import UUID from sqlalchemy import select from sqlalchemy.dialects.postgresql import insert from app.common.base_repository import BaseRepository from app.modules.settings.models import ConsentEvent, ExportJob, UserSettings class SettingsRepository(BaseRepository[UserSettings]): model = UserSettings async def locked(self, account_id: UUID) -> UserSettings: """The account's row, created with the defaults if missing, locked until the request commits.""" await self.session.execute( insert(UserSettings).values(account_id=account_id).on_conflict_do_nothing(index_elements=["account_id"])) row = await self.session.scalar( select(UserSettings).where(UserSettings.account_id == account_id) .with_for_update().execution_options(populate_existing=True)) assert row is not None return row class ConsentRepository(BaseRepository[ConsentEvent]): model = ConsentEvent async def latest(self, account_id: UUID, category: str = "analysis") -> ConsentEvent | None: return await self.session.scalar( select(ConsentEvent).where(ConsentEvent.account_id == account_id, ConsentEvent.category == category) .order_by(ConsentEvent.created_at.desc(), ConsentEvent.id.desc()).limit(1)) class ExportRepository(BaseRepository[ExportJob]): model = ExportJob async def queued(self, requester_id: UUID, scope: str) -> ExportJob | None: return await self.session.scalar( select(ExportJob).where(ExportJob.requester_id == requester_id, ExportJob.scope == scope, ExportJob.status == "queued").limit(1))