schema.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  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. # No 'CASCADE' which works as a no-op in MySQL but is undocumented
  9. sql_delete_column = "ALTER TABLE %(table)s DROP COLUMN %(column)s"
  10. sql_rename_column = "ALTER TABLE %(table)s CHANGE %(old_column)s %(new_column)s %(type)s"
  11. sql_delete_unique = "ALTER TABLE %(table)s DROP INDEX %(name)s"
  12. sql_create_column_inline_fk = (
  13. ', ADD CONSTRAINT %(name)s FOREIGN KEY (%(column)s) '
  14. 'REFERENCES %(to_table)s(%(to_column)s)'
  15. )
  16. sql_delete_fk = "ALTER TABLE %(table)s DROP FOREIGN KEY %(name)s"
  17. sql_delete_index = "DROP INDEX %(name)s ON %(table)s"
  18. sql_create_pk = "ALTER TABLE %(table)s ADD CONSTRAINT %(name)s PRIMARY KEY (%(columns)s)"
  19. sql_delete_pk = "ALTER TABLE %(table)s DROP PRIMARY KEY"
  20. sql_create_index = 'CREATE INDEX %(name)s ON %(table)s (%(columns)s)%(extra)s'
  21. @property
  22. def sql_delete_check(self):
  23. if self.connection.mysql_is_mariadb:
  24. # The name of the column check constraint is the same as the field
  25. # name on MariaDB. Adding IF EXISTS clause prevents migrations
  26. # crash. Constraint is removed during a "MODIFY" column statement.
  27. return 'ALTER TABLE %(table)s DROP CONSTRAINT IF EXISTS %(name)s'
  28. return 'ALTER TABLE %(table)s DROP CHECK %(name)s'
  29. def quote_value(self, value):
  30. self.connection.ensure_connection()
  31. if isinstance(value, str):
  32. value = value.replace('%', '%%')
  33. # MySQLdb escapes to string, PyMySQL to bytes.
  34. quoted = self.connection.connection.escape(value, self.connection.connection.encoders)
  35. if isinstance(value, str) and isinstance(quoted, bytes):
  36. quoted = quoted.decode()
  37. return quoted
  38. def _is_limited_data_type(self, field):
  39. db_type = field.db_type(self.connection)
  40. return db_type is not None and db_type.lower() in self.connection._limited_data_types
  41. def skip_default(self, field):
  42. if not self._supports_limited_data_type_defaults:
  43. return self._is_limited_data_type(field)
  44. return False
  45. @property
  46. def _supports_limited_data_type_defaults(self):
  47. # MariaDB >= 10.2.1 and MySQL >= 8.0.13 supports defaults for BLOB
  48. # and TEXT.
  49. if self.connection.mysql_is_mariadb:
  50. return self.connection.mysql_version >= (10, 2, 1)
  51. return self.connection.mysql_version >= (8, 0, 13)
  52. def _column_default_sql(self, field):
  53. if (
  54. not self.connection.mysql_is_mariadb and
  55. self._supports_limited_data_type_defaults and
  56. self._is_limited_data_type(field)
  57. ):
  58. # MySQL supports defaults for BLOB and TEXT columns only if the
  59. # default value is written as an expression i.e. in parentheses.
  60. return '(%s)'
  61. return super()._column_default_sql(field)
  62. def add_field(self, model, field):
  63. super().add_field(model, field)
  64. # Simulate the effect of a one-off default.
  65. # field.default may be unhashable, so a set isn't used for "in" check.
  66. if self.skip_default(field) and field.default not in (None, NOT_PROVIDED):
  67. effective_default = self.effective_default(field)
  68. self.execute('UPDATE %(table)s SET %(column)s = %%s' % {
  69. 'table': self.quote_name(model._meta.db_table),
  70. 'column': self.quote_name(field.column),
  71. }, [effective_default])
  72. def _field_should_be_indexed(self, model, field):
  73. create_index = super()._field_should_be_indexed(model, field)
  74. storage = self.connection.introspection.get_storage_engine(
  75. self.connection.cursor(), model._meta.db_table
  76. )
  77. # No need to create an index for ForeignKey fields except if
  78. # db_constraint=False because the index from that constraint won't be
  79. # created.
  80. if (storage == "InnoDB" and
  81. create_index and
  82. field.get_internal_type() == 'ForeignKey' and
  83. field.db_constraint):
  84. return False
  85. return not self._is_limited_data_type(field) and create_index
  86. def _delete_composed_index(self, model, fields, *args):
  87. """
  88. MySQL can remove an implicit FK index on a field when that field is
  89. covered by another index like a unique_together. "covered" here means
  90. that the more complex index starts like the simpler one.
  91. http://bugs.mysql.com/bug.php?id=37910 / Django ticket #24757
  92. We check here before removing the [unique|index]_together if we have to
  93. recreate a FK index.
  94. """
  95. first_field = model._meta.get_field(fields[0])
  96. if first_field.get_internal_type() == 'ForeignKey':
  97. constraint_names = self._constraint_names(model, [first_field.column], index=True)
  98. if not constraint_names:
  99. self.execute(self._create_index_sql(model, [first_field], suffix=""))
  100. return super()._delete_composed_index(model, fields, *args)
  101. def _set_field_new_type_null_status(self, field, new_type):
  102. """
  103. Keep the null property of the old field. If it has changed, it will be
  104. handled separately.
  105. """
  106. if field.null:
  107. new_type += " NULL"
  108. else:
  109. new_type += " NOT NULL"
  110. return new_type
  111. def _alter_column_type_sql(self, model, old_field, new_field, new_type):
  112. new_type = self._set_field_new_type_null_status(old_field, new_type)
  113. return super()._alter_column_type_sql(model, old_field, new_field, new_type)
  114. def _rename_field_sql(self, table, old_field, new_field, new_type):
  115. new_type = self._set_field_new_type_null_status(old_field, new_type)
  116. return super()._rename_field_sql(table, old_field, new_field, new_type)