summaryrefslogtreecommitdiff
path: root/lib/gitlab/background_migration/migrate_build_stage.rb
blob: 3e297a90b19ce4a8329e84421e0d3a2526a93553 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# frozen_string_literal: true
# rubocop:disable Metrics/AbcSize
# rubocop:disable Style/Documentation

module Gitlab
  module BackgroundMigration
    class MigrateBuildStage
      module Migratable
        class Stage < ActiveRecord::Base
          self.table_name = 'ci_stages'
        end

        class Build < ActiveRecord::Base
          self.table_name = 'ci_builds'

          def ensure_stage!
            find || create!
          rescue ActiveRecord::RecordNotUnique
            # TODO
          end

          def find
            Stage.find_by(name: self.stage,
                          pipeline_id: self.commit_id,
                          project_id: self.project_id)
          end

          def create!
            Stage.create!(name: self.stage || 'test',
                          pipeline_id: self.commit_id,
                          project_id: self.project_id)
          end
        end
      end

      def perform(start_id, stop_id)
        # TODO, should we disable_statement_timeout?
        # TODO, use plain SQL query?

        stages = Migratable::Build.where('stage_id IS NULL')
          .where("id BETWEEN #{start_id.to_i} AND #{stop_id.to_i}")
          .map { |build| build.ensure_stage! }
          .compact.map(&:id)

        MigrateBuildStageIdReference.new.perform(start_id, stop_id)
        MigrateStageStatus.new.perform(stages.min, stages.max)
      end
    end
  end
end