How can I change the connection of one thread? I want do that:
slow query process at background
Thread.new do
100000.times { User.first.update_attributes(some_field: (rand * 100).to_i) }
end
more slow query process
100000.times { User.first.update_attributes(some_field_2: (rand * 100).to_i) }
``
I want that these 2 threads runs asynchronously but I discover that Rails uses one single connection to do this. I had tried the below too, but although Rails create a new connection, the “User” don’t use it:
slow query process at background
Thread.new do
conn = ActiveRecord::Base.connection_pool.checkout()
100000.times { User.first.update_attributes(some_field: (rand * 100).to_i) }
ActiveRecord::Base.connection_pool.checkin(conn)
end
``
I had tried to set “ActiveRecord::Base.connection = conn” but didn’t work too.
It is possible to each thread have your own connection? How can I set the thread connection?
Ok, I got it. But I had to make a little hack on “retrieve_connection” to achieve this:
module ActiveRecord
module ConnectionAdapters
class ConnectionHandler
def retrieve_connection(klass) #:nodoc:
pool = retrieve_connection_pool(klass)
raise ConnectionNotEstablished, “No connection pool for #{klass}” unless pool
conn = Thread.current[“connection”] || pool.connection
raise ConnectionNotEstablished, “No connection for #{klass} in connection pool” unless conn
conn
end
end
end
end
``
I just modify the “conn = pool.connection” to “conn = Thread.current[“connection”] || pool.connection”. This allows me to define the connection using a custom thread variable. With this hack, my code looked like this:
slow query process at background
Thread.new do
Thread.current[“connection”] = ActiveRecord::Base.connection_pool.checkout()
100000.times { User.first.update_attributes(some_field: (rand * 100).to_i) }
ActiveRecord::Base.connection_pool.checkin(Thread.current[“connection”])
end
more slow query process
100000.times { User.first.update_attributes(some_field_2: (rand * 100).to_i) }
``
This meets my needs, but I wonder if there isn’t a native method to change the connection of a thread. The way I’ve done was so ugly