diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index c930a1213d..fad6e947b0 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,3 +1,16 @@ +* Allow adding nonnamed expression indexes to be revertible. + + Fixes #40732. + + Previously, the following code would raise an error, when executed while rolling back, + and the index name should be specified explicitly. Now, the index name is inferred + automatically. + ```ruby + add_index(:items, "to_tsvector('english', description)") + ``` + + *fatkodima* + * Only warn about negative enums if a positive form that would cause conflicts exists. Fixes #39065. diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb index f3db1a1df5..0c5cdf62e4 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb @@ -1387,8 +1387,14 @@ module ActiveRecord checks = [] + if !options.key?(:name) && column_name.is_a?(String) && /\W/.match?(column_name) + options[:name] = index_name(table_name, column_name) + column_names = [] + else + column_names = index_column_names(column_name || options[:column]) + end + checks << lambda { |i| i.name == options[:name].to_s } if options.key?(:name) - column_names = index_column_names(column_name || options[:column]) if column_names.present? checks << lambda { |i| index_name(table_name, i.columns) == index_name(table_name, column_names) } diff --git a/activerecord/test/cases/invertible_migration_test.rb b/activerecord/test/cases/invertible_migration_test.rb index 6e783a5a92..9b2745f008 100644 --- a/activerecord/test/cases/invertible_migration_test.rb +++ b/activerecord/test/cases/invertible_migration_test.rb @@ -18,6 +18,7 @@ module ActiveRecord create_table("horses") do |t| t.column :content, :text t.column :remind_at, :datetime + t.column :place_id, :integer end end end @@ -198,6 +199,12 @@ module ActiveRecord end end + class RevertNonNamedExpressionIndexMigration < SilentMigration + def change + add_index :horses, "remind_at, place_id" + end + end + class RevertCustomForeignKeyTable < SilentMigration def change change_table(:horses) do |t| @@ -485,6 +492,20 @@ module ActiveRecord end end + def test_migrate_revert_add_index_without_name_on_expression + InvertibleMigration.new.migrate(:up) + RevertNonNamedExpressionIndexMigration.new.migrate(:up) + + connection = ActiveRecord::Base.connection + assert connection.index_exists?(:horses, [:remind_at, :place_id]), + "index on remind_at and place_id should exist" + + RevertNonNamedExpressionIndexMigration.new.migrate(:down) + + assert_not connection.index_exists?(:horses, [:remind_at, :place_id]), + "index on remind_at and place_id should not exist" + end + def test_up_only InvertibleMigration.new.migrate(:up) horse1 = Horse.create