Module: ActiveRecordExplainAnalyze::Relation

Defined in:
lib/activerecord-explain-analyze/relation.rb

Constant Summary collapse

EXPLAIN_FORMATS =
[
  "JSON",
  "TEXT",
  "XML",
  "YAML",
].freeze

Instance Method Summary collapse

Instance Method Details

#exec_explain_with_options(queries, analyze:, format:) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/activerecord-explain-analyze/relation.rb', line 24

def exec_explain_with_options(queries, analyze:, format:)
  str = queries.map do |sql, binds|
    msg = "EXPLAIN for: #{sql}\n".dup
    msg << connection.explain_with_options(sql, binds, analyze, format)
  end.join("\n")

  # Overriding inspect to be more human readable, especially in the console.
  def str.inspect
    self
  end

  str
end

#explain(analyze: false, format: :text) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/activerecord-explain-analyze/relation.rb', line 10

def explain(analyze: false, format: :text)
  format = format.to_s.upcase
  unless EXPLAIN_FORMATS.include?(format)
    raise ArgumentError, "format must be one of: #{EXPLAIN_FORMATS.join(', ')}"
  end

  queries = collecting_queries_for_explain { exec_queries }
  if analyze || format != "TEXT"
    exec_explain_with_options(queries, analyze: analyze, format: format)
  else
    exec_explain(queries)
  end
end