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):
"""Add an entry to the in-memory database."""
self.insert(entry.url_str(), entry.title, entry.atime, entry.redirect,
replace=True)
self.insert([entry.url_str(), entry.title, entry.atime,
entry.redirect], replace=True)
def get_recent(self):
"""Get the most recent history entries."""

View File

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

View File

@ -52,8 +52,7 @@ class SqlCompletionCategory(QSqlQueryModel):
self.set_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)

View File

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

View File

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

View File

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

View File

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