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

Class Method Details

.count(&block) ⇒ Object



25
26
27
# File 'lib/benchmark/sweet/queries.rb', line 25

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

Instance Method Details

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



33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/benchmark/sweet/queries.rb', line 33

def callback(_name, _start, _finish, _id, payload)
  if payload[:sql]
    if payload[:name] == CACHE_STATEMENT
      @instance[: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



47
48
49
# File 'lib/benchmark/sweet/queries.rb', line 47

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

#count(&block) ⇒ Object

TODO: possibly setup a single subscribe and use a context/thread local to properly count metrics



52
53
54
55
56
# File 'lib/benchmark/sweet/queries.rb', line 52

def count(&block)
  @instances = {cache_count: 0, ignored_count: 0, sql_count: 0, instance_count: 0}
  ActiveSupport::Notifications.subscribed(callback_proc, /active_record/, &block)
  @instances
end