customink / secondbase

Seamless second database integration for Rails.
MIT License
220 stars 30 forks source link

Accessing both databases in migrations #57

Closed aaricpittman closed 3 months ago

aaricpittman commented 6 years ago

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?

sarsena commented 6 years ago

What does your database config look like?

aaricpittman commented 6 years ago

This is the rough structure.

development:

test:

production:

second_base:
  development:

  test:

  production:
aaricpittman commented 6 years ago

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 commented 6 years ago

Any reasons that would be a bad idea?

metaskills commented 6 years ago

@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?