BulkWriteFunctionalTest.php 13.2 KB
Newer Older
1 2
<?php

3
namespace MongoDB\Tests\Operation;
4

5
use MongoDB\BulkWriteResult;
6
use MongoDB\Collection;
7
use MongoDB\Driver\BulkWrite as Bulk;
8
use MongoDB\Driver\WriteConcern;
9 10
use MongoDB\Exception\BadMethodCallException;
use MongoDB\Exception\InvalidArgumentException;
11
use MongoDB\Model\BSONDocument;
12
use MongoDB\Operation\BulkWrite;
13 14
use MongoDB\Tests\CommandObserver;
use stdClass;
15 16 17

class BulkWriteFunctionalTest extends FunctionalTestCase
{
18
    private $collection;
19 20 21 22 23

    public function setUp()
    {
        parent::setUp();

24
        $this->collection = new Collection($this->manager, $this->getDatabaseName(), $this->getCollectionName());
25 26 27 28
    }

    public function testInserts()
    {
Jeremy Mikola's avatar
Jeremy Mikola committed
29 30 31
        $ops = [
            ['insertOne' => [['_id' => 1, 'x' => 11]]],
            ['insertOne' => [['x' => 22]]],
32 33
            ['insertOne' => [(object) ['_id' => 'foo', 'x' => 33]]],
            ['insertOne' => [new BSONDocument(['_id' => 'bar', 'x' => 44])]],
Jeremy Mikola's avatar
Jeremy Mikola committed
34
        ];
35

36 37 38
        $operation = new BulkWrite($this->getDatabaseName(), $this->getCollectionName(), $ops);
        $result = $operation->execute($this->getPrimaryServer());

39
        $this->assertInstanceOf('MongoDB\BulkWriteResult', $result);
40
        $this->assertSame(4, $result->getInsertedCount());
41 42 43

        $insertedIds = $result->getInsertedIds();
        $this->assertSame(1, $insertedIds[0]);
44
        $this->assertInstanceOf('MongoDB\BSON\ObjectId', $insertedIds[1]);
45 46
        $this->assertSame('foo', $insertedIds[2]);
        $this->assertSame('bar', $insertedIds[3]);
47

Jeremy Mikola's avatar
Jeremy Mikola committed
48
        $expected = [
49
            ['_id' => 1, 'x' => 11],
Jeremy Mikola's avatar
Jeremy Mikola committed
50
            ['_id' => $insertedIds[1], 'x' => 22],
51 52
            ['_id' => 'foo', 'x' => 33],
            ['_id' => 'bar', 'x' => 44],
Jeremy Mikola's avatar
Jeremy Mikola committed
53
        ];
54

55
        $this->assertSameDocuments($expected, $this->collection->find());
56 57 58 59 60 61
    }

    public function testUpdates()
    {
        $this->createFixtures(4);

Jeremy Mikola's avatar
Jeremy Mikola committed
62 63 64 65 66 67 68
        $ops = [
            ['updateOne' => [['_id' => 2], ['$inc' => ['x' => 1]]]],
            ['updateMany' => [['_id' => ['$gt' => 2]], ['$inc' => ['x' => -1]]]],
            ['updateOne' => [['_id' => 5], ['$set' => ['x' => 55]], ['upsert' => true]]],
            ['updateOne' => [['x' => 66], ['$set' => ['x' => 66]], ['upsert' => true]]],
            ['updateMany' => [['x' => ['$gt' => 50]], ['$inc' => ['x' => 1]]]],
        ];
69

70 71 72
        $operation = new BulkWrite($this->getDatabaseName(), $this->getCollectionName(), $ops);
        $result = $operation->execute($this->getPrimaryServer());

73 74
        $this->assertInstanceOf('MongoDB\BulkWriteResult', $result);
        $this->assertSame(5, $result->getMatchedCount());
75
        $this->assertSame(5, $result->getModifiedCount());
76 77 78 79
        $this->assertSame(2, $result->getUpsertedCount());

        $upsertedIds = $result->getUpsertedIds();
        $this->assertSame(5, $upsertedIds[2]);
80
        $this->assertInstanceOf('MongoDB\BSON\ObjectId', $upsertedIds[3]);
81

Jeremy Mikola's avatar
Jeremy Mikola committed
82 83 84 85 86 87 88 89
        $expected = [
            ['_id' => 1, 'x' => 11],
            ['_id' => 2, 'x' => 23],
            ['_id' => 3, 'x' => 32],
            ['_id' => 4, 'x' => 43],
            ['_id' => 5, 'x' => 56],
            ['_id' => $upsertedIds[3], 'x' => 67],
        ];
90

91
        $this->assertSameDocuments($expected, $this->collection->find());
92 93 94 95 96 97
    }

    public function testDeletes()
    {
        $this->createFixtures(4);

Jeremy Mikola's avatar
Jeremy Mikola committed
98 99 100 101
        $ops = [
            ['deleteOne' => [['_id' => 1]]],
            ['deleteMany' => [['_id' => ['$gt' => 2]]]],
        ];
102

103 104 105
        $operation = new BulkWrite($this->getDatabaseName(), $this->getCollectionName(), $ops);
        $result = $operation->execute($this->getPrimaryServer());

106 107 108
        $this->assertInstanceOf('MongoDB\BulkWriteResult', $result);
        $this->assertSame(3, $result->getDeletedCount());

Jeremy Mikola's avatar
Jeremy Mikola committed
109 110 111
        $expected = [
            ['_id' => 2, 'x' => 22],
        ];
112

113
        $this->assertSameDocuments($expected, $this->collection->find());
114 115 116 117 118 119
    }

    public function testMixedOrderedOperations()
    {
        $this->createFixtures(3);

Jeremy Mikola's avatar
Jeremy Mikola committed
120 121 122 123 124 125 126
        $ops = [
            ['updateOne' => [['_id' => ['$gt' => 1]], ['$inc' => ['x' => 1]]]],
            ['updateMany' => [['_id' => ['$gt' => 1]], ['$inc' => ['x' => 1]]]],
            ['insertOne' => [['_id' => 4, 'x' => 44]]],
            ['deleteMany' => [['x' => ['$nin' => [24, 34]]]]],
            ['replaceOne' => [['_id' => 4], ['_id' => 4, 'x' => 44], ['upsert' => true]]],
        ];
127

128 129 130
        $operation = new BulkWrite($this->getDatabaseName(), $this->getCollectionName(), $ops);
        $result = $operation->execute($this->getPrimaryServer());

131 132 133
        $this->assertInstanceOf('MongoDB\BulkWriteResult', $result);

        $this->assertSame(1, $result->getInsertedCount());
Jeremy Mikola's avatar
Jeremy Mikola committed
134
        $this->assertSame([2 => 4], $result->getInsertedIds());
135 136

        $this->assertSame(3, $result->getMatchedCount());
137
        $this->assertSame(3, $result->getModifiedCount());
138
        $this->assertSame(1, $result->getUpsertedCount());
Jeremy Mikola's avatar
Jeremy Mikola committed
139
        $this->assertSame([4 => 4], $result->getUpsertedIds());
140 141 142

        $this->assertSame(2, $result->getDeletedCount());

Jeremy Mikola's avatar
Jeremy Mikola committed
143 144 145 146 147
        $expected = [
            ['_id' => 2, 'x' => 24],
            ['_id' => 3, 'x' => 34],
            ['_id' => 4, 'x' => 44],
        ];
148

149
        $this->assertSameDocuments($expected, $this->collection->find());
150 151
    }

152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
    public function testUnacknowledgedWriteConcern()
    {
        $ops = [['insertOne' => [['_id' => 1]]]];
        $options = ['writeConcern' => new WriteConcern(0)];
        $operation = new BulkWrite($this->getDatabaseName(), $this->getCollectionName(), $ops, $options);
        $result = $operation->execute($this->getPrimaryServer());

        $this->assertFalse($result->isAcknowledged());

        return $result;
    }

    /**
     * @depends testUnacknowledgedWriteConcern
     */
    public function testUnacknowledgedWriteConcernAccessesDeletedCount(BulkWriteResult $result)
    {
169 170
        $this->expectException(BadMethodCallException::class);
        $this->expectExceptionMessageRegExp('/[\w:\\\\]+ should not be called for an unacknowledged write result/');
171 172 173 174 175 176 177 178
        $result->getDeletedCount();
    }

    /**
     * @depends testUnacknowledgedWriteConcern
     */
    public function testUnacknowledgedWriteConcernAccessesInsertCount(BulkWriteResult $result)
    {
179 180
        $this->expectException(BadMethodCallException::class);
        $this->expectExceptionMessageRegExp('/[\w:\\\\]+ should not be called for an unacknowledged write result/');
181 182 183 184 185 186 187 188
        $result->getInsertedCount();
    }

    /**
     * @depends testUnacknowledgedWriteConcern
     */
    public function testUnacknowledgedWriteConcernAccessesMatchedCount(BulkWriteResult $result)
    {
189 190
        $this->expectException(BadMethodCallException::class);
        $this->expectExceptionMessageRegExp('/[\w:\\\\]+ should not be called for an unacknowledged write result/');
191 192 193 194 195 196 197 198
        $result->getMatchedCount();
    }

    /**
     * @depends testUnacknowledgedWriteConcern
     */
    public function testUnacknowledgedWriteConcernAccessesModifiedCount(BulkWriteResult $result)
    {
199 200
        $this->expectException(BadMethodCallException::class);
        $this->expectExceptionMessageRegExp('/[\w:\\\\]+ should not be called for an unacknowledged write result/');
201 202 203 204 205 206 207 208
        $result->getModifiedCount();
    }

    /**
     * @depends testUnacknowledgedWriteConcern
     */
    public function testUnacknowledgedWriteConcernAccessesUpsertedCount(BulkWriteResult $result)
    {
209 210
        $this->expectException(BadMethodCallException::class);
        $this->expectExceptionMessageRegExp('/[\w:\\\\]+ should not be called for an unacknowledged write result/');
211 212 213 214 215 216 217 218
        $result->getUpsertedCount();
    }

    /**
     * @depends testUnacknowledgedWriteConcern
     */
    public function testUnacknowledgedWriteConcernAccessesUpsertedIds(BulkWriteResult $result)
    {
219 220
        $this->expectException(BadMethodCallException::class);
        $this->expectExceptionMessageRegExp('/[\w:\\\\]+ should not be called for an unacknowledged write result/');
221 222 223
        $result->getUpsertedIds();
    }

224 225
    public function testUnknownOperation()
    {
226 227
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage('Unknown operation type "foo" in $operations[0]');
228
        new BulkWrite($this->getDatabaseName(), $this->getCollectionName(), [
Jeremy Mikola's avatar
Jeremy Mikola committed
229 230
            ['foo' => [['_id' => 1]]],
        ]);
231 232 233 234 235 236 237
    }

    /**
     * @dataProvider provideOpsWithMissingArguments
     */
    public function testMissingArguments(array $ops)
    {
238 239
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessageRegExp('/Missing (first|second) argument for \$operations\[\d+\]\["\w+\"]/');
240
        new BulkWrite($this->getDatabaseName(), $this->getCollectionName(), $ops);
241 242 243 244
    }

    public function provideOpsWithMissingArguments()
    {
Jeremy Mikola's avatar
Jeremy Mikola committed
245 246 247 248 249 250 251 252 253 254 255
        return [
            [[['insertOne' => []]]],
            [[['updateOne' => []]]],
            [[['updateOne' => [['_id' => 1]]]]],
            [[['updateMany' => []]]],
            [[['updateMany' => [['_id' => 1]]]]],
            [[['replaceOne' => []]]],
            [[['replaceOne' => [['_id' => 1]]]]],
            [[['deleteOne' => []]]],
            [[['deleteMany' => []]]],
        ];
256 257 258 259
    }

    public function testUpdateOneRequiresUpdateOperators()
    {
260 261
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage('First key in $operations[0]["updateOne"][1] is not an update operator');
262
        new BulkWrite($this->getDatabaseName(), $this->getCollectionName(), [
Jeremy Mikola's avatar
Jeremy Mikola committed
263 264
            ['updateOne' => [['_id' => 1], ['x' => 1]]],
        ]);
265 266 267 268
    }

    public function testUpdateManyRequiresUpdateOperators()
    {
269 270
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage('First key in $operations[0]["updateMany"][1] is not an update operator');
271
        new BulkWrite($this->getDatabaseName(), $this->getCollectionName(), [
Jeremy Mikola's avatar
Jeremy Mikola committed
272 273
            ['updateMany' => [['_id' => ['$gt' => 1]], ['x' => 1]]],
        ]);
274 275 276 277
    }

    public function testReplaceOneRequiresReplacementDocument()
    {
278 279
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage('First key in $operations[0]["replaceOne"][1] is an update operator');
280
        new BulkWrite($this->getDatabaseName(), $this->getCollectionName(), [
Jeremy Mikola's avatar
Jeremy Mikola committed
281 282
            ['replaceOne' => [['_id' => 1], ['$inc' => ['x' => 1]]]],
        ]);
283 284
    }

285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
    public function testSessionOption()
    {
        if (version_compare($this->getServerVersion(), '3.6.0', '<')) {
            $this->markTestSkipped('Sessions are not supported');
        }

        (new CommandObserver)->observe(
            function() {
                $operation = new BulkWrite(
                    $this->getDatabaseName(),
                    $this->getCollectionName(),
                    [['insertOne' => [['_id' => 1]]]],
                    ['session' => $this->createSession()]
                );

                $operation->execute($this->getPrimaryServer());
            },
302 303
            function(array $event) {
                $this->assertObjectHasAttribute('lsid', $event['started']->getCommand());
304 305 306 307
            }
        );
    }

308 309
    public function testBypassDocumentValidationSetWhenTrue()
    {
310 311 312 313
        if (version_compare($this->getServerVersion(), '3.2.0', '<')) {
            $this->markTestSkipped('bypassDocumentValidation is not supported');
        }

314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
        (new CommandObserver)->observe(
            function() {
                $operation = new BulkWrite(
                    $this->getDatabaseName(),
                    $this->getCollectionName(),
                    [['insertOne' => [['_id' => 1]]]],
                    ['bypassDocumentValidation' => true]
                );

                $operation->execute($this->getPrimaryServer());
            },
            function(array $event) {
                $this->assertObjectHasAttribute('bypassDocumentValidation', $event['started']->getCommand());
                $this->assertEquals(true, $event['started']->getCommand()->bypassDocumentValidation);
            }
        );
    }

    public function testBypassDocumentValidationUnsetWhenFalse()
    {
334 335 336 337
        if (version_compare($this->getServerVersion(), '3.2.0', '<')) {
            $this->markTestSkipped('bypassDocumentValidation is not supported');
        }

338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
        (new CommandObserver)->observe(
            function() {
                $operation = new BulkWrite(
                    $this->getDatabaseName(),
                    $this->getCollectionName(),
                    [['insertOne' => [['_id' => 1]]]],
                    ['bypassDocumentValidation' => false]
                );

                $operation->execute($this->getPrimaryServer());
            },
            function(array $event) {
                $this->assertObjectNotHasAttribute('bypassDocumentValidation', $event['started']->getCommand());
            }
        );
    }

355 356 357 358 359 360 361
    /**
     * Create data fixtures.
     *
     * @param integer $n
     */
    private function createFixtures($n)
    {
362
        $bulkWrite = new Bulk(['ordered' => true]);
363 364

        for ($i = 1; $i <= $n; $i++) {
Jeremy Mikola's avatar
Jeremy Mikola committed
365
            $bulkWrite->insert([
366 367
                '_id' => $i,
                'x' => (integer) ($i . $i),
Jeremy Mikola's avatar
Jeremy Mikola committed
368
            ]);
369 370 371 372 373 374
        }

        $result = $this->manager->executeBulkWrite($this->getNamespace(), $bulkWrite);

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