summaryrefslogtreecommitdiff
path: root/db/post_migrate/20170526101042_migrate_pipeline_stages.rb
blob: 12ad0db3a60cb54cc13511c6742c49cecc46f77d (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
class MigratePipelineStages < ActiveRecord::Migration
  include Gitlab::Database::MigrationHelpers

  DOWNTIME = false

  disable_ddl_transaction!

  def up
    disable_statement_timeout

    execute <<-SQL.strip_heredoc
      INSERT INTO ci_stages (project_id, pipeline_id, name)
        SELECT project_id, commit_id, stage FROM ci_builds
          WHERE stage IS NOT NULL
          GROUP BY project_id, commit_id, stage, stage_idx
          ORDER BY stage_idx
    SQL

    add_concurrent_index(:ci_stages, [:pipeline_id, :name])

    add_column(:ci_builds, :stage_id, :integer)

    stage_id = Arel.sql('(SELECT id FROM ci_stages ' \
                         'WHERE ci_stages.pipeline_id = ci_builds.commit_id ' \
                         'AND ci_stages.name = ci_builds.stage)')
    update_column_in_batches(:ci_builds, :stage_id, stage_id)

    # add_concurrent_foreign_key :ci_stages, :projects, column: :project_id, on_delete: :cascade
    # add_concurrent_foreign_key :ci_builds, :ci_stages, column: :stage_id, on_delete: :cascade
  end

  def down
    execute('TRUNCATE TABLE ci_stages')

    if column_exists?(:ci_builds, :stage_id)
      remove_column(:ci_builds, :stage_id)
    end

    if index_exists?(:ci_stages, [:pipeline_id, :name])
      remove_index(:ci_stages, [:pipeline_id, :name])
    end
  end
end