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

20211206162601_cleanup_after_add_primary_email_to_emails_if_user_confirmed.rb « post_migrate « db - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 14f6c751e4d203996ad2a32744c46ba6a9f5d389 (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

class CleanupAfterAddPrimaryEmailToEmailsIfUserConfirmed < Gitlab::Database::Migration[1.0]
  disable_ddl_transaction!

  MIGRATION_NAME = 'AddPrimaryEmailToEmailsIfUserConfirmed'
  BATCH_SIZE = 10_000

  # Stubbed class to access the User table
  class User < ActiveRecord::Base
    include ::EachBatch

    self.table_name = 'users'
    self.inheritance_column = :_type_disabled

    scope :confirmed, -> { where.not(confirmed_at: nil) }

    has_many :emails
  end

  # Stubbed class to access the Emails table
  class Email < ActiveRecord::Base
    self.table_name = 'emails'
    self.inheritance_column = :_type_disabled

    belongs_to :user
  end

  def up
    finalize_background_migration(MIGRATION_NAME)

    # Select confirmed users that do not have their primary email in the emails table,
    # and create the email record. There should be none if the background migration
    # completed, but in case there is any leftover, we deal with it synchronously.
    not_exists_condition = 'NOT EXISTS (SELECT 1 FROM emails WHERE emails.email = users.email AND emails.user_id = users.id)'

    User.confirmed.each_batch(of: BATCH_SIZE) do |user_batch|
      user_batch.select(:id, :email, :confirmed_at).where(not_exists_condition).each do |user|
        current_time = Time.now.utc

        begin
          Email.create(
            user_id: user.id,
            email: user.email,
            confirmed_at: user.confirmed_at,
            created_at: current_time,
            updated_at: current_time
          )
        rescue StandardError => error
          Gitlab::AppLogger.error("Could not add primary email #{user.email} to emails for user with ID #{user.id} due to #{error}")
        end
      end
    end
  end

  def down
    # Intentionally left blank
  end
end