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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With