File size: 1,683 Bytes
fe40b87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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))