From 814b7775fbb175bf6fb30e7f775b77c334658a8a Mon Sep 17 00:00:00 2001
From: ThibG <thib@sitedethib.com>
Date: Wed, 23 Dec 2020 01:35:02 +0100
Subject: [PATCH] Improve performances of deleting favourites when deleting
 accounts (#15412)

Co-authored-by: Claire <claire.github-309c@sitedethib.com>
---
 app/services/delete_account_service.rb | 22 ++++++++++++++++++++--
 1 file changed, 20 insertions(+), 2 deletions(-)

diff --git a/app/services/delete_account_service.rb b/app/services/delete_account_service.rb
index 58f6ef2ab1..2bb533cfb6 100644
--- a/app/services/delete_account_service.rb
+++ b/app/services/delete_account_service.rb
@@ -9,13 +9,11 @@ class DeleteAccountService < BaseService
     aliases
     block_relationships
     blocked_by_relationships
-    bookmarks
     conversation_mutes
     conversations
     custom_filters
     devices
     domain_blocks
-    favourites
     featured_tags
     follow_requests
     identity_proofs
@@ -147,6 +145,8 @@ class DeleteAccountService < BaseService
     purge_media_attachments!
     purge_polls!
     purge_generated_notifications!
+    purge_favourites!
+    purge_bookmarks!
     purge_feeds!
     purge_other_associations!
 
@@ -178,6 +178,24 @@ class DeleteAccountService < BaseService
     Notification.where(from_account: @account).in_batches.delete_all
   end
 
+  def purge_favourites!
+    @account.favourites.in_batches do |favourites|
+      ids = favourites.pluck(:status_id)
+      StatusStat.where(status_id: ids).update_all('favourites_count = GREATEST(0, favourites_count - 1)')
+      Chewy.strategy.current.update(StatusesIndex, ids) if Chewy.enabled?
+      # Rails.cache.delete_multi would be better, but we don't have it yet
+      ids.each { |id| Rails.cache.delete("statuses/#{id}") }
+      favourites.delete_all
+    end
+  end
+
+  def purge_bookmarks!
+    @account.bookmarks.in_batches do |bookmarks|
+      Chewy.strategy.current.update(StatusesIndex, bookmarks.pluck(:status_id)) if Chewy.enabled?
+      bookmarks.delete_all
+    end
+  end
+
   def purge_other_associations!
     associations_for_destruction.each do |association_name|
       purge_association(association_name)