64 lines
1.6 KiB
Python
64 lines
1.6 KiB
Python
from typing import Optional
|
|
|
|
from sqlalchemy.orm import Session
|
|
|
|
from api.schemas.todo import TodoCreate, TodoUpdate
|
|
from db.models import Todo
|
|
|
|
|
|
def get_todos(db: Session, user_id: int, skip: int = 0, limit: int = 100) -> list[Todo]:
|
|
"""
|
|
Get all todos for a user with pagination
|
|
"""
|
|
return db.query(Todo).filter(Todo.owner_id == user_id).offset(skip).limit(limit).all()
|
|
|
|
|
|
def get_todo(db: Session, todo_id: int, user_id: int) -> Optional[Todo]:
|
|
"""
|
|
Get a specific todo by ID for a specific user
|
|
"""
|
|
return db.query(Todo).filter(Todo.id == todo_id, Todo.owner_id == user_id).first()
|
|
|
|
|
|
def create_todo(db: Session, todo: TodoCreate, user_id: int) -> Todo:
|
|
"""
|
|
Create a new todo for a user
|
|
"""
|
|
db_todo = Todo(**todo.dict(), owner_id=user_id)
|
|
db.add(db_todo)
|
|
db.commit()
|
|
db.refresh(db_todo)
|
|
return db_todo
|
|
|
|
|
|
def update_todo(db: Session, todo_id: int, todo: TodoUpdate, user_id: int) -> Optional[Todo]:
|
|
"""
|
|
Update an existing todo for a user
|
|
"""
|
|
db_todo = get_todo(db, todo_id, user_id)
|
|
if db_todo is None:
|
|
return None
|
|
|
|
# Update only provided fields
|
|
todo_data = todo.dict(exclude_unset=True)
|
|
for key, value in todo_data.items():
|
|
setattr(db_todo, key, value)
|
|
|
|
db.commit()
|
|
db.refresh(db_todo)
|
|
return db_todo
|
|
|
|
|
|
def delete_todo(db: Session, todo_id: int, user_id: int) -> bool:
|
|
"""
|
|
Delete a todo by ID for a user
|
|
Returns True if the todo was deleted, False if it didn't exist
|
|
"""
|
|
db_todo = get_todo(db, todo_id, user_id)
|
|
if db_todo is None:
|
|
return False
|
|
|
|
db.delete(db_todo)
|
|
db.commit()
|
|
return True
|