ankane/multiverse

It is possible manually change DB connection with multiverse?

Closed this issue · 2 comments

Hi @ankane, thanks for elegant solution!

I have two databases that work with multiverse. All of models linked with first DB, but some necessary data stored in the second DB. I need make very complex SQL requests to second DB. I can't write this requests as model methods because it make my models literally dirty. Then i wrap requests code into app/queries/query_...rb like this:

class SomeReport << Report
  attr_accessor :query
  
  def initialize(query)
    ActiveRecord::Base.establish_connection :"second_db_#{Rails.env}"
    @connection = ActiveRecord::Base.connection
    @query = query.downcase
  end

  def build_request
    [... giant SQL from my DBA with @query ...]
  end

  def execute_statement(sql)
    result = @connection.execute(sql).to_a
    if result.present?
      return result
    else
      return []
     end
  end

  def call
     sql = build_request
     result = execute_statement(sql)
   end

Next, in the controller i call SomeReport and get data but after it Rails change connection to from first to second DB and all of my models which were use connection for first DB falling because not found tables from first DB in the second.

Of course, after call SomeReport i can do reconnect to first DB but maybe i will can do it more simple with multiverse? How to use multiverse not in models?

Hey @creadone, if you use Multiverse, it’ll create a SecondDbRecord abstract model that calls establish_connection once. Then you can use SecondDbRecord.connection.execute/select_all to query it.

@ankane, thanks for explain! It helped!