Module: ActiveRecord::ConnectionAdapters::MSSQL::ExplainSupport

Included in:
ActiveRecord::ConnectionAdapters::MSSQLAdapter
Defined in:
lib/arjdbc/mssql/explain_support.rb

Overview

NOTE: the execution plan (explain) is a estimated only for prepared statements similar the jTDS used to provide. The mssql-jdbc driver does not supports explain from prepared statements. more in: https://github.com/Microsoft/mssql-jdbc/issues/778

Constant Summary collapse

DISABLED =
Java::JavaLang::Boolean.getBoolean('arjdbc.mssql.explain_support.disabled')

Instance Method Summary collapse

Instance Method Details

#explain(arel, binds = []) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/arjdbc/mssql/explain_support.rb', line 20

def explain(arel, binds = [])
  return if DISABLED

  if arel.respond_to?(:to_sql)
    raw_sql, raw_binds = to_sql_and_binds(arel, binds)
  else
    raw_sql, raw_binds = arel, binds
  end
  # sql = to_sql(arel, binds)
  # result = with_showplan_on { exec_query(sql, 'EXPLAIN', binds) }
   sql = interpolate_sql_statement(raw_sql, raw_binds)
   result = with_showplan_on do
     exec_query(sql, 'EXPLAIN', [])
   end
  PrinterTable.new(result).pp
end

#interpolate_sql_statement(arel, binds) ⇒ Object (protected)

converting the prepared statements to sql



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/arjdbc/mssql/explain_support.rb', line 40

def interpolate_sql_statement(arel, binds)
  return arel if binds.empty?

  sql = if arel.respond_to?(:to_sql)
          arel.to_sql
        else
          arel
        end

  binds.each do |bind|
    value = quote(bind.value_for_database)
    sql = sql.sub('?', value)
  end

  sql
end

#set_showplan_option(enable = true) ⇒ Object (protected)



64
65
66
67
68
69
70
# File 'lib/arjdbc/mssql/explain_support.rb', line 64

def set_showplan_option(enable = true)
  option = 'SHOWPLAN_ALL'
  execute "SET #{option} #{enable ? 'ON' : 'OFF'}"
rescue Exception => e
  raise ActiveRecord::ActiveRecordError, "#{option} could not be turned" +
    " #{enable ? 'ON' : 'OFF'} (check SHOWPLAN permissions) due : #{e.inspect}"
end

#supports_explain?Boolean

Returns:

  • (Boolean)


16
17
18
# File 'lib/arjdbc/mssql/explain_support.rb', line 16

def supports_explain?
  !DISABLED
end

#with_showplan_onObject (protected)



57
58
59
60
61
62
# File 'lib/arjdbc/mssql/explain_support.rb', line 57

def with_showplan_on
  set_showplan_option(true)
  yield
ensure
  set_showplan_option(false)
end