diff --git a/lib/postgresql_cursor/cursor.rb b/lib/postgresql_cursor/cursor.rb index 57382c0..73d201c 100644 --- a/lib/postgresql_cursor/cursor.rb +++ b/lib/postgresql_cursor/cursor.rb @@ -194,7 +194,7 @@ def each_tuple(&block) #:nodoc: rescue Exception => e raise e ensure - close if @block + close if @block && connection.active? end end @count @@ -216,7 +216,7 @@ def each_batch(&block) #:nodoc: break if has_do_while && rc != @options[:while] end ensure - close if @block + close if @block && connection.active? end end @count diff --git a/test/test_postgresql_cursor.rb b/test/test_postgresql_cursor.rb index 010bff2..4d8e43f 100644 --- a/test/test_postgresql_cursor.rb +++ b/test/test_postgresql_cursor.rb @@ -130,6 +130,26 @@ def test_batch_exception assert_equal e.message, 'Oops' end + def test_exception_in_failed_transaction + begin + Product.each_row_by_sql("select * from products") do |r| + Product.connection.execute('select kaboom') + end + rescue Exception => e + assert_match(/kaboom/, e.message) + end + end + + def test_batch_exception_in_failed_transaction + begin + Product.each_row_batch_by_sql("select * from products") do |r| + Product.connection.execute('select kaboom') + end + rescue Exception => e + assert_match(/kaboom/, e.message) + end + end + def test_cursor cursor = Product.all.each_row assert cursor.respond_to?(:each)