File: batch_nullify_dependent_associations.rb

package info (click to toggle)
gitlab 17.6.5-19
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 629,368 kB
  • sloc: ruby: 1,915,304; javascript: 557,307; sql: 60,639; xml: 6,509; sh: 4,567; makefile: 1,239; python: 406
file content (27 lines) | stat: -rw-r--r-- 949 bytes parent folder | download
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
# frozen_string_literal: true

# Provides a way to execute nullify behaviour in batches
# to avoid query timeouts for really big tables
# Assumes that associations have `dependent: :nullify` statement
module BatchNullifyDependentAssociations
  extend ActiveSupport::Concern

  class_methods do
    def dependent_associations_to_nullify
      reflect_on_all_associations(:has_many).select { |assoc| assoc.options[:dependent] == :nullify }
    end
  end

  def nullify_dependent_associations_in_batches(exclude: [], batch_size: 100)
    self.class.dependent_associations_to_nullify.each do |association|
      next if association.name.in?(exclude)

      loop do
        # rubocop:disable GitlabSecurity/PublicSend
        update_count = public_send(association.name).limit(batch_size).update_all(association.foreign_key => nil)
        # rubocop:enable GitlabSecurity/PublicSend
        break if update_count < batch_size
      end
    end
  end
end