summaryrefslogtreecommitdiff
path: root/lib/gitlab/background_migration/move_container_registry_enabled_to_project_feature.rb
blob: 4eaef26c9c67f7721cd9fc689afcd96234d61e3d (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
# frozen_string_literal: true

module Gitlab
  module BackgroundMigration
    # This migration moves projects.container_registry_enabled values to
    # project_features.container_registry_access_level for the projects within
    # the given range of ids.
    class MoveContainerRegistryEnabledToProjectFeature
      MAX_BATCH_SIZE = 1_000

      module Migratable
        # Migration model namespace isolated from application code.
        class ProjectFeature < ActiveRecord::Base
          ENABLED = 20
          DISABLED = 0
        end
      end

      def perform(from_id, to_id)
        (from_id..to_id).each_slice(MAX_BATCH_SIZE) do |batch|
          process_batch(batch.first, batch.last)
        end
      end

      private

      def process_batch(from_id, to_id)
        ActiveRecord::Base.connection.execute(update_sql(from_id, to_id))

        logger.info(message: "#{self.class}: Copied container_registry_enabled values for projects with IDs between #{from_id}..#{to_id}")
      end

      # For projects that have a project_feature:
      # Set project_features.container_registry_access_level to ENABLED (20) or DISABLED (0)
      #   depending if container_registry_enabled is true or false.
      def update_sql(from_id, to_id)
        <<~SQL
        UPDATE project_features
        SET container_registry_access_level = (CASE p.container_registry_enabled
                                              WHEN true THEN #{ProjectFeature::ENABLED}
                                              WHEN false THEN #{ProjectFeature::DISABLED}
                                              ELSE #{ProjectFeature::DISABLED}
                                              END)
        FROM projects p
        WHERE project_id = p.id AND
        project_id BETWEEN #{from_id} AND #{to_id}
        SQL
      end

      def logger
        @logger ||= Gitlab::BackgroundMigration::Logger.build
      end
    end
  end
end