You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
1.8 KiB
Python

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import libreremo_res as res
import sqlite3 as sql3
logger = logging.getLogger(__name__)
class Database:
def __init__(self, filename):
self.filename = filename
self.con = None
self.cur = None
def _execute(self, sql, factory):
result_list = None
try:
self.con = sql3.connect(self.filename)
self.con.row_factory = factory
self.cur = self.con.cursor()
logging.info("Connection to db open")
self.cur.execute(sql)
result_list = self.cur.fetchall()
except sql3.Error as error:
logging.info("an error occured", error)
finally:
if self.con:
self.con.close()
logging.info("Connection to db closed")
return result_list
def select_books_by_title(self, query):
query = self.__format_query(query)
sql = f"""
SELECT title, author_sort, path FROM books
WHERE title LIKE '{query}';
"""
return self._execute(sql, res.book_factory)
def select_books_by_author(self, query):
query = self.__format_query(query)
sql = f"""
SELECT title, author_sort, path FROM books
WHERE books.author_sort LIKE '%' ||
(SELECT sort FROM authors
WHERE sort LIKE '%{query}%') || '%';
"""
return self._execute(sql, res.book_factory)
def select_authors(self, query):
query = self.__format_query(query)
sql = f"""
SELECT name, sort FROM authors
WHERE name LIKE '{query}';
"""
return self._execute(sql, res.author_factory)
def __format_query(self, query):
formatted_query = "%" + query.replace(" ", "%") + "%"
return formatted_query