FIRQuery.mm 23 KB

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