From dfc77637ea5c1aa81caa72b1cf900e6931d61b54 Mon Sep 17 00:00:00 2001 From: Simon Charette Date: Sat, 3 Feb 2024 10:54:51 -0500 Subject: [PATCH] Fixed #35162 -- Fixed crash when adding fields with db_default on MySQL. MySQL doesn't allow literal DEFAULT values to be used for BLOB, TEXT, GEOMETRY or JSON columns and requires expression to be used instead. Regression in 7414704e88d73dafbcfbb85f9bc54cb6111439d3. --- django/db/backends/base/schema.py | 6 +++++- docs/releases/5.0.2.txt | 4 ++++ tests/schema/tests.py | 13 +++++++++++++ 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/django/db/backends/base/schema.py b/django/db/backends/base/schema.py index 242083b8507..dad3f8d916a 100644 --- a/django/db/backends/base/schema.py +++ b/django/db/backends/base/schema.py @@ -412,7 +412,11 @@ class BaseDatabaseSchemaEditor: """Return the sql and params for the field's database default.""" from django.db.models.expressions import Value - sql = "%s" if isinstance(field.db_default, Value) else "(%s)" + sql = ( + self._column_default_sql(field) + if isinstance(field.db_default, Value) + else "(%s)" + ) query = Query(model=field.model) compiler = query.get_compiler(connection=self.connection) default_sql, params = compiler.compile(field.db_default) diff --git a/docs/releases/5.0.2.txt b/docs/releases/5.0.2.txt index 64ffcb88bda..a385fbd13ef 100644 --- a/docs/releases/5.0.2.txt +++ b/docs/releases/5.0.2.txt @@ -32,3 +32,7 @@ Bugfixes * Fixed a regression in Django 5.0 that caused the ``request_finished`` signal to sometimes not be fired when running Django through an ASGI server, resulting in potential resource leaks (:ticket:`35059`). + +* Fixed a bug in Django 5.0 that caused a migration crash on MySQL when adding + a ``BinaryField``, ``TextField``, ``JSONField``, or ``GeometryField`` with a + ``db_default`` (:ticket:`35162`). diff --git a/tests/schema/tests.py b/tests/schema/tests.py index 3a026281bde..cde3d7f9914 100644 --- a/tests/schema/tests.py +++ b/tests/schema/tests.py @@ -2303,6 +2303,19 @@ class SchemaTests(TransactionTestCase): columns = self.column_classes(Author) self.assertEqual(columns["birth_year"][1].default, "1988") + @isolate_apps("schema") + def test_add_text_field_with_db_default(self): + class Author(Model): + description = TextField(db_default="(missing)") + + class Meta: + app_label = "schema" + + with connection.schema_editor() as editor: + editor.create_model(Author) + columns = self.column_classes(Author) + self.assertIn("(missing)", columns["description"][1].default) + @skipUnlessDBFeature( "supports_column_check_constraints", "can_introspect_check_constraints" )