book-keeping-of5kwb/helpers/book_helpers.py

50 lines
1.4 KiB
Python

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_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 find_book_by_title_and_author(db: Session, title: str, author: str) -> Optional[Book]:
"""
Finds a book by its title and author.
Args:
db (Session): The database session.
title (str): The title of the book.
author (str): The author of the book.
Returns:
Optional[Book]: The book if found, otherwise None.
"""
return db.query(Book).filter(Book.title == title, Book.author == author).first()
def book_exists(db: Session, title: str, author: str) -> bool:
"""
Checks if a book with the given title and author already exists.
Args:
db (Session): The database session.
title (str): The title of the book.
author (str): The author of the book.
Returns:
bool: True if the book exists, False otherwise.
"""
book = find_book_by_title_and_author(db, title, author)
return book is not None