summaryrefslogtreecommitdiff
path: root/db/post_migrate/20190715193142_migrate_discussion_id_on_promoted_epics.rb
blob: ccfec8b3aaf0f9838fb60acb1f17cbcdfdfb4b92 (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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# frozen_string_literal: true

# See http://doc.gitlab.com/ce/development/migration_style_guide.html
# for more information on how to write migrations for GitLab.

class MigrateDiscussionIdOnPromotedEpics < ActiveRecord::Migration[5.2]
  include Gitlab::Database::MigrationHelpers

  # We have ~5000 unique discussion_ids -> this migration will take about 12
  # minutes (5000/1000 * 2 minutes + 2 minutes initial delay) on gitlab.com.
  DOWNTIME = false
  BATCH_SIZE = 1_000
  DELAY_INTERVAL = 2.minutes
  MIGRATION = 'FixPromotedEpicsDiscussionIds'

  disable_ddl_transaction!

  class SystemNoteMetadata < ActiveRecord::Base
    self.table_name = 'system_note_metadata'
  end

  class Note < ActiveRecord::Base
    include EachBatch

    has_one :system_note_metadata

    self.table_name = 'notes'

    def self.fetch_discussion_ids_query
      promoted_epics_query = Note
        .joins(:system_note_metadata)
        .where(system: true)
        .where(noteable_type: 'Epic')
        .where("system_note_metadata.action='moved'")
        .select("DISTINCT noteable_id")

      Note.where(noteable_type: 'Epic')
        .where(noteable_id: promoted_epics_query)
        .order(:discussion_id)
        .distinct.pluck(:discussion_id)
    end
  end

  def up
    add_concurrent_index(:system_note_metadata, :action, where: "action='moved'")

    all_discussion_ids = Note.fetch_discussion_ids_query
    all_discussion_ids.in_groups_of(BATCH_SIZE, false).each_with_index do |ids, index|
      delay = DELAY_INTERVAL * (index + 1)
      BackgroundMigrationWorker.perform_in(delay, MIGRATION, [ids])
    end

    remove_concurrent_index(:system_note_metadata, :action)
  end

  def down
    # no-op
  end
end