rake query_trace

November 17, 2007 Alex Chaffee

QueryTrace is a great Rails plugin (which I learned about from ErrTheBlog) for pinpointing where in your Rails application that slow query is running. Once you have it installed, your logs won’t just tell you that you have a problem, they will pinpoint the exact location of that problem for you. This is invaluable when doing load & performance testing or just trying to understand what the hell ActiveRecord is doing.

Unfortunately, even though it only logs query traces in DEBUG log mode, it still clutters up your test and development logs, and actually slows things down a bit too. So you don’t want to leave it in your project’s vendor/plugins directory after you’re done using it. So I wrote a pair of rake tasks to enable and disable it.

rake query_trace:on                     # Enables the query_trace plugin. Must restart server to take effect.
rake query_trace:off                    # Disables the query_trace plugin. Must restart server to take effect.

The “on” task actually checks out the plugin from query_trace’s subversion repository, makes a tarball in vendor/query_cache.tar.gz, then leaves the tarball around so it doesn’t have to keep going to the network all the time. You can even check the tarball in to your project and it’ll never go to the query_trace repository again. The “off” task just removes the whole vendor/plugins/query_cache directory.

namespace :query_trace do
  desc "Enables the query_trace plugin. Must restart server to take effect."
  task :on => :environment do
    unless File.exist?("#{RAILS_ROOT}/vendor/query_trace.tar.gz")
      Dir.chdir("#{RAILS_ROOT}/vendor") do
        url = "https://terralien.devguard.com/svn/projects/plugins/query_trace"
        puts "Loading query_trace from #{url}..."
        system "svn co #{url} query_trace"
        system "tar zcf query_trace.tar.gz --exclude=.svn query_trace"
        FileUtils.rm_rf("query_trace")
      end
    end
    Dir.chdir("#{RAILS_ROOT}/vendor/plugins") do
      system "tar zxf ../query_trace.tar.gz query_trace"
    end
    puts "QueryTrace plugin enabled. Must restart server to take effect."
  end

  desc "Disables the query_trace plugin. Must restart server to take effect."
  task :off => :environment do
    FileUtils.rm_rf("#{RAILS_ROOT}/vendor/plugins/query_trace")
    puts "QueryTrace plugin disabled. Must restart server to take effect."
  end
end

About the Author

Biography

More Content by Alex Chaffee
Previous
Get Rake to always show the error stack trace for your project
Get Rake to always show the error stack trace for your project

Tired of rake hiding your error stack trace? rake aborted! Build failed (See full trace by running task ...

Next
Installing Freeimage/ImageScience on OS X 10.5 Leopard
Installing Freeimage/ImageScience on OS X 10.5 Leopard

Gleaned these instructions from a rubyonrails-talk thread. Another thing is mysql is a bit funky, you can't...