Different database connections per thread, same model?

I would like to be able to connect to different databases on separate threads and query the same model in each database. For example, without streams, I can do something like:

# given 'db1' and 'db2' are rails environments with connection configurations
['db1', 'db2'].each do |db|
  Post.establish_connection(db)

  Post.where(title: "Foo") 
end
Post.establish_connection(Rails.env)

      

This will span two databases and search for posts in each one. I need to be able to do this in parallel using streams, for example:

['db1', 'db2'].each do |db|
  threads = Thread.new do
    Post.establish_connection(db)

    Post.where(title: "Foo")
  end 
end
threads.join
Post.establish_connection(Rails.env)

      

But it is quite clear that creating a new connection pool in each thread using the global Post class is not thread safe.

What I would like to do is set up a new connection pool on each thread. I got to this:

['db1', 'db2'].each do |db|
  threads = Thread.new do
    conf = ActiveRecord::ConnectionAdapters::ConnectionSpecification.new(Rails.configuration.database_configuration[db], "mysql2_connection")
    pool = ActiveRecord::ConnectionAdapters::ConnectionPool.new(conf)
    pool.with_connection do |con|
      # problem is, I have this con object but using the Post class still uses the thread default connection.
      Post.where(title: "Foo")
    end
  end 
end
threads.join

      

There must be a way to change the connection pool that ActiveRecord uses based on thread by thread?

+3


source to share





All Articles