diff options
Diffstat (limited to 'django/db/backends/mysql/schema.py')
-rw-r--r-- | django/db/backends/mysql/schema.py | 29 |
1 files changed, 24 insertions, 5 deletions
diff --git a/django/db/backends/mysql/schema.py b/django/db/backends/mysql/schema.py index 31829506c1..bfe5a2e805 100644 --- a/django/db/backends/mysql/schema.py +++ b/django/db/backends/mysql/schema.py @@ -209,11 +209,15 @@ class DatabaseSchemaEditor(BaseDatabaseSchemaEditor): self._create_missing_fk_index(model, fields=fields) return super()._delete_composed_index(model, fields, *args) - def _set_field_new_type_null_status(self, field, new_type): + def _set_field_new_type(self, field, new_type): """ - Keep the null property of the old field. If it has changed, it will be - handled separately. + Keep the NULL and DEFAULT properties of the old field. If it has + changed, it will be handled separately. """ + if field.db_default is not NOT_PROVIDED: + default_sql, params = self.db_default_sql(field) + default_sql %= tuple(self.quote_value(p) for p in params) + new_type += f" DEFAULT {default_sql}" if field.null: new_type += " NULL" else: @@ -223,7 +227,7 @@ class DatabaseSchemaEditor(BaseDatabaseSchemaEditor): def _alter_column_type_sql( self, model, old_field, new_field, new_type, old_collation, new_collation ): - new_type = self._set_field_new_type_null_status(old_field, new_type) + new_type = self._set_field_new_type(old_field, new_type) return super()._alter_column_type_sql( model, old_field, new_field, new_type, old_collation, new_collation ) @@ -242,7 +246,7 @@ class DatabaseSchemaEditor(BaseDatabaseSchemaEditor): return field_db_params["check"] def _rename_field_sql(self, table, old_field, new_field, new_type): - new_type = self._set_field_new_type_null_status(old_field, new_type) + new_type = self._set_field_new_type(old_field, new_type) return super()._rename_field_sql(table, old_field, new_field, new_type) def _alter_column_comment_sql(self, model, new_field, new_type, new_db_comment): @@ -252,3 +256,18 @@ class DatabaseSchemaEditor(BaseDatabaseSchemaEditor): def _comment_sql(self, comment): comment_sql = super()._comment_sql(comment) return f" COMMENT {comment_sql}" + + def _alter_column_null_sql(self, model, old_field, new_field): + if new_field.db_default is NOT_PROVIDED: + return super()._alter_column_null_sql(model, old_field, new_field) + + new_db_params = new_field.db_parameters(connection=self.connection) + type_sql = self._set_field_new_type(new_field, new_db_params["type"]) + return ( + "MODIFY %(column)s %(type)s" + % { + "column": self.quote_name(new_field.column), + "type": type_sql, + }, + [], + ) |