How to get Database Connection for Octopus shard?

1.5k views Asked by At

I am using the Octopus gem to do DB sharding in Rails.

How do I get the database connection specific to a shard. For example, I have a shard named "new_db" that I specified in my shards.yml. How do I get the db connection for it? The raw connection. I know how to update/insert to this shard, I just need the connection.

I tried the following with no avail. It just gives me the default connection I specified in my database.yml.

Octopus.using("new_db") do 
    connection = ActiveRecord::Base.connection

end
1

There are 1 answers

0
Francois On

If you have this behavior:

ActiveRecord::Base.connection.class
#=> ActiveRecord::ConnectionAdapters::PostgreSQLAdapter

It means that your connection is not established through Octopus.

You should have:

ActiveRecord::Base.connection.class
#=> Octopus::Proxy

instead...


As momoshu pointed out in this GitHub issue, it might be caused by your app using

 ActiveRecord::Base.establish_connection  

I believe that if you call establish_connection, Octopus stops proxying connections regardless of configuration in shards.yml or Octopus.enabled?.


Other lead

I wasn't able to make it work because the gem was at the top of my gemfile, oddly, moving gem 'ar-octopus' to the bottom of the gemfile made it work.