48 lines
1.2 KiB
Python
48 lines
1.2 KiB
Python
from typing import List, Optional
|
|
from sqlalchemy.orm import Session
|
|
from sqlalchemy import func
|
|
|
|
from models.fruit import Fruit
|
|
from schemas.fruit import FruitCreate
|
|
|
|
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 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(name=fruit_data.name)
|
|
db.add(db_fruit)
|
|
db.commit()
|
|
db.refresh(db_fruit)
|
|
return db_fruit
|
|
|
|
def get_fruit_by_name(db: Session, name: str) -> Optional[Fruit]:
|
|
"""
|
|
Retrieves a single fruit by its name.
|
|
|
|
Args:
|
|
db (Session): The database session.
|
|
name (str): The name of the fruit to retrieve.
|
|
|
|
Returns:
|
|
Optional[Fruit]: The fruit object if found, otherwise None.
|
|
"""
|
|
return db.query(Fruit).filter(func.lower(Fruit.name) == name.lower()).first() |