Friday, January 9, 2009

Use jruby to dump DB schema to ruby

Problem:

I have a database that rails doesn't have an easy way to connect to.

Solution:

Use jruby & JDBC

Requirements:

jruby
activerecord
activerecord-jdbc-adapter
jdbc driver for the database you want to connect to

Resources:

http://jruby-extras.rubyforge.org/activerecord-jdbc-adapter/

Steps:

jruby -S gem install activerecord
jruby -S gem install activerecord-jdbc-adapter

Put the jdbc jar in Classpath for jruby. e.g. inside C:\work\tools\jruby-1.1.6\lib

Run this script:

require 'rubygems'
gem 'activerecord-jdbc-adapter'
require 'jdbc_adapter'
require 'active_record'

ActiveRecord::Base.establish_connection(
:adapter => 'jdbc',
:driver => 'com.microsoft.sqlserver.jdbc.SQLServerDriver',
:url => 'jdbc:sqlserver://localhost:1433;DatabaseName=FineosSixApp',
:username => 'username',
:password => 'password'
)

ActiveRecord::SchemaDumper.dump


To load the schema into say mysql
require 'rubygems'
require 'active_record'

ActiveRecord::Base.establish_connection(
:adapter => "mysql",
:host => "localhost",
:username => 'username',
:password => 'password',
:database => 'database'
)

load('schema.rb')

Future Improvements:

Instead of using jruby on command line, create an ant task that uses jruby.jar and do the same thing.
Basically integrating the schema dump into the build file.

It'll be useful to store the client code base along with schema that runs with the code base.

No comments: