Class: RuboCop::Cop::Migration::AddCheckConstraint

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

Overview

Activate a check constraint in a separate migration in PostgreSQL.

Adding a check constraint without ‘NOT VALID` blocks reads and writes in Postgres and blocks writes in MySQL and MariaDB while every row is checked.

Examples:

# bad
class AddCheckConstraintToOrdersPrice < ActiveRecord::Migration[7.0]
  def change
    add_check_constraint :orders, 'price > 0', name: 'orders_price_positive'
  end
end

# good
class AddCheckConstraintToOrdersPriceWithoutValidation < ActiveRecord::Migration[7.0]
  def change
    add_check_constraint :orders, 'price > 0', name: 'orders_price_positive', validate: false
  end
end

class ActivateCheckConstraintOnOrdersPrice < ActiveRecord::Migration[7.0]
  def change
    validate_check_constraint :orders, name: 'orders_price_positive'
  end
end

Constant Summary collapse

MSG =
'Activate a check constraint in a separate migration in PostgreSQL.'
RESTRICT_ON_SEND =
%i[
  add_check_constraint
].freeze

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
# File 'lib/rubocop/cop/migration/add_check_constraint.rb', line 45

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

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