开发者

Is it possible to output the SQL change scripts that 'rake db:migrate' produces?

Is it possible to output the SQL change scripts that 'rake db:migrate' produ开发者_StackOverflow社区ces?


Building on @qarol but even cooler, add this Rake task to one of your Rake files:

task :log => :environment do
  ActiveRecord::Base.logger = Logger.new(STDOUT)
end

Then you can call ANY Rake task and have the output logged:

rake log db:migrate


You can create a Rake task in lib/tasks/:

namespace :db do
  desc 'Make migration with output'
  task(:migrate_with_sql => :environment) do
    ActiveRecord::Base.logger = Logger.new(STDOUT)
    Rake::Task['db:migrate'].invoke
  end
end

Then call rake db:migrate_with_sql to log the migration.


The SQL output is captured in your environment log file e.g. development.log


I put together the capture_migration_sql gem for this purpose. It will dump your migration SQL to files in db/migration_sql.

It's overkill if you just need to find a single SQL statement, but is great to have if your production process requires the raw SQL statements. It can also make reviewing complex database changes in code reviews a bit easier since there's no ruby -> SQL mental math required.


You can run preview SQL in rails console like this:

ActiveRecord::Base.connection.change_table(:events) do |t|
  t.integer :submission_id, default: 5, null: false
end
#=> ALTER TABLE `events` ADD `submission_id` int DEFAULT 5 NOT NULL

So, just prepend your ordinary migration methods with ActiveRecord::Base.connection. and you are good to go.

There is also rails console --sandbox mode which rollbacks changes after you close the console. Though check if it works for your project, somehow for our project with rails 5 + MySQL it doesn't roll back DDL changes.


If you have migration files ready, you can also run it directly:

ActiveRecord::MigrationContext.new("db/migrate").migrate
ActiveRecord::MigrationContext.new("db/migrate").rollback
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜