FIRQuery.mm 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. /*
  2. * Copyright 2017 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import "FIRQuery.h"
  17. #include <memory>
  18. #include <utility>
  19. #include <vector>
  20. #import "FIRDocumentReference.h"
  21. #import "FIRFirestoreErrors.h"
  22. #import "Firestore/Source/API/FIRDocumentReference+Internal.h"
  23. #import "Firestore/Source/API/FIRDocumentSnapshot+Internal.h"
  24. #import "Firestore/Source/API/FIRFieldPath+Internal.h"
  25. #import "Firestore/Source/API/FIRFieldValue+Internal.h"
  26. #import "Firestore/Source/API/FIRFirestore+Internal.h"
  27. #import "Firestore/Source/API/FIRFirestoreSource+Internal.h"
  28. #import "Firestore/Source/API/FIRListenerRegistration+Internal.h"
  29. #import "Firestore/Source/API/FIRQuery+Internal.h"
  30. #import "Firestore/Source/API/FIRQuerySnapshot+Internal.h"
  31. #import "Firestore/Source/API/FIRSnapshotMetadata+Internal.h"
  32. #import "Firestore/Source/API/FSTUserDataConverter.h"
  33. #include "Firestore/core/src/firebase/firestore/api/query_core.h"
  34. #include "Firestore/core/src/firebase/firestore/api/query_listener_registration.h"
  35. #include "Firestore/core/src/firebase/firestore/core/bound.h"
  36. #include "Firestore/core/src/firebase/firestore/core/direction.h"
  37. #include "Firestore/core/src/firebase/firestore/core/filter.h"
  38. #include "Firestore/core/src/firebase/firestore/core/firestore_client.h"
  39. #include "Firestore/core/src/firebase/firestore/core/order_by.h"
  40. #include "Firestore/core/src/firebase/firestore/core/query.h"
  41. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  42. #include "Firestore/core/src/firebase/firestore/model/field_path.h"
  43. #include "Firestore/core/src/firebase/firestore/model/field_value.h"
  44. #include "Firestore/core/src/firebase/firestore/model/resource_path.h"
  45. #include "Firestore/core/src/firebase/firestore/util/error_apple.h"
  46. #include "Firestore/core/src/firebase/firestore/util/exception.h"
  47. #include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
  48. #include "Firestore/core/src/firebase/firestore/util/statusor.h"
  49. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  50. #include "absl/memory/memory.h"
  51. namespace util = firebase::firestore::util;
  52. using firebase::firestore::api::Firestore;
  53. using firebase::firestore::api::ListenerRegistration;
  54. using firebase::firestore::api::Query;
  55. using firebase::firestore::api::QueryListenerRegistration;
  56. using firebase::firestore::api::QuerySnapshot;
  57. using firebase::firestore::api::SnapshotMetadata;
  58. using firebase::firestore::api::Source;
  59. using firebase::firestore::core::AsyncEventListener;
  60. using firebase::firestore::core::Bound;
  61. using firebase::firestore::core::Direction;
  62. using firebase::firestore::core::EventListener;
  63. using firebase::firestore::core::Filter;
  64. using firebase::firestore::core::ListenOptions;
  65. using firebase::firestore::core::OrderBy;
  66. using firebase::firestore::core::OrderByList;
  67. using firebase::firestore::core::QueryListener;
  68. using firebase::firestore::core::ViewSnapshot;
  69. using firebase::firestore::model::DatabaseId;
  70. using firebase::firestore::model::Document;
  71. using firebase::firestore::model::DocumentKey;
  72. using firebase::firestore::model::FieldPath;
  73. using firebase::firestore::model::FieldValue;
  74. using firebase::firestore::model::ResourcePath;
  75. using firebase::firestore::util::MakeNSError;
  76. using firebase::firestore::util::MakeString;
  77. using firebase::firestore::util::StatusOr;
  78. using firebase::firestore::util::ThrowInvalidArgument;
  79. NS_ASSUME_NONNULL_BEGIN
  80. namespace {
  81. FieldPath MakeFieldPath(NSString *field) {
  82. return FieldPath::FromDotSeparatedString(MakeString(field));
  83. }
  84. FIRQuery *Wrap(Query &&query) {
  85. return [[FIRQuery alloc] initWithQuery:std::move(query)];
  86. }
  87. int32_t SaturatedLimitValue(NSInteger limit) {
  88. int32_t internal_limit;
  89. if (limit == NSNotFound || limit >= core::Target::kNoLimit) {
  90. internal_limit = core::Target::kNoLimit;
  91. } else {
  92. internal_limit = static_cast<int32_t>(limit);
  93. }
  94. return internal_limit;
  95. }
  96. } // namespace
  97. @implementation FIRQuery {
  98. Query _query;
  99. }
  100. #pragma mark - Constructor Methods
  101. - (instancetype)initWithQuery:(Query &&)query {
  102. if (self = [super init]) {
  103. _query = std::move(query);
  104. }
  105. return self;
  106. }
  107. - (instancetype)initWithQuery:(core::Query)query firestore:(std::shared_ptr<Firestore>)firestore {
  108. return [self initWithQuery:Query{std::move(query), std::move(firestore)}];
  109. }
  110. #pragma mark - NSObject Methods
  111. - (BOOL)isEqual:(nullable id)other {
  112. if (other == self) return YES;
  113. if (![[other class] isEqual:[self class]]) return NO;
  114. auto otherQuery = static_cast<FIRQuery *>(other);
  115. return _query == otherQuery->_query;
  116. }
  117. - (NSUInteger)hash {
  118. return _query.Hash();
  119. }
  120. #pragma mark - Public Methods
  121. - (FIRFirestore *)firestore {
  122. return [FIRFirestore recoverFromFirestore:_query.firestore()];
  123. }
  124. - (void)getDocumentsWithCompletion:(void (^)(FIRQuerySnapshot *_Nullable snapshot,
  125. NSError *_Nullable error))completion {
  126. _query.GetDocuments(Source::Default, [self wrapQuerySnapshotBlock:completion]);
  127. }
  128. - (void)getDocumentsWithSource:(FIRFirestoreSource)publicSource
  129. completion:(void (^)(FIRQuerySnapshot *_Nullable snapshot,
  130. NSError *_Nullable error))completion {
  131. Source source = api::MakeSource(publicSource);
  132. _query.GetDocuments(source, [self wrapQuerySnapshotBlock:completion]);
  133. }
  134. - (id<FIRListenerRegistration>)addSnapshotListener:(FIRQuerySnapshotBlock)listener {
  135. return [self addSnapshotListenerWithIncludeMetadataChanges:NO listener:listener];
  136. }
  137. - (id<FIRListenerRegistration>)
  138. addSnapshotListenerWithIncludeMetadataChanges:(BOOL)includeMetadataChanges
  139. listener:(FIRQuerySnapshotBlock)listener {
  140. auto options = ListenOptions::FromIncludeMetadataChanges(includeMetadataChanges);
  141. return [self addSnapshotListenerInternalWithOptions:options listener:listener];
  142. }
  143. - (id<FIRListenerRegistration>)addSnapshotListenerInternalWithOptions:(ListenOptions)internalOptions
  144. listener:
  145. (FIRQuerySnapshotBlock)listener {
  146. std::shared_ptr<Firestore> firestore = self.firestore.wrapped;
  147. const core::Query &query = self.query;
  148. // Convert from ViewSnapshots to QuerySnapshots.
  149. auto view_listener = EventListener<ViewSnapshot>::Create(
  150. [listener, firestore, query](StatusOr<ViewSnapshot> maybe_snapshot) {
  151. if (!maybe_snapshot.status().ok()) {
  152. listener(nil, MakeNSError(maybe_snapshot.status()));
  153. return;
  154. }
  155. ViewSnapshot snapshot = std::move(maybe_snapshot).ValueOrDie();
  156. SnapshotMetadata metadata(snapshot.has_pending_writes(), snapshot.from_cache());
  157. listener([[FIRQuerySnapshot alloc] initWithFirestore:firestore
  158. originalQuery:query
  159. snapshot:std::move(snapshot)
  160. metadata:std::move(metadata)],
  161. nil);
  162. });
  163. // Call the view_listener on the user Executor.
  164. auto async_listener = AsyncEventListener<ViewSnapshot>::Create(
  165. firestore->client()->user_executor(), std::move(view_listener));
  166. std::shared_ptr<QueryListener> query_listener =
  167. firestore->client()->ListenToQuery(query, internalOptions, async_listener);
  168. return [[FSTListenerRegistration alloc]
  169. initWithRegistration:absl::make_unique<QueryListenerRegistration>(firestore->client(),
  170. std::move(async_listener),
  171. std::move(query_listener))];
  172. }
  173. - (FIRQuery *)queryWhereField:(NSString *)field isEqualTo:(id)value {
  174. return [self queryWithFilterOperator:Filter::Operator::Equal field:field value:value];
  175. }
  176. - (FIRQuery *)queryWhereFieldPath:(FIRFieldPath *)path isEqualTo:(id)value {
  177. return [self queryWithFilterOperator:Filter::Operator::Equal path:path.internalValue value:value];
  178. }
  179. - (FIRQuery *)queryWhereField:(NSString *)field isLessThan:(id)value {
  180. return [self queryWithFilterOperator:Filter::Operator::LessThan field:field value:value];
  181. }
  182. - (FIRQuery *)queryWhereFieldPath:(FIRFieldPath *)path isLessThan:(id)value {
  183. return [self queryWithFilterOperator:Filter::Operator::LessThan
  184. path:path.internalValue
  185. value:value];
  186. }
  187. - (FIRQuery *)queryWhereField:(NSString *)field isLessThanOrEqualTo:(id)value {
  188. return [self queryWithFilterOperator:Filter::Operator::LessThanOrEqual field:field value:value];
  189. }
  190. - (FIRQuery *)queryWhereFieldPath:(FIRFieldPath *)path isLessThanOrEqualTo:(id)value {
  191. return [self queryWithFilterOperator:Filter::Operator::LessThanOrEqual
  192. path:path.internalValue
  193. value:value];
  194. }
  195. - (FIRQuery *)queryWhereField:(NSString *)field isGreaterThan:(id)value {
  196. return [self queryWithFilterOperator:Filter::Operator::GreaterThan field:field value:value];
  197. }
  198. - (FIRQuery *)queryWhereFieldPath:(FIRFieldPath *)path isGreaterThan:(id)value {
  199. return [self queryWithFilterOperator:Filter::Operator::GreaterThan
  200. path:path.internalValue
  201. value:value];
  202. }
  203. - (FIRQuery *)queryWhereField:(NSString *)field arrayContains:(id)value {
  204. return [self queryWithFilterOperator:Filter::Operator::ArrayContains field:field value:value];
  205. }
  206. - (FIRQuery *)queryWhereFieldPath:(FIRFieldPath *)path arrayContains:(id)value {
  207. return [self queryWithFilterOperator:Filter::Operator::ArrayContains
  208. path:path.internalValue
  209. value:value];
  210. }
  211. - (FIRQuery *)queryWhereField:(NSString *)field isGreaterThanOrEqualTo:(id)value {
  212. return [self queryWithFilterOperator:Filter::Operator::GreaterThanOrEqual
  213. field:field
  214. value:value];
  215. }
  216. - (FIRQuery *)queryWhereFieldPath:(FIRFieldPath *)path isGreaterThanOrEqualTo:(id)value {
  217. return [self queryWithFilterOperator:Filter::Operator::GreaterThanOrEqual
  218. path:path.internalValue
  219. value:value];
  220. }
  221. - (FIRQuery *)queryWhereField:(NSString *)field arrayContainsAny:(NSArray<id> *)values {
  222. return [self queryWithFilterOperator:Filter::Operator::ArrayContainsAny field:field value:values];
  223. }
  224. - (FIRQuery *)queryWhereFieldPath:(FIRFieldPath *)path arrayContainsAny:(NSArray<id> *)values {
  225. return [self queryWithFilterOperator:Filter::Operator::ArrayContainsAny
  226. path:path.internalValue
  227. value:values];
  228. }
  229. - (FIRQuery *)queryWhereField:(NSString *)field in:(NSArray<id> *)values {
  230. return [self queryWithFilterOperator:Filter::Operator::In field:field value:values];
  231. }
  232. - (FIRQuery *)queryWhereFieldPath:(FIRFieldPath *)path in:(NSArray<id> *)values {
  233. return [self queryWithFilterOperator:Filter::Operator::In path:path.internalValue value:values];
  234. }
  235. - (FIRQuery *)queryFilteredUsingComparisonPredicate:(NSPredicate *)predicate {
  236. NSComparisonPredicate *comparison = (NSComparisonPredicate *)predicate;
  237. if (comparison.comparisonPredicateModifier != NSDirectPredicateModifier) {
  238. ThrowInvalidArgument("Invalid query. Predicate cannot have an aggregate modifier.");
  239. }
  240. NSString *path;
  241. id value = nil;
  242. if ([comparison.leftExpression expressionType] == NSKeyPathExpressionType &&
  243. [comparison.rightExpression expressionType] == NSConstantValueExpressionType) {
  244. path = comparison.leftExpression.keyPath;
  245. value = comparison.rightExpression.constantValue;
  246. switch (comparison.predicateOperatorType) {
  247. case NSEqualToPredicateOperatorType:
  248. return [self queryWhereField:path isEqualTo:value];
  249. case NSLessThanPredicateOperatorType:
  250. return [self queryWhereField:path isLessThan:value];
  251. case NSLessThanOrEqualToPredicateOperatorType:
  252. return [self queryWhereField:path isLessThanOrEqualTo:value];
  253. case NSGreaterThanPredicateOperatorType:
  254. return [self queryWhereField:path isGreaterThan:value];
  255. case NSGreaterThanOrEqualToPredicateOperatorType:
  256. return [self queryWhereField:path isGreaterThanOrEqualTo:value];
  257. default:; // Fallback below to throw assertion.
  258. }
  259. } else if ([comparison.leftExpression expressionType] == NSConstantValueExpressionType &&
  260. [comparison.rightExpression expressionType] == NSKeyPathExpressionType) {
  261. path = comparison.rightExpression.keyPath;
  262. value = comparison.leftExpression.constantValue;
  263. switch (comparison.predicateOperatorType) {
  264. case NSEqualToPredicateOperatorType:
  265. return [self queryWhereField:path isEqualTo:value];
  266. case NSLessThanPredicateOperatorType:
  267. return [self queryWhereField:path isGreaterThan:value];
  268. case NSLessThanOrEqualToPredicateOperatorType:
  269. return [self queryWhereField:path isGreaterThanOrEqualTo:value];
  270. case NSGreaterThanPredicateOperatorType:
  271. return [self queryWhereField:path isLessThan:value];
  272. case NSGreaterThanOrEqualToPredicateOperatorType:
  273. return [self queryWhereField:path isLessThanOrEqualTo:value];
  274. default:; // Fallback below to throw assertion.
  275. }
  276. } else {
  277. ThrowInvalidArgument(
  278. "Invalid query. Predicate comparisons must include a key path and a constant.");
  279. }
  280. // Fallback cases of unsupported comparison operator.
  281. switch (comparison.predicateOperatorType) {
  282. case NSCustomSelectorPredicateOperatorType:
  283. ThrowInvalidArgument("Invalid query. Custom predicate filters are not supported.");
  284. break;
  285. default:
  286. ThrowInvalidArgument("Invalid query. Operator type %s is not supported.",
  287. comparison.predicateOperatorType);
  288. }
  289. }
  290. - (FIRQuery *)queryFilteredUsingCompoundPredicate:(NSPredicate *)predicate {
  291. NSCompoundPredicate *compound = (NSCompoundPredicate *)predicate;
  292. if (compound.compoundPredicateType != NSAndPredicateType || compound.subpredicates.count == 0) {
  293. ThrowInvalidArgument("Invalid query. Only compound queries using AND are supported.");
  294. }
  295. FIRQuery *query = self;
  296. for (NSPredicate *pred in compound.subpredicates) {
  297. query = [query queryFilteredUsingPredicate:pred];
  298. }
  299. return query;
  300. }
  301. - (FIRQuery *)queryFilteredUsingPredicate:(NSPredicate *)predicate {
  302. if ([predicate isKindOfClass:[NSComparisonPredicate class]]) {
  303. return [self queryFilteredUsingComparisonPredicate:predicate];
  304. } else if ([predicate isKindOfClass:[NSCompoundPredicate class]]) {
  305. return [self queryFilteredUsingCompoundPredicate:predicate];
  306. } else if ([predicate isKindOfClass:[[NSPredicate
  307. predicateWithBlock:^BOOL(id obj, NSDictionary *bindings) {
  308. return true;
  309. }] class]]) {
  310. ThrowInvalidArgument("Invalid query. Block-based predicates are not supported. Please use "
  311. "predicateWithFormat to create predicates instead.");
  312. } else {
  313. ThrowInvalidArgument("Invalid query. Expect comparison or compound of comparison predicate. "
  314. "Please use predicateWithFormat to create predicates.");
  315. }
  316. }
  317. - (FIRQuery *)queryOrderedByField:(NSString *)field {
  318. return [self queryOrderedByField:field descending:NO];
  319. }
  320. - (FIRQuery *)queryOrderedByFieldPath:(FIRFieldPath *)fieldPath {
  321. return [self queryOrderedByFieldPath:fieldPath descending:NO];
  322. }
  323. - (FIRQuery *)queryOrderedByField:(NSString *)field descending:(BOOL)descending {
  324. return [self queryOrderedByFieldPath:MakeFieldPath(field)
  325. direction:Direction::FromDescending(descending)];
  326. }
  327. - (FIRQuery *)queryOrderedByFieldPath:(FIRFieldPath *)fieldPath descending:(BOOL)descending {
  328. return [self queryOrderedByFieldPath:fieldPath.internalValue
  329. direction:Direction::FromDescending(descending)];
  330. }
  331. - (FIRQuery *)queryOrderedByFieldPath:(model::FieldPath)fieldPath direction:(Direction)direction {
  332. return Wrap(_query.OrderBy(std::move(fieldPath), direction));
  333. }
  334. - (FIRQuery *)queryLimitedTo:(NSInteger)limit {
  335. return Wrap(_query.LimitToFirst(SaturatedLimitValue(limit)));
  336. }
  337. - (FIRQuery *)queryLimitedToLast:(NSInteger)limit {
  338. return Wrap(_query.LimitToLast(SaturatedLimitValue(limit)));
  339. }
  340. - (FIRQuery *)queryStartingAtDocument:(FIRDocumentSnapshot *)snapshot {
  341. Bound bound = [self boundFromSnapshot:snapshot isBefore:YES];
  342. return Wrap(_query.StartAt(std::move(bound)));
  343. }
  344. - (FIRQuery *)queryStartingAtValues:(NSArray *)fieldValues {
  345. Bound bound = [self boundFromFieldValues:fieldValues isBefore:YES];
  346. return Wrap(_query.StartAt(std::move(bound)));
  347. }
  348. - (FIRQuery *)queryStartingAfterDocument:(FIRDocumentSnapshot *)snapshot {
  349. Bound bound = [self boundFromSnapshot:snapshot isBefore:NO];
  350. return Wrap(_query.StartAt(std::move(bound)));
  351. }
  352. - (FIRQuery *)queryStartingAfterValues:(NSArray *)fieldValues {
  353. Bound bound = [self boundFromFieldValues:fieldValues isBefore:NO];
  354. return Wrap(_query.StartAt(std::move(bound)));
  355. }
  356. - (FIRQuery *)queryEndingBeforeDocument:(FIRDocumentSnapshot *)snapshot {
  357. Bound bound = [self boundFromSnapshot:snapshot isBefore:YES];
  358. return Wrap(_query.EndAt(std::move(bound)));
  359. }
  360. - (FIRQuery *)queryEndingBeforeValues:(NSArray *)fieldValues {
  361. Bound bound = [self boundFromFieldValues:fieldValues isBefore:YES];
  362. return Wrap(_query.EndAt(std::move(bound)));
  363. }
  364. - (FIRQuery *)queryEndingAtDocument:(FIRDocumentSnapshot *)snapshot {
  365. Bound bound = [self boundFromSnapshot:snapshot isBefore:NO];
  366. return Wrap(_query.EndAt(std::move(bound)));
  367. }
  368. - (FIRQuery *)queryEndingAtValues:(NSArray *)fieldValues {
  369. Bound bound = [self boundFromFieldValues:fieldValues isBefore:NO];
  370. return Wrap(_query.EndAt(std::move(bound)));
  371. }
  372. #pragma mark - Private Methods
  373. - (FieldValue)parsedQueryValue:(id)value {
  374. return [self.firestore.dataConverter parsedQueryValue:value];
  375. }
  376. - (FieldValue)parsedQueryValue:(id)value allowArrays:(bool)allowArrays {
  377. return [self.firestore.dataConverter parsedQueryValue:value allowArrays:allowArrays];
  378. }
  379. - (QuerySnapshot::Listener)wrapQuerySnapshotBlock:(FIRQuerySnapshotBlock)block {
  380. class Converter : public EventListener<QuerySnapshot> {
  381. public:
  382. explicit Converter(FIRQuerySnapshotBlock block) : block_(block) {
  383. }
  384. void OnEvent(StatusOr<QuerySnapshot> maybe_snapshot) override {
  385. if (maybe_snapshot.ok()) {
  386. FIRQuerySnapshot *result =
  387. [[FIRQuerySnapshot alloc] initWithSnapshot:std::move(maybe_snapshot).ValueOrDie()];
  388. block_(result, nil);
  389. } else {
  390. block_(nil, util::MakeNSError(maybe_snapshot.status()));
  391. }
  392. }
  393. private:
  394. FIRQuerySnapshotBlock block_;
  395. };
  396. return absl::make_unique<Converter>(block);
  397. }
  398. /** Private helper for all of the queryWhereField: methods. */
  399. - (FIRQuery *)queryWithFilterOperator:(Filter::Operator)filterOperator
  400. field:(NSString *)field
  401. value:(id)value {
  402. return [self queryWithFilterOperator:filterOperator path:MakeFieldPath(field) value:value];
  403. }
  404. - (FIRQuery *)queryWithFilterOperator:(Filter::Operator)filterOperator
  405. path:(const FieldPath &)fieldPath
  406. value:(id)value {
  407. FieldValue fieldValue = [self parsedQueryValue:value
  408. allowArrays:filterOperator == Filter::Operator::In];
  409. auto describer = [value] { return MakeString(NSStringFromClass([value class])); };
  410. return Wrap(_query.Filter(fieldPath, filterOperator, std::move(fieldValue), describer));
  411. }
  412. /**
  413. * Create a Bound from a query given the document.
  414. *
  415. * Note that the Bound will always include the key of the document and the position will be
  416. * unambiguous.
  417. *
  418. * Will throw if the document does not contain all fields of the order by of
  419. * the query or if any of the fields in the order by are an uncommitted server
  420. * timestamp.
  421. */
  422. - (Bound)boundFromSnapshot:(FIRDocumentSnapshot *)snapshot isBefore:(BOOL)isBefore {
  423. if (![snapshot exists]) {
  424. ThrowInvalidArgument("Invalid query. You are trying to start or end a query using a document "
  425. "that doesn't exist.");
  426. }
  427. const Document &document = *snapshot.internalDocument;
  428. const DatabaseId &databaseID = self.firestore.databaseID;
  429. std::vector<FieldValue> components;
  430. // Because people expect to continue/end a query at the exact document provided, we need to
  431. // use the implicit sort order rather than the explicit sort order, because it's guaranteed to
  432. // contain the document key. That way the position becomes unambiguous and the query
  433. // continues/ends exactly at the provided document. Without the key (by using the explicit sort
  434. // orders), multiple documents could match the position, yielding duplicate results.
  435. for (const OrderBy &orderBy : self.query.order_bys()) {
  436. if (orderBy.field() == FieldPath::KeyFieldPath()) {
  437. components.push_back(FieldValue::FromReference(databaseID, document.key()));
  438. } else {
  439. absl::optional<FieldValue> value = document.field(orderBy.field());
  440. if (value) {
  441. if (value->type() == FieldValue::Type::ServerTimestamp) {
  442. ThrowInvalidArgument(
  443. "Invalid query. You are trying to start or end a query using a document for which "
  444. "the field '%s' is an uncommitted server timestamp. (Since the value of this field "
  445. "is unknown, you cannot start/end a query with it.)",
  446. orderBy.field().CanonicalString());
  447. } else {
  448. components.push_back(*value);
  449. }
  450. } else {
  451. ThrowInvalidArgument(
  452. "Invalid query. You are trying to start or end a query using a document for which the "
  453. "field '%s' (used as the order by) does not exist.",
  454. orderBy.field().CanonicalString());
  455. }
  456. }
  457. }
  458. return Bound(std::move(components), isBefore);
  459. }
  460. /** Converts a list of field values to an Bound. */
  461. - (Bound)boundFromFieldValues:(NSArray<id> *)fieldValues isBefore:(BOOL)isBefore {
  462. // Use explicit sort order because it has to match the query the user made
  463. const OrderByList &explicitSortOrders = self.query.explicit_order_bys();
  464. if (fieldValues.count > explicitSortOrders.size()) {
  465. ThrowInvalidArgument("Invalid query. You are trying to start or end a query using more values "
  466. "than were specified in the order by.");
  467. }
  468. std::vector<FieldValue> components;
  469. for (NSUInteger idx = 0, max = fieldValues.count; idx < max; ++idx) {
  470. id rawValue = fieldValues[idx];
  471. const OrderBy &sortOrder = explicitSortOrders[idx];
  472. FieldValue fieldValue = [self parsedQueryValue:rawValue];
  473. if (sortOrder.field().IsKeyFieldPath()) {
  474. if (fieldValue.type() != FieldValue::Type::String) {
  475. ThrowInvalidArgument("Invalid query. Expected a string for the document ID.");
  476. }
  477. const std::string &documentID = fieldValue.string_value();
  478. if (!self.query.IsCollectionGroupQuery() && documentID.find('/') != std::string::npos) {
  479. ThrowInvalidArgument("Invalid query. When querying a collection and ordering by document "
  480. "ID, you must pass a plain document ID, but '%s' contains a slash.",
  481. documentID);
  482. }
  483. ResourcePath path = self.query.path().Append(ResourcePath::FromString(documentID));
  484. if (!DocumentKey::IsDocumentKey(path)) {
  485. ThrowInvalidArgument("Invalid query. When querying a collection group and ordering by "
  486. "document ID, you must pass a value that results in a valid document "
  487. "path, but '%s' is not because it contains an odd number of segments.",
  488. path.CanonicalString());
  489. }
  490. DocumentKey key{path};
  491. fieldValue = FieldValue::FromReference(self.firestore.databaseID, key);
  492. }
  493. components.push_back(fieldValue);
  494. }
  495. return Bound(std::move(components), isBefore);
  496. }
  497. @end
  498. @implementation FIRQuery (Internal)
  499. - (const core::Query &)query {
  500. return _query.query();
  501. }
  502. - (const api::Query &)apiQuery {
  503. return _query;
  504. }
  505. @end
  506. NS_ASSUME_NONNULL_END