diff --git a/docs/python-api.rst b/docs/python-api.rst index 791b9c5..66e6100 100644 --- a/docs/python-api.rst +++ b/docs/python-api.rst @@ -2204,6 +2204,8 @@ You can create a unique index by passing ``unique=True``: Use ``if_not_exists=True`` to do nothing if an index with that name already exists. +Pass ``analyze=True`` to run ``ANALYZE`` against the new index after creating it. + .. _python_api_analyze: Optimizing index usage with ANALYZE diff --git a/sqlite_utils/db.py b/sqlite_utils/db.py index 1348b4a..6a68c1b 100644 --- a/sqlite_utils/db.py +++ b/sqlite_utils/db.py @@ -1554,6 +1554,7 @@ class Table(Queryable): unique: bool = False, if_not_exists: bool = False, find_unique_name: bool = False, + analyze: bool = False, ): """ Create an index on this table. @@ -1565,6 +1566,7 @@ class Table(Queryable): - ``if_not_exists`` - only create the index if one with that name does not already exist. - ``find_unique_name`` - if ``index_name`` is not provided and the automatically derived name already exists, keep incrementing a suffix number to find an available name. + - ``analyze`` - run ``ANALYZE`` against this index after creating it. See :ref:`python_api_create_index`. """ @@ -1581,7 +1583,11 @@ class Table(Queryable): columns_sql.append(fmt.format(column)) suffix = None + created_index_name = None while True: + created_index_name = ( + "{}_{}".format(index_name, suffix) if suffix else index_name + ) sql = ( textwrap.dedent( """ @@ -1591,9 +1597,7 @@ class Table(Queryable): ) .strip() .format( - index_name="{}_{}".format(index_name, suffix) - if suffix - else index_name, + index_name=created_index_name, table_name=self.name, columns=", ".join(columns_sql), unique="UNIQUE " if unique else "", @@ -1618,6 +1622,8 @@ class Table(Queryable): continue else: raise e + if analyze: + self.db.analyze(created_index_name) return self def add_column( diff --git a/tests/test_create.py b/tests/test_create.py index 187d20a..f5d9a12 100644 --- a/tests/test_create.py +++ b/tests/test_create.py @@ -774,6 +774,14 @@ def test_create_index_find_unique_name(fresh_db): assert index_names == {"idx_t_id", "idx_t_id_2", "idx_t_id_3"} +def test_create_index_analyze(fresh_db): + dogs = fresh_db["dogs"] + assert "sqlite_stat1" not in fresh_db.table_names() + dogs.insert({"name": "Cleo", "twitter": "cleopaws"}) + dogs.create_index(["name"], analyze=True) + assert "sqlite_stat1" in fresh_db.table_names() + + @pytest.mark.parametrize( "data_structure", (