Created
August 29, 2016 16:13
-
-
Save ang3lkar/d136c6c7f0f1b82244b7032f6661c96e to your computer and use it in GitHub Desktop.
Run EXPLAIN ANALYZE on all select queries and log the results. Only for development!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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