Welcome to mirror list, hosted at ThFree Co, Russian Federation.

20180201110056_add_foreign_keys_to_todos.rb « migrate « db - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: b7c40f8c01a71ce5cfdc3bdbe92a88dd9434cdaf (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
class AddForeignKeysToTodos < ActiveRecord::Migration
  include Gitlab::Database::MigrationHelpers

  class Todo < ActiveRecord::Base
    self.table_name = 'todos'
    include EachBatch
  end

  BATCH_SIZE = 1000

  DOWNTIME = false

  disable_ddl_transaction!

  def up
    Todo.where('NOT EXISTS ( SELECT true FROM users WHERE id=todos.user_id )').each_batch(of: BATCH_SIZE) do |batch|
      batch.delete_all
    end

    Todo.where('NOT EXISTS ( SELECT true FROM users WHERE id=todos.author_id )').each_batch(of: BATCH_SIZE) do |batch|
      batch.delete_all
    end

    Todo.where('note_id IS NOT NULL AND NOT EXISTS ( SELECT true FROM notes WHERE id=todos.note_id )').each_batch(of: BATCH_SIZE) do |batch|
      batch.delete_all
    end

    add_concurrent_foreign_key :todos, :users, column: :user_id, on_delete: :cascade
    add_concurrent_foreign_key :todos, :users, column: :author_id, on_delete: :cascade
    add_concurrent_foreign_key :todos, :notes, column: :note_id, on_delete: :cascade
  end

  def down
    remove_foreign_key :todos, :users
    remove_foreign_key :todos, column: :author_id
    remove_foreign_key :todos, :notes
  end
end