Mohamed Hafez
Mohamed Hafez

Reputation: 8691

closing ActiveRecord connection on a dead thread

If a thread dies or I have to kill a thread that is using an ActiveRecord connection, how do I make sure that the ActiveRecord connection is returned back to the pool? I keep getting errors like

DEPRECATION WARNING: Database connections will not be closed automatically, please close your database connection at the end of the thread by callingcloseon your connection. For example: ActiveRecord::Base.connection.close

but how do I make sure this happens on a thread that dies unexpectedly, or one that call Thread.kill on?

Upvotes: 1

Views: 1605

Answers (1)

Abdo
Abdo

Reputation: 14051

Ensure connection closing =)

Thread.new do
  begin
     raise "foo"
  ensure
     begin
        if (ActiveRecord::Base.connection && ActiveRecord::Base.connection.active?)
           ActiveRecord::Base.connection.close
        end
      rescue
      end
  end
end

Upvotes: 3

Related Questions