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

后端 未结 5 1273
失恋的感觉
失恋的感觉 2020-12-04 19:00

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

相关标签:
5条回答
  • 2020-12-04 19:45

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

    0 讨论(0)
  • 2020-12-04 19:47

    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.

    0 讨论(0)
  • 2020-12-04 19:47

    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 讨论(0)
  • 2020-12-04 20:00

    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
    
    0 讨论(0)
  • 2020-12-04 20:06

    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.

    0 讨论(0)
提交回复
热议问题