Class: RuboCop::Cop::Migration::AddIndexColumnsCount

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/migration/add_index_columns_count.rb

Overview

Keep non-unique index columns count less than a specified number.

Adding a non-unique index with more than three columns rarely improves performance. Instead, start an index with columns that narrow down the results the most.

Examples:

# bad
add_index :users, %i[a b c d]

# good (`MaxColumnsCount: 3` by default)
add_index :users, %i[a b c]

Constant Summary collapse

RESTRICT_ON_SEND =
%i[
  add_index
  index
].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ void

This method returns an undefined value.

Parameters:

  • node (RuboCop::AST::SendNode)


25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/rubocop/cop/migration/add_index_columns_count.rb', line 25

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

  column_names_node = column_names_node_from(node)
  return unless column_names_node

  column_names_count = columns_count_from(column_names_node)
  return if column_names_count <= max_columns_count

  add_offense(
    column_names_node,
    message: "Keep unique index columns count less than #{max_columns_count}."
  )
end