Added table.delete_where(), closes #62

This commit is contained in:
Simon Willison 2019-11-04 08:18:06 -08:00
commit 169ea455fc
3 changed files with 37 additions and 0 deletions

View file

@ -396,6 +396,17 @@ The ``delete()`` method takes the primary key of the record. This can be a tuple
>>> db["compound_dogs"].delete((5, 3))
Deleting multiple records
=========================
You can delete all records in a table that match a specific WHERE statement using ``table.delete_where()``::
>>> db = sqlite_utils.Database("dogs.db")
>>> # Delete every dog with age less than 3
>>> db["dogs"].delete_where("age < ?", [3]):
Calling ``table.delete_where()`` with no other arguments will delete every row in the table.
Upserting data
==============

View file

@ -864,6 +864,14 @@ class Table(Queryable):
with self.db.conn:
self.db.conn.execute(sql, pk_values)
def delete_where(self, where=None, where_args=None):
if not self.exists:
return []
sql = "delete from [{}]".format(self.name)
if where is not None:
sql += " where " + where
self.db.conn.execute(sql, where_args or [])
def update(self, pk_values, updates=None, alter=False):
updates = updates or {}
if not isinstance(pk_values, (list, tuple)):

View file

@ -12,3 +12,21 @@ def test_delete_pk_table(fresh_db):
table.insert({"id": 2}, pk="id")
table.delete(1)
assert [{"id": 2}] == list(table.rows)
def test_delete_where(fresh_db):
table = fresh_db["table"]
for i in range(1, 11):
table.insert({"id": i}, pk="id")
assert 10 == table.count
table.delete_where("id > ?", [5])
assert 5 == table.count
def test_delete_where_all(fresh_db):
table = fresh_db["table"]
for i in range(1, 11):
table.insert({"id": i}, pk="id")
assert 10 == table.count
table.delete_where()
assert 0 == table.count