Skip to content

Commit

Permalink
Rename the primary key index when renaming a table in pg
Browse files Browse the repository at this point in the history
Backport of dcc143c

Fixes #12856
Closes #14088
  • Loading branch information
sgrif committed Nov 22, 2014
1 parent 63b80b5 commit e39b1f3
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
6 changes: 6 additions & 0 deletions activerecord/CHANGELOG.md
@@ -1,3 +1,9 @@
* Renaming a table in pg also renames the primary key index.

Fixes #12856

*Sean Griffin*

* Make it possible to access fixtures excluded by a `default_scope`.

*Yves Senn*
Expand Down
Expand Up @@ -382,7 +382,10 @@ def rename_table(table_name, new_name)
pk, seq = pk_and_sequence_for(new_name)
if seq == "#{table_name}_#{pk}_seq"
new_seq = "#{new_name}_#{pk}_seq"
idx = "#{table_name}_pkey"
new_idx = "#{new_name}_pkey"
execute "ALTER TABLE #{quote_table_name(seq)} RENAME TO #{quote_table_name(new_seq)}"
execute "ALTER INDEX #{quote_table_name(idx)} RENAME TO #{quote_table_name(new_idx)}"
end

rename_table_indexes(table_name, new_name)
Expand Down
34 changes: 34 additions & 0 deletions activerecord/test/cases/adapters/postgresql/rename_table_test.rb
@@ -0,0 +1,34 @@
require "cases/helper"

class PostgresqlRenameTableTest < ActiveRecord::TestCase
def setup
@connection = ActiveRecord::Base.connection
@connection.create_table :before_rename, force: true
end

def teardown
@connection.execute 'DROP TABLE IF EXISTS "before_rename"'
@connection.execute 'DROP TABLE IF EXISTS "after_rename"'
end

test "renaming a table also renames the primary key index" do
# sanity check
assert_equal 1, num_indices_named("before_rename_pkey")
assert_equal 0, num_indices_named("after_rename_pkey")

@connection.rename_table :before_rename, :after_rename

assert_equal 0, num_indices_named("before_rename_pkey")
assert_equal 1, num_indices_named("after_rename_pkey")
end

private

def num_indices_named(name)
@connection.execute(<<-SQL).values.length
SELECT 1 FROM "pg_index"
JOIN "pg_class" ON "pg_index"."indexrelid" = "pg_class"."oid"
WHERE "pg_class"."relname" = '#{name}'
SQL
end
end

0 comments on commit e39b1f3

Please sign in to comment.