From 0e650ad719ecc9b635dc53865073c65732b4bceb Mon Sep 17 00:00:00 2001 From: Ryan Roden-Corrent Date: Wed, 15 Feb 2017 09:06:23 -0500 Subject: [PATCH] Return namedtuples from SqlTable. Instead of returning a regular tuple and trying to remember which index maps to which field, return named tuples that allow accessing the fields by name. --- qutebrowser/browser/urlmarks.py | 2 +- qutebrowser/misc/sql.py | 7 +++++-- tests/unit/completion/test_sqlmodel.py | 6 ++++++ 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/qutebrowser/browser/urlmarks.py b/qutebrowser/browser/urlmarks.py index e28966b24..d9e49b5c2 100644 --- a/qutebrowser/browser/urlmarks.py +++ b/qutebrowser/browser/urlmarks.py @@ -193,7 +193,7 @@ class QuickmarkManager(UrlMarkManager): if name not in self: raise DoesNotExistError("Quickmark '{}' does not exist!" .format(name)) - urlstr = self[name] + urlstr = self[name].url try: url = urlutils.fuzzy_url(urlstr, do_search=False) except urlutils.InvalidUrlError as e: diff --git a/qutebrowser/misc/sql.py b/qutebrowser/misc/sql.py index 11d64bf72..f23d791ad 100644 --- a/qutebrowser/misc/sql.py +++ b/qutebrowser/misc/sql.py @@ -24,6 +24,8 @@ from PyQt5.QtSql import QSqlDatabase, QSqlQuery from qutebrowser.utils import log +import collections + def init(): """Initialize the SQL database connection.""" @@ -87,13 +89,14 @@ class SqlTable(QObject): self._primary_key = primary_key run_query("CREATE TABLE {} ({}, PRIMARY KEY ({}))" .format(name, ','.join(fields), primary_key)) + self.Entry = collections.namedtuple(name + '_Entry', fields) def __iter__(self): """Iterate rows in the table.""" result = run_query("SELECT * FROM {}".format(self._name)) while result.next(): rec = result.record() - yield tuple(rec.value(i) for i in range(rec.count())) + yield self.Entry(*[rec.value(i) for i in range(rec.count())]) def __contains__(self, key): """Return whether the table contains the matching item. @@ -121,7 +124,7 @@ class SqlTable(QObject): .format(self._name, self._primary_key), [key]) result.next() rec = result.record() - return tuple(rec.value(i) for i in range(rec.count())) + return self.Entry(*[rec.value(i) for i in range(rec.count())]) def delete(self, value, field=None): """Remove all rows for which `field` equals `value`. diff --git a/tests/unit/completion/test_sqlmodel.py b/tests/unit/completion/test_sqlmodel.py index b94e8e048..d3e3ada96 100644 --- a/tests/unit/completion/test_sqlmodel.py +++ b/tests/unit/completion/test_sqlmodel.py @@ -231,3 +231,9 @@ def test_where(): model = sqlmodel.SqlCompletionModel() model.new_category('test_where', where='not c') _check_model(model, [('test_where', [('foo', 'bar', False)])]) + +def test_entry(): + table = sql.SqlTable('test_entry', ['a', 'b', 'c'], primary_key='a') + assert hasattr(table.Entry, 'a') + assert hasattr(table.Entry, 'b') + assert hasattr(table.Entry, 'c')