Skip to content

A platform for community discussion. Free, open, simple.

PERF: Update all user_histories with one query in UserDestroyer (#16717)

David Taylor67b23c0e22ed
diff --git a/app/services/user_destroyer.rb b/app/services/user_destroyer.rb
index b191cbe3dcb..408dffcb9ef 100644
--- a/app/services/user_destroyer.rb
+++ b/app/services/user_destroyer.rb
@@ -47,13 +47,10 @@ class UserDestroyer
# Add info about the user to staff action logs
UserHistory.staff_action_records(
Discourse.system_user, acting_user: user.username
- ).unscope(:order).find_each do |log|
- log.details ||= ''
- log.details = (log.details.split("\n") +
- ["user_id: #{user.id}", "username: #{user.username}"]
- ).join("\n")
- log.save!
- end
+ ).update_all([
+ "details = CONCAT(details, ?)",
+ "\nuser_id: #{user.id}\nusername: #{user.username}"
+ ])
# keep track of emails used
user_emails = user.user_emails.pluck(:email)
diff --git a/spec/services/user_destroyer_spec.rb b/spec/services/user_destroyer_spec.rb
index dcd6d3c5b75..51d3254bc88 100644
--- a/spec/services/user_destroyer_spec.rb
+++ b/spec/services/user_destroyer_spec.rb
@@ -442,19 +442,28 @@ describe UserDestroyer do
logger.log_site_setting_change(
'site_description',
'Our friendly community',
- 'My favourite community'
+ 'My favourite community',
+ )
+ logger.log_site_setting_change(
+ 'site_description',
+ 'Our friendly community',
+ 'My favourite community',
+ details: "existing details"
)
end
it "should keep the staff action log and add the username" do
username = user.username
- log = UserHistory.staff_action_records(
+ ids = UserHistory.staff_action_records(
Discourse.system_user,
acting_user: username
- ).to_a[0]
+ ).map(&:id)
UserDestroyer.new(admin).destroy(user, delete_posts: true)
- log.reload
- expect(log.details).to include(username)
+ details = UserHistory.where(id: ids).map(&:details)
+ expect(details).to contain_exactly(
+ "\nuser_id: #{user.id}\nusername: #{username}",
+ "existing details\nuser_id: #{user.id}\nusername: #{username}"
+ )
end
end