Skip to content

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

PERF: Fix N+1 queries due to user custom fields when loading chat DMs (#35516)

Alan Guo Xiang Tanc9e771157a70
diff --git a/plugins/chat/lib/chat/channel_fetcher.rb b/plugins/chat/lib/chat/channel_fetcher.rb
index f7b5c263767..e452845c8de 100644
--- a/plugins/chat/lib/chat/channel_fetcher.rb
+++ b/plugins/chat/lib/chat/channel_fetcher.rb
@@ -246,7 +246,10 @@ module Chat
User.allowed_user_custom_fields(guardian) +
UserField.all.pluck(:id).map { |fid| "#{User::USER_FIELD_PREFIX}#{fid}" }
- User.preload_custom_fields(channels.flat_map { _1.chatable.users }, preload_fields)
+ User.preload_custom_fields(
+ channels.flat_map { _1.chatable.direct_message_users.map(&:user).compact },
+ preload_fields,
+ )
channels
end
diff --git a/plugins/chat/spec/requests/chat/api/current_user_channels_spec.rb b/plugins/chat/spec/requests/chat/api/current_user_channels_spec.rb
index 56ac38f7344..5473f1410dd 100644
--- a/plugins/chat/spec/requests/chat/api/current_user_channels_spec.rb
+++ b/plugins/chat/spec/requests/chat/api/current_user_channels_spec.rb
@@ -42,6 +42,44 @@ describe Chat::Api::CurrentUserChannelsController do
expect(response.parsed_body["public_channels"][0]["id"]).to eq(channel.id)
end
+ context "with multiple direct messages" do
+ fab!(:user_1, :user)
+ fab!(:user_2, :user)
+ fab!(:dm_channel_1, :direct_message)
+
+ fab!(:direct_message_channel_1) do
+ Fabricate(:direct_message_channel, chatable: dm_channel_1)
+ end
+
+ it "avoids N+1 queries with user custom fields" do
+ custom_field_name = "#{Time.now.to_i}_custom_field"
+ SiteSetting.public_user_custom_fields = custom_field_name
+
+ Fabricate(
+ :user_chat_channel_membership_for_dm,
+ chat_channel: direct_message_channel_1,
+ user: user_1,
+ following: true,
+ )
+
+ Chat::DirectMessageUser.create!(direct_message: dm_channel_1, user: user_1)
+ Chat::DirectMessageUser.create!(direct_message: dm_channel_1, user: user_2)
+
+ sign_in(user_1)
+
+ queries =
+ track_sql_queries do
+ get "/chat/api/me/channels"
+
+ expect(response.status).to eq(200)
+ end
+
+ expect(
+ queries.count { |q| q.include?("user_custom_fields") && q.include?(custom_field_name) },
+ ).to eq(1)
+ end
+ end
+
context "with multiple channels and category group moderation" do
fab!(:group)
fab!(:channel_1, :category_channel)