pgutils.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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(PgPartialIndex, 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] + self.fields + 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(PgPartialIndex, self).__repr__()
  47. def deconstruct(self):
  48. path, args, kwargs = super(PgPartialIndex, 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(PgPartialIndex, self).get_sql_create_template_values(
  53. model, schema_editor, '')
  54. parameters['extra'] = self.get_sql_extra(model, schema_editor)
  55. return parameters
  56. def get_sql_extra(self, model, schema_editor):
  57. quote_name = schema_editor.quote_name
  58. quote_value = schema_editor.quote_value
  59. clauses = []
  60. for field, condition in self.where.items():
  61. field_name = None
  62. compr = None
  63. if field.endswith('__lt'):
  64. field_name = field[:-4]
  65. compr = '<'
  66. elif field.endswith('__gt'):
  67. field_name = field[:-4]
  68. compr = '>'
  69. elif field.endswith('__lte'):
  70. field_name = field[:-5]
  71. compr = '<='
  72. elif field.endswith('__gte'):
  73. field_name = field[:-5]
  74. compr = '>='
  75. else:
  76. field_name = field
  77. compr = '='
  78. column = model._meta.get_field(field_name).column
  79. clauses.append('{} {} {}'.format(
  80. quote_name(column), compr, quote_value(condition)))
  81. # sort clauses for their order to be determined and testable
  82. return ' WHERE {}'.format(' AND '.join(sorted(clauses)))
  83. class CreatePartialIndex(RunSQL):
  84. CREATE_SQL = """
  85. CREATE INDEX %(index_name)s ON %(table)s (%(field)s)
  86. WHERE %(condition)s;
  87. """
  88. REMOVE_SQL = """
  89. DROP INDEX %(index_name)s
  90. """
  91. def __init__(self, field, index_name, condition):
  92. self.model, self.field = field.split('.')
  93. self.index_name = index_name
  94. self.condition = condition
  95. @property
  96. def reversible(self):
  97. return True
  98. def state_forwards(self, app_label, state):
  99. pass
  100. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  101. model = from_state.apps.get_model(app_label, self.model)
  102. statement = self.CREATE_SQL % {
  103. 'index_name': self.index_name,
  104. 'table': model._meta.db_table,
  105. 'field': self.field,
  106. 'condition': self.condition,
  107. }
  108. schema_editor.execute(statement)
  109. def database_backwards(self, app_label, schema_editor, from_state, to_state):
  110. schema_editor.execute(self.REMOVE_SQL % {'index_name': self.index_name})
  111. def describe(self):
  112. message = "Create PostgreSQL partial index on field %s in %s for %s"
  113. formats = (self.field, self.model_name, self.values)
  114. return message % formats
  115. class CreatePartialCompositeIndex(CreatePartialIndex):
  116. CREATE_SQL = """
  117. CREATE INDEX %(index_name)s ON %(table)s (%(fields)s)
  118. WHERE %(condition)s;
  119. """
  120. REMOVE_SQL = """
  121. DROP INDEX %(index_name)s
  122. """
  123. def __init__(self, model, fields, index_name, condition):
  124. self.model = model
  125. self.fields = fields
  126. self.index_name = index_name
  127. self.condition = condition
  128. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  129. model = from_state.apps.get_model(app_label, self.model)
  130. statement = self.CREATE_SQL % {
  131. 'index_name': self.index_name,
  132. 'table': model._meta.db_table,
  133. 'fields': ', '.join(self.fields),
  134. 'condition': self.condition,
  135. }
  136. schema_editor.execute(statement)
  137. def describe(self):
  138. message = ("Create PostgreSQL partial composite index on fields %s in %s for %s")
  139. formats = (', '.join(self.fields), self.model_name, self.values)
  140. return message % formats
  141. def batch_update(queryset, step=50):
  142. """util because psycopg2 iterators aren't memory effective in Dj<1.11"""
  143. paginator = Paginator(queryset.order_by('pk'), step)
  144. for page_number in paginator.page_range:
  145. for obj in paginator.page(page_number).object_list:
  146. yield obj
  147. def batch_delete(queryset, step=50):
  148. """another util cos paginator goes bobbins when you are deleting"""
  149. queryset_exists = True
  150. while queryset_exists:
  151. for obj in queryset[:step]:
  152. yield obj
  153. queryset_exists = queryset.exists()