1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

SQLite3: Fix rename reference column not to lose foreign key constraint

Fixes #33520.
This commit is contained in:
Ryuta Kamizono 2018-08-20 02:15:18 +09:00
parent fd1ec91c73
commit b6e583343a
2 changed files with 31 additions and 11 deletions

View file

@ -409,14 +409,24 @@ module ActiveRecord
def alter_table(table_name, options = {})
altered_table_name = "a#{table_name}"
options_to_restore = { foreign_keys: foreign_keys(table_name) }
caller = lambda { |definition| yield definition if block_given? }
foreign_keys = foreign_keys(table_name)
caller = lambda do |definition|
rename = options[:rename] || {}
foreign_keys.each do |fk|
if column = rename[fk.options[:column]]
fk.options[:column] = column
end
definition.foreign_key(fk.to_table, fk.options)
end
yield definition if block_given?
end
transaction do
disable_referential_integrity do
move_table(table_name, altered_table_name,
options.merge(temporary: true))
move_table(altered_table_name, table_name, options_to_restore, &caller)
move_table(table_name, altered_table_name, options.merge(temporary: true))
move_table(altered_table_name, table_name, &caller)
end
end
end
@ -448,12 +458,6 @@ module ActiveRecord
)
end
if options[:foreign_keys]
options[:foreign_keys].each do |fk|
@definition.foreign_key(fk.to_table, fk.options)
end
end
yield @definition if block_given?
end
copy_table_indexes(from, to, options[:rename] || {})

View file

@ -81,6 +81,22 @@ if ActiveRecord::Base.connection.supports_foreign_keys_in_create?
assert_equal "astronauts", fk.from_table
assert_equal "rockets", fk.to_table
end
def test_rename_reference_column_of_child_table
rocket = Rocket.create!(name: "myrocket")
rocket.astronauts << Astronaut.create!
@connection.rename_column :astronauts, :rocket_id, :new_rocket_id
foreign_keys = @connection.foreign_keys("astronauts")
assert_equal 1, foreign_keys.size
fk = foreign_keys.first
assert_equal "myrocket", Rocket.first.name
assert_equal "astronauts", fk.from_table
assert_equal "rockets", fk.to_table
assert_equal "new_rocket_id", fk.options[:column]
end
end
end
end