Class: RuboCop::Cop::Migration::AddColumnWithDefaultValue

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
RangeHelp, Migration::CopConcerns::ColumnTypeMethod
Defined in:
lib/rubocop/cop/migration/add_column_with_default_value.rb

Overview

Add the column without a default value then change the default.

In earlier versions of Postgres, MySQL, and MariaDB, adding a column with a default value to an existing table causes the entire table to be rewritten. During this time, reads and writes are blocked in Postgres, and writes are blocked in MySQL and MariaDB.

Examples:

# bad
class AddSomeColumnToUsers < ActiveRecord::Migration[7.0]
  def change
    add_column :users, :some_column, :string, default: 'some value'
  end
end

# good
class AddSomeColumnToUsers < ActiveRecord::Migration[7.0]
  def change
    add_column :users, :some_column, :string
    change_column_default :users, :some_column, 'some value'
  end
end

Constant Summary collapse

MSG =
'Add the column without a default value then change the default.'
RESTRICT_ON_SEND =
[
  :add_column,
  *COLUMN_TYPE_METHOD_NAMES
].freeze

Constants included from Migration::CopConcerns::ColumnTypeMethod

Migration::CopConcerns::ColumnTypeMethod::COLUMN_TYPE_METHOD_NAMES

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ void

This method returns an undefined value.

Parameters:

  • node (RuboCop::AST::SendNode)


45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/rubocop/cop/migration/add_column_with_default_value.rb', line 45

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

  default_option_node = non_nil_default_option_node_from(node)
  return unless default_option_node

  add_offense(default_option_node) do |corrector|
    autocorrect(
      corrector,
      default_option_node: default_option_node,
      send_node: node
    )
  end
end