Skip to content

Commit

Permalink
Merge pull request #210 from puzzle/fix/fix_join_tables
Browse files Browse the repository at this point in the history
Add id primary key to order_team_members table
  • Loading branch information
Kagemaru authored Mar 12, 2024
2 parents 31072a9 + fa66e53 commit 6e90e50
Show file tree
Hide file tree
Showing 2 changed files with 120 additions and 75 deletions.
38 changes: 38 additions & 0 deletions db/migrate/20240311175613_add_id_to_order_team_members.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
class AddIdToOrderTeamMembers < ActiveRecord::Migration[7.1]

def change
remove_index :order_team_members, column: :employee_id
remove_index :order_team_members, column: :order_id

reversible do |dir|
dir.up { deduplicate_entries }
end

add_column :order_team_members, :id, :primary_key
add_index :order_team_members, [:employee_id, :order_id], unique: true
end

private

def deduplicate_entries
execute <<~SQL
DELETE FROM "order_team_members"
WHERE "ctid" IN (
SELECT "ctid"
FROM (
SELECT
"ctid",
"employee_id",
"order_id",
row_number() OVER (
PARTITION BY "employee_id", "order_id"
ORDER BY "employee_id", "order_id"
) AS "rnum"
FROM "order_team_members"
) "t"
WHERE "t"."rnum" > 1
);
SQL
end

end
Loading

0 comments on commit 6e90e50

Please sign in to comment.