transaction_isolation icon indicating copy to clipboard operation
transaction_isolation copied to clipboard

Calls to establish_connection inside the block break final execute call in isolation_level

Open patakijv opened this issue 7 years ago • 1 comments

I have tried using this to wrap long running background jobs that process reports to help with deadlock issues and concurrency in our Rails 3.2 project.

Within our report processing process, a call is made to a method that performs a temporary connection to another database and then returns returns the base connection to the main database. It does this by using the establish_connection method and then another establish_connection to get back to the original main database in that method's ensure block.

The problem appears to arise due to the fact that establish_connection calls remove_connection and because of that, it makes the execute call in isolation_level's ensure block fail because @connection is nil. The failure message refers to the fact that query is not a method on nil which is referring to @connetion.query called in execute.

ActiveRecord::StatementInvalid: NoMethodError: undefined method `query' for nil:NilClass:

The top level method that calls the process runs without any errors like this and has been for a while if it is not part of the isolation_level block. It is only when this database connection switching occurs inside the block that it becomes a problem.

Perhaps a fix is to call connect if @connection.nil? in the ensure block and that would resolve this?

patakijv avatar Oct 18 '17 18:10 patakijv

Correcting a previous comment where a patch put in place appeared to have solved the problem by adding connect if @connectin.nil? into the ensure block of isolation_level however after further investigation, this really appears to be a new connection because if I test isolation level again in the ensure block before changing it back to the session default, it is already back to the session default and not what it was changed to - therefore it must be a new connection all together. A different approach needs to be considered to resolve this.

patakijv avatar Oct 18 '17 19:10 patakijv