FIX: n+1 in search result (#438)

When assignment data is preloaded, cache variable should be set when topic is assigned but also when topic is not assigned to avoid additional queries.
This commit is contained in:
Krzysztof Kotlarek 2023-02-01 16:28:21 +11:00 committed by GitHub
parent a9b44a973c
commit a907a98d87
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 20 additions and 4 deletions

View File

@ -306,10 +306,9 @@ after_initialize do
topic_assignments&.find { |assignment| assignment.target_type == "Topic" } topic_assignments&.find { |assignment| assignment.target_type == "Topic" }
indirect_assignments = indirect_assignments =
topic_assignments&.select { |assignment| assignment.target_type == "Post" } topic_assignments&.select { |assignment| assignment.target_type == "Post" }
if direct_assignment
assigned_to = direct_assignment.assigned_to post.topic.preload_assigned_to(direct_assignment&.assigned_to)
post.topic.preload_assigned_to(assigned_to) post.topic.preload_indirectly_assigned_to(nil)
end
if indirect_assignments.present? if indirect_assignments.present?
indirect_assignment_map = indirect_assignment_map =
indirect_assignments.reduce({}) do |acc, assignment| indirect_assignments.reduce({}) do |acc, assignment|

View File

@ -37,4 +37,21 @@ describe SearchController do
expect(assigned_to_group_data["assign_icon"]).to eq("group-plus") expect(assigned_to_group_data["assign_icon"]).to eq("group-plus")
expect(assigned_to_group_data["assign_path"]).to eq("/g/#{group.name}/assigned/everyone") expect(assigned_to_group_data["assign_path"]).to eq("/g/#{group.name}/assigned/everyone")
end end
it "does not result in N+1 queries when search returns multiple results" do
SearchIndexer.enable
SiteSetting.assigns_public = true
post = Fabricate(:post, topic: Fabricate(:topic, title: "this is an awesome title"))
get "/search/query.json", params: { term: "awesome" }
initial_sql_queries_count =
track_sql_queries { get "/search/query.json", params: { term: "awesome" } }.count
Fabricate(:post, topic: Fabricate(:topic, title: "this is an awesome title 2"))
Fabricate(:post, topic: Fabricate(:topic, title: "this is an awesome title 3"))
new_sql_queries_count =
track_sql_queries { get "/search/query.json", params: { term: "awesome" } }.count
expect(new_sql_queries_count).to eq(initial_sql_queries_count)
end
end end