userver: userver/storages/mongo/options.hpp Source File
Loading...
Searching...
No Matches
options.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/storages/mongo/options.hpp
4/// @brief Query options
5
6#include <chrono>
7#include <cstddef>
8#include <cstdint>
9#include <initializer_list>
10#include <optional>
11#include <string>
12#include <string_view>
13#include <utility>
14#include <vector>
15
16#include <userver/formats/bson/bson_builder.hpp>
17#include <userver/formats/bson/document.hpp>
18#include <userver/formats/bson/value.hpp>
19
20USERVER_NAMESPACE_BEGIN
21
22/// Collection operation options
23namespace storages::mongo::options {
24
25/// @brief Read preference
26/// @see https://docs.mongodb.com/manual/reference/read-preference/
28public:
29 enum Mode {
30 /// read from primary, default mode
32 /// read from secondary
34 /// read from primary if available, fallback to secondary
36 /// read from secondary if available, fallback to primary
38 /// read from any host with the lowest latency
40 };
41
42 explicit ReadPreference(Mode mode);
43 ReadPreference(Mode mode, std::vector<formats::bson::Document> tags);
44
45 Mode GetMode() const;
46 std::optional<std::chrono::seconds> GetMaxStaleness() const;
47 const std::vector<formats::bson::Document>& GetTags() const;
48
49 /// @brief Sets maximum replication lag for eligible replica.
50 /// @note Must be at least 90 seconds, cannot be used with kPrimary mode.
51 ReadPreference& SetMaxStaleness(std::optional<std::chrono::seconds> max_staleness);
52
53 /// @brief Adds a tag to the tag set.
54 /// @note Cannot be used with kPrimary mode.
56
57private:
58 Mode mode_;
59 std::optional<std::chrono::seconds> max_staleness_;
60 std::vector<formats::bson::Document> tags_;
61};
62
63/// @brief Read concern
64/// @see https://docs.mongodb.org/manual/reference/readConcern/
65enum class ReadConcern {
66 /// no replication checks, default level
67 kLocal,
68 /// return data replicated to a majority of RS members
70 /// waits for all running majority writes to finish before read
72 /// no replication checks, may return orphaned documents if sharded; since 3.6
74};
75
76/// @brief Write concern
77/// @see https://docs.mongodb.org/manual/reference/write-concern/
79public:
80 enum Level {
81 /// Wait until propagation to a "majority" of RS nodes
83 /// Do not check for operation errors, do not wait for write, same as `0`
85 };
86
87 /// Default timeout for "majority" write concern
89
90 /// Creates a write concern with the special level
91 explicit WriteConcern(Level level);
92
93 /// Creates a write concern waiting for propagation to `nodes_count` RS nodes
94 explicit WriteConcern(size_t nodes_count);
95
96 /// Creates a write concern defined in RS config
97 explicit WriteConcern(std::string tag);
98
99 bool IsMajority() const;
100 size_t NodesCount() const;
101 const std::string& Tag() const;
102 std::optional<bool> Journal() const;
103 const std::chrono::milliseconds& Timeout() const;
104
105 /// Sets write concern timeout, `0` means no timeout
106 WriteConcern& SetTimeout(std::chrono::milliseconds timeout);
107
108 /// Sets whether to wait for on-disk journal commit
110
111private:
112 size_t nodes_count_;
113 bool is_majority_;
114 std::optional<bool> journal_;
115 std::string tag_;
116 std::chrono::milliseconds timeout_;
117};
118
119/// Disables ordering on bulk operations causing them to continue after an error
120class Unordered {};
121
122/// Enables insertion of a new document when update selector matches nothing
123class Upsert {};
124
125/// Enables automatic one-time retry of duplicate key errors
127
128/// Specifies that FindAndModify should return the new version of an object
129class ReturnNew {};
130
131/// Specifies the number of documents to skip
132class Skip {
133public:
134 explicit Skip(size_t value) : value_(value) {}
135
136 size_t Value() const { return value_; }
137
138 size_t value_;
139};
140
141/// @brief Specifies the number of documents to request from the server
142/// @note The value of `0` means "no limit".
143class Limit {
144public:
145 explicit Limit(size_t value) : value_(value) {}
146
147 size_t Value() const { return value_; }
148
149private:
150 size_t value_;
151};
152
153/// @brief Selects fields to be returned
154/// @note `_id` field is always included by default, order might be significant
155/// @see
156/// https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/
158public:
159 /// Creates a default projection including all fields
160 Projection() = default;
161
162 /// Creates a projection including only specified fields
163 Projection(std::initializer_list<std::string_view> fields_to_include);
164
165 /// Includes a field into the projection
166 Projection& Include(std::string_view field);
167
168 /// @brief Excludes a field from the projection
169 /// @warning Projection cannot have a mix of inclusion and exclusion.
170 /// Only the `_id` field can always be excluded.
171 Projection& Exclude(std::string_view field);
172
173 /// @brief Setups an array slice in the projection
174 /// @param field name of the array field to slice
175 /// @param limit the number of items to return
176 /// @param skip the following number of items
177 /// @note `skip` can be negative, this corresponds to counting from the end
178 /// backwards.
179 /// @note `limit < 0, skip == 0` is equivalent to `limit' = -limit, skip' =
180 /// limit`.
181 /// @warning Cannot be applied to views.
182 Projection& Slice(std::string_view field, int32_t limit, int32_t skip = 0);
183
184 /// @brief Matches the first element of an array satisfying a predicate
185 /// @param field name of the array to search
186 /// @param pred predicate to apply to elements
187 /// @note Array field will be absent from the result if no elements match.
188 /// @note Empty document as a predicate will only match empty documents.
189 Projection& ElemMatch(std::string_view field, const formats::bson::Document& pred);
190
191 /// @cond
192 /// Projection specification BSON access
193 const bson_t* GetProjectionBson() const;
194 /// @endcond
195
196private:
197 formats::bson::impl::BsonBuilder projection_builder_;
198};
199
200/// Sorts the results
201class Sort {
202public:
203 enum Direction {
204 kAscending,
205 kDescending,
206 };
207
208 /// Creates an empty ordering specification
209 Sort() = default;
210
211 /// Stores the specified ordering specification
213
214 /// Appends a field to the ordering specification
215 Sort& By(std::string_view field, Direction direction);
216
217 /// @cond
218 /// Sort specification BSON access
219 const bson_t* GetSortBson() const;
220 /// @endcond
221
222private:
223 formats::bson::impl::BsonBuilder sort_builder_;
224};
225
226/// @brief Specifies an index to use for the query
227/// @warning Only plans using the index will be considered.
228class Hint {
229public:
230 /// Specifies an index by name
231 explicit Hint(std::string index_name);
232
233 /// Specifies an index by fields covered
234 explicit Hint(formats::bson::Document index_spec);
235
236 /// @cond
237 /// Retrieves a hint value
238 const formats::bson::Value& Value() const;
239 /// @endcond
240
241private:
242 formats::bson::Value value_;
243};
244
245/// @brief Specifies an array of filter documents that
246/// determine which array elements to modify for an update
247/// operation on an array field.
249public:
250 /// Specifies list of filters
251 explicit ArrayFilters(std::initializer_list<formats::bson::Document>);
252
253 /// @cond
254 /// Retrieves an arrayFilters value
255 const formats::bson::Value& Value() const;
256 /// @endcond
257
258private:
259 formats::bson::Value value_;
260};
261
262/// Selects count implementation to use: new aggregation-based or old cmd-based
263enum class ForceCountImpl { kAggregate, kCmd };
264
265/// Suppresses errors on querying a sharded collection with unavailable shards
267
268/// @brief Disables exception throw on server errors, should be checked manually
269/// in WriteResult
271
272/// @brief Enables tailable cursor, which block at the end of capped collections
273/// @note Automatically sets `awaitData`.
274/// @see https://docs.mongodb.com/manual/core/tailable-cursors/
275class Tailable {};
276
277/// Sets a comment for the operation, which would be visible in profile data
278class Comment {
279public:
280 explicit Comment(std::string);
281
282 const std::string& Value() const;
283
284private:
285 std::string value_;
286};
287
288/// @brief Specifies the server-side time limit for the operation
289/// @warning This does not set any client-side timeouts.
291public:
292 explicit MaxServerTime(const std::chrono::milliseconds& value) : value_(value) {}
293
294 const std::chrono::milliseconds& Value() const { return value_; }
295
296private:
297 std::chrono::milliseconds value_;
298};
299
300} // namespace storages::mongo::options
301
302USERVER_NAMESPACE_END