Commit 36302fb6 authored by Dmitriy Zaporozhets (DZ)'s avatar Dmitriy Zaporozhets (DZ)

Merge branch 'reduce-query-in-root-ancestor' into 'master'

Reduce DB queries when loading root_ancestor

See merge request gitlab-org/gitlab!69533
parents 07485bfe d2680a35
...@@ -74,7 +74,7 @@ module Namespaces ...@@ -74,7 +74,7 @@ module Namespaces
return super unless use_traversal_ids_for_root_ancestor? return super unless use_traversal_ids_for_root_ancestor?
strong_memoize(:root_ancestor) do strong_memoize(:root_ancestor) do
if parent.nil? if parent_id.nil?
self self
else else
Namespace.find_by(id: traversal_ids.first) Namespace.find_by(id: traversal_ids.first)
......
...@@ -7,12 +7,12 @@ module Namespaces ...@@ -7,12 +7,12 @@ module Namespaces
include RecursiveScopes include RecursiveScopes
def root_ancestor def root_ancestor
return self if parent.nil? if persisted? && !parent_id.nil?
if persisted?
strong_memoize(:root_ancestor) do strong_memoize(:root_ancestor) do
recursive_self_and_ancestors.reorder(nil).find_by(parent_id: nil) recursive_ancestors.reorder(nil).find_by(parent_id: nil)
end end
elsif parent.nil?
self
else else
parent.root_ancestor parent.root_ancestor
end end
......
...@@ -1377,6 +1377,13 @@ RSpec.describe Namespace do ...@@ -1377,6 +1377,13 @@ RSpec.describe Namespace do
expect { root_group.root_ancestor }.not_to exceed_query_limit(0) expect { root_group.root_ancestor }.not_to exceed_query_limit(0)
end end
it 'returns root_ancestor for nested group with a single query' do
nested_group = create(:group, parent: root_group)
nested_group.reload
expect { nested_group.root_ancestor }.not_to exceed_query_limit(1)
end
it 'returns the top most ancestor' do it 'returns the top most ancestor' do
nested_group = create(:group, parent: root_group) nested_group = create(:group, parent: root_group)
deep_nested_group = create(:group, parent: nested_group) deep_nested_group = create(:group, parent: nested_group)
......
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