rename sequence only if it exists

This commit is contained in:
Abdelkader Boudih 2014-06-27 08:46:07 +00:00
parent 30b56084fb
commit b58ec66f0e
3 changed files with 17 additions and 3 deletions

View File

@ -1,3 +1,7 @@
* PostgreSQL renaming table doesn't attempt to rename non existent sequences
*Abdelkader Boudih*
* Move 'dependent: :destroy' handling for 'belongs_to' * Move 'dependent: :destroy' handling for 'belongs_to'
from 'before_destroy' to 'after_destroy' callback chain from 'before_destroy' to 'after_destroy' callback chain

View File

@ -375,8 +375,8 @@ module ActiveRecord
end end
# Renames a table. # Renames a table.
# Also renames a table's primary key sequence if the sequence name matches the # Also renames a table's primary key sequence if the sequence name exists and
# Active Record default. # matches the Active Record default.
# #
# Example: # Example:
# rename_table('octopuses', 'octopi') # rename_table('octopuses', 'octopi')
@ -384,7 +384,7 @@ module ActiveRecord
clear_cache! clear_cache!
execute "ALTER TABLE #{quote_table_name(table_name)} RENAME TO #{quote_table_name(new_name)}" execute "ALTER TABLE #{quote_table_name(table_name)} RENAME TO #{quote_table_name(new_name)}"
pk, seq = pk_and_sequence_for(new_name) pk, seq = pk_and_sequence_for(new_name)
if seq.identifier == "#{table_name}_#{pk}_seq" if seq && seq.identifier == "#{table_name}_#{pk}_seq"
new_seq = "#{new_name}_#{pk}_seq" new_seq = "#{new_name}_#{pk}_seq"
execute "ALTER TABLE #{quote_table_name(seq)} RENAME TO #{quote_table_name(new_seq)}" execute "ALTER TABLE #{quote_table_name(seq)} RENAME TO #{quote_table_name(new_seq)}"
end end

View File

@ -76,6 +76,16 @@ module ActiveRecord
assert_equal ConnectionAdapters::PostgreSQL::Name.new("public", "octopi_#{pk}_seq"), seq assert_equal ConnectionAdapters::PostgreSQL::Name.new("public", "octopi_#{pk}_seq"), seq
end end
def test_renaming_table_doesnt_attempt_to_rename_non_existent_sequences
enable_uuid_ossp!(connection)
connection.create_table :cats, id: :uuid
assert_nothing_raised { rename_table :cats, :felines }
assert connection.table_exists? :felines
ensure
connection.drop_table :cats if connection.table_exists? :cats
connection.drop_table :felines if connection.table_exists? :felines
end
end end
end end
end end