# frozen_string_literal: true

module Gitlab
  module BackgroundMigration
    class BackfillArchivedAndTraversalIdsToVulnerabilityReads < BatchedMigrationJob
      operation_name :backfill_archived_and_traversal_ids_in_vulnerability_reads_table
      feature_category :vulnerability_management

      def perform
        # This allow_cross_joins_across_databases call will never be removed.
        # The definition of this migration cannot function after the decomposition
        # of the Sec database. As such, it must be finalised before the decomposition.
        Gitlab::Database.allow_cross_joins_across_databases(
          url: 'https://gitlab.com/gitlab-org/gitlab/-/merge_requests/164505'
        ) do
          each_sub_batch do |sub_batch|
            connection.exec_update(update_sql(sub_batch))
          end
        end
      end

      private

      def update_sql(sub_batch)
        <<~SQL
        UPDATE
          vulnerability_reads
        SET
          traversal_ids = namespaces.traversal_ids,
          archived = projects.archived
        FROM
          projects
        INNER JOIN namespaces ON namespaces.id = projects.namespace_id
        WHERE
          vulnerability_reads.id IN (#{sub_batch.select(:id).to_sql}) AND
          vulnerability_reads.project_id = projects.id
        SQL
      end
    end
  end
end
