Skip to content

Commit 5ae03be

Browse files
committed
When streaming results, continue result.count across calls to result.each
Generally .each is passed a block, but handle if it isn't. Important because Enumerator implements its methods in terms of each.
1 parent 70bf629 commit 5ae03be

File tree

1 file changed

+17
-20
lines changed

1 file changed

+17
-20
lines changed

ext/mysql2/result.c

Lines changed: 17 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -504,40 +504,28 @@ static VALUE rb_mysql_result_each(int argc, VALUE * argv, VALUE self) {
504504
app_timezone = Qnil;
505505
}
506506

507-
if (wrapper->lastRowProcessed == 0) {
508-
if (wrapper->is_streaming) {
509-
/* We can't get number of rows if we're streaming, */
510-
/* until we've finished fetching all rows */
511-
wrapper->numberOfRows = 0;
507+
if (wrapper->is_streaming) {
508+
/* When streaming, we will only yield rows, not return them. */
509+
if (wrapper->rows == Qnil) {
512510
wrapper->rows = rb_ary_new();
513-
} else {
514-
wrapper->numberOfRows = mysql_num_rows(wrapper->result);
515-
if (wrapper->numberOfRows == 0) {
516-
wrapper->rows = rb_ary_new();
517-
return wrapper->rows;
518-
}
519-
wrapper->rows = rb_ary_new2(wrapper->numberOfRows);
520511
}
521-
}
522512

523-
if (wrapper->is_streaming) {
524513
if (!wrapper->streamingComplete) {
525514
VALUE row;
526515

527516
fields = mysql_fetch_fields(wrapper->result);
528517

529518
do {
530519
row = rb_mysql_result_fetch_row(self, db_timezone, app_timezone, symbolizeKeys, asArray, castBool, cast, fields);
531-
532-
if (block != Qnil && row != Qnil) {
533-
rb_yield(row);
534-
wrapper->lastRowProcessed++;
520+
if (row != Qnil) {
521+
wrapper->numberOfRows++;
522+
if (block != Qnil) {
523+
rb_yield(row);
524+
}
535525
}
536526
} while(row != Qnil);
537527

538528
rb_mysql_result_free_result(wrapper);
539-
540-
wrapper->numberOfRows = wrapper->lastRowProcessed;
541529
wrapper->streamingComplete = 1;
542530

543531
// Check for errors, the connection might have gone out from under us
@@ -550,6 +538,15 @@ static VALUE rb_mysql_result_each(int argc, VALUE * argv, VALUE self) {
550538
rb_raise(cMysql2Error, "You have already fetched all the rows for this query and streaming is true. (to reiterate you must requery).");
551539
}
552540
} else {
541+
if (wrapper->lastRowProcessed == 0) {
542+
wrapper->numberOfRows = mysql_num_rows(wrapper->result);
543+
if (wrapper->numberOfRows == 0) {
544+
wrapper->rows = rb_ary_new();
545+
return wrapper->rows;
546+
}
547+
wrapper->rows = rb_ary_new2(wrapper->numberOfRows);
548+
}
549+
553550
if (cacheRows && wrapper->lastRowProcessed == wrapper->numberOfRows) {
554551
/* we've already read the entire dataset from the C result into our */
555552
/* internal array. Lets hand that over to the user since it's ready to go */

0 commit comments

Comments
 (0)