pgutils.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. from django.core.paginator import Paginator
  2. from django.db.models import Index
  3. from django.db.migrations.operations import RunSQL
  4. from django.utils.six import text_type
  5. class PgPartialIndex(Index):
  6. suffix = 'part'
  7. max_name_length = 31
  8. def __init__(self, fields=[], name=None, where=None):
  9. if not where:
  10. raise ValueError('partial index requires WHERE clause')
  11. self.where = where
  12. super(PartialIndex, self).__init__(fields, name)
  13. def set_name_with_model(self, model):
  14. table_name = model._meta.db_table
  15. column_names = sorted(self.where.keys())
  16. where_items = []
  17. for key in sorted(self.where.keys()):
  18. where_items.append('{}:{}'.format(key, repr(self.where[key])))
  19. # The length of the parts of the name is based on the default max
  20. # length of 30 characters.
  21. hash_data = [table_name] + where_items + [self.suffix]
  22. self.name = '%s_%s_%s' % (
  23. table_name[:11],
  24. column_names[0][:7],
  25. '%s_%s' % (self._hash_generator(*hash_data), self.suffix),
  26. )
  27. assert len(self.name) <= self.max_name_length, (
  28. 'Index too long for multiple database support. Is self.suffix '
  29. 'longer than 3 characters?'
  30. )
  31. self.check_name()
  32. def __repr__(self):
  33. if self.where is not None:
  34. where_items = []
  35. for key in sorted(self.where.keys()):
  36. where_items.append('='.join([
  37. key,
  38. repr(self.where[key])
  39. ]))
  40. return '<%(name)s: fields=%(fields)s, where=%(where)s>' % {
  41. 'name': self.__class__.__name__,
  42. 'fields': "'{}'".format(', '.join(self.fields)),
  43. 'where': "'{}'".format(', '.join(where_items)),
  44. }
  45. else:
  46. return super(PartialIndex, self).__repr__()
  47. def deconstruct(self):
  48. path, args, kwargs = super(PartialIndex, self).deconstruct()
  49. kwargs['where'] = self.where
  50. return path, args, kwargs
  51. def get_sql_create_template_values(self, model, schema_editor, using):
  52. parameters = super(PartialIndex, self).get_sql_create_template_values(model, schema_editor, '')
  53. parameters['extra'] = self.get_sql_extra(schema_editor)
  54. return parameters
  55. def get_sql_extra(self, schema_editor):
  56. quote_name = schema_editor.quote_name
  57. quote_value = schema_editor.quote_value
  58. clauses = []
  59. for field, condition in self.where.items():
  60. fieldname = None
  61. compr = None
  62. if field.endswith('__lt'):
  63. fieldname = field[:-4]
  64. compr = '<'
  65. elif field.endswith('__gt'):
  66. fieldname = field[:-4]
  67. compr = '>'
  68. elif field.endswith('__lte'):
  69. fieldname = field[:-5]
  70. compr = '<='
  71. elif field.endswith('__gte'):
  72. fieldname = field[:-5]
  73. compr = '>='
  74. else:
  75. fieldname = field
  76. compr = '='
  77. clauses.append('{} {} {}'.format(
  78. quote_name(fieldname), compr, quote_value(condition)))
  79. return ' WHERE {}'.format(' AND '.join(clauses))
  80. class CreatePartialIndex(RunSQL):
  81. CREATE_SQL = """
  82. CREATE INDEX %(index_name)s ON %(table)s (%(field)s)
  83. WHERE %(condition)s;
  84. """
  85. REMOVE_SQL = """
  86. DROP INDEX %(index_name)s
  87. """
  88. def __init__(self, field, index_name, condition):
  89. self.model, self.field = field.split('.')
  90. self.index_name = index_name
  91. self.condition = condition
  92. @property
  93. def reversible(self):
  94. return True
  95. def state_forwards(self, app_label, state):
  96. pass
  97. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  98. model = from_state.apps.get_model(app_label, self.model)
  99. statement = self.CREATE_SQL % {
  100. 'index_name': self.index_name,
  101. 'table': model._meta.db_table,
  102. 'field': self.field,
  103. 'condition': self.condition,
  104. }
  105. schema_editor.execute(statement)
  106. def database_backwards(self, app_label, schema_editor, from_state, to_state):
  107. schema_editor.execute(self.REMOVE_SQL % {'index_name': self.index_name})
  108. def describe(self):
  109. message = "Create PostgreSQL partial index on field %s in %s for %s"
  110. formats = (self.field, self.model_name, self.values)
  111. return message % formats
  112. class CreatePartialCompositeIndex(CreatePartialIndex):
  113. CREATE_SQL = """
  114. CREATE INDEX %(index_name)s ON %(table)s (%(fields)s)
  115. WHERE %(condition)s;
  116. """
  117. REMOVE_SQL = """
  118. DROP INDEX %(index_name)s
  119. """
  120. def __init__(self, model, fields, index_name, condition):
  121. self.model = model
  122. self.fields = fields
  123. self.index_name = index_name
  124. self.condition = condition
  125. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  126. model = from_state.apps.get_model(app_label, self.model)
  127. statement = self.CREATE_SQL % {
  128. 'index_name': self.index_name,
  129. 'table': model._meta.db_table,
  130. 'fields': ', '.join(self.fields),
  131. 'condition': self.condition,
  132. }
  133. schema_editor.execute(statement)
  134. def describe(self):
  135. message = ("Create PostgreSQL partial composite index on fields %s in %s for %s")
  136. formats = (', '.join(self.fields), self.model_name, self.values)
  137. return message % formats
  138. def batch_update(queryset, step=50):
  139. """util because psycopg2 iterators aren't memory effective in Dj<1.11"""
  140. paginator = Paginator(queryset.order_by('pk'), step)
  141. for page_number in paginator.page_range:
  142. for obj in paginator.page(page_number).object_list:
  143. yield obj
  144. def batch_delete(queryset, step=50):
  145. """another util cos paginator goes bobbins when you are deleting"""
  146. queryset_exists = True
  147. while queryset_exists:
  148. for obj in queryset[:step]:
  149. yield obj
  150. queryset_exists = queryset.exists()