FIRQuery.mm 25 KB

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