secondbase icon indicating copy to clipboard operation
secondbase copied to clipboard

Accessing both databases in migrations

Open aaricpittman opened this issue 6 years ago • 5 comments

I'm trying to access both databases in a secondbase migration to transfer data between the two. Unfortunately, ActiveRecord::Base.connection is pointing at the same connection as SecondBase::Base.connection. Thoughts on how I would do that?

aaricpittman avatar Mar 14 '18 20:03 aaricpittman

What does your database config look like?

sarsena avatar Mar 14 '18 21:03 sarsena

This is the rough structure.

development:

test:

production:

second_base:
  development:

  test:

  production:

aaricpittman avatar Mar 14 '18 21:03 aaricpittman

I have it working with something like the following in my migration class.

class PrimaryServerBase < ActiveRecord::Base
  self.abstract_class = true
  establish_connection Rails.application.config.database_configuration[Rails.env]
end

class PrimaryServerModel < PrimaryServerBase
end

aaricpittman avatar Mar 14 '18 21:03 aaricpittman

Any reasons that would be a bad idea?

aaricpittman avatar Mar 14 '18 22:03 aaricpittman

@aaricpittman That looks perfectly fine. Even when an application has one database and doing some ETL in a migration, I always declare a local model in the migration to isolate behavior. In your case you have a need to talk to two models that spans DBs and hence you would need to use establish_connection like you are doing above.

The only issue I can think of is declaring an explicit second transaction. But that is only important if you are writing to both DBs during the migration. If your PrimaryServerBase connection is read-only and you are writing to Secondbase - you are already guaranteed a transaction due to the current migration. If not, just open a transaction block on your other model. Sound good?

metaskills avatar Mar 15 '18 02:03 metaskills