Skip to content

Instantly share code, notes, and snippets.

@zunda
Created July 28, 2019 22:38
Show Gist options
  • Save zunda/91f848982e2090911a949957fe3e3596 to your computer and use it in GitHub Desktop.
Save zunda/91f848982e2090911a949957fe3e3596 to your computer and use it in GitHub Desktop.
namespace :db do
desc 'Merge duplicate tags'
task remove_dup_tags: :environment do
ActiveRecord::Base.transaction do
con = ActiveRecord::Base.connection
dup_ids = con.select_rows(<<-'_SQL'
SELECT JSON_AGG(id ORDER BY id) AS ids
FROM tags
WHERE name IN (SELECT name FROM tags GROUP BY name HAVING COUNT(1) > 1)
GROUP BY name;
_SQL
).map{|x| JSON.parse(x.first)}
puts "IDs for duplicate tags:"
puts dup_ids.map{|x| "\t" + x.join(', ')}
%w(account_tag_stats featured_tags statuses_tags).each do |table|
puts "Merging tags on #{table}..."
dup_ids.each do |target_id, *src_ids|
src_ids.each do |src_id|
con.execute("UPDATE #{table} SET tag_id=#{target_id} WHERE tag_id=#{src_id};")
end
end
end
puts "Deleting tags that are no longer in use..."
dup_ids.each do |target_id, *src_ids|
src_ids.each do |src_id|
con.execute("DELETE FROM tags WHERE id=#{src_id};")
end
end
end
end
end
@zunda
Copy link
Author

zunda commented Jul 28, 2019

Merging tags on account_tag_stats...
rake aborted!
ActiveRecord::RecordNotUnique: PG::UniqueViolation: ERROR:  duplicate key value violates unique constraint "index_account_tag_stats_on_tag_id"
DETAIL:  Key (tag_id)=(27844) already exists.
: UPDATE account_tag_stats SET tag_id=27844 WHERE tag_id=36790;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment