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

namespace MongoDB\Tests\Collection;

5
use MongoDB\BSON\Javascript;
6
use MongoDB\Collection;
7
use MongoDB\Driver\BulkWrite;
8
use MongoDB\Driver\ReadConcern;
9 10
use MongoDB\Driver\ReadPreference;
use MongoDB\Driver\WriteConcern;
11
use MongoDB\Exception\InvalidArgumentException;
12
use MongoDB\Operation\Count;
13
use MongoDB\Operation\MapReduce;
14
use MongoDB\Tests\CommandObserver;
15
use Exception;
16
use stdClass;
17

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

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

    public function provideInvalidDatabaseAndCollectionNames()
44
    {
Jeremy Mikola's avatar
Jeremy Mikola committed
45 46 47 48
        return [
            [null],
            [''],
        ];
49 50
    }

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

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

64 65 66 67
        foreach ($this->getInvalidReadConcernValues() as $value) {
            $options[][] = ['readConcern' => $value];
        }

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

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

76 77 78 79 80 81 82
        foreach ($this->getInvalidWriteConcernValues() as $value) {
            $options[][] = ['writeConcern' => $value];
        }

        return $options;
    }

83 84 85 86 87
    public function testGetManager()
    {
        $this->assertSame($this->manager, $this->collection->getManager());
    }

88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
    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());
    }

108 109 110 111 112
    public function testAggregateWithinTransaction()
    {
        $this->skipIfTransactionsAreNotSupported();

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

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

139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
    public function testCreateIndexSplitsCommandOptions()
    {
        if (version_compare($this->getServerVersion(), '3.6.0', '<')) {
            $this->markTestSkipped('Sessions are not supported');
        }

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

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

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

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

188 189 190 191 192 193 194 195 196 197 198
    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);
    }

199 200 201 202
    public function testFindOne()
    {
        $this->createFixtures(5);

Jeremy Mikola's avatar
Jeremy Mikola committed
203 204
        $filter = ['_id' => ['$lt' => 5]];
        $options = [
205
            'skip' => 1,
Jeremy Mikola's avatar
Jeremy Mikola committed
206 207
            'sort' => ['x' => -1],
        ];
208

209
        $expected = ['_id' => 3, 'x' => 33];
210

211
        $this->assertSameDocument($expected, $this->collection->findOne($filter, $options));
212 213
    }

214 215 216 217 218
    public function testFindWithinTransaction()
    {
        $this->skipIfTransactionsAreNotSupported();

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

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

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

254
        $collection = new Collection($this->manager, $this->getDatabaseName(), $this->getCollectionName(), $collectionOptions);
255 256 257
        $clone = $collection->withOptions();
        $debug = $clone->__debugInfo();

258 259 260
        $this->assertSame($this->manager, $debug['manager']);
        $this->assertSame($this->getDatabaseName(), $debug['databaseName']);
        $this->assertSame($this->getCollectionName(), $debug['collectionName']);
261
        $this->assertInstanceOf(\MongoDB\Driver\ReadConcern::class, $debug['readConcern']);
262
        $this->assertSame(ReadConcern::LOCAL, $debug['readConcern']->getLevel());
263
        $this->assertInstanceOf(\MongoDB\Driver\ReadPreference::class, $debug['readPreference']);
264
        $this->assertSame(ReadPreference::RP_SECONDARY_PREFERRED, $debug['readPreference']->getMode());
265 266
        $this->assertInternalType('array', $debug['typeMap']);
        $this->assertSame(['root' => 'array'], $debug['typeMap']);
267
        $this->assertInstanceOf(\MongoDB\Driver\WriteConcern::class, $debug['writeConcern']);
268 269 270
        $this->assertSame(WriteConcern::MAJORITY, $debug['writeConcern']->getW());
    }

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

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

283
        $this->assertInstanceOf(\MongoDB\Driver\ReadConcern::class, $debug['readConcern']);
284
        $this->assertSame(ReadConcern::LOCAL, $debug['readConcern']->getLevel());
285
        $this->assertInstanceOf(\MongoDB\Driver\ReadPreference::class, $debug['readPreference']);
286
        $this->assertSame(ReadPreference::RP_SECONDARY_PREFERRED, $debug['readPreference']->getMode());
287 288
        $this->assertInternalType('array', $debug['typeMap']);
        $this->assertSame(['root' => 'array'], $debug['typeMap']);
289
        $this->assertInstanceOf(\MongoDB\Driver\WriteConcern::class, $debug['writeConcern']);
290 291 292
        $this->assertSame(WriteConcern::MAJORITY, $debug['writeConcern']->getW());
    }

293 294 295 296 297 298 299 300 301 302
    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);

303
        $this->assertInstanceOf(\MongoDB\MapReduceResult::class, $result);
304 305 306 307 308 309 310 311 312 313
        $expected = [
            [ '_id' => 1.0, 'value' => 66.0 ],
        ];

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

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

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
    public function collectionMethodClosures()
    {
        return [
            [
                function($collection, $session, $options = []) {
                    $collection->aggregate(
                        [['$match' => ['_id' => ['$lt' => 3]]]],
                        ['session' => $session] + $options
                    );
                }, 'rw'
            ],

            [
                function($collection, $session, $options = []) {
                    $collection->bulkWrite(
                        [['insertOne' => [['test' => 'foo']]]],
                        ['session' => $session] + $options
                    );
                }, 'w'
            ],

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

            [
                function($collection, $session, $options = []) {
                    $collection->countDocuments(
                        [],
                        ['session' => $session] + $options
                    );
                }, 'r'
            ],

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

            [
                function($collection, $session, $options = []) {
                    $collection->deleteMany(
                        ['test' => 'foo'],
                        ['session' => $session] + $options
                    );
                }, 'w'
            ],

            [
                function($collection, $session, $options = []) {
                    $collection->deleteOne(
                        ['test' => 'foo'],
                        ['session' => $session] + $options
                    );
                }, 'w'
            ],

            [
                function($collection, $session, $options = []) {
                    $collection->distinct(
                        '_id',
                        [],
                        ['session' => $session] + $options
                    );
                }, 'r'
            ],

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

            [
                function($collection, $session, $options = []) {
                    $collection->find(
                        ['test' => 'foo'],
                        ['session' => $session] + $options
                    );
                }, 'r'
            ],

            [
                function($collection, $session, $options = []) {
                    $collection->findOne(
                        ['test' => 'foo'],
                        ['session' => $session] + $options
                    );
                }, 'r'
            ],

            [
                function($collection, $session, $options = []) {
                    $collection->findOneAndDelete(
                        ['test' => 'foo'],
                        ['session' => $session] + $options
                    );
                }, 'w'
            ],

            [
                function($collection, $session, $options = []) {
                    $collection->findOneAndReplace(
                        ['test' => 'foo'],
                        [],
                        ['session' => $session] + $options
                    );
                }, 'w'
            ],

            [
                function($collection, $session, $options = []) {
                    $collection->findOneAndUpdate(
                        ['test' => 'foo'],
                        ['$set' => ['updated' => 1]],
                        ['session' => $session] + $options
                    );
                }, 'w'
            ],

            [
                function($collection, $session, $options = []) {
                    $collection->insertMany(
                        [
                            ['test' => 'foo'],
                            ['test' => 'bar'],
                        ],
                        ['session' => $session] + $options
                    );
                }, 'w'
            ],

            [
                function($collection, $session, $options = []) {
                    $collection->insertOne(
                        ['test' => 'foo'],
                        ['session' => $session] + $options
                    );
                }, 'w'
            ],

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

            [
                function($collection, $session, $options = []) {
                    $collection->replaceOne(
                        ['test' => 'foo'],
                        [],
                        ['session' => $session] + $options
                    );
                }, 'w'
            ],

            [
                function($collection, $session, $options = []) {
                    $collection->updateMany(
                        ['test' => 'foo'],
                        ['$set' => ['updated' => 1]],
                        ['session' => $session] + $options
                    );
                }, 'w'
            ],

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

            /* Disabled, as it's illegal to use change streams in transactions
            [
                function($collection, $session, $options = []) {
                    $collection->watch(
                        [],
                        ['session' => $session] + $options
                    );
                }, 'r'
            ],
            */
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
        ];
    }

    public function collectionReadMethodClosures()
    {
        return array_filter(
            $this->collectionMethodClosures(),
            function($rw) {
                if (strchr($rw[1], 'r') !== false) {
                    return true;
                }
            }
        );
    }

    public function collectionWriteMethodClosures()
    {
        return array_filter(
            $this->collectionMethodClosures(),
            function($rw) {
                if (strchr($rw[1], 'w') !== false) {
                    return true;
                }
            }
        );
    }

    /**
     * @dataProvider collectionMethodClosures
     */
    public function testMethodDoesNotInheritReadWriteConcernInTranasaction(\Closure $method)
    {
        $this->skipIfTransactionsAreNotSupported();

        $this->createCollection();

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

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

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

    /**
     * @dataProvider collectionWriteMethodClosures
     * @expectedException MongoDB\Exception\UnsupportedException
     * @expectedExceptionMessage "writeConcern" option cannot be specified within a transaction
     */
    public function testMethodInTransactionWithWriteConcernOption($method)
    {
        $this->skipIfTransactionsAreNotSupported();

        $this->createCollection();

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

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

    /**
     * @dataProvider collectionReadMethodClosures
     * @expectedException MongoDB\Exception\UnsupportedException
     * @expectedExceptionMessage "readConcern" option cannot be specified within a transaction
     */
    public function testMethodInTransactionWithReadConcernOption($method)
    {
        $this->skipIfTransactionsAreNotSupported();

        $this->createCollection();

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

        try {
656
            call_user_func($method, $this->collection, $session, ['readConcern' => new ReadConcern(ReadConcern::LOCAL)]);
657 658 659 660 661
        } finally {
            $session->endSession();
        }
    }

662 663 664 665
    /**
     * Create data fixtures.
     *
     * @param integer $n
666
     * @param array   $executeBulkWriteOptions
667
     */
668
    private function createFixtures($n, array $executeBulkWriteOptions = [])
669
    {
670
        $bulkWrite = new BulkWrite(['ordered' => true]);
671 672

        for ($i = 1; $i <= $n; $i++) {
Jeremy Mikola's avatar
Jeremy Mikola committed
673
            $bulkWrite->insert([
674 675
                '_id' => $i,
                'x' => (integer) ($i . $i),
Jeremy Mikola's avatar
Jeremy Mikola committed
676
            ]);
677 678
        }

679
        $result = $this->manager->executeBulkWrite($this->getNamespace(), $bulkWrite, $executeBulkWriteOptions);
680 681 682

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