summaryrefslogtreecommitdiff
path: root/lib/gitlab/background_migration/extract_project_topics_into_separate_table.rb
blob: 31b5b5cdb7324d496218e26ca5f4d3d44867c6ec (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
60
61
62
63
# frozen_string_literal: true

module Gitlab
  module BackgroundMigration
    # The class to extract the project topics into a separate `topics` table
    class ExtractProjectTopicsIntoSeparateTable
      # Temporary AR table for tags
      class Tag < ActiveRecord::Base
        self.table_name = 'tags'
      end

      # Temporary AR table for taggings
      class Tagging < ActiveRecord::Base
        self.table_name = 'taggings'
        belongs_to :tag
      end

      # Temporary AR table for topics
      class Topic < ActiveRecord::Base
        self.table_name = 'topics'
      end

      # Temporary AR table for project topics
      class ProjectTopic < ActiveRecord::Base
        self.table_name = 'project_topics'
        belongs_to :topic
      end

      # Temporary AR table for projects
      class Project < ActiveRecord::Base
        self.table_name = 'projects'
      end

      def perform(start_id, stop_id)
        Tagging.includes(:tag).where(taggable_type: 'Project', id: start_id..stop_id).each do |tagging|
          if Project.exists?(id: tagging.taggable_id) && tagging.tag
            begin
              topic = Topic.find_or_create_by(name: tagging.tag.name)
              project_topic = ProjectTopic.find_or_create_by(project_id: tagging.taggable_id, topic: topic)

              tagging.delete if project_topic.persisted?
            rescue StandardError => e
              Gitlab::ErrorTracking.log_exception(e, tagging_id: tagging.id)
            end
          else
            tagging.delete
          end
        end

        mark_job_as_succeeded(start_id, stop_id)
      end

      private

      def mark_job_as_succeeded(*arguments)
        Gitlab::Database::BackgroundMigrationJob.mark_all_as_succeeded(
          self.class.name.demodulize,
          arguments
        )
      end
    end
  end
end