2016-06-26 00:32:56 +08:00
|
|
|
import hashlib
|
|
|
|
|
|
|
|
from django.utils.encoding import force_bytes
|
|
|
|
|
2017-01-20 17:20:53 +08:00
|
|
|
__all__ = ['Index']
|
2016-06-26 00:32:56 +08:00
|
|
|
|
|
|
|
# The max length of the names of the indexes (restricted to 30 due to Oracle)
|
|
|
|
MAX_NAME_LENGTH = 30
|
|
|
|
|
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class Index:
|
2016-06-26 00:32:56 +08:00
|
|
|
suffix = 'idx'
|
|
|
|
|
|
|
|
def __init__(self, fields=[], name=None):
|
2016-08-14 08:00:51 +08:00
|
|
|
if not isinstance(fields, list):
|
|
|
|
raise ValueError('Index.fields must be a list.')
|
2016-06-26 00:32:56 +08:00
|
|
|
if not fields:
|
|
|
|
raise ValueError('At least one field is required to define an index.')
|
|
|
|
self.fields = fields
|
2016-07-22 20:52:44 +08:00
|
|
|
# A list of 2-tuple with the field name and ordering ('' or 'DESC').
|
|
|
|
self.fields_orders = [
|
|
|
|
(field_name[1:], 'DESC') if field_name.startswith('-') else (field_name, '')
|
|
|
|
for field_name in self.fields
|
|
|
|
]
|
2016-07-18 22:29:47 +08:00
|
|
|
self.name = name or ''
|
|
|
|
if self.name:
|
2016-06-26 00:32:56 +08:00
|
|
|
errors = self.check_name()
|
2016-07-18 22:29:47 +08:00
|
|
|
if len(self.name) > MAX_NAME_LENGTH:
|
2016-06-26 00:32:56 +08:00
|
|
|
errors.append('Index names cannot be longer than %s characters.' % MAX_NAME_LENGTH)
|
|
|
|
if errors:
|
|
|
|
raise ValueError(errors)
|
|
|
|
|
|
|
|
def check_name(self):
|
|
|
|
errors = []
|
|
|
|
# Name can't start with an underscore on Oracle; prepend D if needed.
|
2016-07-18 22:29:47 +08:00
|
|
|
if self.name[0] == '_':
|
2016-06-26 00:32:56 +08:00
|
|
|
errors.append('Index names cannot start with an underscore (_).')
|
2016-07-18 22:29:47 +08:00
|
|
|
self.name = 'D%s' % self.name[1:]
|
2016-06-26 00:32:56 +08:00
|
|
|
# Name can't start with a number on Oracle; prepend D if needed.
|
2016-07-18 22:29:47 +08:00
|
|
|
elif self.name[0].isdigit():
|
2016-06-26 00:32:56 +08:00
|
|
|
errors.append('Index names cannot start with a number (0-9).')
|
2016-07-18 22:29:47 +08:00
|
|
|
self.name = 'D%s' % self.name[1:]
|
2016-06-26 00:32:56 +08:00
|
|
|
return errors
|
|
|
|
|
2016-10-13 20:39:44 +08:00
|
|
|
def get_sql_create_template_values(self, model, schema_editor, using):
|
2016-07-22 20:52:44 +08:00
|
|
|
fields = [model._meta.get_field(field_name) for field_name, order in self.fields_orders]
|
2016-07-07 00:57:17 +08:00
|
|
|
tablespace_sql = schema_editor._get_index_tablespace_sql(model, fields)
|
2016-06-26 00:32:56 +08:00
|
|
|
quote_name = schema_editor.quote_name
|
2016-07-22 20:52:44 +08:00
|
|
|
columns = [
|
|
|
|
('%s %s' % (quote_name(field.column), order)).strip()
|
|
|
|
for field, (field_name, order) in zip(fields, self.fields_orders)
|
|
|
|
]
|
2016-10-13 20:39:44 +08:00
|
|
|
return {
|
2016-07-07 00:57:17 +08:00
|
|
|
'table': quote_name(model._meta.db_table),
|
2016-06-26 00:32:56 +08:00
|
|
|
'name': quote_name(self.name),
|
2016-07-22 20:52:44 +08:00
|
|
|
'columns': ', '.join(columns),
|
2016-08-08 19:50:25 +08:00
|
|
|
'using': using,
|
2016-06-26 00:32:56 +08:00
|
|
|
'extra': tablespace_sql,
|
|
|
|
}
|
|
|
|
|
2017-01-17 00:28:30 +08:00
|
|
|
def create_sql(self, model, schema_editor, using=''):
|
2016-10-13 20:39:44 +08:00
|
|
|
sql_create_index = schema_editor.sql_create_index
|
2017-01-17 00:28:30 +08:00
|
|
|
sql_parameters = self.get_sql_create_template_values(model, schema_editor, using)
|
2016-10-13 20:39:44 +08:00
|
|
|
return sql_create_index % sql_parameters
|
|
|
|
|
2016-07-07 00:57:17 +08:00
|
|
|
def remove_sql(self, model, schema_editor):
|
2016-06-26 00:32:56 +08:00
|
|
|
quote_name = schema_editor.quote_name
|
|
|
|
return schema_editor.sql_delete_index % {
|
2016-07-07 00:57:17 +08:00
|
|
|
'table': quote_name(model._meta.db_table),
|
2016-06-26 00:32:56 +08:00
|
|
|
'name': quote_name(self.name),
|
|
|
|
}
|
|
|
|
|
|
|
|
def deconstruct(self):
|
|
|
|
path = '%s.%s' % (self.__class__.__module__, self.__class__.__name__)
|
|
|
|
path = path.replace('django.db.models.indexes', 'django.db.models')
|
2016-06-20 23:50:05 +08:00
|
|
|
return (path, (), {'fields': self.fields, 'name': self.name})
|
2016-06-26 00:32:56 +08:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _hash_generator(*args):
|
|
|
|
"""
|
|
|
|
Generate a 32-bit digest of a set of arguments that can be used to
|
|
|
|
shorten identifying names.
|
|
|
|
"""
|
|
|
|
h = hashlib.md5()
|
|
|
|
for arg in args:
|
|
|
|
h.update(force_bytes(arg))
|
|
|
|
return h.hexdigest()[:6]
|
|
|
|
|
2016-07-18 22:29:47 +08:00
|
|
|
def set_name_with_model(self, model):
|
2016-06-26 00:32:56 +08:00
|
|
|
"""
|
|
|
|
Generate a unique name for the index.
|
|
|
|
|
|
|
|
The name is divided into 3 parts - table name (12 chars), field name
|
|
|
|
(8 chars) and unique hash + suffix (10 chars). Each part is made to
|
|
|
|
fit its size by truncating the excess length.
|
|
|
|
"""
|
2016-07-18 22:29:47 +08:00
|
|
|
table_name = model._meta.db_table
|
2016-07-22 20:52:44 +08:00
|
|
|
column_names = [model._meta.get_field(field_name).column for field_name, order in self.fields_orders]
|
|
|
|
column_names_with_order = [
|
|
|
|
(('-%s' if order else '%s') % column_name)
|
|
|
|
for column_name, (field_name, order) in zip(column_names, self.fields_orders)
|
|
|
|
]
|
|
|
|
hash_data = [table_name] + column_names_with_order + [self.suffix]
|
2016-07-18 22:29:47 +08:00
|
|
|
self.name = '%s_%s_%s' % (
|
2016-06-26 00:32:56 +08:00
|
|
|
table_name[:11],
|
|
|
|
column_names[0][:7],
|
|
|
|
'%s_%s' % (self._hash_generator(*hash_data), self.suffix),
|
|
|
|
)
|
2016-07-18 22:29:47 +08:00
|
|
|
assert len(self.name) <= 30, (
|
2016-06-26 00:32:56 +08:00
|
|
|
'Index too long for multiple database support. Is self.suffix '
|
|
|
|
'longer than 3 characters?'
|
|
|
|
)
|
2016-07-18 22:29:47 +08:00
|
|
|
self.check_name()
|
2016-06-26 00:32:56 +08:00
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return "<%s: fields='%s'>" % (self.__class__.__name__, ', '.join(self.fields))
|
|
|
|
|
|
|
|
def __eq__(self, other):
|
|
|
|
return (self.__class__ == other.__class__) and (self.deconstruct() == other.deconstruct())
|