summaryrefslogtreecommitdiff
path: root/db/migrate/20210611100359_rebuild_index_for_cadence_iterations_automation.rb
blob: ecd8bac22bee1cd538fc8bc406c37d1ec08588bf (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
# frozen_string_literal: true

class RebuildIndexForCadenceIterationsAutomation < ActiveRecord::Migration[6.0]
  include Gitlab::Database::MigrationHelpers

  INDEX_NAME = 'cadence_create_iterations_automation'

  disable_ddl_transaction!

  def up
    return if index_exists_and_is_valid?

    remove_concurrent_index_by_name :iterations_cadences, INDEX_NAME

    disable_statement_timeout do
      execute(
        <<-SQL
          CREATE INDEX CONCURRENTLY #{INDEX_NAME} ON iterations_cadences
          USING BTREE(automatic, duration_in_weeks, (DATE ((COALESCE("iterations_cadences"."last_run_date", DATE('01-01-1970')) + "iterations_cadences"."duration_in_weeks" * INTERVAL '1 week')))) 
          WHERE duration_in_weeks IS NOT NULL
      SQL
      )
    end
  end

  def down
    remove_concurrent_index_by_name :iterations_cadences, INDEX_NAME
  end

  def index_exists_and_is_valid?
    execute(
      <<-SQL
        SELECT identifier
        FROM postgres_indexes
        WHERE identifier LIKE '%#{INDEX_NAME}' AND valid_index=TRUE
      SQL
    ).any?
  end
end