Skip to content

Seek to beginning of result set before iterating #27

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions lib/mysql.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
12 changes: 12 additions & 0 deletions test/test_mysql.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down