from typing import List, Optional from sqlalchemy.orm import Session from models.todo import Todo from schemas.todo import TodoCreate, TodoUpdate import uuid def create_todo(db: Session, todo_data: TodoCreate) -> Todo: """ Creates a new todo in the database. Args: db (Session): The database session. todo_data (TodoCreate): The data for the todo to create. Returns: Todo: The newly created todo object. """ db_todo = Todo(**todo_data.dict()) db.add(db_todo) db.commit() db.refresh(db_todo) return db_todo def get_all_todos(db: Session) -> List[Todo]: """ Retrieves all todos from the database. Args: db (Session): The database session. Returns: List[Todo]: A list of all todo objects. """ return db.query(Todo).all() def get_todo_by_id(db: Session, todo_id: uuid.UUID) -> Optional[Todo]: """ Retrieves a single todo by its ID. Args: db (Session): The database session. todo_id (UUID): The ID of the todo to retrieve. Returns: Optional[Todo]: The todo object if found, otherwise None. """ return db.query(Todo).filter(Todo.id == todo_id).first() def update_todo(db: Session, todo_id: uuid.UUID, todo_data: TodoUpdate) -> Optional[Todo]: """ Updates an existing todo in the database. Args: db (Session): The database session. todo_id (UUID): The ID of the todo to update. todo_data (TodoUpdate): The updated data for the todo. Returns: Optional[Todo]: The updated todo object if found, otherwise None. """ existing_todo = get_todo_by_id(db, todo_id) if not existing_todo: return None todo_data_dict = todo_data.dict(exclude_unset=True) for key, value in todo_data_dict.items(): setattr(existing_todo, key, value) db.commit() db.refresh(existing_todo) return existing_todo def delete_todo(db: Session, todo_id: uuid.UUID) -> bool: """ Deletes a todo from the database. Args: db (Session): The database session. todo_id (UUID): The ID of the todo to delete. Returns: bool: True if the todo was deleted, False otherwise. """ existing_todo = get_todo_by_id(db, todo_id) if not existing_todo: return False db.delete(existing_todo) db.commit() return True