Created
November 3, 2010 14:22
-
-
Save asterite/661129 to your computer and use it in GitHub Desktop.
For Ruby on Rails. Put it in your config/initializers folder to print the number of queries executed in a controller action, and also raise an exception if that count exceeds a maximum
This file contains hidden or 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
module QueryCount | |
Max = 10 | |
module MysqlAdapterExtensions | |
def self.included(base) | |
base.alias_method_chain :execute, :review | |
end | |
def execute_with_review(sql, *args) | |
if Thread.current[:query_count] && ['select', 'insert', 'update', 'delete'].include?(sql[0 .. 6].downcase.strip) | |
Thread.current[:query_count] += 1 | |
raise "Query count exceeded maximum (#{Max})" if Thread.current[:query_count] > Max | |
end | |
execute_without_review(sql, *args) | |
end | |
end | |
module ControllerExtensions | |
def self.included(base) | |
base.alias_method_chain :process, :review | |
end | |
def process_with_review(*args) | |
Thread.current[:query_count] = 0 | |
result = process_without_review(*args) | |
count = Thread.current[:query_count] | |
Rails.logger.info "[QueryCount:#{count}] #{args[0].url}" | |
result | |
end | |
end | |
end | |
env = ENV['RAILS_ENV'] | |
if env != 'production' | |
ActiveRecord::ConnectionAdapters::MysqlAdapter.send(:include, QueryCount::MysqlAdapterExtensions) | |
ActionController::Base.send(:include, QueryCount::ControllerExtensions) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment