Class: Mysql2QueryFilter::Plugin::CasualLog

Inherits:
Base
  • Object
show all
Defined in:
lib/mysql2_query_filter/plugin/casual_log.rb

Constant Summary collapse

REGEXPS =
{
  'select_type' => Regexp.union(
    /DEPENDENT\sUNION/,
    /DEPENDENT\sSUBQUERY/,
    /UNCACHEABLE\sUNION/,
    /UNCACHEABLE\sSUBQUERY/
  ),
  'type' =>  Regexp.union(
    /index/,
    /ALL/
  ),
  'possible_keys' => Regexp.union(
    /NULL/
  ),
  'key' => Regexp.union(
    /NULL/
  ),
  'Extra' => Regexp.union(
    /Using\sfilesort/,
    /Using\stemporary/
  )
}

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ CasualLog



32
33
34
35
36
37
# File 'lib/mysql2_query_filter/plugin/casual_log.rb', line 32

def initialize(options)
  super
  @out = @options[:out] || $stderr
  @matcher = @options[:match] || proc {|sql, client| true }
  @client = @options[:client]
end

Instance Method Details

#filter(sql, client) ⇒ 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
# File 'lib/mysql2_query_filter/plugin/casual_log.rb', line 39

def filter(sql, client)
  if sql =~ /\A\s*SELECT\b/i and @matcher.call(sql, client)
    conn = @client || client
    badquery = false
    explains = []

    conn.query("EXPLAIN #{sql}", :as => :hash).each_with_index do |result, i|
      colorize_explain(result).tap {|bq| badquery ||= bq }
      explains << format_explain(result, i + 1)
    end

    if badquery
      query_options = conn.query_options.dup
      query_options.delete(:password)

      @out << "# Time: \#{Time.now.strftime(\"%Y-%m-%d %H:%M:%S\")}\n# Query options: \#{query_options.inspect}\n# Query: \#{sql}\n\#{explains.join(\"\\n\")}\n      EOS\n    end\n  end\nrescue => e\n  $stderr.puts colored([e.message, e.backtrace.first].join(\"\\n\"))\nend\n"