CollectionFunctionalTest.php 24.7 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
use function array_filter;
use function call_user_func;
19 20
use function is_scalar;
use function json_encode;
21
use function strchr;
22
use function usort;
23
use function version_compare;
24

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

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

    public function provideInvalidDatabaseAndCollectionNames()
51
    {
Jeremy Mikola's avatar
Jeremy Mikola committed
52 53 54 55
        return [
            [null],
            [''],
        ];
56 57
    }

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

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

71 72 73 74
        foreach ($this->getInvalidReadConcernValues() as $value) {
            $options[][] = ['readConcern' => $value];
        }

75 76 77 78
        foreach ($this->getInvalidReadPreferenceValues() as $value) {
            $options[][] = ['readPreference' => $value];
        }

79 80 81 82
        foreach ($this->getInvalidArrayValues() as $value) {
            $options[][] = ['typeMap' => $value];
        }

83 84 85 86 87 88 89
        foreach ($this->getInvalidWriteConcernValues() as $value) {
            $options[][] = ['writeConcern' => $value];
        }

        return $options;
    }

90 91 92 93 94
    public function testGetManager()
    {
        $this->assertSame($this->manager, $this->collection->getManager());
    }

95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
    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());
    }

115 116 117 118 119
    public function testAggregateWithinTransaction()
    {
        $this->skipIfTransactionsAreNotSupported();

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

        $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();
        }
    }

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

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

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
    /**
     * @dataProvider provideTypeMapOptionsAndExpectedDocuments
     */
    public function testDistinctWithTypeMap(array $typeMap, array $expectedDocuments)
    {
        $bulkWrite = new BulkWrite(['ordered' => true]);
        $bulkWrite->insert([
            'x' => (object) ['foo' => 'bar'],
        ]);
        $bulkWrite->insert(['x' => 4]);
        $bulkWrite->insert([
            'x' => (object) ['foo' => ['foo' => 'bar']],
        ]);
        $this->manager->executeBulkWrite($this->getNamespace(), $bulkWrite);

        $values = $this->collection->withOptions(['typeMap' => $typeMap])->distinct('x');

        /* This sort callable sorts all scalars to the front of the list. All
         * non-scalar values are sorted by running json_encode on them and
         * comparing their string representations.
         */
        $sort = function ($a, $b) {
            if (is_scalar($a) && ! is_scalar($b)) {
                return -1;
            }

            if (! is_scalar($a)) {
                if (is_scalar($b)) {
                    return 1;
                }

                $a = json_encode($a);
                $b = json_encode($b);
            }

            return $a < $b ? -1 : 1;
        };

        usort($expectedDocuments, $sort);
        usort($values, $sort);

        $this->assertEquals($expectedDocuments, $values);
    }

    public function provideTypeMapOptionsAndExpectedDocuments()
    {
        return [
            'No type map' => [
                ['root' => 'array', 'document' => 'array'],
                [
                    ['foo' => 'bar'],
                    4,
                    ['foo' => ['foo' => 'bar']],
                ],
            ],
            'array/array' => [
                ['root' => 'array', 'document' => 'array'],
                [
                    ['foo' => 'bar'],
                    4,
                    ['foo' => ['foo' => 'bar']],
                ],
            ],
            'object/array' => [
                ['root' => 'object', 'document' => 'array'],
                [
                    (object) ['foo' => 'bar'],
                    4,
                    (object) ['foo' => ['foo' => 'bar']],
                ],
            ],
            'array/stdClass' => [
                ['root' => 'array', 'document' => 'stdClass'],
                [
                    ['foo' => 'bar'],
                    4,
                    ['foo' => (object) ['foo' => 'bar']],
                ],
            ],
        ];
    }

258 259
    public function testDrop()
    {
Jeremy Mikola's avatar
Jeremy Mikola committed
260
        $writeResult = $this->collection->insertOne(['x' => 1]);
261 262 263 264 265 266
        $this->assertEquals(1, $writeResult->getInsertedCount());

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

268 269 270 271 272
    /**
     * @todo Move this to a unit test once Manager can be mocked
     */
    public function testDropIndexShouldNotAllowWildcardCharacter()
    {
273
        $this->expectException(InvalidArgumentException::class);
274 275 276
        $this->collection->dropIndex('*');
    }

277 278 279 280 281 282 283 284 285 286 287
    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);
    }

288 289 290 291
    public function testFindOne()
    {
        $this->createFixtures(5);

Jeremy Mikola's avatar
Jeremy Mikola committed
292 293
        $filter = ['_id' => ['$lt' => 5]];
        $options = [
294
            'skip' => 1,
Jeremy Mikola's avatar
Jeremy Mikola committed
295 296
            'sort' => ['x' => -1],
        ];
297

298
        $expected = ['_id' => 3, 'x' => 33];
299

300
        $this->assertSameDocument($expected, $this->collection->findOne($filter, $options));
301 302
    }

303 304 305 306 307
    public function testFindWithinTransaction()
    {
        $this->skipIfTransactionsAreNotSupported();

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

        $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();
        }
    }

334
    public function testWithOptionsInheritsOptions()
335 336
    {
        $collectionOptions = [
337
            'readConcern' => new ReadConcern(ReadConcern::LOCAL),
338
            'readPreference' => new ReadPreference(ReadPreference::RP_SECONDARY_PREFERRED),
339
            'typeMap' => ['root' => 'array'],
340 341 342
            'writeConcern' => new WriteConcern(WriteConcern::MAJORITY),
        ];

343
        $collection = new Collection($this->manager, $this->getDatabaseName(), $this->getCollectionName(), $collectionOptions);
344 345 346
        $clone = $collection->withOptions();
        $debug = $clone->__debugInfo();

347 348 349
        $this->assertSame($this->manager, $debug['manager']);
        $this->assertSame($this->getDatabaseName(), $debug['databaseName']);
        $this->assertSame($this->getCollectionName(), $debug['collectionName']);
350
        $this->assertInstanceOf(ReadConcern::class, $debug['readConcern']);
351
        $this->assertSame(ReadConcern::LOCAL, $debug['readConcern']->getLevel());
352
        $this->assertInstanceOf(ReadPreference::class, $debug['readPreference']);
353
        $this->assertSame(ReadPreference::RP_SECONDARY_PREFERRED, $debug['readPreference']->getMode());
354
        $this->assertIsArray($debug['typeMap']);
355
        $this->assertSame(['root' => 'array'], $debug['typeMap']);
356
        $this->assertInstanceOf(WriteConcern::class, $debug['writeConcern']);
357 358 359
        $this->assertSame(WriteConcern::MAJORITY, $debug['writeConcern']->getW());
    }

360
    public function testWithOptionsPassesOptions()
361 362
    {
        $collectionOptions = [
363
            'readConcern' => new ReadConcern(ReadConcern::LOCAL),
364
            'readPreference' => new ReadPreference(ReadPreference::RP_SECONDARY_PREFERRED),
365
            'typeMap' => ['root' => 'array'],
366 367 368 369 370 371
            'writeConcern' => new WriteConcern(WriteConcern::MAJORITY),
        ];

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

372
        $this->assertInstanceOf(ReadConcern::class, $debug['readConcern']);
373
        $this->assertSame(ReadConcern::LOCAL, $debug['readConcern']->getLevel());
374
        $this->assertInstanceOf(ReadPreference::class, $debug['readPreference']);
375
        $this->assertSame(ReadPreference::RP_SECONDARY_PREFERRED, $debug['readPreference']->getMode());
376
        $this->assertIsArray($debug['typeMap']);
377
        $this->assertSame(['root' => 'array'], $debug['typeMap']);
378
        $this->assertInstanceOf(WriteConcern::class, $debug['writeConcern']);
379 380 381
        $this->assertSame(WriteConcern::MAJORITY, $debug['writeConcern']->getW());
    }

382 383 384 385 386 387 388 389 390 391
    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);

392
        $this->assertInstanceOf(MapReduceResult::class, $result);
393 394 395 396 397 398 399 400 401 402
        $expected = [
            [ '_id' => 1.0, 'value' => 66.0 ],
        ];

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

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

403 404 405 406
    public function collectionMethodClosures()
    {
        return [
            [
407
                function ($collection, $session, $options = []) {
408 409 410 411
                    $collection->aggregate(
                        [['$match' => ['_id' => ['$lt' => 3]]]],
                        ['session' => $session] + $options
                    );
412
                }, 'rw',
413 414 415
            ],

            [
416
                function ($collection, $session, $options = []) {
417 418 419 420
                    $collection->bulkWrite(
                        [['insertOne' => [['test' => 'foo']]]],
                        ['session' => $session] + $options
                    );
421
                }, 'w',
422 423 424 425 426 427 428 429 430 431 432 433 434 435
            ],

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

            [
436
                function ($collection, $session, $options = []) {
437 438 439 440
                    $collection->countDocuments(
                        [],
                        ['session' => $session] + $options
                    );
441
                }, 'r',
442 443 444 445 446 447 448 449 450 451 452 453 454 455
            ],

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

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

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

            [
474
                function ($collection, $session, $options = []) {
475 476 477 478 479
                    $collection->distinct(
                        '_id',
                        [],
                        ['session' => $session] + $options
                    );
480
                }, 'r',
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
            ],

            /* 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'
            ],
            */

            [
524
                function ($collection, $session, $options = []) {
525 526 527 528
                    $collection->find(
                        ['test' => 'foo'],
                        ['session' => $session] + $options
                    );
529
                }, 'r',
530 531 532
            ],

            [
533
                function ($collection, $session, $options = []) {
534 535 536 537
                    $collection->findOne(
                        ['test' => 'foo'],
                        ['session' => $session] + $options
                    );
538
                }, 'r',
539 540 541
            ],

            [
542
                function ($collection, $session, $options = []) {
543 544 545 546
                    $collection->findOneAndDelete(
                        ['test' => 'foo'],
                        ['session' => $session] + $options
                    );
547
                }, 'w',
548 549 550
            ],

            [
551
                function ($collection, $session, $options = []) {
552 553 554 555 556
                    $collection->findOneAndReplace(
                        ['test' => 'foo'],
                        [],
                        ['session' => $session] + $options
                    );
557
                }, 'w',
558 559 560
            ],

            [
561
                function ($collection, $session, $options = []) {
562 563 564 565 566
                    $collection->findOneAndUpdate(
                        ['test' => 'foo'],
                        ['$set' => ['updated' => 1]],
                        ['session' => $session] + $options
                    );
567
                }, 'w',
568 569 570
            ],

            [
571
                function ($collection, $session, $options = []) {
572 573 574 575 576 577 578
                    $collection->insertMany(
                        [
                            ['test' => 'foo'],
                            ['test' => 'bar'],
                        ],
                        ['session' => $session] + $options
                    );
579
                }, 'w',
580 581 582
            ],

            [
583
                function ($collection, $session, $options = []) {
584 585 586 587
                    $collection->insertOne(
                        ['test' => 'foo'],
                        ['session' => $session] + $options
                    );
588
                }, 'w',
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
            ],

            /* 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'
            ],
            */

            [
615
                function ($collection, $session, $options = []) {
616 617 618 619 620
                    $collection->replaceOne(
                        ['test' => 'foo'],
                        [],
                        ['session' => $session] + $options
                    );
621
                }, 'w',
622 623 624
            ],

            [
625
                function ($collection, $session, $options = []) {
626 627 628 629 630
                    $collection->updateMany(
                        ['test' => 'foo'],
                        ['$set' => ['updated' => 1]],
                        ['session' => $session] + $options
                    );
631
                }, 'w',
632 633 634
            ],

            [
635
                function ($collection, $session, $options = []) {
636 637 638 639 640
                    $collection->updateOne(
                        ['test' => 'foo'],
                        ['$set' => ['updated' => 1]],
                        ['session' => $session] + $options
                    );
641
                }, 'w',
642
            ],
643 644 645 646 647 648 649 650 651 652 653

            /* Disabled, as it's illegal to use change streams in transactions
            [
                function($collection, $session, $options = []) {
                    $collection->watch(
                        [],
                        ['session' => $session] + $options
                    );
                }, 'r'
            ],
            */
654 655 656 657 658 659 660
        ];
    }

    public function collectionReadMethodClosures()
    {
        return array_filter(
            $this->collectionMethodClosures(),
661
            function ($rw) {
662 663 664 665 666 667 668 669 670 671 672
                if (strchr($rw[1], 'r') !== false) {
                    return true;
                }
            }
        );
    }

    public function collectionWriteMethodClosures()
    {
        return array_filter(
            $this->collectionMethodClosures(),
673
            function ($rw) {
674 675 676 677 678 679 680 681 682 683
                if (strchr($rw[1], 'w') !== false) {
                    return true;
                }
            }
        );
    }

    /**
     * @dataProvider collectionMethodClosures
     */
684
    public function testMethodDoesNotInheritReadWriteConcernInTranasaction(Closure $method)
685 686 687 688 689 690 691 692 693 694
    {
        $this->skipIfTransactionsAreNotSupported();

        $this->createCollection();

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

        $collection = $this->collection->withOptions([
            'readConcern' => new ReadConcern(ReadConcern::LOCAL),
695
            'writeConcern' => new WriteConcern(1),
696 697
        ]);

698 699
        (new CommandObserver())->observe(
            function () use ($method, $collection, $session) {
700
                call_user_func($method, $collection, $session);
701
            },
702
            function (array $event) {
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
                $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();

721 722 723
        $this->expectException(UnsupportedException::class);
        $this->expectExceptionMessage('"writeConcern" option cannot be specified within a transaction');

724
        try {
725
            call_user_func($method, $this->collection, $session, ['writeConcern' => new WriteConcern(1)]);
726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
        } finally {
            $session->endSession();
        }
    }

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

        $this->createCollection();

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

743 744 745
        $this->expectException(UnsupportedException::class);
        $this->expectExceptionMessage('"readConcern" option cannot be specified within a transaction');

746
        try {
747
            call_user_func($method, $this->collection, $session, ['readConcern' => new ReadConcern(ReadConcern::LOCAL)]);
748 749 750 751 752
        } finally {
            $session->endSession();
        }
    }

753 754 755 756
    /**
     * Create data fixtures.
     *
     * @param integer $n
757
     * @param array   $executeBulkWriteOptions
758
     */
759
    private function createFixtures($n, array $executeBulkWriteOptions = [])
760
    {
761
        $bulkWrite = new BulkWrite(['ordered' => true]);
762 763

        for ($i = 1; $i <= $n; $i++) {
Jeremy Mikola's avatar
Jeremy Mikola committed
764
            $bulkWrite->insert([
765 766
                '_id' => $i,
                'x' => (integer) ($i . $i),
Jeremy Mikola's avatar
Jeremy Mikola committed
767
            ]);
768 769
        }

770
        $result = $this->manager->executeBulkWrite($this->getNamespace(), $bulkWrite, $executeBulkWriteOptions);
771 772 773

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