Skip to content

PHPLIB-559: Make aggregate command explainable #760

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 1 commit into from
Jul 1, 2020
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
1 change: 1 addition & 0 deletions docs/reference/method/MongoDBCollection-explain.txt
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ Explainable Commands

Explainable commands include, but are not limited to:

- :phpclass:`MongoDB\\Operation\\Aggregate`
- :phpclass:`MongoDB\\Operation\\Count`
- :phpclass:`MongoDB\\Operation\\DeleteMany`
- :phpclass:`MongoDB\\Operation\\DeleteOne`
Expand Down
46 changes: 29 additions & 17 deletions src/Operation/Aggregate.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@
* @see \MongoDB\Collection::aggregate()
* @see http://docs.mongodb.org/manual/reference/command/aggregate/
*/
class Aggregate implements Executable
class Aggregate implements Executable, Explainable
{
/** @var integer */
private static $wireVersionForCollation = 5;
Expand Down Expand Up @@ -285,9 +285,12 @@ public function execute(Server $server)
}

$hasExplain = ! empty($this->options['explain']);
$hasWriteStage = is_last_pipeline_operator_write($this->pipeline);
$hasWriteStage = $this->hasWriteStage();

$command = $this->createCommand($server, $hasWriteStage);
$command = new Command(
$this->createCommandDocument($server, $hasWriteStage),
$this->createCommandOptions()
);
$options = $this->createOptions($hasWriteStage, $hasExplain);

$cursor = $hasWriteStage && ! $hasExplain
Expand Down Expand Up @@ -315,20 +318,17 @@ public function execute(Server $server)
return new ArrayIterator($result->result);
}

/**
* Create the aggregate command.
*
* @param Server $server
* @param boolean $hasWriteStage
* @return Command
*/
private function createCommand(Server $server, $hasWriteStage)
public function getCommandDocument(Server $server)
{
return $this->createCommandDocument($server, $this->hasWriteStage());
}

private function createCommandDocument(Server $server, bool $hasWriteStage) : array
{
$cmd = [
'aggregate' => $this->collectionName ?? 1,
'pipeline' => $this->pipeline,
];
$cmdOptions = [];

$cmd['allowDiskUse'] = $this->options['allowDiskUse'];

Expand All @@ -352,10 +352,6 @@ private function createCommand(Server $server, $hasWriteStage)
$cmd['hint'] = is_array($this->options['hint']) ? (object) $this->options['hint'] : $this->options['hint'];
}

if (isset($this->options['maxAwaitTimeMS'])) {
$cmdOptions['maxAwaitTimeMS'] = $this->options['maxAwaitTimeMS'];
}

if ($this->options['useCursor']) {
/* Ignore batchSize if pipeline includes an $out or $merge stage, as
* no documents will be returned and sending a batchSize of zero
Expand All @@ -365,7 +361,18 @@ private function createCommand(Server $server, $hasWriteStage)
: new stdClass();
}

return new Command($cmd, $cmdOptions);
return $cmd;
}

private function createCommandOptions() : array
{
$cmdOptions = [];

if (isset($this->options['maxAwaitTimeMS'])) {
$cmdOptions['maxAwaitTimeMS'] = $this->options['maxAwaitTimeMS'];
}

return $cmdOptions;
}

/**
Expand Down Expand Up @@ -399,4 +406,9 @@ private function createOptions($hasWriteStage, $hasExplain)

return $options;
}

private function hasWriteStage() : bool
{
return is_last_pipeline_operator_write($this->pipeline);
}
}
7 changes: 7 additions & 0 deletions src/Operation/Explain.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ class Explain implements Executable
const VERBOSITY_EXEC_STATS = 'executionStats';
const VERBOSITY_QUERY = 'queryPlanner';

/** @var integer */
private static $wireVersionForAggregate = 7;

/** @var integer */
private static $wireVersionForDistinct = 4;

Expand Down Expand Up @@ -108,6 +111,10 @@ public function execute(Server $server)
throw UnsupportedException::explainNotSupported();
}

if ($this->explainable instanceof Aggregate && ! server_supports_feature($server, self::$wireVersionForAggregate)) {
throw UnsupportedException::explainNotSupported();
}

$cmd = ['explain' => $this->explainable->getCommandDocument($server)];

if (isset($this->options['verbosity'])) {
Expand Down
4 changes: 2 additions & 2 deletions src/Operation/Explainable.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@
use MongoDB\Driver\Server;

/**
* Explainable interface for explainable operations (count, distinct, find,
* findAndModify, delete, and update).
* Explainable interface for explainable operations (aggregate, count, distinct,
* find, findAndModify, delete, and update).
*
* @internal
*/
Expand Down
47 changes: 45 additions & 2 deletions tests/Operation/ExplainFunctionalTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace MongoDB\Tests\Operation;

use MongoDB\Driver\BulkWrite;
use MongoDB\Operation\Aggregate;
use MongoDB\Operation\Count;
use MongoDB\Operation\CreateCollection;
use MongoDB\Operation\Delete;
Expand Down Expand Up @@ -387,6 +388,43 @@ public function testUpdateOne($verbosity, $executionStatsExpected, $allPlansExec
$this->assertExplainResult($result, $executionStatsExpected, $allPlansExecutionExpected);
}

public function testAggregate()
{
if (version_compare($this->getServerVersion(), '4.0.0', '<')) {
$this->markTestSkipped('Explaining aggregate command requires server version >= 4.0');
}

$this->createFixtures(3);

$pipeline = [['$group' => ['_id' => null]]];
$operation = new Aggregate($this->getDatabaseName(), $this->getCollectionName(), $pipeline);

$explainOperation = new Explain($this->getDatabaseName(), $operation, ['verbosity' => Explain::VERBOSITY_QUERY, 'typeMap' => ['root' => 'array', 'document' => 'array']]);
$result = $explainOperation->execute($this->getPrimaryServer());

$this->assertExplainResult($result, false, false, true);
}

/**
* @dataProvider provideVerbosityInformation
*/
public function testAggregateOptimizedToQuery($verbosity, $executionStatsExpected, $allPlansExecutionExpected)
{
if (version_compare($this->getServerVersion(), '4.2.0', '<')) {
$this->markTestSkipped('MongoDB < 4.2 does not optimize simple aggregation pipelines');
}

$this->createFixtures(3);

$pipeline = [['$match' => ['_id' => ['$ne' => 2]]]];
$operation = new Aggregate($this->getDatabaseName(), $this->getCollectionName(), $pipeline);

$explainOperation = new Explain($this->getDatabaseName(), $operation, ['verbosity' => $verbosity, 'typeMap' => ['root' => 'array', 'document' => 'array']]);
$result = $explainOperation->execute($this->getPrimaryServer());

$this->assertExplainResult($result, $executionStatsExpected, $allPlansExecutionExpected);
}

public function provideVerbosityInformation()
{
return [
Expand All @@ -396,9 +434,14 @@ public function provideVerbosityInformation()
];
}

private function assertExplainResult($result, $executionStatsExpected, $allPlansExecutionExpected)
private function assertExplainResult($result, $executionStatsExpected, $allPlansExecutionExpected, $stagesExpected = false)
{
$this->assertArrayHasKey('queryPlanner', $result);
if ($stagesExpected) {
$this->assertArrayHasKey('stages', $result);
} else {
$this->assertArrayHasKey('queryPlanner', $result);
}

if ($executionStatsExpected) {
$this->assertArrayHasKey('executionStats', $result);
if ($allPlansExecutionExpected) {
Expand Down