This repository has been archived by the owner on Feb 1, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 326
/
cursor.c
1280 lines (1053 loc) · 37.1 KB
/
cursor.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
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
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright 2009-2014 MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <php.h>
#include <zend_interfaces.h>
#include <zend_exceptions.h>
#include "mcon/manager.h"
#include "mcon/utils.h"
#include "exceptions/duplicate_key_exception.h"
#include "exceptions/execution_timeout_exception.h"
#include "cursor_shared.h"
#ifdef WIN32
# ifndef int64_t
typedef __int64 int64_t;
# endif
#else
# include <unistd.h>
#endif
#include <math.h>
#include "php_mongo.h"
#include "bson.h"
#include "db.h"
#include "cursor.h"
#include "collection.h"
#include "util/log.h"
#include "log_stream.h"
#include "cursor_shared.h"
#include "contrib/php-json.h"
/* externs */
extern zend_class_entry *mongo_ce_Id, *mongo_ce_MongoClient, *mongo_ce_DB;
extern zend_class_entry *mongo_ce_Collection, *mongo_ce_Exception;
extern zend_class_entry *mongo_ce_CursorInterface;
extern zend_class_entry *mongo_ce_ConnectionException;
extern zend_class_entry *mongo_ce_CursorException;
extern zend_class_entry *mongo_ce_CursorTimeoutException;
extern zend_class_entry *mongo_ce_DuplicateKeyException;
extern zend_class_entry *mongo_ce_ExecutionTimeoutException;
extern zend_object_handlers mongo_default_handlers;
ZEND_EXTERN_MODULE_GLOBALS(mongo)
static zend_object_value php_mongo_cursor_new(zend_class_entry *class_type TSRMLS_DC);
static void php_mongocursor_next(mongo_cursor *cursor, zval *return_value TSRMLS_DC);
zend_class_entry *mongo_ce_Cursor = NULL;
/* Queries the database. Returns SUCCESS or FAILURE. */
static int mongo_cursor__do_query(mongo_cursor *cursor TSRMLS_DC);
#define PREITERATION_SETUP \
PHP_MONGO_GET_CURSOR(getThis()); \
\
if (cursor->started_iterating) { \
zend_throw_exception(mongo_ce_CursorException, "cannot modify cursor after beginning iteration.", 0 TSRMLS_CC); \
return; \
}
/* Returns FAILURE if something went wrong, but an exception is set too. DO NOT
* CONTINUE in the calling method if this one returns FAILURE. */
int php_mongocursor_create(mongo_cursor *cursor, zval *zlink, char *ns, int ns_len, zval *zquery, zval *zfields TSRMLS_DC)
{
zval *empty, *timeout;
zval **data;
mongoclient *link;
link = (mongoclient*)zend_object_store_get_object(zlink TSRMLS_CC);
MONGO_CHECK_INITIALIZED_C(link->manager, MongoClient);
if (!php_mongo_is_valid_namespace(ns, ns_len)) {
php_mongo_cursor_throw(mongo_ce_CursorException, NULL, 21 TSRMLS_CC, "An invalid 'ns' argument is given (%s)", ns);
return FAILURE;
}
/* if query or fields weren't passed, make them default to an empty array */
MAKE_STD_ZVAL(empty);
object_init(empty);
/* These are both initialized to the same zval, but that's okay because.
* There's no way to change them without creating a new cursor */
if (!zquery || (Z_TYPE_P(zquery) == IS_ARRAY && zend_hash_num_elements(HASH_P(zquery)) == 0)) {
zquery = empty;
}
if (!zfields) {
zfields = empty;
}
/* db connection */
cursor->zmongoclient = zlink;
zval_add_ref(&zlink);
/* Legacy handling where the projection is an array of field names to be
* included (e.g. ['x', 'y', 'z'] is converted to {'x': 1, 'y': 1, 'z': 1}).
* This behavior dates back to 0.9.4, but there is no record of it in the
* extension's documentation. It should be deprecated/removed in the future,
* as it conflicts with supporting some legitimate projections (PHP-1056).
*/
if (Z_TYPE_P(zfields) == IS_ARRAY && php_mongo_is_numeric_array(zfields TSRMLS_CC) == SUCCESS) {
HashPosition pointer;
zval *fields;
MAKE_STD_ZVAL(fields);
array_init(fields);
/* fields to return */
for (
zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(zfields), &pointer);
zend_hash_get_current_data_ex(Z_ARRVAL_P(zfields), (void**) &data, &pointer) == SUCCESS;
zend_hash_move_forward_ex(Z_ARRVAL_P(zfields), &pointer)
) {
int key_type, key_len;
ulong index;
char *key;
key_type = zend_hash_get_current_key_ex(Z_ARRVAL_P(zfields), &key, (uint*)&key_len, &index, NO_DUP, &pointer);
if (key_type == HASH_KEY_IS_LONG) {
if (Z_TYPE_PP(data) == IS_STRING) {
add_assoc_long(fields, Z_STRVAL_PP(data), 1);
} else {
zval_ptr_dtor(&empty);
zval_ptr_dtor(&fields);
zend_throw_exception(mongo_ce_Exception, "field names must be strings", 8 TSRMLS_CC);
return FAILURE;
}
} else {
add_assoc_zval(fields, key, *data);
zval_add_ref(data);
}
}
cursor->fields = fields;
} else {
/* if it's already an object, we don't have to worry */
cursor->fields = zfields;
zval_add_ref(&zfields);
}
/* ns */
cursor->ns = estrdup(ns);
/* query */
cursor->query = zquery;
zval_add_ref(&zquery);
/* reset iteration pointer, just in case */
php_mongo_cursor_reset(cursor TSRMLS_CC);
/* Set initial connection to NULL. This allows us to override the cursor
* just after construction. THis is useful as a temporary hack until we
* have refactored to create cursors with an already configured cursor. See
* also the other TODO in this file on this. */
cursor->connection = NULL;
cursor->at = 0;
cursor->num = 0;
cursor->special = 0;
cursor->persist = 0;
cursor->current = NULL;
timeout = zend_read_static_property(mongo_ce_Cursor, "timeout", strlen("timeout"), NOISY TSRMLS_CC);
convert_to_long(timeout);
/* The value hasn't been modified from what we registered it as originally */
if (Z_LVAL_P(timeout) == PHP_MONGO_STATIC_CURSOR_TIMEOUT_NOT_SET_INITIALIZER) {
cursor->timeout = link->servers->options.socketTimeoutMS;
mongo_manager_log(link->manager, MLOG_CON, MLOG_FINE, "Initializing cursor timeout to %d (from connection options)", cursor->timeout);
} else {
cursor->timeout = Z_LVAL_P(timeout);
/* The value was modified, bad user, bad user! Tell him its deprecated */
php_error_docref(NULL TSRMLS_CC, E_DEPRECATED, "The 'MongoCursor::$timeout' static property is deprecated, please call MongoCursor->timeout() instead");
mongo_manager_log(link->manager, MLOG_CON, MLOG_FINE, "Initializing cursor timeout to %d (from deprecated static property)", cursor->timeout);
}
/* If the static property "slaveOkay" is set, we need to switch to a
* MONGO_RP_SECONDARY_PREFERRED as well, but only if read preferences
* aren't already set. */
if (cursor->read_pref.type == MONGO_RP_PRIMARY) {
zval *zslaveokay;
zslaveokay = zend_read_static_property(mongo_ce_Cursor, "slaveOkay", strlen("slaveOkay"), NOISY TSRMLS_CC);
if (Z_TYPE_P(zslaveokay) != IS_NULL) {
cursor->read_pref.type = Z_BVAL_P(zslaveokay) ? MONGO_RP_SECONDARY_PREFERRED : MONGO_RP_PRIMARY;
php_error_docref(NULL TSRMLS_CC, E_DEPRECATED, "The 'slaveOkay' option is deprecated. Please switch to read-preferences");
}
}
/* get rid of extra ref */
zval_ptr_dtor(&empty);
return SUCCESS;
}
/* {{{ MongoCursor->__construct(MongoClient connection, string ns [, array query [, array fields]])
Constructs a MongoCursor */
PHP_METHOD(MongoCursor, __construct)
{
zval *zlink = NULL, *zquery = NULL, *zfields = NULL;
char *ns;
int ns_len;
mongo_cursor *cursor;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Os|zz", &zlink, mongo_ce_MongoClient, &ns, &ns_len, &zquery, &zfields) == FAILURE) {
return;
}
MUST_BE_ARRAY_OR_OBJECT(3, zquery);
MUST_BE_ARRAY_OR_OBJECT(4, zfields);
cursor = (mongo_cursor*)zend_object_store_get_object(getThis() TSRMLS_CC);
php_mongocursor_create(cursor, zlink, ns, ns_len, zquery, zfields TSRMLS_CC);
}
/* }}} */
/* {{{ MongoCursor::hasNext
*/
PHP_METHOD(MongoCursor, hasNext)
{
mongo_cursor *cursor = (mongo_cursor*)zend_object_store_get_object(getThis() TSRMLS_CC);
MONGO_CHECK_INITIALIZED(cursor->zmongoclient, MongoCursor);
if (!cursor->started_iterating) {
php_mongo_runquery(cursor TSRMLS_CC);
if (EG(exception)) {
RETURN_NULL();
}
cursor->started_iterating = 1;
/* This is a special case. If hasNext() is called, and we have to
* trigger the query to run, then the cursor position is aready at the
* "first" item. However, nothing should have been advanced yet and
* hence the pointer is one too far. In order to prevent it from being
* one too far, this flag prevents the pointer from being increased in
* php_mongocursor_advance. */
cursor->cursor_options |= MONGO_CURSOR_OPT_DONT_ADVANCE_ON_FIRST_NEXT;
}
MONGO_CHECK_INITIALIZED(cursor->connection, MongoCursor);
/* This is a special case. If hasNext() is called and triggers the query to
* run, cursor->at is 0 but we have not actually advanced to the first
* element (unlike rewind()) and will not do so until getNext() is called.
* Check for this special case rather than using -1 as our position. */
if (cursor->cursor_options & MONGO_CURSOR_OPT_DONT_ADVANCE_ON_FIRST_NEXT && cursor->at == cursor->num - 1) {
RETURN_TRUE;
}
if ((cursor->limit > 0 && cursor->at >= cursor->limit - 1) || cursor->num == 0) {
if (cursor->cursor_id != 0) {
php_mongo_kill_cursor(cursor->connection, cursor->cursor_id TSRMLS_CC);
cursor->cursor_id = 0;
}
RETURN_FALSE;
}
/* We need to look for one less than the end, because after this check, we
* still would need to be able to advance to the next item. */
if (cursor->at < cursor->num - 1) {
RETURN_TRUE;
} else if (cursor->cursor_id == 0) {
RETURN_FALSE;
} else if (cursor->connection == NULL) {
/* if we have a cursor_id, we should have a server */
php_mongo_cursor_throw(mongo_ce_CursorException, NULL, 18 TSRMLS_CC, "trying to get more, but cannot find server");
return;
}
if (!php_mongo_get_more(cursor TSRMLS_CC)) {
RETURN_FALSE;
}
/* Since we're not advancing, this function will only detect errors
* indicated in the OP_REPLY error flags. Any error indicated with an $err
* field in the first response document will be picked up during a
* subsequent call to getNext(), which will call php_mongo_handle_error()
* again via php_mongocursor_advance(). */
if (php_mongo_handle_error(cursor TSRMLS_CC)) {
RETURN_FALSE;
}
/* Another special case. Because we had tested for *one more* above, we do
* need to check whether there are actually more results before we
* conclusively can say there are more results on the cursor. We try to run
* getMore here, and then check whether it had changed the "num" from the
* last value. The last value of "num" is now "start", so that's why we
* compare it with that. */
if (cursor->start == cursor->num) {
RETURN_FALSE;
}
/* Since we just issued a getMore, we repeat the same checks as earlier. If
* our position before the last element we return true. Otherwise, we return
* false. If the cursor was closed remotely, its id is zero and cursor->num
* will not have advanced, so false will still be returned. We needn't worry
* about checking for a null connection, as php_mongo_get_more() would have
* thrown an exception for that case. */
if (cursor->at < cursor->num - 1) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
/* }}} */
/* {{{ MongoCursor iteration helpers */
int php_mongocursor_is_valid(mongo_cursor *cursor)
{
return cursor->current != NULL;
}
int php_mongocursor_load_current_element(mongo_cursor *cursor TSRMLS_DC)
{
mongo_bson_conversion_options cmd_options = MONGO_BSON_CONVERSION_OPTIONS_INIT;
/* Free the previous current item */
php_mongo_cursor_clear_current_element(cursor);
/* Do processing of subsequent batches, like a normal cursor */
if (cursor->at >= cursor->num) {
return FAILURE;
}
/* Deal with options for command cursor */
if (cursor->cursor_options & MONGO_CURSOR_OPT_CMD_CURSOR) {
cmd_options.flag_cmd_cursor_as_int64 = 1;
}
/* Init and convert */
MAKE_STD_ZVAL(cursor->current);
array_init(cursor->current);
cursor->buf.pos = (char*) bson_to_zval_iter(
(char*)cursor->buf.pos,
cursor->buf.end - cursor->buf.pos,
Z_ARRVAL_P(cursor->current),
&cmd_options
TSRMLS_CC
);
if (EG(exception)) {
php_mongo_cursor_clear_current_element(cursor);
return FAILURE;
}
return SUCCESS;
}
int php_mongocursor_advance(mongo_cursor *cursor TSRMLS_DC)
{
int retrieved;
/* Free the previous current item */
php_mongo_cursor_clear_current_element(cursor);
if (cursor->cursor_options & MONGO_CURSOR_OPT_DONT_ADVANCE_ON_FIRST_NEXT) {
cursor->cursor_options &= ~MONGO_CURSOR_OPT_DONT_ADVANCE_ON_FIRST_NEXT;
} else {
cursor->at++;
}
if (cursor->at == cursor->num && cursor->cursor_id != 0) {
if (cursor->dead) {
php_mongo_cursor_throw(mongo_ce_ConnectionException, cursor->connection, 12 TSRMLS_CC, "the connection has been terminated, and this cursor is dead");
return FAILURE;
}
/* Limit reached */
if (cursor->limit != 0 && cursor->at >= cursor->limit) {
php_mongo_kill_cursor(cursor->connection, cursor->cursor_id TSRMLS_CC);
cursor->cursor_id = 0;
return FAILURE;
}
if (!php_mongo_get_more(cursor TSRMLS_CC)) {
return FAILURE;
}
}
retrieved = php_mongocursor_load_current_element(cursor TSRMLS_CC);
if (php_mongo_handle_error(cursor TSRMLS_CC)) {
return FAILURE;
}
return retrieved;
}
/* }}} */
/* {{{ MongoCursor::limit
*/
PHP_METHOD(MongoCursor, limit)
{
long l;
mongo_cursor *cursor;
PREITERATION_SETUP;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &l) == FAILURE) {
return;
}
php_mongo_cursor_set_limit(cursor, l);
RETVAL_ZVAL(getThis(), 1, 0);
}
/* }}} */
/* {{{ MongoCursor::skip
*/
PHP_METHOD(MongoCursor, skip)
{
long l;
mongo_cursor *cursor;
PREITERATION_SETUP;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &l) == FAILURE) {
return;
}
cursor->skip = l;
RETURN_ZVAL(getThis(), 1, 0);
}
/* }}} */
/* {{{ MongoCursor::fields
*/
PHP_METHOD(MongoCursor, fields)
{
zval *z;
mongo_cursor *cursor;
PREITERATION_SETUP;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &z) == FAILURE) {
return;
}
MUST_BE_ARRAY_OR_OBJECT(1, z);
zval_ptr_dtor(&cursor->fields);
cursor->fields = z;
zval_add_ref(&z);
RETURN_ZVAL(getThis(), 1, 0);
}
/* }}} */
/* {{{ proto MongoCursor MongoCursor::maxTimeMS(int ms)
* Configures a maximum time for the query to run, including fetching results. */
PHP_METHOD(MongoCursor, maxTimeMS)
{
long time_ms;
mongo_cursor *cursor;
zval *value;
PREITERATION_SETUP;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &time_ms) == FAILURE) {
return;
}
PHP_MONGO_GET_CURSOR(getThis());
MONGO_CHECK_INITIALIZED(cursor->zmongoclient, MongoCursor);
MAKE_STD_ZVAL(value);
ZVAL_LONG(value, time_ms);
if (php_mongo_cursor_add_option(cursor, "$maxTimeMS", value TSRMLS_CC)) {
RETVAL_ZVAL(getThis(), 1, 0);
}
zval_ptr_dtor(&value);
}
/* }}} */
/* {{{ Cursor flags
Sets or unsets the flag <flag>. With mode = -1, the arguments are parsed.
Otherwise the mode should contain 0 for unsetting and 1 for setting the flag. */
static inline void set_cursor_flag(INTERNAL_FUNCTION_PARAMETERS, int flag, int mode)
{
zend_bool z = 1;
mongo_cursor *cursor;
PREITERATION_SETUP;
if (mode == -1) {
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &z) == FAILURE) {
return;
}
} else {
z = mode;
}
if (z) {
cursor->opts |= flag;
} else {
cursor->opts &= ~flag;
}
RETURN_ZVAL(getThis(), 1, 0);
}
/* {{{ MongoCursor::setFlag(int bit [, bool set])
*/
PHP_METHOD(MongoCursor, setFlag)
{
long bit;
zend_bool set = 1;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|b", &bit, &set) == FAILURE) {
return;
}
/* Prevent bit 6 (CURSOR_FLAG_EXHAUST) from being set. This is because the
* driver can't handle this at the moment. */
if (bit == 6) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "The CURSOR_FLAG_EXHAUST(6) flag is not supported");
return;
}
set_cursor_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1 << bit, set);
}
/* }}} */
/* {{{ MongoCursor::tailable(bool flag)
*/
PHP_METHOD(MongoCursor, tailable)
{
set_cursor_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, CURSOR_FLAG_TAILABLE, -1);
}
/* }}} */
/* {{{ MongoCursor::slaveOkay(bool flag)
*/
PHP_METHOD(MongoCursor, slaveOkay)
{
mongo_cursor *cursor;
zend_bool slave_okay = 1;
PREITERATION_SETUP;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &slave_okay) == FAILURE) {
return;
}
set_cursor_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, CURSOR_FLAG_SLAVE_OKAY, slave_okay);
/* slaveOkay implicitly sets read preferences.
*
* With slave_okay being true or absent, the RP is switched to SECONDARY
* PREFERRED but only if the current configured RP is PRIMARY - so that
* other read preferences are not overwritten. As slaveOkay really only
* means "read from any secondary" that does not conflict.
*
* With slave_okay being false, the RP is switched to PRIMARY. Setting it
* to PRIMARY when it already is PRIMARY doesn't hurt. */
if (slave_okay) {
if (cursor->read_pref.type == MONGO_RP_PRIMARY) {
cursor->read_pref.type = MONGO_RP_SECONDARY_PREFERRED;
}
} else {
cursor->read_pref.type = MONGO_RP_PRIMARY;
}
}
/* }}} */
/* {{{ MongoCursor::immortal(bool flag)
*/
PHP_METHOD(MongoCursor, immortal)
{
set_cursor_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, CURSOR_FLAG_NO_CURSOR_TO, -1);
}
/* }}} */
/* {{{ MongoCursor::awaitData(bool flag)
*/
PHP_METHOD(MongoCursor, awaitData)
{
set_cursor_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, CURSOR_FLAG_AWAIT_DATA, -1);
}
/* }}} */
/* {{{ MongoCursor::partial(bool flag)
*/
PHP_METHOD(MongoCursor, partial)
{
set_cursor_flag(INTERNAL_FUNCTION_PARAM_PASSTHRU, CURSOR_FLAG_PARTIAL, -1);
}
/* }}} */
/* }}} */
/* {{{ MongoCursor::addOption
*/
PHP_METHOD(MongoCursor, addOption)
{
char *key;
int key_len;
zval *value;
mongo_cursor *cursor;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz", &key, &key_len, &value) == FAILURE) {
return;
}
PHP_MONGO_GET_CURSOR(getThis());
MONGO_CHECK_INITIALIZED(cursor->zmongoclient, MongoCursor);
if (php_mongo_cursor_add_option(cursor, key, value TSRMLS_CC)) {
RETURN_ZVAL(getThis(), 1, 0);
}
}
/* }}} */
/* {{{ MongoCursor::snapshot
*/
PHP_METHOD(MongoCursor, snapshot)
{
zval *yes;
mongo_cursor *cursor = (mongo_cursor*)zend_object_store_get_object(getThis() TSRMLS_CC);
MONGO_CHECK_INITIALIZED(cursor->zmongoclient, MongoCursor);
MAKE_STD_ZVAL(yes);
ZVAL_TRUE(yes);
if (php_mongo_cursor_add_option(cursor, "$snapshot", yes TSRMLS_CC)) {
RETVAL_ZVAL(getThis(), 1, 0);
}
zval_ptr_dtor(&yes);
}
/* }}} */
/* {{{ MongoCursor->sort(array fields)
*/
PHP_METHOD(MongoCursor, sort)
{
zval *fields;
mongo_cursor *cursor = (mongo_cursor*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &fields) == FAILURE) {
return;
}
MUST_BE_ARRAY_OR_OBJECT(1, fields);
MONGO_CHECK_INITIALIZED(cursor->zmongoclient, MongoCursor);
if (php_mongo_cursor_add_option(cursor, "$orderby", fields TSRMLS_CC)) {
RETURN_ZVAL(getThis(), 1, 0);
}
}
/* }}} */
/* {{{ proto MongoCursor MongoCursor::hint(mixed index)
Hint the index, by name or fields, to use for the query. */
PHP_METHOD(MongoCursor, hint)
{
zval *index;
mongo_cursor *cursor = (mongo_cursor*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &index) == FAILURE) {
return;
}
MONGO_CHECK_INITIALIZED(cursor->zmongoclient, MongoCursor);
if (php_mongo_cursor_add_option(cursor, "$hint", index TSRMLS_CC)) {
RETURN_ZVAL(getThis(), 1, 0);
}
}
/* }}} */
/* {{{ MongoCursor->explain
*/
PHP_METHOD(MongoCursor, explain)
{
int temp_limit;
zval *yes;
mongo_cursor *cursor = (mongo_cursor*)zend_object_store_get_object(getThis() TSRMLS_CC);
MONGO_CHECK_INITIALIZED(cursor->zmongoclient, MongoCursor);
php_mongo_cursor_reset(cursor TSRMLS_CC);
/* make explain use a hard limit */
temp_limit = cursor->limit;
if (cursor->limit > 0) {
cursor->limit *= -1;
}
MAKE_STD_ZVAL(yes);
ZVAL_TRUE(yes);
if (!php_mongo_cursor_add_option(cursor, "$explain", yes TSRMLS_CC)) {
zval_ptr_dtor(&yes);
return;
}
zval_ptr_dtor(&yes);
php_mongocursor_next(cursor, return_value TSRMLS_CC);
if (php_mongo_handle_error(cursor TSRMLS_CC)) {
return;
}
/* reset cursor to original state */
cursor->limit = temp_limit;
zend_hash_del(HASH_P(cursor->query), "$explain", strlen("$explain") + 1);
php_mongo_cursor_reset(cursor TSRMLS_CC);
}
/* }}} */
void php_mongo_runquery(mongo_cursor *cursor TSRMLS_DC)
{
int ns_len;
php_mongo_cursor_reset(cursor TSRMLS_CC);
if (mongo_cursor__do_query(cursor TSRMLS_CC) == SUCCESS || EG(exception)) {
return;
}
ns_len = strlen(cursor->ns);
if (ns_len >= 5 && strcmp(".$cmd", cursor->ns + (ns_len - 5)) == 0) {
php_mongo_cursor_throw(mongo_ce_CursorException, cursor->connection, 19 TSRMLS_CC, "couldn't send command");
return;
}
}
/* {{{ MongoCursor->doQuery
*/
PHP_METHOD(MongoCursor, doQuery)
{
mongo_cursor *cursor;
PHP_MONGO_GET_CURSOR(getThis());
MONGO_CHECK_INITIALIZED(cursor->zmongoclient, MongoCursor);
php_mongo_runquery(cursor TSRMLS_CC);
}
/* }}} */
/* Adds the $readPreference option to the query objects */
void mongo_apply_mongos_rp(mongo_cursor *cursor)
{
zval *rp, *tags;
char *type;
/* Older mongos don't like $readPreference, so don't apply it
* when we want the default behaviour anyway */
if (cursor->read_pref.type == MONGO_RP_PRIMARY) {
return;
}
if (cursor->read_pref.type == MONGO_RP_SECONDARY_PREFERRED) {
/* If there aren't any tags, don't add $readPreference, the slaveOkay
* flag is enough This gives us improved compatability with older
* mongos */
if (cursor->read_pref.tagset_count == 0) {
return;
}
}
type = mongo_read_preference_type_to_name(cursor->read_pref.type);
MAKE_STD_ZVAL(rp);
array_init(rp);
add_assoc_string(rp, "mode", type, 1);
tags = php_mongo_make_tagsets(&cursor->read_pref);
if (tags) {
add_assoc_zval(rp, "tags", tags);
}
php_mongo_make_special(cursor);
add_assoc_zval(cursor->query, "$readPreference", rp);
}
static int mongo_cursor__do_query(mongo_cursor *cursor TSRMLS_DC)
{
mongo_buffer buf;
char *error_message;
mongoclient *link;
mongo_read_preference rp;
if (!cursor) {
zend_throw_exception(mongo_ce_Exception, "The MongoCursor object has not been correctly initialized by its constructor", 0 TSRMLS_CC);
return FAILURE;
}
/* db connection zmongoclient */
link = (mongoclient*)zend_object_store_get_object(cursor->zmongoclient TSRMLS_CC);
if (!link->servers) {
zend_throw_exception(mongo_ce_Exception, "The Mongo object has not been correctly initialized by its constructor", 0 TSRMLS_CC);
return FAILURE;
}
/* If we had a connection we need to remove it from the callback map before
* we assign it another connection. */
if (cursor->connection) {
mongo_deregister_callback_from_connection(cursor->connection, cursor);
}
/* Sets the wire protocol flag to allow reading from a secondary. The read
* preference spec states: "slaveOk remains as a bit in the wire protocol
* and drivers will set this bit to 1 for all reads except with PRIMARY
* read preference." */
cursor->opts = cursor->opts | (cursor->read_pref.type != MONGO_RP_PRIMARY ? CURSOR_FLAG_SLAVE_OKAY : 0);
/* store the link's read preference to backup, and overwrite with the
* cursors's read preferences */
mongo_read_preference_copy(&link->servers->read_pref, &rp);
mongo_read_preference_replace(&cursor->read_pref, &link->servers->read_pref);
/* TODO: We have to assume to use a read connection here, but it should
* really be refactored so that we can create a cursor with the correct
* read/write setup already, instead of having to force a new mode later
* (like we do for commands right now through
* php_mongo_cursor_force_primary). See also MongoDB::command and
* append_getlasterror, where this has to be done too. */
cursor->connection = mongo_get_read_write_connection_with_callback(
link->manager,
link->servers,
cursor->cursor_options & MONGO_CURSOR_OPT_FORCE_PRIMARY ? MONGO_CON_FLAG_WRITE : MONGO_CON_FLAG_READ,
cursor,
php_mongo_cursor_mark_dead,
(char**) &error_message
);
/* restore read preferences from backup */
mongo_read_preference_replace(&rp, &link->servers->read_pref);
mongo_read_preference_dtor(&rp);
/* Throw exception in case we have no connection */
if (cursor->connection == NULL) {
if (error_message) {
zend_throw_exception(mongo_ce_ConnectionException, error_message, 71 TSRMLS_CC);
free(error_message);
} else {
zend_throw_exception(mongo_ce_ConnectionException, "Could not retrieve connection", 72 TSRMLS_CC);
}
return FAILURE;
}
/* Apply read preference query option, but only if we have a MongoS
* connection */
if (cursor->connection->connection_type == MONGO_NODE_MONGOS) {
mongo_apply_mongos_rp(cursor);
}
/* Create query buffer */
CREATE_BUF(buf, INITIAL_BUF_SIZE);
if (php_mongo_write_query(&buf, cursor, cursor->connection->max_bson_size, cursor->connection->max_message_size TSRMLS_CC) == FAILURE) {
efree(buf.start);
return FAILURE;
}
mongo_log_stream_query(cursor->connection, cursor TSRMLS_CC);
if (link->manager->send(cursor->connection, &link->servers->options, buf.start, buf.pos - buf.start, (char **) &error_message) == -1) {
if (error_message) {
php_mongo_cursor_throw(mongo_ce_CursorException, cursor->connection, 14 TSRMLS_CC, "couldn't send query: %s", error_message);
free(error_message);
} else {
php_mongo_cursor_throw(mongo_ce_CursorException, cursor->connection, 14 TSRMLS_CC, "couldn't send query");
}
efree(buf.start);
return php_mongo_cursor_failed(cursor TSRMLS_CC);
}
efree(buf.start);
if (php_mongo_get_reply(cursor TSRMLS_CC) == FAILURE) {
/* php_mongo_get_reply() throws exceptions */
return php_mongo_cursor_failed(cursor TSRMLS_CC);
}
return SUCCESS;
}
/* }}} */
/* ITERATOR FUNCTIONS */
/* {{{ MongoCursor->valid
*/
PHP_METHOD(MongoCursor, valid)
{
mongo_cursor *cursor;
if (zend_parse_parameters_none()) {
return;
}
cursor = (mongo_cursor*)zend_object_store_get_object(getThis() TSRMLS_CC);
MONGO_CHECK_INITIALIZED(cursor->zmongoclient, MongoCursor);
if (!cursor->started_iterating) {
RETURN_FALSE;
}
if (cursor->dead) {
RETURN_FALSE;
}
if (!php_mongocursor_is_valid(cursor)) {
RETURN_FALSE;
}
RETURN_TRUE;
}
/* }}} */
/* {{{ MongoCursor->current
*/
PHP_METHOD(MongoCursor, current)
{
mongo_cursor *cursor = (mongo_cursor*)zend_object_store_get_object(getThis() TSRMLS_CC);
MONGO_CHECK_INITIALIZED(cursor->zmongoclient, MongoCursor);
if (cursor->current) {
RETURN_ZVAL(cursor->current, 1, 0);
}
}
/* }}} */
/* {{{ MongoCursor->key
*/
PHP_METHOD(MongoCursor, key)
{
zval **id;
mongo_cursor *cursor = (mongo_cursor*)zend_object_store_get_object(getThis() TSRMLS_CC);
MONGO_CHECK_INITIALIZED(cursor->zmongoclient, MongoCursor);
if (!cursor->current) {
RETURN_NULL();
}
if (Z_TYPE_P(cursor->current) == IS_ARRAY && zend_hash_find(HASH_P(cursor->current), "_id", 4, (void**)&id) == SUCCESS) {
if (Z_TYPE_PP(id) == IS_OBJECT) {
zend_std_cast_object_tostring(*id, return_value, IS_STRING TSRMLS_CC);
} else {
RETVAL_ZVAL(*id, 1, 0);
convert_to_string(return_value);
}
} else {
RETURN_LONG(cursor->at);
}
}
/* }}} */
static void php_mongocursor_next(mongo_cursor *cursor, zval *return_value TSRMLS_DC)
{
MONGO_CHECK_INITIALIZED(cursor->zmongoclient, MongoCursor);
MONGO_CURSOR_CHECK_DEAD;
/* Ideally, next() shouldn't be doing this. Instead users should use
* doQuery() themselves. But, BC */
if (!cursor->started_iterating) {
php_mongo_runquery(cursor TSRMLS_CC);
if (EG(exception)) {
RETURN_NULL();
}
cursor->started_iterating = 1;
php_mongocursor_load_current_element(cursor TSRMLS_CC);
} else {
php_mongocursor_advance(cursor TSRMLS_CC);
}
if (!php_mongocursor_is_valid(cursor)) {
RETURN_NULL();
}
if (cursor->current) {
RETURN_ZVAL(cursor->current, 1, 0);
}
}
/* {{{ MongoCursor->next(void)
* Advances the cursor to the next result, and returns that result */
PHP_METHOD(MongoCursor, next)
{
mongo_cursor *cursor = (mongo_cursor*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
php_mongocursor_next(cursor, return_value TSRMLS_CC);
}
/* }}} */
/* {{{ MongoCursor->rewind
*/