From c5aa6b5e16c17153ed0de8f0e96b9458fe7c95f2 Mon Sep 17 00:00:00 2001 From: Joffrey JAFFEUX Date: Tue, 5 Dec 2023 13:46:58 +0100 Subject: [PATCH] FIX: correctly update replies_count on chat_threads (#24711) The previous query would look at the existing messages, count them, and update the associated thread. But, if for some reason messages were **ALL** deleted without updating the `replies_count`, then the query wouldn't find any message, and wouldn't update any thread's `replies_count`. --- plugins/chat/app/models/chat/thread.rb | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/plugins/chat/app/models/chat/thread.rb b/plugins/chat/app/models/chat/thread.rb index 7531dfbd658..4caab5a7884 100644 --- a/plugins/chat/app/models/chat/thread.rb +++ b/plugins/chat/app/models/chat/thread.rb @@ -126,17 +126,16 @@ module Chat # It is updated eventually via Jobs::Chat::PeriodicalUpdates. In # future we may want to update this more frequently. updated_thread_ids = DB.query_single <<~SQL - UPDATE chat_threads threads - SET replies_count = subquery.replies_count + UPDATE chat_threads ct + SET replies_count = GREATEST(COALESCE(subquery.new_count, 0), 0) FROM ( - SELECT COUNT(*) - 1 AS replies_count, thread_id - FROM chat_messages - WHERE chat_messages.deleted_at IS NULL AND thread_id IS NOT NULL - GROUP BY thread_id - ) subquery - WHERE threads.id = subquery.thread_id - AND subquery.replies_count != threads.replies_count - RETURNING threads.id AS thread_id; + SELECT cm.thread_id, COUNT(cm.*) - 1 AS new_count + FROM chat_threads + LEFT JOIN chat_messages cm ON cm.thread_id = chat_threads.id AND cm.deleted_at IS NULL + GROUP BY cm.thread_id + ) AS subquery + WHERE ct.id = subquery.thread_id AND ct.replies_count IS DISTINCT FROM GREATEST(COALESCE(subquery.new_count, 0), 0) + RETURNING ct.id AS thread_id SQL return if updated_thread_ids.empty? self.clear_caches!(updated_thread_ids)