Get rid of varargs in sql.run_query.

Things are clearer when just passing a list.
This commit is contained in:
Ryan Roden-Corrent 2017-02-14 08:59:01 -05:00
parent b70d5ba901
commit df995c02a3
7 changed files with 55 additions and 56 deletions

View File

@ -188,8 +188,8 @@ class WebHistory(sql.SqlTable):
def _add_entry(self, entry): def _add_entry(self, entry):
"""Add an entry to the in-memory database.""" """Add an entry to the in-memory database."""
self.insert(entry.url_str(), entry.title, entry.atime, entry.redirect, self.insert([entry.url_str(), entry.title, entry.atime,
replace=True) entry.redirect], replace=True)
def get_recent(self): def get_recent(self):
"""Get the most recent history entries.""" """Get the most recent history entries."""

View File

@ -128,7 +128,7 @@ class QuickmarkManager(UrlMarkManager):
except ValueError: except ValueError:
message.error("Invalid quickmark '{}'".format(line)) message.error("Invalid quickmark '{}'".format(line))
else: else:
self.insert(key, url) self.insert([key, url])
def prompt_save(self, url): def prompt_save(self, url):
"""Prompt for a new quickmark name to be added and add it. """Prompt for a new quickmark name to be added and add it.
@ -168,7 +168,7 @@ class QuickmarkManager(UrlMarkManager):
def set_mark(): def set_mark():
"""Really set the quickmark.""" """Really set the quickmark."""
self.insert(name, url) self.insert([name, url])
log.misc.debug("Added quickmark {} for {}".format(name, url)) log.misc.debug("Added quickmark {} for {}".format(name, url))
if name in self: if name in self:
@ -231,7 +231,7 @@ class BookmarkManager(UrlMarkManager):
parts = line.split(maxsplit=1) parts = line.split(maxsplit=1)
urlstr = parts[0] urlstr = parts[0]
title = parts[1] if len(parts) == 2 else '' title = parts[1] if len(parts) == 2 else ''
self.insert(urlstr, title) self.insert([urlstr, title])
def add(self, url, title, *, toggle=False): def add(self, url, title, *, toggle=False):
"""Add a new bookmark. """Add a new bookmark.
@ -259,5 +259,5 @@ class BookmarkManager(UrlMarkManager):
else: else:
raise AlreadyExistsError("Bookmark already exists!") raise AlreadyExistsError("Bookmark already exists!")
else: else:
self.insert(urlstr, title) self.insert([urlstr, title])
return True return True

View File

@ -52,8 +52,7 @@ class SqlCompletionCategory(QSqlQueryModel):
self.set_pattern('%') self.set_pattern('%')
def set_pattern(self, pattern): def set_pattern(self, pattern):
# TODO: kill star-args for run_query query = sql.run_query(self._querystr, [pattern for _ in self._fields])
query = sql.run_query(self._querystr, *[pattern for _ in self._fields])
self.setQuery(query) self.setQuery(query)

View File

@ -39,17 +39,17 @@ def close():
QSqlDatabase.removeDatabase(QSqlDatabase.database().connectionName()) QSqlDatabase.removeDatabase(QSqlDatabase.database().connectionName())
def run_query(querystr, *values): def run_query(querystr, values=None):
"""Run the given SQL query string on the database. """Run the given SQL query string on the database.
Args: Args:
values: positional parameter bindings. values: A list of positional parameter bindings.
""" """
log.completion.debug('Running SQL query: "{}"'.format(querystr)) log.completion.debug('Running SQL query: "{}"'.format(querystr))
database = QSqlDatabase.database() database = QSqlDatabase.database()
query = QSqlQuery(database) query = QSqlQuery(database)
query.prepare(querystr) query.prepare(querystr)
for val in values: for val in values or []:
query.addBindValue(val) query.addBindValue(val)
log.completion.debug('Query bindings: {}'.format(query.boundValues())) log.completion.debug('Query bindings: {}'.format(query.boundValues()))
if not query.exec_(): if not query.exec_():
@ -102,7 +102,7 @@ class SqlTable(QObject):
key: Primary key value to search for. key: Primary key value to search for.
""" """
query = run_query("SELECT * FROM {} where {} = ?" query = run_query("SELECT * FROM {} where {} = ?"
.format(self._name, self._primary_key), key) .format(self._name, self._primary_key), [key])
return query.next() return query.next()
def __len__(self): def __len__(self):
@ -118,7 +118,7 @@ class SqlTable(QObject):
key: Primary key value to fetch. key: Primary key value to fetch.
""" """
result = run_query("SELECT * FROM {} where {} = ?" result = run_query("SELECT * FROM {} where {} = ?"
.format(self._name, self._primary_key), key) .format(self._name, self._primary_key), [key])
result.next() result.next()
rec = result.record() rec = result.record()
return tuple(rec.value(i) for i in range(rec.count())) return tuple(rec.value(i) for i in range(rec.count()))
@ -135,22 +135,22 @@ class SqlTable(QObject):
""" """
field = field or self._primary_key field = field or self._primary_key
query = run_query("DELETE FROM {} where {} = ?" query = run_query("DELETE FROM {} where {} = ?"
.format(self._name, field), value) .format(self._name, field), [value])
if not query.numRowsAffected(): if not query.numRowsAffected():
raise KeyError('No row with {} = "{}"'.format(field, value)) raise KeyError('No row with {} = "{}"'.format(field, value))
self.changed.emit() self.changed.emit()
def insert(self, *values, replace=False): def insert(self, values, replace=False):
"""Append a row to the table. """Append a row to the table.
Args: Args:
values: Values in the order fields were given on table creation. values: A list of values to insert.
replace: If true, allow inserting over an existing primary key. replace: If true, allow inserting over an existing primary key.
""" """
cmd = "REPLACE" if replace else "INSERT" cmd = "REPLACE" if replace else "INSERT"
paramstr = ','.join(['?'] * len(values)) paramstr = ','.join(['?'] * len(values))
run_query("{} INTO {} values({})" run_query("{} INTO {} values({})"
.format(cmd, self._name, paramstr), *values) .format(cmd, self._name, paramstr), values)
self.changed.emit() self.changed.emit()
def delete_all(self): def delete_all(self):

View File

@ -135,18 +135,18 @@ def _mock_view_index(model, category_idx, child_idx, qtbot):
def quickmarks(init_sql): def quickmarks(init_sql):
"""Pre-populate the quickmark database.""" """Pre-populate the quickmark database."""
table = sql.SqlTable('Quickmarks', ['name', 'url'], primary_key='name') table = sql.SqlTable('Quickmarks', ['name', 'url'], primary_key='name')
table.insert('aw', 'https://wiki.archlinux.org') table.insert(['aw', 'https://wiki.archlinux.org'])
table.insert('ddg', 'https://duckduckgo.com') table.insert(['ddg', 'https://duckduckgo.com'])
table.insert('wiki', 'https://wikipedia.org') table.insert(['wiki', 'https://wikipedia.org'])
@pytest.fixture @pytest.fixture
def bookmarks(init_sql): def bookmarks(init_sql):
"""Pre-populate the bookmark database.""" """Pre-populate the bookmark database."""
table = sql.SqlTable('Bookmarks', ['url', 'title'], primary_key='url') table = sql.SqlTable('Bookmarks', ['url', 'title'], primary_key='url')
table.insert('https://github.com', 'GitHub') table.insert(['https://github.com', 'GitHub'])
table.insert('https://python.org', 'Welcome to Python.org') table.insert(['https://python.org', 'Welcome to Python.org'])
table.insert('http://qutebrowser.org', 'qutebrowser | qutebrowser') table.insert(['http://qutebrowser.org', 'qutebrowser | qutebrowser'])
@pytest.fixture @pytest.fixture
@ -154,12 +154,12 @@ def web_history(stubs, init_sql):
"""Pre-populate the web-history database.""" """Pre-populate the web-history database."""
table = sql.SqlTable("History", ['url', 'title', 'atime', 'redirect'], table = sql.SqlTable("History", ['url', 'title', 'atime', 'redirect'],
primary_key='url') primary_key='url')
table.insert('http://qutebrowser.org', 'qutebrowser', table.insert(['http://qutebrowser.org', 'qutebrowser',
datetime(2015, 9, 5).timestamp(), False) datetime(2015, 9, 5).timestamp(), False])
table.insert('https://python.org', 'Welcome to Python.org', table.insert(['https://python.org', 'Welcome to Python.org',
datetime(2016, 3, 8).timestamp(), False) datetime(2016, 3, 8).timestamp(), False])
table.insert('https://github.com', 'https://github.com', table.insert(['https://github.com', 'https://github.com',
datetime(2016, 5, 1).timestamp(), False) datetime(2016, 5, 1).timestamp(), False])
def test_command_completion(qtmodeltester, monkeypatch, stubs, config_stub, def test_command_completion(qtmodeltester, monkeypatch, stubs, config_stub,

View File

@ -67,7 +67,7 @@ def test_count(rowcounts, expected):
name = 'Foo' + str(i) name = 'Foo' + str(i)
table = sql.SqlTable(name, ['a'], primary_key='a') table = sql.SqlTable(name, ['a'], primary_key='a')
for rownum in range(rowcount): for rownum in range(rowcount):
table.insert(rownum) table.insert([rownum])
model.new_category(name) model.new_category(name)
assert model.count() == expected assert model.count() == expected
@ -104,7 +104,7 @@ def test_count(rowcounts, expected):
def test_sorting(sort_by, sort_order, data, expected): def test_sorting(sort_by, sort_order, data, expected):
table = sql.SqlTable('Foo', ['a', 'b', 'c'], primary_key='a') table = sql.SqlTable('Foo', ['a', 'b', 'c'], primary_key='a')
for row in data: for row in data:
table.insert(*row) table.insert(row)
model = sqlmodel.SqlCompletionModel() model = sqlmodel.SqlCompletionModel()
model.new_category('Foo', sort_by=sort_by, sort_order=sort_order) model.new_category('Foo', sort_by=sort_by, sort_order=sort_order)
_check_model(model, [('Foo', expected)]) _check_model(model, [('Foo', expected)])
@ -166,7 +166,7 @@ def test_set_pattern(pattern, filter_cols, before, after):
for name, rows in before: for name, rows in before:
table = sql.SqlTable(name, ['a', 'b', 'c'], primary_key='a') table = sql.SqlTable(name, ['a', 'b', 'c'], primary_key='a')
for row in rows: for row in rows:
table.insert(*row) table.insert(row)
model.new_category(name) model.new_category(name)
model.set_pattern(pattern) model.set_pattern(pattern)
_check_model(model, after) _check_model(model, after)
@ -197,7 +197,7 @@ def test_first_last_item(data, first, last):
for name, rows in data: for name, rows in data:
table = sql.SqlTable(name, ['a'], primary_key='a') table = sql.SqlTable(name, ['a'], primary_key='a')
for row in rows: for row in rows:
table.insert(row) table.insert([row])
model.new_category(name) model.new_category(name)
assert model.data(model.first_item()) == first assert model.data(model.first_item()) == first
assert model.data(model.last_item()) == last assert model.data(model.last_item()) == last

View File

@ -36,19 +36,19 @@ def test_init():
def test_insert(qtbot): def test_insert(qtbot):
table = sql.SqlTable('Foo', ['name', 'val', 'lucky'], primary_key='name') table = sql.SqlTable('Foo', ['name', 'val', 'lucky'], primary_key='name')
with qtbot.waitSignal(table.changed): with qtbot.waitSignal(table.changed):
table.insert('one', 1, False) table.insert(['one', 1, False])
with qtbot.waitSignal(table.changed): with qtbot.waitSignal(table.changed):
table.insert('wan', 1, False) table.insert(['wan', 1, False])
with pytest.raises(sql.SqlException): with pytest.raises(sql.SqlException):
# duplicate primary key # duplicate primary key
table.insert('one', 1, False) table.insert(['one', 1, False])
def test_iter(): def test_iter():
table = sql.SqlTable('Foo', ['name', 'val', 'lucky'], primary_key='name') table = sql.SqlTable('Foo', ['name', 'val', 'lucky'], primary_key='name')
table.insert('one', 1, False) table.insert(['one', 1, False])
table.insert('nine', 9, False) table.insert(['nine', 9, False])
table.insert('thirteen', 13, True) table.insert(['thirteen', 13, True])
assert list(table) == [('one', 1, False), assert list(table) == [('one', 1, False),
('nine', 9, False), ('nine', 9, False),
('thirteen', 13, True)] ('thirteen', 13, True)]
@ -56,17 +56,17 @@ def test_iter():
def test_replace(qtbot): def test_replace(qtbot):
table = sql.SqlTable('Foo', ['name', 'val', 'lucky'], primary_key='name') table = sql.SqlTable('Foo', ['name', 'val', 'lucky'], primary_key='name')
table.insert('one', 1, False) table.insert(['one', 1, False])
with qtbot.waitSignal(table.changed): with qtbot.waitSignal(table.changed):
table.insert('one', 1, True, replace=True) table.insert(['one', 1, True], replace=True)
assert list(table) == [('one', 1, True)] assert list(table) == [('one', 1, True)]
def test_delete(qtbot): def test_delete(qtbot):
table = sql.SqlTable('Foo', ['name', 'val', 'lucky'], primary_key='name') table = sql.SqlTable('Foo', ['name', 'val', 'lucky'], primary_key='name')
table.insert('one', 1, False) table.insert(['one', 1, False])
table.insert('nine', 9, False) table.insert(['nine', 9, False])
table.insert('thirteen', 13, True) table.insert(['thirteen', 13, True])
with pytest.raises(KeyError): with pytest.raises(KeyError):
table.delete('nope') table.delete('nope')
with qtbot.waitSignal(table.changed): with qtbot.waitSignal(table.changed):
@ -80,19 +80,19 @@ def test_delete(qtbot):
def test_len(): def test_len():
table = sql.SqlTable('Foo', ['name', 'val', 'lucky'], primary_key='name') table = sql.SqlTable('Foo', ['name', 'val', 'lucky'], primary_key='name')
assert len(table) == 0 assert len(table) == 0
table.insert('one', 1, False) table.insert(['one', 1, False])
assert len(table) == 1 assert len(table) == 1
table.insert('nine', 9, False) table.insert(['nine', 9, False])
assert len(table) == 2 assert len(table) == 2
table.insert('thirteen', 13, True) table.insert(['thirteen', 13, True])
assert len(table) == 3 assert len(table) == 3
def test_contains(): def test_contains():
table = sql.SqlTable('Foo', ['name', 'val', 'lucky'], primary_key='name') table = sql.SqlTable('Foo', ['name', 'val', 'lucky'], primary_key='name')
table.insert('one', 1, False) table.insert(['one', 1, False])
table.insert('nine', 9, False) table.insert(['nine', 9, False])
table.insert('thirteen', 13, True) table.insert(['thirteen', 13, True])
assert 'oone' not in table assert 'oone' not in table
assert 'ninee' not in table assert 'ninee' not in table
assert 1 not in table assert 1 not in table
@ -104,9 +104,9 @@ def test_contains():
def test_index(): def test_index():
table = sql.SqlTable('Foo', ['name', 'val', 'lucky'], primary_key='name') table = sql.SqlTable('Foo', ['name', 'val', 'lucky'], primary_key='name')
table.insert('one', 1, False) table.insert(['one', 1, False])
table.insert('nine', 9, False) table.insert(['nine', 9, False])
table.insert('thirteen', 13, True) table.insert(['thirteen', 13, True])
assert table['one'] == ('one', 1, False) assert table['one'] == ('one', 1, False)
assert table['nine'] == ('nine', 9, False) assert table['nine'] == ('nine', 9, False)
assert table['thirteen'] == ('thirteen', 13, True) assert table['thirteen'] == ('thirteen', 13, True)
@ -114,9 +114,9 @@ def test_index():
def test_delete_all(qtbot): def test_delete_all(qtbot):
table = sql.SqlTable('Foo', ['name', 'val', 'lucky'], primary_key='name') table = sql.SqlTable('Foo', ['name', 'val', 'lucky'], primary_key='name')
table.insert('one', 1, False) table.insert(['one', 1, False])
table.insert('nine', 9, False) table.insert(['nine', 9, False])
table.insert('thirteen', 13, True) table.insert(['thirteen', 13, True])
with qtbot.waitSignal(table.changed): with qtbot.waitSignal(table.changed):
table.delete_all() table.delete_all()
assert list(table) == [] assert list(table) == []