Sha256: 83a1593b9e370749b7cbdc4aaac4c4e05962ec0120ecf1802da0449be6ceec54

Contents?: true

Size: 1.83 KB

Versions: 8

Compression:

Stored size: 1.83 KB

Contents

# frozen_string_literal: true

module ActiveRecord
  module ConnectionAdapters
    module SQLServer
      module CoreExt
        module Explain
          SQLSERVER_STATEMENT_PREFIX = "EXEC sp_executesql "
          SQLSERVER_STATEMENT_REGEXP = /N'(.+)', N'(.+)', (.+)/

          def exec_explain(queries, options = [])
            with_connection do |connection|
              return super(queries, options) unless connection.sqlserver?

              unprepared_queries = queries.map do |(sql, binds)|
                [unprepare_sqlserver_statement(sql, binds), binds]
              end

              super(unprepared_queries, options)
            end
          end

          private

          # This is somewhat hacky, but it should reliably reformat our prepared sql statement
          # which uses sp_executesql to just the first argument, then unquote it. Likewise our
          # `sp_executesql` method should substitute the @n args with the quoted values.
          def unprepare_sqlserver_statement(sql, binds)
            return sql unless sql.start_with?(SQLSERVER_STATEMENT_PREFIX)

            executesql = sql.from(SQLSERVER_STATEMENT_PREFIX.length)
            executesql = executesql.match(SQLSERVER_STATEMENT_REGEXP).to_a[1]

            binds.each_with_index do |bind, index|

              value = if bind.is_a?(::ActiveModel::Attribute)  then
                connection.quote(bind.value_for_database)
              else
                connection.quote(bind)
              end
              executesql = executesql.sub("@#{index}", value)
            end

            executesql
          end
        end
      end
    end
  end
end

ActiveSupport.on_load(:active_record) do
  extend ActiveRecord::ConnectionAdapters::SQLServer::CoreExt::Explain
  ActiveRecord::Relation.include(ActiveRecord::ConnectionAdapters::SQLServer::CoreExt::Explain)
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
activerecord-sqlserver-adapter-7.2.4 lib/active_record/connection_adapters/sqlserver/core_ext/explain.rb
activerecord-sqlserver-adapter-8.0.2 lib/active_record/connection_adapters/sqlserver/core_ext/explain.rb
activerecord-sqlserver-adapter-7.2.3 lib/active_record/connection_adapters/sqlserver/core_ext/explain.rb
activerecord-sqlserver-adapter-8.0.1 lib/active_record/connection_adapters/sqlserver/core_ext/explain.rb
activerecord-sqlserver-adapter-8.0.0 lib/active_record/connection_adapters/sqlserver/core_ext/explain.rb
activerecord-sqlserver-adapter-7.2.2 lib/active_record/connection_adapters/sqlserver/core_ext/explain.rb
activerecord-sqlserver-adapter-7.2.1 lib/active_record/connection_adapters/sqlserver/core_ext/explain.rb
activerecord-sqlserver-adapter-7.2.0 lib/active_record/connection_adapters/sqlserver/core_ext/explain.rb