add custum SQL in persistant state

This commit is contained in:
simon987 2021-01-17 10:05:39 -05:00
parent f914759b71
commit d615ebdbd9
3 changed files with 22 additions and 1 deletions

View File

@ -90,6 +90,16 @@ class Table:
self._state = state
self._table = table
def sql(self, where_clause, *params):
with sqlite3.connect(self._state.dbfile, **self._state.dbargs) as conn:
conn.row_factory = sqlite3.Row
try:
cur = conn.execute("SELECT * FROM %s %s" % (self._table, where_clause), params)
for row in cur:
yield dict(row)
except:
return None
def __iter__(self):
with sqlite3.connect(self._state.dbfile, **self._state.dbargs) as conn:
conn.row_factory = sqlite3.Row

View File

@ -2,7 +2,7 @@ from setuptools import setup
setup(
name="hexlib",
version="1.23",
version="1.24",
description="Misc utility methods",
author="simon987",
author_email="me@simon987.net",

View File

@ -75,3 +75,14 @@ class TestPersistentState(TestCase):
val["id"] = 1
self.assertDictEqual(val, s["a"][1])
def test_sql(self):
s = PersistentState()
s["a"][1] = {"a": True}
s["a"][2] = {"a": False}
s["a"][3] = {"a": True}
items = list(s["a"].sql("WHERE a=0 ORDER BY id"))
self.assertDictEqual(items[0], s["a"][2])