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

3
namespace MongoDB\Tests\Operation;
4

5
use MongoDB\BSON\ObjectId;
6
use MongoDB\BulkWriteResult;
7
use MongoDB\Collection;
8
use MongoDB\Driver\BulkWrite as Bulk;
9
use MongoDB\Driver\WriteConcern;
10
use MongoDB\Exception\BadMethodCallException;
11
use MongoDB\Model\BSONDocument;
12
use MongoDB\Operation\BulkWrite;
13
use MongoDB\Tests\CommandObserver;
14
use Symfony\Bridge\PhpUnit\SetUpTearDownTrait;
15
use function version_compare;
16 17 18

class BulkWriteFunctionalTest extends FunctionalTestCase
{
19 20
    use SetUpTearDownTrait;

21
    /** @var Collection */
22
    private $collection;
23

24
    private function doSetUp()
25 26 27
    {
        parent::setUp();

28
        $this->collection = new Collection($this->manager, $this->getDatabaseName(), $this->getCollectionName());
29 30 31 32
    }

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

40 41 42
        $operation = new BulkWrite($this->getDatabaseName(), $this->getCollectionName(), $ops);
        $result = $operation->execute($this->getPrimaryServer());

43
        $this->assertInstanceOf(BulkWriteResult::class, $result);
44
        $this->assertSame(4, $result->getInsertedCount());
45 46 47

        $insertedIds = $result->getInsertedIds();
        $this->assertSame(1, $insertedIds[0]);
48
        $this->assertInstanceOf(ObjectId::class, $insertedIds[1]);
49 50
        $this->assertSame('foo', $insertedIds[2]);
        $this->assertSame('bar', $insertedIds[3]);
51

Jeremy Mikola's avatar
Jeremy Mikola committed
52
        $expected = [
53
            ['_id' => 1, 'x' => 11],
Jeremy Mikola's avatar
Jeremy Mikola committed
54
            ['_id' => $insertedIds[1], 'x' => 22],
55 56
            ['_id' => 'foo', 'x' => 33],
            ['_id' => 'bar', 'x' => 44],
Jeremy Mikola's avatar
Jeremy Mikola committed
57
        ];
58

59
        $this->assertSameDocuments($expected, $this->collection->find());
60 61 62 63 64 65
    }

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

Jeremy Mikola's avatar
Jeremy Mikola committed
66 67 68 69 70 71 72
        $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]]]],
        ];
73

74 75 76
        $operation = new BulkWrite($this->getDatabaseName(), $this->getCollectionName(), $ops);
        $result = $operation->execute($this->getPrimaryServer());

77
        $this->assertInstanceOf(BulkWriteResult::class, $result);
78
        $this->assertSame(5, $result->getMatchedCount());
79
        $this->assertSame(5, $result->getModifiedCount());
80 81 82 83
        $this->assertSame(2, $result->getUpsertedCount());

        $upsertedIds = $result->getUpsertedIds();
        $this->assertSame(5, $upsertedIds[2]);
84
        $this->assertInstanceOf(ObjectId::class, $upsertedIds[3]);
85

Jeremy Mikola's avatar
Jeremy Mikola committed
86 87 88 89 90 91 92 93
        $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],
        ];
94

95
        $this->assertSameDocuments($expected, $this->collection->find());
96 97 98 99 100 101
    }

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

Jeremy Mikola's avatar
Jeremy Mikola committed
102 103 104 105
        $ops = [
            ['deleteOne' => [['_id' => 1]]],
            ['deleteMany' => [['_id' => ['$gt' => 2]]]],
        ];
106

107 108 109
        $operation = new BulkWrite($this->getDatabaseName(), $this->getCollectionName(), $ops);
        $result = $operation->execute($this->getPrimaryServer());

110
        $this->assertInstanceOf(BulkWriteResult::class, $result);
111 112
        $this->assertSame(3, $result->getDeletedCount());

Jeremy Mikola's avatar
Jeremy Mikola committed
113 114 115
        $expected = [
            ['_id' => 2, 'x' => 22],
        ];
116

117
        $this->assertSameDocuments($expected, $this->collection->find());
118 119 120 121 122 123
    }

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

Jeremy Mikola's avatar
Jeremy Mikola committed
124 125 126 127 128 129 130
        $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]]],
        ];
131

132 133 134
        $operation = new BulkWrite($this->getDatabaseName(), $this->getCollectionName(), $ops);
        $result = $operation->execute($this->getPrimaryServer());

135
        $this->assertInstanceOf(BulkWriteResult::class, $result);
136 137

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

        $this->assertSame(3, $result->getMatchedCount());
141
        $this->assertSame(3, $result->getModifiedCount());
142
        $this->assertSame(1, $result->getUpsertedCount());
Jeremy Mikola's avatar
Jeremy Mikola committed
143
        $this->assertSame([4 => 4], $result->getUpsertedIds());
144 145 146

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

Jeremy Mikola's avatar
Jeremy Mikola committed
147 148 149 150 151
        $expected = [
            ['_id' => 2, 'x' => 24],
            ['_id' => 3, 'x' => 34],
            ['_id' => 4, 'x' => 44],
        ];
152

153
        $this->assertSameDocuments($expected, $this->collection->find());
154 155
    }

156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
    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)
    {
173 174
        $this->expectException(BadMethodCallException::class);
        $this->expectExceptionMessageRegExp('/[\w:\\\\]+ should not be called for an unacknowledged write result/');
175 176 177 178 179 180 181 182
        $result->getDeletedCount();
    }

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

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

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

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

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

228 229 230 231 232 233
    public function testSessionOption()
    {
        if (version_compare($this->getServerVersion(), '3.6.0', '<')) {
            $this->markTestSkipped('Sessions are not supported');
        }

234 235
        (new CommandObserver())->observe(
            function () {
236 237 238 239 240 241 242 243 244
                $operation = new BulkWrite(
                    $this->getDatabaseName(),
                    $this->getCollectionName(),
                    [['insertOne' => [['_id' => 1]]]],
                    ['session' => $this->createSession()]
                );

                $operation->execute($this->getPrimaryServer());
            },
245
            function (array $event) {
246
                $this->assertObjectHasAttribute('lsid', $event['started']->getCommand());
247 248 249 250
            }
        );
    }

251 252
    public function testBypassDocumentValidationSetWhenTrue()
    {
253 254 255 256
        if (version_compare($this->getServerVersion(), '3.2.0', '<')) {
            $this->markTestSkipped('bypassDocumentValidation is not supported');
        }

257 258
        (new CommandObserver())->observe(
            function () {
259 260 261 262 263 264 265 266 267
                $operation = new BulkWrite(
                    $this->getDatabaseName(),
                    $this->getCollectionName(),
                    [['insertOne' => [['_id' => 1]]]],
                    ['bypassDocumentValidation' => true]
                );

                $operation->execute($this->getPrimaryServer());
            },
268
            function (array $event) {
269 270 271 272 273 274 275 276
                $this->assertObjectHasAttribute('bypassDocumentValidation', $event['started']->getCommand());
                $this->assertEquals(true, $event['started']->getCommand()->bypassDocumentValidation);
            }
        );
    }

    public function testBypassDocumentValidationUnsetWhenFalse()
    {
277 278 279 280
        if (version_compare($this->getServerVersion(), '3.2.0', '<')) {
            $this->markTestSkipped('bypassDocumentValidation is not supported');
        }

281 282
        (new CommandObserver())->observe(
            function () {
283 284 285 286 287 288 289 290 291
                $operation = new BulkWrite(
                    $this->getDatabaseName(),
                    $this->getCollectionName(),
                    [['insertOne' => [['_id' => 1]]]],
                    ['bypassDocumentValidation' => false]
                );

                $operation->execute($this->getPrimaryServer());
            },
292
            function (array $event) {
293 294 295 296 297
                $this->assertObjectNotHasAttribute('bypassDocumentValidation', $event['started']->getCommand());
            }
        );
    }

298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
    public function testBulkWriteWithPipelineUpdates()
    {
        if (version_compare($this->getServerVersion(), '4.2.0', '<')) {
            $this->markTestSkipped('Pipeline-style updates are not supported');
        }

        $this->createFixtures(4);

        $ops = [
            ['updateOne' => [['_id' => 2], [['$addFields' => ['y' => 2]]]]],
            ['updateMany' => [['_id' => ['$gt' => 2]], [['$addFields' => ['y' => '$_id']]]]],
        ];

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

        $this->assertInstanceOf(BulkWriteResult::class, $result);
        $this->assertSame(3, $result->getMatchedCount());
        $this->assertSame(3, $result->getModifiedCount());

        $expected = [
            ['_id' => 1, 'x' => 11],
            ['_id' => 2, 'x' => 22, 'y' => 2],
            ['_id' => 3, 'x' => 33, 'y' => 3],
            ['_id' => 4, 'x' => 44, 'y' => 4],
        ];

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

328 329 330 331 332 333 334
    /**
     * Create data fixtures.
     *
     * @param integer $n
     */
    private function createFixtures($n)
    {
335
        $bulkWrite = new Bulk(['ordered' => true]);
336 337

        for ($i = 1; $i <= $n; $i++) {
Jeremy Mikola's avatar
Jeremy Mikola committed
338
            $bulkWrite->insert([
339 340
                '_id' => $i,
                'x' => (integer) ($i . $i),
Jeremy Mikola's avatar
Jeremy Mikola committed
341
            ]);
342 343 344 345 346 347
        }

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

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