Class: RuboCop::Cop::Isucon::Mysql2::PrepareExecute

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/isucon/mysql2/prepare_execute.rb

Overview

Use db.xquery instead of db.prepare.execute

Examples:

# bad (auto-correct isn't possible)
statement = db.prepare('SELECT * FROM `users` WHERE `id` = ?')
statement.execute(
  session[:user][:id]
).first

# bad (auto-correct is possible)
db.prepare('SELECT * FROM `users` WHERE `id` = ?').execute(
  session[:user][:id]
).first

# good
require 'mysql2-cs-bind'

db.xquery('SELECT * FROM `users` WHERE `id` = ?',
  session[:user][:id]
).first

Constant Summary collapse

MSG =
"Use `db.xquery` instead of `db.prepare.execute`"
EXECUTE_LENGTH =
"execute".length

Instance Method Summary collapse

Instance Method Details

#find_prepare_execute(node) ⇒ Object



36
37
38
39
40
41
42
43
44
# File 'lib/rubocop/cop/isucon/mysql2/prepare_execute.rb', line 36

def_node_search :find_prepare_execute, <<~PATTERN
  (send
    (send
      (send nil? _) :prepare $_
    )
    :execute
    ...
  )
PATTERN

#on_send(node) ⇒ Object

Parameters:

  • node (RuboCop::AST::Node)


67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/rubocop/cop/isucon/mysql2/prepare_execute.rb', line 67

def on_send(node)
  if prepare_with_execute?(node)
    find_prepare_execute(node) do |prepare_arg_node|
      add_offense(node) do |corrector|
        perform_autocorrect(corrector: corrector, node: node, prepare_arg_node: prepare_arg_node)
      end
    end
    return
  end

  add_offense(node) if prepare_without_execute?(node)
end

#prepare?(node) ⇒ Boolean

Returns:

  • (Boolean)


60
61
62
63
64
# File 'lib/rubocop/cop/isucon/mysql2/prepare_execute.rb', line 60

def_node_matcher :prepare?, <<~PATTERN
  (send
    (send nil? _) :prepare _
  )
PATTERN

#prepare_with_execute?(node) ⇒ Boolean

Returns:

  • (Boolean)


48
49
50
51
52
53
54
55
56
# File 'lib/rubocop/cop/isucon/mysql2/prepare_execute.rb', line 48

def_node_matcher :prepare_with_execute?, <<~PATTERN
  (send
    (send
      (send nil? _) :prepare _
    )
    :execute
    ...
  )
PATTERN