Debian Codegraph @

tests/postgres_tests/test_indexes.py

raw
1 from django.contrib.postgres.indexes import (
2 BloomIndex,
3 BrinIndex,
4 BTreeIndex,
5 GinIndex,
6 GistIndex,
7 HashIndex,
8 OpClass,
9 PostgresIndex,
10 SpGistIndex,
11 )
12 from django.db import connection
13 from django.db.models import CharField, F, Index, Q
14 from django.db.models.functions import Cast, Collate, Length, Lower
15 from django.test.utils import register_lookup
16
17 from . import PostgreSQLSimpleTestCase, PostgreSQLTestCase
18 from .fields import SearchVector, SearchVectorField
19 from .models import CharFieldModel, IntegerArrayModel, Scene, TextFieldModel
20
21
22 class IndexTestMixin:
23 def test_name_auto_generation(self):
24 index = self.index_class(fields=["field"])
25 index.set_name_with_model(CharFieldModel)
26 self.assertRegex(
27 index.name, r"postgres_te_field_[0-9a-f]{6}_%s" % self.index_class.suffix
28 )
29
30 def test_deconstruction_no_customization(self):
31 index = self.index_class(
32 fields=["title"], name="test_title_%s" % self.index_class.suffix
33 )
34 path, args, kwargs = index.deconstruct()
35 self.assertEqual(
36 path, "django.contrib.postgres.indexes.%s" % self.index_class.__name__
37 )
38 self.assertEqual(args, ())
39 self.assertEqual(
40 kwargs,
41 {"fields": ["title"], "name": "test_title_%s" % self.index_class.suffix},
42 )
43
44 def test_deconstruction_with_expressions_no_customization(self):
45 name = f"test_title_{self.index_class.suffix}"
46 index = self.index_class(Lower("title"), name=name)
47 path, args, kwargs = index.deconstruct()
48 self.assertEqual(
49 path,
50 f"django.contrib.postgres.indexes.{self.index_class.__name__}",
51 )
52 self.assertEqual(args, (Lower("title"),))
53 self.assertEqual(kwargs, {"name": name})
54
55
56 class BloomIndexTests(IndexTestMixin, PostgreSQLSimpleTestCase):
57 index_class = BloomIndex
58
59 def test_suffix(self):
60 self.assertEqual(BloomIndex.suffix, "bloom")
61
62 def test_deconstruction(self):
63 index = BloomIndex(fields=["title"], name="test_bloom", length=80, columns=[4])
64 path, args, kwargs = index.deconstruct()
65 self.assertEqual(path, "django.contrib.postgres.indexes.BloomIndex")
66 self.assertEqual(args, ())
67 self.assertEqual(
68 kwargs,
69 {
70 "fields": ["title"],
71 "name": "test_bloom",
72 "length": 80,
73 "columns": [4],
74 },
75 )
76
77 def test_invalid_fields(self):
78 msg = "Bloom indexes support a maximum of 32 fields."
79 with self.assertRaisesMessage(ValueError, msg):
80 BloomIndex(fields=["title"] * 33, name="test_bloom")
81
82 def test_invalid_columns(self):
83 msg = "BloomIndex.columns must be a list or tuple."
84 with self.assertRaisesMessage(ValueError, msg):
85 BloomIndex(fields=["title"], name="test_bloom", columns="x")
86 msg = "BloomIndex.columns cannot have more values than fields."
87 with self.assertRaisesMessage(ValueError, msg):
88 BloomIndex(fields=["title"], name="test_bloom", columns=[4, 3])
89
90 def test_invalid_columns_value(self):
91 msg = "BloomIndex.columns must contain integers from 1 to 4095."
92 for length in (0, 4096):
93 with self.subTest(length), self.assertRaisesMessage(ValueError, msg):
94 BloomIndex(fields=["title"], name="test_bloom", columns=[length])
95
96 def test_invalid_length(self):
97 msg = "BloomIndex.length must be None or an integer from 1 to 4096."
98 for length in (0, 4097):
99 with self.subTest(length), self.assertRaisesMessage(ValueError, msg):
100 BloomIndex(fields=["title"], name="test_bloom", length=length)
101
102
103 class BrinIndexTests(IndexTestMixin, PostgreSQLSimpleTestCase):
104 index_class = BrinIndex
105
106 def test_suffix(self):
107 self.assertEqual(BrinIndex.suffix, "brin")
108
109 def test_deconstruction(self):
110 index = BrinIndex(
111 fields=["title"],
112 name="test_title_brin",
113 autosummarize=True,
114 pages_per_range=16,
115 )
116 path, args, kwargs = index.deconstruct()
117 self.assertEqual(path, "django.contrib.postgres.indexes.BrinIndex")
118 self.assertEqual(args, ())
119 self.assertEqual(
120 kwargs,
121 {
122 "fields": ["title"],
123 "name": "test_title_brin",
124 "autosummarize": True,
125 "pages_per_range": 16,
126 },
127 )
128
129 def test_invalid_pages_per_range(self):
130 with self.assertRaisesMessage(
131 ValueError, "pages_per_range must be None or a positive integer"
132 ):
133 BrinIndex(fields=["title"], name="test_title_brin", pages_per_range=0)
134
135
136 class BTreeIndexTests(IndexTestMixin, PostgreSQLSimpleTestCase):
137 index_class = BTreeIndex
138
139 def test_suffix(self):
140 self.assertEqual(BTreeIndex.suffix, "btree")
141
142 def test_deconstruction(self):
143 index = BTreeIndex(fields=["title"], name="test_title_btree")
144 path, args, kwargs = index.deconstruct()
145 self.assertEqual(path, "django.contrib.postgres.indexes.BTreeIndex")
146 self.assertEqual(args, ())
147 self.assertEqual(kwargs, {"fields": ["title"], "name": "test_title_btree"})
148
149 index = BTreeIndex(
150 fields=["title"],
151 name="test_title_btree",
152 fillfactor=80,
153 deduplicate_items=False,
154 )
155 path, args, kwargs = index.deconstruct()
156 self.assertEqual(path, "django.contrib.postgres.indexes.BTreeIndex")
157 self.assertEqual(args, ())
158 self.assertEqual(
159 kwargs,
160 {
161 "fields": ["title"],
162 "name": "test_title_btree",
163 "fillfactor": 80,
164 "deduplicate_items": False,
165 },
166 )
167
168
169 class GinIndexTests(IndexTestMixin, PostgreSQLSimpleTestCase):
170 index_class = GinIndex
171
172 def test_suffix(self):
173 self.assertEqual(GinIndex.suffix, "gin")
174
175 def test_deconstruction(self):
176 index = GinIndex(
177 fields=["title"],
178 name="test_title_gin",
179 fastupdate=True,
180 gin_pending_list_limit=128,
181 )
182 path, args, kwargs = index.deconstruct()
183 self.assertEqual(path, "django.contrib.postgres.indexes.GinIndex")
184 self.assertEqual(args, ())
185 self.assertEqual(
186 kwargs,
187 {
188 "fields": ["title"],
189 "name": "test_title_gin",
190 "fastupdate": True,
191 "gin_pending_list_limit": 128,
192 },
193 )
194
195
196 class GistIndexTests(IndexTestMixin, PostgreSQLSimpleTestCase):
197 index_class = GistIndex
198
199 def test_suffix(self):
200 self.assertEqual(GistIndex.suffix, "gist")
201
202 def test_deconstruction(self):
203 index = GistIndex(
204 fields=["title"], name="test_title_gist", buffering=False, fillfactor=80
205 )
206 path, args, kwargs = index.deconstruct()
207 self.assertEqual(path, "django.contrib.postgres.indexes.GistIndex")
208 self.assertEqual(args, ())
209 self.assertEqual(
210 kwargs,
211 {
212 "fields": ["title"],
213 "name": "test_title_gist",
214 "buffering": False,
215 "fillfactor": 80,
216 },
217 )
218
219
220 class HashIndexTests(IndexTestMixin, PostgreSQLSimpleTestCase):
221 index_class = HashIndex
222
223 def test_suffix(self):
224 self.assertEqual(HashIndex.suffix, "hash")
225
226 def test_deconstruction(self):
227 index = HashIndex(fields=["title"], name="test_title_hash", fillfactor=80)
228 path, args, kwargs = index.deconstruct()
229 self.assertEqual(path, "django.contrib.postgres.indexes.HashIndex")
230 self.assertEqual(args, ())
231 self.assertEqual(
232 kwargs, {"fields": ["title"], "name": "test_title_hash", "fillfactor": 80}
233 )
234
235
236 class SpGistIndexTests(IndexTestMixin, PostgreSQLSimpleTestCase):
237 index_class = SpGistIndex
238
239 def test_suffix(self):
240 self.assertEqual(SpGistIndex.suffix, "spgist")
241
242 def test_deconstruction(self):
243 index = SpGistIndex(fields=["title"], name="test_title_spgist", fillfactor=80)
244 path, args, kwargs = index.deconstruct()
245 self.assertEqual(path, "django.contrib.postgres.indexes.SpGistIndex")
246 self.assertEqual(args, ())
247 self.assertEqual(
248 kwargs, {"fields": ["title"], "name": "test_title_spgist", "fillfactor": 80}
249 )
250
251
252 class SchemaTests(PostgreSQLTestCase):
253 get_opclass_query = """
254 SELECT opcname, c.relname FROM pg_opclass AS oc
255 JOIN pg_index as i on oc.oid = ANY(i.indclass)
256 JOIN pg_class as c on c.oid = i.indexrelid
257 WHERE c.relname = %s
258 """
259
260 def get_constraints(self, table):
261 """
262 Get the indexes on the table using a new cursor.
263 """
264 with connection.cursor() as cursor:
265 return connection.introspection.get_constraints(cursor, table)
266
267 def test_gin_index(self):
268 # Ensure the table is there and doesn't have an index.
269 self.assertNotIn(
270 "field", self.get_constraints(IntegerArrayModel._meta.db_table)
271 )
272 # Add the index
273 index_name = "integer_array_model_field_gin"
274 index = GinIndex(fields=["field"], name=index_name)
275 with connection.schema_editor() as editor:
276 editor.add_index(IntegerArrayModel, index)
277 constraints = self.get_constraints(IntegerArrayModel._meta.db_table)
278 # Check gin index was added
279 self.assertEqual(constraints[index_name]["type"], GinIndex.suffix)
280 # Drop the index
281 with connection.schema_editor() as editor:
282 editor.remove_index(IntegerArrayModel, index)
283 self.assertNotIn(
284 index_name, self.get_constraints(IntegerArrayModel._meta.db_table)
285 )
286
287 def test_gin_fastupdate(self):
288 index_name = "integer_array_gin_fastupdate"
289 index = GinIndex(fields=["field"], name=index_name, fastupdate=False)
290 with connection.schema_editor() as editor:
291 editor.add_index(IntegerArrayModel, index)
292 constraints = self.get_constraints(IntegerArrayModel._meta.db_table)
293 self.assertEqual(constraints[index_name]["type"], "gin")
294 self.assertEqual(constraints[index_name]["options"], ["fastupdate=off"])
295 with connection.schema_editor() as editor:
296 editor.remove_index(IntegerArrayModel, index)
297 self.assertNotIn(
298 index_name, self.get_constraints(IntegerArrayModel._meta.db_table)
299 )
300
301 def test_partial_gin_index(self):
302 with register_lookup(CharField, Length):
303 index_name = "char_field_gin_partial_idx"
304 index = GinIndex(
305 fields=["field"], name=index_name, condition=Q(field__length=40)
306 )
307 with connection.schema_editor() as editor:
308 editor.add_index(CharFieldModel, index)
309 constraints = self.get_constraints(CharFieldModel._meta.db_table)
310 self.assertEqual(constraints[index_name]["type"], "gin")
311 with connection.schema_editor() as editor:
312 editor.remove_index(CharFieldModel, index)
313 self.assertNotIn(
314 index_name, self.get_constraints(CharFieldModel._meta.db_table)
315 )
316
317 def test_partial_gin_index_with_tablespace(self):
318 with register_lookup(CharField, Length):
319 index_name = "char_field_gin_partial_idx"
320 index = GinIndex(
321 fields=["field"],
322 name=index_name,
323 condition=Q(field__length=40),
324 db_tablespace="pg_default",
325 )
326 with connection.schema_editor() as editor:
327 editor.add_index(CharFieldModel, index)
328 self.assertIn(
329 'TABLESPACE "pg_default" ',
330 str(index.create_sql(CharFieldModel, editor)),
331 )
332 constraints = self.get_constraints(CharFieldModel._meta.db_table)
333 self.assertEqual(constraints[index_name]["type"], "gin")
334 with connection.schema_editor() as editor:
335 editor.remove_index(CharFieldModel, index)
336 self.assertNotIn(
337 index_name, self.get_constraints(CharFieldModel._meta.db_table)
338 )
339
340 def test_gin_parameters(self):
341 index_name = "integer_array_gin_params"
342 index = GinIndex(
343 fields=["field"],
344 name=index_name,
345 fastupdate=True,
346 gin_pending_list_limit=64,
347 db_tablespace="pg_default",
348 )
349 with connection.schema_editor() as editor:
350 editor.add_index(IntegerArrayModel, index)
351 self.assertIn(
352 ") WITH (gin_pending_list_limit = 64, fastupdate = on) TABLESPACE",
353 str(index.create_sql(IntegerArrayModel, editor)),
354 )
355 constraints = self.get_constraints(IntegerArrayModel._meta.db_table)
356 self.assertEqual(constraints[index_name]["type"], "gin")
357 self.assertEqual(
358 constraints[index_name]["options"],
359 ["gin_pending_list_limit=64", "fastupdate=on"],
360 )
361 with connection.schema_editor() as editor:
362 editor.remove_index(IntegerArrayModel, index)
363 self.assertNotIn(
364 index_name, self.get_constraints(IntegerArrayModel._meta.db_table)
365 )
366
367 def test_trigram_op_class_gin_index(self):
368 index_name = "trigram_op_class_gin"
369 index = GinIndex(OpClass(F("scene"), name="gin_trgm_ops"), name=index_name)
370 with connection.schema_editor() as editor:
371 editor.add_index(Scene, index)
372 with editor.connection.cursor() as cursor:
373 cursor.execute(self.get_opclass_query, [index_name])
374 self.assertCountEqual(cursor.fetchall(), [("gin_trgm_ops", index_name)])
375 constraints = self.get_constraints(Scene._meta.db_table)
376 self.assertIn(index_name, constraints)
377 self.assertIn(constraints[index_name]["type"], GinIndex.suffix)
378 with connection.schema_editor() as editor:
379 editor.remove_index(Scene, index)
380 self.assertNotIn(index_name, self.get_constraints(Scene._meta.db_table))
381
382 def test_cast_search_vector_gin_index(self):
383 index_name = "cast_search_vector_gin"
384 index = GinIndex(Cast("field", SearchVectorField()), name=index_name)
385 with connection.schema_editor() as editor:
386 editor.add_index(TextFieldModel, index)
387 sql = index.create_sql(TextFieldModel, editor)
388 table = TextFieldModel._meta.db_table
389 constraints = self.get_constraints(table)
390 self.assertIn(index_name, constraints)
391 self.assertIn(constraints[index_name]["type"], GinIndex.suffix)
392 self.assertIs(sql.references_column(table, "field"), True)
393 self.assertIn("::tsvector", str(sql))
394 with connection.schema_editor() as editor:
395 editor.remove_index(TextFieldModel, index)
396 self.assertNotIn(index_name, self.get_constraints(table))
397
398 def test_bloom_index(self):
399 index_name = "char_field_model_field_bloom"
400 index = BloomIndex(fields=["field"], name=index_name)
401 with connection.schema_editor() as editor:
402 editor.add_index(CharFieldModel, index)
403 constraints = self.get_constraints(CharFieldModel._meta.db_table)
404 self.assertEqual(constraints[index_name]["type"], BloomIndex.suffix)
405 with connection.schema_editor() as editor:
406 editor.remove_index(CharFieldModel, index)
407 self.assertNotIn(
408 index_name, self.get_constraints(CharFieldModel._meta.db_table)
409 )
410
411 def test_bloom_parameters(self):
412 index_name = "char_field_model_field_bloom_params"
413 index = BloomIndex(fields=["field"], name=index_name, length=512, columns=[3])
414 with connection.schema_editor() as editor:
415 editor.add_index(CharFieldModel, index)
416 constraints = self.get_constraints(CharFieldModel._meta.db_table)
417 self.assertEqual(constraints[index_name]["type"], BloomIndex.suffix)
418 self.assertEqual(constraints[index_name]["options"], ["length=512", "col1=3"])
419 with connection.schema_editor() as editor:
420 editor.remove_index(CharFieldModel, index)
421 self.assertNotIn(
422 index_name, self.get_constraints(CharFieldModel._meta.db_table)
423 )
424
425 def test_brin_index(self):
426 index_name = "char_field_model_field_brin"
427 index = BrinIndex(fields=["field"], name=index_name, pages_per_range=4)
428 with connection.schema_editor() as editor:
429 editor.add_index(CharFieldModel, index)
430 constraints = self.get_constraints(CharFieldModel._meta.db_table)
431 self.assertEqual(constraints[index_name]["type"], BrinIndex.suffix)
432 self.assertEqual(constraints[index_name]["options"], ["pages_per_range=4"])
433 with connection.schema_editor() as editor:
434 editor.remove_index(CharFieldModel, index)
435 self.assertNotIn(
436 index_name, self.get_constraints(CharFieldModel._meta.db_table)
437 )
438
439 def test_brin_parameters(self):
440 index_name = "char_field_brin_params"
441 index = BrinIndex(fields=["field"], name=index_name, autosummarize=True)
442 with connection.schema_editor() as editor:
443 editor.add_index(CharFieldModel, index)
444 constraints = self.get_constraints(CharFieldModel._meta.db_table)
445 self.assertEqual(constraints[index_name]["type"], BrinIndex.suffix)
446 self.assertEqual(constraints[index_name]["options"], ["autosummarize=on"])
447 with connection.schema_editor() as editor:
448 editor.remove_index(CharFieldModel, index)
449 self.assertNotIn(
450 index_name, self.get_constraints(CharFieldModel._meta.db_table)
451 )
452
453 def test_btree_index(self):
454 # Ensure the table is there and doesn't have an index.
455 self.assertNotIn("field", self.get_constraints(CharFieldModel._meta.db_table))
456 # Add the index.
457 index_name = "char_field_model_field_btree"
458 index = BTreeIndex(fields=["field"], name=index_name)
459 with connection.schema_editor() as editor:
460 editor.add_index(CharFieldModel, index)
461 constraints = self.get_constraints(CharFieldModel._meta.db_table)
462 # The index was added.
463 self.assertEqual(constraints[index_name]["type"], BTreeIndex.suffix)
464 # Drop the index.
465 with connection.schema_editor() as editor:
466 editor.remove_index(CharFieldModel, index)
467 self.assertNotIn(
468 index_name, self.get_constraints(CharFieldModel._meta.db_table)
469 )
470
471 def test_btree_parameters(self):
472 index_name = "integer_array_btree_parameters"
473 index = BTreeIndex(
474 fields=["field"], name=index_name, fillfactor=80, deduplicate_items=False
475 )
476 with connection.schema_editor() as editor:
477 editor.add_index(CharFieldModel, index)
478 constraints = self.get_constraints(CharFieldModel._meta.db_table)
479 self.assertEqual(constraints[index_name]["type"], BTreeIndex.suffix)
480 self.assertEqual(
481 constraints[index_name]["options"],
482 ["fillfactor=80", "deduplicate_items=off"],
483 )
484 with connection.schema_editor() as editor:
485 editor.remove_index(CharFieldModel, index)
486 self.assertNotIn(
487 index_name, self.get_constraints(CharFieldModel._meta.db_table)
488 )
489
490 def test_gist_index(self):
491 # Ensure the table is there and doesn't have an index.
492 self.assertNotIn("field", self.get_constraints(CharFieldModel._meta.db_table))
493 # Add the index.
494 index_name = "char_field_model_field_gist"
495 index = GistIndex(fields=["field"], name=index_name)
496 with connection.schema_editor() as editor:
497 editor.add_index(CharFieldModel, index)
498 constraints = self.get_constraints(CharFieldModel._meta.db_table)
499 # The index was added.
500 self.assertEqual(constraints[index_name]["type"], GistIndex.suffix)
501 # Drop the index.
502 with connection.schema_editor() as editor:
503 editor.remove_index(CharFieldModel, index)
504 self.assertNotIn(
505 index_name, self.get_constraints(CharFieldModel._meta.db_table)
506 )
507
508 def test_gist_parameters(self):
509 index_name = "integer_array_gist_buffering"
510 index = GistIndex(
511 fields=["field"], name=index_name, buffering=True, fillfactor=80
512 )
513 with connection.schema_editor() as editor:
514 editor.add_index(CharFieldModel, index)
515 constraints = self.get_constraints(CharFieldModel._meta.db_table)
516 self.assertEqual(constraints[index_name]["type"], GistIndex.suffix)
517 self.assertEqual(
518 constraints[index_name]["options"], ["buffering=on", "fillfactor=80"]
519 )
520 with connection.schema_editor() as editor:
521 editor.remove_index(CharFieldModel, index)
522 self.assertNotIn(
523 index_name, self.get_constraints(CharFieldModel._meta.db_table)
524 )
525
526 def test_gist_include(self):
527 index_name = "scene_gist_include_setting"
528 index = GistIndex(name=index_name, fields=["scene"], include=["setting"])
529 with connection.schema_editor() as editor:
530 editor.add_index(Scene, index)
531 constraints = self.get_constraints(Scene._meta.db_table)
532 self.assertIn(index_name, constraints)
533 self.assertEqual(constraints[index_name]["type"], GistIndex.suffix)
534 self.assertEqual(constraints[index_name]["columns"], ["scene", "setting"])
535 with connection.schema_editor() as editor:
536 editor.remove_index(Scene, index)
537 self.assertNotIn(index_name, self.get_constraints(Scene._meta.db_table))
538
539 def test_tsvector_op_class_gist_index(self):
540 index_name = "tsvector_op_class_gist"
541 index = GistIndex(
542 OpClass(
543 SearchVector("scene", "setting", config="english"),
544 name="tsvector_ops",
545 ),
546 name=index_name,
547 )
548 with connection.schema_editor() as editor:
549 editor.add_index(Scene, index)
550 sql = index.create_sql(Scene, editor)
551 table = Scene._meta.db_table
552 constraints = self.get_constraints(table)
553 self.assertIn(index_name, constraints)
554 self.assertIn(constraints[index_name]["type"], GistIndex.suffix)
555 self.assertIs(sql.references_column(table, "scene"), True)
556 self.assertIs(sql.references_column(table, "setting"), True)
557 with connection.schema_editor() as editor:
558 editor.remove_index(Scene, index)
559 self.assertNotIn(index_name, self.get_constraints(table))
560
561 def test_search_vector(self):
562 """SearchVector generates IMMUTABLE SQL in order to be indexable."""
563 index_name = "test_search_vector"
564 index = Index(SearchVector("id", "scene", config="english"), name=index_name)
565 # Indexed function must be IMMUTABLE.
566 with connection.schema_editor() as editor:
567 editor.add_index(Scene, index)
568 constraints = self.get_constraints(Scene._meta.db_table)
569 self.assertIn(index_name, constraints)
570 self.assertIs(constraints[index_name]["index"], True)
571
572 with connection.schema_editor() as editor:
573 editor.remove_index(Scene, index)
574 self.assertNotIn(index_name, self.get_constraints(Scene._meta.db_table))
575
576 def test_hash_index(self):
577 # Ensure the table is there and doesn't have an index.
578 self.assertNotIn("field", self.get_constraints(CharFieldModel._meta.db_table))
579 # Add the index.
580 index_name = "char_field_model_field_hash"
581 index = HashIndex(fields=["field"], name=index_name)
582 with connection.schema_editor() as editor:
583 editor.add_index(CharFieldModel, index)
584 constraints = self.get_constraints(CharFieldModel._meta.db_table)
585 # The index was added.
586 self.assertEqual(constraints[index_name]["type"], HashIndex.suffix)
587 # Drop the index.
588 with connection.schema_editor() as editor:
589 editor.remove_index(CharFieldModel, index)
590 self.assertNotIn(
591 index_name, self.get_constraints(CharFieldModel._meta.db_table)
592 )
593
594 def test_hash_parameters(self):
595 index_name = "integer_array_hash_fillfactor"
596 index = HashIndex(fields=["field"], name=index_name, fillfactor=80)
597 with connection.schema_editor() as editor:
598 editor.add_index(CharFieldModel, index)
599 constraints = self.get_constraints(CharFieldModel._meta.db_table)
600 self.assertEqual(constraints[index_name]["type"], HashIndex.suffix)
601 self.assertEqual(constraints[index_name]["options"], ["fillfactor=80"])
602 with connection.schema_editor() as editor:
603 editor.remove_index(CharFieldModel, index)
604 self.assertNotIn(
605 index_name, self.get_constraints(CharFieldModel._meta.db_table)
606 )
607
608 def test_spgist_index(self):
609 # Ensure the table is there and doesn't have an index.
610 self.assertNotIn("field", self.get_constraints(TextFieldModel._meta.db_table))
611 # Add the index.
612 index_name = "text_field_model_field_spgist"
613 index = SpGistIndex(fields=["field"], name=index_name)
614 with connection.schema_editor() as editor:
615 editor.add_index(TextFieldModel, index)
616 constraints = self.get_constraints(TextFieldModel._meta.db_table)
617 # The index was added.
618 self.assertEqual(constraints[index_name]["type"], SpGistIndex.suffix)
619 # Drop the index.
620 with connection.schema_editor() as editor:
621 editor.remove_index(TextFieldModel, index)
622 self.assertNotIn(
623 index_name, self.get_constraints(TextFieldModel._meta.db_table)
624 )
625
626 def test_spgist_parameters(self):
627 index_name = "text_field_model_spgist_fillfactor"
628 index = SpGistIndex(fields=["field"], name=index_name, fillfactor=80)
629 with connection.schema_editor() as editor:
630 editor.add_index(TextFieldModel, index)
631 constraints = self.get_constraints(TextFieldModel._meta.db_table)
632 self.assertEqual(constraints[index_name]["type"], SpGistIndex.suffix)
633 self.assertEqual(constraints[index_name]["options"], ["fillfactor=80"])
634 with connection.schema_editor() as editor:
635 editor.remove_index(TextFieldModel, index)
636 self.assertNotIn(
637 index_name, self.get_constraints(TextFieldModel._meta.db_table)
638 )
639
640 def test_spgist_include(self):
641 index_name = "scene_spgist_include_setting"
642 index = SpGistIndex(name=index_name, fields=["scene"], include=["setting"])
643 with connection.schema_editor() as editor:
644 editor.add_index(Scene, index)
645 constraints = self.get_constraints(Scene._meta.db_table)
646 self.assertIn(index_name, constraints)
647 self.assertEqual(constraints[index_name]["type"], SpGistIndex.suffix)
648 self.assertEqual(constraints[index_name]["columns"], ["scene", "setting"])
649 with connection.schema_editor() as editor:
650 editor.remove_index(Scene, index)
651 self.assertNotIn(index_name, self.get_constraints(Scene._meta.db_table))
652
653 def test_custom_suffix(self):
654 class CustomSuffixIndex(PostgresIndex):
655 suffix = "sfx"
656
657 def create_sql(self, model, schema_editor, using="gin", **kwargs):
658 return super().create_sql(model, schema_editor, using=using, **kwargs)
659
660 index = CustomSuffixIndex(fields=["field"], name="custom_suffix_idx")
661 self.assertEqual(index.suffix, "sfx")
662 with connection.schema_editor() as editor:
663 self.assertIn(
664 " USING gin ",
665 str(index.create_sql(CharFieldModel, editor)),
666 )
667
668 def test_op_class(self):
669 index_name = "test_op_class"
670 index = Index(
671 OpClass(Lower("field"), name="text_pattern_ops"),
672 name=index_name,
673 )
674 with connection.schema_editor() as editor:
675 editor.add_index(TextFieldModel, index)
676 with editor.connection.cursor() as cursor:
677 cursor.execute(self.get_opclass_query, [index_name])
678 self.assertCountEqual(cursor.fetchall(), [("text_pattern_ops", index_name)])
679
680 def test_op_class_descending_collation(self):
681 collation = connection.features.test_collations.get("non_default")
682 if not collation:
683 self.skipTest("This backend does not support case-insensitive collations.")
684 index_name = "test_op_class_descending_collation"
685 index = Index(
686 Collate(
687 OpClass(Lower("field"), name="text_pattern_ops").desc(nulls_last=True),
688 collation=collation,
689 ),
690 name=index_name,
691 )
692 with connection.schema_editor() as editor:
693 editor.add_index(TextFieldModel, index)
694 self.assertIn(
695 "COLLATE %s" % editor.quote_name(collation),
696 str(index.create_sql(TextFieldModel, editor)),
697 )
698 with editor.connection.cursor() as cursor:
699 cursor.execute(self.get_opclass_query, [index_name])
700 self.assertCountEqual(cursor.fetchall(), [("text_pattern_ops", index_name)])
701 table = TextFieldModel._meta.db_table
702 constraints = self.get_constraints(table)
703 self.assertIn(index_name, constraints)
704 self.assertEqual(constraints[index_name]["orders"], ["DESC"])
705 with connection.schema_editor() as editor:
706 editor.remove_index(TextFieldModel, index)
707 self.assertNotIn(index_name, self.get_constraints(table))
708
709 def test_op_class_descending_partial(self):
710 index_name = "test_op_class_descending_partial"
711 index = Index(
712 OpClass(Lower("field"), name="text_pattern_ops").desc(),
713 name=index_name,
714 condition=Q(field__contains="China"),
715 )
716 with connection.schema_editor() as editor:
717 editor.add_index(TextFieldModel, index)
718 with editor.connection.cursor() as cursor:
719 cursor.execute(self.get_opclass_query, [index_name])
720 self.assertCountEqual(cursor.fetchall(), [("text_pattern_ops", index_name)])
721 constraints = self.get_constraints(TextFieldModel._meta.db_table)
722 self.assertIn(index_name, constraints)
723 self.assertEqual(constraints[index_name]["orders"], ["DESC"])
724
725 def test_op_class_descending_partial_tablespace(self):
726 index_name = "test_op_class_descending_partial_tablespace"
727 index = Index(
728 OpClass(Lower("field").desc(), name="text_pattern_ops"),
729 name=index_name,
730 condition=Q(field__contains="China"),
731 db_tablespace="pg_default",
732 )
733 with connection.schema_editor() as editor:
734 editor.add_index(TextFieldModel, index)
735 self.assertIn(
736 'TABLESPACE "pg_default" ',
737 str(index.create_sql(TextFieldModel, editor)),
738 )
739 with editor.connection.cursor() as cursor:
740 cursor.execute(self.get_opclass_query, [index_name])
741 self.assertCountEqual(cursor.fetchall(), [("text_pattern_ops", index_name)])
742 constraints = self.get_constraints(TextFieldModel._meta.db_table)
743 self.assertIn(index_name, constraints)
744 self.assertEqual(constraints[index_name]["orders"], ["DESC"])