Class: ActiveRecordQueryCount::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.



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

def initialize
  reset_query_count
end

Instance Attribute Details

#active_record_query_trackerObject

Returns the value of attribute active_record_query_tracker.



4
5
6
# File 'lib/active_record_query_count/recording/tracker.rb', line 4

def active_record_query_tracker
  @active_record_query_tracker
end

#subscriptionObject

Returns the value of attribute subscription.



4
5
6
# File 'lib/active_record_query_count/recording/tracker.rb', line 4

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



11
12
13
14
15
16
17
# File 'lib/active_record_query_count/recording/tracker.rb', line 11

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



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

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



37
38
39
40
# File 'lib/active_record_query_count/recording/tracker.rb', line 37

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