Monday, November 13, 2006

Rails: Get the schema_info version number from Rake

Recently a coworker asked if there was a simple way to get the current version out of the schema_info table. Of course, one simple answer is to simply look in the database.

However, if you want to quickly pull the version from a command line, this rake task should do the trick*:
namespace :db do
desc "Returns the current schema version"
task :version => :environment do
puts "Current version: " + ActiveRecord::Migrator.current_version.to_s
end
end
* 2nd version submitted by Doug as a comment.


Comments:
Ahh cute. Rake is a lovely thing indeed :)
 
Maybe it's cause I'm on edge rails, but the return value from connection.execute(select) doesn't have a result method for me. This is the code that's working for me instead:

namespace :db do
desc "Returns the current schema version"
task :version => :environment do
connection = ActiveRecord::Base.connection
select = "select * from schema_info"
version = connection.execute(select).first["version"]
puts "Current version: #{version}"
end
end

(sorry don't know how to get whitespace formatting to work in blogger comments...)
 
Jacob, what DB are you using? My example (probably poorly) assumes postgresql.
 
What about just using ActiveRecord::Migrator.current_version?
 
The last line of output from script/about lists the current schema revision. Setting RAILS_ENV allows you to query a particular environment's database.
 
Doug, thanks, I'll update the entry.

Jamie, I've never used script/about, thanks for pointing that out.
 
Just to be sure, I like to wrap that in a begin/rescue block

begin
puts 'current version is ' + ActiveRecord::Migrator.current_version}.to_s
rescue
puts 'database has not been migrated yet: ' + $!.to_s
end
 
Thanks for this tip. I used it as a starting point so I can do:

#going backwards
rake db:rollback:4

# going forward
rake db:rollback:-3

It's on my blog if you're curious.
 
And, much later, I turned this up while looking to do the same thing. I snagged the implementations offered by Doug and ncryptic and included them in a plugin called GenerallyUseful (with full credit to them and this post for the code).

Thanks for the post!
 
Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?