schema.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. from django.db.backends.base.schema import BaseDatabaseSchemaEditor
  2. from django.db.models import NOT_PROVIDED
  3. class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):
  4. sql_rename_table = "RENAME TABLE %(old_table)s TO %(new_table)s"
  5. sql_alter_column_null = "MODIFY %(column)s %(type)s NULL"
  6. sql_alter_column_not_null = "MODIFY %(column)s %(type)s NOT NULL"
  7. sql_alter_column_type = "MODIFY %(column)s %(type)s"
  8. sql_rename_column = "ALTER TABLE %(table)s CHANGE %(old_column)s %(new_column)s %(type)s"
  9. sql_delete_table = "DROP TABLE %(table)s"
  10. sql_delete_column = "ALTER TABLE %(table)s DROP COLUMN %(column)s"
  11. sql_delete_unique = "ALTER TABLE %(table)s DROP INDEX %(name)s"
  12. sql_delete_index = "DROP INDEX %(name)s ON %(table)s"
  13. alter_string_set_null = 'MODIFY %(column)s %(type)s NULL;'
  14. alter_string_drop_null = 'MODIFY %(column)s %(type)s NOT NULL;'
  15. sql_create_pk = "ALTER TABLE %(table)s ADD CONSTRAINT %(name)s PRIMARY KEY (%(columns)s)"
  16. sql_delete_pk = "ALTER TABLE %(table)s DROP PRIMARY KEY"
  17. def quote_value(self, value):
  18. # Inner import to allow module to fail to load gracefully
  19. import MySQLdb.converters
  20. return MySQLdb.escape(value, MySQLdb.converters.conversions)
  21. def skip_default(self, field):
  22. """
  23. MySQL doesn't accept default values for longtext and longblob
  24. and implicitly treats these columns as nullable.
  25. """
  26. return field.db_type(self.connection) in {'longtext', 'longblob'}
  27. def add_field(self, model, field):
  28. super(DatabaseSchemaEditor, self).add_field(model, field)
  29. # Simulate the effect of a one-off default.
  30. # field.default may be unhashable, so a set isn't used for "in" check.
  31. if self.skip_default(field) and field.default not in (None, NOT_PROVIDED):
  32. effective_default = self.effective_default(field)
  33. self.execute('UPDATE %(table)s SET %(column)s = %%s' % {
  34. 'table': self.quote_name(model._meta.db_table),
  35. 'column': self.quote_name(field.column),
  36. }, [effective_default])
  37. def _model_indexes_sql(self, model):
  38. storage = self.connection.introspection.get_storage_engine(
  39. self.connection.cursor(), model._meta.db_table
  40. )
  41. if storage == "InnoDB":
  42. for field in model._meta.local_fields:
  43. if field.db_index and not field.unique and field.get_internal_type() == "ForeignKey":
  44. # Temporary setting db_index to False (in memory) to disable
  45. # index creation for FKs (index automatically created by MySQL)
  46. field.db_index = False
  47. return super(DatabaseSchemaEditor, self)._model_indexes_sql(model)
  48. def _delete_composed_index(self, model, fields, *args):
  49. """
  50. MySQL can remove an implicit FK index on a field when that field is
  51. covered by another index like a unique_together. "covered" here means
  52. that the more complex index starts like the simpler one.
  53. http://bugs.mysql.com/bug.php?id=37910 / Django ticket #24757
  54. We check here before removing the [unique|index]_together if we have to
  55. recreate a FK index.
  56. """
  57. first_field = model._meta.get_field(fields[0])
  58. if first_field.get_internal_type() == 'ForeignKey':
  59. constraint_names = self._constraint_names(model, [first_field.column], index=True)
  60. if not constraint_names:
  61. self.execute(self._create_index_sql(model, [first_field], suffix=""))
  62. return super(DatabaseSchemaEditor, self)._delete_composed_index(model, fields, *args)
  63. def _set_field_new_type_null_status(self, field, new_type):
  64. """
  65. Keep the null property of the old field. If it has changed, it will be
  66. handled separately.
  67. """
  68. if field.null:
  69. new_type += " NULL"
  70. else:
  71. new_type += " NOT NULL"
  72. return new_type
  73. def _alter_column_type_sql(self, table, old_field, new_field, new_type):
  74. new_type = self._set_field_new_type_null_status(old_field, new_type)
  75. return super(DatabaseSchemaEditor, self)._alter_column_type_sql(table, old_field, new_field, new_type)
  76. def _rename_field_sql(self, table, old_field, new_field, new_type):
  77. new_type = self._set_field_new_type_null_status(old_field, new_type)
  78. return super(DatabaseSchemaEditor, self)._rename_field_sql(table, old_field, new_field, new_type)
  79. def remove_field(self, model, field):
  80. """
  81. Removes a field from a model. Usually involves deleting a column,
  82. but for M2Ms may involve deleting a table.
  83. """
  84. # Special-case implicit M2M tables
  85. if field.many_to_many and field.rel.through._meta.auto_created:
  86. return self.delete_model(field.rel.through)
  87. # It might not actually have a column behind it
  88. if field.db_parameters(connection=self.connection)['type'] is None:
  89. return
  90. # Drop any FK constraints, MySQL requires explicit deletion
  91. if field.rel:
  92. fk_names = self._constraint_names(model, [field.column], foreign_key=True)
  93. for fk_name in fk_names:
  94. self.execute(self._delete_constraint_sql(self.sql_delete_fk, model, fk_name))
  95. # Drop any Index, TiDB requires explicite deletion
  96. if field.db_index:
  97. idx_names = self._constraint_names(model, [field.column], index=True)
  98. for idx_name in idx_names:
  99. self.execute(self._delete_constraint_sql(self.sql_delete_index, model, idx_name))
  100. # Delete the column
  101. sql = self.sql_delete_column % {
  102. "table": self.quote_name(model._meta.db_table),
  103. "column": self.quote_name(field.column),
  104. }
  105. self.execute(sql)
  106. # Reset connection if required
  107. if self.connection.features.connection_persists_old_columns:
  108. self.connection.close()