summaryrefslogtreecommitdiff
path: root/src/mongo/db/pipeline/document_source_out.h
blob: ca485b5279c5bbc1dffcf127260b9cbc2688895f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
/**
 * Copyright (C) 2016 MongoDB Inc.
 *
 * This program is free software: you can redistribute it and/or  modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * 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
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * 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 GNU Affero General 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/document_source.h"
#include "mongo/db/pipeline/document_source_out_gen.h"

namespace mongo {

/**
 * Abstract class for the $out aggregation stage.
 */
class DocumentSourceOut : public DocumentSource, public NeedsMergerDocumentSource {
public:
    /**
     * A "lite parsed" $out stage is similar to other stages involving foreign collections except in
     * some cases the foreign collection is allowed to be sharded.
     */
    class LiteParsed final : public LiteParsedDocumentSourceForeignCollections {
    public:
        static std::unique_ptr<LiteParsed> parse(const AggregationRequest& request,
                                                 const BSONElement& spec);

        LiteParsed(NamespaceString outNss, PrivilegeVector privileges, bool allowShardedOutNss)
            : LiteParsedDocumentSourceForeignCollections(outNss, privileges),
              _allowShardedOutNss(allowShardedOutNss) {}

        bool allowShardedForeignCollection(NamespaceString nss) const final {
            return _allowShardedOutNss ? true : (_foreignNssSet.find(nss) == _foreignNssSet.end());
        }

        bool allowedToPassthroughFromMongos() const final {
            // Do not allow passthrough from mongos even if the source collection is unsharded. This
            // ensures that the unique index verification happens once on mongos and can be bypassed
            // on the shards.
            return false;
        }

    private:
        bool _allowShardedOutNss;
    };

    DocumentSourceOut(NamespaceString outputNs,
                      const boost::intrusive_ptr<ExpressionContext>& expCtx,
                      WriteModeEnum mode,
                      std::set<FieldPath> uniqueKey);

    virtual ~DocumentSourceOut() = default;

    GetNextResult getNext() final;
    const char* getSourceName() const final;
    Value serialize(boost::optional<ExplainOptions::Verbosity> explain = boost::none) const final;
    DepsTracker::State getDependencies(DepsTracker* deps) const final;
    /**
     * For purposes of tracking which fields come from where, this stage does not modify any fields.
     */
    GetModPathsReturn getModifiedPaths() const final {
        return {GetModPathsReturn::Type::kFiniteSet, std::set<std::string>{}, {}};
    }

    StageConstraints constraints(Pipeline::SplitState pipeState) const final {
        return {StreamType::kStreaming,
                PositionRequirement::kLast,
                // A $out to an unsharded collection should merge on the primary shard to perform
                // local writes. A $out to a sharded collection has no requirement, since each shard
                // can perform its own portion of the write.
                HostTypeRequirement::kPrimaryShard,
                DiskUseRequirement::kWritesPersistentData,
                FacetRequirement::kNotAllowed,
                TransactionRequirement::kNotAllowed};
    }

    const NamespaceString& getOutputNs() const {
        return _outputNs;
    }

    WriteModeEnum getMode() const {
        return _mode;
    }

    boost::intrusive_ptr<DocumentSource> getShardSource() final {
        return nullptr;
    }
    MergingLogic mergingLogic() final {
        return {this};
    }
    virtual bool canRunInParallelBeforeOut(
        const std::set<std::string>& nameOfShardKeyFieldsUponEntryToStage) const final {
        // If someone is asking the question, this must be the $out stage in question, so yes!
        return true;
    }


    /**
     * Retrieves the namespace to direct each batch to, which may be a temporary namespace or the
     * final output namespace.
     */
    virtual const NamespaceString& getWriteNs() const = 0;

    /**
     * Prepares the DocumentSource to be able to write incoming batches to the desired collection.
     */
    virtual void initializeWriteNs() = 0;

    /**
     * Storage for a batch of BSON Objects to be inserted/updated to the write namespace. The
     * extracted unique key values are also stored in a batch, used by $out with mode
     * "replaceDocuments" as the query portion of the update.
     *
     */
    struct BatchedObjects {
        void emplace(BSONObj&& obj, BSONObj&& key) {
            objects.emplace_back(std::move(obj));
            uniqueKeys.emplace_back(std::move(key));
        }

        bool empty() const {
            return objects.empty();
        }

        size_t size() const {
            return objects.size();
        }

        void clear() {
            objects.clear();
            uniqueKeys.clear();
        }

        std::vector<BSONObj> objects;
        // Store the unique keys as BSON objects instead of Documents for compatibility with the
        // batch update command. (e.g. {q: <array of uniqueKeys>, u: <array of objects>})
        std::vector<BSONObj> uniqueKeys;
    };

    /**
     * Writes the documents in 'batch' to the write namespace.
     */
    virtual void spill(BatchedObjects&& batch) {
        pExpCtx->mongoProcessInterface->insert(pExpCtx, getWriteNs(), std::move(batch.objects));
    };

    /**
     * Finalize the output collection, called when there are no more documents to write.
     */
    virtual void finalize() = 0;

    /**
     * Creates a new $out stage from the given arguments.
     */
    static boost::intrusive_ptr<DocumentSourceOut> create(
        NamespaceString outputNs,
        const boost::intrusive_ptr<ExpressionContext>& expCtx,
        WriteModeEnum,
        std::set<FieldPath> uniqueKey = std::set<FieldPath>{"_id"});

    /**
     * Parses a $out stage from the user-supplied BSON.
     */
    static boost::intrusive_ptr<DocumentSource> createFromBson(
        BSONElement elem, const boost::intrusive_ptr<ExpressionContext>& pExpCtx);

private:
    bool _initialized = false;
    bool _done = false;

    const NamespaceString _outputNs;
    WriteModeEnum _mode;

    // Holds the unique key used for uniquely identifying documents. There must exist a unique index
    // with this key pattern (up to order). Default is "_id" for unsharded collections, and "_id"
    // plus the shard key for sharded collections.
    std::set<FieldPath> _uniqueKeyFields;

    // True if '_uniqueKeyFields' contains the _id. We store this as a separate boolean to avoid
    // repeated lookups into the set.
    bool _uniqueKeyIncludesId;
};

}  // namespace mongo