90 lines
2.6 KiB
Python
90 lines
2.6 KiB
Python
from typing import List, Optional
|
|
from uuid import UUID
|
|
from sqlalchemy.orm import Session
|
|
from sqlalchemy import asc, desc
|
|
from models.fruit import Fruit
|
|
from schemas.fruit import FruitCreate, FruitUpdate
|
|
|
|
def get_all_fruits(db: Session, order_by: Optional[str] = None) -> List[Fruit]:
|
|
"""
|
|
Retrieves all fruits from the database.
|
|
|
|
Args:
|
|
db (Session): The database session.
|
|
order_by (Optional[str]): The field to order the results by ('asc' or 'desc').
|
|
|
|
Returns:
|
|
List[Fruit]: A list of all fruit objects.
|
|
"""
|
|
query = db.query(Fruit)
|
|
if order_by == 'asc':
|
|
query = query.order_by(asc(Fruit.name))
|
|
elif order_by == 'desc':
|
|
query = query.order_by(desc(Fruit.name))
|
|
return query.all()
|
|
|
|
def get_fruit_by_id(db: Session, fruit_id: UUID) -> Optional[Fruit]:
|
|
"""
|
|
Retrieves a single fruit by its ID.
|
|
|
|
Args:
|
|
db (Session): The database session.
|
|
fruit_id (UUID): The ID of the fruit to retrieve.
|
|
|
|
Returns:
|
|
Optional[Fruit]: The fruit object if found, otherwise None.
|
|
"""
|
|
return db.query(Fruit).filter(Fruit.id == fruit_id).first()
|
|
|
|
def create_fruit(db: Session, fruit_data: FruitCreate) -> Fruit:
|
|
"""
|
|
Creates a new fruit in the database.
|
|
|
|
Args:
|
|
db (Session): The database session.
|
|
fruit_data (FruitCreate): The data for the fruit to create.
|
|
|
|
Returns:
|
|
Fruit: The newly created fruit object.
|
|
"""
|
|
db_fruit = Fruit.create_new_fruit(name=fruit_data.name, description=fruit_data.description, price=fruit_data.price)
|
|
db.add(db_fruit)
|
|
db.commit()
|
|
db.refresh(db_fruit)
|
|
return db_fruit
|
|
|
|
def update_fruit(db: Session, fruit_id: UUID, fruit_data: FruitUpdate) -> Fruit:
|
|
"""
|
|
Updates an existing fruit in the database.
|
|
|
|
Args:
|
|
db (Session): The database session.
|
|
fruit_id (UUID): The ID of the fruit to update.
|
|
fruit_data (FruitUpdate): The updated data for the fruit.
|
|
|
|
Returns:
|
|
Fruit: The updated fruit object.
|
|
"""
|
|
db_fruit = Fruit.update_fruit(fruit_id, **fruit_data.dict(exclude_unset=True))
|
|
db.commit()
|
|
db.refresh(db_fruit)
|
|
return db_fruit
|
|
|
|
def delete_fruit(db: Session, fruit_id: UUID) -> bool:
|
|
"""
|
|
Deletes a fruit from the database.
|
|
|
|
Args:
|
|
db (Session): The database session.
|
|
fruit_id (UUID): The ID of the fruit to delete.
|
|
|
|
Returns:
|
|
bool: True if the fruit was successfully deleted, False otherwise.
|
|
"""
|
|
db_fruit = db.query(Fruit).filter(Fruit.id == fruit_id).first()
|
|
if not db_fruit:
|
|
return False
|
|
|
|
db.delete(db_fruit)
|
|
db.commit()
|
|
return True |