Skip to content

Commit 32a8f9c

Browse files
committed
Refactor index creation
1 parent 5ab4f6e commit 32a8f9c

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

django_mongodb_backend/indexes.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,46 @@ def where_node_idx(self, compiler, connection):
101101
return mql
102102

103103

104+
def create_mongodb_index(self, model, schema_editor, field=None, unique=False, column_prefix=""):
105+
from collections import defaultdict
106+
107+
if self.contains_expressions:
108+
return None
109+
kwargs = {}
110+
filter_expression = defaultdict(dict)
111+
if self.condition:
112+
filter_expression.update(self._get_condition_mql(model, schema_editor))
113+
if unique:
114+
kwargs["unique"] = True
115+
# Indexing on $type matches the value of most SQL databases by
116+
# allowing multiple null values for the unique constraint.
117+
if field:
118+
column = column_prefix + field.column
119+
filter_expression[column].update({"$type": field.db_type(schema_editor.connection)})
120+
else:
121+
for field_name, _ in self.fields_orders:
122+
field_ = model._meta.get_field(field_name)
123+
filter_expression[field_.column].update(
124+
{"$type": field_.db_type(schema_editor.connection)}
125+
)
126+
if filter_expression:
127+
kwargs["partialFilterExpression"] = filter_expression
128+
index_orders = (
129+
[(column_prefix + field.column, ASCENDING)]
130+
if field
131+
else [
132+
# order is "" if ASCENDING or "DESC" if DESCENDING (see
133+
# django.db.models.indexes.Index.fields_orders).
134+
(
135+
column_prefix + model._meta.get_field(field_name).column,
136+
ASCENDING if order == "" else DESCENDING,
137+
)
138+
for field_name, order in self.fields_orders
139+
]
140+
)
141+
return IndexModel(index_orders, name=self.name, **kwargs)
142+
143+
104144
def register_indexes():
105145
BuiltinLookup.as_mql_idx = builtin_lookup_idx
106146
Index._get_condition_mql = _get_condition_mql

0 commit comments

Comments
 (0)