File size: 2,124 Bytes
2756f0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
"""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()