Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

indexes.py 4.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. import hashlib
  2. from django.db.backends.utils import split_identifier
  3. from django.utils.encoding import force_bytes
  4. __all__ = ['Index']
  5. class Index:
  6. suffix = 'idx'
  7. # The max length of the name of the index (restricted to 30 for
  8. # cross-database compatibility with Oracle)
  9. max_name_length = 30
  10. def __init__(self, *, fields=(), name=None, db_tablespace=None):
  11. if not isinstance(fields, (list, tuple)):
  12. raise ValueError('Index.fields must be a list or tuple.')
  13. if not fields:
  14. raise ValueError('At least one field is required to define an index.')
  15. self.fields = list(fields)
  16. # A list of 2-tuple with the field name and ordering ('' or 'DESC').
  17. self.fields_orders = [
  18. (field_name[1:], 'DESC') if field_name.startswith('-') else (field_name, '')
  19. for field_name in self.fields
  20. ]
  21. self.name = name or ''
  22. if self.name:
  23. errors = self.check_name()
  24. if len(self.name) > self.max_name_length:
  25. errors.append('Index names cannot be longer than %s characters.' % self.max_name_length)
  26. if errors:
  27. raise ValueError(errors)
  28. self.db_tablespace = db_tablespace
  29. def check_name(self):
  30. errors = []
  31. # Name can't start with an underscore on Oracle; prepend D if needed.
  32. if self.name[0] == '_':
  33. errors.append('Index names cannot start with an underscore (_).')
  34. self.name = 'D%s' % self.name[1:]
  35. # Name can't start with a number on Oracle; prepend D if needed.
  36. elif self.name[0].isdigit():
  37. errors.append('Index names cannot start with a number (0-9).')
  38. self.name = 'D%s' % self.name[1:]
  39. return errors
  40. def create_sql(self, model, schema_editor, using=''):
  41. fields = [model._meta.get_field(field_name) for field_name, _ in self.fields_orders]
  42. col_suffixes = [order[1] for order in self.fields_orders]
  43. return schema_editor._create_index_sql(
  44. model, fields, name=self.name, using=using, db_tablespace=self.db_tablespace,
  45. col_suffixes=col_suffixes,
  46. )
  47. def remove_sql(self, model, schema_editor):
  48. quote_name = schema_editor.quote_name
  49. return schema_editor.sql_delete_index % {
  50. 'table': quote_name(model._meta.db_table),
  51. 'name': quote_name(self.name),
  52. }
  53. def deconstruct(self):
  54. path = '%s.%s' % (self.__class__.__module__, self.__class__.__name__)
  55. path = path.replace('django.db.models.indexes', 'django.db.models')
  56. kwargs = {'fields': self.fields, 'name': self.name}
  57. if self.db_tablespace is not None:
  58. kwargs['db_tablespace'] = self.db_tablespace
  59. return (path, (), kwargs)
  60. def clone(self):
  61. """Create a copy of this Index."""
  62. _, _, kwargs = self.deconstruct()
  63. return self.__class__(**kwargs)
  64. @staticmethod
  65. def _hash_generator(*args):
  66. """
  67. Generate a 32-bit digest of a set of arguments that can be used to
  68. shorten identifying names.
  69. """
  70. h = hashlib.md5()
  71. for arg in args:
  72. h.update(force_bytes(arg))
  73. return h.hexdigest()[:6]
  74. def set_name_with_model(self, model):
  75. """
  76. Generate a unique name for the index.
  77. The name is divided into 3 parts - table name (12 chars), field name
  78. (8 chars) and unique hash + suffix (10 chars). Each part is made to
  79. fit its size by truncating the excess length.
  80. """
  81. _, table_name = split_identifier(model._meta.db_table)
  82. column_names = [model._meta.get_field(field_name).column for field_name, order in self.fields_orders]
  83. column_names_with_order = [
  84. (('-%s' if order else '%s') % column_name)
  85. for column_name, (field_name, order) in zip(column_names, self.fields_orders)
  86. ]
  87. # The length of the parts of the name is based on the default max
  88. # length of 30 characters.
  89. hash_data = [table_name] + column_names_with_order + [self.suffix]
  90. self.name = '%s_%s_%s' % (
  91. table_name[:11],
  92. column_names[0][:7],
  93. '%s_%s' % (self._hash_generator(*hash_data), self.suffix),
  94. )
  95. assert len(self.name) <= self.max_name_length, (
  96. 'Index too long for multiple database support. Is self.suffix '
  97. 'longer than 3 characters?'
  98. )
  99. self.check_name()
  100. def __repr__(self):
  101. return "<%s: fields='%s'>" % (self.__class__.__name__, ', '.join(self.fields))
  102. def __eq__(self, other):
  103. return (self.__class__ == other.__class__) and (self.deconstruct() == other.deconstruct())