SQL output from ActiveRecord migration without executing it (not rails!)

There are tons of questions similar to this one that talk about rails plugins as a solution, but I don't use rails, read on for

I have a Rakefile in a sinatra project that allows me to rake db:migrate . It will do my migration perfectly, but I would like to pass this flag (or write a new rake command), which does the same, but outputs SQL to STDOUT and does not commit the changes to the database. Does anyone know how to do this?

My first thought was to try running ActiveRecord and see if I can get SQL at all, but that doesn't work! Any ideas?

 namespace :db do task :migrate_sql do require 'logger' ActiveRecord::Base.logger = Logger.new(STDOUT) Rake::Task['db:migrate'].invoke # This does the migration and doesn't output SQL - so no good! end end 
+4
source share
1 answer

I think there is no easy way to do this for the following reasons:

  • up , down and change are methods that execute other methods; there is no global migration query string that is created and executed
  • no operator methods ( add_column , etc.) expose their expressions as strings; as I understand it, they are implemented as connection adapter methods, and, for example, the mysql adapter has the add_column_sql method , and the postgresql adapter is not, and its sql is a variable inside the add_column method

So, if you really need this functionality, I think your best option is to copy sql from the log.

0
source

Source: https://habr.com/ru/post/1488018/


All Articles