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 5.7KB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. from django.db.backends.utils import names_digest, split_identifier
  2. from django.db.models.query_utils import Q
  3. from django.db.models.sql import Query
  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, opclasses=(), condition=None):
  11. if opclasses and not name:
  12. raise ValueError('An index must be named to use opclasses.')
  13. if not isinstance(condition, (type(None), Q)):
  14. raise ValueError('Index.condition must be a Q instance.')
  15. if condition and not name:
  16. raise ValueError('An index must be named to use condition.')
  17. if not isinstance(fields, (list, tuple)):
  18. raise ValueError('Index.fields must be a list or tuple.')
  19. if not isinstance(opclasses, (list, tuple)):
  20. raise ValueError('Index.opclasses must be a list or tuple.')
  21. if opclasses and len(fields) != len(opclasses):
  22. raise ValueError('Index.fields and Index.opclasses must have the same number of elements.')
  23. if not fields:
  24. raise ValueError('At least one field is required to define an index.')
  25. self.fields = list(fields)
  26. # A list of 2-tuple with the field name and ordering ('' or 'DESC').
  27. self.fields_orders = [
  28. (field_name[1:], 'DESC') if field_name.startswith('-') else (field_name, '')
  29. for field_name in self.fields
  30. ]
  31. self.name = name or ''
  32. if self.name:
  33. errors = self.check_name()
  34. if len(self.name) > self.max_name_length:
  35. errors.append('Index names cannot be longer than %s characters.' % self.max_name_length)
  36. if errors:
  37. raise ValueError(errors)
  38. self.db_tablespace = db_tablespace
  39. self.opclasses = opclasses
  40. self.condition = condition
  41. def check_name(self):
  42. errors = []
  43. # Name can't start with an underscore on Oracle; prepend D if needed.
  44. if self.name[0] == '_':
  45. errors.append('Index names cannot start with an underscore (_).')
  46. self.name = 'D%s' % self.name[1:]
  47. # Name can't start with a number on Oracle; prepend D if needed.
  48. elif self.name[0].isdigit():
  49. errors.append('Index names cannot start with a number (0-9).')
  50. self.name = 'D%s' % self.name[1:]
  51. return errors
  52. def _get_condition_sql(self, model, schema_editor):
  53. if self.condition is None:
  54. return None
  55. query = Query(model=model)
  56. where = query.build_where(self.condition)
  57. compiler = query.get_compiler(connection=schema_editor.connection)
  58. sql, params = where.as_sql(compiler, schema_editor.connection)
  59. return sql % tuple(schema_editor.quote_value(p) for p in params)
  60. def create_sql(self, model, schema_editor, using=''):
  61. fields = [model._meta.get_field(field_name) for field_name, _ in self.fields_orders]
  62. col_suffixes = [order[1] for order in self.fields_orders]
  63. condition = self._get_condition_sql(model, schema_editor)
  64. return schema_editor._create_index_sql(
  65. model, fields, name=self.name, using=using, db_tablespace=self.db_tablespace,
  66. col_suffixes=col_suffixes, opclasses=self.opclasses, condition=condition,
  67. )
  68. def remove_sql(self, model, schema_editor):
  69. return schema_editor._delete_index_sql(model, self.name)
  70. def deconstruct(self):
  71. path = '%s.%s' % (self.__class__.__module__, self.__class__.__name__)
  72. path = path.replace('django.db.models.indexes', 'django.db.models')
  73. kwargs = {'fields': self.fields, 'name': self.name}
  74. if self.db_tablespace is not None:
  75. kwargs['db_tablespace'] = self.db_tablespace
  76. if self.opclasses:
  77. kwargs['opclasses'] = self.opclasses
  78. if self.condition:
  79. kwargs['condition'] = self.condition
  80. return (path, (), kwargs)
  81. def clone(self):
  82. """Create a copy of this Index."""
  83. _, _, kwargs = self.deconstruct()
  84. return self.__class__(**kwargs)
  85. def set_name_with_model(self, model):
  86. """
  87. Generate a unique name for the index.
  88. The name is divided into 3 parts - table name (12 chars), field name
  89. (8 chars) and unique hash + suffix (10 chars). Each part is made to
  90. fit its size by truncating the excess length.
  91. """
  92. _, table_name = split_identifier(model._meta.db_table)
  93. column_names = [model._meta.get_field(field_name).column for field_name, order in self.fields_orders]
  94. column_names_with_order = [
  95. (('-%s' if order else '%s') % column_name)
  96. for column_name, (field_name, order) in zip(column_names, self.fields_orders)
  97. ]
  98. # The length of the parts of the name is based on the default max
  99. # length of 30 characters.
  100. hash_data = [table_name] + column_names_with_order + [self.suffix]
  101. self.name = '%s_%s_%s' % (
  102. table_name[:11],
  103. column_names[0][:7],
  104. '%s_%s' % (names_digest(*hash_data, length=6), self.suffix),
  105. )
  106. assert len(self.name) <= self.max_name_length, (
  107. 'Index too long for multiple database support. Is self.suffix '
  108. 'longer than 3 characters?'
  109. )
  110. self.check_name()
  111. def __repr__(self):
  112. return "<%s: fields='%s'%s>" % (
  113. self.__class__.__name__, ', '.join(self.fields),
  114. '' if self.condition is None else ', condition=%s' % self.condition,
  115. )
  116. def __eq__(self, other):
  117. return (self.__class__ == other.__class__) and (self.deconstruct() == other.deconstruct())