@@ -475,6 +475,51 @@ static void rb_mysql_row_query_options(VALUE opts, ID *db_timezone, ID *app_time
475
475
}
476
476
}
477
477
478
+ static VALUE rb_mysql_result_element (VALUE self , VALUE seek ) {
479
+ VALUE row , opts ;
480
+ ID db_timezone , app_timezone ;
481
+ long offset ;
482
+ int symbolizeKeys , asArray , castBool , cacheRows , cast ;
483
+ mysql2_result_wrapper * wrapper ;
484
+
485
+ GetMysql2Result (self , wrapper );
486
+
487
+ offset = NUM2LONG (seek );
488
+
489
+ if (!wrapper -> numberOfRows ) {
490
+ wrapper -> numberOfRows = mysql_num_rows (wrapper -> result );
491
+ }
492
+
493
+ opts = rb_iv_get (self , "@query_options" );
494
+ rb_mysql_row_query_options (opts , & db_timezone , & app_timezone , & symbolizeKeys , & asArray , & castBool , & cast , & cacheRows );
495
+
496
+ if (wrapper -> is_streaming ) {
497
+ rb_raise (cMysql2Error , "Element reference operator #[] cannot be used in streaming mode." );
498
+ }
499
+
500
+ /* count back from the end if passed a negative number */
501
+ if (offset < 0 ) {
502
+ offset = wrapper -> numberOfRows + offset ;
503
+ }
504
+
505
+ /* negative offset was too big */
506
+ if (offset < 0 ) {
507
+ return Qnil ;
508
+ /* rb_raise(cMysql2Error, "Out of range: offset %ld is beyond %lu rows (offset begins at 0).", offset, wrapper->numberOfRows); */
509
+ }
510
+
511
+ if (wrapper -> numberOfRows <= (unsigned long )offset ) {
512
+ return Qnil ;
513
+ /* rb_raise(cMysql2Error, "Out of range: offset %ld is beyond %lu rows (offset begins at 0).", offset, wrapper->numberOfRows); */
514
+ }
515
+
516
+ mysql_data_seek (wrapper -> result , offset );
517
+
518
+ row = rb_mysql_result_fetch_row (self , db_timezone , app_timezone , symbolizeKeys , asArray , castBool , cast );
519
+
520
+ return row ;
521
+ }
522
+
478
523
static VALUE rb_mysql_result_each (int argc , VALUE * argv , VALUE self ) {
479
524
VALUE defaults , opts , block ;
480
525
ID db_timezone , app_timezone ;
@@ -634,6 +679,7 @@ void init_mysql2_result() {
634
679
cDateTime = rb_const_get (rb_cObject , rb_intern ("DateTime" ));
635
680
636
681
cMysql2Result = rb_define_class_under (mMysql2 , "Result" , rb_cObject );
682
+ rb_define_method (cMysql2Result , "[]" , rb_mysql_result_element , 1 );
637
683
rb_define_method (cMysql2Result , "each" , rb_mysql_result_each , -1 );
638
684
rb_define_method (cMysql2Result , "fields" , rb_mysql_result_fetch_fields , 0 );
639
685
rb_define_method (cMysql2Result , "count" , rb_mysql_result_count , 0 );
0 commit comments