diff --git a/sqlite_utils/db.py b/sqlite_utils/db.py index aacdc893..6cd82022 100644 --- a/sqlite_utils/db.py +++ b/sqlite_utils/db.py @@ -2572,7 +2572,11 @@ def enable_fts( ) ) should_recreate = False - if replace and self.db["{}_fts".format(self.name)].exists(): + fts_table_exists = self.db["{}_fts".format(self.name)].exists() + if not replace and fts_table_exists: + # FTS table already exists and replace=False, so return early + return self + if replace and fts_table_exists: # Does the table need to be recreated? fts_schema = self.db["{}_fts".format(self.name)].schema if fts_schema != create_fts_sql: diff --git a/tests/test_fts.py b/tests/test_fts.py index 9c635ffa..909b66a2 100644 --- a/tests/test_fts.py +++ b/tests/test_fts.py @@ -428,6 +428,28 @@ def test_enable_fts_error_message_on_views(): assert e.value.args[0] == "enable_fts() is supported on tables but not on views" +def test_enable_fts_twice_without_replace(): + # Regression test for https://github.com/simonw/sqlite-utils/issues/694 + # Calling enable_fts() twice without replace=True should not error + db = Database(memory=True) + db["books"].insert( + { + "id": 1, + "title": "Habits of Australian Marsupials", + "author": "Marlee Hawkins", + }, + pk="id", + ) + # First call creates the FTS table + db["books"].enable_fts(["title", "author"]) + assert db["books_fts"].exists() + # Second call without replace=True should return early without error + result = db["books"].enable_fts(["title", "author"]) + assert result == db["books"] + # FTS table should still exist + assert db["books_fts"].exists() + + @pytest.mark.parametrize( "kwargs,fts,expected", [