-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathClient.php
More file actions
2072 lines (1785 loc) · 69.5 KB
/
Client.php
File metadata and controls
2072 lines (1785 loc) · 69.5 KB
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
<?php
namespace Utopia\Mongo;
use MongoDB\BSON\Document;
use MongoDB\BSON\Int64;
use MongoDB\Driver\Exception\InvalidArgumentException;
use Ramsey\Uuid\Uuid;
use stdClass;
use Swoole\Client as SwooleClient;
use Swoole\Coroutine;
use Swoole\Coroutine\Client as CoroutineClient;
class Client
{
/**
* Unique identifier for socket connection.
*/
private string $id;
/**
* Socket (sync or async) client.
*/
private SwooleClient|CoroutineClient $client;
/**
* Active sessions with transaction state tracking.
*/
private array $sessions = [];
/**
* Current cluster time for causal consistency.
*/
private ?object $clusterTime = null;
/**
* Current operation time for causal consistency.
*/
private ?object $operationTime = null;
/**
* Connection status flag.
*/
private bool $isConnected = false;
/**
* Defines commands Mongo uses over wire protocol.
*/
public const COMMAND_CREATE = "create";
public const COMMAND_DELETE = "delete";
public const COMMAND_FIND = "find";
public const COMMAND_FIND_AND_MODIFY = "findAndModify";
public const COMMAND_GET_LAST_ERROR = "getLastError";
public const COMMAND_GET_MORE = "getMore";
public const COMMAND_INSERT = "insert";
public const COMMAND_RESET_ERROR = "resetError";
public const COMMAND_UPDATE = "update";
public const COMMAND_COUNT = "count";
public const COMMAND_AGGREGATE = "aggregate";
public const COMMAND_DISTINCT = "distinct";
public const COMMAND_MAP_REDUCE = "mapReduce";
public const COMMAND_START_SESSION = "startSession";
public const COMMAND_COMMIT_TRANSACTION = "commitTransaction";
public const COMMAND_ABORT_TRANSACTION = "abortTransaction";
public const COMMAND_END_SESSIONS = "endSessions";
public const COMMAND_LIST_INDEXES = "listIndexes";
public const COMMAND_COLLMOD = "collMod";
public const COMMAND_KILL_CURSORS = "killCursors";
// Connection and performance settings
private int $defaultMaxTimeMS = 30000; // 30 seconds default
// Transaction error codes for retry logic
public const TRANSIENT_TRANSACTION_ERROR = 'TransientTransactionError';
public const UNKNOWN_TRANSACTION_COMMIT_RESULT = 'UnknownTransactionCommitResult';
public const TRANSACTION_TIMEOUT_ERROR = 50;
public const TRANSACTION_ABORTED_ERROR = 251;
// Transaction states
public const TRANSACTION_NONE = 'none';
public const TRANSACTION_STARTING = 'starting';
public const TRANSACTION_IN_PROGRESS = 'in_progress';
public const TRANSACTION_COMMITTED = 'committed';
public const TRANSACTION_ABORTED = 'aborted';
// Read concerns
public const READ_CONCERN_LOCAL = 'local';
public const READ_CONCERN_AVAILABLE = 'available';
public const READ_CONCERN_MAJORITY = 'majority';
public const READ_CONCERN_LINEARIZABLE = 'linearizable';
public const READ_CONCERN_SNAPSHOT = 'snapshot';
// Read preferences
public const READ_PREFERENCE_PRIMARY = 'primary';
public const READ_PREFERENCE_SECONDARY = 'secondary';
public const READ_PREFERENCE_PRIMARY_PREFERRED = 'primaryPreferred';
public const READ_PREFERENCE_SECONDARY_PREFERRED = 'secondaryPreferred';
public const READ_PREFERENCE_NEAREST = 'nearest';
/**
* Commands that do not support readConcern options
*/
private array $readConcernNotSupportedCommands = [
self::COMMAND_GET_MORE,
self::COMMAND_KILL_CURSORS
];
/**
* Authentication for connection
*/
private Auth $auth;
/**
* Default Database Name
*/
private string $database;
/**
* Database $host
*/
private string $host;
/**
* Database $port
*/
private int $port;
/**
* Create a Mongo connection.
* @param string $database
* @param string $host
* @param int $port
* @param string $user
* @param string $password
* @param Boolean $useCoroutine
* @throws \Exception
*/
public function __construct(
string $database,
string $host,
int $port,
string $user,
string $password,
bool $useCoroutine = false
) {
if (empty($database)) {
throw new \InvalidArgumentException('Database name cannot be empty');
}
if (empty($host)) {
throw new \InvalidArgumentException('Host cannot be empty');
}
if ($port <= 0 || $port > 65535) {
throw new \InvalidArgumentException('Port must be between 1 and 65535');
}
if (empty($user)) {
throw new \InvalidArgumentException('Username cannot be empty');
}
if (empty($password)) {
throw new \InvalidArgumentException('Password cannot be empty');
}
$this->id = uniqid('utopia.mongo.client');
$this->database = $database;
$this->host = $host;
$this->port = $port;
// Only use coroutines if explicitly requested and we're in a coroutine context
if ($useCoroutine) {
try {
$cid = Coroutine::getCid();
if ($cid <= 0) {
$useCoroutine = false;
}
} catch (\Throwable) {
$useCoroutine = false;
}
}
$this->client = $useCoroutine
? new CoroutineClient(SWOOLE_SOCK_TCP | SWOOLE_KEEP)
: new SwooleClient(SWOOLE_SOCK_TCP | SWOOLE_KEEP);
// Set socket options to prevent hanging
$this->client->set([
'open_tcp_keepalive' => true,
'tcp_keepidle' => 4, // Start keepalive after 4s idle
'tcp_keepinterval' => 3, // Keepalive interval 3s
'tcp_keepcount' => 2, // Close after 2 failed keepalives
'timeout' => 30 // 30 second connection timeout
]);
$this->auth = new Auth([
'authcid' => $user,
'secret' => Auth::encodeCredentials($user, $password)
]);
}
/**
* Connect to MongoDB using TCP/IP and Wire Protocol.
* @throws Exception
*/
public function connect(): self
{
if ($this->client->isConnected()) {
return $this;
}
if (empty($this->host)) {
throw new Exception('MongoDB host cannot be empty');
}
if ($this->port <= 0 || $this->port > 65535) {
throw new Exception('MongoDB port must be between 1 and 65535');
}
if (!$this->client->connect($this->host, $this->port)) {
throw new Exception("Failed to connect to MongoDB at {$this->host}:{$this->port}");
}
$this->isConnected = true;
[$payload, $db] = $this->auth->start();
$res = $this->query($payload, $db);
[$payload, $db] = $this->auth->continue($res);
$this->query($payload, $db);
return $this;
}
/**
* Create a UUID using UUID7 standard for MongoDB _id field.
*
* @return string
*/
public function createUuid(): string
{
return Uuid::uuid7()->toString();
}
/**
* Send a BSON packed query to connection with comprehensive session, causal consistency, and transaction support.
*
* @param array<string, mixed> $command Command to execute
* @param string|null $db Database name
* @return stdClass|array|int Query result
* @throws Exception
*/
public function query(array $command, ?string $db = null): stdClass|array|int
{
// Validate connection state before each operation
$this->validateConnection();
$sessionId = null;
// Extract and process session from options if provided
if (isset($command['session'])) {
$sessionData = $command['session'];
unset($command['session']);
// Handle different session formats
if (is_array($sessionData) && isset($sessionData['id'])) {
$command['lsid'] = $sessionData['id'];
$rawId = $sessionData['id']->id ?? null;
} else {
$command['lsid'] = $sessionData;
$rawId = $sessionData->id ?? null;
}
$sessionId = $rawId instanceof \MongoDB\BSON\Binary
? bin2hex($rawId->getData())
: $rawId;
// Add transaction parameters if session is in transaction
if ($sessionId && isset($this->sessions[$sessionId]) &&
$this->sessions[$sessionId]['state'] === self::TRANSACTION_IN_PROGRESS) {
$command['txnNumber'] = new Int64($this->sessions[$sessionId]['txnNumber']);
$command['autocommit'] = false;
// Check if this is the first operation
$isFirstOperation = !isset($this->sessions[$sessionId]['firstOperationDone']);
// Add the first operation flag for the first operation in the transaction
if ($isFirstOperation) {
$command['startTransaction'] = true;
$this->sessions[$sessionId]['firstOperationDone'] = true;
// Add transaction options from startTransaction
if (isset($this->sessions[$sessionId]['transactionOptions'])) {
$txnOpts = $this->sessions[$sessionId]['transactionOptions'];
if (isset($txnOpts['readConcern']) && !isset($command['readConcern'])) {
$command['readConcern'] = $txnOpts['readConcern'];
}
if (isset($txnOpts['writeConcern']) && !isset($command['writeConcern'])) {
$command['writeConcern'] = $txnOpts['writeConcern'];
}
}
}
// IMPORTANT: Do NOT add causal consistency readConcern for ANY operation in a transaction
// MongoDB transactions provide their own consistency guarantees, and readConcern can only
// be specified on the first operation (which is handled above via transactionOptions)
// Attempting to add readConcern to subsequent operations will cause E72 InvalidOptions error
// Remove any readConcern that might have been added before this point for non-first operations
if (!$isFirstOperation && isset($command['readConcern'])) {
unset($command['readConcern']);
}
} else {
// Not in a transaction - can add causal consistency readConcern freely
if ($this->operationTime !== null && !isset($command['readConcern']['afterClusterTime'])) {
$command['readConcern'] = $command['readConcern'] ?? [];
$command['readConcern']['afterClusterTime'] = $this->operationTime;
}
}
} else {
// No session - can add causal consistency readConcern freely (unless explicitly skipped)
if (!isset($command['skipReadConcern']) &&
$this->operationTime !== null &&
!isset($command['readConcern']['afterClusterTime'])) {
$command['readConcern'] = $command['readConcern'] ?? [];
$command['readConcern']['afterClusterTime'] = $this->operationTime;
}
}
// Remove internal flag before sending to MongoDB
unset($command['skipReadConcern']);
// CRITICAL: Remove readConcern from any non-first operation in a transaction
// MongoDB will reject commands with readConcern that have txnNumber but not startTransaction
// Or if the command is in the readConcernNotSupportedCommands array
if (
(
isset($command['txnNumber'])
&& !isset($command['startTransaction'])
&& isset($command['readConcern'])
)
|| \in_array(array_key_first($command) ?? '', $this->readConcernNotSupportedCommands)
) {
unset($command['readConcern']);
}
// Add cluster time for causal consistency
if ($this->clusterTime !== null) {
$command['$clusterTime'] = $this->clusterTime;
}
$params = array_merge($command, [
'$db' => $db ?? $this->database,
]);
$sections = Document::fromPHP($params);
$message = pack('V*', 21 + strlen($sections), $this->id, 0, 2013, 0) . "\0" . $sections;
$result = $this->send($message);
$this->updateCausalConsistency($result);
// Update session last use time if session was provided
if ($sessionId && isset($this->sessions[$sessionId])) {
$this->sessions[$sessionId]['lastUse'] = time();
}
return $result;
}
/**
* Send a message to connection.
*
* @param mixed $data
* @return stdClass|array|int
* @throws Exception
*/
public function send(mixed $data): stdClass|array|int
{
// Check if connection is alive, connect if not
if (!$this->client->isConnected()) {
$this->connect();
}
$result = $this->client->send($data);
// If send fails, try to reconnect once
if ($result === false) {
$this->close();
$this->connect();
$result = $this->client->send($data);
if ($result === false) {
throw new Exception('Failed to send data to MongoDB after reconnection attempt');
}
}
return $this->receive();
}
/**
* Receive a message from connection.
* @throws Exception
*/
private function receive(): stdClass|array|int
{
$chunks = [];
$receivedLength = 0;
$responseLength = null;
$attempts = 0;
$maxAttempts = 10000;
$sleepTime = 100;
do {
$chunk = @$this->client->recv();
if ($chunk === false || $chunk === '') {
$attempts++;
if ($attempts >= $maxAttempts) {
throw new Exception('Receive timeout: no data received within reasonable time');
}
// Adaptive backoff: shorter delays for coroutines, longer for sync
if ($this->client instanceof CoroutineClient) {
Coroutine::sleep(0.001); // 1ms for coroutines
} else {
\usleep((int)$sleepTime); // Microsecond precision for sync client
$sleepTime = (int)\min($sleepTime * 1.2, 10000); // Cap at 10ms for faster checking
}
continue;
}
// Reset attempts counter when we receive data
$attempts = 0;
$sleepTime = 100; // Reset to 0.1ms
$chunkLen = \strlen($chunk);
$receivedLength += $chunkLen;
$chunks[] = $chunk;
// Parse message length from first 4 bytes
if ($responseLength === null && $receivedLength >= 4) {
$firstData = $chunks[0];
if (\strlen($firstData) < 4) {
$firstData = \implode('', $chunks);
}
$responseLength = \unpack('Vl', substr($firstData, 0, 4))['l'];
// Validate response length before allocating memory to prevent memory exhaustion
if ($responseLength > 16777216) { // 16MB limit
throw new Exception('Response too large: ' . $responseLength . ' bytes');
}
// Validate for negative or tiny values
if ($responseLength < 21) { // Minimum MongoDB message size
throw new Exception('Invalid response length: ' . $responseLength . ' bytes');
}
}
if ($responseLength !== null && $receivedLength >= $responseLength) {
break;
}
} while (true);
$res = \implode('', $chunks);
return $this->parseResponse($res, $responseLength);
}
/**
* Selects a collection.
*
* Note: Since Mongo creates on the fly, this just returns
* an instances of self.
*/
public function selectDatabase(): self
{
return $this;
}
/**
* Creates a collection.
*
* Note: Since Mongo creates on the fly, this just returns
* an instances of self.
*/
public function createDatabase(): self
{
return $this;
}
/**
* Get a list of databases.
*/
public function listDatabaseNames(): stdClass
{
return $this->query([
'listDatabases' => 1,
'nameOnly' => true,
], 'admin');
}
/**
* Drop (remove) a database.
* https://docs.mongodb.com/manual/reference/command/dropDatabase/#mongodb-dbcommand-dbcmd.dropDatabase
*
* @param array $options
* @param string|null $db
* @return bool
* @throws Exception
*/
public function dropDatabase(array $options = [], ?string $db = null): bool
{
$db ??= $this->database;
$res = $this->query(array_merge(["dropDatabase" => 1], $options), $db);
return $res->ok === 1.0;
}
public function selectCollection($name): self
{
return $this;
}
/**
* Create a collection.
* https://docs.mongodb.com/manual/reference/command/create/#mongodb-dbcommand-dbcmd.create
*
* @param string $name
* @param array $options
* @return bool
* @throws Exception
*/
public function createCollection(string $name, array $options = []): bool
{
$list = $this->listCollectionNames(["name" => $name], $options);
if (\count($list->cursor->firstBatch) > 0) {
throw new Exception('Collection Exists', 48);
}
$res = $this->query(array_merge([
'create' => $name,
], $options));
return $res->ok === 1.0;
}
/**
* Drop a collection.
* https://docs.mongodb.com/manual/reference/command/drop/#mongodb-dbcommand-dbcmd.drop
*
* @param string $name
* @param array $options
* @return bool
* @throws Exception
*/
public function dropCollection(string $name, array $options = []): bool
{
$res = $this->query(array_merge([
'drop' => $name,
], $options));
return $res->ok === 1.0;
}
/**
* List collections (name only).
* https://docs.mongodb.com/manual/reference/command/listCollections/#listcollections
*
* @param array $filter
* @param array $options
*
* @return stdClass
* @throws Exception
*/
public function listCollectionNames(array $filter = [], array $options = []): stdClass
{
$qry = array_merge(
[
"listCollections" => 1.0,
"nameOnly" => true,
"authorizedCollections" => true,
"filter" => $this->toObject($filter)
],
$options
);
return $this->query($qry);
}
/**
* Create indexes.
* https://docs.mongodb.com/manual/reference/command/createIndexes/#createindexes
*
* @param string $collection
* @param array $indexes
* @param array $options
*
* @return boolean
* @throws Exception
*/
public function createIndexes(string $collection, array $indexes, array $options = []): bool
{
foreach ($indexes as $key => $index) {
if ($index['unique'] ?? false) {
/**
* TODO: Unique Indexes are now sparse indexes, which results into incomplete indexes.
* However, if partialFilterExpression is present, we can't use sparse.
*/
if (!\array_key_exists('partialFilterExpression', $index)) {
$indexes[$key] = \array_merge($index, ['sparse' => true]);
}
}
}
$qry = array_merge(
[
'createIndexes' => $collection,
'indexes' => $indexes
],
$options
);
$this->query($qry);
return true;
}
/**
* Drop indexes from a collection.
* https://docs.mongodb.com/manual/reference/command/dropIndexes/#dropindexes
*
* @param string $collection
* @param array $indexes
* @param array $options
*
* @return Client
* @throws Exception
*/
public function dropIndexes(string $collection, array $indexes, array $options = []): self
{
$this->query(
array_merge([
'dropIndexes' => $collection,
'index' => $indexes,
], $options)
);
return $this;
}
/**
* Insert document with full transaction and session support.
* https://docs.mongodb.com/manual/reference/command/insert/#mongodb-dbcommand-dbcmd.insert
*
* @param string $collection Collection name
* @param array $document Document to insert
* @param array $options Options array supporting:
* - session: Session object for transactions
* - writeConcern: Write concern specification
* - readConcern: Read concern specification
* - readPreference: Read preference
* - maxTimeMS: Operation timeout in milliseconds
* - ordered: Whether to stop on first error (default: true)
*
* @return array Inserted document with _id
* @throws Exception
*/
public function insert(string $collection, array $document, array $options = []): array
{
$docObj = new stdClass();
foreach ($document as $key => $value) {
$docObj->{$key} = $value;
}
if (!isset($docObj->_id) || $docObj->_id === '') {
$docObj->_id = $this->createUuid();
}
// Build command with session and concerns
$command = [
self::COMMAND_INSERT => $collection,
'documents' => [$docObj],
];
// Add session if provided
if (isset($options['session'])) {
$command['session'] = $options['session'];
}
// Add write concern if provided with validation
if (isset($options['writeConcern'])) {
$command['writeConcern'] = $this->createWriteConcern($options['writeConcern']);
}
// Add read concern if provided with validation (skip for non-first transaction operations)
if (isset($options['readConcern']) && !$this->shouldSkipReadConcern($options)) {
$command['readConcern'] = $this->createReadConcern($options['readConcern']);
}
// Add other options (excluding those we've already handled)
$otherOptions = array_diff_key($options, array_flip(['session', 'writeConcern', 'readConcern']));
$command = array_merge($command, $otherOptions);
$this->query($command);
return $this->toArray($docObj);
}
/**
* Insert multiple documents with improved batching for MongoDB 8+ performance.
* Automatically handles large datasets by batching operations with full transaction support.
*
* @param string $collection Collection name
* @param array $documents Array of documents to insert
* @param array $options Options array supporting:
* - session: Session object for transactions
* - writeConcern: Write concern specification
* - readConcern: Read concern specification
* - readPreference: Read preference
* - maxTimeMS: Operation timeout in milliseconds
* - ordered: Whether to stop on first error (default: true)
* - batchSize: Number of documents per batch (default: 1000)
* @return array Array of inserted documents with generated _ids
* @throws Exception
*/
public function insertMany(string $collection, array $documents, array $options = []): array
{
if (empty($documents)) {
return [];
}
$batchSize = $options['batchSize'] ?? 1000;
$ordered = $options['ordered'] ?? true;
$insertedDocs = [];
// Process documents in batches for better performance
$batches = array_chunk($documents, $batchSize);
foreach ($batches as $batch) {
$docObjs = [];
foreach ($batch as $document) {
$docObj = new stdClass();
foreach ($document as $key => $value) {
$docObj->{$key} = $value;
}
if (!isset($docObj->_id) || $docObj->_id === '') {
$docObj->_id = $this->createUuid();
}
$docObjs[] = $docObj;
}
// Build command with session and concerns
$command = [
self::COMMAND_INSERT => $collection,
'documents' => $docObjs,
'ordered' => $ordered,
];
// Add session if provided
if (isset($options['session'])) {
$command['session'] = $options['session'];
}
// Add write concern if provided with validation
if (isset($options['writeConcern'])) {
$command['writeConcern'] = $this->createWriteConcern($options['writeConcern']);
}
// Add read concern if provided with validation (skip for non-first transaction operations)
if (isset($options['readConcern']) && !$this->shouldSkipReadConcern($options)) {
$command['readConcern'] = $this->createReadConcern($options['readConcern']);
}
// Add other options (excluding those we've already handled)
$otherOptions = array_diff_key($options, array_flip(['session', 'writeConcern', 'readConcern', 'batchSize']));
$command = array_merge($command, $otherOptions);
$this->query($command);
$insertedDocs = array_merge($insertedDocs, $this->toArray($docObjs));
}
return $insertedDocs;
}
/**
* Retrieve the last lastDocument
*
* @param string $collection
*
* @return array
* @throws Exception
*/
public function lastDocument(string $collection): array
{
$result = $this->find($collection, [], [
'sort' => ['_id' => -1],
'limit' => 1
])->cursor->firstBatch[0];
return $this->toArray($result);
}
/**
* Update document(s) with full transaction and session support.
* https://docs.mongodb.com/manual/reference/command/update/#syntax
*
* @param string $collection Collection name
* @param array $where Filter criteria
* @param array $updates Update operations
* @param array $options Options array supporting:
* - session: Session object for transactions
* - writeConcern: Write concern specification
* - readConcern: Read concern specification
* - readPreference: Read preference
* - maxTimeMS: Operation timeout in milliseconds
* - upsert: Whether to insert if no match found
* - arrayFilters: Array filters for updates
* @param bool $multi Whether to update multiple documents
*
* @return int Number of modified documents
* @throws Exception
*/
public function update(string $collection, array $where = [], array $updates = [], array $options = [], bool $multi = false): int
{
// Build command with session and concerns
$command = [
self::COMMAND_UPDATE => $collection,
'updates' => [
[
'q' => $this->toObject($where),
'u' => $this->toObject($updates),
'multi' => $multi,
'upsert' => $options['upsert'] ?? false
]
]
];
// Add session if provided
if (isset($options['session'])) {
$command['session'] = $options['session'];
}
// Add write concern if provided with validation
if (isset($options['writeConcern'])) {
$command['writeConcern'] = $this->createWriteConcern($options['writeConcern']);
}
// Add read concern if provided with validation (skip for non-first transaction operations)
if (isset($options['readConcern']) && !$this->shouldSkipReadConcern($options)) {
$command['readConcern'] = $this->createReadConcern($options['readConcern']);
}
// Add other options (excluding those we've already handled)
$otherOptions = array_diff_key($options, array_flip(['session', 'writeConcern', 'readConcern', 'upsert']));
$command = array_merge($command, $otherOptions);
return $this->query($command);
}
/**
* Insert, or update, document(s) with support for bulk operations.
* https://docs.mongodb.com/manual/reference/command/update/#syntax
*
* @param string $collection
* @param array $operations Array of operations, each with 'filter' and 'update' keys
* @param array $options
*
* @return int Number of modified documents
* @throws Exception
*/
public function upsert(string $collection, array $operations, array $options = []): int
{
$updates = [];
foreach ($operations as $op) {
$updateOperation = [
'q' => $op['filter'],
'u' => $this->toObject($op['update']),
'upsert' => true,
'multi' => isset($op['multi']) ? $op['multi'] : false,
];
$updates[] = $updateOperation;
}
return $this->query(
array_merge(
[
self::COMMAND_UPDATE => $collection,
'updates' => $updates,
],
$options
)
);
}
/**
* Find document(s) with full transaction and session support.
* https://docs.mongodb.com/manual/reference/command/find/#mongodb-dbcommand-dbcmd.find
*
* @param string $collection Collection name
* @param array $filters Query filters
* @param array $options Options array supporting:
* - session: Session object for transactions
* - readConcern: Read concern specification
* - readPreference: Read preference
* - maxTimeMS: Operation timeout in milliseconds
* - limit: Maximum number of documents to return
* - skip: Number of documents to skip
* - sort: Sort specification
* - projection: Field projection specification
* - hint: Index hint
* - allowPartialResults: Allow partial results from sharded clusters
* @return stdClass Query result
* @throws Exception
*/
public function find(string $collection, array $filters = [], array $options = []): stdClass
{
$filters = $this->cleanFilters($filters);
// Build command with session and concerns
$command = [
self::COMMAND_FIND => $collection,
'filter' => $this->toObject($filters),
];
// Add session if provided
if (isset($options['session'])) {
$command['session'] = $options['session'];
}
// Add read concern if provided with validation (skip for non-first transaction operations)
if (isset($options['readConcern']) && !$this->shouldSkipReadConcern($options)) {
$command['readConcern'] = $this->createReadConcern($options['readConcern']);
}
// Add read preference if provided
if (isset($options['readPreference'])) {
$command['$readPreference'] = $options['readPreference'];
}
// Add other options (excluding those we've already handled)
$otherOptions = array_diff_key($options, array_flip(['session', 'readConcern', 'readPreference']));
$command = array_merge($command, $otherOptions);
return $this->query($command);
}
/**
* Aggregate a collection pipeline with full transaction and session support.
*
* @param string $collection Collection name
* @param array $pipeline Aggregation pipeline
* @param array $options Options array supporting:
* - session: Session object for transactions
* - readConcern: Read concern specification
* - readPreference: Read preference
* - maxTimeMS: Operation timeout in milliseconds
* - allowDiskUse: Allow using disk for large result sets
* - batchSize: Batch size for cursor
* - hint: Index hint
* - explain: Return query execution plan
*
* @return stdClass Aggregation result
* @throws Exception
*/
public function aggregate(string $collection, array $pipeline, array $options = []): stdClass
{
// Build command with session and concerns
$command = [
self::COMMAND_AGGREGATE => $collection,
'pipeline' => $pipeline,
'cursor' => $this->toObject([]),
];
// Add session if provided
if (isset($options['session'])) {
$command['session'] = $options['session'];
}
// Add read concern if provided with validation (skip for non-first transaction operations)
if (isset($options['readConcern']) && !$this->shouldSkipReadConcern($options)) {
$command['readConcern'] = $this->createReadConcern($options['readConcern']);
}
// Add read preference if provided
if (isset($options['readPreference'])) {
$command['$readPreference'] = $options['readPreference'];
}
// Add other options (excluding those we've already handled)
$otherOptions = array_diff_key($options, array_flip(['session', 'readConcern', 'readPreference']));
$command = array_merge($command, $otherOptions);