Skip to content

Commit f8187be

Browse files
committed
Merge pull request #745 from ajaska/allow-repeated-each
Allow repeated each with :cache_rows => false
2 parents e58d027 + 8733029 commit f8187be

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

ext/mysql2/result.c

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -834,15 +834,17 @@ static VALUE rb_mysql_result_each_(VALUE self,
834834

835835
if (row == Qnil) {
836836
/* we don't need the mysql C dataset around anymore, peace it */
837-
rb_mysql_result_free_result(wrapper);
837+
if (args->cacheRows) {
838+
rb_mysql_result_free_result(wrapper);
839+
}
838840
return Qnil;
839841
}
840842

841843
if (args->block_given != Qnil) {
842844
rb_yield(row);
843845
}
844846
}
845-
if (wrapper->lastRowProcessed == wrapper->numberOfRows) {
847+
if (wrapper->lastRowProcessed == wrapper->numberOfRows && args->cacheRows) {
846848
/* we don't need the mysql C dataset around anymore, peace it */
847849
rb_mysql_result_free_result(wrapper);
848850
}
@@ -917,6 +919,10 @@ static VALUE rb_mysql_result_each(int argc, VALUE * argv, VALUE self) {
917919
if (wrapper->rows == Qnil && !wrapper->is_streaming) {
918920
wrapper->numberOfRows = wrapper->stmt_wrapper ? mysql_stmt_num_rows(wrapper->stmt_wrapper->stmt) : mysql_num_rows(wrapper->result);
919921
wrapper->rows = rb_ary_new2(wrapper->numberOfRows);
922+
} else if (wrapper->rows && !cacheRows) {
923+
mysql_data_seek(wrapper->result, 0);
924+
wrapper->lastRowProcessed = 0;
925+
wrapper->rows = rb_ary_new2(wrapper->numberOfRows);
920926
}
921927

922928
// Backward compat

spec/mysql2/result_spec.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,11 @@
8282
expect(result.first.object_id).not_to eql(result.first.object_id)
8383
end
8484

85+
it "should be able to iterate a second time even if cache_rows is disabled" do
86+
result = @client.query "SELECT 1 UNION SELECT 2", :cache_rows => false
87+
expect(result.to_a).to eql(result.to_a)
88+
end
89+
8590
it "should yield different value for #first if streaming" do
8691
result = @client.query "SELECT 1 UNION SELECT 2", :stream => true, :cache_rows => false
8792
expect(result.first).not_to eql(result.first)

0 commit comments

Comments
 (0)