20170622135728_add_unique_constraint_to_ci_variables.rb 913 Bytes
Newer Older
1
class AddUniqueConstraintToCiVariables < ActiveRecord::Migration[4.2]
2 3 4
  include Gitlab::Database::MigrationHelpers

  DOWNTIME = false
5
  INDEX_NAME = 'index_ci_variables_on_project_id_and_key_and_environment_scope'
6 7 8 9

  disable_ddl_transaction!

  def up
10
    unless this_index_exists?
11
      add_concurrent_index(:ci_variables, columns, name: INDEX_NAME, unique: true)
12 13 14 15
    end
  end

  def down
16 17 18 19 20 21
    if this_index_exists?
      if Gitlab::Database.mysql? && !index_exists?(:ci_variables, :project_id)
        # Need to add this index for MySQL project_id foreign key constraint
        add_concurrent_index(:ci_variables, :project_id)
      end

22
      remove_concurrent_index(:ci_variables, columns, name: INDEX_NAME)
23 24 25
    end
  end

26 27 28
  private

  def this_index_exists?
29
    index_exists?(:ci_variables, columns, name: INDEX_NAME)
30 31
  end

32 33 34 35
  def columns
    @columns ||= [:project_id, :key, :environment_scope]
  end
end