From d3bbcb6b635c686f440b52475345720cad6cb807 Mon Sep 17 00:00:00 2001 From: Labrys of Knossos Date: Mon, 8 Apr 2019 19:23:21 -0400 Subject: [PATCH 1/2] Remove unnecessary dict factory for database. --- core/main_db.py | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/core/main_db.py b/core/main_db.py index 4be8aa3c..220b44ca 100644 --- a/core/main_db.py +++ b/core/main_db.py @@ -37,10 +37,7 @@ class DBConnection(object): self.filename = filename self.connection = sqlite3.connect(db_filename(filename), 20) - if row_type == 'dict': - self.connection.row_factory = self._dict_factory - else: - self.connection.row_factory = sqlite3.Row + self.connection.row_factory = sqlite3.Row def check_db_version(self): result = None @@ -214,13 +211,6 @@ class DBConnection(object): for column in cursor } - # http://stackoverflow.com/questions/3300464/how-can-i-get-dict-from-sqlite-query - def _dict_factory(self, cursor, row): - return { - col[0]: row[idx] - for idx, col in enumerate(cursor.description) - } - def sanity_check_database(connection, sanity_check): sanity_check(connection).check() From 455915907b97fd80a4666291134ad10257c45e18 Mon Sep 17 00:00:00 2001 From: Labrys of Knossos Date: Mon, 8 Apr 2019 19:22:16 -0400 Subject: [PATCH 2/2] Fix key access for sqlite3.Row on Python 2.7 Fixes #1607 --- core/main_db.py | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/core/main_db.py b/core/main_db.py index 220b44ca..d9d7c1b9 100644 --- a/core/main_db.py +++ b/core/main_db.py @@ -11,11 +11,37 @@ import re import sqlite3 import time -from six import text_type +from six import text_type, PY2 import core from core import logger +if PY2: + class Row(sqlite3.Row, object): + """ + Row factory that uses Byte Strings for keys. + + The sqlite3.Row in Python 2 does not support unicode keys. + This overrides __getitem__ to attempt to encode the key to bytes first. + """ + + def __getitem__(self, item): + """ + Get an item from the row by index or key. + + :param item: Index or Key of item to return. + :return: An item from the sqlite3.Row. + """ + try: + # sqlite3.Row column names should be Bytes in Python 2 + item = item.encode() + except AttributeError: + pass # assume item is a numeric index + + return super(Row, self).__getitem__(item) +else: + from sqlite3 import Row + def db_filename(filename='nzbtomedia.db', suffix=None): """ @@ -37,7 +63,7 @@ class DBConnection(object): self.filename = filename self.connection = sqlite3.connect(db_filename(filename), 20) - self.connection.row_factory = sqlite3.Row + self.connection.row_factory = Row def check_db_version(self): result = None