From a32fce9e1da695980a56c49793673bf147b95048 Mon Sep 17 00:00:00 2001 From: Andrei Prigorshnev Date: Wed, 1 Nov 2023 17:05:54 +0400 Subject: [PATCH] FIX: Further optimize mentioning groups in chat messages (part 2) (#24185) This is a follow-up to e6299a3. I additionally fixed these three things: 1. Since e6299a3 there's no need anymore to join the group_users table when looking for users who were reached by a group mention, so I removed that join in that commit. But turned out we were joining the group_users table twice, so I removed the second join in this PR. That drastically speeded up my test query, from 6 sec to 0.26 sec. 2. We also were joining twice the user_chat_channel_memebership table, so I removed the second unnecessary join too. 3. We actually need to join the user_chat_channel_memebership table only in certain cases, and we don't need to do that for group mentions, so I fixed that too. As a result of these changes, time of my test query fall down from 6 sec to 0.001 sec. And the resulting SQL query now contains only one JOIN statement. --- plugins/chat/lib/chat/parsed_mentions.rb | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/plugins/chat/lib/chat/parsed_mentions.rb b/plugins/chat/lib/chat/parsed_mentions.rb index a246ef8f26f..cb66917071c 100644 --- a/plugins/chat/lib/chat/parsed_mentions.rb +++ b/plugins/chat/lib/chat/parsed_mentions.rb @@ -89,7 +89,7 @@ module Chat private def channel_members - chat_users.where( + chat_users.includes(:user_chat_channel_memberships).where( user_chat_channel_memberships: { following: true, chat_channel_id: @message.chat_channel.id, @@ -98,13 +98,7 @@ module Chat end def chat_users - User - .includes(:user_chat_channel_memberships, :group_users) - .distinct - .joins("LEFT OUTER JOIN user_chat_channel_memberships uccm ON uccm.user_id = users.id") - .joins(:user_option) - .real - .where(user_options: { chat_enabled: true }) + User.distinct.joins(:user_option).real.where(user_options: { chat_enabled: true }) end def mentionable_groups