Skip to content

Instantly share code, notes, and snippets.

@asterite
Created November 3, 2010 14:22
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 asterite/661129 to your computer and use it in GitHub Desktop.
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
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