Commit 5771972e authored by Grzegorz Bizon's avatar Grzegorz Bizon

Use database query to calculate average stage position

parent fc6ec8ad
...@@ -24,12 +24,14 @@ module Ci ...@@ -24,12 +24,14 @@ module Ci
self.status = DEFAULT_STATUS if self.status.nil? self.status = DEFAULT_STATUS if self.status.nil?
end end
before_validation do before_validation unless: :importing? do
next unless index.nil? next if index.present?
statuses.pluck(:stage_idx).tap do |indices| self.index = statuses.select(:stage_idx)
self.index = indices.max_by { |index| indices.count(index) } .where('stage_idx IS NOT NULL')
end .group(:stage_idx)
.order('COUNT(*) DESC')
.first&.stage_idx.to_i
end end
state_machine :status, initial: :created do state_machine :status, initial: :created do
......
...@@ -92,7 +92,10 @@ describe Ci::Stage, :models do ...@@ -92,7 +92,10 @@ describe Ci::Stage, :models do
context 'when stage has been imported and does not have index set' do context 'when stage has been imported and does not have index set' do
before do before do
stage.update_column(:index, nil) stage.update_column(:index, nil)
end
context 'when stage has statuses' do
before do
create(:ci_build, :running, stage_id: stage.id, stage_idx: 10) create(:ci_build, :running, stage_id: stage.id, stage_idx: 10)
end end
...@@ -104,5 +107,16 @@ describe Ci::Stage, :models do ...@@ -104,5 +107,16 @@ describe Ci::Stage, :models do
expect(stage.reload.index).to eq 10 expect(stage.reload.index).to eq 10
end end
end end
context 'when stage does not have statuses' do
it 'fallbacks to zero' do
expect(stage.reload.index).to be_nil
stage.update_status
expect(stage.reload.index).to eq 0
end
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