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

module Gitlab
  module BackgroundMigration
    # Sets the `namespace_id` of the existing `vulnerability_reads` records
    class BackfillNamespaceIdOfVulnerabilityReads < BatchedMigrationJob
      operation_name :set_namespace_id

      UPDATE_SQL = <<~SQL
        UPDATE
          vulnerability_reads
        SET
          namespace_id = sub_query.namespace_id
        FROM
          (%<subquery>s) as sub_query
        WHERE
          vulnerability_reads.vulnerability_id = sub_query.vulnerability_id
      SQL

      def perform
        each_sub_batch do |sub_batch|
          update_query = update_query_for(sub_batch)

          connection.execute(update_query)
        end
      end

      private

      def update_query_for(sub_batch)
        subquery = sub_batch.select("vulnerability_reads.vulnerability_id, projects.namespace_id")
                            .joins("INNER JOIN projects ON projects.id = vulnerability_reads.project_id")

        format(UPDATE_SQL, subquery: subquery.to_sql)
      end
    end
  end
end