Problem Domain
Heroku Cedar stack, with multiple databases. RDS for main database, and Postgres for a second Analytics database. Server runs using the read/write RDS and Postgres databases. Nightly rake task, which are run in a different environment, needs to run a specific Resque queue in a read-only slave of the RDS database.
Postgres DB connection
For the record, all models in the Postgres database include:
module Trove::PostgresConnection
def self.included(base)
base.class_eval do
…set up Postgres database
end
end
end
This works fine, and, being a module injected into each class, does not get squashed by any changes to ActiveRecord::Base.connection
MySQL Connection
Defined using the Heroku RDS plugin. Connection is made to the read/write production database. Unfortunately, this connection is used regardless of environment. Thus, running a rake task on Heroku using RAILS_ENV=analytics rake some:task does not use this connection for ActiveRecord::Base:
analytics:
adapter: mysql2
encoding: utf8
database: dbase
username: uname
password: pword
host: read-only.uri.on.amazonaws.com
reconnect: true
port: 3306
Rather, it uses the connection string provided in the RDS connection:
puts Rails.env
-> 'analytics'
puts SomeModel.connection_config[:host]
-> read-write.uri.on.amazonaws.com
Took me a while to figure that out. Note to self: don't just look at environment, look at database host.
Current Workaround
# Perform an operation using another database connection in ActiveRecord
module SwapConnection
def with_connection_to(config, &block)
ActiveRecord::Base.connection.disconnect!
ActiveRecord::Base.establish_connection(config)
yield
end
end
require 'swap_connection'
class TroveCalculations
@queue = :trove_queue
def self.perform(class_name, id)
SwapConnection.with_connection_to(Rails.env) do
Do something in a given queue
end
end
end
Desired ability
Have something like this in the Procfile
troveworker: env RAILS_ENV=analytics QUEUE=trove_queue bundle exec rake resque:work
which actually uses the analytics database.yml config for that worker. We currently run our server with this Procfile, but it still uses the RDS database.