Class: BrainzLab::Rails::Analyzers::NPlusOneDetector

Inherits:
Object
  • Object
show all
Defined in:
lib/brainzlab/rails/analyzers/n_plus_one_detector.rb

Overview

Detects N+1 query patterns by tracking similar queries within a request

Constant Summary collapse

THRESHOLD =

Minimum repeated queries to flag as N+1

3

Instance Method Summary collapse

Constructor Details

#initializeNPlusOneDetector

Returns a new instance of NPlusOneDetector.



10
11
12
13
# File 'lib/brainzlab/rails/analyzers/n_plus_one_detector.rb', line 10

def initialize
  @query_tracker = {}
  @request_id = nil
end

Instance Method Details

#check(sql, name, unique_id) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/brainzlab/rails/analyzers/n_plus_one_detector.rb', line 15

def check(sql, name, unique_id)
  # Reset tracker on new request
  reset_if_new_request(unique_id)

  # Skip non-SELECT queries
  return nil unless sql.to_s.strip.upcase.start_with?('SELECT')

  # Skip SCHEMA queries
  return nil if name == 'SCHEMA'

  # Normalize query for comparison (remove specific values)
  normalized = normalize_query(sql)

  # Track query occurrences
  @query_tracker[normalized] ||= { count: 0, first_seen: Time.now, sql: sql }
  @query_tracker[normalized][:count] += 1

  # Check if threshold exceeded
  count = @query_tracker[normalized][:count]
  if count == THRESHOLD
    {
      query: truncate_sql(sql),
      normalized: normalized,
      count: count,
      model: extract_model_from_query(sql),
      location: extract_caller_location
    }
  else
    nil
  end
end