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.

9 comments:

  1. Ahh cute. Rake is a lovely thing indeed :)

    ReplyDelete
  2. Anonymous10:29 AM

    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...)

    ReplyDelete
  3. Anonymous11:47 AM

    Jacob, what DB are you using? My example (probably poorly) assumes postgresql.

    ReplyDelete
  4. Anonymous12:30 PM

    What about just using ActiveRecord::Migrator.current_version?

    ReplyDelete
  5. Anonymous2:11 PM

    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.

    ReplyDelete
  6. Anonymous2:24 PM

    Doug, thanks, I'll update the entry.

    Jamie, I've never used script/about, thanks for pointing that out.

    ReplyDelete
  7. Anonymous6:48 PM

    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

    ReplyDelete
  8. Anonymous8:09 AM

    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.

    ReplyDelete
  9. 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!

    ReplyDelete

Note: Only a member of this blog may post a comment.