diff options
author | Thong Kuah <tkuah@gitlab.com> | 2018-12-04 00:38:20 +1300 |
---|---|---|
committer | Thong Kuah <tkuah@gitlab.com> | 2018-12-04 00:38:20 +1300 |
commit | b9bccad61e346eed5f1d98cbac87e8cbe0be6150 (patch) | |
tree | a4c651722ed4375be247287314364696faf12f8d | |
parent | 6fac5cc7862b33d495259445019852f0ddffff49 (diff) | |
download | gitlab-ce-34758-deployment-cluster.tar.gz |
Eager load clusters to prevent N+134758-deployment-cluster
This also means we need to apply the `current_scope` otherwise this
method will return all clusters associated with the groups regardless of
any scopes applied to this method
-rw-r--r-- | app/models/clusters/cluster.rb | 3 | ||||
-rw-r--r-- | spec/models/clusters/cluster_spec.rb | 16 |
2 files changed, 18 insertions, 1 deletions
diff --git a/app/models/clusters/cluster.rb b/app/models/clusters/cluster.rb index a7943f8cf04..448f6ee6388 100644 --- a/app/models/clusters/cluster.rb +++ b/app/models/clusters/cluster.rb @@ -94,7 +94,8 @@ module Clusters end def self.ancestor_clusters_for_clusterable(clusterable, hierarchy_order: :asc) - hierarchy_groups = clusterable.ancestors_upto(hierarchy_order: hierarchy_order) + hierarchy_groups = clusterable.ancestors_upto(hierarchy_order: hierarchy_order).eager_load(:clusters) + hierarchy_groups = hierarchy_groups.merge(current_scope) if current_scope hierarchy_groups.flat_map do |group| group.clusters diff --git a/spec/models/clusters/cluster_spec.rb b/spec/models/clusters/cluster_spec.rb index d3a9a410ec7..3ce83cd2c03 100644 --- a/spec/models/clusters/cluster_spec.rb +++ b/spec/models/clusters/cluster_spec.rb @@ -288,6 +288,22 @@ describe Clusters::Cluster do is_expected.to eq([group_cluster, sub_group_cluster]) end + it 'avoids N+1 queries' do + another_project = create(:project) + control_count = ActiveRecord::QueryRecorder.new do + described_class.ancestor_clusters_for_clusterable(another_project, hierarchy_order: hierarchy_order) + end.count + + cluster2 = create(:cluster, :provided_by_gcp, :group) + child2 = cluster2.group + child2.update!(parent: sub_group) + project = create(:project, group: child2) + + expect do + described_class.ancestor_clusters_for_clusterable(project, hierarchy_order: hierarchy_order) + end.not_to exceed_query_limit(control_count) + end + context 'for a group' do let(:clusterable) { sub_group } |