From 563926895fc695203920e05b07d9507b3faf9189 Mon Sep 17 00:00:00 2001 From: Karina Kwiatek Date: Wed, 20 Dec 2023 10:28:49 +0000 Subject: [PATCH] Remove duplicate reactions --- ...231220100445_remove_duplicate_reactions.rb | 20 +++++++++++++++++++ db/schema.rb | 3 ++- 2 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 db/migrate/20231220100445_remove_duplicate_reactions.rb diff --git a/db/migrate/20231220100445_remove_duplicate_reactions.rb b/db/migrate/20231220100445_remove_duplicate_reactions.rb new file mode 100644 index 00000000..d949e40c --- /dev/null +++ b/db/migrate/20231220100445_remove_duplicate_reactions.rb @@ -0,0 +1,20 @@ +# frozen_string_literal: true + +class RemoveDuplicateReactions < ActiveRecord::Migration[7.0] + def up + execute <<~SQUIRREL + DELETE FROM reactions + WHERE id IN ( + SELECT id FROM ( + SELECT id, row_number() over (PARTITION BY parent_type, parent_id, user_id ORDER BY id) AS row_number FROM reactions + )s WHERE row_number >= 2 + ) + SQUIRREL + + add_index :reactions, %i[parent_type parent_id user_id], unique: true + end + + def down + remove_index :reactions, %i[parent_type parent_id user_id] + end +end diff --git a/db/schema.rb b/db/schema.rb index 0bc10764..e4990d1f 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema[7.0].define(version: 2023_12_09_212629) do +ActiveRecord::Schema[7.0].define(version: 2023_12_20_100445) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" @@ -149,6 +149,7 @@ ActiveRecord::Schema[7.0].define(version: 2023_12_09_212629) do t.datetime "created_at", null: false t.datetime "updated_at", null: false t.index ["parent_id", "parent_type"], name: "index_reactions_on_parent_id_and_parent_type" + t.index ["parent_type", "parent_id", "user_id"], name: "index_reactions_on_parent_type_and_parent_id_and_user_id", unique: true t.index ["user_id", "created_at"], name: "index_reactions_on_user_id_and_created_at" end