Created
August 28, 2012 15:12
-
-
Save kitallis/3498949 to your computer and use it in GitHub Desktop.
rebase migrations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace :migrations do | |
DB_PATH = ActiveRecord::Migrator.migrations_path | |
SEPARATOR = " --- " | |
UPTO = ENV['upto'] | |
def run_command(command) | |
%x(#{command}).tap do |result| | |
status = $? | |
unless status.success? | |
raise "Command Error -- (#{status.exitstatus}): [#{command}]" | |
end | |
result | |
end | |
end | |
def generate_schema_dump | |
Rake::Task["db:schema:dump"].invoke | |
end | |
def run_migrations | |
Rake::Task["db:migrate"].invoke | |
end | |
def ordinal_position_of_migration | |
output = run_command("ls #{DB_PATH} | awk '{ print NR \"#{SEPARATOR}\" $0 }'") | |
output.split("\n"). | |
map { |migration| migration.split(SEPARATOR) }. | |
select { |migration| migration[1] =~ Regexp.new(UPTO) }.flatten.first | |
end | |
def remove_list_of_migrations | |
upto = ordinal_position_of_migration | |
run_command("ls #{DB_PATH}/* | head -n#{upto} | xargs rm -v") | |
end | |
def timestamp_of_migration | |
File.basename(UPTO.split("_").first, ".rb") | |
end | |
def extract_schema_dump | |
dump = StringIO.new | |
ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, dump) | |
dump.string. | |
split("\n"). | |
reject { |line| line =~ /^ActiveRecord::Schema.define/ }. | |
join("\n") | |
end | |
def indented_schema_dump(times) | |
extract_schema_dump.split("\n"). | |
map { |line| line.insert(0, " " * times) }. | |
join("\n") | |
end | |
def create_migration_file | |
template = <<-EOS | |
class RebaseOldMigrations < ActiveRecord::Migration | |
def change | |
#{indented_schema_dump(2)} | |
end | |
EOS | |
file = timestamp_of_migration + "_rebase_old_migrations.rb" | |
migration_file = File.join(DB_PATH, file) | |
File.open(migration_file, 'w') { |mf| mf.write(template) } | |
end | |
desc "Squash/Rebase all migrations upto a certain point" | |
task :squash do | |
puts "* Generating schema dump..." | |
generate_schema_dump | |
puts "* Removing old migrations..." | |
remove_list_of_migrations | |
puts "* Creating squashed migration file..." | |
create_migration_file | |
puts "* Running the migrations as a sanity check..." | |
run_migrations | |
puts "* Done. See #{DB_PATH}." | |
end | |
task :rebase => :squash | |
end |
Author
kitallis
commented
Sep 16, 2012
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment