From 0686c2869262d01d5d22d137c6aca8aa50289285 Mon Sep 17 00:00:00 2001 From: Raphael Sofaer Date: Thu, 17 Mar 2011 16:54:25 -0700 Subject: [PATCH] Make post guids unique --- db/migrate/20110317222802_guid_is_unique.rb | 36 +++++++++++++++++++++ db/schema.rb | 4 +-- 2 files changed, 38 insertions(+), 2 deletions(-) create mode 100644 db/migrate/20110317222802_guid_is_unique.rb diff --git a/db/migrate/20110317222802_guid_is_unique.rb b/db/migrate/20110317222802_guid_is_unique.rb new file mode 100644 index 000000000..a829b5fd5 --- /dev/null +++ b/db/migrate/20110317222802_guid_is_unique.rb @@ -0,0 +1,36 @@ +class GuidIsUnique < ActiveRecord::Migration + def self.consolidate_post(guid) + post_ids = execute("select posts.id from posts where posts.guid = #{guid}").to_a.flatten! + keep_id = post_ids.pop + execute("UPDATE comments + SET comments.post_id = #{keep_id} + WHERE comments.post_id IN (#{post_ids.join(',')})") + + execute("UPDATE posts + SET posts.status_message_id = #{keep_id} + WHERE posts.status_message_id IN (#{post_ids.join(',')})") + + execute("DELETE post_visibilities WHERE post_visibilities.post_id IN (#{post_ids.join(',')})") + execute("DELETE mentions WHERE mentions.post_id IN (#{post_ids.join(',')})") + execute("DELETE posts WHERE posts.id IN (#{post_ids.join(',')})") + end + def self.up + sql = <<-SQL + SELECT posts.guid FROM posts + GROUP BY posts.guid + HAVING COUNT(*)>1; + SQL + duplicated_guids = execute(sql).to_a.flatten! + + duplicated_guids.each do |guid| + consolidate_post(guid) + end if duplicated_guids + remove_index :posts, :guid + add_index :posts, :guid, :unique => true + end + + def self.down + remove_index :posts, :column => :guid + add_index :posts, :guid + end +end diff --git a/db/schema.rb b/db/schema.rb index 775bb8c47..b64ec39d0 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended to check this file into your version control system. -ActiveRecord::Schema.define(:version => 20110314043119) do +ActiveRecord::Schema.define(:version => 20110317222802) do create_table "aspect_memberships", :force => true do |t| t.integer "aspect_id", :null => false @@ -213,7 +213,7 @@ ActiveRecord::Schema.define(:version => 20110314043119) do end add_index "posts", ["author_id"], :name => "index_posts_on_person_id" - add_index "posts", ["guid"], :name => "index_posts_on_guid" + add_index "posts", ["guid"], :name => "index_posts_on_guid", :unique => true add_index "posts", ["mongo_id"], :name => "index_posts_on_mongo_id" add_index "posts", ["status_message_id", "pending"], :name => "index_posts_on_status_message_id_and_pending" add_index "posts", ["status_message_id"], :name => "index_posts_on_status_message_id"