You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

34 lines
1.8 KiB

  1. class AddCaseInsensitiveIndexToTags < ActiveRecord::Migration[5.2]
  2. disable_ddl_transaction!
  3. def up
  4. Tag.connection.select_all('SELECT string_agg(id::text, \',\') AS ids FROM tags GROUP BY lower(name) HAVING count(*) > 1').to_ary.each do |row|
  5. canonical_tag_id = row['ids'].split(',').first
  6. redundant_tag_ids = row['ids'].split(',')[1..-1]
  7. safety_assured do
  8. execute "UPDATE accounts_tags AS t0 SET tag_id = #{canonical_tag_id} WHERE tag_id IN (#{redundant_tag_ids.join(', ')}) AND NOT EXISTS (SELECT t1.tag_id FROM accounts_tags AS t1 WHERE t1.tag_id = #{canonical_tag_id} AND t1.account_id = t0.account_id)"
  9. execute "UPDATE statuses_tags AS t0 SET tag_id = #{canonical_tag_id} WHERE tag_id IN (#{redundant_tag_ids.join(', ')}) AND NOT EXISTS (SELECT t1.tag_id FROM statuses_tags AS t1 WHERE t1.tag_id = #{canonical_tag_id} AND t1.status_id = t0.status_id)"
  10. execute "UPDATE featured_tags AS t0 SET tag_id = #{canonical_tag_id} WHERE tag_id IN (#{redundant_tag_ids.join(', ')}) AND NOT EXISTS (SELECT t1.tag_id FROM featured_tags AS t1 WHERE t1.tag_id = #{canonical_tag_id} AND t1.account_id = t0.account_id)"
  11. end
  12. Tag.where(id: redundant_tag_ids).in_batches.delete_all
  13. end
  14. begin
  15. safety_assured { execute 'CREATE UNIQUE INDEX CONCURRENTLY index_tags_on_name_lower ON tags (lower(name))' }
  16. rescue ActiveRecord::StatementInvalid
  17. remove_index :tags, name: 'index_tags_on_name_lower'
  18. raise
  19. end
  20. remove_index :tags, name: 'index_tags_on_name'
  21. remove_index :tags, name: 'hashtag_search_index'
  22. end
  23. def down
  24. add_index :tags, :name, unique: true, algorithm: :concurrently
  25. safety_assured { execute 'CREATE INDEX CONCURRENTLY hashtag_search_index ON tags (name text_pattern_ops)' }
  26. remove_index :tags, name: 'index_tags_on_name_lower'
  27. end
  28. end