FIRQuery.mm 29 KB

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