Sha256: 426a797b9e80ed1c4a85f6c2f199389160a57630f1c5507289031c59ff13eff5

Contents?: true

Size: 754 Bytes

Versions: 9

Compression:

Stored size: 754 Bytes

Contents

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

        # use transaction for safety
        with_transaction(statement_timeout: (explain_timeout_sec * 1000), rollback: true) do
          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")
        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

9 entries across 9 versions & 1 rubygems

Version Path
pghero-2.5.1 lib/pghero/methods/explain.rb
pghero-2.5.0 lib/pghero/methods/explain.rb
pghero-2.4.2 lib/pghero/methods/explain.rb
pghero-2.4.1 lib/pghero/methods/explain.rb
pghero-2.4.0 lib/pghero/methods/explain.rb
pghero-2.3.0 lib/pghero/methods/explain.rb
pghero-2.2.1 lib/pghero/methods/explain.rb
pghero-2.2.0 lib/pghero/methods/explain.rb
pghero-2.1.1 lib/pghero/methods/explain.rb