Joseph
Joseph

Reputation: 3959

rake db:schema:dump is not producing schema for all databases

I have this project and I need to integrate a bunch of databases into my Rails project.

This is the database configuration that I have to work with.

$ nano config/database.yml

production:
  adapter: mysql2
  reconnect: true
  pool: 5
  username: user_xyz
  password: 123456
  database: database1
  host: localhost


  database_2:
    adapter: mysql2
    reconnect: false
    pool: 5
    username: user_xyz
    password: 123456
    database: database2
    host: 192.168.2.100

  database_3:
    adapter: mysql2
    reconnect: false
    pool: 5
    username: user_xyz
    password: 123456
    database: database3
    host: 192.168.2.101

  database_4:
    adapter: mysql2
    reconnect: false
    database: database4
    pool: 5
    username: user_xyz
    password: 123456
    host: 192.168.2.102

I need to update the schema inside db/schema.rb but unfortunately it's only producing the schema for production (database1).

$ RAILS_ENV=production bundle exec rake db:schema:dump

I can't just run this as it complains:

$ bundle exec rake db:schema:dump
rake aborted!
database configuration does not specify adapter

What do I need to do to get all of these databases into db/schema.rb?

Upvotes: 1

Views: 1196

Answers (2)

Sean Huber
Sean Huber

Reputation: 3985

Austio's answer is a good one. Here is some extra detail on how to implement a solution. Create a new rake file, e.g., lib/tasks/schema_dump.rake, and add the following contents:

namespace :db do
  namespace :schema do
    desc 'dumps the schema of database_1 to db/schema_db1.rb'
    task :dump_db1 => :environment do
      ActiveRecord::Base.establish_connection 'database_4'
      File.open(Rails.root.join('db', 'schema_db1.rb'), 'w') do |file|
        ActiveRecord::SchemaDumper.dump ActiveRecord::Base.connection, file
      end
    end
  end
end

Now when you run rake db:schema:dump it'll dump the schema of your primary database to db/schema.rb (like traditional Rails). But when you run rake db:schema:dump_db1, it'll dump the schema of your database_1 block into db/schema_db1.rb.

You can create similar tasks for your other database blocks and have a schema file for each database.

Upvotes: 5

Austio
Austio

Reputation: 6075

You will need to establish a connection to each database that you would like to schema dump on. Here is example for database_4

ActiveRecord::Base.establish_connection 'database_4'

Then when you run schema dump, it will dump the current database you have a connection with. I'm not sure if the rake task has arguments to copy it to a different file name, so you may have to rename the file.

Upvotes: 1

Related Questions