72 lines
2.3 KiB
Python
72 lines
2.3 KiB
Python
import uuid
|
|
from typing import Optional
|
|
|
|
from sqlalchemy import select, func
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.models.competitor import Competitor
|
|
|
|
|
|
class CompetitorRepository:
|
|
def __init__(self, session: AsyncSession):
|
|
self.session = session
|
|
|
|
async def get_by_id(self, id: uuid.UUID) -> Optional[Competitor]:
|
|
result = await self.session.execute(
|
|
select(Competitor).where(Competitor.id == id)
|
|
)
|
|
return result.scalar_one_or_none()
|
|
|
|
async def list_by_brand(
|
|
self, brand_id: uuid.UUID, *, skip: int = 0, limit: int = 100
|
|
) -> list[Competitor]:
|
|
result = await self.session.execute(
|
|
select(Competitor)
|
|
.where(Competitor.brand_id == brand_id)
|
|
.order_by(Competitor.created_at.desc())
|
|
.offset(skip)
|
|
.limit(limit)
|
|
)
|
|
return list(result.scalars().all())
|
|
|
|
async def count_by_brand(self, brand_id: uuid.UUID) -> int:
|
|
result = await self.session.execute(
|
|
select(func.count()).select_from(Competitor).where(
|
|
Competitor.brand_id == brand_id
|
|
)
|
|
)
|
|
return result.scalar_one()
|
|
|
|
async def get_by_brand(self, brand_name: str) -> list[Competitor]:
|
|
from app.models.brand import Brand
|
|
result = await self.session.execute(
|
|
select(Competitor)
|
|
.join(Brand, Competitor.brand_id == Brand.id)
|
|
.where(Brand.name == brand_name)
|
|
)
|
|
return list(result.scalars().all())
|
|
|
|
async def create(self, **kwargs) -> Competitor:
|
|
instance = Competitor(**kwargs)
|
|
self.session.add(instance)
|
|
await self.session.flush()
|
|
return instance
|
|
|
|
async def update(self, id: uuid.UUID, **kwargs) -> Optional[Competitor]:
|
|
instance = await self.get_by_id(id)
|
|
if instance is None:
|
|
return None
|
|
for key, value in kwargs.items():
|
|
if hasattr(instance, key):
|
|
setattr(instance, key, value)
|
|
await self.session.flush()
|
|
return instance
|
|
|
|
async def delete(self, id: uuid.UUID) -> bool:
|
|
instance = await self.get_by_id(id)
|
|
if instance is None:
|
|
return False
|
|
await self.session.delete(instance)
|
|
await self.session.flush()
|
|
return True
|