2012-05-25 10:58:16 -04:00
|
|
|
require 'active_support/lazy_load_hooks'
|
2013-04-16 16:46:55 -04:00
|
|
|
require 'active_record/explain_registry'
|
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-04-16 16:46:55 -04:00
|
|
|
# Executes the block with the collect flag enabled. Queries are collected
|
|
|
|
# asynchronously by the subscriber and returned.
|
2011-12-16 15:12:05 -05:00
|
|
|
def collecting_queries_for_explain # :nodoc:
|
2013-04-16 16:46:55 -04:00
|
|
|
ExplainRegistry.collect = true
|
2013-03-05 10:35:55 -05:00
|
|
|
yield
|
2013-04-16 16:46:55 -04:00
|
|
|
ExplainRegistry.queries
|
2011-12-16 15:12:05 -05:00
|
|
|
ensure
|
2013-04-16 16:46:55 -04:00
|
|
|
ExplainRegistry.reset
|
2011-12-16 15:12:05 -05:00
|
|
|
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:
|
2013-04-16 16:46:55 -04:00
|
|
|
str = 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
|
2013-04-16 16:46:55 -04:00
|
|
|
|
2012-05-31 03:58:17 -04:00
|
|
|
str
|
2011-12-16 15:12:05 -05:00
|
|
|
end
|
2011-12-02 07:32:18 -05:00
|
|
|
end
|
|
|
|
end
|