File: relation.rb

package info (click to toggle)
ruby-activerecord-explain-analyze 0.1.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 100 kB
  • sloc: ruby: 73; sh: 4; makefile: 3
file content (38 lines) | stat: -rw-r--r-- 1,002 bytes parent folder | download
1
2
3
4
5
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
38
module ActiveRecordExplainAnalyze
  module Relation
    EXPLAIN_FORMATS = [
      "JSON",
      "TEXT",
      "XML",
      "YAML",
    ].freeze

    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

    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
  end
end