Friday, May 29, 2009

Copying schema to a new, non-test database

As far as I can tell, there's no easy way to copy the schema for one of our databases to a new database config entry. So, here's a quickie script that schleps schemata for you. (I would love someone to tell me "Oh, to do that, you just do X" and then demonstrate it: this is kind of ugly, though it's based on how the railties Rakefile does it...)

require 'stringio'

# We want to copy the schema from class h[:db] to the database entry
# named "#{h[:prefix]}#{RAILS_ENV}"
#
to_copy = [
{ :db => SomeUseDbAbstractClass,
:prefix => "evaldb_",
}
]

to_copy.each { |h|
db = h[:db]
prefix = h[:prefix]

# Place to stick the schema
s = StringIO.new()

# Dump the schema
ActiveRecord::SchemaDumper.dump(db.connection, s)

# Extract the schema
s.rewind
schema = s.string


# Grab the original connection... we'll need this in a bit.
conn_spec_original = UseDbPluginClass.get_use_db_conn_spec({})

# Grab the destination connection information
conn_spec = UseDbPluginClass.get_use_db_conn_spec(:prefix => prefix)


# SQLite3 doesn't like the ENGINEs we emit... scrubadub.
if conn_spec["adapter"] == "sqlite3"
schema.gsub!(/ENGINE=(MyISAM|InnoDB)/, '')
end


# Move the default AR connection over to our destination database
ActiveRecord::Base.establish_connection(conn_spec)

# Play back the "migration" schema dump
eval schema

# Restore connection to its proper home
ActiveRecord::Base.establish_connection(conn_spec_original)
}

No comments:

Post a Comment