about summary refs log tree commit diff
path: root/db/migrate/20221021055441_add_index_featured_tags_on_account_id_and_tag_id.rb
blob: 74d7673f7d9979ef4e285c77551e020b22d0e785 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class AddIndexFeaturedTagsOnAccountIdAndTagId < ActiveRecord::Migration[6.1]
  disable_ddl_transaction!

  def up
    duplicates = FeaturedTag.connection.select_all('SELECT string_agg(id::text, \',\') AS ids FROM featured_tags GROUP BY account_id, tag_id HAVING count(*) > 1').to_ary

    duplicates.each do |row|
      FeaturedTag.where(id: row['ids'].split(',')[0...-1]).destroy_all
    end

    add_index :featured_tags, [:account_id, :tag_id], unique: true, algorithm: :concurrently
    remove_index :featured_tags, [:account_id], algorithm: :concurrently
  end

  def down
    add_index :featured_tags, [:account_id], algorithm: :concurrently
    remove_index :featured_tags, [:account_id, :tag_id], unique: true, algorithm: :concurrently
  end
end