Class: Benchmark::Sweet::Queries::QueryCounter

Inherits:
Object
  • Object
show all
Defined in:
lib/benchmark/sweet/queries.rb

Overview

Derived from code found in stackoverflow.com/questions/5490411/counting-the-number-of-queries-performed

This could get much more elaborate results could be separated by payload (sometimes nil) or payload Could add explains for all queries (and determine index usage)

Constant Summary collapse

CACHE_STATEMENT =
"CACHE".freeze
IGNORED_STATEMENTS =
%w(CACHE SCHEMA).freeze
IGNORED_QUERIES =
/^(?:ROLLBACK|BEGIN|COMMIT|SAVEPOINT|RELEASE)/.freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeQueryCounter

Returns a new instance of QueryCounter.



37
38
39
# File 'lib/benchmark/sweet/queries.rb', line 37

def initialize
  clear
end

Class Method Details

.count(&block) ⇒ Object



29
30
31
# File 'lib/benchmark/sweet/queries.rb', line 29

def self.count(&block)
  new.count(&block)
end

Instance Method Details

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



41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/benchmark/sweet/queries.rb', line 41

def callback(_name, _start, _finish, _id, payload)
  if payload[:sql]
    if payload[:name] == CACHE_STATEMENT
      @instances[:cache_count] += 1
    elsif IGNORED_STATEMENTS.include?(payload[:name]) || IGNORED_QUERIES.match(payload[:sql])
      @instances[:ignored_count] += 1
    else
      @instances[:sql_count] += 1
    end
  else
    @instances[:instance_count] += payload[:record_count]
  end
end

#callback_procObject



55
56
57
# File 'lib/benchmark/sweet/queries.rb', line 55

def callback_proc
  lambda(&method(:callback))
end

#clearObject



59
60
61
# File 'lib/benchmark/sweet/queries.rb', line 59

def clear
  @instances = {cache_count: 0, ignored_count: 0, sql_count: 0, instance_count: 0}
end

#count(&block) ⇒ Object

either use 10.times { value = count(&block) } or use sub { 10.times { block.call; value = get_clear } }



69
70
71
72
73
# File 'lib/benchmark/sweet/queries.rb', line 69

def count(&block)
  clear
  sub(&block)
  @instances
end

#getObject



64
# File 'lib/benchmark/sweet/queries.rb', line 64

def get; @instances; end

#get_clearObject



63
# File 'lib/benchmark/sweet/queries.rb', line 63

def get_clear; @instances.tap { clear }; end

#sub(&block) ⇒ Object



75
76
77
# File 'lib/benchmark/sweet/queries.rb', line 75

def sub(&block)
  ActiveSupport::Notifications.subscribed(callback_proc, /active_record/, &block)
end