feat: Add helper functions for Route

This commit is contained in:
Backend IM Bot 2025-04-09 13:19:37 +00:00
parent 36835eaa29
commit 51e3b12c1e

90
helpers/route_helpers.py Normal file
View File

@ -0,0 +1,90 @@
from typing import List, Optional
from sqlalchemy.orm import Session
from models.route import Route
from schemas.route import RouteCreate, RouteSchema
from uuid import UUID
def get_route_by_id(db: Session, route_id: UUID) -> Optional[Route]:
"""
Get a route by its ID.
Args:
db (Session): SQLAlchemy database session.
route_id (UUID): The ID of the route to retrieve.
Returns:
Optional[Route]: The route object if found, None otherwise.
"""
return db.query(Route).filter(Route.id == route_id).first()
def get_all_routes(db: Session) -> List[Route]:
"""
Get all routes from the database.
Args:
db (Session): SQLAlchemy database session.
Returns:
List[Route]: A list of all route objects.
"""
return db.query(Route).all()
def create_route(db: Session, route_data: RouteCreate) -> Route:
"""
Create a new route in the database.
Args:
db (Session): SQLAlchemy database session.
route_data (RouteCreate): The data to create a new route.
Returns:
Route: The newly created route object.
"""
new_route = Route(**route_data.dict())
db.add(new_route)
db.commit()
db.refresh(new_route)
return new_route
def update_route(db: Session, route_id: UUID, route_data: RouteSchema) -> Optional[Route]:
"""
Update an existing route in the database.
Args:
db (Session): SQLAlchemy database session.
route_id (UUID): The ID of the route to update.
route_data (RouteSchema): The updated data for the route.
Returns:
Optional[Route]: The updated route object if found, None otherwise.
"""
route = get_route_by_id(db, route_id)
if route:
route.name = route_data.name
route.description = route_data.description
route.origin = route_data.origin
route.destination = route_data.destination
route.distance = route_data.distance
route.duration = route_data.duration
db.commit()
db.refresh(route)
return route
return None
def delete_route(db: Session, route_id: UUID) -> bool:
"""
Delete a route from the database.
Args:
db (Session): SQLAlchemy database session.
route_id (UUID): The ID of the route to delete.
Returns:
bool: True if the route was deleted successfully, False otherwise.
"""
route = get_route_by_id(db, route_id)
if route:
db.delete(route)
db.commit()
return True
return False