How does one load a schema into a secondary database? It seems that the ability to set a secondary database connection while maintaining the main ActiveRecord::Base.connection
is not supported in Rails.
Domain Definition
We have models using a secondary database. Our primary database is MySQL, the secondary database is PostgreSQL. To use the ActiveRecord documentation's example:
|
+-- Book
| |
| +-- ScaryBook
| +-- GoodBook
+-- Author
+-- BankAccount
Where Book
is abstract and uses establish_connection
to connect to Postgres.
When dealing with the database, we can either use ActiveRecord::Base.connection
or Book.connection
.
Schema dump
To wit: Rails database tasks in the schema
namespace allow us to dump the schema as so:
ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file)
Which would allow me to do the following:
ActiveRecord::SchemaDumper.dump(Book.connection, file)
Problem: Schema Load
However, the load task holds no such ability. It merely evaluates the schema file as a whole:
desc 'Load a schema.rb file into the database'
task :load => :environment do
file = ENV['SCHEMA'] || "#{Rails.root}/db/schema.rb"
if File.exists?(file)
load(file)
else
abort %{#{file} doesn't exist yet. Run "rake db:migrate" to create it then try again. If you do not intend to use a database, you should instead alter #{Rails.root}/config/application.rb to limit the frameworks that will be loaded}
end
end
Where the schema file runs ActiveRecord::Schema.define
without the connection definition. (Noting that the define method runs in the context of "the current connection adapter").
How do I change that "current connection adapter" without doing an ad-hoc ActiveRecord::Base.establish_connection
, which is not what I want to do? I essentially want to run ActiveRecord::Schema.define
in the context of Book.connection
.
Edit: I'll note that I need a programmatic solution outside of running rake tasks, which is why I'm looking within the rake tasks to see what they're actually doing.