| 1 |
from django.db.backends.base.schema import BaseDatabaseSchemaEditor |
| 2 |
from django.db.models import NOT_PROVIDED, F, UniqueConstraint |
| 3 |
from django.db.models.constants import LOOKUP_SEP |
| 4 |
|
| 5 |
|
| 6 |
class DatabaseSchemaEditor(BaseDatabaseSchemaEditor): |
| 7 |
sql_rename_table = "RENAME TABLE %(old_table)s TO %(new_table)s" |
| 8 |
|
| 9 |
sql_alter_column_null = "MODIFY %(column)s %(type)s NULL" |
| 10 |
sql_alter_column_not_null = "MODIFY %(column)s %(type)s NOT NULL" |
| 11 |
sql_alter_column_type = "MODIFY %(column)s %(type)s%(collation)s%(comment)s" |
| 12 |
sql_alter_column_no_default_null = "ALTER COLUMN %(column)s SET DEFAULT NULL" |
| 13 |
|
| 14 |
# No 'CASCADE' which works as a no-op in MySQL but is undocumented |
| 15 |
sql_delete_column = "ALTER TABLE %(table)s DROP COLUMN %(column)s" |
| 16 |
|
| 17 |
sql_delete_unique = "ALTER TABLE %(table)s DROP INDEX %(name)s" |
| 18 |
sql_create_column_inline_fk = ( |
| 19 |
", ADD CONSTRAINT %(name)s FOREIGN KEY (%(column)s) " |
| 20 |
"REFERENCES %(to_table)s(%(to_column)s)" |
| 21 |
) |
| 22 |
sql_delete_fk = "ALTER TABLE %(table)s DROP FOREIGN KEY %(name)s" |
| 23 |
|
| 24 |
sql_delete_index = "DROP INDEX %(name)s ON %(table)s" |
| 25 |
sql_rename_index = "ALTER TABLE %(table)s RENAME INDEX %(old_name)s TO %(new_name)s" |
| 26 |
|
| 27 |
sql_create_pk = ( |
| 28 |
"ALTER TABLE %(table)s ADD CONSTRAINT %(name)s PRIMARY KEY (%(columns)s)" |
| 29 |
) |
| 30 |
sql_delete_pk = "ALTER TABLE %(table)s DROP PRIMARY KEY" |
| 31 |
|
| 32 |
sql_create_index = "CREATE INDEX %(name)s ON %(table)s (%(columns)s)%(extra)s" |
| 33 |
|
| 34 |
sql_alter_table_comment = "ALTER TABLE %(table)s COMMENT = %(comment)s" |
| 35 |
sql_alter_column_comment = None |
| 36 |
|
| 37 |
@property |
| 38 |
def sql_delete_check(self): |
| 39 |
if self.connection.mysql_is_mariadb: |
| 40 |
# The name of the column check constraint is the same as the field |
| 41 |
# name on MariaDB. Adding IF EXISTS clause prevents migrations |
| 42 |
# crash. Constraint is removed during a "MODIFY" column statement. |
| 43 |
return "ALTER TABLE %(table)s DROP CONSTRAINT IF EXISTS %(name)s" |
| 44 |
return "ALTER TABLE %(table)s DROP CHECK %(name)s" |
| 45 |
|
| 46 |
@property |
| 47 |
def sql_rename_column(self): |
| 48 |
is_mariadb = self.connection.mysql_is_mariadb |
| 49 |
if is_mariadb and self.connection.mysql_version < (10, 5, 2): |
| 50 |
# MariaDB < 10.5.2 doesn't support an |
| 51 |
# "ALTER TABLE ... RENAME COLUMN" statement. |
| 52 |
return "ALTER TABLE %(table)s CHANGE %(old_column)s %(new_column)s %(type)s" |
| 53 |
return super().sql_rename_column |
| 54 |
|
| 55 |
def quote_value(self, value): |
| 56 |
self.connection.ensure_connection() |
| 57 |
# MySQLdb escapes to string, PyMySQL to bytes. |
| 58 |
quoted = self.connection.connection.escape( |
| 59 |
value, self.connection.connection.encoders |
| 60 |
) |
| 61 |
if isinstance(value, str) and isinstance(quoted, bytes): |
| 62 |
quoted = quoted.decode() |
| 63 |
return quoted |
| 64 |
|
| 65 |
def _is_limited_data_type(self, field): |
| 66 |
db_type = field.db_type(self.connection) |
| 67 |
return ( |
| 68 |
db_type is not None |
| 69 |
and db_type.lower() in self.connection._limited_data_types |
| 70 |
) |
| 71 |
|
| 72 |
def _is_text_or_blob(self, field): |
| 73 |
db_type = field.db_type(self.connection) |
| 74 |
return db_type and db_type.lower().endswith(("blob", "text")) |
| 75 |
|
| 76 |
def skip_default(self, field): |
| 77 |
default_is_empty = self.effective_default(field) in ("", b"") |
| 78 |
if default_is_empty and self._is_text_or_blob(field): |
| 79 |
return True |
| 80 |
if not self._supports_limited_data_type_defaults: |
| 81 |
return self._is_limited_data_type(field) |
| 82 |
return False |
| 83 |
|
| 84 |
def skip_default_on_alter(self, field): |
| 85 |
default_is_empty = self.effective_default(field) in ("", b"") |
| 86 |
if default_is_empty and self._is_text_or_blob(field): |
| 87 |
return True |
| 88 |
if self._is_limited_data_type(field) and not self.connection.mysql_is_mariadb: |
| 89 |
# MySQL doesn't support defaults for BLOB and TEXT in the |
| 90 |
# ALTER COLUMN statement. |
| 91 |
return True |
| 92 |
return False |
| 93 |
|
| 94 |
@property |
| 95 |
def _supports_limited_data_type_defaults(self): |
| 96 |
# MariaDB and MySQL >= 8.0.13 support defaults for BLOB and TEXT. |
| 97 |
if self.connection.mysql_is_mariadb: |
| 98 |
return True |
| 99 |
return self.connection.mysql_version >= (8, 0, 13) |
| 100 |
|
| 101 |
def _column_default_sql(self, field): |
| 102 |
if ( |
| 103 |
not self.connection.mysql_is_mariadb |
| 104 |
and self._supports_limited_data_type_defaults |
| 105 |
and self._is_limited_data_type(field) |
| 106 |
): |
| 107 |
# MySQL supports defaults for BLOB and TEXT columns only if the |
| 108 |
# default value is written as an expression i.e. in parentheses. |
| 109 |
return "(%s)" |
| 110 |
return super()._column_default_sql(field) |
| 111 |
|
| 112 |
def add_field(self, model, field): |
| 113 |
super().add_field(model, field) |
| 114 |
|
| 115 |
# Simulate the effect of a one-off default. |
| 116 |
# field.default may be unhashable, so a set isn't used for "in" check. |
| 117 |
if self.skip_default(field) and field.default not in (None, NOT_PROVIDED): |
| 118 |
effective_default = self.effective_default(field) |
| 119 |
self.execute( |
| 120 |
"UPDATE %(table)s SET %(column)s = %%s" |
| 121 |
% { |
| 122 |
"table": self.quote_name(model._meta.db_table), |
| 123 |
"column": self.quote_name(field.column), |
| 124 |
}, |
| 125 |
[effective_default], |
| 126 |
) |
| 127 |
|
| 128 |
def remove_constraint(self, model, constraint): |
| 129 |
if ( |
| 130 |
isinstance(constraint, UniqueConstraint) |
| 131 |
and constraint.create_sql(model, self) is not None |
| 132 |
): |
| 133 |
self._create_missing_fk_index( |
| 134 |
model, |
| 135 |
fields=constraint.fields, |
| 136 |
expressions=constraint.expressions, |
| 137 |
) |
| 138 |
super().remove_constraint(model, constraint) |
| 139 |
|
| 140 |
def remove_index(self, model, index): |
| 141 |
self._create_missing_fk_index( |
| 142 |
model, |
| 143 |
fields=[field_name for field_name, _ in index.fields_orders], |
| 144 |
expressions=index.expressions, |
| 145 |
) |
| 146 |
super().remove_index(model, index) |
| 147 |
|
| 148 |
def _field_should_be_indexed(self, model, field): |
| 149 |
if not super()._field_should_be_indexed(model, field): |
| 150 |
return False |
| 151 |
|
| 152 |
storage = self.connection.introspection.get_storage_engine( |
| 153 |
self.connection.cursor(), model._meta.db_table |
| 154 |
) |
| 155 |
# No need to create an index for ForeignKey fields except if |
| 156 |
# db_constraint=False because the index from that constraint won't be |
| 157 |
# created. |
| 158 |
if ( |
| 159 |
storage == "InnoDB" |
| 160 |
and field.get_internal_type() == "ForeignKey" |
| 161 |
and field.db_constraint |
| 162 |
): |
| 163 |
return False |
| 164 |
return not self._is_limited_data_type(field) |
| 165 |
|
| 166 |
def _create_missing_fk_index( |
| 167 |
self, |
| 168 |
model, |
| 169 |
*, |
| 170 |
fields, |
| 171 |
expressions=None, |
| 172 |
): |
| 173 |
""" |
| 174 |
MySQL can remove an implicit FK index on a field when that field is |
| 175 |
covered by another index like a unique_together. "covered" here means |
| 176 |
that the more complex index has the FK field as its first field (see |
| 177 |
https://bugs.mysql.com/bug.php?id=37910). |
| 178 |
|
| 179 |
Manually create an implicit FK index to make it possible to remove the |
| 180 |
composed index. |
| 181 |
""" |
| 182 |
first_field_name = None |
| 183 |
if fields: |
| 184 |
first_field_name = fields[0] |
| 185 |
elif ( |
| 186 |
expressions |
| 187 |
and self.connection.features.supports_expression_indexes |
| 188 |
and isinstance(expressions[0], F) |
| 189 |
and LOOKUP_SEP not in expressions[0].name |
| 190 |
): |
| 191 |
first_field_name = expressions[0].name |
| 192 |
|
| 193 |
if not first_field_name: |
| 194 |
return |
| 195 |
|
| 196 |
first_field = model._meta.get_field(first_field_name) |
| 197 |
if first_field.get_internal_type() == "ForeignKey": |
| 198 |
column = self.connection.introspection.identifier_converter( |
| 199 |
first_field.column |
| 200 |
) |
| 201 |
with self.connection.cursor() as cursor: |
| 202 |
constraint_names = [ |
| 203 |
name |
| 204 |
for name, infodict in self.connection.introspection.get_constraints( |
| 205 |
cursor, model._meta.db_table |
| 206 |
).items() |
| 207 |
if infodict["index"] and infodict["columns"][0] == column |
| 208 |
] |
| 209 |
# There are no other indexes that starts with the FK field, only |
| 210 |
# the index that is expected to be deleted. |
| 211 |
if len(constraint_names) == 1: |
| 212 |
self.execute( |
| 213 |
self._create_index_sql(model, fields=[first_field], suffix="") |
| 214 |
) |
| 215 |
|
| 216 |
def _delete_composed_index(self, model, fields, *args): |
| 217 |
self._create_missing_fk_index(model, fields=fields) |
| 218 |
return super()._delete_composed_index(model, fields, *args) |
| 219 |
|
| 220 |
def _set_field_new_type(self, field, new_type): |
| 221 |
""" |
| 222 |
Keep the NULL and DEFAULT properties of the old field. If it has |
| 223 |
changed, it will be handled separately. |
| 224 |
""" |
| 225 |
if field.has_db_default(): |
| 226 |
default_sql, params = self.db_default_sql(field) |
| 227 |
default_sql %= tuple(self.quote_value(p) for p in params) |
| 228 |
new_type += f" DEFAULT {default_sql}" |
| 229 |
if field.null: |
| 230 |
new_type += " NULL" |
| 231 |
else: |
| 232 |
new_type += " NOT NULL" |
| 233 |
return new_type |
| 234 |
|
| 235 |
def _alter_column_type_sql( |
| 236 |
self, model, old_field, new_field, new_type, old_collation, new_collation |
| 237 |
): |
| 238 |
new_type = self._set_field_new_type(old_field, new_type) |
| 239 |
return super()._alter_column_type_sql( |
| 240 |
model, old_field, new_field, new_type, old_collation, new_collation |
| 241 |
) |
| 242 |
|
| 243 |
def _field_db_check(self, field, field_db_params): |
| 244 |
if self.connection.mysql_is_mariadb and self.connection.mysql_version >= ( |
| 245 |
10, |
| 246 |
5, |
| 247 |
2, |
| 248 |
): |
| 249 |
return super()._field_db_check(field, field_db_params) |
| 250 |
# On MySQL and MariaDB < 10.5.2 (no support for |
| 251 |
# "ALTER TABLE ... RENAME COLUMN" statements), check constraints with |
| 252 |
# the column name as it requires explicit recreation when the column is |
| 253 |
# renamed. |
| 254 |
return field_db_params["check"] |
| 255 |
|
| 256 |
def _rename_field_sql(self, table, old_field, new_field, new_type): |
| 257 |
new_type = self._set_field_new_type(old_field, new_type) |
| 258 |
return super()._rename_field_sql(table, old_field, new_field, new_type) |
| 259 |
|
| 260 |
def _alter_column_comment_sql(self, model, new_field, new_type, new_db_comment): |
| 261 |
# Comment is alter when altering the column type. |
| 262 |
return "", [] |
| 263 |
|
| 264 |
def _comment_sql(self, comment): |
| 265 |
comment_sql = super()._comment_sql(comment) |
| 266 |
return f" COMMENT {comment_sql}" |
| 267 |
|
| 268 |
def _alter_column_null_sql(self, model, old_field, new_field): |
| 269 |
if not new_field.has_db_default(): |
| 270 |
return super()._alter_column_null_sql(model, old_field, new_field) |
| 271 |
|
| 272 |
new_db_params = new_field.db_parameters(connection=self.connection) |
| 273 |
type_sql = self._set_field_new_type(new_field, new_db_params["type"]) |
| 274 |
return ( |
| 275 |
"MODIFY %(column)s %(type)s" |
| 276 |
% { |
| 277 |
"column": self.quote_name(new_field.column), |
| 278 |
"type": type_sql, |
| 279 |
}, |
| 280 |
[], |
| 281 |
) |