72 lines
1.9 KiB
Python
72 lines
1.9 KiB
Python
from typing import Optional, Union
|
|
|
|
from sqlalchemy import desc
|
|
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."""
|
|
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, optionally filtered by completion status."""
|
|
query = db.query(Todo)
|
|
|
|
if completed is not None:
|
|
query = query.filter(Todo.completed == completed)
|
|
|
|
return query.order_by(desc(Todo.created_at)).offset(skip).limit(limit).all()
|
|
|
|
|
|
def get_todos_count(db: Session, completed: Optional[bool] = None) -> int:
|
|
"""Get the total count of todo items, optionally filtered by completion status."""
|
|
query = db.query(Todo)
|
|
|
|
if completed is not None:
|
|
query = query.filter(Todo.completed == completed)
|
|
|
|
return query.count()
|
|
|
|
|
|
def create_todo(db: Session, todo: TodoCreate) -> Todo:
|
|
"""Create a new todo item."""
|
|
db_todo = Todo(**todo.model_dump())
|
|
db.add(db_todo)
|
|
db.commit()
|
|
db.refresh(db_todo)
|
|
return db_todo
|
|
|
|
|
|
def update_todo(db: Session, todo_id: int, todo: TodoUpdate) -> Optional[Todo]:
|
|
"""Update an existing todo item."""
|
|
db_todo = get_todo(db, todo_id)
|
|
if db_todo is None:
|
|
return None
|
|
|
|
update_data = todo.model_dump(exclude_unset=True)
|
|
for field, value in update_data.items():
|
|
setattr(db_todo, field, value)
|
|
|
|
db.commit()
|
|
db.refresh(db_todo)
|
|
return db_todo
|
|
|
|
|
|
def delete_todo(db: Session, todo_id: int) -> Union[bool, None]:
|
|
"""Delete a todo item by its ID."""
|
|
db_todo = get_todo(db, todo_id)
|
|
if db_todo is None:
|
|
return None
|
|
|
|
db.delete(db_todo)
|
|
db.commit()
|
|
return True |