Class: RuboCop::Cop::Migration::ChangeColumnNull

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/migration/change_column_null.rb

Overview

Avoid simply setting ‘NOT NULL` constraint on an existing column in PostgreSQL.

It blocks reads and writes while every row is checked. In PostgreSQL 12+, you can safely set ‘NOT NULL` constraint if corresponding check constraint exists.

Examples:

# bad
class SetNotNullColumnConstraintToUsersName < ActiveRecord::Migration[7.0]
  def change
    change_column_null :users, :name, false
  end
end

# good
class SetNotNullCheckConstraintToUsersName < ActiveRecord::Migration[7.0]
  def change
    add_check_constraint :users, 'name IS NOT NULL', name: 'users_name_is_not_null', validate: false
  end
end

class ReplaceNotNullConstraintOnUsersName < ActiveRecord::Migration[7.0]
  def change
    validate_constraint :users, name: 'users_name_is_not_null'
    change_column_null :users, :name, false
    remove_check_constraint :users, name: 'users_name_is_not_null'
  end
end

Constant Summary collapse

MSG =
'Avoid simply setting `NOT NULL` constraint on an existing column in PostgreSQL.'
RESTRICT_ON_SEND =
i[
  change_column_null
  change_null
].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ void

This method returns an undefined value.

Parameters:

  • node (RuboCop::AST::SendNode)


48
49
50
51
52
53
54
# File 'lib/rubocop/cop/migration/change_column_null.rb', line 48

def on_send(node)
  return if called_with_validate_constraint?(node)

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