20180320182229_add_indexes_for_user_activity_queries.rb 1.31 KB
Newer Older
1
class AddIndexesForUserActivityQueries < ActiveRecord::Migration[4.2]
2 3 4 5 6 7 8
  include Gitlab::Database::MigrationHelpers

  DOWNTIME = false

  disable_ddl_transaction!

  def up
9 10
    add_concurrent_index :events, [:author_id, :project_id] unless index_exists?(:events, [:author_id, :project_id])
    add_concurrent_index :user_interacted_projects, :user_id unless index_exists?(:user_interacted_projects, :user_id)
11 12 13
  end

  def down
14
    remove_concurrent_index :events, [:author_id, :project_id] if index_exists?(:events, [:author_id, :project_id])
15 16

    patch_foreign_keys do
17
      remove_concurrent_index :user_interacted_projects, :user_id if index_exists?(:user_interacted_projects, :user_id)
18 19 20 21 22 23
    end
  end

  private

  def patch_foreign_keys
24 25
    return yield if Gitlab::Database.postgresql?

26
    # MySQL doesn't like to remove the index with a foreign key using it.
27 28
    remove_foreign_key :user_interacted_projects, :users if fk_exists?(:user_interacted_projects, :user_id)

29
    yield
30

31
    # Let's re-add the foreign key using the existing index on (user_id, project_id)
32 33 34 35 36 37 38
    add_concurrent_foreign_key :user_interacted_projects, :users, column: :user_id unless fk_exists?(:user_interacted_projects, :user_id)
  end

  def fk_exists?(table, column)
    foreign_keys(table).any? do |key|
      key.options[:column] == column.to_s
    end
39 40
  end
end