Deirdre Saoirse Moen

Sounds Like Weird

Rails, moving stuff from one db to another

07 April 2006

Sometimes, you want ActiveRecord to do all the heavy lifting of data conversion. Plus, then you can use all the stuff you want during the conversion.

#!/usr/local/bin/ruby

Copies stuff from old mysql db to new postgres db, including changing of icky

old int fields to shiny booleans.

require ‘rubygems’
require_gem ‘activerecord’

require ‘../app/models/survey.rb’
require ‘../app/models/topic.rb’

Read database config via YAML

@dbs = YAML::load(ERB.new(IO.read(“../config/database.yml”)).result)

connect to old db.

curr_db = @dbs[‘production-mysql’]
ActiveRecord::Base.establishconnection(:adapter => currdb[“adapter”],
:database => curr_db[“database”],
:host => curr_db[“host”],
:username => curr_db[“username”],
:password => curr_db[“password”])

read in all the records

@surveys = Survey.find(:all)

close the db

ActiveRecord::Base.remove_connection

change to postgres db.

curr_db = @dbs[‘production’]
ActiveRecord::Base.establishconnection(:adapter => currdb[“adapter”],
:database => curr_db[“database”],
:host => curr_db[“host”],
:username => curr_db[“username”],
:password => curr_db[“password”])

for survey in @surveys
s = survey.clone
s.save
end

close the db

ActiveRecord::Base.remove_connection


Related Posts