Class: RuboCop::Cop::Migration::BatchInTransaction

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
Migration::CopConcerns::BatchProcessing, Migration::CopConcerns::DisableDdlTransaction
Defined in:
lib/rubocop/cop/migration/batch_in_transaction.rb

Overview

Disable transaction in batch processing.

To avoid locking the table.

Examples:

# bad
class AddSomeColumnToUsersThenBackfillSomeColumn < ActiveRecord::Migration[7.0]
  def change
    add_column :users, :some_column, :text
    User.update_all(some_column: 'some value')
  end
end

# good
class AddSomeColumnToUsers < ActiveRecord::Migration[7.0]
  def change
    add_column :users, :some_column, :text
  end
end

class BackfillSomeColumnToUsers < ActiveRecord::Migration[7.0]
  disable_ddl_transaction!

  def up
    User.unscoped.in_batches do |relation|
      relation.update_all(some_column: 'some value')
      sleep(0.01)
    end
  end
end

Constant Summary collapse

MSG =
'Disable transaction in batch processing.'
RESTRICT_ON_SEND =
i[
  delete_all
  update_all
].freeze

Constants included from Migration::CopConcerns::BatchProcessing

Migration::CopConcerns::BatchProcessing::BATCH_PROCESSING_METHOD_NAMES

Instance Method Summary collapse

Methods included from Migration::CopConcerns::DisableDdlTransaction

included

Methods included from Migration::CopConcerns::BatchProcessing

included

Instance Method Details

#on_send(node) ⇒ void

This method returns an undefined value.

Parameters:

  • node (RuboCop::AST::SendNode)


54
55
56
57
58
59
60
# File 'lib/rubocop/cop/migration/batch_in_transaction.rb', line 54

def on_send(node)
  return unless wrong?(node)

  add_offense(node) do |corrector|
    autocorrect(corrector, node)
  end
end