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:
|
2016-07-18 20:43:38 -04:00
|
|
|
str = queries.map do |sql, binds|
|
|
|
|
msg = "EXPLAIN for: #{sql}"
|
|
|
|
unless binds.empty?
|
|
|
|
msg << " "
|
|
|
|
msg << binds.map { |attr| render_bind(attr) }.inspect
|
|
|
|
end
|
|
|
|
msg << "\n"
|
|
|
|
msg << connection.explain(sql, binds)
|
2011-12-16 15:12:05 -05:00
|
|
|
end.join("\n")
|
2012-05-31 03:58:17 -04:00
|
|
|
|
2014-07-19 03:20:41 -04:00
|
|
|
# Overriding inspect to be more human readable, especially 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
|
2016-07-18 20:43:38 -04:00
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def render_bind(attr)
|
|
|
|
value = if attr.type.binary? && attr.value
|
|
|
|
"<#{attr.value_for_database.to_s.bytesize} bytes of binary data>"
|
|
|
|
else
|
|
|
|
connection.type_cast(attr.value_for_database)
|
|
|
|
end
|
|
|
|
|
|
|
|
[attr.name, value]
|
|
|
|
end
|
2011-12-02 07:32:18 -05:00
|
|
|
end
|
|
|
|
end
|