From 51e3b12c1e166c21625b3a3deafbb1b1fc2ef4ed Mon Sep 17 00:00:00 2001 From: Backend IM Bot Date: Wed, 9 Apr 2025 13:19:37 +0000 Subject: [PATCH] feat: Add helper functions for Route --- helpers/route_helpers.py | 90 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 helpers/route_helpers.py diff --git a/helpers/route_helpers.py b/helpers/route_helpers.py new file mode 100644 index 0000000..0aa5d11 --- /dev/null +++ b/helpers/route_helpers.py @@ -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 \ No newline at end of file