Commit d2680a35 authored by Heinrich Lee Yu's avatar Heinrich Lee Yu

Reduce DB queries when loading root_ancestor

In the most common case where the record is persisted, we do not need to
load `parent`

Changelog: performance
parent a998bacb
......@@ -74,7 +74,7 @@ module Namespaces
return super unless use_traversal_ids_for_root_ancestor?
strong_memoize(:root_ancestor) do
if parent.nil?
if parent_id.nil?
self
else
Namespace.find_by(id: traversal_ids.first)
......
......@@ -7,12 +7,12 @@ module Namespaces
include RecursiveScopes
def root_ancestor
return self if parent.nil?
if persisted?
if persisted? && !parent_id.nil?
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
elsif parent.nil?
self
else
parent.root_ancestor
end
......
......@@ -1377,6 +1377,13 @@ RSpec.describe Namespace do
expect { root_group.root_ancestor }.not_to exceed_query_limit(0)
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
nested_group = create(:group, parent: root_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