From 2f0851886ff902b4421bf58a50a680c57df645ae Mon Sep 17 00:00:00 2001 From: Matt Parlane Date: Wed, 30 Mar 2016 16:49:53 +1300 Subject: [PATCH] Seek to beginning of result set before iterating. This avoids the set appearing to be empty if the user tries iterating after performing a count. --- lib/mysql.rb | 4 ++++ test/test_mysql.rb | 12 ++++++++++++ 2 files changed, 16 insertions(+) diff --git a/lib/mysql.rb b/lib/mysql.rb index 66f2ff9..d4d335f 100644 --- a/lib/mysql.rb +++ b/lib/mysql.rb @@ -670,6 +670,7 @@ def fetch_hash(with_table=nil) # @yield [Array] record data # @return [self] self. If block is not specified, this returns Enumerator. def each(&block) + data_seek(0) return enum_for(:each) unless block while rec = fetch block.call rec @@ -682,6 +683,7 @@ def each(&block) # @yield [Hash] record data # @return [self] self. If block is not specified, this returns Enumerator. def each_hash(with_table=nil, &block) + data_seek(0) return enum_for(:each_hash, with_table) unless block while rec = fetch_hash(with_table) block.call rec @@ -964,6 +966,7 @@ def bind_result(*args) # @return [Mysql::Stmt] self # @return [Enumerator] If block is not specified def each(&block) + data_seek(0) return enum_for(:each) unless block while rec = fetch block.call rec @@ -977,6 +980,7 @@ def each(&block) # @return [Mysql::Stmt] self # @return [Enumerator] If block is not specified def each_hash(with_table=nil, &block) + data_seek(0) return enum_for(:each_hash, with_table) unless block while rec = fetch_hash(with_table) block.call rec diff --git a/test/test_mysql.rb b/test/test_mysql.rb index 07205ba..314af6e 100644 --- a/test/test_mysql.rb +++ b/test/test_mysql.rb @@ -815,6 +815,18 @@ class TestMysql < Test::Unit::TestCase end end + test '#each_hash iterate block with a hash, after performing a count' do + expect = [{"id"=>"1","str"=>"abc"}, {"id"=>"2","str"=>"defg"}, {"id"=>"3","str"=>"hi"}, {"id"=>"4","str"=>nil}] + expect_count = expect.length + @res.count + block_count = 0 + @res.each_hash do |a| + assert{ a == expect.shift } + block_count += 1 + end + assert{ block_count == expect_count} + end + test '#row_tell returns position of current record, #row_seek set position of current record' do assert{ @res.fetch_row == ['1', 'abc'] } pos = @res.row_tell