Commit 7b812c7f authored by Catalin Irimie's avatar Catalin Irimie

Fix N+1 when looking up user's solo owned groups

Before this change, the solo_owned_groups lookup would generate
additional queries for each group owned by the user, and is used in
can_be_removed? user checks and profile view pages
parent 62f75747
...@@ -1245,7 +1245,7 @@ class User < ApplicationRecord ...@@ -1245,7 +1245,7 @@ class User < ApplicationRecord
end end
def solo_owned_groups def solo_owned_groups
@solo_owned_groups ||= owned_groups.select do |group| @solo_owned_groups ||= owned_groups.includes(:owners).select do |group|
group.owners == [self] group.owners == [self]
end end
end end
......
---
title: Fix N+1 when looking up user's solo owned groups
merge_request: 48340
author:
type: performance
...@@ -2965,6 +2965,49 @@ RSpec.describe User do ...@@ -2965,6 +2965,49 @@ RSpec.describe User do
end end
end end
describe '#solo_owned_groups' do
subject { create(:user) }
context 'no owned groups' do
it { expect(subject.solo_owned_groups).to be_empty }
end
context 'has owned groups' do
let_it_be(:group) { create(:group) }
before do
group.add_owner(subject)
end
context 'not solo owner' do
let_it_be(:user2) { create(:user) }
before do
group.add_owner(user2)
end
it { expect(subject.solo_owned_groups).to be_empty }
end
context 'solo owner' do
it { expect(subject.solo_owned_groups).to include(group) }
it 'avoids N+1 queries' do
instance1 = User.find(subject.id)
instance2 = User.find(subject.id)
control_count = ActiveRecord::QueryRecorder.new do
instance1.solo_owned_groups
end.count
create(:group).add_owner(subject)
expect { instance2.solo_owned_groups }.not_to exceed_query_limit(control_count)
end
end
end
end
describe "#recent_push" do describe "#recent_push" do
let(:user) { build(:user) } let(:user) { build(:user) }
let(:project) { build(:project) } let(:project) { build(:project) }
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment