Is "with_connection" necessary with "exec_query"?

Viewed 475

I'm occasionally getting PG::TRDeadlockDetected on a Rails with PostgreSQL app (served via Passenger/Nginx) and traced it down to places in the code which use ActiveRecord::Base.connection.exececute.

In order to fix this, I'm replacing .execute with .exec_query or .exec_update as per what the docs recommend. However, it's not really made clear whether ActiveRecord::Base.connection.exec_query gets the connection from the connection pool or not.

  • When using ActiveRecord::Base.connection.exec_query in a Rails controller, does it have to be wrapped with ActiveRecord::Base.connection_pool.with_connection? (my guess: yes)
  • When using ActiveRecord::Base.connection.exec_query outside of the context of a request (say a Rake tasks executed as cronjob), does it have to be wrapped with ActiveRecord::Base.connection_pool.with_connection? (my guess: yes)

And if wrapping is necessary, are there shorter alternatives compared to:

ActiveRecord::Base.connection_pool.with_connection do |connection|
  connection.exec_update "REINDEX INDEX my_complex_index"
end

(my guess: no)

Thanks for your hints!

0 Answers
Related