summaryrefslogtreecommitdiff
path: root/app/services/users/migrate_to_ghost_user_service.rb
blob: 1e1ed1791ec7e90397ff5a9a1a7bfdcc724d3bc3 (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
# When a user is destroyed, some of their associated records are
# moved to a "Ghost User", to prevent these associated records from
# being destroyed.
#
# For example, all the issues/MRs a user has created are _not_ destroyed
# when the user is destroyed.
module Users
  class MigrateToGhostUserService
    extend ActiveSupport::Concern

    attr_reader :ghost_user, :user

    def initialize(user)
      @user = user
    end

    def execute
      # Block the user before moving records to prevent a data race.
      # For example, if the user creates an issue after `migrate_issues`
      # runs and before the user is destroyed, the destroy will fail with
      # an exception.
      user.block

      user.transaction do
        @ghost_user = User.ghost

        migrate_issues
        migrate_merge_requests
        migrate_notes
        migrate_abuse_reports
        migrate_award_emoji
      end

      user.reload
    end

    private

    def migrate_issues
      user.issues.update_all(author_id: ghost_user.id)
    end

    def migrate_merge_requests
      user.merge_requests.update_all(author_id: ghost_user.id)
    end

    def migrate_notes
      user.notes.update_all(author_id: ghost_user.id)
    end

    def migrate_abuse_reports
      user.reported_abuse_reports.update_all(reporter_id: ghost_user.id)
    end

    def migrate_award_emoji
      user.award_emoji.update_all(user_id: ghost_user.id)
    end
  end
end