schema.py 7.0 KB

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