20170713104829_add_foreign_key_to_merge_requests.rb 1.01 KB
Newer Older
1
class AddForeignKeyToMergeRequests < ActiveRecord::Migration[4.2]
2 3 4 5 6 7
  include Gitlab::Database::MigrationHelpers

  DOWNTIME = false

  disable_ddl_transaction!

8 9 10 11 12
  class MergeRequest < ActiveRecord::Base
    self.table_name = 'merge_requests'
    include ::EachBatch
  end

13
  def up
14 15 16
    scope = <<-SQL.strip_heredoc
      head_pipeline_id IS NOT NULL
        AND NOT EXISTS (
17 18 19 20 21
          SELECT 1 FROM ci_pipelines
            WHERE ci_pipelines.id = merge_requests.head_pipeline_id
        )
    SQL

22 23 24 25
    MergeRequest.where(scope).each_batch(of: 1000) do |merge_requests|
      merge_requests.update_all(head_pipeline_id: nil)
    end

26
    unless foreign_key_exists?(:merge_requests, column: :head_pipeline_id)
27 28 29 30 31 32
      add_concurrent_foreign_key(:merge_requests, :ci_pipelines,
                                 column: :head_pipeline_id, on_delete: :nullify)
    end
  end

  def down
33
    if foreign_key_exists?(:merge_requests, column: :head_pipeline_id)
34 35 36 37
      remove_foreign_key(:merge_requests, column: :head_pipeline_id)
    end
  end
end