test_indexes.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. from unittest import mock
  2. from django.contrib.postgres.indexes import (
  3. BloomIndex, BrinIndex, BTreeIndex, GinIndex, GistIndex, HashIndex,
  4. SpGistIndex,
  5. )
  6. from django.db import NotSupportedError, connection
  7. from django.db.models import CharField, Q
  8. from django.db.models.functions import Length
  9. from django.test import skipUnlessDBFeature
  10. from django.test.utils import register_lookup
  11. from . import PostgreSQLSimpleTestCase, PostgreSQLTestCase
  12. from .models import CharFieldModel, IntegerArrayModel, Scene
  13. class IndexTestMixin:
  14. def test_name_auto_generation(self):
  15. index = self.index_class(fields=['field'])
  16. index.set_name_with_model(CharFieldModel)
  17. self.assertRegex(index.name, r'postgres_te_field_[0-9a-f]{6}_%s' % self.index_class.suffix)
  18. def test_deconstruction_no_customization(self):
  19. index = self.index_class(fields=['title'], name='test_title_%s' % self.index_class.suffix)
  20. path, args, kwargs = index.deconstruct()
  21. self.assertEqual(path, 'django.contrib.postgres.indexes.%s' % self.index_class.__name__)
  22. self.assertEqual(args, ())
  23. self.assertEqual(kwargs, {'fields': ['title'], 'name': 'test_title_%s' % self.index_class.suffix})
  24. class BloomIndexTests(IndexTestMixin, PostgreSQLSimpleTestCase):
  25. index_class = BloomIndex
  26. def test_suffix(self):
  27. self.assertEqual(BloomIndex.suffix, 'bloom')
  28. def test_deconstruction(self):
  29. index = BloomIndex(fields=['title'], name='test_bloom', length=80, columns=[4])
  30. path, args, kwargs = index.deconstruct()
  31. self.assertEqual(path, 'django.contrib.postgres.indexes.BloomIndex')
  32. self.assertEqual(args, ())
  33. self.assertEqual(kwargs, {
  34. 'fields': ['title'],
  35. 'name': 'test_bloom',
  36. 'length': 80,
  37. 'columns': [4],
  38. })
  39. def test_invalid_fields(self):
  40. msg = 'Bloom indexes support a maximum of 32 fields.'
  41. with self.assertRaisesMessage(ValueError, msg):
  42. BloomIndex(fields=['title'] * 33, name='test_bloom')
  43. def test_invalid_columns(self):
  44. msg = 'BloomIndex.columns must be a list or tuple.'
  45. with self.assertRaisesMessage(ValueError, msg):
  46. BloomIndex(fields=['title'], name='test_bloom', columns='x')
  47. msg = 'BloomIndex.columns cannot have more values than fields.'
  48. with self.assertRaisesMessage(ValueError, msg):
  49. BloomIndex(fields=['title'], name='test_bloom', columns=[4, 3])
  50. def test_invalid_columns_value(self):
  51. msg = 'BloomIndex.columns must contain integers from 1 to 4095.'
  52. for length in (0, 4096):
  53. with self.subTest(length), self.assertRaisesMessage(ValueError, msg):
  54. BloomIndex(fields=['title'], name='test_bloom', columns=[length])
  55. def test_invalid_length(self):
  56. msg = 'BloomIndex.length must be None or an integer from 1 to 4096.'
  57. for length in (0, 4097):
  58. with self.subTest(length), self.assertRaisesMessage(ValueError, msg):
  59. BloomIndex(fields=['title'], name='test_bloom', length=length)
  60. class BrinIndexTests(IndexTestMixin, PostgreSQLSimpleTestCase):
  61. index_class = BrinIndex
  62. def test_suffix(self):
  63. self.assertEqual(BrinIndex.suffix, 'brin')
  64. def test_deconstruction(self):
  65. index = BrinIndex(fields=['title'], name='test_title_brin', autosummarize=True, pages_per_range=16)
  66. path, args, kwargs = index.deconstruct()
  67. self.assertEqual(path, 'django.contrib.postgres.indexes.BrinIndex')
  68. self.assertEqual(args, ())
  69. self.assertEqual(kwargs, {
  70. 'fields': ['title'],
  71. 'name': 'test_title_brin',
  72. 'autosummarize': True,
  73. 'pages_per_range': 16,
  74. })
  75. def test_invalid_pages_per_range(self):
  76. with self.assertRaisesMessage(ValueError, 'pages_per_range must be None or a positive integer'):
  77. BrinIndex(fields=['title'], name='test_title_brin', pages_per_range=0)
  78. class BTreeIndexTests(IndexTestMixin, PostgreSQLSimpleTestCase):
  79. index_class = BTreeIndex
  80. def test_suffix(self):
  81. self.assertEqual(BTreeIndex.suffix, 'btree')
  82. def test_deconstruction(self):
  83. index = BTreeIndex(fields=['title'], name='test_title_btree', fillfactor=80)
  84. path, args, kwargs = index.deconstruct()
  85. self.assertEqual(path, 'django.contrib.postgres.indexes.BTreeIndex')
  86. self.assertEqual(args, ())
  87. self.assertEqual(kwargs, {'fields': ['title'], 'name': 'test_title_btree', 'fillfactor': 80})
  88. class GinIndexTests(IndexTestMixin, PostgreSQLSimpleTestCase):
  89. index_class = GinIndex
  90. def test_suffix(self):
  91. self.assertEqual(GinIndex.suffix, 'gin')
  92. def test_deconstruction(self):
  93. index = GinIndex(
  94. fields=['title'],
  95. name='test_title_gin',
  96. fastupdate=True,
  97. gin_pending_list_limit=128,
  98. )
  99. path, args, kwargs = index.deconstruct()
  100. self.assertEqual(path, 'django.contrib.postgres.indexes.GinIndex')
  101. self.assertEqual(args, ())
  102. self.assertEqual(kwargs, {
  103. 'fields': ['title'],
  104. 'name': 'test_title_gin',
  105. 'fastupdate': True,
  106. 'gin_pending_list_limit': 128,
  107. })
  108. class GistIndexTests(IndexTestMixin, PostgreSQLSimpleTestCase):
  109. index_class = GistIndex
  110. def test_suffix(self):
  111. self.assertEqual(GistIndex.suffix, 'gist')
  112. def test_deconstruction(self):
  113. index = GistIndex(fields=['title'], name='test_title_gist', buffering=False, fillfactor=80)
  114. path, args, kwargs = index.deconstruct()
  115. self.assertEqual(path, 'django.contrib.postgres.indexes.GistIndex')
  116. self.assertEqual(args, ())
  117. self.assertEqual(kwargs, {
  118. 'fields': ['title'],
  119. 'name': 'test_title_gist',
  120. 'buffering': False,
  121. 'fillfactor': 80,
  122. })
  123. class HashIndexTests(IndexTestMixin, PostgreSQLSimpleTestCase):
  124. index_class = HashIndex
  125. def test_suffix(self):
  126. self.assertEqual(HashIndex.suffix, 'hash')
  127. def test_deconstruction(self):
  128. index = HashIndex(fields=['title'], name='test_title_hash', fillfactor=80)
  129. path, args, kwargs = index.deconstruct()
  130. self.assertEqual(path, 'django.contrib.postgres.indexes.HashIndex')
  131. self.assertEqual(args, ())
  132. self.assertEqual(kwargs, {'fields': ['title'], 'name': 'test_title_hash', 'fillfactor': 80})
  133. class SpGistIndexTests(IndexTestMixin, PostgreSQLSimpleTestCase):
  134. index_class = SpGistIndex
  135. def test_suffix(self):
  136. self.assertEqual(SpGistIndex.suffix, 'spgist')
  137. def test_deconstruction(self):
  138. index = SpGistIndex(fields=['title'], name='test_title_spgist', fillfactor=80)
  139. path, args, kwargs = index.deconstruct()
  140. self.assertEqual(path, 'django.contrib.postgres.indexes.SpGistIndex')
  141. self.assertEqual(args, ())
  142. self.assertEqual(kwargs, {'fields': ['title'], 'name': 'test_title_spgist', 'fillfactor': 80})
  143. class SchemaTests(PostgreSQLTestCase):
  144. def get_constraints(self, table):
  145. """
  146. Get the indexes on the table using a new cursor.
  147. """
  148. with connection.cursor() as cursor:
  149. return connection.introspection.get_constraints(cursor, table)
  150. def test_gin_index(self):
  151. # Ensure the table is there and doesn't have an index.
  152. self.assertNotIn('field', self.get_constraints(IntegerArrayModel._meta.db_table))
  153. # Add the index
  154. index_name = 'integer_array_model_field_gin'
  155. index = GinIndex(fields=['field'], name=index_name)
  156. with connection.schema_editor() as editor:
  157. editor.add_index(IntegerArrayModel, index)
  158. constraints = self.get_constraints(IntegerArrayModel._meta.db_table)
  159. # Check gin index was added
  160. self.assertEqual(constraints[index_name]['type'], GinIndex.suffix)
  161. # Drop the index
  162. with connection.schema_editor() as editor:
  163. editor.remove_index(IntegerArrayModel, index)
  164. self.assertNotIn(index_name, self.get_constraints(IntegerArrayModel._meta.db_table))
  165. def test_gin_fastupdate(self):
  166. index_name = 'integer_array_gin_fastupdate'
  167. index = GinIndex(fields=['field'], name=index_name, fastupdate=False)
  168. with connection.schema_editor() as editor:
  169. editor.add_index(IntegerArrayModel, index)
  170. constraints = self.get_constraints(IntegerArrayModel._meta.db_table)
  171. self.assertEqual(constraints[index_name]['type'], 'gin')
  172. self.assertEqual(constraints[index_name]['options'], ['fastupdate=off'])
  173. with connection.schema_editor() as editor:
  174. editor.remove_index(IntegerArrayModel, index)
  175. self.assertNotIn(index_name, self.get_constraints(IntegerArrayModel._meta.db_table))
  176. def test_partial_gin_index(self):
  177. with register_lookup(CharField, Length):
  178. index_name = 'char_field_gin_partial_idx'
  179. index = GinIndex(fields=['field'], name=index_name, condition=Q(field__length=40))
  180. with connection.schema_editor() as editor:
  181. editor.add_index(CharFieldModel, index)
  182. constraints = self.get_constraints(CharFieldModel._meta.db_table)
  183. self.assertEqual(constraints[index_name]['type'], 'gin')
  184. with connection.schema_editor() as editor:
  185. editor.remove_index(CharFieldModel, index)
  186. self.assertNotIn(index_name, self.get_constraints(CharFieldModel._meta.db_table))
  187. def test_partial_gin_index_with_tablespace(self):
  188. with register_lookup(CharField, Length):
  189. index_name = 'char_field_gin_partial_idx'
  190. index = GinIndex(
  191. fields=['field'],
  192. name=index_name,
  193. condition=Q(field__length=40),
  194. db_tablespace='pg_default',
  195. )
  196. with connection.schema_editor() as editor:
  197. editor.add_index(CharFieldModel, index)
  198. self.assertIn('TABLESPACE "pg_default" ', str(index.create_sql(CharFieldModel, editor)))
  199. constraints = self.get_constraints(CharFieldModel._meta.db_table)
  200. self.assertEqual(constraints[index_name]['type'], 'gin')
  201. with connection.schema_editor() as editor:
  202. editor.remove_index(CharFieldModel, index)
  203. self.assertNotIn(index_name, self.get_constraints(CharFieldModel._meta.db_table))
  204. def test_gin_parameters(self):
  205. index_name = 'integer_array_gin_params'
  206. index = GinIndex(fields=['field'], name=index_name, fastupdate=True, gin_pending_list_limit=64)
  207. with connection.schema_editor() as editor:
  208. editor.add_index(IntegerArrayModel, index)
  209. constraints = self.get_constraints(IntegerArrayModel._meta.db_table)
  210. self.assertEqual(constraints[index_name]['type'], 'gin')
  211. self.assertEqual(constraints[index_name]['options'], ['gin_pending_list_limit=64', 'fastupdate=on'])
  212. with connection.schema_editor() as editor:
  213. editor.remove_index(IntegerArrayModel, index)
  214. self.assertNotIn(index_name, self.get_constraints(IntegerArrayModel._meta.db_table))
  215. def test_bloom_index(self):
  216. index_name = 'char_field_model_field_bloom'
  217. index = BloomIndex(fields=['field'], name=index_name)
  218. with connection.schema_editor() as editor:
  219. editor.add_index(CharFieldModel, index)
  220. constraints = self.get_constraints(CharFieldModel._meta.db_table)
  221. self.assertEqual(constraints[index_name]['type'], BloomIndex.suffix)
  222. with connection.schema_editor() as editor:
  223. editor.remove_index(CharFieldModel, index)
  224. self.assertNotIn(index_name, self.get_constraints(CharFieldModel._meta.db_table))
  225. def test_bloom_parameters(self):
  226. index_name = 'char_field_model_field_bloom_params'
  227. index = BloomIndex(fields=['field'], name=index_name, length=512, columns=[3])
  228. with connection.schema_editor() as editor:
  229. editor.add_index(CharFieldModel, index)
  230. constraints = self.get_constraints(CharFieldModel._meta.db_table)
  231. self.assertEqual(constraints[index_name]['type'], BloomIndex.suffix)
  232. self.assertEqual(constraints[index_name]['options'], ['length=512', 'col1=3'])
  233. with connection.schema_editor() as editor:
  234. editor.remove_index(CharFieldModel, index)
  235. self.assertNotIn(index_name, self.get_constraints(CharFieldModel._meta.db_table))
  236. def test_brin_index(self):
  237. index_name = 'char_field_model_field_brin'
  238. index = BrinIndex(fields=['field'], name=index_name, pages_per_range=4)
  239. with connection.schema_editor() as editor:
  240. editor.add_index(CharFieldModel, index)
  241. constraints = self.get_constraints(CharFieldModel._meta.db_table)
  242. self.assertEqual(constraints[index_name]['type'], BrinIndex.suffix)
  243. self.assertEqual(constraints[index_name]['options'], ['pages_per_range=4'])
  244. with connection.schema_editor() as editor:
  245. editor.remove_index(CharFieldModel, index)
  246. self.assertNotIn(index_name, self.get_constraints(CharFieldModel._meta.db_table))
  247. @skipUnlessDBFeature('has_brin_autosummarize')
  248. def test_brin_parameters(self):
  249. index_name = 'char_field_brin_params'
  250. index = BrinIndex(fields=['field'], name=index_name, autosummarize=True)
  251. with connection.schema_editor() as editor:
  252. editor.add_index(CharFieldModel, index)
  253. constraints = self.get_constraints(CharFieldModel._meta.db_table)
  254. self.assertEqual(constraints[index_name]['type'], BrinIndex.suffix)
  255. self.assertEqual(constraints[index_name]['options'], ['autosummarize=on'])
  256. with connection.schema_editor() as editor:
  257. editor.remove_index(CharFieldModel, index)
  258. self.assertNotIn(index_name, self.get_constraints(CharFieldModel._meta.db_table))
  259. def test_brin_autosummarize_not_supported(self):
  260. index_name = 'brin_options_exception'
  261. index = BrinIndex(fields=['field'], name=index_name, autosummarize=True)
  262. with self.assertRaisesMessage(NotSupportedError, 'BRIN option autosummarize requires PostgreSQL 10+.'):
  263. with mock.patch('django.db.backends.postgresql.features.DatabaseFeatures.has_brin_autosummarize', False):
  264. with connection.schema_editor() as editor:
  265. editor.add_index(CharFieldModel, index)
  266. self.assertNotIn(index_name, self.get_constraints(CharFieldModel._meta.db_table))
  267. def test_btree_index(self):
  268. # Ensure the table is there and doesn't have an index.
  269. self.assertNotIn('field', self.get_constraints(CharFieldModel._meta.db_table))
  270. # Add the index.
  271. index_name = 'char_field_model_field_btree'
  272. index = BTreeIndex(fields=['field'], name=index_name)
  273. with connection.schema_editor() as editor:
  274. editor.add_index(CharFieldModel, index)
  275. constraints = self.get_constraints(CharFieldModel._meta.db_table)
  276. # The index was added.
  277. self.assertEqual(constraints[index_name]['type'], BTreeIndex.suffix)
  278. # Drop the index.
  279. with connection.schema_editor() as editor:
  280. editor.remove_index(CharFieldModel, index)
  281. self.assertNotIn(index_name, self.get_constraints(CharFieldModel._meta.db_table))
  282. def test_btree_parameters(self):
  283. index_name = 'integer_array_btree_fillfactor'
  284. index = BTreeIndex(fields=['field'], name=index_name, fillfactor=80)
  285. with connection.schema_editor() as editor:
  286. editor.add_index(CharFieldModel, index)
  287. constraints = self.get_constraints(CharFieldModel._meta.db_table)
  288. self.assertEqual(constraints[index_name]['type'], BTreeIndex.suffix)
  289. self.assertEqual(constraints[index_name]['options'], ['fillfactor=80'])
  290. with connection.schema_editor() as editor:
  291. editor.remove_index(CharFieldModel, index)
  292. self.assertNotIn(index_name, self.get_constraints(CharFieldModel._meta.db_table))
  293. def test_gist_index(self):
  294. # Ensure the table is there and doesn't have an index.
  295. self.assertNotIn('field', self.get_constraints(CharFieldModel._meta.db_table))
  296. # Add the index.
  297. index_name = 'char_field_model_field_gist'
  298. index = GistIndex(fields=['field'], name=index_name)
  299. with connection.schema_editor() as editor:
  300. editor.add_index(CharFieldModel, index)
  301. constraints = self.get_constraints(CharFieldModel._meta.db_table)
  302. # The index was added.
  303. self.assertEqual(constraints[index_name]['type'], GistIndex.suffix)
  304. # Drop the index.
  305. with connection.schema_editor() as editor:
  306. editor.remove_index(CharFieldModel, index)
  307. self.assertNotIn(index_name, self.get_constraints(CharFieldModel._meta.db_table))
  308. def test_gist_parameters(self):
  309. index_name = 'integer_array_gist_buffering'
  310. index = GistIndex(fields=['field'], name=index_name, buffering=True, fillfactor=80)
  311. with connection.schema_editor() as editor:
  312. editor.add_index(CharFieldModel, index)
  313. constraints = self.get_constraints(CharFieldModel._meta.db_table)
  314. self.assertEqual(constraints[index_name]['type'], GistIndex.suffix)
  315. self.assertEqual(constraints[index_name]['options'], ['buffering=on', 'fillfactor=80'])
  316. with connection.schema_editor() as editor:
  317. editor.remove_index(CharFieldModel, index)
  318. self.assertNotIn(index_name, self.get_constraints(CharFieldModel._meta.db_table))
  319. @skipUnlessDBFeature('supports_covering_gist_indexes')
  320. def test_gist_include(self):
  321. index_name = 'scene_gist_include_setting'
  322. index = GistIndex(name=index_name, fields=['scene'], include=['setting'])
  323. with connection.schema_editor() as editor:
  324. editor.add_index(Scene, index)
  325. constraints = self.get_constraints(Scene._meta.db_table)
  326. self.assertIn(index_name, constraints)
  327. self.assertEqual(constraints[index_name]['type'], GistIndex.suffix)
  328. self.assertEqual(constraints[index_name]['columns'], ['scene', 'setting'])
  329. with connection.schema_editor() as editor:
  330. editor.remove_index(Scene, index)
  331. self.assertNotIn(index_name, self.get_constraints(Scene._meta.db_table))
  332. def test_gist_include_not_supported(self):
  333. index_name = 'gist_include_exception'
  334. index = GistIndex(fields=['scene'], name=index_name, include=['setting'])
  335. msg = 'Covering GiST indexes requires PostgreSQL 12+.'
  336. with self.assertRaisesMessage(NotSupportedError, msg):
  337. with mock.patch(
  338. 'django.db.backends.postgresql.features.DatabaseFeatures.supports_covering_gist_indexes',
  339. False,
  340. ):
  341. with connection.schema_editor() as editor:
  342. editor.add_index(Scene, index)
  343. self.assertNotIn(index_name, self.get_constraints(Scene._meta.db_table))
  344. def test_hash_index(self):
  345. # Ensure the table is there and doesn't have an index.
  346. self.assertNotIn('field', self.get_constraints(CharFieldModel._meta.db_table))
  347. # Add the index.
  348. index_name = 'char_field_model_field_hash'
  349. index = HashIndex(fields=['field'], name=index_name)
  350. with connection.schema_editor() as editor:
  351. editor.add_index(CharFieldModel, index)
  352. constraints = self.get_constraints(CharFieldModel._meta.db_table)
  353. # The index was added.
  354. self.assertEqual(constraints[index_name]['type'], HashIndex.suffix)
  355. # Drop the index.
  356. with connection.schema_editor() as editor:
  357. editor.remove_index(CharFieldModel, index)
  358. self.assertNotIn(index_name, self.get_constraints(CharFieldModel._meta.db_table))
  359. def test_hash_parameters(self):
  360. index_name = 'integer_array_hash_fillfactor'
  361. index = HashIndex(fields=['field'], name=index_name, fillfactor=80)
  362. with connection.schema_editor() as editor:
  363. editor.add_index(CharFieldModel, index)
  364. constraints = self.get_constraints(CharFieldModel._meta.db_table)
  365. self.assertEqual(constraints[index_name]['type'], HashIndex.suffix)
  366. self.assertEqual(constraints[index_name]['options'], ['fillfactor=80'])
  367. with connection.schema_editor() as editor:
  368. editor.remove_index(CharFieldModel, index)
  369. self.assertNotIn(index_name, self.get_constraints(CharFieldModel._meta.db_table))
  370. def test_spgist_index(self):
  371. # Ensure the table is there and doesn't have an index.
  372. self.assertNotIn('field', self.get_constraints(CharFieldModel._meta.db_table))
  373. # Add the index.
  374. index_name = 'char_field_model_field_spgist'
  375. index = SpGistIndex(fields=['field'], name=index_name)
  376. with connection.schema_editor() as editor:
  377. editor.add_index(CharFieldModel, index)
  378. constraints = self.get_constraints(CharFieldModel._meta.db_table)
  379. # The index was added.
  380. self.assertEqual(constraints[index_name]['type'], SpGistIndex.suffix)
  381. # Drop the index.
  382. with connection.schema_editor() as editor:
  383. editor.remove_index(CharFieldModel, index)
  384. self.assertNotIn(index_name, self.get_constraints(CharFieldModel._meta.db_table))
  385. def test_spgist_parameters(self):
  386. index_name = 'integer_array_spgist_fillfactor'
  387. index = SpGistIndex(fields=['field'], name=index_name, fillfactor=80)
  388. with connection.schema_editor() as editor:
  389. editor.add_index(CharFieldModel, index)
  390. constraints = self.get_constraints(CharFieldModel._meta.db_table)
  391. self.assertEqual(constraints[index_name]['type'], SpGistIndex.suffix)
  392. self.assertEqual(constraints[index_name]['options'], ['fillfactor=80'])
  393. with connection.schema_editor() as editor:
  394. editor.remove_index(CharFieldModel, index)
  395. self.assertNotIn(index_name, self.get_constraints(CharFieldModel._meta.db_table))