Skip to content

PHPLIB-1419 Encode Agg builder objects in Collection methods #1383

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Sep 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions psalm-baseline.xml
Original file line number Diff line number Diff line change
Expand Up @@ -191,13 +191,20 @@
<file src="src/Client.php">
<MixedArgument>
<code><![CDATA[$driverOptions['driver'] ?? []]]></code>
<code><![CDATA[$pipeline]]></code>
</MixedArgument>
<MixedAssignment>
<code><![CDATA[$mergedDriver['platform']]]></code>
</MixedAssignment>
<MixedPropertyTypeCoercion>
<code><![CDATA[$driverOptions['builderEncoder'] ?? new BuilderEncoder()]]></code>
</MixedPropertyTypeCoercion>
<NamedArgumentNotAllowed>
<code><![CDATA[$pipeline]]></code>
</NamedArgumentNotAllowed>
<PossiblyInvalidArgument>
<code><![CDATA[$pipeline]]></code>
</PossiblyInvalidArgument>
</file>
<file src="src/Codec/EncodeIfSupported.php">
<ArgumentTypeCoercion>
Expand All @@ -220,9 +227,22 @@
</MixedArgumentTypeCoercion>
</file>
<file src="src/Collection.php">
<MixedArgument>
<code><![CDATA[$pipeline]]></code>
<code><![CDATA[$pipeline]]></code>
</MixedArgument>
<MixedPropertyTypeCoercion>
<code><![CDATA[$options['builderEncoder'] ?? new BuilderEncoder()]]></code>
</MixedPropertyTypeCoercion>
<NamedArgumentNotAllowed>
<code><![CDATA[$pipeline]]></code>
<code><![CDATA[$pipeline]]></code>
</NamedArgumentNotAllowed>
<PossiblyInvalidArgument>
<code><![CDATA[$pipeline]]></code>
<code><![CDATA[$pipeline]]></code>
<code><![CDATA[$pipeline]]></code>
</PossiblyInvalidArgument>
</file>
<file src="src/Command/ListCollections.php">
<MixedAssignment>
Expand All @@ -237,9 +257,22 @@
</MixedAssignment>
</file>
<file src="src/Database.php">
<MixedArgument>
<code><![CDATA[$pipeline]]></code>
<code><![CDATA[$pipeline]]></code>
</MixedArgument>
<MixedPropertyTypeCoercion>
<code><![CDATA[$options['builderEncoder'] ?? new BuilderEncoder()]]></code>
</MixedPropertyTypeCoercion>
<NamedArgumentNotAllowed>
<code><![CDATA[$pipeline]]></code>
<code><![CDATA[$pipeline]]></code>
</NamedArgumentNotAllowed>
<PossiblyInvalidArgument>
<code><![CDATA[$pipeline]]></code>
<code><![CDATA[$pipeline]]></code>
<code><![CDATA[$pipeline]]></code>
</PossiblyInvalidArgument>
</file>
<file src="src/GridFS/Bucket.php">
<MixedArgument>
Expand Down Expand Up @@ -857,6 +890,7 @@
<MixedAssignment>
<code><![CDATA[$element[$key]]]></code>
<code><![CDATA[$stage]]></code>
<code><![CDATA[$stage]]></code>
<code><![CDATA[$type]]></code>
<code><![CDATA[$typeMap['fieldPaths'][$fieldPath . '.' . $existingFieldPath]]]></code>
<code><![CDATA[$typeMap['fieldPaths'][$fieldPath]]]></code>
Expand Down
7 changes: 7 additions & 0 deletions src/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
use MongoDB\BSON\Document;
use MongoDB\BSON\PackedArray;
use MongoDB\Builder\BuilderEncoder;
use MongoDB\Builder\Pipeline;
use MongoDB\Codec\Encoder;
use MongoDB\Driver\ClientEncryption;
use MongoDB\Driver\Exception\InvalidArgumentException as DriverInvalidArgumentException;
Expand Down Expand Up @@ -391,6 +392,12 @@ public function startSession(array $options = [])
*/
public function watch(array $pipeline = [], array $options = [])
{
if (is_builder_pipeline($pipeline)) {
$pipeline = new Pipeline(...$pipeline);
}

$pipeline = $this->builderEncoder->encodeIfSupported($pipeline);

if (! isset($options['readPreference']) && ! is_in_transaction($options)) {
$options['readPreference'] = $this->readPreference;
}
Expand Down
13 changes: 13 additions & 0 deletions src/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
use MongoDB\BSON\JavascriptInterface;
use MongoDB\BSON\PackedArray;
use MongoDB\Builder\BuilderEncoder;
use MongoDB\Builder\Pipeline;
use MongoDB\Codec\DocumentCodec;
use MongoDB\Codec\Encoder;
use MongoDB\Driver\CursorInterface;
Expand Down Expand Up @@ -223,6 +224,12 @@
*/
public function aggregate(array $pipeline, array $options = [])
{
if (is_builder_pipeline($pipeline)) {
$pipeline = new Pipeline(...$pipeline);
}

$pipeline = $this->builderEncoder->encodeIfSupported($pipeline);

$hasWriteStage = is_last_pipeline_operator_write($pipeline);

$options = $this->inheritReadPreference($options);
Expand Down Expand Up @@ -1098,6 +1105,12 @@
*/
public function watch(array $pipeline = [], array $options = [])
{
if (is_builder_pipeline($pipeline)) {
$pipeline = new Pipeline(...$pipeline);
}

$pipeline = $this->builderEncoder->encodeIfSupported($pipeline);

$options = $this->inheritReadOptions($options);
$options = $this->inheritCodecOrTypeMap($options);

Expand Down
13 changes: 13 additions & 0 deletions src/Database.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
use MongoDB\BSON\Document;
use MongoDB\BSON\PackedArray;
use MongoDB\Builder\BuilderEncoder;
use MongoDB\Builder\Pipeline;
use MongoDB\Codec\Encoder;
use MongoDB\Driver\ClientEncryption;
use MongoDB\Driver\Cursor;
Expand Down Expand Up @@ -202,6 +203,12 @@
*/
public function aggregate(array $pipeline, array $options = [])
{
if (is_builder_pipeline($pipeline)) {
$pipeline = new Pipeline(...$pipeline);
}

$pipeline = $this->builderEncoder->encodeIfSupported($pipeline);

$hasWriteStage = is_last_pipeline_operator_write($pipeline);

if (! isset($options['readPreference']) && ! is_in_transaction($options)) {
Expand Down Expand Up @@ -611,6 +618,12 @@
*/
public function watch(array $pipeline = [], array $options = [])
{
if (is_builder_pipeline($pipeline)) {
$pipeline = new Pipeline(...$pipeline);
}

$pipeline = $this->builderEncoder->encodeIfSupported($pipeline);

if (! isset($options['readPreference']) && ! is_in_transaction($options)) {
$options['readPreference'] = $this->readPreference;
}
Expand Down
22 changes: 22 additions & 0 deletions src/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
use MongoDB\BSON\Document;
use MongoDB\BSON\PackedArray;
use MongoDB\BSON\Serializable;
use MongoDB\Builder\Type\StageInterface;
use MongoDB\Driver\Exception\RuntimeException as DriverRuntimeException;
use MongoDB\Driver\Manager;
use MongoDB\Driver\ReadPreference;
Expand Down Expand Up @@ -327,6 +328,27 @@
return true;
}

/**
* Returns whether the argument is a list that contains at least one
* {@see StageInterface} object.
*
* @internal
*/
function is_builder_pipeline(array $pipeline): bool
{
if (! $pipeline || ! array_is_list($pipeline)) {
return false;
}

foreach ($pipeline as $stage) {
if (is_object($stage) && $stage instanceof StageInterface) {
return true;
}
}

return false;
}

/**
* Returns whether we are currently in a transaction.
*
Expand Down
25 changes: 25 additions & 0 deletions tests/ClientFunctionalTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

namespace MongoDB\Tests;

use MongoDB\Builder\Pipeline;
use MongoDB\Builder\Query;
use MongoDB\Builder\Stage;
use MongoDB\Client;
use MongoDB\Driver\BulkWrite;
use MongoDB\Driver\Command;
Expand All @@ -13,6 +16,7 @@

use function call_user_func;
use function is_callable;
use function iterator_to_array;
use function sprintf;

/**
Expand Down Expand Up @@ -137,4 +141,25 @@ public function testAddAndRemoveSubscriber(): void

$client->getManager()->executeCommand('admin', new Command(['ping' => 1]));
}

public function testWatchWithBuilderPipeline(): void
{
$this->skipIfChangeStreamIsNotSupported();

if ($this->isShardedCluster()) {
$this->markTestSkipped('Test does not apply on sharded clusters: need more than a single getMore call on the change stream.');
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I assume this was copied from testChangeStreamExample_1_4 in DocumentationExamplesTest. I think this skip was only done for documentation examples to avoid complicating the code snippets.

32bade4 also introduced advanceCursorUntilValid() to fix change stream iteration for sharded clusters in our other tests.

I won't push for changing this, but wanted to provide some context.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the context. In fact, I've simplified the documentation example you pointed. Given what's being tested, I don't think it's essential for the test to run on all server typologies.


$pipeline = new Pipeline(
Stage::match(operationType: Query::eq('insert')),
);
// Extract the list of stages for arg type restriction
$pipeline = iterator_to_array($pipeline);

$changeStream = $this->client->watch($pipeline);
$this->client->selectCollection($this->getDatabaseName(), $this->getCollectionName())->insertOne(['x' => 3]);
$changeStream->next();
$this->assertTrue($changeStream->valid());
$this->assertEquals('insert', $changeStream->current()->operationType);
}
}
34 changes: 32 additions & 2 deletions tests/Collection/BuilderCollectionFunctionalTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@

namespace MongoDB\Tests\Collection;

use MongoDB\Builder\Expression;
use MongoDB\Builder\Pipeline;
use MongoDB\Builder\Query;
use MongoDB\Builder\Stage;

use function iterator_to_array;

class BuilderCollectionFunctionalTest extends FunctionalTestCase
{
public function setUp(): void
Expand All @@ -17,7 +20,18 @@ public function setUp(): void

public function testAggregate(): void
{
$this->markTestSkipped('Not supported yet');
$this->collection->insertMany([['x' => 10], ['x' => 10], ['x' => 10]]);
$pipeline = new Pipeline(
Stage::bucketAuto(
groupBy: Expression::intFieldPath('x'),
buckets: 2,
),
);
// Extract the list of stages for arg type restriction
$pipeline = iterator_to_array($pipeline);

$results = $this->collection->aggregate($pipeline)->toArray();
$this->assertCount(2, $results);
}

public function testBulkWriteDeleteMany(): void
Expand Down Expand Up @@ -245,6 +259,22 @@ public function testUpdateManyWithPipeline(): void

public function testWatch(): void
{
$this->markTestSkipped('Not supported yet');
$this->skipIfChangeStreamIsNotSupported();

if ($this->isShardedCluster()) {
$this->markTestSkipped('Test does not apply on sharded clusters: need more than a single getMore call on the change stream.');
}

$pipeline = new Pipeline(
Stage::match(operationType: Query::eq('insert')),
);
// Extract the list of stages for arg type restriction
$pipeline = iterator_to_array($pipeline);

$changeStream = $this->collection->watch($pipeline);
$this->collection->insertOne(['x' => 3]);
$changeStream->next();
$this->assertTrue($changeStream->valid());
$this->assertEquals('insert', $changeStream->current()->operationType);
}
}
63 changes: 63 additions & 0 deletions tests/Database/BuilderDatabaseFunctionalTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<?php

namespace MongoDB\Tests\Database;

use MongoDB\Builder\Expression;
use MongoDB\Builder\Pipeline;
use MongoDB\Builder\Query;
use MongoDB\Builder\Stage;

use function iterator_to_array;

class BuilderDatabaseFunctionalTest extends FunctionalTestCase
{
public function tearDown(): void
{
$this->dropCollection($this->getDatabaseName(), $this->getCollectionName());

parent::tearDown();
}

public function testAggregate(): void
{
$this->skipIfServerVersion('<', '6.0.0', '$documents stage is not supported');

$pipeline = new Pipeline(
Stage::documents([
['x' => 1],
['x' => 2],
['x' => 3],
]),
Stage::bucketAuto(
groupBy: Expression::intFieldPath('x'),
buckets: 2,
),
);
// Extract the list of stages for arg type restriction
$pipeline = iterator_to_array($pipeline);

$results = $this->database->aggregate($pipeline)->toArray();
$this->assertCount(2, $results);
}

public function testWatch(): void
{
$this->skipIfChangeStreamIsNotSupported();

if ($this->isShardedCluster()) {
$this->markTestSkipped('Test does not apply on sharded clusters: need more than a single getMore call on the change stream.');
}

$pipeline = new Pipeline(
Stage::match(operationType: Query::eq('insert')),
);
// Extract the list of stages for arg type restriction
$pipeline = iterator_to_array($pipeline);

$changeStream = $this->database->watch($pipeline);
$this->database->selectCollection($this->getCollectionName())->insertOne(['x' => 3]);
$changeStream->next();
$this->assertTrue($changeStream->valid());
$this->assertEquals('insert', $changeStream->current()->operationType);
}
}
Loading