FIRQuery.mm 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  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/api/query_core.h"
  34. #include "Firestore/core/src/api/query_listener_registration.h"
  35. #include "Firestore/core/src/api/query_snapshot.h"
  36. #include "Firestore/core/src/api/source.h"
  37. #include "Firestore/core/src/core/bound.h"
  38. #include "Firestore/core/src/core/direction.h"
  39. #include "Firestore/core/src/core/filter.h"
  40. #include "Firestore/core/src/core/firestore_client.h"
  41. #include "Firestore/core/src/core/listen_options.h"
  42. #include "Firestore/core/src/core/order_by.h"
  43. #include "Firestore/core/src/core/query.h"
  44. #include "Firestore/core/src/model/document_key.h"
  45. #include "Firestore/core/src/model/field_path.h"
  46. #include "Firestore/core/src/model/field_value.h"
  47. #include "Firestore/core/src/model/resource_path.h"
  48. #include "Firestore/core/src/util/error_apple.h"
  49. #include "Firestore/core/src/util/exception.h"
  50. #include "Firestore/core/src/util/hard_assert.h"
  51. #include "Firestore/core/src/util/statusor.h"
  52. #include "Firestore/core/src/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 isNotEqualTo:(id)value {
  184. return [self queryWithFilterOperator:Filter::Operator::NotEqual field:field value:value];
  185. }
  186. - (FIRQuery *)queryWhereFieldPath:(FIRFieldPath *)path isNotEqualTo:(id)value {
  187. return [self queryWithFilterOperator:Filter::Operator::NotEqual
  188. path:path.internalValue
  189. value:value];
  190. }
  191. - (FIRQuery *)queryWhereField:(NSString *)field isLessThan:(id)value {
  192. return [self queryWithFilterOperator:Filter::Operator::LessThan field:field value:value];
  193. }
  194. - (FIRQuery *)queryWhereFieldPath:(FIRFieldPath *)path isLessThan:(id)value {
  195. return [self queryWithFilterOperator:Filter::Operator::LessThan
  196. path:path.internalValue
  197. value:value];
  198. }
  199. - (FIRQuery *)queryWhereField:(NSString *)field isLessThanOrEqualTo:(id)value {
  200. return [self queryWithFilterOperator:Filter::Operator::LessThanOrEqual field:field value:value];
  201. }
  202. - (FIRQuery *)queryWhereFieldPath:(FIRFieldPath *)path isLessThanOrEqualTo:(id)value {
  203. return [self queryWithFilterOperator:Filter::Operator::LessThanOrEqual
  204. path:path.internalValue
  205. value:value];
  206. }
  207. - (FIRQuery *)queryWhereField:(NSString *)field isGreaterThan:(id)value {
  208. return [self queryWithFilterOperator:Filter::Operator::GreaterThan field:field value:value];
  209. }
  210. - (FIRQuery *)queryWhereFieldPath:(FIRFieldPath *)path isGreaterThan:(id)value {
  211. return [self queryWithFilterOperator:Filter::Operator::GreaterThan
  212. path:path.internalValue
  213. value:value];
  214. }
  215. - (FIRQuery *)queryWhereField:(NSString *)field arrayContains:(id)value {
  216. return [self queryWithFilterOperator:Filter::Operator::ArrayContains field:field value:value];
  217. }
  218. - (FIRQuery *)queryWhereFieldPath:(FIRFieldPath *)path arrayContains:(id)value {
  219. return [self queryWithFilterOperator:Filter::Operator::ArrayContains
  220. path:path.internalValue
  221. value:value];
  222. }
  223. - (FIRQuery *)queryWhereField:(NSString *)field isGreaterThanOrEqualTo:(id)value {
  224. return [self queryWithFilterOperator:Filter::Operator::GreaterThanOrEqual
  225. field:field
  226. value:value];
  227. }
  228. - (FIRQuery *)queryWhereFieldPath:(FIRFieldPath *)path isGreaterThanOrEqualTo:(id)value {
  229. return [self queryWithFilterOperator:Filter::Operator::GreaterThanOrEqual
  230. path:path.internalValue
  231. value:value];
  232. }
  233. - (FIRQuery *)queryWhereField:(NSString *)field arrayContainsAny:(NSArray<id> *)values {
  234. return [self queryWithFilterOperator:Filter::Operator::ArrayContainsAny field:field value:values];
  235. }
  236. - (FIRQuery *)queryWhereFieldPath:(FIRFieldPath *)path arrayContainsAny:(NSArray<id> *)values {
  237. return [self queryWithFilterOperator:Filter::Operator::ArrayContainsAny
  238. path:path.internalValue
  239. value:values];
  240. }
  241. - (FIRQuery *)queryWhereField:(NSString *)field in:(NSArray<id> *)values {
  242. return [self queryWithFilterOperator:Filter::Operator::In field:field value:values];
  243. }
  244. - (FIRQuery *)queryWhereFieldPath:(FIRFieldPath *)path in:(NSArray<id> *)values {
  245. return [self queryWithFilterOperator:Filter::Operator::In path:path.internalValue value:values];
  246. }
  247. - (FIRQuery *)queryWhereField:(NSString *)field notIn:(NSArray<id> *)values {
  248. return [self queryWithFilterOperator:Filter::Operator::NotIn field:field value:values];
  249. }
  250. - (FIRQuery *)queryWhereFieldPath:(FIRFieldPath *)path notIn:(NSArray<id> *)values {
  251. return [self queryWithFilterOperator:Filter::Operator::NotIn
  252. path:path.internalValue
  253. value:values];
  254. }
  255. - (FIRQuery *)queryFilteredUsingComparisonPredicate:(NSPredicate *)predicate {
  256. NSComparisonPredicate *comparison = (NSComparisonPredicate *)predicate;
  257. if (comparison.comparisonPredicateModifier != NSDirectPredicateModifier) {
  258. ThrowInvalidArgument("Invalid query. Predicate cannot have an aggregate modifier.");
  259. }
  260. NSString *path;
  261. id value = nil;
  262. if ([comparison.leftExpression expressionType] == NSKeyPathExpressionType &&
  263. [comparison.rightExpression expressionType] == NSConstantValueExpressionType) {
  264. path = comparison.leftExpression.keyPath;
  265. value = comparison.rightExpression.constantValue;
  266. switch (comparison.predicateOperatorType) {
  267. case NSEqualToPredicateOperatorType:
  268. return [self queryWhereField:path isEqualTo:value];
  269. case NSLessThanPredicateOperatorType:
  270. return [self queryWhereField:path isLessThan:value];
  271. case NSLessThanOrEqualToPredicateOperatorType:
  272. return [self queryWhereField:path isLessThanOrEqualTo:value];
  273. case NSGreaterThanPredicateOperatorType:
  274. return [self queryWhereField:path isGreaterThan:value];
  275. case NSGreaterThanOrEqualToPredicateOperatorType:
  276. return [self queryWhereField:path isGreaterThanOrEqualTo:value];
  277. case NSNotEqualToPredicateOperatorType:
  278. return [self queryWhereField:path isNotEqualTo:value];
  279. default:; // Fallback below to throw assertion.
  280. }
  281. } else if ([comparison.leftExpression expressionType] == NSConstantValueExpressionType &&
  282. [comparison.rightExpression expressionType] == NSKeyPathExpressionType) {
  283. path = comparison.rightExpression.keyPath;
  284. value = comparison.leftExpression.constantValue;
  285. switch (comparison.predicateOperatorType) {
  286. case NSEqualToPredicateOperatorType:
  287. return [self queryWhereField:path isEqualTo:value];
  288. case NSLessThanPredicateOperatorType:
  289. return [self queryWhereField:path isGreaterThan:value];
  290. case NSLessThanOrEqualToPredicateOperatorType:
  291. return [self queryWhereField:path isGreaterThanOrEqualTo:value];
  292. case NSGreaterThanPredicateOperatorType:
  293. return [self queryWhereField:path isLessThan:value];
  294. case NSGreaterThanOrEqualToPredicateOperatorType:
  295. return [self queryWhereField:path isLessThanOrEqualTo:value];
  296. case NSNotEqualToPredicateOperatorType:
  297. return [self queryWhereField:path isNotEqualTo:value];
  298. default:; // Fallback below to throw assertion.
  299. }
  300. } else {
  301. ThrowInvalidArgument(
  302. "Invalid query. Predicate comparisons must include a key path and a constant.");
  303. }
  304. // Fallback cases of unsupported comparison operator.
  305. switch (comparison.predicateOperatorType) {
  306. case NSCustomSelectorPredicateOperatorType:
  307. ThrowInvalidArgument("Invalid query. Custom predicate filters are not supported.");
  308. break;
  309. default:
  310. ThrowInvalidArgument("Invalid query. Operator type %s is not supported.",
  311. comparison.predicateOperatorType);
  312. }
  313. }
  314. - (FIRQuery *)queryFilteredUsingCompoundPredicate:(NSPredicate *)predicate {
  315. NSCompoundPredicate *compound = (NSCompoundPredicate *)predicate;
  316. if (compound.compoundPredicateType != NSAndPredicateType || compound.subpredicates.count == 0) {
  317. ThrowInvalidArgument("Invalid query. Only compound queries using AND are supported.");
  318. }
  319. FIRQuery *query = self;
  320. for (NSPredicate *pred in compound.subpredicates) {
  321. query = [query queryFilteredUsingPredicate:pred];
  322. }
  323. return query;
  324. }
  325. - (FIRQuery *)queryFilteredUsingPredicate:(NSPredicate *)predicate {
  326. if ([predicate isKindOfClass:[NSComparisonPredicate class]]) {
  327. return [self queryFilteredUsingComparisonPredicate:predicate];
  328. } else if ([predicate isKindOfClass:[NSCompoundPredicate class]]) {
  329. return [self queryFilteredUsingCompoundPredicate:predicate];
  330. } else if ([predicate isKindOfClass:[[NSPredicate predicateWithBlock:^BOOL(id, NSDictionary *) {
  331. return true;
  332. }] class]]) {
  333. ThrowInvalidArgument("Invalid query. Block-based predicates are not supported. Please use "
  334. "predicateWithFormat to create predicates instead.");
  335. } else {
  336. ThrowInvalidArgument("Invalid query. Expect comparison or compound of comparison predicate. "
  337. "Please use predicateWithFormat to create predicates.");
  338. }
  339. }
  340. - (FIRQuery *)queryOrderedByField:(NSString *)field {
  341. return [self queryOrderedByField:field descending:NO];
  342. }
  343. - (FIRQuery *)queryOrderedByFieldPath:(FIRFieldPath *)fieldPath {
  344. return [self queryOrderedByFieldPath:fieldPath descending:NO];
  345. }
  346. - (FIRQuery *)queryOrderedByField:(NSString *)field descending:(BOOL)descending {
  347. return [self queryOrderedByFieldPath:MakeFieldPath(field)
  348. direction:Direction::FromDescending(descending)];
  349. }
  350. - (FIRQuery *)queryOrderedByFieldPath:(FIRFieldPath *)fieldPath descending:(BOOL)descending {
  351. return [self queryOrderedByFieldPath:fieldPath.internalValue
  352. direction:Direction::FromDescending(descending)];
  353. }
  354. - (FIRQuery *)queryOrderedByFieldPath:(model::FieldPath)fieldPath direction:(Direction)direction {
  355. return Wrap(_query.OrderBy(std::move(fieldPath), direction));
  356. }
  357. - (FIRQuery *)queryLimitedTo:(NSInteger)limit {
  358. return Wrap(_query.LimitToFirst(SaturatedLimitValue(limit)));
  359. }
  360. - (FIRQuery *)queryLimitedToLast:(NSInteger)limit {
  361. return Wrap(_query.LimitToLast(SaturatedLimitValue(limit)));
  362. }
  363. - (FIRQuery *)queryStartingAtDocument:(FIRDocumentSnapshot *)snapshot {
  364. Bound bound = [self boundFromSnapshot:snapshot isBefore:YES];
  365. return Wrap(_query.StartAt(std::move(bound)));
  366. }
  367. - (FIRQuery *)queryStartingAtValues:(NSArray *)fieldValues {
  368. Bound bound = [self boundFromFieldValues:fieldValues isBefore:YES];
  369. return Wrap(_query.StartAt(std::move(bound)));
  370. }
  371. - (FIRQuery *)queryStartingAfterDocument:(FIRDocumentSnapshot *)snapshot {
  372. Bound bound = [self boundFromSnapshot:snapshot isBefore:NO];
  373. return Wrap(_query.StartAt(std::move(bound)));
  374. }
  375. - (FIRQuery *)queryStartingAfterValues:(NSArray *)fieldValues {
  376. Bound bound = [self boundFromFieldValues:fieldValues isBefore:NO];
  377. return Wrap(_query.StartAt(std::move(bound)));
  378. }
  379. - (FIRQuery *)queryEndingBeforeDocument:(FIRDocumentSnapshot *)snapshot {
  380. Bound bound = [self boundFromSnapshot:snapshot isBefore:YES];
  381. return Wrap(_query.EndAt(std::move(bound)));
  382. }
  383. - (FIRQuery *)queryEndingBeforeValues:(NSArray *)fieldValues {
  384. Bound bound = [self boundFromFieldValues:fieldValues isBefore:YES];
  385. return Wrap(_query.EndAt(std::move(bound)));
  386. }
  387. - (FIRQuery *)queryEndingAtDocument:(FIRDocumentSnapshot *)snapshot {
  388. Bound bound = [self boundFromSnapshot:snapshot isBefore:NO];
  389. return Wrap(_query.EndAt(std::move(bound)));
  390. }
  391. - (FIRQuery *)queryEndingAtValues:(NSArray *)fieldValues {
  392. Bound bound = [self boundFromFieldValues:fieldValues isBefore:NO];
  393. return Wrap(_query.EndAt(std::move(bound)));
  394. }
  395. #pragma mark - Private Methods
  396. - (FieldValue)parsedQueryValue:(id)value {
  397. return [self.firestore.dataConverter parsedQueryValue:value];
  398. }
  399. - (FieldValue)parsedQueryValue:(id)value allowArrays:(bool)allowArrays {
  400. return [self.firestore.dataConverter parsedQueryValue:value allowArrays:allowArrays];
  401. }
  402. - (QuerySnapshotListener)wrapQuerySnapshotBlock:(FIRQuerySnapshotBlock)block {
  403. class Converter : public EventListener<QuerySnapshot> {
  404. public:
  405. explicit Converter(FIRQuerySnapshotBlock block) : block_(block) {
  406. }
  407. void OnEvent(StatusOr<QuerySnapshot> maybe_snapshot) override {
  408. if (maybe_snapshot.ok()) {
  409. FIRQuerySnapshot *result =
  410. [[FIRQuerySnapshot alloc] initWithSnapshot:std::move(maybe_snapshot).ValueOrDie()];
  411. block_(result, nil);
  412. } else {
  413. block_(nil, util::MakeNSError(maybe_snapshot.status()));
  414. }
  415. }
  416. private:
  417. FIRQuerySnapshotBlock block_;
  418. };
  419. return absl::make_unique<Converter>(block);
  420. }
  421. /** Private helper for all of the queryWhereField: methods. */
  422. - (FIRQuery *)queryWithFilterOperator:(Filter::Operator)filterOperator
  423. field:(NSString *)field
  424. value:(id)value {
  425. return [self queryWithFilterOperator:filterOperator path:MakeFieldPath(field) value:value];
  426. }
  427. - (FIRQuery *)queryWithFilterOperator:(Filter::Operator)filterOperator
  428. path:(const FieldPath &)fieldPath
  429. value:(id)value {
  430. FieldValue fieldValue = [self parsedQueryValue:value
  431. allowArrays:filterOperator == Filter::Operator::In ||
  432. filterOperator == Filter::Operator::NotIn];
  433. auto describer = [value] { return MakeString(NSStringFromClass([value class])); };
  434. return Wrap(_query.Filter(fieldPath, filterOperator, std::move(fieldValue), describer));
  435. }
  436. /**
  437. * Create a Bound from a query given the document.
  438. *
  439. * Note that the Bound will always include the key of the document and the position will be
  440. * unambiguous.
  441. *
  442. * Will throw if the document does not contain all fields of the order by of
  443. * the query or if any of the fields in the order by are an uncommitted server
  444. * timestamp.
  445. */
  446. - (Bound)boundFromSnapshot:(FIRDocumentSnapshot *)snapshot isBefore:(BOOL)isBefore {
  447. if (![snapshot exists]) {
  448. ThrowInvalidArgument("Invalid query. You are trying to start or end a query using a document "
  449. "that doesn't exist.");
  450. }
  451. const Document &document = *snapshot.internalDocument;
  452. const DatabaseId &databaseID = self.firestore.databaseID;
  453. std::vector<FieldValue> components;
  454. // Because people expect to continue/end a query at the exact document provided, we need to
  455. // use the implicit sort order rather than the explicit sort order, because it's guaranteed to
  456. // contain the document key. That way the position becomes unambiguous and the query
  457. // continues/ends exactly at the provided document. Without the key (by using the explicit sort
  458. // orders), multiple documents could match the position, yielding duplicate results.
  459. for (const OrderBy &orderBy : self.query.order_bys()) {
  460. if (orderBy.field() == FieldPath::KeyFieldPath()) {
  461. components.push_back(FieldValue::FromReference(databaseID, document.key()));
  462. } else {
  463. absl::optional<FieldValue> value = document.field(orderBy.field());
  464. if (value) {
  465. if (value->type() == FieldValue::Type::ServerTimestamp) {
  466. ThrowInvalidArgument(
  467. "Invalid query. You are trying to start or end a query using a document for which "
  468. "the field '%s' is an uncommitted server timestamp. (Since the value of this field "
  469. "is unknown, you cannot start/end a query with it.)",
  470. orderBy.field().CanonicalString());
  471. } else {
  472. components.push_back(*value);
  473. }
  474. } else {
  475. ThrowInvalidArgument(
  476. "Invalid query. You are trying to start or end a query using a document for which the "
  477. "field '%s' (used as the order by) does not exist.",
  478. orderBy.field().CanonicalString());
  479. }
  480. }
  481. }
  482. return Bound(std::move(components), isBefore);
  483. }
  484. /** Converts a list of field values to an Bound. */
  485. - (Bound)boundFromFieldValues:(NSArray<id> *)fieldValues isBefore:(BOOL)isBefore {
  486. // Use explicit sort order because it has to match the query the user made
  487. const OrderByList &explicitSortOrders = self.query.explicit_order_bys();
  488. if (fieldValues.count > explicitSortOrders.size()) {
  489. ThrowInvalidArgument("Invalid query. You are trying to start or end a query using more values "
  490. "than were specified in the order by.");
  491. }
  492. std::vector<FieldValue> components;
  493. for (NSUInteger idx = 0, max = fieldValues.count; idx < max; ++idx) {
  494. id rawValue = fieldValues[idx];
  495. const OrderBy &sortOrder = explicitSortOrders[idx];
  496. FieldValue fieldValue = [self parsedQueryValue:rawValue];
  497. if (sortOrder.field().IsKeyFieldPath()) {
  498. if (fieldValue.type() != FieldValue::Type::String) {
  499. ThrowInvalidArgument("Invalid query. Expected a string for the document ID.");
  500. }
  501. const std::string &documentID = fieldValue.string_value();
  502. if (!self.query.IsCollectionGroupQuery() && documentID.find('/') != std::string::npos) {
  503. ThrowInvalidArgument("Invalid query. When querying a collection and ordering by document "
  504. "ID, you must pass a plain document ID, but '%s' contains a slash.",
  505. documentID);
  506. }
  507. ResourcePath path = self.query.path().Append(ResourcePath::FromString(documentID));
  508. if (!DocumentKey::IsDocumentKey(path)) {
  509. ThrowInvalidArgument("Invalid query. When querying a collection group and ordering by "
  510. "document ID, you must pass a value that results in a valid document "
  511. "path, but '%s' is not because it contains an odd number of segments.",
  512. path.CanonicalString());
  513. }
  514. DocumentKey key{path};
  515. fieldValue = FieldValue::FromReference(self.firestore.databaseID, key);
  516. }
  517. components.push_back(fieldValue);
  518. }
  519. return Bound(std::move(components), isBefore);
  520. }
  521. @end
  522. @implementation FIRQuery (Internal)
  523. - (const core::Query &)query {
  524. return _query.query();
  525. }
  526. - (const api::Query &)apiQuery {
  527. return _query;
  528. }
  529. @end
  530. NS_ASSUME_NONNULL_END