diff options
| author | Hana Pearlman <hana.pearlman@mongodb.com> | 2022-09-20 15:34:54 +0000 |
|---|---|---|
| committer | Evergreen Agent <no-reply@evergreen.mongodb.com> | 2022-09-20 16:20:17 +0000 |
| commit | 9f8cd4b9e0099770650b8bbd7e18203cd73033a1 (patch) | |
| tree | 1897a4a42abc40e33bb95ee497509c84c466a6f3 | |
| parent | da82313422df769b13af93f5469b85f8cb5d39b2 (diff) | |
| download | mongo-9f8cd4b9e0099770650b8bbd7e18203cd73033a1.tar.gz | |
SERVER-66846 Translate simple inclusion and exclusion $project by walking over ProjectionAST
Co-authored-by: Emily Wang emily.wang@mongodb.com
| -rw-r--r-- | jstests/cqf/projection.js | 191 | ||||
| -rw-r--r-- | jstests/noPassthrough/cqf_fallback.js | 13 | ||||
| -rw-r--r-- | src/mongo/db/pipeline/SConscript | 1 | ||||
| -rw-r--r-- | src/mongo/db/pipeline/abt/canonical_query_translation.cpp | 14 | ||||
| -rw-r--r-- | src/mongo/db/pipeline/abt/document_source_visitor.cpp | 26 | ||||
| -rw-r--r-- | src/mongo/db/pipeline/abt/field_map_builder.h | 2 | ||||
| -rw-r--r-- | src/mongo/db/pipeline/abt/projection_ast_visitor.cpp | 147 | ||||
| -rw-r--r-- | src/mongo/db/pipeline/abt/projection_ast_visitor.h | 42 | ||||
| -rw-r--r-- | src/mongo/db/pipeline/abt/transformer_visitor.h | 2 | ||||
| -rw-r--r-- | src/mongo/db/pipeline/document_source_project.cpp | 64 | ||||
| -rw-r--r-- | src/mongo/db/pipeline/document_source_single_document_transformation.cpp | 12 | ||||
| -rw-r--r-- | src/mongo/db/pipeline/document_source_single_document_transformation.h | 19 | ||||
| -rw-r--r-- | src/mongo/db/query/cqf_command_utils.cpp | 105 |
13 files changed, 550 insertions, 88 deletions
diff --git a/jstests/cqf/projection.js b/jstests/cqf/projection.js new file mode 100644 index 00000000000..9bd12a47786 --- /dev/null +++ b/jstests/cqf/projection.js @@ -0,0 +1,191 @@ +/** + * Testing simple inclusion/exclusion projections with dotted path fields while forcing CQF. + * Many of these tests are similar/repeats of core/projection_semantics.js + */ + +(function() { +"use strict"; +load('jstests/aggregation/extras/utils.js'); // For assertArrayEq. +load('jstests/libs/optimizer_utils.js'); + +const coll = db.cqf_project; + +// Tests that when 'projection' is applied to 'input', we get 'expectedOutput'. +// Tests that this remains true if indexes are added. +function testInputOutput({input, projection, expectedOutput, interestingIndexes = []}) { + coll.drop(); + assert.commandWorked(coll.insert(input)); + const result = coll.aggregate([{$project: projection}]).toArray(); + assertArrayEq( + {actual: result, expected: expectedOutput, extraErrorMsg: tojson({project: projection})}); + + for (let indexSpec of interestingIndexes) { + assert.commandWorked(coll.createIndex(indexSpec)); + const result = coll.aggregate([{$project: projection}]).toArray(); + assertArrayEq({ + actual: result, + expected: expectedOutput, + extraErrorMsg: tojson({project: projection}) + }); + assert.commandWorked(coll.dropIndex(indexSpec)); + } + + const explain = assert.commandWorked(db.runCommand( + {explain: {aggregate: coll.getName(), pipeline: [{$project: projection}], cursor: {}}})); + assert(usedBonsaiOptimizer(explain), tojson(explain)); +} + +(function testInclusionOneLevelOfNesting() { + // Test the case where two paths in a projection go through the same parent object. + const testIncludeOnlyADotBAndADotC = (input, output) => testInputOutput({ + input: input, + projection: {'a.b': 1, 'a.c': 1, _id: 0}, + expectedOutput: output, + interestingIndexes: [{'a.b': 1, 'a.c': 1}, {'a.b': -1}] + }); + testIncludeOnlyADotBAndADotC({_id: 0, a: {b: "scalar", c: "scalar", d: "extra"}}, + [{a: {b: "scalar", c: "scalar"}}]); + testIncludeOnlyADotBAndADotC({_id: 1, a: [{b: 1, c: 2, d: 3}, {b: 4, c: 5, d: 6}]}, + [{a: [{b: 1, c: 2}, {b: 4, c: 5}]}]); + + // Array cases where one or both of the paths don't exist. + testIncludeOnlyADotBAndADotC({_id: 5, a: [{b: 1, c: 2}, {b: 3, d: 4}]}, + [{a: [{b: 1, c: 2}, {b: 3}]}]); + testIncludeOnlyADotBAndADotC({_id: 6, a: [{c: 1, d: 2}, {b: 3, d: 4}]}, + [{a: [{c: 1}, {b: 3}]}]); + testIncludeOnlyADotBAndADotC({_id: 7, a: []}, [{a: []}]); + testIncludeOnlyADotBAndADotC({_id: 8, a: [{b: 1, c: 2}, "extra", {b: 3, c: 4}]}, + [{a: [{b: 1, c: 2}, {b: 3, c: 4}]}]); +}()); + +(function testInclusionNestedId() { + // Test the case where two paths in a projection go through the same parent object. + const testIncludeOnlyADotBAndId = (input, output) => testInputOutput({ + input: input, + projection: {'a.b': 1, _id: 1}, + expectedOutput: output, + interestingIndexes: [] + }); + testIncludeOnlyADotBAndId({_id: {a: 0}, a: {b: "scalar", c: "scalar", d: "extra"}}, + [{_id: {a: 0}, a: {b: "scalar"}}]); + testIncludeOnlyADotBAndId({_id: {a: 1}, a: [{b: 1, c: 2, d: 3}, {b: 4, c: 5, d: 6}]}, + [{_id: {a: 1}, a: [{b: 1}, {b: 4}]}]); + + // Array cases where one or both of the paths don't exist. + testIncludeOnlyADotBAndId({_id: {a: 5}, a: [{b: 1, c: 2}, {b: 3, d: 4}]}, + [{_id: {a: 5}, a: [{b: 1}, {b: 3}]}]); + testIncludeOnlyADotBAndId({_id: {a: 6}, a: [{c: 1, d: 2}, {b: 3, d: 4}]}, + [{_id: {a: 6}, a: [{}, {b: 3}]}]); + testIncludeOnlyADotBAndId({_id: {a: 7}, a: []}, [{_id: {a: 7}, a: []}]); + testIncludeOnlyADotBAndId({_id: {a: 8}, a: [{b: 1}, "extra", {b: 3}]}, + [{_id: {a: 8}, a: [{b: 1}, {b: 3}]}]); +}()); + +(function testInclusionLevelsOfNesting() { + const testIncludeADotBDotC = (input, output) => testInputOutput({ + input: input, + projection: {'a.b.c': 1, _id: 0}, + expectedOutput: output, + interestingIndexes: [{'a.b.c': 1}, {'a.b': 1}] + }); + // The cases from above with just 'a.b' are mostly the same for 'a.b.c': + testIncludeADotBDotC({a: [], x: "extra"}, [{a: []}]); + testIncludeADotBDotC({a: [{}, {}], x: "extra"}, [{a: [{}, {}]}]); + testIncludeADotBDotC({a: ["scalar", "scalar"], x: "extra"}, [{a: []}]); + testIncludeADotBDotC({a: [null]}, [{a: []}]); + testIncludeADotBDotC({a: ["scalar", {}, "scalar", {c: 1}], x: "extra"}, [{a: [{}, {}]}]); + testIncludeADotBDotC({a: [[]]}, [{a: [[]]}]); + testIncludeADotBDotC({a: [[1, 2, 3]]}, [{a: [[]]}]); + // Now some with 'a.b' existing but no 'a.b.c'. + testIncludeADotBDotC({a: {b: []}}, [{a: {b: []}}]); + testIncludeADotBDotC({a: {b: ["scalar"]}}, [{a: {b: []}}]); + testIncludeADotBDotC({a: {b: [[]]}}, [{a: {b: [[]]}}]); + testIncludeADotBDotC({a: [{b: "scalar"}]}, [{a: [{}]}]); + testIncludeADotBDotC({a: [{b: []}]}, [{a: [{b: []}]}]); + testIncludeADotBDotC({a: [{b: ["scalar"]}]}, [{a: [{b: []}]}]); + testIncludeADotBDotC({a: [{b: [[]]}]}, [{a: [{b: [[]]}]}]); + testIncludeADotBDotC({a: [{b: {x: 1}}]}, [{a: [{b: {}}]}]); + testIncludeADotBDotC({a: [{b: [{}]}]}, [{a: [{b: [{}]}]}]); + testIncludeADotBDotC({a: [[1, {b: 1}, {b: 2, c: 2}, "scalar"]]}, [{a: [[{}, {}]]}]); + testIncludeADotBDotC({a: [1, {b: [[1, 2], [{}], 2]}, 2]}, [{a: [{b: [[], [{}]]}]}]); + testIncludeADotBDotC({a: [[1, 2], [{b: [[1, 2], [{c: [[1, 2], [{}], 2]}], 2]}], 2]}, + [{a: [[], [{b: [[], [{c: [[1, 2], [{}], 2]}]]}]]}]); + testIncludeADotBDotC({a: [{b: [{c: ["scalar"]}]}]}, [{a: [{b: [{c: ["scalar"]}]}]}]); + testIncludeADotBDotC({a: [{b: [1, {c: ["scalar"]}, 2]}]}, [{a: [{b: [{c: ["scalar"]}]}]}]); + testIncludeADotBDotC({a: [{b: [[1, 2], [{c: ["scalar"]}], 2]}]}, + [{a: [{b: [[], [{c: ["scalar"]}]]}]}]); + testIncludeADotBDotC({a: [1, {b: [[1, 2], [{c: [1, {}, 2]}], 2]}, 2]}, + [{a: [{b: [[], [{c: [1, {}, 2]}]]}]}]); + testIncludeADotBDotC({a: [[1, 2], [{b: [[1, 2], [{c: [[1, 2], [{}], 2]}], 2]}], 2]}, + [{a: [[], [{b: [[], [{c: [[1, 2], [{}], 2]}]]}]]}]); +}()); + +(function testExclusionSemantics() { + const testInputOutputExclusion = ({input, projection, expectedOutput}) => testInputOutput({ + input: input, + projection: projection, + expectedOutput: expectedOutput, + }); + + testInputOutputExclusion({ + input: {_id: 9, a: {b: 1, c: 1, d: 1}, x: {y: 1, z: 1}}, + projection: {"a.b": 0}, + expectedOutput: [{_id: 9, a: {c: 1, d: 1}, x: {y: 1, z: 1}}] + }); + testInputOutputExclusion({ + input: {_id: 10, a: ["scalar", {b: 1, c: 1, d: 1}, {b: 2, c: 2}, {b: 3}]}, + projection: {"a.b": 0}, + expectedOutput: [{_id: 10, a: ["scalar", {c: 1, d: 1}, {c: 2}, {}]}] + }); + testInputOutputExclusion({ + input: {_id: 11, a: [{b: 1, c: 1, d: 1}, {b: 2, c: 2}, {b: 3}]}, + projection: {"a.b": 0, "a.c": 0}, + expectedOutput: [{_id: 11, a: [{d: 1}, {}, {}]}] + }); + testInputOutputExclusion({ + input: {_id: 11, a: [[], [{b: [[1, 2], {c: 1, d: 1}]}]]}, + projection: {"a.b.c": 0}, + expectedOutput: [{_id: 11, a: [[], [{b: [[1, 2], {d: 1}]}]]}] + }); +}()); + +// Simple exclusion and inclusions over multiple documents. +(function testSimple() { + const docs = [ + {_id: 0, a: 1, b: {c: 1, d: 1}}, + {_id: 1, a: 2, b: {c: 2, d: 2}}, + {_id: 2, a: [], b: {c: 3, d: 3}}, + ]; + testInputOutput({ + input: docs, + projection: {a: 1}, + expectedOutput: [{_id: 0, a: 1}, {_id: 1, a: 2}, {_id: 2, a: []}], + interestingIndexes: [], + }); + testInputOutput({ + input: docs, + projection: {a: 1, _id: 0}, + expectedOutput: [{a: 1}, {a: 2}, {a: []}], + interestingIndexes: [], + }); + testInputOutput({ + input: docs, + projection: {"b.c": 1, _id: 0}, + expectedOutput: [{b: {c: 1}}, {b: {c: 2}}, {b: {c: 3}}], + interestingIndexes: [], + }); + testInputOutput({ + input: docs, + projection: {a: 0, _id: 0}, + expectedOutput: [{b: {c: 1, d: 1}}, {b: {c: 2, d: 2}}, {b: {c: 3, d: 3}}], + interestingIndexes: [], + }); + testInputOutput({ + input: docs, + projection: {a: 0, _id: 1}, + expectedOutput: + [{_id: 0, b: {c: 1, d: 1}}, {_id: 1, b: {c: 2, d: 2}}, {_id: 2, b: {c: 3, d: 3}}], + interestingIndexes: [], + }); +}()); +}()); diff --git a/jstests/noPassthrough/cqf_fallback.js b/jstests/noPassthrough/cqf_fallback.js index 95b81e16e62..ac26d7efcab 100644 --- a/jstests/noPassthrough/cqf_fallback.js +++ b/jstests/noPassthrough/cqf_fallback.js @@ -105,8 +105,19 @@ assertNotSupportedByBonsai({ cursor: {} }, false); +assertNotSupportedByBonsai( + {aggregate: coll.getName(), pipeline: [{$project: {'a.b': '$c'}}], cursor: {}}, true); +assertNotSupportedByBonsai({find: coll.getName(), filter: {}, projection: {'a.b': '$c'}}, true); + +assertNotSupportedByBonsai( + {aggregate: coll.getName(), pipeline: [{$addFields: {a: '$z'}}], cursor: {}}, true); + +assertNotSupportedByBonsai( + {aggregate: coll.getName(), pipeline: [{$project: {a: {$slice: ["$a", 0, 1]}}}], cursor: {}}, + false); +assertNotSupportedByBonsai( + {find: coll.getName(), filter: {}, projection: {a: {$slice: ["$a", 0, 1]}}}, false); -// Test-only projection spec. assertNotSupportedByBonsai( {find: coll.getName(), filter: {}, projection: {a: {$concat: ["test", "-only"]}}}, true); assertNotSupportedByBonsai({ diff --git a/src/mongo/db/pipeline/SConscript b/src/mongo/db/pipeline/SConscript index 422eb578043..bca0ed04164 100644 --- a/src/mongo/db/pipeline/SConscript +++ b/src/mongo/db/pipeline/SConscript @@ -231,6 +231,7 @@ pipelineEnv.Library( 'abt/expr_algebrizer_context.cpp', 'abt/field_map_builder.cpp', 'abt/match_expression_visitor.cpp', + 'abt/projection_ast_visitor.cpp', 'abt/transformer_visitor.cpp', 'abt/utils.cpp', 'document_source.cpp', diff --git a/src/mongo/db/pipeline/abt/canonical_query_translation.cpp b/src/mongo/db/pipeline/abt/canonical_query_translation.cpp index 87c13355f37..3bdfdb59c6b 100644 --- a/src/mongo/db/pipeline/abt/canonical_query_translation.cpp +++ b/src/mongo/db/pipeline/abt/canonical_query_translation.cpp @@ -32,6 +32,7 @@ #include "mongo/db/pipeline/abt/algebrizer_context.h" #include "mongo/db/pipeline/abt/collation_translation.h" #include "mongo/db/pipeline/abt/match_expression_visitor.h" +#include "mongo/db/pipeline/abt/projection_ast_visitor.h" #include "mongo/db/pipeline/abt/transformer_visitor.h" namespace mongo::optimizer { @@ -56,7 +57,18 @@ ABT translateCanonicalQueryToABT(const Metadata& metadata, } if (auto proj = canonicalQuery.getProj()) { - translateProjection(ctx, scanProjName, canonicalQuery.getExpCtx(), proj); + // TODO: SERVER-68516: this is a workaround to support computed projection + // in the short term. Remove this workaround and complete projection translation via + // projeciton_ast_visitor instead. + try { + translateProjection(ctx, proj); + } catch (const DBException& ex) { + if (ex.code() == ErrorCodes::InternalErrorNotSupported) { + translateProjection(ctx, scanProjName, canonicalQuery.getExpCtx(), proj); + } else { + throw; + } + } } auto skipAmount = canonicalQuery.getFindCommandRequest().getSkip(); diff --git a/src/mongo/db/pipeline/abt/document_source_visitor.cpp b/src/mongo/db/pipeline/abt/document_source_visitor.cpp index 85b4fe314a4..cd3002a37f3 100644 --- a/src/mongo/db/pipeline/abt/document_source_visitor.cpp +++ b/src/mongo/db/pipeline/abt/document_source_visitor.cpp @@ -33,6 +33,7 @@ #include "mongo/db/pipeline/abt/algebrizer_context.h" #include "mongo/db/pipeline/abt/collation_translation.h" #include "mongo/db/pipeline/abt/match_expression_visitor.h" +#include "mongo/db/pipeline/abt/projection_ast_visitor.h" #include "mongo/db/pipeline/abt/transformer_visitor.h" #include "mongo/db/pipeline/abt/utils.h" #include "mongo/db/pipeline/document_source_bucket_auto.h" @@ -469,6 +470,31 @@ public: } void visit(const DocumentSourceSingleDocumentTransformation* source) override { + switch (source->getType()) { + case TransformerInterface::TransformerType::kComputedProjection: + case TransformerInterface::TransformerType::kGroupFromFirstDocument: + case TransformerInterface::TransformerType::kReplaceRoot: + break; + case TransformerInterface::TransformerType::kExclusionProjection: + case TransformerInterface::TransformerType::kInclusionProjection: { + tassert(6684600, + "Translating Inclusion or Exclusion projection but there's no AST in " + "DocumentSource", + source->hasProjectionAST()); + try { + translateProjection(_ctx, source->getProjectionAST()); + return; + } catch (const DBException& ex) { + if (ex.code() != ErrorCodes::InternalErrorNotSupported) { + throw; + } + } + } + } + + // TODO: SERVER-68516: this is a workaround to support computed projection + // in the short term. Remove this workaround and complete projection translation via + // projection_ast_visitor instead. const ProjectionName& rootProjName = _ctx.getNode()._rootProjection; FieldMapBuilder builder(rootProjName, rootProjName == _ctx.getScanProjName()); ABTTransformerVisitor visitor(_ctx, builder); diff --git a/src/mongo/db/pipeline/abt/field_map_builder.h b/src/mongo/db/pipeline/abt/field_map_builder.h index 3246bc07ab8..c8af6181286 100644 --- a/src/mongo/db/pipeline/abt/field_map_builder.h +++ b/src/mongo/db/pipeline/abt/field_map_builder.h @@ -57,7 +57,7 @@ struct FieldMapEntry { bool _hasDrop = false; std::string _constVarName; - // TODO SERVER-66846: Consider maintaining children as a vector of FieldMapEntry's. Then we can + // TODO SERVER-68516: Consider maintaining children as a vector of FieldMapEntry's. Then we can // remove the _fieldMap member of FieldMapBuilder. // Child paths are potentially dotted field paths. OrderedPathSet _childPaths; diff --git a/src/mongo/db/pipeline/abt/projection_ast_visitor.cpp b/src/mongo/db/pipeline/abt/projection_ast_visitor.cpp new file mode 100644 index 00000000000..1fff9f40ee6 --- /dev/null +++ b/src/mongo/db/pipeline/abt/projection_ast_visitor.cpp @@ -0,0 +1,147 @@ +/** + * Copyright (C) 2022-present MongoDB, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the Server Side Public License, version 1, + * as published by MongoDB, Inc. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * Server Side Public License for more details. + * + * You should have received a copy of the Server Side Public License + * along with this program. If not, see + * <http://www.mongodb.com/licensing/server-side-public-license>. + * + * As a special exception, the copyright holders give permission to link the + * code of portions of this program with the OpenSSL library under certain + * conditions as described in each individual source file and distribute + * linked combinations including the program with the OpenSSL library. You + * must comply with the Server Side Public License in all respects for + * all of the code used other than as permitted herein. If you modify file(s) + * with this exception, you may extend this exception to your version of the + * file(s), but you are not obligated to do so. If you do not wish to do so, + * delete this exception statement from your version. If you delete this + * exception statement from all source files in the program, then also delete + * it in the license file. + */ + +#include "mongo/db/pipeline/abt/projection_ast_visitor.h" + +#include "mongo/db/pipeline/abt/agg_expression_visitor.h" +#include "mongo/db/pipeline/abt/utils.h" +#include "mongo/db/query/projection_ast_path_tracking_visitor.h" + +namespace mongo::optimizer { + +class ProjectionPreVisitor final : public projection_ast::ProjectionASTConstVisitor { +public: + ProjectionPreVisitor(projection_ast::PathTrackingVisitorContext<>* context, + bool isInclusion, + const ProjectionName& rootProjName, + const ProjectionName& scanProjName) + : _context{context}, + _builder(rootProjName, rootProjName == scanProjName), + _isInclusion(isInclusion) { + invariant(_context); + } + + void visit(const projection_ast::ProjectionPositionalASTNode* node) final { + unsupportedProjectionType("ProjectionPositionalASTNode"); + } + + void visit(const projection_ast::ProjectionSliceASTNode* node) final { + unsupportedProjectionType("ProjectionSliceASTNode"); + } + + void visit(const projection_ast::ProjectionElemMatchASTNode* node) final { + unsupportedProjectionType("ProjectionElemMatchASTNode"); + } + + void visit(const projection_ast::ExpressionASTNode* node) final { + unsupportedProjectionType("ExpressionASTNode"); + } + + void visit(const projection_ast::BooleanConstantASTNode* node) final { + const auto& path = _context->fullPath(); + if (_isInclusion) { + const auto isIdField = path == "_id"; + // If current field is _id and _id : 0, then don't include it. + if (isIdField && !node->value()) { + return; + } + // In inclusion projection only _id field can be excluded, make sure this is the case. + tassert( + 6684601, "In inclusion projection only _id field can be excluded", node->value()); + builderIntegrateInclusion(path.fullPath()); + } else { + builderIntegrateExclusion(path.fullPath()); + } + } + + void visit(const projection_ast::ProjectionPathASTNode* node) final {} + void visit(const projection_ast::MatchExpressionASTNode* node) final { + unsupportedProjectionType("MatchExpressionASTNode"); + } + + auto generateABT() { + return _builder.generateABT(); + } + +private: + projection_ast::PathTrackingVisitorContext<>* _context; + FieldMapBuilder _builder; + bool _isInclusion; + + void assertSupportedPath(const std::string& path) { + uassert(ErrorCodes::InternalErrorNotSupported, + "Projection contains unsupported numeric path component", + !FieldRef(path).hasNumericPathComponents()); + } + + void builderIntegrateInclusion(const std::string& fullPath) { + assertSupportedPath(fullPath); + _builder.integrateFieldPath(FieldPath(fullPath), + [](const bool isLastElement, FieldMapEntry& entry) { + entry._hasLeadingObj = true; + entry._hasKeep = true; + }); + } + + void builderIntegrateExclusion(const std::string& fullPath) { + assertSupportedPath(fullPath); + _builder.integrateFieldPath(FieldPath(fullPath), + [](const bool isLastElement, FieldMapEntry& entry) { + if (isLastElement) { + entry._hasDrop = true; + } + }); + } + + void unsupportedProjectionType(const std::string& unsupportedNode) const { + uasserted(ErrorCodes::InternalErrorNotSupported, + str::stream() << "Projection node is not supported (type: " << unsupportedNode + << ")"); + } +}; + +void translateProjection(AlgebrizerContext& ctx, const projection_ast::Projection* proj) { + projection_ast::PathTrackingVisitorContext context{}; + const bool isInclusion = proj->type() == projection_ast::ProjectType::kInclusion; + const ProjectionName& rootProjName = ctx.getNode()._rootProjection; + + ProjectionPreVisitor astVisitor{&context, isInclusion, rootProjName, ctx.getScanProjName()}; + projection_ast::PathTrackingWalker walker{&context, {&astVisitor}, {}}; + tree_walker::walk<true, projection_ast::ASTNode>(proj->root(), &walker); + + auto result = astVisitor.generateABT(); + if (!result) { + return; + } + auto entry = ctx.getNode(); + const ProjectionName projName = ctx.getNextId("combinedProjection"); + ctx.setNode<EvaluationNode>(projName, projName, std::move(*result), std::move(entry._node)); +} + +} // namespace mongo::optimizer diff --git a/src/mongo/db/pipeline/abt/projection_ast_visitor.h b/src/mongo/db/pipeline/abt/projection_ast_visitor.h new file mode 100644 index 00000000000..8a076fc80bf --- /dev/null +++ b/src/mongo/db/pipeline/abt/projection_ast_visitor.h @@ -0,0 +1,42 @@ +/** + * Copyright (C) 2022-present MongoDB, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the Server Side Public License, version 1, + * as published by MongoDB, Inc. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * Server Side Public License for more details. + * + * You should have received a copy of the Server Side Public License + * along with this program. If not, see + * <http://www.mongodb.com/licensing/server-side-public-license>. + * + * As a special exception, the copyright holders give permission to link the + * code of portions of this program with the OpenSSL library under certain + * conditions as described in each individual source file and distribute + * linked combinations including the program with the OpenSSL library. You + * must comply with the Server Side Public License in all respects for + * all of the code used other than as permitted herein. If you modify file(s) + * with this exception, you may extend this exception to your version of the + * file(s), but you are not obligated to do so. If you do not wish to do so, + * delete this exception statement from your version. If you delete this + * exception statement from all source files in the program, then also delete + * it in the license file. + */ + +#pragma once + +#include "mongo/db/pipeline/abt/algebrizer_context.h" +#include "mongo/db/pipeline/abt/field_map_builder.h" +#include "mongo/db/query/projection.h" + +namespace mongo::optimizer { +/** + * Populate's ctx's root node with an EvaluationNode encoding the projection. + */ +void translateProjection(AlgebrizerContext& ctx, const projection_ast::Projection* proj); + +} // namespace mongo::optimizer diff --git a/src/mongo/db/pipeline/abt/transformer_visitor.h b/src/mongo/db/pipeline/abt/transformer_visitor.h index c29de4f6169..8313454d540 100644 --- a/src/mongo/db/pipeline/abt/transformer_visitor.h +++ b/src/mongo/db/pipeline/abt/transformer_visitor.h @@ -39,6 +39,8 @@ namespace mongo::optimizer { +// TODO: SERVER-68516 remove this file and implement computed projection translation in +// projection_ast_visitor.h. class ABTTransformerVisitor : public TransformerInterfaceConstVisitor { public: ABTTransformerVisitor(AlgebrizerContext& ctx, FieldMapBuilder& builder) diff --git a/src/mongo/db/pipeline/document_source_project.cpp b/src/mongo/db/pipeline/document_source_project.cpp index 72c19be3c05..acaa05091e3 100644 --- a/src/mongo/db/pipeline/document_source_project.cpp +++ b/src/mongo/db/pipeline/document_source_project.cpp @@ -68,39 +68,37 @@ intrusive_ptr<DocumentSource> DocumentSourceProject::create( const intrusive_ptr<ExpressionContext>& expCtx, StringData specifiedName) { const bool isIndependentOfAnyCollection = false; - intrusive_ptr<DocumentSource> project(new DocumentSourceSingleDocumentTransformation( - expCtx, - [&]() { - // The ProjectionExecutor will internally perform a check to see if the provided - // specification is valid, and throw an exception if it was not. The exception is caught - // here so we can add the name that was actually specified by the user, be it $project - // or an alias. - try { - // We won't optimize the executor on creation, and will do it as part of the - // pipeline optimization process when requested via the 'optimize()' method on - // 'DocumentSourceSingleDocumentTransformation', so we won't pass the - // 'kOptimzeExecutor' flag to the projection executor builder. - // - // Note that this is also important for $lookup inner pipelines to not being - // optimized too early, as it may lead to incorrect positioning of the caching - // stage due to missing dependencies on certain variables, as they could have been - // optimized away. - auto builderParams = projection_executor::BuilderParamsBitSet{ - projection_executor::kDefaultBuilderParams}; - builderParams.reset(projection_executor::kOptimizeExecutor); - return projection_executor::buildProjectionExecutor( - expCtx, - &projection, - ProjectionPolicies::aggregateProjectionPolicies(), - builderParams); - } catch (DBException& ex) { - ex.addContext("Invalid " + specifiedName.toString()); - throw; - } - }(), - kStageName, - isIndependentOfAnyCollection)); - return project; + + // The ProjectionExecutor will internally perform a check to see if the provided + // specification is valid, and throw an exception if it was not. The exception is caught + // here so we can add the name that was actually specified by the user, be it $project + // or an alias. + try { + // We won't optimize the executor on creation, and will do it as part of the + // pipeline optimization process when requested via the 'optimize()' method on + // 'DocumentSourceSingleDocumentTransformation', so we won't pass the + // 'kOptimzeExecutor' flag to the projection executor builder. + // + // Note that this is also important for $lookup inner pipelines to not being + // optimized too early, as it may lead to incorrect positioning of the caching + // stage due to missing dependencies on certain variables, as they could have been + // optimized away. + auto builderParams = + projection_executor::BuilderParamsBitSet{projection_executor::kDefaultBuilderParams}; + builderParams.reset(projection_executor::kOptimizeExecutor); + auto parsedTransform = projection_executor::buildProjectionExecutor( + expCtx, &projection, ProjectionPolicies::aggregateProjectionPolicies(), builderParams); + + return new DocumentSourceSingleDocumentTransformation( + expCtx, + std::move(parsedTransform), + kStageName, + isIndependentOfAnyCollection, + std::make_unique<projection_ast::Projection>(std::move(projection))); + } catch (DBException& ex) { + ex.addContext("Invalid " + specifiedName.toString()); + throw; + } } boost::intrusive_ptr<DocumentSource> DocumentSourceProject::createUnset( diff --git a/src/mongo/db/pipeline/document_source_single_document_transformation.cpp b/src/mongo/db/pipeline/document_source_single_document_transformation.cpp index a8079a78994..67be45c89ce 100644 --- a/src/mongo/db/pipeline/document_source_single_document_transformation.cpp +++ b/src/mongo/db/pipeline/document_source_single_document_transformation.cpp @@ -53,6 +53,18 @@ DocumentSourceSingleDocumentTransformation::DocumentSourceSingleDocumentTransfor _name(name.toString()), _isIndependentOfAnyCollection(isIndependentOfAnyCollection) {} +DocumentSourceSingleDocumentTransformation::DocumentSourceSingleDocumentTransformation( + const intrusive_ptr<ExpressionContext>& pExpCtx, + std::unique_ptr<TransformerInterface> parsedTransform, + const StringData name, + bool isIndependentOfAnyCollection, + std::unique_ptr<projection_ast::Projection> projectionAST) + : DocumentSource(name, pExpCtx), + _parsedTransform(std::move(parsedTransform)), + _name(name.toString()), + _isIndependentOfAnyCollection(isIndependentOfAnyCollection), + _projectionAST(std::move(projectionAST)) {} + const char* DocumentSourceSingleDocumentTransformation::getSourceName() const { return _name.c_str(); } diff --git a/src/mongo/db/pipeline/document_source_single_document_transformation.h b/src/mongo/db/pipeline/document_source_single_document_transformation.h index f52d07099a2..295d225e60d 100644 --- a/src/mongo/db/pipeline/document_source_single_document_transformation.h +++ b/src/mongo/db/pipeline/document_source_single_document_transformation.h @@ -58,6 +58,13 @@ public: StringData name, bool independentOfAnyCollection); + DocumentSourceSingleDocumentTransformation( + const boost::intrusive_ptr<ExpressionContext>& pExpCtx, + std::unique_ptr<TransformerInterface> parsedTransform, + StringData name, + bool independentOfAnyCollection, + std::unique_ptr<projection_ast::Projection> projectionAST); + // virtuals from DocumentSource const char* getSourceName() const final; @@ -97,6 +104,15 @@ public: return *_parsedTransform; } + const projection_ast::Projection* getProjectionAST() const { + tassert(6684603, "Expected a projection AST but found none", hasProjectionAST()); + return _projectionAST.get(); + } + + bool hasProjectionAST() const { + return _projectionAST != nullptr; + } + /** * Extract computed projection(s) depending on the 'oldName' argument if the transformation is * of type inclusion projection or computed projection. Extraction is not allowed if the name of @@ -151,6 +167,9 @@ private: // Cached stage options in case this DocumentSource is disposed before serialized (e.g. explain // with a sort which will auto-dispose of the pipeline). Document _cachedStageOptions; + + // Stores a projectionAST if the DocumentSource is a projection/addFields, otherwise is nullptr + std::unique_ptr<projection_ast::Projection> _projectionAST = nullptr; }; } // namespace mongo diff --git a/src/mongo/db/query/cqf_command_utils.cpp b/src/mongo/db/query/cqf_command_utils.cpp index e87bdb76048..b444b96d35c 100644 --- a/src/mongo/db/query/cqf_command_utils.cpp +++ b/src/mongo/db/query/cqf_command_utils.cpp @@ -30,10 +30,6 @@ #include "mongo/db/query/cqf_command_utils.h" #include "mongo/db/commands/test_commands_enabled.h" -#include "mongo/db/exec/add_fields_projection_executor.h" -#include "mongo/db/exec/exclusion_projection_executor.h" -#include "mongo/db/exec/inclusion_projection_executor.h" -#include "mongo/db/exec/projection_executor_builder.h" #include "mongo/db/exec/sbe/abt/abt_lower.h" #include "mongo/db/matcher/expression_always_boolean.h" #include "mongo/db/matcher/expression_array.h" @@ -110,6 +106,7 @@ #include "mongo/db/pipeline/visitors/document_source_visitor.h" #include "mongo/db/pipeline/visitors/document_source_walker.h" #include "mongo/db/pipeline/visitors/transformer_interface_walker.h" +#include "mongo/db/query/projection_ast_path_tracking_visitor.h" #include "mongo/db/query/query_feature_flags_gen.h" #include "mongo/db/query/query_knobs_gen.h" #include "mongo/db/query/query_planner_params.h" @@ -366,60 +363,52 @@ private: bool& _eligible; }; - -class ABTTransformerVisitor : public TransformerInterfaceConstVisitor { +class ABTProjectionVisitor final : public projection_ast::ProjectionASTConstVisitor { public: - ABTTransformerVisitor(bool& eligible) : _eligible(eligible) {} - - void visit(const projection_executor::ExclusionProjectionExecutor* transformer) override { - checkUnsupportedInclusionExclusion(transformer); + ABTProjectionVisitor(projection_ast::PathTrackingVisitorContext<>* context, bool& eligible) + : _context{context}, _eligible(eligible) { + invariant(_context); } - void visit(const projection_executor::InclusionProjectionExecutor* transformer) override { - checkUnsupportedInclusionExclusion(transformer); + void visit(const projection_ast::ProjectionPositionalASTNode* node) final { + unsupportedProjectionType(); } - void visit(const projection_executor::AddFieldsProjectionExecutor* transformer) override { - unsupportedTransformer(transformer); + void visit(const projection_ast::ProjectionSliceASTNode* node) final { + unsupportedProjectionType(); } - void visit(const GroupFromFirstDocumentTransformation* transformer) override { - unsupportedTransformer(transformer); + void visit(const projection_ast::ProjectionElemMatchASTNode* node) final { + unsupportedProjectionType(); } - void visit(const ReplaceRootTransformation* transformer) override { - unsupportedTransformer(transformer); + void visit(const projection_ast::ExpressionASTNode* node) final { + unsupportedProjectionType(); } -private: - void unsupportedTransformer(const TransformerInterface* transformer) { - _eligible = false; + void visit(const projection_ast::BooleanConstantASTNode* node) final { + const auto& path = _context->fullPath(); + assertSupportedPath(path.fullPath()); } - template <typename T> - void checkUnsupportedInclusionExclusion(const T* transformer) { - OrderedPathSet computedPaths; - StringMap<std::string> renamedPaths; - transformer->getRoot()->reportComputedPaths(&computedPaths, &renamedPaths); + void visit(const projection_ast::ProjectionPathASTNode* node) final {} - // Non-simple projections are supported under test only. - if (computedPaths.size() > 0 || renamedPaths.size() > 0) { - unsupportedTransformer(transformer); - return; - } + void visit(const projection_ast::MatchExpressionASTNode* node) final { + unsupportedProjectionType(); + } - OrderedPathSet preservedPaths; - transformer->getRoot()->reportProjectedPaths(&preservedPaths); +private: + projection_ast::PathTrackingVisitorContext<>* _context; + bool& _eligible; - for (const std::string& path : preservedPaths) { - if (FieldRef(path).hasNumericPathComponents()) { - unsupportedTransformer(transformer); - return; - } - } + void assertSupportedPath(const std::string& path) { + if (FieldRef(path).hasNumericPathComponents()) + _eligible = false; } - bool& _eligible; + void unsupportedProjectionType() { + _eligible = false; + } }; /** @@ -572,9 +561,26 @@ public: } void visit(const DocumentSourceSingleDocumentTransformation* source) override { - ABTTransformerVisitor visitor(eligible); - TransformerInterfaceWalker walker(&visitor); - walker.walk(&source->getTransformer()); + switch (source->getType()) { + case TransformerInterface::TransformerType::kComputedProjection: + case TransformerInterface::TransformerType::kGroupFromFirstDocument: + case TransformerInterface::TransformerType::kReplaceRoot: + eligible = false; + break; + case TransformerInterface::TransformerType::kExclusionProjection: + case TransformerInterface::TransformerType::kInclusionProjection: { + tassert(6684602, + "Translating Inclusion or Exclusion projection but there's no AST in " + "DocumentSource", + source->hasProjectionAST()); + + projection_ast::PathTrackingVisitorContext context; + ABTProjectionVisitor visitor(&context, eligible); + projection_ast::PathTrackingWalker walker{&context, {&visitor}, {}}; + tree_walker::walk<true, projection_ast::ASTNode>(source->getProjectionAST()->root(), + &walker); + } + } } void unsupportedStage(const DocumentSource* source) { @@ -741,15 +747,10 @@ bool isEligibleForBonsai(const CanonicalQuery& cq, tree_walker::walk<true, MatchExpression>(expression, &walker); if (cq.getProj()) { - // TODO SERVER-66846 Replace this with ProjectionAST walker - auto projExecutor = projection_executor::buildProjectionExecutor( - cq.getExpCtx(), - cq.getProj(), - ProjectionPolicies::findProjectionPolicies(), - projection_executor::BuilderParamsBitSet{projection_executor::kDefaultBuilderParams}); - ABTTransformerVisitor visitor(eligible); - TransformerInterfaceWalker walker(&visitor); - walker.walk(projExecutor.get()); + projection_ast::PathTrackingVisitorContext context; + ABTProjectionVisitor visitor(&context, eligible); + projection_ast::PathTrackingWalker walker{&context, {&visitor}, {}}; + tree_walker::walk<true, projection_ast::ASTNode>(cq.getProj()->root(), &walker); } return eligible; |
