summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorFlorian Bruhin <me@the-compiler.org>2021-01-14 11:22:56 +0100
committerFlorian Bruhin <me@the-compiler.org>2021-01-14 11:24:31 +0100
commit4d893e75a175d7f05c5627a1dca4e176ce1e70e6 (patch)
tree2d6e5f0e1edcc78c1ab007637ab79f0e72478588
parent0f0a59c279c60f9a327cbf976637387c39bcf7b5 (diff)
downloadqutebrowser-4d893e75a175d7f05c5627a1dca4e176ce1e70e6.tar.gz
qutebrowser-4d893e75a175d7f05c5627a1dca4e176ce1e70e6.zip
sql: Add Query.__bool__
Makes it clearer what the intent is (rather than implicitly falling back on __len__ via Python) and also happens to be a small (most probably insignificant) performance improvement. On my machine, without a __bool__: Name (time in us) Min Max Median test_bool_benchmark 144.2940 879.5960 167.2730 With it: Name (time in us) Min Max Median test_bool_benchmark 133.3990 876.1080 152.1879
-rw-r--r--qutebrowser/misc/sql.py6
-rw-r--r--tests/unit/misc/test_sql.py20
2 files changed, 26 insertions, 0 deletions
diff --git a/qutebrowser/misc/sql.py b/qutebrowser/misc/sql.py
index 7844253f0..090c3a5d2 100644
--- a/qutebrowser/misc/sql.py
+++ b/qutebrowser/misc/sql.py
@@ -394,6 +394,12 @@ class SqlTable(QObject):
q.run()
return q.value()
+ def __bool__(self):
+ """Check whether there's any data in the table."""
+ q = Query(f"SELECT 1 FROM {self._name} LIMIT 1")
+ q.run()
+ return q.query.next()
+
def delete(self, field, value, *, optional=False, like=False):
"""Remove all rows for which `field` equals `value`.
diff --git a/tests/unit/misc/test_sql.py b/tests/unit/misc/test_sql.py
index 3edbbffb0..ab34727a9 100644
--- a/tests/unit/misc/test_sql.py
+++ b/tests/unit/misc/test_sql.py
@@ -255,6 +255,26 @@ def test_len():
assert len(table) == 3
+def test_bool():
+ table = sql.SqlTable('Foo', ['name'])
+ assert not table
+ table.insert({'name': 'one'})
+ assert table
+
+
+def test_bool_benchmark(benchmark):
+ table = sql.SqlTable('Foo', ['number'])
+
+ # Simulate a history table
+ table.create_index('NumberIndex', 'number')
+ table.insert_batch({'number': [str(i) for i in range(100_000)]})
+
+ def run():
+ assert table
+
+ benchmark(run)
+
+
def test_contains():
table = sql.SqlTable('Foo', ['name', 'val', 'lucky'])
table.insert({'name': 'one', 'val': 1, 'lucky': False})