Skip to content

Commit 7646b94

Browse files
committed
Fix dropping a non existing atlas index
1 parent 9dacee9 commit 7646b94

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

django_mongodb_backend/schema.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -293,7 +293,13 @@ def remove_index(self, model, index):
293293
if index.contains_expressions:
294294
return
295295
if isinstance(index, SearchIndex | VectorSearchIndex):
296-
if self.connection.features.supports_atlas_search:
296+
# Drop the index if it exists, particularly if it may not have been created previously
297+
# due to lack of Atlas search support, but now the database supports it.
298+
constraints = self.connection.introspection.get_constraints(
299+
cursor=None,
300+
table_name=model._meta.db_table,
301+
)
302+
if self.connection.features.supports_atlas_search and index.name in constraints:
297303
self.get_collection(model._meta.db_table).drop_search_index(index.name)
298304
else:
299305
self.get_collection(model._meta.db_table).drop_index(index.name)

tests/indexes_/test_atlas_indexes.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from unittest import mock
2+
13
from django.db import connection
24
from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature
35

@@ -38,6 +40,17 @@ def test_simple(self):
3840
editor.add_index(index=index, model=Article)
3941
self.assertAddRemoveIndex(editor, Article, index)
4042

43+
def test_drop_non_existing_index(self):
44+
with connection.schema_editor() as editor:
45+
index = SearchIndex(
46+
name="recent_article_idx",
47+
fields=["number"],
48+
)
49+
editor.get_collection = mock.MagicMock()
50+
editor.remove_index(index=index, model=Article)
51+
# Verify that the collection was not accessed
52+
editor.get_collection.assert_not_called()
53+
4154
@skipIfDBFeature("supports_atlas_search")
4255
def test_index_not_created(self):
4356
with connection.schema_editor() as editor:
@@ -120,6 +133,17 @@ def assertAddRemoveIndex(self, editor, model, index):
120133
),
121134
)
122135

136+
def test_drop_non_existing_index(self):
137+
with connection.schema_editor() as editor:
138+
index = SearchIndex(
139+
name="recent_article_idx",
140+
fields=["number"],
141+
)
142+
editor.get_collection = mock.MagicMock()
143+
editor.remove_index(index=index, model=Article)
144+
# Verify that the collection was not accessed
145+
editor.get_collection.assert_not_called()
146+
123147
@skipUnlessDBFeature("supports_atlas_search")
124148
def test_deconstruct_default_similarity(self):
125149
index = VectorSearchIndex(

0 commit comments

Comments
 (0)