-
Notifications
You must be signed in to change notification settings - Fork 11
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Ticket CV2-5653 [WIP]: Adding migration and rake task to delete dupli…
…cate relationships
- Loading branch information
Showing
3 changed files
with
41 additions
and
6 deletions.
There are no files selected for viewing
33 changes: 33 additions & 0 deletions
33
db/migrate/20241123001206_add_unique_index_to_relationships_table.rb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
class AddUniqueIndexToRelationshipsTable < ActiveRecord::Migration[6.1] | ||
def change | ||
# The code below is a copy-paste from the rake task lib/tasks/migrate/20230216030351_delete_duplicate_relationships.rake | ||
# and it's responsible for deleting any remaining duplicate relationship, but first, before running this migration, be | ||
# sure to run the rake task above, with: rake check:migrate:delete_duplicate_relationships | ||
duplicates = Relationship.group(:target_id).having('COUNT(id) > 1').count | ||
n = duplicates.size | ||
i = 0 | ||
duplicates.each do |pm_id, count| | ||
i += 1 | ||
puts "[#{Time.now}] #{i}/#{n}" | ||
if count > 1 | ||
relationships = Relationship.where(target_id: pm_id).order('id ASC').to_a | ||
# Keep the confirmed relationship, or the one whose model is image, video or audio... if none, keep the first one | ||
keep = relationships.find{ |r| r.relationship_type == Relationship.confirmed_type } || relationships.find{ |r| ['image', 'video', 'audio'].include?(r.model) } || relationships.first | ||
raise "No relationship to keep for target_id #{pm_id}!" if keep.nil? | ||
relationships.each do |relationship| | ||
if relationship.id == keep.id | ||
puts " Keeping relationship ##{r.id}" | ||
else | ||
puts " Deleting relationship ##{r.id}" | ||
relationship.destroy! | ||
end | ||
relationship.source.clear_cached_fields | ||
relationship.target.clear_cached_fields | ||
end | ||
end | ||
end | ||
|
||
remove_index :relationships, name: 'index_relationships_on_target_id' | ||
add_index :relationships, :target_id, unique: true | ||
end | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters