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.



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

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

Instance Method Details

#analyzeObject



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
72
73
74
# File 'lib/sql_query_analyzer/suggestion_engine.rb', line 26

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

  # Build the full plan text (all lines) so advisors can see Filters, etc.
  full_plan = @explain_output.map { |row| row["QUERY PLAN"] }.join("\n")

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

    # Capture cost & estimates
    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|
      next unless rule[:matcher].call(line)

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

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

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

  presenter = QueryPlanPresenter.new(
    output:        @explain_output.map { |r| r["QUERY PLAN"] },
    warnings:      warnings,
    total_cost:    total_cost,
    rows_estimate: rows_estimate,
    actual_time:   actual_time
  )

  presenter.display
  QueryPlanPresenter.classify_cost(total_cost)
end