Skip to content

Instantly share code, notes, and snippets.

@rwilcox
Created September 10, 2010 16:12
Show Gist options
  • Save rwilcox/573910 to your computer and use it in GitHub Desktop.
Save rwilcox/573910 to your computer and use it in GitHub Desktop.
Keep migrations straight when you (a) have a lot of them or (b) use data_migration plugin
namespace :db do
namespace :migrate do
desc "Do you need to run db:migrate or db:data:migrate? `rake db:migrate:incoming_check'[SHA1 RANGE]'`"
task :incoming_check, :git_refs, :needs => :environment do |task, args|
# User story:
# as a developer, I should be able to see what migrations have changed
# in a series of commits -- what new ones and what old ones - so I can know
# what migration commands I need to run (rake db:migrate,
# rake db:data:migrate PATH=..., (if you're using the data_migration plugin!) or maybe just alert you that
# you should complain to your fellow devs because someone changed an old migration!)
#
# Assumes you're using git. This is github after all.
#
# Example:
# $ git pull
# ......
# 931ab31..304eee2 master -> master
# $ rake db:migrate:incoming_check"[931ab31..304eee2]"
# will return nothing if there are no migrations affected by that git sha1 range
# will tell you about new migrations or old migrations as appropriate
db_modified_files = `git diff --numstat #{args[:git_refs]} | cut -f3 - | grep db/`
db_modified_files.each do |current_file|
if current_file =~ /db\/.+\/(\d+)_.+\.rb/ # ok, it's a migration file (vs schema or something)
migration_version = $~[1]
res = ActiveRecord::Base.connection.execute("select COUNT(*) from schema_migrations WHERE version='#{migration_version}'")
if res.kind_of? Mysql::Result
# make MySQL results look like the results we get from sqlite. RPW 09-13-2010
out = []
res.each {|r| out << r}
res = out
end
if res[0][0] == 0
puts "NEW MIGRATION: #{current_file}"
else
puts "OLD MIGRATION, CHANGED: #{current_file}"
end
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment