Skip to content

Instantly share code, notes, and snippets.

@spalenza
Forked from xaviershay/migration_sql.rb
Last active May 23, 2019 20:33
Show Gist options
  • Save spalenza/91e5a0e9b50934bae2b1ad82a066a5da to your computer and use it in GitHub Desktop.
Save spalenza/91e5a0e9b50934bae2b1ad82a066a5da to your computer and use it in GitHub Desktop.
Get SQL output from a Rails migration
#!/usr/bin/env ruby
require_relative 'config/environment'
path = ARGV.shift || raise("specify migration as first argument")
require_relative path
filename = File.basename(path, ".rb")
timestamp, name = filename.split("_", 2)
name = name.camelcase
ActiveRecord::Migration.verbose = false
module Wrapper
def execute(sql, *args)
if sql =~ /^ALTER\ TABLE|((CREATE|DROP) (TABLE|VIEW))|INSERT|INDEX/i
puts sql.gsub(/`/, '') + ";"
else
super
end
end
end
ActiveRecord::Base.connection # Needed to load Mysql2Adapter
ActiveRecord::ConnectionAdapters::Mysql2Adapter.prepend(Wrapper)
migration = name.constantize
migration.migrate(:up)
ActiveRecord::SchemaMigration.create!(:version => timestamp.to_s)
@spalenza
Copy link
Author

./migration_sql.rb db/migrate/20190523201104_add_index_to_wallets.rb

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment