views:

117

answers:

1

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

+1  A: 

You could add an accessor that says if you wish to log or not.

@@queries = []
@@loging = false
cattr_accessor :queries, :logging

def log_info_with_trace(sql, name, runtime)
    return unless @logger && @logger.debug?
    @@queries << sql if @@logging 
end

When you do a ActiveRecord::ConnectionAdapters::AbstractAdapter::logging = true
Then, your SQL queries will be logged. When you set it to false, they won't.

So you can log them only whenever you want.

To erase the old queries, you just need to clear the array.

ActiveRecord::ConnectionAdapters::AbstractAdapter::queries.clear
Damien MATHIEU
Hi Damien,Thanks for your answer, now i can filter queries related to the needed action but the problem i can't erase old queries.Mondher
Mondher Gatri
See my edition to remove the "old" queries.
Damien MATHIEU