Class: Mysql2::Result

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
ext/mysql2_ext.c

Instance Method Summary collapse

Instance Method Details

#each(*args) ⇒ Object



618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
# File 'ext/mysql2_ext.c', line 618

static VALUE rb_mysql_result_each(int argc, VALUE * argv, VALUE self) {
  VALUE opts, block;
  mysql2_result_wrapper * wrapper;
  unsigned long i;

  GetMysql2Result(self, wrapper);

  rb_scan_args(argc, argv, "01&", &opts, &block);

  if (wrapper->lastRowProcessed == 0) {
    wrapper->numberOfRows = mysql_num_rows(wrapper->result);
    if (wrapper->numberOfRows == 0) {
      return Qnil;
    }
    wrapper->rows = rb_ary_new2(wrapper->numberOfRows);
  }

  if (wrapper->lastRowProcessed == wrapper->numberOfRows) {
    // we've already read the entire dataset from the C result into our
    // internal array. Lets hand that over to the user since it's ready to go
    for (i = 0; i < wrapper->numberOfRows; i++) {
      rb_yield(rb_ary_entry(wrapper->rows, i));
    }
  } else {
    unsigned long rowsProcessed = 0;
    rowsProcessed = RARRAY_LEN(wrapper->rows);
    for (i = 0; i < wrapper->numberOfRows; i++) {
      VALUE row;
      if (i < rowsProcessed) {
        row = rb_ary_entry(wrapper->rows, i);
      } else {
        row = rb_mysql_result_fetch_row(argc, argv, self);
        rb_ary_store(wrapper->rows, i, row);
        wrapper->lastRowProcessed++;
      }

      if (row == Qnil) {
        // we don't need the mysql C dataset around anymore, peace it
        rb_mysql_result_free_result(wrapper);
        return Qnil;
      }

      if (block != Qnil) {
        rb_yield(row);
      }
    }
    if (wrapper->lastRowProcessed == wrapper->numberOfRows) {
      // we don't need the mysql C dataset around anymore, peace it
      rb_mysql_result_free_result(wrapper);
    }
  }

  return wrapper->rows;
}