From 8e1360b7a74509fd5e045fdc12e01865be21bd08 Mon Sep 17 00:00:00 2001 From: coderrr Date: Wed, 14 Jan 2009 05:30:56 +0700 Subject: [PATCH] added using_connection method; like with_connection but sets it as default connection while inside the block --- .../abstract/connection_pool.rb | 19 +++++++++++++++++++ activerecord/test/cases/pooled_connections_test.rb | 19 +++++++++++++++++++ 2 files changed, 38 insertions(+), 0 deletions(-) diff --git a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb index 901b171..f08989a 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb @@ -116,6 +116,25 @@ module ActiveRecord checkin conn end + # Reserves a connection, sets it as the primary connection for the + # thread, and yields to a block. Ensures that the connection is checked + # back when it is finished. + def using_connection(&block) + return yield if Thread.current[:__AR__using_connection] + Thread.current[:__AR__using_connection] = true + + release_connection + with_connection do |conn| + begin + @reserved_connections[current_connection_id] = conn + yield + ensure + @reserved_connections.delete(current_connection_id) + Thread.current[:__AR__using_connection] = nil + end + end + end + # Returns true if a connection has already been opened. def connected? !@connections.empty? diff --git a/activerecord/test/cases/pooled_connections_test.rb b/activerecord/test/cases/pooled_connections_test.rb index 2649a93..34de450 100644 --- a/activerecord/test/cases/pooled_connections_test.rb +++ b/activerecord/test/cases/pooled_connections_test.rb @@ -1,4 +1,5 @@ require "cases/helper" +require 'timeout' class PooledConnectionsTest < ActiveRecord::TestCase def setup @@ -89,6 +90,24 @@ class PooledConnectionsTest < ActiveRecord::TestCase ensure ActiveRecord::Base.connection_handler = old_handler end + + def test_using_connection + ActiveRecord::Base.establish_connection(@connection.merge({:pool => 2, :wait_timeout => 10})) + threads = [] + 10.times do + threads << Thread.new do + ActiveRecord::Base.connection_pool.using_connection do + ActiveRecord::Base.connection.execute("select 1") + end + end + end + + assert_nothing_raised do + Timeout.timeout(2) do + threads.each {|t| t.join } + end + end + end end unless %w(FrontBase).include? ActiveRecord::Base.connection.adapter_name class AllowConcurrencyDeprecatedTest < ActiveRecord::TestCase -- 1.5.6.3