Class: SqlQueryAnalyzer::SuggestionEngine

Inherits:
Object
  • Object
show all
Defined in:
lib/sql_query_analyzer/suggestion_engine.rb

Instance Method Summary collapse

Constructor Details

#initialize(explain_output, sql = nil) ⇒ SuggestionEngine

Returns a new instance of SuggestionEngine.



20
21
22
23
# File 'lib/sql_query_analyzer/suggestion_engine.rb', line 20

def initialize(explain_output, sql = nil)
  @explain_output = explain_output
  @sql = sql
end

Instance Method Details

#analyzeObject



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/sql_query_analyzer/suggestion_engine.rb', line 25

def analyze
  output = []
  warnings = []
  total_cost, rows_estimate, actual_time = nil

  @explain_output.each_with_index do |row, idx|
    line = row["QUERY PLAN"]
    output << line

    if line =~ /cost=\d+\.\d+\.\.(\d+\.\d+) rows=(\d+)/
      total_cost = $1.to_f
      rows_estimate = $2.to_i
    end

    actual_time ||= $1.to_f if line =~ /actual time=(\d+\.\d+)/

    SuggestionRules.all.each do |rule|
      if rule[:matcher].call(line)

        suggestion = Suggestion.new(rule[:severity], rule[:message])
        if rule[:message].include?("Sequential Scan")
          dynamic_msg = SequentialScanAdvisor.new(line).enhanced_message
          suggestion = Suggestion.new(rule[:severity], dynamic_msg) if dynamic_msg
        end

        warnings << {
          line_number: idx + 1,
          line_text: line,
          suggestion: suggestion
        }
      end
    end
  end

  warnings.concat(SqlLevelRules.evaluate(@sql))

  presenter = QueryPlanPresenter.new(
    output: output,
    warnings: warnings,
    total_cost: total_cost,
    rows_estimate: rows_estimate,
    actual_time: actual_time
  )

  presenter.display
  QueryPlanPresenter.classify_cost(total_cost)
end