Skip to content

Create BackfillEventsTargetTypeForProjects batched background migration

See 'target_type' parameter for Events API is nil f... (&19098) for context

Currently, project events are created without a set target_type and target_id. This is causing a problem with our Events RESP API as the target_type filter always gives an empty result for project.

After Set `events.target_type` to `project` when crea... (#565786 - closed) has been completed. We now need to backfill the existing records.

Implementation Guide

  1. Ensure that the temporary index Create temporary index for `BackfillEventsTarge... (#565790 - closed) has been created.
  2. Create a script to backfill the events.target_type rows:
# frozen_string_literal: true

module Gitlab
  module BackgroundMigration
    class BackfillProjectEventsTargetType < BatchedMigrationJob
      PROJECT_ACTIONS = [1, 8, 9, 11].freeze # Defined in Events::PROJECT_ACTIONS

      # rubocop:disable Database/AvoidScopeTo -- supported by an index `tmp_idx_events_missing_project_target_type`
      scope_to ->(relation) { relation.where(target_type: nil, action: PROJECT_ACTIONS).where.not(project_id: nil) }
      # rubocop:enable Database/AvoidScopeTo

      operation_name :back_project_events_target_type
      feature_category :groups_and_projects

      def perform
        each_sub_batch do |sub_batch|
          sub_batch.update_all(
            target_type: 'Project',
            target_id: Arel.sql('project_id')
          )
        end
      end
    end
  end
end

Note: All rows with empty target type is either a project action or push event (https://console.postgres.ai/gitlab/gitlab-production-main/sessions/42844/commands/131183)

Edited by Shane Maglangit