1
+ from functools import singledispatchmethod
2
+
1
3
from django .db .backends .base .schema import BaseDatabaseSchemaEditor
2
4
from django .db .models import Index , UniqueConstraint
5
+ from pymongo .operations import IndexModel , SearchIndexModel
6
+
7
+ from django_mongodb_backend .indexes import AtlasSearchIndex
3
8
4
9
from .fields import EmbeddedModelField
5
10
from .query import wrap_database_errors
@@ -256,6 +261,18 @@ def alter_unique_together(
256
261
model , constraint , parent_model = parent_model , column_prefix = column_prefix
257
262
)
258
263
264
+ @singledispatchmethod
265
+ def _add_index (self , index , model ):
266
+ raise ValueError (f"{ type (index )} isn't a supported index type" )
267
+
268
+ @_add_index .register
269
+ def _ (self , index : IndexModel , model ):
270
+ return self .get_collection (model ._meta .db_table ).create_indexes ([index ])
271
+
272
+ @_add_index .register
273
+ def _ (self , index : SearchIndexModel , model ):
274
+ return self .get_collection (model ._meta .db_table ).create_search_index (index )
275
+
259
276
@ignore_embedded_models
260
277
def add_index (
261
278
self , model , index , * , field = None , unique = False , column_prefix = "" , parent_model = None
@@ -265,7 +282,7 @@ def add_index(
265
282
)
266
283
if idx :
267
284
model = parent_model or model
268
- self .get_collection ( model . _meta . db_table ). create_indexes ([ idx ] )
285
+ self ._add_index ( idx , model )
269
286
270
287
def _add_composed_index (self , model , field_names , column_prefix = "" , parent_model = None ):
271
288
"""Add an index on the given list of field_names."""
@@ -279,11 +296,23 @@ def _add_field_index(self, model, field, *, column_prefix=""):
279
296
index .name = self ._create_index_name (model ._meta .db_table , [column_prefix + field .column ])
280
297
self .add_index (model , index , field = field , column_prefix = column_prefix )
281
298
299
+ @singledispatchmethod
300
+ def _remove_index (self , index , model ):
301
+ raise ValueError (f"{ type (index )} isn't a supported index type" )
302
+
303
+ @_remove_index .register
304
+ def _ (self , index : Index , model ):
305
+ return self .get_collection (model ._meta .db_table ).drop_index (index .name )
306
+
307
+ @_remove_index .register
308
+ def _ (self , index : AtlasSearchIndex , model ):
309
+ return self .get_collection (model ._meta .db_table ).drop_search_index (index .name )
310
+
282
311
@ignore_embedded_models
283
312
def remove_index (self , model , index ):
284
313
if index .contains_expressions :
285
314
return
286
- self .get_collection ( model . _meta . db_table ). drop_index ( index . name )
315
+ self ._remove_index ( index , model )
287
316
288
317
def _remove_composed_index (
289
318
self , model , field_names , constraint_kwargs , column_prefix = "" , parent_model = None
0 commit comments