Skip to content

Commit

Permalink
make active_connection? return true only if there is an open connecti…
Browse files Browse the repository at this point in the history
…on in use for the current thread. fixes rails#5330
  • Loading branch information
tenderlove committed Mar 8, 2012
1 parent 263d842 commit cff19cf
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -95,10 +95,11 @@ def connection
@reserved_connections[current_connection_id] ||= checkout
end

# Check to see if there is an active connection in this connection
# pool.
# Is there an open connection that is being used for the current thread?
def active_connection?
active_connections.any?
@reserved_connections.fetch(current_connection_id) {
return false
}.in_use?
end

# Signal that the thread is finished with the current connection.
Expand Down
42 changes: 42 additions & 0 deletions activerecord/test/cases/connection_pool_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@
module ActiveRecord
module ConnectionAdapters
class ConnectionPoolTest < ActiveRecord::TestCase
attr_reader :pool

def setup
super

# Keep a duplicate pool so we do not bother others
@pool = ConnectionPool.new ActiveRecord::Base.connection_pool.spec

Expand All @@ -18,6 +22,44 @@ def setup
end
end

def teardown
super
@pool.disconnect!
end

def active_connections(pool)
pool.connections.find_all(&:in_use?)
end

def test_with_connection
assert_equal 0, active_connections(pool).size

main_thread = pool.connection
assert_equal 1, active_connections(pool).size

Thread.new {
pool.with_connection do |conn|
assert conn
assert_equal 2, active_connections(pool).size
end
assert_equal 1, active_connections(pool).size
}.join

main_thread.close
assert_equal 0, active_connections(pool).size
end

def test_active_connection_in_use
assert !pool.active_connection?
main_thread = pool.connection

assert pool.active_connection?

main_thread.close

assert !pool.active_connection?
end

def test_active_connection?
assert !@pool.active_connection?
assert @pool.connection
Expand Down

0 comments on commit cff19cf

Please sign in to comment.