class Benchmark::Sweet::Queries::QueryCounter

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)

Constants

CACHE_STATEMENT
IGNORED_QUERIES
IGNORED_STATEMENTS

Public Class Methods

count(&block) click to toggle source
# File lib/benchmark/sweet/queries.rb, line 25
def self.count(&block)
  new.count(&block)
end

Public Instance Methods

callback(_name, _start, _finish, _id, payload) click to toggle source
# 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_proc() click to toggle source
# File lib/benchmark/sweet/queries.rb, line 47
def callback_proc
  lambda(&method(:callback))
end
count(&block) click to toggle source

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

# 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