86 lines
2.5 KiB
Python
86 lines
2.5 KiB
Python
from typing import Optional
|
|
from sqlalchemy.orm import Session
|
|
from sqlalchemy.exc import IntegrityError
|
|
|
|
from models.grocery import Grocery
|
|
from schemas.grocery import GroceryCreate
|
|
|
|
def create_grocery(db: Session, grocery_data: GroceryCreate) -> Optional[Grocery]:
|
|
"""
|
|
Creates a new grocery item in the database.
|
|
|
|
Args:
|
|
db (Session): The database session
|
|
grocery_data (GroceryCreate): The data for the grocery item to create
|
|
|
|
Returns:
|
|
Optional[Grocery]: The newly created grocery object, or None if creation failed
|
|
"""
|
|
try:
|
|
normalized_name = normalize_grocery_name(grocery_data.name)
|
|
db_grocery = Grocery(
|
|
name=normalized_name,
|
|
color=grocery_data.color,
|
|
shape=grocery_data.shape
|
|
)
|
|
db.add(db_grocery)
|
|
db.commit()
|
|
db.refresh(db_grocery)
|
|
return db_grocery
|
|
except IntegrityError:
|
|
db.rollback()
|
|
return None
|
|
|
|
def get_grocery_by_name(db: Session, name: str) -> Optional[Grocery]:
|
|
"""
|
|
Retrieves a grocery item by its name using the indexed name column.
|
|
Returns the complete grocery object including the color and shape fields.
|
|
|
|
Args:
|
|
db (Session): The database session
|
|
name (str): The name of the grocery item to retrieve
|
|
|
|
Returns:
|
|
Optional[Grocery]: The grocery object if found, otherwise None
|
|
"""
|
|
normalized_name = normalize_grocery_name(name)
|
|
return db.query(Grocery).filter(Grocery.name == normalized_name).first()
|
|
|
|
def validate_grocery_name(name: str) -> bool:
|
|
"""
|
|
Validates the grocery name according to business rules.
|
|
|
|
Args:
|
|
name (str): The name to validate
|
|
|
|
Returns:
|
|
bool: True if the name is valid, False otherwise
|
|
"""
|
|
if not name or not isinstance(name, str):
|
|
return False
|
|
|
|
# Remove leading/trailing whitespace and check length
|
|
name = name.strip()
|
|
if len(name) < 1:
|
|
return False
|
|
|
|
# Additional validation rules could be added here
|
|
return True
|
|
|
|
def normalize_grocery_name(name: str) -> str:
|
|
"""
|
|
Normalizes a grocery name for consistency in storage and indexing.
|
|
Ensures consistent name format for the indexed name column.
|
|
|
|
Args:
|
|
name (str): The name to normalize
|
|
|
|
Returns:
|
|
str: The normalized name
|
|
"""
|
|
if not name:
|
|
raise ValueError("Grocery name cannot be empty")
|
|
|
|
# Remove extra whitespace and capitalize first letter
|
|
normalized = " ".join(name.split())
|
|
return normalized.strip().capitalize() |