Class: Benchmark::Sweet::Queries::QueryCounter
- Inherits:
-
Object
- Object
- Benchmark::Sweet::Queries::QueryCounter
- 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
- #callback(_name, _start, _finish, _id, payload) ⇒ Object
- #callback_proc ⇒ Object
- #clear ⇒ Object
-
#count(&block) ⇒ Object
either use 10.times { value = count(&block) } or use sub { 10.times { block.call; value = get_clear } }.
- #get ⇒ Object
- #get_clear ⇒ Object
-
#initialize ⇒ QueryCounter
constructor
A new instance of QueryCounter.
- #sub(&block) ⇒ Object
Constructor Details
#initialize ⇒ QueryCounter
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_proc ⇒ Object
55 56 57 |
# File 'lib/benchmark/sweet/queries.rb', line 55 def callback_proc lambda(&method(:callback)) end |
#clear ⇒ Object
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 |
#get ⇒ Object
64 |
# File 'lib/benchmark/sweet/queries.rb', line 64 def get; @instances; end |
#get_clear ⇒ Object
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 |