1
+ import operator
2
+
1
3
from django .db import NotSupportedError , connection
2
4
from django .db .models import (
3
5
Index ,
4
6
Q ,
5
7
)
6
8
from django .test import (
7
9
TestCase ,
10
+ skipIfDBFeature ,
11
+ skipUnlessDBFeature ,
8
12
)
9
13
10
14
from .models import Article
@@ -57,11 +61,23 @@ def test_raises_on_xor(self):
57
61
)._get_condition_mql (Article , schema_editor = editor )
58
62
self .assertEqual (context_manager .exception .args [0 ], "Xor in indexes is not supported." )
59
63
64
+ @skipIfDBFeature ("is_mongodb_6_0" )
65
+ def test_raises_on_or (self ):
66
+ with self .assertRaises (
67
+ NotSupportedError
68
+ ) as context_manager , connection .schema_editor () as editor :
69
+ Index (
70
+ name = "raises_on_negated" ,
71
+ fields = ["headline" ],
72
+ condition = Q (pk = True ) ^ Q (pk = False ),
73
+ )._get_condition_mql (Article , schema_editor = editor )
74
+ self .assertEqual (context_manager .exception .args [0 ], "Or in indexes is not supported." )
75
+
76
+ @skipUnlessDBFeature ("is_mongodb_6_0" )
60
77
def test_composite_index (self ):
61
78
with connection .schema_editor () as editor :
62
79
index = Index (
63
80
name = "composite_proposition" ,
64
- # This is changed
65
81
fields = ["headline" ],
66
82
condition = Q (number__gte = 3 ) & (Q (text__gt = "test1" ) | Q (text__in = ["A" , "B" ])),
67
83
)
@@ -86,3 +102,31 @@ def test_composite_index(self):
86
102
),
87
103
)
88
104
editor .remove_index (index = index , model = Article )
105
+
106
+ def test_composite_op_index (self ):
107
+ for op in (
108
+ [operator .or_ , operator .and_ ] if connection .features .is_mongodb_6_0 else [operator .and_ ]
109
+ ):
110
+ with self .subTest (operator = op ), connection .schema_editor () as editor :
111
+ index = Index (
112
+ name = "composite_proposition" ,
113
+ fields = ["headline" ],
114
+ condition = op (Q (number__gte = 3 ), Q (text__gt = "test1" )),
115
+ )
116
+ index ._get_condition_mql (Article , schema_editor = editor )
117
+ mongo_operator = "$and" if op == operator .and_ else "$or"
118
+ target = {mongo_operator : [{"number" : {"$gte" : 3 }}, {"text" : {"$gt" : "test1" }}]}
119
+ self .assertEqual (
120
+ target ,
121
+ index ._get_condition_mql (Article , schema_editor = editor ),
122
+ )
123
+ editor .add_index (index = index , model = Article )
124
+ with connection .cursor () as cursor :
125
+ self .assertIn (
126
+ index .name ,
127
+ connection .introspection .get_constraints (
128
+ cursor = cursor ,
129
+ table_name = Article ._meta .db_table ,
130
+ ),
131
+ )
132
+ editor .remove_index (index = index , model = Article )
0 commit comments