Permalink
Browse files

Merge pull request #29248 from yawboakye/rename-should-rename-table-pkey

`rename_table` should rename primary key index name
  • Loading branch information...
guilleiguaran committed May 29, 2017
2 parents 1c275d8 + de387ea commit e7a33a5ed74cc0987544396f0742110fa5a5e228
@@ -377,14 +377,15 @@ def rename_table(table_name, new_name)
clear_cache!
execute "ALTER TABLE #{quote_table_name(table_name)} RENAME TO #{quote_table_name(new_name)}"
pk, seq = pk_and_sequence_for(new_name)
if seq && seq.identifier == "#{table_name}_#{pk}_seq"
new_seq = "#{new_name}_#{pk}_seq"
if pk
idx = "#{table_name}_pkey"
new_idx = "#{new_name}_pkey"
execute "ALTER TABLE #{seq.quoted} RENAME TO #{quote_table_name(new_seq)}"
execute "ALTER INDEX #{quote_table_name(idx)} RENAME TO #{quote_table_name(new_idx)}"
if seq && seq.identifier == "#{table_name}_#{pk}_seq"
new_seq = "#{new_name}_#{pk}_seq"
execute "ALTER TABLE #{seq.quoted} RENAME TO #{quote_table_name(new_seq)}"
end
end
rename_table_indexes(table_name, new_name)
end
@@ -79,10 +79,33 @@ def test_rename_table_for_postgresql_should_also_rename_default_sequence
assert_equal ConnectionAdapters::PostgreSQL::Name.new("public", "octopi_#{pk}_seq"), seq
end
def test_renaming_table_renames_primary_key
connection.create_table :cats, id: :uuid, default: "uuid_generate_v4()"
rename_table :cats, :felines
assert connection.table_exists? :felines
refute connection.table_exists? :cats
primary_key_name = connection.select_values(<<-SQL.strip_heredoc, "SCHEMA")[0]
SELECT c.relname
FROM pg_class c
JOIN pg_index i
ON c.oid = i.indexrelid
WHERE i.indisprimary
AND i.indrelid = 'felines'::regclass
SQL
assert_equal "felines_pkey", primary_key_name
ensure
connection.drop_table :cats, if_exists: true
connection.drop_table :felines, if_exists: true
end
def test_renaming_table_doesnt_attempt_to_rename_non_existent_sequences
connection.create_table :cats, id: :uuid, default: "uuid_generate_v4()"
assert_nothing_raised { rename_table :cats, :felines }
assert connection.table_exists? :felines
refute connection.table_exists? :cats
ensure
connection.drop_table :cats, if_exists: true
connection.drop_table :felines, if_exists: true

0 comments on commit e7a33a5

Please sign in to comment.