20230531153942_add_primary_key_to_accounts_tags_join_table.rb 901 B

123456789101112131415161718192021222324
  1. # frozen_string_literal: true
  2. class AddPrimaryKeyToAccountsTagsJoinTable < ActiveRecord::Migration[6.1]
  3. disable_ddl_transaction!
  4. def up
  5. ActiveRecord::Base.transaction do
  6. safety_assured do
  7. execute 'ALTER TABLE accounts_tags ADD PRIMARY KEY USING INDEX index_accounts_tags_on_tag_id_and_account_id'
  8. # Rename for consistency as the primary key's name is not represented in db/schema.rb
  9. execute 'ALTER INDEX index_accounts_tags_on_tag_id_and_account_id RENAME TO accounts_tags_pkey'
  10. end
  11. end
  12. end
  13. def down
  14. safety_assured do
  15. # I have found no way to demote the primary key to an index, instead, re-create the index
  16. execute 'CREATE UNIQUE INDEX CONCURRENTLY index_accounts_tags_on_tag_id_and_account_id ON accounts_tags (tag_id, account_id)'
  17. execute 'ALTER TABLE accounts_tags DROP CONSTRAINT accounts_tags_pkey'
  18. end
  19. end
  20. end