73 lines
1.9 KiB
Python
73 lines
1.9 KiB
Python
from typing import Optional
|
|
from sqlalchemy.orm import Session
|
|
from sqlalchemy.exc import IntegrityError
|
|
from models.fruit import Fruit
|
|
from schemas.fruit import FruitCreate
|
|
from uuid import UUID
|
|
|
|
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.
|
|
|
|
Raises:
|
|
IntegrityError: If a fruit with the same name already exists.
|
|
"""
|
|
try:
|
|
db_fruit = Fruit(**fruit_data.dict())
|
|
db.add(db_fruit)
|
|
db.commit()
|
|
db.refresh(db_fruit)
|
|
return db_fruit
|
|
except IntegrityError:
|
|
db.rollback()
|
|
raise ValueError(f"A fruit with the name '{fruit_data.name}' already exists.")
|
|
|
|
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 get_all_fruits(db: Session) -> list[Fruit]:
|
|
"""
|
|
Retrieves all fruits from the database.
|
|
|
|
Args:
|
|
db (Session): The database session.
|
|
|
|
Returns:
|
|
list[Fruit]: A list of all fruit objects.
|
|
"""
|
|
return db.query(Fruit).all()
|
|
|
|
def delete_fruit(db: Session, fruit_id: UUID) -> None:
|
|
"""
|
|
Deletes a fruit from the database by its ID.
|
|
|
|
Args:
|
|
db (Session): The database session.
|
|
fruit_id (UUID): The ID of the fruit to delete.
|
|
|
|
Returns:
|
|
None
|
|
"""
|
|
fruit = db.query(Fruit).filter(Fruit.id == fruit_id).first()
|
|
if fruit:
|
|
db.delete(fruit)
|
|
db.commit()
|
|
else:
|
|
raise ValueError(f"No fruit found with ID {fruit_id}") |