multiple_connection_handler

A gem for Rails that provides a class, MultipleConnectionHandler, that allows for access to connections to any databases in the database.yml file for your Rails application. Quick and dirty implementation to let us do dirty things.

Full disclosure

Implemented as a singleton accessed solely through the class methods. Some instance methods are exposed, but you should NOT use them directly. You should also NOT try to instantiate multiple MultipleConnectionHandler objects.

Have NOT evaluated any thread-safety of this code. In fact, it’s probably not safe to multithread code that’s will use the MultipleConnectionHandler, as there is no locking on cached db connections.

NOTE NOTE NOTE NOTE NOTE NOTE
-----------------------------
This should only be used if you're being bad and are executing queries via
raw SQL, and not using ActiveRecord methods. If you just want to specify
different databases for your various models, see ActiveRecord::Base
documentation.

I admit up front this is pretty hacky in how we’re piggy-backing on ActiveRecord’s connection pooling and ConnectionHandler. So please read through the code (esp. the connection() instance method) before proceeding.

Example (yes, this is a terrible example)

dev_migrations = MultipleConnectionHandler.connection(:development).execute(

"SELECT * FROM schema_migrations")

staging_migrations = MultipleConnectionHandler.connection(:staging).execute(

"SELECT * FROM schema_migrations")

if dev_migrations != staging_migrations

Rails.logger.error "Can't push data from staging to dev right now cause " +
                   "they're on different migrations"

end

Testing

You may notice the lack of unit tests. Yeah, we just tested this manually. Probably the best, as you basically need acess to multiple dbs in order to test whether this functionality is working. I guess if you’d like, you could create some models tied to different db instances, use this to directly modify those models and then use the models to verify the changes. Meh.