Skip to content

Instantly share code, notes, and snippets.

@richrines
Forked from jsanders/explain_analyze.rb
Created June 21, 2016 22:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richrines/b282c8ef02dfb3857edde5323cfb6c45 to your computer and use it in GitHub Desktop.
Save richrines/b282c8ef02dfb3857edde5323cfb6c45 to your computer and use it in GitHub Desktop.
Run EXPLAIN ANALYZE on all select queries and log the results. Definitely don't use this if performance matters...
if Rails.env.development?
require 'active_record/connection_adapters/postgresql_adapter'
class ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
def __explain_analyze(sql, command, *args)
meth = "#{command}_without_explain_analyze".to_sym
if /\A\s*SELECT/i.match(sql)
newsql = "EXPLAIN ANALYZE #{sql}"
plan = send(meth, newsql, *args).map { |row| row['QUERY PLAN'] }.join("\n")
Rails.logger.debug("\e[1m\e[31mQUERY PLAN FOR: #{sql.strip};\n#{plan}\e[0m")
end
send(meth, sql, *args)
end
def execute_with_explain_analyze(sql, *args)
__explain_analyze(sql, :execute, *args)
end
def exec_query_with_explain_analyze(sql, *args)
__explain_analyze(sql, :exec_query, *args)
end
alias_method_chain :execute, :explain_analyze
alias_method_chain :exec_query, :explain_analyze
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment