Skip to content

Commit

Permalink
Fix renaming primary key index when renaming a PostgreSQL table havin…
Browse files Browse the repository at this point in the history
…g uuid primary key
  • Loading branch information
fatkodima committed Nov 10, 2023
1 parent fd20970 commit 7fba608
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
Expand Up @@ -341,7 +341,7 @@ def pk_and_sequence_for(table) # :nodoc:
JOIN pg_namespace nsp ON (t.relnamespace = nsp.oid)
WHERE t.oid = #{quote(quote_table_name(table))}::regclass
AND cons.contype = 'p'
AND pg_get_expr(def.adbin, def.adrelid) ~* 'nextval|uuid_generate'
AND pg_get_expr(def.adbin, def.adrelid) ~* 'nextval|uuid_generate|gen_random_uuid'
SQL
end

Expand Down
31 changes: 26 additions & 5 deletions activerecord/test/cases/adapters/postgresql/rename_table_test.rb
Expand Up @@ -5,7 +5,6 @@
class PostgresqlRenameTableTest < ActiveRecord::PostgreSQLTestCase
def setup
@connection = ActiveRecord::Base.connection
@connection.create_table :before_rename, force: true
end

def teardown
Expand All @@ -14,14 +13,36 @@ def teardown
end

test "renaming a table also renames the primary key index" do
assert_changes(-> { num_indices_named("before_rename_pkey") }, from: 1, to: 0) do
assert_changes(-> { num_indices_named("after_rename_pkey") }, from: 0, to: 1) do
@connection.rename_table :before_rename, :after_rename
end
@connection.create_table :before_rename, force: true

assert_renames_index("before_rename_pkey", "after_rename_pkey") do
@connection.rename_table :before_rename, :after_rename
end
end

test "renaming a table with uuid primary key and uuid_generate_v4() default also renames the primary key index" do
@connection.create_table :before_rename, force: true, id: :uuid, default: -> { "uuid_generate_v4()" }

assert_renames_index("before_rename_pkey", "after_rename_pkey") do
@connection.rename_table :before_rename, :after_rename
end
end

test "renaming a table with uuid primary key and gen_random_uuid() default also renames the primary key index" do
@connection.create_table :before_rename, force: true, id: :uuid, default: -> { "gen_random_uuid()" }

assert_renames_index("before_rename_pkey", "after_rename_pkey") do
@connection.rename_table :before_rename, :after_rename
end
end

private
def assert_renames_index(from, to, &block)
assert_changes(-> { num_indices_named(from) }, from: 1, to: 0) do
assert_changes(-> { num_indices_named(to) }, from: 0, to: 1, &block)
end
end

def num_indices_named(name)
@connection.execute(<<~SQL).values.length
SELECT 1 FROM "pg_index"
Expand Down

0 comments on commit 7fba608

Please sign in to comment.