Skip to content

Commit

Permalink
CV2-5348: Fix N+1 query (#2092)
Browse files Browse the repository at this point in the history
* CV2-5348: fix n+1 query

* CV2-5464: add unit test
  • Loading branch information
melsawy authored Oct 16, 2024
1 parent a897c88 commit 04e2897
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 7 deletions.
13 changes: 6 additions & 7 deletions app/models/bot/smooch.rb
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,12 @@ def report_image
def get_deduplicated_tipline_requests
uids = []
tipline_requests = []
ProjectMedia.where(id: self.related_items_ids).each do |pm|
pm.tipline_requests.find_each do |tr|
uid = tr.tipline_user_uid
next if uids.include?(uid)
uids << uid
tipline_requests << tr
end
pm_ids = ProjectMedia.where(id: self.related_items_ids).map(&:id)
TiplineRequest.where(associated_type: 'ProjectMedia', associated_id: pm_ids).find_each do |tr|
uid = tr.tipline_user_uid
next if uids.include?(uid)
uids << uid
tipline_requests << tr
end
tipline_requests
end
Expand Down
22 changes: 22 additions & 0 deletions test/models/project_media_8_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,26 @@ def teardown

assert_equal 1, pm.annotations('tag').count
end

test "should verify n + 1 for deduplicated TiplineRequest(CV2-5464)" do
t = create_team
pm = create_project_media team: t
pm2 = create_project_media team: t
pm3 = create_project_media team: t
create_relationship source_id: pm.id, target_id: pm2.id, relationship_type: Relationship.confirmed_type
[pm, pm2, pm3].each do |ass|
create_tipline_request team_id: t.id, associated: ass
end
assert_queries(4, '=') {
pm.get_deduplicated_tipline_requests
}
# Should add a new item for related_items_ids and got same queries count
create_relationship source_id: pm.id, target_id: pm3.id, relationship_type: Relationship.confirmed_type
[pm, pm2, pm3].each do |ass|
create_tipline_request team_id: t.id, associated: ass
end
assert_queries(4, '=') {
pm.get_deduplicated_tipline_requests
}
end
end

0 comments on commit 04e2897

Please sign in to comment.