mirror of
https://github.com/simonw/sqlite-utils.git
synced 2026-07-23 09:24:31 +02:00
Added table.rows_where(where, args) method
This commit is contained in:
parent
72a6f430df
commit
f70e35c9bb
3 changed files with 36 additions and 1 deletions
|
|
@ -65,6 +65,13 @@ To iterate through dictionaries for each of the rows in a table, use ``.rows``::
|
|||
{'id': 1, 'age': 4, 'name': 'Cleo'}
|
||||
{'id': 2, 'age': 2, 'name': 'Pancakes'}
|
||||
|
||||
You can filter rows by a WHERE clause using ``.rows_where(where, where_args)``::
|
||||
|
||||
>>> db = sqlite_utils.Database("dogs.db")
|
||||
>>> for row in db["dogs"].rows_where("age > ?", [3]):
|
||||
... print(row)
|
||||
{'id': 1, 'age': 4, 'name': 'Cleo'}
|
||||
|
||||
Creating tables
|
||||
===============
|
||||
|
||||
|
|
|
|||
|
|
@ -365,9 +365,15 @@ class Table:
|
|||
|
||||
@property
|
||||
def rows(self):
|
||||
return self.rows_where()
|
||||
|
||||
def rows_where(self, where=None, where_args=None):
|
||||
if not self.exists:
|
||||
return []
|
||||
cursor = self.db.conn.execute("select * from [{}]".format(self.name))
|
||||
sql = "select * from [{}]".format(self.name)
|
||||
if where is not None:
|
||||
sql += " where " + where
|
||||
cursor = self.db.conn.execute(sql, where_args or [])
|
||||
columns = [c[0] for c in cursor.description]
|
||||
for row in cursor:
|
||||
yield dict(zip(columns, row))
|
||||
|
|
|
|||
22
tests/test_get.py
Normal file
22
tests/test_get.py
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
import pytest
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"where,where_args,expected_ids",
|
||||
[
|
||||
("name = ?", ["Pancakes"], {2}),
|
||||
("age > ?", [3], {1}),
|
||||
("name is not null", [], {1, 2}),
|
||||
("is_good = ?", [True], {1, 2}),
|
||||
],
|
||||
)
|
||||
def test_rows_where(where, where_args, expected_ids, fresh_db):
|
||||
table = fresh_db["dogs"]
|
||||
table.insert_all(
|
||||
[
|
||||
{"id": 1, "name": "Cleo", "age": 4, "is_good": True},
|
||||
{"id": 2, "name": "Pancakes", "age": 3, "is_good": True},
|
||||
],
|
||||
pk="id",
|
||||
)
|
||||
assert expected_ids == {r["id"] for r in table.rows_where(where, where_args)}
|
||||
Loading…
Add table
Add a link
Reference in a new issue