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

module Gitlab
  module BackgroundMigration
    # The class to populates the migration_plan column of container_repositories
    # with the current plan of the namespaces that owns the container_repository
    #
    # The plan can be NULL, in which case no UPDATE
    # will be executed.
    class PopulateContainerRepositoryMigrationPlan
      def perform(start_id, end_id)
        (start_id..end_id).each do |id|
          execute(<<~SQL)
            WITH selected_plan AS (
              SELECT "plans"."name"
              FROM "container_repositories"
              INNER JOIN "projects" ON "projects"."id" = "container_repositories"."project_id"
              INNER JOIN "namespaces" ON "namespaces"."id" = "projects"."namespace_id"
              INNER JOIN "gitlab_subscriptions" ON "gitlab_subscriptions"."namespace_id" = "namespaces"."traversal_ids"[1]
              INNER JOIN "plans" ON "plans"."id" = "gitlab_subscriptions"."hosted_plan_id"
              WHERE "container_repositories"."id" = #{id}
            )
            UPDATE container_repositories
            SET migration_plan = selected_plan.name
            FROM selected_plan
            WHERE container_repositories.id = #{id};
          SQL
        end

        mark_job_as_succeeded(start_id, end_id)
      end

      private

      def connection
        @connection ||= ApplicationRecord.connection
      end

      def execute(sql)
        connection.execute(sql)
      end

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