dev-0hpc7y/helpers/book_helpers.py

90 lines
2.3 KiB
Python

from typing import List, Optional
from sqlalchemy.orm import Session
from models.book import Book
from schemas.book import BookCreate, BookUpdate
import uuid
def get_all_books(db: Session) -> List[Book]:
"""
Retrieves all books from the database.
Args:
db (Session): The database session.
Returns:
List[Book]: A list of all book objects.
"""
return db.query(Book).all()
def get_book_by_id(db: Session, book_id: uuid.UUID) -> Optional[Book]:
"""
Retrieves a single 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 create_book(db: Session, book_data: BookCreate) -> Book:
"""
Creates a new book in the database.
Args:
db (Session): The database session.
book_data (BookCreate): 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 update_book(db: Session, book_id: uuid.UUID, book_data: BookUpdate) -> Optional[Book]:
"""
Updates an existing book in the database.
Args:
db (Session): The database session.
book_id (UUID): The ID of the book to update.
book_data (BookUpdate): 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 not db_book:
return None
for field, value in book_data.dict(exclude_unset=True).items():
setattr(db_book, field, value)
db.add(db_book)
db.commit()
db.refresh(db_book)
return db_book
def delete_book(db: Session, book_id: uuid.UUID) -> bool:
"""
Deletes a 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 successfully deleted, False otherwise.
"""
db_book = db.query(Book).filter(Book.id == book_id).first()
if not db_book:
return False
db.delete(db_book)
db.commit()
return True