Module: ActiveRecordQueryCounter
- Defined in:
- lib/active_record_query_counter.rb
Overview
Everything you need to count ActiveRecord queries and row counts within a block.
Usage:
ActiveRecordQueryCounter.count_queries do
yield
puts ActiveRecordQueryCounter.query_count
puts ActiveRecordQueryCounter.row_count
end
Defined Under Namespace
Modules: ConnectionAdapterExtension Classes: RackMiddleware, SidekiqMiddleware
Class Method Summary collapse
-
.count_queries ⇒ Object
Enable query counting within a block.
-
.enable!(connection_class) ⇒ Object
Enable the query counting behavior on a connection adapter class.
-
.increment(row_count, elapsed_time) ⇒ Object
Increment the query counters.
-
.info ⇒ Object
Return the query info as a hash with keys :query_count, :row_count, :query_time.
- .query_count ⇒ Object
- .query_time ⇒ Object
- .row_count ⇒ Object
Class Method Details
.count_queries ⇒ Object
Enable query counting within a block.
17 18 19 20 21 22 23 24 25 |
# File 'lib/active_record_query_counter.rb', line 17 def count_queries current = Thread.current[:database_query_counter] begin Thread.current[:database_query_counter] = [0, 0, 0.0] yield ensure Thread.current[:database_query_counter] = current end end |
.enable!(connection_class) ⇒ Object
Enable the query counting behavior on a connection adapter class.
68 69 70 71 72 |
# File 'lib/active_record_query_counter.rb', line 68 def enable!(connection_class) unless connection_class.include?(ConnectionAdapterExtension) connection_class.prepend(ConnectionAdapterExtension) end end |
.increment(row_count, elapsed_time) ⇒ Object
Increment the query counters
28 29 30 31 32 33 34 35 |
# File 'lib/active_record_query_counter.rb', line 28 def increment(row_count, elapsed_time) current = Thread.current[:database_query_counter] if current.is_a?(Array) current[0] = current[0].to_i + 1 current[1] = current[1].to_i + row_count current[2] = current[2].to_f + elapsed_time end end |
.info ⇒ Object
Return the query info as a hash with keys :query_count, :row_count, :query_time. or nil if not inside a block where queries are being counted.
54 55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/active_record_query_counter.rb', line 54 def info current = Thread.current[:database_query_counter] if current { :query_count => current[0], :row_count => current[1], :query_time => current[2] } else nil end end |
.query_count ⇒ Object
37 38 39 40 |
# File 'lib/active_record_query_counter.rb', line 37 def query_count current = Thread.current[:database_query_counter] current[0].to_i if current.is_a?(Array) end |
.query_time ⇒ Object
47 48 49 50 |
# File 'lib/active_record_query_counter.rb', line 47 def query_time current = Thread.current[:database_query_counter] current[2].to_f if current.is_a?(Array) end |
.row_count ⇒ Object
42 43 44 45 |
# File 'lib/active_record_query_counter.rb', line 42 def row_count current = Thread.current[:database_query_counter] current[1].to_i if current.is_a?(Array) end |