-
Notifications
You must be signed in to change notification settings - Fork 137
Expand file tree
/
Copy pathquery_main.cc
More file actions
351 lines (301 loc) · 13.4 KB
/
Copy pathquery_main.cc
File metadata and controls
351 lines (301 loc) · 13.4 KB
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
/*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "firestore/src/main/query_main.h"
#include <utility>
#include "Firestore/core/src/api/aggregate_query.h"
#include "Firestore/core/src/api/listener_registration.h"
#include "Firestore/core/src/core/filter.h"
#include "Firestore/core/src/core/listen_options.h"
#include "Firestore/core/src/model/document_key.h"
#include "Firestore/core/src/model/field_path.h"
#include "Firestore/core/src/model/resource_path.h"
#include "Firestore/core/src/model/server_timestamp_util.h"
#include "Firestore/core/src/model/value_util.h"
#include "Firestore/core/src/nanopb/nanopb_util.h"
#include "Firestore/core/src/util/exception.h"
#include "app/src/assert.h"
#include "firestore/src/common/exception_common.h"
#include "firestore/src/common/hard_assert_common.h"
#include "firestore/src/common/macros.h"
#include "firestore/src/include/firebase/firestore.h"
#include "firestore/src/main/aggregate_query_main.h"
#include "firestore/src/main/converter_main.h"
#include "firestore/src/main/document_snapshot_main.h"
#include "firestore/src/main/filter_main.h"
#include "firestore/src/main/listener_main.h"
#include "firestore/src/main/promise_main.h"
#include "firestore/src/main/set_options_main.h"
#include "firestore/src/main/source_main.h"
#include "firestore/src/main/util_main.h"
namespace firebase {
namespace firestore {
using model::DeepClone;
using model::DocumentKey;
using model::GetTypeOrder;
using model::IsServerTimestamp;
using model::RefValue;
using model::ResourcePath;
using model::TypeOrder;
using nanopb::CheckedSize;
using nanopb::MakeArray;
using nanopb::MakeString;
using nanopb::Message;
using nanopb::SharedMessage;
QueryInternal::QueryInternal(api::Query&& query)
: query_{std::move(query)},
promise_factory_{PromiseFactory<AsyncApis>::Create(this)},
user_data_converter_{&firestore_internal()->database_id()} {}
Firestore* QueryInternal::firestore() { return GetFirestore(&query_); }
FirestoreInternal* QueryInternal::firestore_internal() {
return GetFirestoreInternal(&query_);
}
const FirestoreInternal* QueryInternal::firestore_internal() const {
return GetFirestoreInternal(&query_);
}
Query QueryInternal::OrderBy(const FieldPath& field_path,
Query::Direction direction) const {
api::Query decorated = query_.OrderBy(
GetInternal(field_path), direction == Query::Direction::kDescending);
return MakePublic(std::move(decorated));
}
Query QueryInternal::Limit(int32_t limit) const {
return MakePublic(query_.LimitToFirst(limit));
}
Query QueryInternal::LimitToLast(int32_t limit) const {
return MakePublic(query_.LimitToLast(limit));
}
Future<QuerySnapshot> QueryInternal::Get(Source source) {
auto promise = promise_factory_.CreatePromise<QuerySnapshot>(AsyncApis::kGet);
auto listener = ListenerWithPromise<api::QuerySnapshot>(promise);
query_.GetDocuments(ToCoreApi(source), std::move(listener));
return promise.future();
}
AggregateQuery QueryInternal::Count() { return MakePublic(query_.Count()); }
AggregateQuery QueryInternal::Aggregate(const AggregateField& aggregate_field) {
// TODO: Implement Aggregate
// return MakePublic(aggregate_field);
}
Query QueryInternal::Where(const Filter& filter) const {
SIMPLE_HARD_ASSERT(!filter.IsEmpty());
core::Filter core_filter =
GetInternal(&filter)->ToCoreFilter(query_, user_data_converter_);
api::Query decorated = query_.AddNewFilter(std::move(core_filter));
return MakePublic(std::move(decorated));
}
Query QueryInternal::Where(const FieldPath& field_path,
Operator op,
const FieldValue& value) const {
return Where(UnaryFilterInternal::UnaryFilter(field_path, op, value));
}
Query QueryInternal::Where(const FieldPath& field_path,
Operator op,
const std::vector<FieldValue>& values) const {
return Where(UnaryFilterInternal::UnaryFilter(field_path, op, values));
}
Query QueryInternal::WithBound(BoundPosition bound_pos,
const DocumentSnapshot& snapshot) const {
core::Bound bound = ToBound(bound_pos, snapshot);
return MakePublic(CreateQueryWithBound(bound_pos, std::move(bound)));
}
Query QueryInternal::WithBound(BoundPosition bound_pos,
const std::vector<FieldValue>& values) const {
core::Bound bound = ToBound(bound_pos, values);
return MakePublic(CreateQueryWithBound(bound_pos, std::move(bound)));
}
ListenerRegistration QueryInternal::AddSnapshotListener(
MetadataChanges metadata_changes, EventListener<QuerySnapshot>* listener) {
auto options = core::ListenOptions::FromIncludeMetadataChanges(
metadata_changes == MetadataChanges::kInclude);
auto result = query_.AddSnapshotListener(
options, ListenerWithEventListener<api::QuerySnapshot>(listener));
return MakePublic(std::move(result), firestore_internal());
}
ListenerRegistration QueryInternal::AddSnapshotListener(
MetadataChanges metadata_changes,
std::function<void(const QuerySnapshot&, Error, const std::string&)>
callback) {
auto options = core::ListenOptions::FromIncludeMetadataChanges(
metadata_changes == MetadataChanges::kInclude);
auto result = query_.AddSnapshotListener(
options, ListenerWithCallback<api::QuerySnapshot>(std::move(callback)));
return MakePublic(std::move(result), firestore_internal());
}
bool operator==(const QueryInternal& lhs, const QueryInternal& rhs) {
return lhs.query_ == rhs.query_;
}
core::Bound QueryInternal::ToBound(
BoundPosition bound_pos, const DocumentSnapshot& public_snapshot) const {
if (!public_snapshot.exists()) {
SimpleThrowInvalidArgument(
"Invalid query. You are trying to start or end a query using a "
"document that doesn't exist.");
}
const api::DocumentSnapshot& api_snapshot = GetCoreApi(public_snapshot);
const model::DocumentKey& key =
api_snapshot.internal_document().value()->key();
const model::DatabaseId& database_id = firestore_internal()->database_id();
const core::Query& internal_query = query_.query();
SharedMessage<google_firestore_v1_ArrayValue> components{{}};
components->values_count =
CheckedSize(internal_query.normalized_order_bys().size());
components->values =
MakeArray<google_firestore_v1_Value>(components->values_count);
// Because people expect to continue/end a query at the exact document
// provided, we need to use the implicit sort order rather than the explicit
// sort order, because it's guaranteed to contain the document key. That way
// the position becomes unambiguous and the query continues/ends exactly at
// the provided document. Without the key (by using the explicit sort orders),
// multiple documents could match the position, yielding duplicate results.
for (size_t i = 0; i < internal_query.normalized_order_bys().size(); ++i) {
const core::OrderBy& order_by = internal_query.normalized_order_bys()[i];
const model::FieldPath& field_path = order_by.field();
if (field_path.IsKeyFieldPath()) {
components->values[i] = *RefValue(database_id, key).release();
continue;
}
absl::optional<google_firestore_v1_Value> value =
api_snapshot.GetValue(field_path);
if (!value) {
// TODO(b/147444199): use string formatting.
// ThrowInvalidArgument(
// "Invalid query. You are trying to start or end a query using a "
// "document for which the field '%s' (used as the order by) does not
// " "exist.", field_path.CanonicalString());
auto message = std::string(
"Invalid query. You are trying to start or end a "
"query using a document for which the field '") +
field_path.CanonicalString() +
"' (used as the order by) does not exist.";
SimpleThrowInvalidArgument(message);
}
if (IsServerTimestamp(*value)) {
// TODO(b/147444199): use string formatting.
// ThrowInvalidArgument(
// "Invalid query. You are trying to start or end a query using a "
// "document for which the field '%s' is an uncommitted server "
// "timestamp. (Since the value of this field is unknown, you cannot "
// "start/end a query with it.)",
// field_path.CanonicalString());
auto message =
std::string(
"Invalid query. You are trying to start or end a query using a "
"document for which the field '") +
field_path.CanonicalString() +
"' is an uncommitted server timestamp. (Since the value of this "
"field is unknown, you cannot start/end a query with it.)";
SimpleThrowInvalidArgument(message);
}
components->values[i] = *DeepClone(*value).release();
}
return core::Bound::FromValue(std::move(components), IsInclusive(bound_pos));
}
core::Bound QueryInternal::ToBound(
BoundPosition bound_pos,
const std::vector<FieldValue>& field_values) const {
const core::Query& internal_query = query_.query();
// Use explicit order bys because it has to match the query the user made.
const std::vector<core::OrderBy>& explicit_order_bys =
internal_query.explicit_order_bys();
if (field_values.size() > explicit_order_bys.size()) {
SimpleThrowInvalidArgument(
"Invalid query. You are trying to start or end a query using more "
"values than were specified in the order by.");
}
SharedMessage<google_firestore_v1_ArrayValue> components{{}};
components->values_count = CheckedSize(field_values.size());
components->values =
MakeArray<google_firestore_v1_Value>(components->values_count);
for (int i = 0; i != field_values.size(); ++i) {
Message<google_firestore_v1_Value> field_value =
user_data_converter_.ParseQueryValue(field_values[i]);
const core::OrderBy& order_by = explicit_order_bys[i];
if (order_by.field().IsKeyFieldPath()) {
components->values[i] =
*ConvertDocumentId(field_value, internal_query).release();
} else {
components->values[i] = *field_value.release();
}
}
return core::Bound::FromValue(std::move(components), IsInclusive(bound_pos));
}
Message<google_firestore_v1_Value> QueryInternal::ConvertDocumentId(
const Message<google_firestore_v1_Value>& from,
const core::Query& internal_query) const {
if (GetTypeOrder(*from) != TypeOrder::kString) {
SimpleThrowInvalidArgument(
"Invalid query. Expected a string for the document ID.");
}
std::string document_id = MakeString(from->string_value);
if (!internal_query.IsCollectionGroupQuery() &&
document_id.find('/') != std::string::npos) {
// TODO(b/147444199): use string formatting.
// ThrowInvalidArgument(
// "Invalid query. When querying a collection and ordering by document "
// "ID, you must pass a plain document ID, but '%s' contains a slash.",
// document_id);
auto message =
std::string(
"Invalid query. When querying a collection and ordering "
"by document ID, you must pass a plain document ID, but '") +
document_id + "' contains a slash.";
SimpleThrowInvalidArgument(message);
}
ResourcePath path =
internal_query.path().Append(ResourcePath::FromString(document_id));
if (!DocumentKey::IsDocumentKey(path)) {
// TODO(b/147444199): use string formatting.
// ThrowInvalidArgument(
// "Invalid query. When querying a collection group and ordering by "
// "document ID, you must pass a value that results in a valid document
// " "path, but '%s' is not because it contains an odd number of
// segments.", path.CanonicalString());
auto message =
std::string(
"Invalid query. When querying a collection group and ordering by "
"document ID, you must pass a value that results in a valid "
"document path, but '") +
path.CanonicalString() +
"' is not because it contains an odd number of segments.";
SimpleThrowInvalidArgument(message);
}
const model::DatabaseId& database_id = firestore_internal()->database_id();
return RefValue(database_id, DocumentKey{std::move(path)});
}
api::Query QueryInternal::CreateQueryWithBound(BoundPosition bound_pos,
core::Bound&& bound) const {
switch (bound_pos) {
case BoundPosition::kStartAt:
case BoundPosition::kStartAfter:
return query_.StartAt(std::move(bound));
case BoundPosition::kEndBefore:
case BoundPosition::kEndAt:
return query_.EndAt(std::move(bound));
}
FIRESTORE_UNREACHABLE();
}
bool QueryInternal::IsInclusive(BoundPosition bound_pos) {
switch (bound_pos) {
case BoundPosition::kStartAt:
case BoundPosition::kEndAt:
return true;
case BoundPosition::kStartAfter:
case BoundPosition::kEndBefore:
return false;
}
FIRESTORE_UNREACHABLE();
}
} // namespace firestore
} // namespace firebase