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.

64 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__)
3 years ago
class Database:
3 years ago
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)
3 years ago
self.con.row_factory = factory
3 years ago
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:
3 years ago
self.con.close()
logging.info("Connection to db closed")
3 years ago
return result_list
def select_books_by_title(self, query):
3 years ago
query = format_query(query)
3 years ago
sql = f"""
3 years ago
SELECT title, author_sort, path FROM books
3 years ago
WHERE title LIKE "{query}";
3 years ago
"""
3 years ago
return self._execute(sql, res.book_factory)
3 years ago
def select_books_by_author(self, query):
3 years ago
query = 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
3 years ago
WHERE sort LIKE "{query}") || '%';
3 years ago
"""
3 years ago
return self._execute(sql, res.book_factory)
3 years ago
def select_authors(self, query):
3 years ago
query = format_query(query)
3 years ago
sql = f"""
3 years ago
SELECT name, sort FROM authors
3 years ago
WHERE name LIKE "{query}";
3 years ago
"""
3 years ago
return self._execute(sql, res.author_factory)
3 years ago
3 years ago
def format_query(query):
formatted_query = "%" + query.replace(" ", "%") + "%"
return formatted_query