views:

1044

answers:

3

I'm looking for something like CodeIgniter's:

$this->db->last_query();

(http://codeigniter.com/user_guide/database/helpers.html)

+13  A: 

AFAIK, there's no easy way to access the list of queries. Nonetheless you can easily get access to them creating a super simple logger.

If you open the class ActiveRecord::ConnectionAdapters::AbstractAdapter you'll see a method called log. This method is invoked on each query to log the statement. By default, it logs all the statements with the Rails logger.

You can do something like

ActiveRecord::ConnectionAdapters::AbstractAdapter.class_eval do

  attr_reader :last_query
  alias_method_chain :log, :last_query

  def log_with_last_query(sql, name, &block)
    @last_query = [sql, name]
    log_without_last_query(sql, name, &block)
  end

end

Now you can get the query with

ActiveRecord::Base.connection.last_query # => ...
Simone Carletti
+1 for monkey patching a part of Rails, the king of monkey patching.
Max A.
A: 

Your development log should include all SQL queries that are run.

Corban Brook
Yeah, but that's the thing -- it has ALL of the queries. I only want to see what I explicitly log.
Nikki Erwin Ramirez
+1  A: 

Dear all, I’m developing an application dedicated to generate statistical reports, I would like that user after saving their stat report they save sql queries too. To do that I wrote the following module:

module SqlHunter

class ActiveRecord::ConnectionAdapters::AbstractAdapter

    @@queries = [] 
    cattr_accessor :queries 
    def log_info_with_trace(sql, name, runtime)
     return unless @logger && @logger.debug?
    @@queries << sql 
    end
    alias_method_chain :log_info, :trace
end

end

in the controller I wrote that

sqlfile = File.open("public/advancedStats/#{@dir_name}/advancedStatQuery.sql", 'w')
@queries = ActiveRecord::ConnectionAdapters::AbstractAdapter::queries
for query in @queries do
    sqlfile.write("#{query} \n")
end
sqlfile.close

I also modified Rails environment by adding this line:

ActiveRecord::Base.logger.level = Logger::DEBUG

This program is working and I can get all queries but, I need only the specific queries done by one user to generate a stat report.

Is someone has any idea, Thanks,

mgatri

Mondher Gatri
Asked as a real question here : http://stackoverflow.com/questions/1701236/how-to-get-sql-queries-for-each-user-where-env-is-production
Damien MATHIEU