Commit 79085e71 authored by Furkan Ayhan's avatar Furkan Ayhan

Optimize User#ci_owned_runners query

This will move two subqueries into CTEs
and let them use the existing index with smarter query plans.

Changelog: performance
parent f1e83fc2
......@@ -15,6 +15,9 @@ module Ci
end
scope :by_namespace_id, -> (namespace_id) { where(namespace_id: namespace_id) }
scope :namespace_id_from_traversal_ids, -> do
select('ci_namespace_mirrors.traversal_ids[array_length(ci_namespace_mirrors.traversal_ids, 1)] AS namespace_id')
end
class << self
def sync!(event)
......
......@@ -2232,20 +2232,32 @@ class User < ApplicationRecord
end
def ci_owned_project_runners_from_group_members
Ci::RunnerProject
cte_project_ids = Gitlab::SQL::CTE.new(
:cte_project_ids,
Ci::ProjectMirror
.select(:project_id)
.joins('JOIN ci_namespace_mirrors ON ci_namespace_mirrors.traversal_ids[array_length(ci_namespace_mirrors.traversal_ids, 1)] = ci_project_mirrors.namespace_id')
.merge(ci_namespace_mirrors_for_group_members(Gitlab::Access::MAINTAINER))
)
Ci::Runner
.select('ci_runners.*')
.joins(:runner)
.joins('JOIN ci_project_mirrors ON ci_project_mirrors.project_id = ci_runner_projects.project_id')
.joins('JOIN ci_namespace_mirrors ON ci_namespace_mirrors.namespace_id = ci_project_mirrors.namespace_id')
.merge(ci_namespace_mirrors_for_group_members(Gitlab::Access::MAINTAINER))
.joins(:runner_projects)
.where('ci_runner_projects.project_id IN (SELECT project_id FROM cte_project_ids)')
.with(cte_project_ids.to_arel)
end
def ci_owned_group_runners
Ci::RunnerNamespace
cte_namespace_ids = Gitlab::SQL::CTE.new(
:cte_namespace_ids,
ci_namespace_mirrors_for_group_members(Gitlab::Access::OWNER).namespace_id_from_traversal_ids
)
Ci::Runner
.select('ci_runners.*')
.joins(:runner)
.joins('JOIN ci_namespace_mirrors ON ci_namespace_mirrors.namespace_id = ci_runner_namespaces.namespace_id')
.merge(ci_namespace_mirrors_for_group_members(Gitlab::Access::OWNER))
.joins(:runner_namespaces)
.where('ci_runner_namespaces.namespace_id IN (SELECT namespace_id FROM cte_namespace_ids)')
.with(cte_namespace_ids.to_arel)
end
def ci_namespace_mirrors_for_group_members(level)
......
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