FIRQuery.mm 22 KB

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