FIRQuery.mm 23 KB

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