Files
shveitechbot/repositories/products.py
2026-03-11 20:26:38 +07:00

88 lines
2.5 KiB
Python

from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from sqlalchemy.sql.expression import func
from typing import Optional
from config import PAGE_SIZE
from db.models import Product
class ProductRepository:
async def get_product_by_id(
self, session: AsyncSession, product_id: int
) -> Optional[Product]:
stmt = select(Product).where(Product.id == product_id)
return await session.scalar(stmt)
async def get_product_by_category(
self, session: AsyncSession, category_id: int, *, limit: int, offset: int
) -> list[Product]:
stmt = (
select(Product)
.where(Product.category_id == category_id)
.order_by(Product.id)
.offset(offset)
.limit(limit)
)
result = await session.scalars(stmt)
return list(result)
async def add_product_file_id(
self, session: AsyncSession, product_id: int, *, file_id: str
) -> None:
product = await self.get_product_by_id(session, product_id)
product.file_id = file_id
await session.commit()
async def search(
self,
session: AsyncSession,
query: str,
*,
limit: int = PAGE_SIZE + 1,
offset: int = 0,
) -> list[Optional[Product]]:
ts_query = func.plainto_tsquery("simple", query)
stmt = (
select(Product)
.where(Product.search_vector.op("@@")(ts_query))
.order_by(func.ts_rank(Product.search_vector, ts_query).desc())
.limit(limit)
.offset(offset)
)
res = await session.scalars(stmt)
return list(res)
async def update_product_name_by_id(
self, session: AsyncSession, product_id: int, name: str
):
product = await self.get_product_by_id(session, product_id=product_id)
product.name = name
await session.commit()
return product
async def update_product_description_by_id(
self, session: AsyncSession, product_id: int, description: str
):
product = await self.get_product_by_id(session, product_id=product_id)
product.description = description
await session.commit()
return product
async def update_product_price_by_id(
self, session: AsyncSession, product_id: int, price: str
):
product = await self.get_product_by_id(session, product_id=product_id)
product.price = price
await session.commit()
return product