aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/test/cases/explain_test.rb
blob: 6409290e8d953b75fb9d9ec1a0064c6408186754 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
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

    def test_relation_explain
      message = Car.where(:name => 'honda').explain
      assert_match(/^EXPLAIN for:/, message)
    end

    def test_collecting_queries_for_explain
      queries = ActiveRecord::Base.collecting_queries_for_explain do
        Car.where(:name => 'honda').to_a
      end

      sql, binds = queries[0]
      assert_match "SELECT", sql
      if binds.any?
        assert_equal 1, binds.length
        assert_equal "honda", binds.last.value
      else
        assert_match 'honda', sql
      end
    end

    def test_exec_explain_with_no_binds
      sqls    = %w(foo bar)
      binds   = [[], []]
      queries = sqls.zip(binds)

      stub_explain_for_query_plans do
        expected = sqls.map {|sql| "EXPLAIN for: #{sql}\nquery plan #{sql}"}.join("\n")
        assert_equal expected, base.exec_explain(queries)
      end
    end

    def test_exec_explain_with_binds
      sqls    = %w(foo bar)
      binds   = [[bind_param('wadus', 1)], [bind_param('chaflan', 2)]]
      queries = sqls.zip(binds)

      stub_explain_for_query_plans(["query plan foo\n", "query plan bar\n"]) do
        expected = <<-SQL.strip_heredoc
          EXPLAIN for: #{sqls[0]} [["wadus", 1]]
          query plan foo

          EXPLAIN for: #{sqls[1]} [["chaflan", 2]]
          query plan bar
        SQL
        assert_equal expected, base.exec_explain(queries)
      end
    end

    def test_unsupported_connection_adapter
      connection.stub(:supports_explain?, false) do
        assert_not_called(base.logger, :warn) do
          Car.where(:name => 'honda').to_a
        end
      end
    end

    private

      def stub_explain_for_query_plans(query_plans = ['query plan foo', 'query plan bar'])
        explain_called = 0

        connection.stub(:explain, proc{ explain_called += 1; query_plans[explain_called - 1] }) do
          yield
        end
      end

      def bind_param(name, value)
        ActiveRecord::Relation::QueryAttribute.new(name, value, ActiveRecord::Type::Value.new)
      end
  end
end