from typing import List, Optional from sqlalchemy.orm import Session from models.book import Book from schemas.book import UserBookCreate, UserBookUpdate import uuid def get_user_books(db: Session, title: Optional[str] = None, author: Optional[str] = None, genre: Optional[str] = None) -> List[Book]: """ Retrieves a list of user books from the database based on optional filters. Args: db (Session): The database session. title (Optional[str]): Filter by book title. author (Optional[str]): Filter by book author. genre (Optional[str]): Filter by book genre. Returns: List[Book]: A list of book objects matching the filters. """ query = db.query(Book) if title: query = query.filter(Book.title.ilike(f"%{title}%")) if author: query = query.filter(Book.author.ilike(f"%{author}%")) if genre: query = query.filter(Book.genre.ilike(f"%{genre}%")) return query.all() def create_user_book(db: Session, book_data: UserBookCreate) -> Book: """ Creates a new user book in the database. Args: db (Session): The database session. book_data (UserBookCreate): The data for the book to create. Returns: Book: The newly created book object. """ db_book = Book(**book_data.dict()) db.add(db_book) db.commit() db.refresh(db_book) return db_book def get_user_book_by_id(db: Session, book_id: uuid.UUID) -> Optional[Book]: """ Retrieves a single user book by its ID. Args: db (Session): The database session. book_id (UUID): The ID of the book to retrieve. Returns: Optional[Book]: The book object if found, otherwise None. """ return db.query(Book).filter(Book.id == book_id).first() def update_user_book(db: Session, book_id: uuid.UUID, book_data: UserBookUpdate) -> Optional[Book]: """ Updates an existing user book in the database. Args: db (Session): The database session. book_id (UUID): The ID of the book to update. book_data (UserBookUpdate): The updated data for the book. Returns: Optional[Book]: The updated book object if found, otherwise None. """ db_book = db.query(Book).filter(Book.id == book_id).first() if db_book: update_data = book_data.dict(exclude_unset=True) for key, value in update_data.items(): setattr(db_book, key, value) db.commit() db.refresh(db_book) return db_book return None def delete_user_book(db: Session, book_id: uuid.UUID) -> bool: """ Deletes a user book from the database. Args: db (Session): The database session. book_id (UUID): The ID of the book to delete. Returns: bool: True if the book was deleted, False otherwise. """ db_book = db.query(Book).filter(Book.id == book_id).first() if db_book: db.delete(db_book) db.commit() return True return False