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

Optimise SQL query

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