Module: NPlusInsight::Subscriber

Defined in:
lib/n_plus_insight/subscriber.rb

Constant Summary collapse

TABLE_PATTERN =
/\b(?:FROM|JOIN)\s+["`]?([a-zA-Z_][\w.]*)["`]?/i

Class Method Summary collapse

Class Method Details

.install!Object



6
7
8
9
10
11
# File 'lib/n_plus_insight/subscriber.rb', line 6

def install!
  return if @subscriber
  @subscriber = ActiveSupport::Notifications.subscribe("sql.active_record") do |_name, started, finished, _id, payload|
    record(started, finished, payload)
  end
end

.record(started, finished, payload) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/n_plus_insight/subscriber.rb', line 13

def record(started, finished, payload)
  collector = Current.collector
  return unless collector
  sql = payload[:sql].to_s
  config = NPlusInsight.configuration
  return if payload[:cached] || payload[:name].to_s == "SCHEMA"
  return unless sql.lstrip.match?(/\ASELECT\b/i)
  return if config.ignore_sql.any? { |pattern| pattern.match?(sql) }

  collector << Query.new(
    sql: sql,
    name: payload[:name],
    duration_ms: (finished - started) * 1000,
    cached: payload[:cached],
    location: SourceLocation.from(caller),
    tables: sql.scan(TABLE_PATTERN).flatten.map { |table| table.split(".").last.delete('"`') }.uniq
  )
end