summaryrefslogtreecommitdiff
path: root/db/migrate/20180710162338_add_foreign_key_from_notification_settings_to_users.rb
blob: 79691f2b24cd17d7b50123ef4a595a56cb800c56 (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
class AddForeignKeyFromNotificationSettingsToUsers < ActiveRecord::Migration[4.2]
  include Gitlab::Database::MigrationHelpers

  class NotificationSetting < ActiveRecord::Base
    self.table_name = 'notification_settings'

    include EachBatch
  end

  class User < ActiveRecord::Base
    self.table_name = 'users'
  end

  DOWNTIME = false

  disable_ddl_transaction!

  def up
    NotificationSetting.each_batch(of: 1000) do |batch|
      batch.where('NOT EXISTS (?)', User.select(1).where('users.id = notification_settings.user_id'))
        .delete_all
    end

    add_concurrent_foreign_key(:notification_settings, :users, column: :user_id, on_delete: :cascade)
  end

  def down
    remove_foreign_key(:notification_settings, column: :user_id)
  end
end