isbn-sort/isbn_sort/modules/db.py

127 lines
2.8 KiB
Python

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"],
author=data["author"],
status=data["status_"],
owner=data["owner_"],
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 add_book(book):
try:
book = get_book(book.isbn)
return "duplicate"
except IndexError:
db = get_db()
db.execute(
"""
INSERT INTO book (isbn, title, author, status_, owner_, category)
VALUES (?, ?, ?, ?, ?, ?)
""",
(book.isbn, book.title, book.author, book.status, book.owner, book.category)
)
db.commit()
return "added"
def update_book(book):
db = get_db()
db.execute(
"""
UPDATE book SET title=?, author=?, status_=?, owner_=?, category=?
WHERE isbn=?
""",
(book.title, book.author, book.status, book.owner, 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.owner 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"],
status=data_row["status_"],
owner=data_row["owner_"],
author=data_row["author"],
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]