feat: Add helper functions for Book
This commit is contained in:
parent
81300c5768
commit
6b10bedd9a
71
helpers/book_helpers.py
Normal file
71
helpers/book_helpers.py
Normal file
@ -0,0 +1,71 @@
|
|||||||
|
from typing import Optional
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from models.book import Book
|
||||||
|
from schemas.book import BookCreate
|
||||||
|
|
||||||
|
def create_book(db: Session, book: BookCreate) -> Optional[Book]:
|
||||||
|
"""
|
||||||
|
Create a new book in the database.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
db (Session): SQLAlchemy database session.
|
||||||
|
book (BookCreate): Pydantic model containing book data.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Optional[Book]: The created book object, or None if creation failed.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
db_book = Book(
|
||||||
|
title=book.title,
|
||||||
|
author=book.author,
|
||||||
|
description=book.description,
|
||||||
|
page_count=book.page_count,
|
||||||
|
genre=book.genre,
|
||||||
|
publisher_id=book.publisher_id
|
||||||
|
)
|
||||||
|
db.add(db_book)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(db_book)
|
||||||
|
return db_book
|
||||||
|
except Exception as e:
|
||||||
|
db.rollback()
|
||||||
|
print(f"Error creating book: {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
def get_book_by_id(db: Session, book_id: str) -> Optional[Book]:
|
||||||
|
"""
|
||||||
|
Get a book by its ID from the database.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
db (Session): SQLAlchemy database session.
|
||||||
|
book_id (str): UUID of the book.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Optional[Book]: The book object if found, or None if not found.
|
||||||
|
"""
|
||||||
|
return db.query(Book).filter(Book.id == book_id).first()
|
||||||
|
|
||||||
|
def get_book_by_title(db: Session, title: str) -> Optional[Book]:
|
||||||
|
"""
|
||||||
|
Get a book by its title from the database.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
db (Session): SQLAlchemy database session.
|
||||||
|
title (str): Title of the book.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Optional[Book]: The book object if found, or None if not found.
|
||||||
|
"""
|
||||||
|
return db.query(Book).filter(Book.title == title).first()
|
||||||
|
|
||||||
|
def validate_page_count(page_count: int) -> bool:
|
||||||
|
"""
|
||||||
|
Validate the page count for a book.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
page_count (int): Number of pages in the book.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
bool: True if the page count is valid (greater than 0), False otherwise.
|
||||||
|
"""
|
||||||
|
return page_count > 0
|
Loading…
x
Reference in New Issue
Block a user