61 lines
1.7 KiB
Python
61 lines
1.7 KiB
Python
import uuid
|
|
from typing import List, Optional
|
|
from sqlalchemy.orm import Session
|
|
from models.book import Book
|
|
from models.author import Author
|
|
from schemas.book import BookCreate, BookSchema
|
|
|
|
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.
|
|
"""
|
|
authors = [db.query(Author).get(author_id) for author_id in book_data.author_ids]
|
|
if any(author is None for author in authors):
|
|
raise ValueError("One or more author IDs are invalid")
|
|
|
|
db_book = Book(
|
|
title=book_data.title,
|
|
description=book_data.description,
|
|
year_published=book_data.year_published,
|
|
authors=authors
|
|
)
|
|
db.add(db_book)
|
|
db.commit()
|
|
db.refresh(db_book)
|
|
return db_book
|
|
|
|
def get_book_by_id(db: Session, book_id: uuid.UUID) -> Optional[BookSchema]:
|
|
"""
|
|
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[BookSchema]: The book schema object if found, otherwise None.
|
|
"""
|
|
book = db.query(Book).filter(Book.id == book_id).first()
|
|
if book:
|
|
return BookSchema.from_orm(book)
|
|
return None
|
|
|
|
def get_all_books(db: Session) -> List[BookSchema]:
|
|
"""
|
|
Retrieves all books from the database.
|
|
|
|
Args:
|
|
db (Session): The database session.
|
|
|
|
Returns:
|
|
List[BookSchema]: A list of all book schema objects.
|
|
"""
|
|
books = db.query(Book).all()
|
|
return [BookSchema.from_orm(book) for book in books] |