Class: ActiveRecordQueryCount::Recording::Tracker

Inherits:
Object
  • Object
show all
Defined in:
lib/active_record_query_count/recording/tracker.rb

Constant Summary collapse

REGEX_TABLE_SQL =
/FROM\s+"(?<table>[^"]+)"/

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeTracker

Returns a new instance of Tracker.



9
10
11
# File 'lib/active_record_query_count/recording/tracker.rb', line 9

def initialize
  reset_query_count
end

Instance Attribute Details

#active_record_query_trackerObject

Returns the value of attribute active_record_query_tracker.



7
8
9
# File 'lib/active_record_query_count/recording/tracker.rb', line 7

def active_record_query_tracker
  @active_record_query_tracker
end

#subscriptionObject

Returns the value of attribute subscription.



7
8
9
# File 'lib/active_record_query_count/recording/tracker.rb', line 7

def subscription
  @subscription
end

Instance Method Details

#reset_query_countObject

This assums that in the same location of the code it will always be the same sql query



14
15
16
17
18
19
20
# File 'lib/active_record_query_count/recording/tracker.rb', line 14

def reset_query_count
  @active_record_query_tracker = Hash.new do |hash, key|
    hash[key] = { count: 0, location: Hash.new do |loc_hash, loc_key|
                                        loc_hash[loc_key] = { count: 0, sql: nil }
                                      end }
  end
end

#subscribeObject



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/active_record_query_count/recording/tracker.rb', line 22

def subscribe
  return unless subscription.nil?

  @subscription = ActiveSupport::Notifications.subscribe('sql.active_record') do |_a, start, finish, _d, payload|
    caller_from_sql = caller
    sql = payload[:sql]
    match = sql.match(REGEX_TABLE_SQL)
    if match.present? && match[:table]
      actual_location = Rails.backtrace_cleaner.clean(caller_from_sql).first
      active_record_query_tracker[match[:table]][:count] += 1
      active_record_query_tracker[match[:table]][:location][actual_location][:duration] ||= 0
      active_record_query_tracker[match[:table]][:location][actual_location][:duration] += (finish - start) * 1000
      active_record_query_tracker[match[:table]][:location][actual_location][:count] += 1
      active_record_query_tracker[match[:table]][:location][actual_location][:sql] = sql
    end
  end
end

#unsubscribeObject



40
41
42
43
# File 'lib/active_record_query_count/recording/tracker.rb', line 40

def unsubscribe
  ActiveSupport::Notifications.unsubscribe(@subscription)
  @subscription = nil
end