Repository: brightway-lca/brightway2-data

Issue:
`IndexManager` does not properly delete search database
**Issue in short:** When you delete a searchable database and create one with the same name, you cannot properly create activities within it anymore.

When you delete a database, the `IndexManager` deletes the accompanied search database by dropping the tables as follows:
https://github.com/brightway-lca/brightway2-data/blob/4fd8e9388085abb9208b66f520f0e147bf3e5e7c/bw2data/search/indices.py#L80-L83

However, this means that the database file is not removed. If you then reinstate a database with the same name `IndexManager.create()` is not called as `os.path.exists(self.path)` will validate as true.

https://github.com/brightway-lca/brightway2-data/blob/4fd8e9388085abb9208b66f520f0e147bf3e5e7c/bw2data/search/indices.py#L13-L18

This in turn leads to no tables being created in the database, which in turn leads to activities not being able to be saved because of the following exception:

```Python
File "***\Lib\site-packages\bw2data\backends\proxies.py", line 356, in save
    IndexManager(Database(self["database"]).filename).update_dataset(self._data)
File "***\Lib\site-packages\bw2data\search\indices.py", line 70, in update_dataset
    ).execute()
      ^^^^^^^^^
File "***\Lib\site-packages\peewee.py", line 2036, in inner
    return method(self, database, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "***\Lib\site-packages\peewee.py", line 2107, in execute
    return self._execute(database)
           ^^^^^^^^^^^^^^^^^^^^^^^
File "***\Lib\site-packages\peewee.py", line 2625, in _execute
    cursor = database.execute(self)
             ^^^^^^^^^^^^^^^^^^^^^^
File "***\Lib\site-packages\peewee.py", line 3330, in execute
    return self.execute_sql(sql, params)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "***\Lib\site-packages\peewee.py", line 3320, in execute_sql
    with __exception_wrapper__:
File "***\Lib\site-packages\peewee.py", line 3088, in __exit__
    reraise(new_type, new_type(exc_value, *exc_args), traceback)
File "***\Lib\site-packages\peewee.py", line 196, in reraise
    raise value.with_traceback(tb)
File "***\Lib\site-packages\peewee.py", line 3322, in execute_sql
    cursor.execute(sql, params or ())
peewee.OperationalError: no such table: bw2schema

```

Discussion hints:
codecov[bot]: ## [Codecov](https://app.codecov.io/gh/brightway-lca/brightway2-data/pull/235?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=brightway-lca) Report
All modified and coverable lines are covered by tests :white_check_mark:
> Project coverage is 85.12%. Comparing base [(`0c61d18`)](https://app.codecov.io/gh/brightway-lca/brightway2-data/commit/0c61d18c54608c6ab19b7279465064a118680c05?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=brightway-lca) to head [(`1aa5d0a`)](https://app.codecov.io/gh/brightway-lca/brightway2-data/commit/1aa5d0a048b6ec46484c1fe8e50a94650760f869?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=brightway-lca).
> Report is 150 commits behind head on main.

<details><summary>Additional details and impacted files</summary>


```diff
@@            Coverage Diff             @@
##             main     #235      +/-   ##
==========================================
+ Coverage   83.24%   85.12%   +1.88%     
==========================================
  Files          39       42       +3     
  Lines        3730     4471     +741     
==========================================
+ Hits         3105     3806     +701     
- Misses        625      665      +40     
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/brightway-lca/brightway2-data/pull/235?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=brightway-lca).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=brightway-lca).

tngTUDOR: Tests do not pass with windows :(
vjousse: Did you try to restart the tests? It looks like the errors are not related to the changes and I have no Windows to run the tests locally

Solution patch:
diff --git a/bw2data/search/indices.py b/bw2data/search/indices.py
index c59ad89..d8ccef8 100644
--- a/bw2data/search/indices.py
+++ b/bw2data/search/indices.py
@@ -13,7 +13,7 @@ class IndexManager:
     def __init__(self, database_path):
         self.path = os.path.join(projects.request_directory("search"), database_path)
         self.db = SqliteExtDatabase(self.path)
-        if not os.path.exists(self.path):
+        if not os.path.exists(self.path) or len(self.db.get_tables()) == 0:
             self.create()
 
     def get(self):


Test patch:
diff --git a/tests/search.py b/tests/search.py
index c4c58e8..d9044e9 100644
--- a/tests/search.py
+++ b/tests/search.py
@@ -146,7 +146,7 @@ def test_modify_database():
 
 
 @bw2test
-def test_delete_database():
+def test_searchable_database():
     db = SQLiteBackend("foo")
     ds = {("foo", "bar"): {"database": "foo", "code": "bar", "name": "lollipop"}}
     db.write(ds)
@@ -163,6 +163,16 @@ def test_delete_database():
         assert not s.search("lollipop", proxy=False)
 
 
+@bw2test
+def test_delete_database():
+    im = IndexManager("foo")
+    im.add_dataset({"database": "foo", "code": "bar", "name": "lollipop"})
+    im.delete_database()
+    # Check that we can create an IM with the same name without throwing an exception
+    im = IndexManager("foo")
+    im.add_dataset({"database": "foo", "code": "bar", "name": "lollipop"})
+
+
 @bw2test
 def test_reset_index():
     im = IndexManager("foo")