From a951d1077052aec8446f1ddf40ec021044f14d11 Mon Sep 17 00:00:00 2001 From: Bastian Bartmann Date: Wed, 4 Dec 2024 16:55:11 +0100 Subject: [PATCH] Changing column null does not change default function --- activerecord/CHANGELOG.md | 4 ++++ .../connection_adapters/abstract_mysql_adapter.rb | 6 +++++- activerecord/test/cases/migration/columns_test.rb | 12 ++++++++++++ 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index 9abfc5799e566..c5f937d4a9283 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -102,4 +102,8 @@ *Kazuma Watanabe* +* Fix MySQL default functions getting dropped when changing a column's nullability. + + *Bastian Bartmann* + Please check [8-0-stable](https://github.com/rails/rails/blob/8-0-stable/activerecord/CHANGELOG.md) for previous changes. diff --git a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb index 4808d137cf2ab..4ec13c85b35de 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb @@ -403,7 +403,11 @@ def build_change_column_definition(table_name, column_name, type, **options) # : type ||= column.sql_type unless options.key?(:default) - options[:default] = column.default + options[:default] = if column.default_function + -> { column.default_function } + else + column.default + end end unless options.key?(:null) diff --git a/activerecord/test/cases/migration/columns_test.rb b/activerecord/test/cases/migration/columns_test.rb index 99a3c148b391d..51260e68a0679 100644 --- a/activerecord/test/cases/migration/columns_test.rb +++ b/activerecord/test/cases/migration/columns_test.rb @@ -346,6 +346,18 @@ def test_change_column_null_with_non_boolean_arguments_raises assert_equal "change_column_null expects a boolean value (true for NULL, false for NOT NULL). Got: #{{ from: true, to: false }}", e.message end + def test_change_column_null_does_not_change_default_functions + skip unless current_adapter?(:Mysql2Adapter, :TrilogyAdapter) + + connection.change_column_default "test_models", "created_at", -> { "(NOW())" } + TestModel.reset_column_information + assert_equal "(now())", TestModel.columns_hash["created_at"].default_function + + connection.change_column_null "test_models", "created_at", true + TestModel.reset_column_information + assert_equal "(now())", TestModel.columns_hash["created_at"].default_function + end + def test_remove_column_no_second_parameter_raises_exception assert_raise(ArgumentError) { connection.remove_column("funny") } end