Class: FullTableScanMatchers::SQLWatcher

Inherits:
Object
  • Object
show all
Defined in:
lib/full_table_scan_matchers/sql_watcher.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ SQLWatcher

Returns a new instance of SQLWatcher.



5
6
7
8
# File 'lib/full_table_scan_matchers/sql_watcher.rb', line 5

def initialize(options = {})
  @log     = []
  @options = options
end

Instance Attribute Details

#logObject (readonly)

Returns the value of attribute log.



3
4
5
# File 'lib/full_table_scan_matchers/sql_watcher.rb', line 3

def log
  @log
end

#optionsObject (readonly)

Returns the value of attribute options.



3
4
5
# File 'lib/full_table_scan_matchers/sql_watcher.rb', line 3

def options
  @options
end

Instance Method Details

#callback(_name, _start, _finish, _message_id, payload) ⇒ Object

Method called from the ActiveSupport::Notifications module (through the lambda created by to_proc) when an SQL query is made.

Parameters:

  • _name (String)

    name of the event

  • _start (Time)

    when the instrumented block started execution

  • _finish (Time)

    when the instrumented block ended execution

  • _message_id (String)

    unique ID for this notification

  • payload (Hash)

    the payload



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/full_table_scan_matchers/sql_watcher.rb', line 27

def callback(_name, _start,  _finish, _message_id, payload)
  sql_statement = payload[:sql]
  return if     sql_statement =~ /EXPLAIN /i # That's from us, don't EXPLAIN the EXPLAINS!
  return unless sql_statement =~ /SELECT /   # Only selects for now
  return if     any_match? ignores, sql_statement
  return unless any_match? tables,  sql_statement if options[:tables]

  backtrace = if FullTableScanMatchers.configuration.log_backtrace
    raw_backtrace      = caller
    filtered_backtrace = FullTableScanMatchers.configuration.backtrace_filter.call(raw_backtrace)
    "#{filtered_backtrace.join("\n")}\n"
  else
    nil
  end

  @log << {sql: sql_statement.strip, backtrace: backtrace}
end

#countObject



45
46
47
# File 'lib/full_table_scan_matchers/sql_watcher.rb', line 45

def count
  log.count
end

#to_procProc

Turns a SQLWatcher instance into a lambda. Designed to be used when subscribing to events through the ActiveSupport::Notifications module.

Returns:

  • (Proc)


14
15
16
# File 'lib/full_table_scan_matchers/sql_watcher.rb', line 14

def to_proc
  lambda &method(:callback)
end