Sha256: 2c27034d6fb8da83f805ce7c4dd95cf44ecd0fe6d594f71629e548d55cd43f64

Contents?: true

Size: 974 Bytes

Versions: 3

Compression:

Stored size: 974 Bytes

Contents

module PgHero
  module Methods
    module Explain
      def explain(sql)
        sql = squish(sql)
        explanation = nil
        explain_safe = explain_safe?

        # use transaction for safety
        connection_model.transaction do
          # protect the DB with a 10 second timeout
          # this could potentially increase the timeout, but 10 seconds should be okay
          select_all("SET LOCAL statement_timeout = 10000")
          if (sql.sub(/;\z/, "").include?(";") || sql.upcase.include?("COMMIT")) && !explain_safe
            raise ActiveRecord::StatementInvalid, "Unsafe statement"
          end
          explanation = select_all("EXPLAIN #{sql}").map { |v| v["QUERY PLAN"] }.join("\n")
          raise ActiveRecord::Rollback
        end

        explanation
      end

      private

      def explain_safe?
        select_all("SELECT 1; SELECT 1")
        false
      rescue ActiveRecord::StatementInvalid
        true
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
pghero-1.6.5 lib/pghero/methods/explain.rb
pghero-1.6.4 lib/pghero/methods/explain.rb
pghero-1.6.3 lib/pghero/methods/explain.rb