Similar to 'rails server' that prints every SQL query executed I would like to do the same for rake tasks.
What is the best way to achieve that?
Depending on your environment, Rake will log sql queries just like any Rails process will & in the same logfile. So on your dev box, check your log/development.log file - it will contain your Rake task's queries. If you want queries logged in production, set the log level in your Rake task to DEBUG, and make sure the rake task depends on :environment.
desc "Task with SQL logging"
task :test_log => :environment do
Rails.logger.level = Logger::DEBUG
Your code here...
end
Proper answer is to put this at the beginning of rake task:
ActiveRecord::Base.logger = Logger.new STDOUT
rake db:migrate --trace
The --trace will show details
echo '' > log/development.log
rake db:migrate:redo VERSION=20141017153933
cat log/development.log
I tried the above and couldn't get it to work. Syntax was fine, no errors, but no sql came to stdout (or the log). I'm using rails 3.2. I'm also running in a production environment.
To see the sql queries generated by my rake tasks, I used the technique found at http://eewang.github.io/blog/2013/07/29/how-to-use-rake-tasks-to-generate-migration-sql/
In particular, I just inserted this block in my task before the find() statements that generated the SQL queries I was intersted in:
ActiveRecord::Base.connection.class.class_eval do
# alias the adapter's execute for later use
alias :old_execute :execute
# define our own execute
def execute(sql, name = nil)
print "===== #{sql}\n"
old_execute sql, name
end
end
Then I could see the SQL on stdout. This is not my code - Eugene Wang came up with this technique.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With