CollectionFunctionalTest.php 22.2 KB
Newer Older
1 2 3 4
<?php

namespace MongoDB\Tests\Collection;

5
use Closure;
6
use MongoDB\BSON\Javascript;
7
use MongoDB\Collection;
8
use MongoDB\Driver\BulkWrite;
9
use MongoDB\Driver\ReadConcern;
10 11
use MongoDB\Driver\ReadPreference;
use MongoDB\Driver\WriteConcern;
12
use MongoDB\Exception\InvalidArgumentException;
13
use MongoDB\Exception\UnsupportedException;
14
use MongoDB\MapReduceResult;
15
use MongoDB\Operation\Count;
16
use MongoDB\Tests\CommandObserver;
17 18 19 20
use function array_filter;
use function call_user_func;
use function strchr;
use function version_compare;
21

22 23 24 25 26
/**
 * Functional tests for the Collection class.
 */
class CollectionFunctionalTest extends FunctionalTestCase
{
27
    /**
28
     * @dataProvider provideInvalidDatabaseAndCollectionNames
29
     */
30
    public function testConstructorDatabaseNameArgument($databaseName)
31
    {
32
        $this->expectException(InvalidArgumentException::class);
33
        // TODO: Move to unit test once ManagerInterface can be mocked (PHPC-378)
34
        new Collection($this->manager, $databaseName, $this->getCollectionName());
35 36
    }

37 38 39 40 41
    /**
     * @dataProvider provideInvalidDatabaseAndCollectionNames
     */
    public function testConstructorCollectionNameArgument($collectionName)
    {
42
        $this->expectException(InvalidArgumentException::class);
43 44 45 46 47
        // TODO: Move to unit test once ManagerInterface can be mocked (PHPC-378)
        new Collection($this->manager, $this->getDatabaseName(), $collectionName);
    }

    public function provideInvalidDatabaseAndCollectionNames()
48
    {
Jeremy Mikola's avatar
Jeremy Mikola committed
49 50 51 52
        return [
            [null],
            [''],
        ];
53 54
    }

55 56 57 58 59
    /**
     * @dataProvider provideInvalidConstructorOptions
     */
    public function testConstructorOptionTypeChecks(array $options)
    {
60
        $this->expectException(InvalidArgumentException::class);
61
        new Collection($this->manager, $this->getDatabaseName(), $this->getCollectionName(), $options);
62 63 64 65 66 67
    }

    public function provideInvalidConstructorOptions()
    {
        $options = [];

68 69 70 71
        foreach ($this->getInvalidReadConcernValues() as $value) {
            $options[][] = ['readConcern' => $value];
        }

72 73 74 75
        foreach ($this->getInvalidReadPreferenceValues() as $value) {
            $options[][] = ['readPreference' => $value];
        }

76 77 78 79
        foreach ($this->getInvalidArrayValues() as $value) {
            $options[][] = ['typeMap' => $value];
        }

80 81 82 83 84 85 86
        foreach ($this->getInvalidWriteConcernValues() as $value) {
            $options[][] = ['writeConcern' => $value];
        }

        return $options;
    }

87 88 89 90 91
    public function testGetManager()
    {
        $this->assertSame($this->manager, $this->collection->getManager());
    }

92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
    public function testToString()
    {
        $this->assertEquals($this->getNamespace(), (string) $this->collection);
    }

    public function getGetCollectionName()
    {
        $this->assertEquals($this->getCollectionName(), $this->collection->getCollectionName());
    }

    public function getGetDatabaseName()
    {
        $this->assertEquals($this->getDatabaseName(), $this->collection->getDatabaseName());
    }

    public function testGetNamespace()
    {
        $this->assertEquals($this->getNamespace(), $this->collection->getNamespace());
    }

112 113 114 115 116
    public function testAggregateWithinTransaction()
    {
        $this->skipIfTransactionsAreNotSupported();

        // Collection must be created before the transaction starts
117
        $this->createCollection();
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

        $session = $this->manager->startSession();
        $session->startTransaction();

        try {
            $this->createFixtures(3, ['session' => $session]);

            $cursor = $this->collection->aggregate(
                [['$match' => ['_id' => ['$lt' => 3]]]],
                ['session' => $session]
            );

            $expected = [
                ['_id' => 1, 'x' => 11],
                ['_id' => 2, 'x' => 22],
            ];

            $this->assertSameDocuments($expected, $cursor);

            $session->commitTransaction();
        } finally {
            $session->endSession();
        }
    }

143 144 145 146 147 148
    public function testCreateIndexSplitsCommandOptions()
    {
        if (version_compare($this->getServerVersion(), '3.6.0', '<')) {
            $this->markTestSkipped('Sessions are not supported');
        }

149 150
        (new CommandObserver())->observe(
            function () {
151 152 153 154 155 156 157 158 159 160 161
                $this->collection->createIndex(
                    ['x' => 1],
                    [
                        'maxTimeMS' => 1000,
                        'session' => $this->manager->startSession(),
                        'sparse' => true,
                        'unique' => true,
                        'writeConcern' => new WriteConcern(1),
                    ]
                );
            },
162
            function (array $event) {
163
                $command = $event['started']->getCommand();
164 165 166 167 168 169 170 171 172
                $this->assertObjectHasAttribute('lsid', $command);
                $this->assertObjectHasAttribute('maxTimeMS', $command);
                $this->assertObjectHasAttribute('writeConcern', $command);
                $this->assertObjectHasAttribute('sparse', $command->indexes[0]);
                $this->assertObjectHasAttribute('unique', $command->indexes[0]);
            }
        );
    }

173 174
    public function testDrop()
    {
Jeremy Mikola's avatar
Jeremy Mikola committed
175
        $writeResult = $this->collection->insertOne(['x' => 1]);
176 177 178 179 180 181
        $this->assertEquals(1, $writeResult->getInsertedCount());

        $commandResult = $this->collection->drop();
        $this->assertCommandSucceeded($commandResult);
        $this->assertCollectionCount($this->getNamespace(), 0);
    }
182

183 184 185 186 187
    /**
     * @todo Move this to a unit test once Manager can be mocked
     */
    public function testDropIndexShouldNotAllowWildcardCharacter()
    {
188
        $this->expectException(InvalidArgumentException::class);
189 190 191
        $this->collection->dropIndex('*');
    }

192 193 194 195 196 197 198 199 200 201 202
    public function testExplain()
    {
        $this->createFixtures(3);

        $operation = new Count($this->getDatabaseName(), $this->getCollectionName(), ['x' => ['$gte' => 1]], []);

        $result = $this->collection->explain($operation);

        $this->assertArrayHasKey('queryPlanner', $result);
    }

203 204 205 206
    public function testFindOne()
    {
        $this->createFixtures(5);

Jeremy Mikola's avatar
Jeremy Mikola committed
207 208
        $filter = ['_id' => ['$lt' => 5]];
        $options = [
209
            'skip' => 1,
Jeremy Mikola's avatar
Jeremy Mikola committed
210 211
            'sort' => ['x' => -1],
        ];
212

213
        $expected = ['_id' => 3, 'x' => 33];
214

215
        $this->assertSameDocument($expected, $this->collection->findOne($filter, $options));
216 217
    }

218 219 220 221 222
    public function testFindWithinTransaction()
    {
        $this->skipIfTransactionsAreNotSupported();

        // Collection must be created before the transaction starts
223
        $this->createCollection();
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

        $session = $this->manager->startSession();
        $session->startTransaction();

        try {
            $this->createFixtures(3, ['session' => $session]);

            $cursor = $this->collection->find(
                ['_id' => ['$lt' => 3]],
                ['session' => $session]
            );

            $expected = [
                ['_id' => 1, 'x' => 11],
                ['_id' => 2, 'x' => 22],
            ];

            $this->assertSameDocuments($expected, $cursor);

            $session->commitTransaction();
        } finally {
            $session->endSession();
        }
    }

249
    public function testWithOptionsInheritsOptions()
250 251
    {
        $collectionOptions = [
252
            'readConcern' => new ReadConcern(ReadConcern::LOCAL),
253
            'readPreference' => new ReadPreference(ReadPreference::RP_SECONDARY_PREFERRED),
254
            'typeMap' => ['root' => 'array'],
255 256 257
            'writeConcern' => new WriteConcern(WriteConcern::MAJORITY),
        ];

258
        $collection = new Collection($this->manager, $this->getDatabaseName(), $this->getCollectionName(), $collectionOptions);
259 260 261
        $clone = $collection->withOptions();
        $debug = $clone->__debugInfo();

262 263 264
        $this->assertSame($this->manager, $debug['manager']);
        $this->assertSame($this->getDatabaseName(), $debug['databaseName']);
        $this->assertSame($this->getCollectionName(), $debug['collectionName']);
265
        $this->assertInstanceOf(ReadConcern::class, $debug['readConcern']);
266
        $this->assertSame(ReadConcern::LOCAL, $debug['readConcern']->getLevel());
267
        $this->assertInstanceOf(ReadPreference::class, $debug['readPreference']);
268
        $this->assertSame(ReadPreference::RP_SECONDARY_PREFERRED, $debug['readPreference']->getMode());
269
        $this->assertIsArray($debug['typeMap']);
270
        $this->assertSame(['root' => 'array'], $debug['typeMap']);
271
        $this->assertInstanceOf(WriteConcern::class, $debug['writeConcern']);
272 273 274
        $this->assertSame(WriteConcern::MAJORITY, $debug['writeConcern']->getW());
    }

275
    public function testWithOptionsPassesOptions()
276 277
    {
        $collectionOptions = [
278
            'readConcern' => new ReadConcern(ReadConcern::LOCAL),
279
            'readPreference' => new ReadPreference(ReadPreference::RP_SECONDARY_PREFERRED),
280
            'typeMap' => ['root' => 'array'],
281 282 283 284 285 286
            'writeConcern' => new WriteConcern(WriteConcern::MAJORITY),
        ];

        $clone = $this->collection->withOptions($collectionOptions);
        $debug = $clone->__debugInfo();

287
        $this->assertInstanceOf(ReadConcern::class, $debug['readConcern']);
288
        $this->assertSame(ReadConcern::LOCAL, $debug['readConcern']->getLevel());
289
        $this->assertInstanceOf(ReadPreference::class, $debug['readPreference']);
290
        $this->assertSame(ReadPreference::RP_SECONDARY_PREFERRED, $debug['readPreference']->getMode());
291
        $this->assertIsArray($debug['typeMap']);
292
        $this->assertSame(['root' => 'array'], $debug['typeMap']);
293
        $this->assertInstanceOf(WriteConcern::class, $debug['writeConcern']);
294 295 296
        $this->assertSame(WriteConcern::MAJORITY, $debug['writeConcern']->getW());
    }

297 298 299 300 301 302 303 304 305 306
    public function testMapReduce()
    {
        $this->createFixtures(3);

        $map = new Javascript('function() { emit(1, this.x); }');
        $reduce = new Javascript('function(key, values) { return Array.sum(values); }');
        $out = ['inline' => 1];

        $result = $this->collection->mapReduce($map, $reduce, $out);

307
        $this->assertInstanceOf(MapReduceResult::class, $result);
308 309 310 311 312 313 314 315 316 317
        $expected = [
            [ '_id' => 1.0, 'value' => 66.0 ],
        ];

        $this->assertSameDocuments($expected, $result);

        $this->assertGreaterThanOrEqual(0, $result->getExecutionTimeMS());
        $this->assertNotEmpty($result->getCounts());
    }

318 319 320 321
    public function collectionMethodClosures()
    {
        return [
            [
322
                function ($collection, $session, $options = []) {
323 324 325 326
                    $collection->aggregate(
                        [['$match' => ['_id' => ['$lt' => 3]]]],
                        ['session' => $session] + $options
                    );
327
                }, 'rw',
328 329 330
            ],

            [
331
                function ($collection, $session, $options = []) {
332 333 334 335
                    $collection->bulkWrite(
                        [['insertOne' => [['test' => 'foo']]]],
                        ['session' => $session] + $options
                    );
336
                }, 'w',
337 338 339 340 341 342 343 344 345 346 347 348 349 350
            ],

            /* Disabled, as count command can't be used in transactions
            [
                function($collection, $session, $options = []) {
                    $collection->count(
                        [],
                        ['session' => $session] + $options
                    );
                }, 'r'
            ],
            */

            [
351
                function ($collection, $session, $options = []) {
352 353 354 355
                    $collection->countDocuments(
                        [],
                        ['session' => $session] + $options
                    );
356
                }, 'r',
357 358 359 360 361 362 363 364 365 366 367 368 369 370
            ],

            /* Disabled, as it's illegal to use createIndex command in transactions
            [
                function($collection, $session, $options = []) {
                    $collection->createIndex(
                        ['test' => 1],
                        ['session' => $session] + $options
                    );
                }, 'w'
            ],
            */

            [
371
                function ($collection, $session, $options = []) {
372 373 374 375
                    $collection->deleteMany(
                        ['test' => 'foo'],
                        ['session' => $session] + $options
                    );
376
                }, 'w',
377 378 379
            ],

            [
380
                function ($collection, $session, $options = []) {
381 382 383 384
                    $collection->deleteOne(
                        ['test' => 'foo'],
                        ['session' => $session] + $options
                    );
385
                }, 'w',
386 387 388
            ],

            [
389
                function ($collection, $session, $options = []) {
390 391 392 393 394
                    $collection->distinct(
                        '_id',
                        [],
                        ['session' => $session] + $options
                    );
395
                }, 'r',
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
            ],

            /* Disabled, as it's illegal to use drop command in transactions
            [
                function($collection, $session, $options = []) {
                    $collection->drop(
                        ['session' => $session] + $options
                    );
                }, 'w'
            ],
            */

            /* Disabled, as it's illegal to use dropIndexes command in transactions
            [
                function($collection, $session, $options = []) {
                    $collection->dropIndex(
                        '_id_1',
                        ['session' => $session] + $options
                    );
                }, 'w'
            ], */

            /* Disabled, as it's illegal to use dropIndexes command in transactions
            [
                function($collection, $session, $options = []) {
                    $collection->dropIndexes(
                        ['session' => $session] + $options
                    );
                }, 'w'
            ],
            */

            /* Disabled, as count command can't be used in transactions
            [
                function($collection, $session, $options = []) {
                    $collection->estimatedDocumentCount(
                        ['session' => $session] + $options
                    );
                }, 'r'
            ],
            */

            [
439
                function ($collection, $session, $options = []) {
440 441 442 443
                    $collection->find(
                        ['test' => 'foo'],
                        ['session' => $session] + $options
                    );
444
                }, 'r',
445 446 447
            ],

            [
448
                function ($collection, $session, $options = []) {
449 450 451 452
                    $collection->findOne(
                        ['test' => 'foo'],
                        ['session' => $session] + $options
                    );
453
                }, 'r',
454 455 456
            ],

            [
457
                function ($collection, $session, $options = []) {
458 459 460 461
                    $collection->findOneAndDelete(
                        ['test' => 'foo'],
                        ['session' => $session] + $options
                    );
462
                }, 'w',
463 464 465
            ],

            [
466
                function ($collection, $session, $options = []) {
467 468 469 470 471
                    $collection->findOneAndReplace(
                        ['test' => 'foo'],
                        [],
                        ['session' => $session] + $options
                    );
472
                }, 'w',
473 474 475
            ],

            [
476
                function ($collection, $session, $options = []) {
477 478 479 480 481
                    $collection->findOneAndUpdate(
                        ['test' => 'foo'],
                        ['$set' => ['updated' => 1]],
                        ['session' => $session] + $options
                    );
482
                }, 'w',
483 484 485
            ],

            [
486
                function ($collection, $session, $options = []) {
487 488 489 490 491 492 493
                    $collection->insertMany(
                        [
                            ['test' => 'foo'],
                            ['test' => 'bar'],
                        ],
                        ['session' => $session] + $options
                    );
494
                }, 'w',
495 496 497
            ],

            [
498
                function ($collection, $session, $options = []) {
499 500 501 502
                    $collection->insertOne(
                        ['test' => 'foo'],
                        ['session' => $session] + $options
                    );
503
                }, 'w',
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
            ],

            /* Disabled, as it's illegal to use listIndexes command in transactions
            [
                function($collection, $session, $options = []) {
                    $collection->listIndexes(
                        ['session' => $session] + $options
                    );
                }, 'r'
            ],
            */

            /* Disabled, as it's illegal to use mapReduce command in transactions
            [
                function($collection, $session, $options = []) {
                    $collection->mapReduce(
                        new \MongoDB\BSON\Javascript('function() { emit(this.state, this.pop); }'),
                        new \MongoDB\BSON\Javascript('function(key, values) { return Array.sum(values) }'),
                        ['inline' => 1],
                        ['session' => $session] + $options
                    );
                }, 'rw'
            ],
            */

            [
530
                function ($collection, $session, $options = []) {
531 532 533 534 535
                    $collection->replaceOne(
                        ['test' => 'foo'],
                        [],
                        ['session' => $session] + $options
                    );
536
                }, 'w',
537 538 539
            ],

            [
540
                function ($collection, $session, $options = []) {
541 542 543 544 545
                    $collection->updateMany(
                        ['test' => 'foo'],
                        ['$set' => ['updated' => 1]],
                        ['session' => $session] + $options
                    );
546
                }, 'w',
547 548 549
            ],

            [
550
                function ($collection, $session, $options = []) {
551 552 553 554 555
                    $collection->updateOne(
                        ['test' => 'foo'],
                        ['$set' => ['updated' => 1]],
                        ['session' => $session] + $options
                    );
556
                }, 'w',
557
            ],
558 559 560 561 562 563 564 565 566 567 568

            /* Disabled, as it's illegal to use change streams in transactions
            [
                function($collection, $session, $options = []) {
                    $collection->watch(
                        [],
                        ['session' => $session] + $options
                    );
                }, 'r'
            ],
            */
569 570 571 572 573 574 575
        ];
    }

    public function collectionReadMethodClosures()
    {
        return array_filter(
            $this->collectionMethodClosures(),
576
            function ($rw) {
577 578 579 580 581 582 583 584 585 586 587
                if (strchr($rw[1], 'r') !== false) {
                    return true;
                }
            }
        );
    }

    public function collectionWriteMethodClosures()
    {
        return array_filter(
            $this->collectionMethodClosures(),
588
            function ($rw) {
589 590 591 592 593 594 595 596 597 598
                if (strchr($rw[1], 'w') !== false) {
                    return true;
                }
            }
        );
    }

    /**
     * @dataProvider collectionMethodClosures
     */
599
    public function testMethodDoesNotInheritReadWriteConcernInTranasaction(Closure $method)
600 601 602 603 604 605 606 607 608 609
    {
        $this->skipIfTransactionsAreNotSupported();

        $this->createCollection();

        $session = $this->manager->startSession();
        $session->startTransaction();

        $collection = $this->collection->withOptions([
            'readConcern' => new ReadConcern(ReadConcern::LOCAL),
610
            'writeConcern' => new WriteConcern(1),
611 612
        ]);

613 614
        (new CommandObserver())->observe(
            function () use ($method, $collection, $session) {
615
                call_user_func($method, $collection, $session);
616
            },
617
            function (array $event) {
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
                $this->assertObjectNotHasAttribute('writeConcern', $event['started']->getCommand());
                $this->assertObjectNotHasAttribute('readConcern', $event['started']->getCommand());
            }
        );
    }

    /**
     * @dataProvider collectionWriteMethodClosures
     */
    public function testMethodInTransactionWithWriteConcernOption($method)
    {
        $this->skipIfTransactionsAreNotSupported();

        $this->createCollection();

        $session = $this->manager->startSession();
        $session->startTransaction();

636 637 638
        $this->expectException(UnsupportedException::class);
        $this->expectExceptionMessage('"writeConcern" option cannot be specified within a transaction');

639
        try {
640
            call_user_func($method, $this->collection, $session, ['writeConcern' => new WriteConcern(1)]);
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
        } finally {
            $session->endSession();
        }
    }

    /**
     * @dataProvider collectionReadMethodClosures
     */
    public function testMethodInTransactionWithReadConcernOption($method)
    {
        $this->skipIfTransactionsAreNotSupported();

        $this->createCollection();

        $session = $this->manager->startSession();
        $session->startTransaction();

658 659 660
        $this->expectException(UnsupportedException::class);
        $this->expectExceptionMessage('"readConcern" option cannot be specified within a transaction');

661
        try {
662
            call_user_func($method, $this->collection, $session, ['readConcern' => new ReadConcern(ReadConcern::LOCAL)]);
663 664 665 666 667
        } finally {
            $session->endSession();
        }
    }

668 669 670 671
    /**
     * Create data fixtures.
     *
     * @param integer $n
672
     * @param array   $executeBulkWriteOptions
673
     */
674
    private function createFixtures($n, array $executeBulkWriteOptions = [])
675
    {
676
        $bulkWrite = new BulkWrite(['ordered' => true]);
677 678

        for ($i = 1; $i <= $n; $i++) {
Jeremy Mikola's avatar
Jeremy Mikola committed
679
            $bulkWrite->insert([
680 681
                '_id' => $i,
                'x' => (integer) ($i . $i),
Jeremy Mikola's avatar
Jeremy Mikola committed
682
            ]);
683 684
        }

685
        $result = $this->manager->executeBulkWrite($this->getNamespace(), $bulkWrite, $executeBulkWriteOptions);
686 687 688

        $this->assertEquals($n, $result->getInsertedCount());
    }
689
}