Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Loading schema into secondary database

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.

like image 594
JohnMetta Avatar asked Jun 07 '26 18:06

JohnMetta


1 Answers

How to dump schema:

ActiveRecord::Base.establish_connection "custom_db_#{Rails.env}".to_sym 
File.open Rails.root.join('db/schema_custom_db.rb'), 'w:utf-8' do |file| 
  ActiveRecord::SchemaDumper.dump ActiveRecord::Base.connection, file
end

How to load schema:

ActiveRecord::Tasks::DatabaseTasks.load_schema_current :ruby, Rails.root.join('db/schema_custom_db.rb'), "custom_db_#{Rails.env}"
like image 192
vano468 Avatar answered Jun 09 '26 07:06

vano468



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!