Commit 1685b9dc authored by Kamil Trzcinski's avatar Kamil Trzcinski

Optimise SQL query

parent ee2e5835
......@@ -7,10 +7,14 @@ module Ci
builds =
if current_runner.shared?
# this returns builds that are ordered by number of running builds
# we prefer projects that don't use shared runners at all
builds.joins("JOIN (#{projects_with_builds_for_shared_runners.to_sql}) AS projects ON ci_builds.gl_project_id=projects.gl_project_id").
order('projects.running_builds ASC', 'ci_builds.id ASC')
builds.
# don't run projects which have not enables shared runners
joins(:project).where(projects: { builds_enabled: true, shared_runners_enabled: true }).
# this returns builds that are ordered by number of running builds
# we prefer projects that don't use shared runners at all
joins("LEFT JOIN (#{running_builds_for_shared_runners.to_sql}) AS project_builds ON ci_builds.gl_project_id=project_builds.gl_project_id").
order('COALESCE(project_builds.running_builds, 0) ASC', 'ci_builds.id ASC')
else
# do run projects which are only assigned to this runner (FIFO)
builds.where(project: current_runner.projects.where(builds_enabled: true)).order('created_at ASC')
......@@ -38,15 +42,9 @@ module Ci
private
def projects_with_builds_for_shared_runners
Ci::Build.running_or_pending.
joins(:project).where(projects: { builds_enabled: true, shared_runners_enabled: true }).
group(:gl_project_id).
select(:gl_project_id, "count(case when status = 'running' AND runner_id = (#{shared_runners.to_sql}) then 1 end) as running_builds")
end
def shared_runners
Ci::Runner.shared.select(:id)
def running_builds_for_shared_runners
Ci::Build.running.where(runner: Ci::Runner.shared).
group(:gl_project_id).select(:gl_project_id, 'count(*) AS running_builds')
end
end
end
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