from typing import List, Optional from sqlalchemy.orm import Session from app.models.todo import Todo from app.schemas.todo import TodoCreate, TodoUpdate def get_todo(db: Session, todo_id: int) -> Optional[Todo]: """ Get a Todo item by its ID. Args: db: Database session todo_id: ID of the Todo item to retrieve Returns: Todo item if found, None otherwise """ return db.query(Todo).filter(Todo.id == todo_id).first() def get_todos( db: Session, skip: int = 0, limit: int = 100, completed: Optional[bool] = None ) -> List[Todo]: """ Get a list of Todo items with optional filtering and pagination. Args: db: Database session skip: Number of items to skip (offset) limit: Maximum number of items to return completed: Filter by completion status if provided Returns: List of Todo items """ query = db.query(Todo) if completed is not None: query = query.filter(Todo.completed == completed) return query.offset(skip).limit(limit).all() def create_todo(db: Session, todo: TodoCreate) -> Todo: """ Create a new Todo item. Args: db: Database session todo: Todo data for creation Returns: The created Todo item """ db_todo = Todo( title=todo.title, description=todo.description, completed=todo.completed ) db.add(db_todo) db.commit() db.refresh(db_todo) return db_todo def update_todo(db: Session, todo_id: int, todo_update: TodoUpdate) -> Optional[Todo]: """ Update an existing Todo item. Args: db: Database session todo_id: ID of the Todo item to update todo_update: Todo data for update Returns: Updated Todo item if found, None otherwise """ db_todo = get_todo(db, todo_id) if not db_todo: return None # Update model with provided values, skipping None values update_data = todo_update.model_dump(exclude_unset=True) for key, value in update_data.items(): setattr(db_todo, key, value) db.add(db_todo) db.commit() db.refresh(db_todo) return db_todo def delete_todo(db: Session, todo_id: int) -> bool: """ Delete a Todo item. Args: db: Database session todo_id: ID of the Todo item to delete Returns: True if deleted successfully, False if item not found """ db_todo = get_todo(db, todo_id) if not db_todo: return False db.delete(db_todo) db.commit() return True