Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a new ActiveRecord Connection Pool with Ruby on Rails?

I have a RoR app that works great with the main RoR database. I also want to connect to arbitrary databases in a way such that I won't recreate the database connection with each new HTTP request. From my research it looks like a connection pool is the way to go.

However, I am having trouble figuring out how to create the pool itself:

config = ActiveRecord::ConnectionAdapters::ConnectionSpecification.new( {
          "adapter"  => "postgresql",
          "host"     => "localhost",
          "port"     => 9000,
          "database" => "foo_test",
          "username" => "foo",
          "password" => "bar",
          "pool"     => "5",
          "timeout"  => "3000"
        })

my_connection_pool = ActiveRecord::ConnectionAdapters::ConnectionPool.new(config)

This errors with NameError: uninitialized constant ActiveRecord::ConnectionAdapters::ConnectionSpecification. Interstingly ActiveRecord::ConnectionAdapters::ConnectionPool works fine (but doesn't have the right config object).

What do I do here?

And also, are these the right things to be using to solve my problem?

like image 620
Some Guy Avatar asked Mar 27 '14 06:03

Some Guy


People also ask

How do you create a database connection pooling?

Create an instance of GenericObjectPoolConfig and set maximum idle, minimum idle and maximum connection properties. Now initialize ObjectPool using instances created in step 2 and step 3. Now set pool as an instance of PoolableConnectionFactory. Finally, initialize an instance of DataSource.

What is connection pool in rails?

A connection pool synchronizes thread access to a limited number of database connections. The basic idea is that each thread checks out a database connection from the pool, uses that connection, and checks the connection back in.

What is ActiveRecord :: Base in Ruby?

in Ruby, :: accesses static class or module constants. ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.


1 Answers

Depending on your use case, Rails might do this for you automatically. Each ActiveRecord::Base subclass looks up the inheritance chain to find its pool, so

class Foo < ActiveRecord::Base
end

Uses the ActiveRecord::Base connection pool, but

class Bar < ActiveRecord::Base
  establish_connection database: 'some_other_db'
end

class BarSub < Bar
end

would both connect to 'some_other_db' using the Bar pool.

I don't remember exactly, but I think every time you use ActiveRecord::Base.establish_connection (or establish_connection on any subclass) it creates a new pool. Doing otherwise would be absurd!

A possibly helpful SO post on establish_connection

like image 142
Woahdae Avatar answered Oct 11 '22 09:10

Woahdae