Skip to content

Rails DB Rake Tasks

metaskills edited this page Sep 13, 2010 · 17 revisions

As of 2.3.6 of the adapter, we compliant to the rake task interfaces in the :db namespace of rails. That means for new developers that are working with a non-legacy DB that is accurately reflected by schema.rb can now use the standard rake tasks for just about everything except actually setting up the new/test databases.

The only problem is that the we have not yet committed patches yet upstream to rails to remove Windows specific command interpolation from their databases.rake task. So, we have to do two things. First, here is an extension to Rake that allows us to method chain tasks.

Next, here are the overrides for each task in a default rails application. Some notes about them – first, we are not supporting any native SQL structure dump. No scptxfr or anything like that. Because we have a mixed dev community these are left blank. The override rake task finally allows you to build your own platform specific task now without rails core task blowing up on us. The main task is db:test:purge. We now use our own #recreate_database method which basically just removes all the tables prior to a schema load. If the database is not there and/or an exception is raised, it calls #recreate_database! with the database name from your configuration. The bang method will attempt to create your database. Hopefully the connection user has perms for this.

An Example That Also Uses Clones A Legacy Database For Testing.

I use this on my SQL Server 2000 database to clone a legacy database that can not be represented by the schema.rb due to views, stored procedures, and many other things. This solution assumes two important things. First that you are developing your rails application from a unix’y system, who doesn’t? Second that you have taken the time to instally Cygwin and OpenSSH on your target development Windows database box. I wont even cover that topic, consult your local Google index.

OK, assuming that is done, here is the new databases.rake task. A few key points about it. It uses Net::SSH to open a connection to your windows box and assumes osql and scptxfr are installed on your box and in the Cygwin path. Using these commands it dump a series of files used to create the structure of the database. If you have custom file groups (these do not play well with test dbs, customize the #my_db_filegroups method. When importing the structure into a new “…_test” database, it will remove foreign key constraints. Finally it will copy the schema migrations over from development. This way running “rake test” will only clone the db if needed, since this can be a lengthy process, 2-5 minutes depending on your legacy DB size.