from flask import current_app from flask import g import sqlite3 from .book import Book def get_db(): """Connect to the application's configured database. The connection is unique for each request and will be reused if this is called again. """ if "db" not in g: g.db = sqlite3.connect( current_app.config["DATABASE"], detect_types=sqlite3.PARSE_DECLTYPES ) g.db.row_factory = sqlite3.Row return g.db def get_book(isbn): db = get_db() data = db.execute( """ SELECT * FROM book WHERE isbn=? """, (isbn,) ).fetchone() if data is None: raise IndexError("Book not in db") book = Book(isbn) book._manual_load( data["title"], publisher=data["publisher"], publish_date=data["publish_date"], author=data["author"], count=data["count"], category=data["category"] if data["category"] != "" else None ) return book def delete_book(isbn): db = get_db() data = db.execute( """ DELETE FROM book WHERE isbn=? """, (isbn,) ) db.commit() def increment_count(book): if book.count == -1: book = get_book(book.isbn) db = get_db() db.execute( """ UPDATE book SET count=? WHERE isbn=? """, (book.count+1, book.isbn) ) db.commit() def add_book(book): try: book = get_book(book.isbn) increment_count(book) return "duplicate" except IndexError: if book.count == -1: book.count = 1 db = get_db() db.execute( """ INSERT INTO book (isbn, count, title, author, publisher, publish_date, category) VALUES (?, ?, ?, ?, ?, ?, ?) """, (book.isbn, book.count, book.title, book.author, book.publisher, book.publish_date, book.category) ) db.commit() return "added" def update_book(book): db = get_db() db.execute( """ UPDATE book SET count=?, title=?, author=?, publisher=?, publish_date=?, category=? WHERE isbn=? """, (book.count, book.title, book.author, book.publisher, book.publish_date, book.category, book.isbn) ) db.commit() return "updated" def get_all_books(): def count_none(book): count = 0 if book.title is None: count += 1 if book.author is None: count += 1 if book.publish_date is None: count += 1 if book.publisher is None: count += 1 if book.category is None: count += 1 return -count db = get_db() data = db.execute( """ SELECT * FROM book """ ).fetchall() books = [] for data_row in data: book = Book(data_row["isbn"]) book._manual_load( data_row["title"], publisher=data_row["publisher"], publish_date=data_row["publish_date"], author=data_row["author"], count=data_row["count"], category=data_row["category"] if data_row["category"] != "" else None ) books.append(book) return sorted(books, key=count_none) def get_categories(): db = get_db() data = db.execute( """ SELECT DISTINCT category FROM book """ ).fetchall() return [row["category"] for row in data]