Skip to content

Commit

Permalink
Fix connection leak when no connection open in the current thread (#22)
Browse files Browse the repository at this point in the history
Follow-up for #21
Fixes #20 (specifically #20 (comment))

Method `connected?` checks if there are any connections open, even in a different thread,
while `active_connection?` checks for connection owned by current thread.

See:
 - https://api.rubyonrails.org/v5.2.3/classes/ActiveRecord/ConnectionAdapters/ConnectionPool.html#method-i-active_connection-3F
 - https://api.rubyonrails.org/v5.2.3/classes/ActiveRecord/ConnectionAdapters/ConnectionPool.html#method-i-connected-3F
  • Loading branch information
Envek authored Jun 20, 2022
1 parent 9056d71 commit a241e98
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
2 changes: 1 addition & 1 deletion lib/after_commit_everywhere.rb
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ def register_callback(connection: nil, name:, without_tx:, callback:)
# Helper method to determine whether we're currently in transaction or not
def in_transaction?(connection = nil)
# Don't establish new connection if not connected: we apparently not in transaction
return false unless connection || ActiveRecord::Base.connection_pool.connected?
return false unless connection || ActiveRecord::Base.connection_pool.active_connection?

connection ||= default_connection
# service transactions (tests and database_cleaner) are not joinable
Expand Down
10 changes: 9 additions & 1 deletion spec/after_commit_everywhere_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
subject do
example_class.new.after_commit do
handler.call
expect(ActiveRecord::Base.connection.transaction_open?).to(be_falsey) if ActiveRecord::Base.connection_pool.connected?
expect(ActiveRecord::Base.connection.transaction_open?).to(be_falsey) if ActiveRecord::Base.connection_pool.active_connection?
end
end

Expand Down Expand Up @@ -186,6 +186,14 @@
expect { subject }.not_to change { ActiveRecord::Base.connection_pool.connections.size }
end
end

context "when connection to the database has been established in another thread" do
before { ActiveRecord::Base.connection }

it "doesn't leak connections" do
expect { Thread.new { subject }.join }.not_to change { ActiveRecord::Base.connection_pool.connections.size }
end
end
end

describe "#before_commit" do
Expand Down

0 comments on commit a241e98

Please sign in to comment.