Skip to content

Instantly share code, notes, and snippets.

@mikecmpbll
Created December 12, 2014 10:11
Show Gist options
  • Save mikecmpbll/b5e7a163b619290a33a7 to your computer and use it in GitHub Desktop.
Save mikecmpbll/b5e7a163b619290a33a7 to your computer and use it in GitHub Desktop.
Threaded query to multiple DBs
def run(scope, dbs)
results = {}
threads = []
dbs.each do |db|
threads = Thread.new do
while_connected_to(db) do |conn|
query_model = scope.model
puts "USING CONN: #{conn.object_id} as opposed to #{Student.connection.object_id}"
result_set = conn.select_all(scope.to_sql, "My Super Special Fab Load")
column_types = result_set.column_types
results[db] = result_set.map { |record| query_model.instantiate(record, column_types) }
end
end
end
threads.join
results
end
def while_connected_to(db, &b)
conf = ActiveRecord::ConnectionAdapters::ConnectionSpecification.new(Rails.configuration.database_configuration[db.to_s], "mysql2_connection")
pool = ActiveRecord::ConnectionAdapters::ConnectionPool.new(conf)
pool.with_connection(&b)
pool.clear_reloadable_connections!
pool.disconnect!
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment