test_indexes.py 21 KB

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