69 lines
1.9 KiB
Python
69 lines
1.9 KiB
Python
from typing import Any, Dict, List, Optional, Union
|
|
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.models.product import Product
|
|
from app.schemas.product import ProductCreate, ProductUpdate
|
|
|
|
|
|
def get_product(db: Session, user_id: int, product_id: int) -> Optional[Product]:
|
|
"""Get a product by ID for a specific user."""
|
|
return db.query(Product).filter(
|
|
Product.id == product_id, Product.user_id == user_id
|
|
).first()
|
|
|
|
|
|
def get_products(
|
|
db: Session, user_id: int, skip: int = 0, limit: int = 100
|
|
) -> List[Product]:
|
|
"""Get a list of products for a specific user."""
|
|
return db.query(Product).filter(Product.user_id == user_id).offset(skip).limit(limit).all()
|
|
|
|
|
|
def create_product(db: Session, user_id: int, product_in: ProductCreate) -> Product:
|
|
"""Create a new product for a specific user."""
|
|
product_data = product_in.model_dump()
|
|
db_product = Product(**product_data, user_id=user_id)
|
|
|
|
db.add(db_product)
|
|
db.commit()
|
|
db.refresh(db_product)
|
|
return db_product
|
|
|
|
|
|
def update_product(
|
|
db: Session,
|
|
user_id: int,
|
|
db_product: Product,
|
|
product_in: Union[ProductUpdate, Dict[str, Any]]
|
|
) -> Product:
|
|
"""Update a product."""
|
|
product_data = db_product.to_dict()
|
|
|
|
if isinstance(product_in, dict):
|
|
update_data = product_in
|
|
else:
|
|
update_data = product_in.model_dump(exclude_unset=True)
|
|
|
|
# Update product fields
|
|
for field in product_data:
|
|
if field in update_data:
|
|
setattr(db_product, field, update_data[field])
|
|
|
|
db.add(db_product)
|
|
db.commit()
|
|
db.refresh(db_product)
|
|
return db_product
|
|
|
|
|
|
def delete_product(db: Session, user_id: int, product_id: int) -> Optional[Product]:
|
|
"""Delete a product."""
|
|
product = db.query(Product).filter(
|
|
Product.id == product_id, Product.user_id == user_id
|
|
).first()
|
|
if not product:
|
|
return None
|
|
|
|
db.delete(product)
|
|
db.commit()
|
|
return product |