Module: ActiveRecordAnalyze

Defined in:
lib/activerecord-analyze.rb,
lib/activerecord-analyze/version.rb

Constant Summary collapse

VERSION =
"0.11.0"

Class Method Summary collapse

Class Method Details

.analyze_sql(raw_sql, opts = {}) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/activerecord-analyze.rb', line 6

def self.analyze_sql(raw_sql, opts = {})
  if opts[:full_debug] == true
    opts = {
      format: :pretty_json,
      verbose: true,
      costs: true,
      buffers: true,
      timing: true,
      summary: true
    }
  end

  prefix = "EXPLAIN #{build_prefix(opts)}"

  result = ActiveRecord::Base.connection.execute("#{prefix} #{raw_sql}").to_a


  if [:json, :hash, :pretty_json].include?(opts[:format])
    raw_json = result[0].fetch("QUERY PLAN")
    if opts[:format] == :json
      raw_json
    elsif opts[:format] == :hash
      JSON.parse(raw_json)
    elsif opts[:format] == :pretty_json
      JSON.pretty_generate(JSON.parse(raw_json))
    end
  else
    result.map do |el|
      el.fetch("QUERY PLAN")
    end.join("\n")
  end
end

.build_prefix(opts = {}) ⇒ Object



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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/activerecord-analyze.rb', line 39

def self.build_prefix(opts = {})
  format_sql = if fmt = opts[:format].presence
    case fmt
    when :json
      "FORMAT JSON, "
    when :hash
      "FORMAT JSON, "
    when :pretty_json
      "FORMAT JSON, "
    when :yaml
      "FORMAT YAML, "
    when :text
      "FORMAT TEXT, "
    when :xml
      "FORMAT XML, "
    else
      ""
    end
  end

  verbose_sql = if opts[:verbose] == true
    ", VERBOSE"
  end

  costs_sql = if opts[:costs] == true
    ", COSTS"
  end

  settings_sql = if opts[:settings] == true
    ", SETTINGS"
  end

  buffers_sql = if opts[:buffers] == true
    ", BUFFERS"
  end

  timing_sql = if opts[:timing] == true
    ", TIMING"
  end

  summary_sql = if opts[:summary] == true
    ", SUMMARY"
  end

  analyze_sql = if opts[:analyze] == false
    ""
  else
    "ANALYZE"
  end

  opts_sql = "(#{format_sql}#{analyze_sql}#{verbose_sql}#{costs_sql}#{settings_sql}#{buffers_sql}#{timing_sql}#{summary_sql})"
    .strip.gsub(/\s+/, " ")
    .gsub(/\(\s?\s?\s?,/, "(")
    .gsub(/\s,\s/, " ")
    .gsub(/\(\s?\)/, "")
end