2011-12-02 07:32:18 -05:00
|
|
|
require 'cases/helper'
|
|
|
|
require 'models/car'
|
|
|
|
require 'active_support/core_ext/string/strip'
|
|
|
|
|
|
|
|
if ActiveRecord::Base.connection.supports_explain?
|
|
|
|
class ExplainTest < ActiveRecord::TestCase
|
|
|
|
fixtures :cars
|
|
|
|
|
|
|
|
def base
|
|
|
|
ActiveRecord::Base
|
|
|
|
end
|
|
|
|
|
|
|
|
def connection
|
|
|
|
base.connection
|
|
|
|
end
|
|
|
|
|
2013-02-24 12:59:34 -05:00
|
|
|
def test_relation_explain
|
|
|
|
message = Car.where(:name => 'honda').explain
|
|
|
|
assert_match(/^EXPLAIN for:/, message)
|
2011-12-04 14:29:56 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def test_collecting_queries_for_explain
|
2013-03-05 10:35:55 -05:00
|
|
|
queries = ActiveRecord::Base.collecting_queries_for_explain do
|
2012-07-27 07:01:25 -04:00
|
|
|
Car.where(:name => 'honda').to_a
|
2011-12-02 07:32:18 -05:00
|
|
|
end
|
|
|
|
|
2011-12-04 14:29:56 -05:00
|
|
|
sql, binds = queries[0]
|
|
|
|
assert_match "SELECT", sql
|
2014-01-14 21:05:00 -05:00
|
|
|
if binds.any?
|
|
|
|
assert_equal 1, binds.length
|
|
|
|
assert_equal "honda", binds.flatten.last
|
|
|
|
else
|
|
|
|
assert_match 'honda', sql
|
|
|
|
end
|
2011-12-02 07:32:18 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def test_exec_explain_with_no_binds
|
2011-12-04 14:29:56 -05:00
|
|
|
sqls = %w(foo bar)
|
|
|
|
binds = [[], []]
|
|
|
|
queries = sqls.zip(binds)
|
2011-12-02 07:32:18 -05:00
|
|
|
|
|
|
|
connection.stubs(:explain).returns('query plan foo', 'query plan bar')
|
|
|
|
expected = sqls.map {|sql| "EXPLAIN for: #{sql}\nquery plan #{sql}"}.join("\n")
|
2011-12-04 14:29:56 -05:00
|
|
|
assert_equal expected, base.exec_explain(queries)
|
2011-12-02 07:32:18 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def test_exec_explain_with_binds
|
|
|
|
cols = [Object.new, Object.new]
|
|
|
|
cols[0].expects(:name).returns('wadus')
|
|
|
|
cols[1].expects(:name).returns('chaflan')
|
|
|
|
|
2011-12-04 14:29:56 -05:00
|
|
|
sqls = %w(foo bar)
|
|
|
|
binds = [[[cols[0], 1]], [[cols[1], 2]]]
|
|
|
|
queries = sqls.zip(binds)
|
2011-12-02 07:32:18 -05:00
|
|
|
|
|
|
|
connection.stubs(:explain).returns("query plan foo\n", "query plan bar\n")
|
|
|
|
expected = <<-SQL.strip_heredoc
|
|
|
|
EXPLAIN for: #{sqls[0]} [["wadus", 1]]
|
|
|
|
query plan foo
|
|
|
|
|
|
|
|
EXPLAIN for: #{sqls[1]} [["chaflan", 2]]
|
|
|
|
query plan bar
|
|
|
|
SQL
|
2011-12-04 14:29:56 -05:00
|
|
|
assert_equal expected, base.exec_explain(queries)
|
2011-12-02 07:32:18 -05:00
|
|
|
end
|
|
|
|
|
2012-11-21 09:28:37 -05:00
|
|
|
def test_unsupported_connection_adapter
|
|
|
|
connection.stubs(:supports_explain?).returns(false)
|
|
|
|
|
|
|
|
base.logger.expects(:warn).never
|
|
|
|
|
2013-02-24 12:59:34 -05:00
|
|
|
Car.where(:name => 'honda').to_a
|
2011-12-02 14:16:07 -05:00
|
|
|
end
|
|
|
|
|
2011-12-02 07:32:18 -05:00
|
|
|
end
|
|
|
|
end
|