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.

62 lines
1.8 KiB
Python

3 years ago
#!/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):
3 years ago
query = self.__format_query(query)
3 years ago
sql = f"""
3 years ago
SELECT title, author_sort, path FROM books
WHERE title LIKE '{query}';
"""
return self._execute(sql, res.book_factory)
3 years ago
def select_books_by_author(self, query):
3 years ago
query = self.__format_query(query)
3 years ago
sql = f"""
3 years ago
SELECT title, author_sort, path FROM books
WHERE books.author_sort LIKE '%' ||
(SELECT sort FROM authors
WHERE sort = '{query}') || '%';
"""
3 years ago
return self._execute(sql, res.book_factory)
def select_authors(self, query):
3 years ago
query = self.__format_query(query)
3 years ago
sql = f"""
3 years ago
SELECT name, sort FROM authors
WHERE name LIKE '{query}';
"""
3 years ago
return self._execute(sql, res.author_factory)
3 years ago
def __format_query(self, query):
formatted_query = "%" + query.replace(" ", "%") + "%"
return formatted_query