Last active
August 29, 2015 14:05
-
-
Save ainame/e221dff60c217d9dc08a to your computer and use it in GitHub Desktop.
開発環境ではarproxy+explain_parserでexplainをログに吐く. arproxy.rbはconfig/initializer/arproxy.rb などに置く.
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 defined?(Rails) && Rails.env.development? | |
class ExplainTracer < Arproxy::Base | |
def execute(sql, name = nil) | |
return super(sql, name) unless load_and_select_query?(sql, name) | |
result = super("EXPLAIN #{sql}", name) | |
explain = ExplainParser.call(result).first | |
log_for_explain(sql, explain) | |
# must to call super with original query | |
super(sql, name) | |
end | |
def log_for_explain(sql, explain) | |
Rails.logger.info log_using_index(sql) if explain.using_index? | |
Rails.logger.info log_possible_keys_not_found(sql) unless explain.possible_keys | |
Rails.logger.error log_danger_sql(sql, 'using filesort') if explain.using_filesort? | |
Rails.logger.error log_danger_sql(sql, 'using temporary') if explain.using_temporary? | |
end | |
def load_and_select_query?(sql, name) | |
sql =~ /^SELECT/ && name =~ /Load/ | |
end | |
def log_using_index(sql) | |
"[Using Index] - #{sql}" | |
end | |
def log_possible_keys_not_found(sql) | |
"[Not Found Possible Keys] - #{sql}" | |
end | |
def log_danger_sql(sql, type) | |
at_mart_line = "@" * sql.size | |
<<EOS | |
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#{at_mart_line} | |
WARNING: #{type} - #{sql}; | |
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#{at_mart_line} | |
EOS | |
end | |
end | |
Arproxy.configure do |config| | |
config.adapter = 'mysql2' | |
config.use ExplainTracer | |
end | |
Arproxy.enable! | |
end |
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
gem 'arproxy' | |
gem 'explain_parser' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment