Skip to content

Instantly share code, notes, and snippets.

@jsanders
Created December 18, 2013 22:56
Show Gist options
  • Save jsanders/8031340 to your computer and use it in GitHub Desktop.
Save jsanders/8031340 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