diff --git a/docs/python-api.rst b/docs/python-api.rst index a8fd786..c79e5bb 100644 --- a/docs/python-api.rst +++ b/docs/python-api.rst @@ -717,6 +717,8 @@ You can delete all records in a table that match a specific WHERE statement usin Calling ``table.delete_where()`` with no other arguments will delete every row in the table. +Pass ``analyze=True`` to run ``ANALYZE`` against the table after deleting the rows. + .. _python_api_upsert: Upserting data diff --git a/sqlite_utils/db.py b/sqlite_utils/db.py index 6d3bcf9..e40eb12 100644 --- a/sqlite_utils/db.py +++ b/sqlite_utils/db.py @@ -2119,15 +2119,28 @@ class Table(Queryable): return self def delete_where( - self, where: str = None, where_args: Optional[Union[Iterable, dict]] = None + self, + where: str = None, + where_args: Optional[Union[Iterable, dict]] = None, + analyze: bool = False, ) -> "Table": - "Delete rows matching specified where clause, or delete all rows in the table." + """ + Delete rows matching the specified where clause, or delete all rows in the table. + + - ``where`` - a SQL fragment to use as a ``WHERE`` clause, for example ``age > ?`` or ``age > :age``. + - ``where_args`` - a list of arguments (if using ``?``) or a dictionary (if using ``:age``). + - ``analyze`` - set to ``True`` to run ``ANALYZE`` after the rows have been deleted. + + See :ref:`python_api_delete_where`. + """ if not self.exists(): return self sql = "delete from [{}]".format(self.name) if where is not None: sql += " where " + where self.db.execute(sql, where_args or []) + if analyze: + self.analyze() return self def update( diff --git a/tests/test_delete.py b/tests/test_delete.py index 1198d06..f057749 100644 --- a/tests/test_delete.py +++ b/tests/test_delete.py @@ -30,3 +30,17 @@ def test_delete_where_all(fresh_db): assert 10 == table.count table.delete_where() assert 0 == table.count + + +def test_delete_where_analyze(fresh_db): + table = fresh_db["table"] + table.insert_all(({"id": i, "i": i} for i in range(10)), pk="id") + table.create_index(["i"], analyze=True) + assert "sqlite_stat1" in fresh_db.table_names() + assert list(fresh_db["sqlite_stat1"].rows) == [ + {"tbl": "table", "idx": "idx_table_i", "stat": "10 1"} + ] + table.delete_where("id > ?", [5], analyze=True) + assert list(fresh_db["sqlite_stat1"].rows) == [ + {"tbl": "table", "idx": "idx_table_i", "stat": "6 1"} + ]