Specifying the output file for a rails schema dump

The other day I was working with a multi-database rails application, and I needed to generate a schema.rb for a secondary database. I assumed that the db:schema:dump rake task could probably take an argument to specify the output filename. But if this is documented anywhere, I could not find it. So I decided take a look at the source for that task. However, I don’t look at the rails source very often and I had trouble finding the source for that particular rake task. I did a quick google search to see if there was a nifty programmatic way to find the source location for a rake task. As I found out in this post, there is. From a rails console, you can execute something like the following.

> require 'rake'
 => ["RAKEVERSION", "FileList", "RakeFileUtils"] 
> task_name ='db:schema:dump'
 => "db:schema:load" 
> Rails.application.load_tasks
> Rake.application[task_name]
 => [["./gems/activerecord/lib/active_record/railties/databases.rake", 324]] 

Pretty cool. From there it was easy to find the source for the task.

desc "Create a db/schema.rb file that can be portably used against any DB supported by AR"
    task :dump => :environment do
      require 'active_record/schema_dumper'['SCHEMA'] || "#{Rails.root}/db/schema.rb", "w") do |file|
        ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file)

From line 4, it is very easy to see that the parameter SCHEMA will override the usual schema.rb filename. so you can do something like:

> rake db:schema:dump SCHEMA=/tmp/schema2.rb

I never would have guessed the parmeter name was SCHEMA, since you are specifying a filename rather then a schema name.

Leave a Reply

Your email address will not be published. Required fields are marked *