2012-05-25 10:58:16 -04:00
|
|
|
require 'active_support/lazy_load_hooks'
|
2011-12-15 15:07:41 -05:00
|
|
|
|
2011-12-02 07:32:18 -05:00
|
|
|
module ActiveRecord
|
2011-12-02 14:16:07 -05:00
|
|
|
module Explain
|
2013-02-24 12:59:34 -05:00
|
|
|
# Relation#explain needs to be able to collect the queries.
|
2011-12-16 15:12:05 -05:00
|
|
|
def collecting_queries_for_explain # :nodoc:
|
|
|
|
current = Thread.current
|
|
|
|
original, current[:available_queries_for_explain] = current[:available_queries_for_explain], []
|
2013-03-05 10:35:55 -05:00
|
|
|
yield
|
|
|
|
return current[:available_queries_for_explain]
|
2011-12-16 15:12:05 -05:00
|
|
|
ensure
|
2013-03-18 14:34:39 -04:00
|
|
|
# Note that the return value above does not depend on this assignment.
|
2011-12-16 15:12:05 -05:00
|
|
|
current[:available_queries_for_explain] = original
|
|
|
|
end
|
2011-12-15 15:07:41 -05:00
|
|
|
|
2011-12-16 15:12:05 -05:00
|
|
|
# Makes the adapter execute EXPLAIN for the tuples of queries and bindings.
|
|
|
|
# Returns a formatted string ready to be logged.
|
|
|
|
def exec_explain(queries) # :nodoc:
|
2012-05-31 03:58:17 -04:00
|
|
|
str = queries && queries.map do |sql, bind|
|
2011-12-16 15:12:05 -05:00
|
|
|
[].tap do |msg|
|
|
|
|
msg << "EXPLAIN for: #{sql}"
|
|
|
|
unless bind.empty?
|
|
|
|
bind_msg = bind.map {|col, val| [col.name, val]}.inspect
|
|
|
|
msg.last << " #{bind_msg}"
|
|
|
|
end
|
|
|
|
msg << connection.explain(sql, bind)
|
2011-12-03 08:26:34 -05:00
|
|
|
end.join("\n")
|
2011-12-16 15:12:05 -05:00
|
|
|
end.join("\n")
|
2012-05-31 03:58:17 -04:00
|
|
|
|
2012-06-01 10:57:52 -04:00
|
|
|
# Overriding inspect to be more human readable, specially in the console.
|
2012-05-31 03:58:17 -04:00
|
|
|
def str.inspect
|
|
|
|
self
|
|
|
|
end
|
|
|
|
str
|
2011-12-16 15:12:05 -05:00
|
|
|
end
|
2011-12-02 07:32:18 -05:00
|
|
|
end
|
|
|
|
end
|