FIRQuery.m 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  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. #import "FIRDocumentReference.h"
  18. #import "Firestore/Source/API/FIRDocumentReference+Internal.h"
  19. #import "Firestore/Source/API/FIRDocumentSnapshot+Internal.h"
  20. #import "Firestore/Source/API/FIRFieldPath+Internal.h"
  21. #import "Firestore/Source/API/FIRFirestore+Internal.h"
  22. #import "Firestore/Source/API/FIRListenerRegistration+Internal.h"
  23. #import "Firestore/Source/API/FIRQuery+Internal.h"
  24. #import "Firestore/Source/API/FIRQuerySnapshot+Internal.h"
  25. #import "Firestore/Source/API/FIRQuery_Init.h"
  26. #import "Firestore/Source/API/FIRSnapshotMetadata+Internal.h"
  27. #import "Firestore/Source/API/FSTUserDataConverter.h"
  28. #import "Firestore/Source/Core/FSTEventManager.h"
  29. #import "Firestore/Source/Core/FSTFirestoreClient.h"
  30. #import "Firestore/Source/Core/FSTQuery.h"
  31. #import "Firestore/Source/Model/FSTDocument.h"
  32. #import "Firestore/Source/Model/FSTDocumentKey.h"
  33. #import "Firestore/Source/Model/FSTFieldValue.h"
  34. #import "Firestore/Source/Model/FSTPath.h"
  35. #import "Firestore/Source/Util/FSTAssert.h"
  36. #import "Firestore/Source/Util/FSTAsyncQueryListener.h"
  37. #import "Firestore/Source/Util/FSTUsageValidation.h"
  38. NS_ASSUME_NONNULL_BEGIN
  39. @interface FIRQueryListenOptions ()
  40. - (instancetype)initWithIncludeQueryMetadataChanges:(BOOL)includeQueryMetadataChanges
  41. includeDocumentMetadataChanges:(BOOL)includeDocumentMetadataChanges
  42. NS_DESIGNATED_INITIALIZER;
  43. @end
  44. @implementation FIRQueryListenOptions
  45. + (instancetype)options {
  46. return [[FIRQueryListenOptions alloc] init];
  47. }
  48. - (instancetype)initWithIncludeQueryMetadataChanges:(BOOL)includeQueryMetadataChanges
  49. includeDocumentMetadataChanges:(BOOL)includeDocumentMetadataChanges {
  50. if (self = [super init]) {
  51. _includeQueryMetadataChanges = includeQueryMetadataChanges;
  52. _includeDocumentMetadataChanges = includeDocumentMetadataChanges;
  53. }
  54. return self;
  55. }
  56. - (instancetype)init {
  57. return [self initWithIncludeQueryMetadataChanges:NO includeDocumentMetadataChanges:NO];
  58. }
  59. - (instancetype)includeQueryMetadataChanges:(BOOL)includeQueryMetadataChanges {
  60. return [[FIRQueryListenOptions alloc]
  61. initWithIncludeQueryMetadataChanges:includeQueryMetadataChanges
  62. includeDocumentMetadataChanges:_includeDocumentMetadataChanges];
  63. }
  64. - (instancetype)includeDocumentMetadataChanges:(BOOL)includeDocumentMetadataChanges {
  65. return [[FIRQueryListenOptions alloc]
  66. initWithIncludeQueryMetadataChanges:_includeQueryMetadataChanges
  67. includeDocumentMetadataChanges:includeDocumentMetadataChanges];
  68. }
  69. @end
  70. @interface FIRQuery ()
  71. @property(nonatomic, strong, readonly) FSTQuery *query;
  72. @end
  73. @implementation FIRQuery (Internal)
  74. + (instancetype)referenceWithQuery:(FSTQuery *)query firestore:(FIRFirestore *)firestore {
  75. return [[FIRQuery alloc] initWithQuery:query firestore:firestore];
  76. }
  77. @end
  78. @implementation FIRQuery
  79. #pragma mark - Constructor Methods
  80. - (instancetype)initWithQuery:(FSTQuery *)query firestore:(FIRFirestore *)firestore {
  81. if (self = [super init]) {
  82. _query = query;
  83. _firestore = firestore;
  84. }
  85. return self;
  86. }
  87. #pragma mark - NSObject Methods
  88. - (BOOL)isEqual:(nullable id)other {
  89. if (other == self) return YES;
  90. if (!other || ![[other class] isEqual:[self class]]) return NO;
  91. return [self isEqualToQuery:other];
  92. }
  93. - (BOOL)isEqualToQuery:(nullable FIRQuery *)query {
  94. if (self == query) return YES;
  95. if (query == nil) return NO;
  96. if (self.firestore != query.firestore && ![self.firestore isEqual:query.firestore]) return NO;
  97. if (self.query != query.query && ![self.query isEqual:query.query]) return NO;
  98. return YES;
  99. }
  100. - (NSUInteger)hash {
  101. NSUInteger hash = [self.firestore hash];
  102. hash = hash * 31u + [self.query hash];
  103. return hash;
  104. }
  105. #pragma mark - Public Methods
  106. - (void)getDocumentsWithCompletion:(void (^)(FIRQuerySnapshot *_Nullable snapshot,
  107. NSError *_Nullable error))completion {
  108. FSTListenOptions *options = [[FSTListenOptions alloc] initWithIncludeQueryMetadataChanges:YES
  109. includeDocumentMetadataChanges:YES
  110. waitForSyncWhenOnline:YES];
  111. dispatch_semaphore_t registered = dispatch_semaphore_create(0);
  112. __block id<FIRListenerRegistration> listenerRegistration;
  113. FIRQuerySnapshotBlock listener = ^(FIRQuerySnapshot *snapshot, NSError *error) {
  114. if (error) {
  115. completion(nil, error);
  116. return;
  117. }
  118. // Remove query first before passing event to user to avoid user actions affecting the
  119. // now stale query.
  120. dispatch_semaphore_wait(registered, DISPATCH_TIME_FOREVER);
  121. [listenerRegistration remove];
  122. completion(snapshot, nil);
  123. };
  124. listenerRegistration = [self addSnapshotListenerInternalWithOptions:options listener:listener];
  125. dispatch_semaphore_signal(registered);
  126. }
  127. - (id<FIRListenerRegistration>)addSnapshotListener:(FIRQuerySnapshotBlock)listener {
  128. return [self addSnapshotListenerWithOptions:nil listener:listener];
  129. }
  130. - (id<FIRListenerRegistration>)addSnapshotListenerWithOptions:
  131. (nullable FIRQueryListenOptions *)options
  132. listener:(FIRQuerySnapshotBlock)listener {
  133. return [self addSnapshotListenerInternalWithOptions:[self internalOptions:options]
  134. listener:listener];
  135. }
  136. - (id<FIRListenerRegistration>)
  137. addSnapshotListenerInternalWithOptions:(FSTListenOptions *)internalOptions
  138. listener:(FIRQuerySnapshotBlock)listener {
  139. FIRFirestore *firestore = self.firestore;
  140. FSTQuery *query = self.query;
  141. FSTViewSnapshotHandler snapshotHandler = ^(FSTViewSnapshot *snapshot, NSError *error) {
  142. if (error) {
  143. listener(nil, error);
  144. return;
  145. }
  146. FIRSnapshotMetadata *metadata =
  147. [FIRSnapshotMetadata snapshotMetadataWithPendingWrites:snapshot.hasPendingWrites
  148. fromCache:snapshot.fromCache];
  149. listener([FIRQuerySnapshot snapshotWithFirestore:firestore
  150. originalQuery:query
  151. snapshot:snapshot
  152. metadata:metadata],
  153. nil);
  154. };
  155. FSTAsyncQueryListener *asyncListener =
  156. [[FSTAsyncQueryListener alloc] initWithDispatchQueue:self.firestore.client.userDispatchQueue
  157. snapshotHandler:snapshotHandler];
  158. FSTQueryListener *internalListener =
  159. [firestore.client listenToQuery:query
  160. options:internalOptions
  161. viewSnapshotHandler:[asyncListener asyncSnapshotHandler]];
  162. return [[FSTListenerRegistration alloc] initWithClient:self.firestore.client
  163. asyncListener:asyncListener
  164. internalListener:internalListener];
  165. }
  166. - (FIRQuery *)queryWhereField:(NSString *)field isEqualTo:(id)value {
  167. return [self queryWithFilterOperator:FSTRelationFilterOperatorEqual field:field value:value];
  168. }
  169. - (FIRQuery *)queryWhereFieldPath:(FIRFieldPath *)path isEqualTo:(id)value {
  170. return [self queryWithFilterOperator:FSTRelationFilterOperatorEqual
  171. path:path.internalValue
  172. value:value];
  173. }
  174. - (FIRQuery *)queryWhereField:(NSString *)field isLessThan:(id)value {
  175. return [self queryWithFilterOperator:FSTRelationFilterOperatorLessThan field:field value:value];
  176. }
  177. - (FIRQuery *)queryWhereFieldPath:(FIRFieldPath *)path isLessThan:(id)value {
  178. return [self queryWithFilterOperator:FSTRelationFilterOperatorLessThan
  179. path:path.internalValue
  180. value:value];
  181. }
  182. - (FIRQuery *)queryWhereField:(NSString *)field isLessThanOrEqualTo:(id)value {
  183. return [self queryWithFilterOperator:FSTRelationFilterOperatorLessThanOrEqual
  184. field:field
  185. value:value];
  186. }
  187. - (FIRQuery *)queryWhereFieldPath:(FIRFieldPath *)path isLessThanOrEqualTo:(id)value {
  188. return [self queryWithFilterOperator:FSTRelationFilterOperatorLessThanOrEqual
  189. path:path.internalValue
  190. value:value];
  191. }
  192. - (FIRQuery *)queryWhereField:(NSString *)field isGreaterThan:(id)value {
  193. return
  194. [self queryWithFilterOperator:FSTRelationFilterOperatorGreaterThan field:field value:value];
  195. }
  196. - (FIRQuery *)queryWhereFieldPath:(FIRFieldPath *)path isGreaterThan:(id)value {
  197. return [self queryWithFilterOperator:FSTRelationFilterOperatorGreaterThan
  198. path:path.internalValue
  199. value:value];
  200. }
  201. - (FIRQuery *)queryWhereField:(NSString *)field isGreaterThanOrEqualTo:(id)value {
  202. return [self queryWithFilterOperator:FSTRelationFilterOperatorGreaterThanOrEqual
  203. field:field
  204. value:value];
  205. }
  206. - (FIRQuery *)queryWhereFieldPath:(FIRFieldPath *)path isGreaterThanOrEqualTo:(id)value {
  207. return [self queryWithFilterOperator:FSTRelationFilterOperatorGreaterThanOrEqual
  208. path:path.internalValue
  209. value:value];
  210. }
  211. - (FIRQuery *)queryOrderedByField:(NSString *)field {
  212. return
  213. [self queryOrderedByFieldPath:[FIRFieldPath pathWithDotSeparatedString:field] descending:NO];
  214. }
  215. - (FIRQuery *)queryOrderedByFieldPath:(FIRFieldPath *)fieldPath {
  216. return [self queryOrderedByFieldPath:fieldPath descending:NO];
  217. }
  218. - (FIRQuery *)queryOrderedByField:(NSString *)field descending:(BOOL)descending {
  219. return [self queryOrderedByFieldPath:[FIRFieldPath pathWithDotSeparatedString:field]
  220. descending:descending];
  221. }
  222. - (FIRQuery *)queryOrderedByFieldPath:(FIRFieldPath *)fieldPath descending:(BOOL)descending {
  223. [self validateNewOrderByPath:fieldPath.internalValue];
  224. if (self.query.startAt) {
  225. FSTThrowInvalidUsage(
  226. @"InvalidQueryException",
  227. @"Invalid query. You must not specify a starting point before specifying the order by.");
  228. }
  229. if (self.query.endAt) {
  230. FSTThrowInvalidUsage(
  231. @"InvalidQueryException",
  232. @"Invalid query. You must not specify an ending point before specifying the order by.");
  233. }
  234. FSTSortOrder *sortOrder =
  235. [FSTSortOrder sortOrderWithFieldPath:fieldPath.internalValue ascending:!descending];
  236. return [FIRQuery referenceWithQuery:[self.query queryByAddingSortOrder:sortOrder]
  237. firestore:self.firestore];
  238. }
  239. - (FIRQuery *)queryLimitedTo:(NSInteger)limit {
  240. if (limit <= 0) {
  241. FSTThrowInvalidArgument(@"Invalid Query. Query limit (%ld) is invalid. Limit must be positive.",
  242. (long)limit);
  243. }
  244. return [FIRQuery referenceWithQuery:[self.query queryBySettingLimit:limit] firestore:_firestore];
  245. }
  246. - (FIRQuery *)queryStartingAtDocument:(FIRDocumentSnapshot *)snapshot {
  247. FSTBound *bound = [self boundFromSnapshot:snapshot isBefore:YES];
  248. return [FIRQuery referenceWithQuery:[self.query queryByAddingStartAt:bound]
  249. firestore:self.firestore];
  250. }
  251. - (FIRQuery *)queryStartingAtValues:(NSArray *)fieldValues {
  252. FSTBound *bound = [self boundFromFieldValues:fieldValues isBefore:YES];
  253. return [FIRQuery referenceWithQuery:[self.query queryByAddingStartAt:bound]
  254. firestore:self.firestore];
  255. }
  256. - (FIRQuery *)queryStartingAfterDocument:(FIRDocumentSnapshot *)snapshot {
  257. FSTBound *bound = [self boundFromSnapshot:snapshot isBefore:NO];
  258. return [FIRQuery referenceWithQuery:[self.query queryByAddingStartAt:bound]
  259. firestore:self.firestore];
  260. }
  261. - (FIRQuery *)queryStartingAfterValues:(NSArray *)fieldValues {
  262. FSTBound *bound = [self boundFromFieldValues:fieldValues isBefore:NO];
  263. return [FIRQuery referenceWithQuery:[self.query queryByAddingStartAt:bound]
  264. firestore:self.firestore];
  265. }
  266. - (FIRQuery *)queryEndingBeforeDocument:(FIRDocumentSnapshot *)snapshot {
  267. FSTBound *bound = [self boundFromSnapshot:snapshot isBefore:YES];
  268. return
  269. [FIRQuery referenceWithQuery:[self.query queryByAddingEndAt:bound] firestore:self.firestore];
  270. }
  271. - (FIRQuery *)queryEndingBeforeValues:(NSArray *)fieldValues {
  272. FSTBound *bound = [self boundFromFieldValues:fieldValues isBefore:YES];
  273. return
  274. [FIRQuery referenceWithQuery:[self.query queryByAddingEndAt:bound] firestore:self.firestore];
  275. }
  276. - (FIRQuery *)queryEndingAtDocument:(FIRDocumentSnapshot *)snapshot {
  277. FSTBound *bound = [self boundFromSnapshot:snapshot isBefore:NO];
  278. return
  279. [FIRQuery referenceWithQuery:[self.query queryByAddingEndAt:bound] firestore:self.firestore];
  280. }
  281. - (FIRQuery *)queryEndingAtValues:(NSArray *)fieldValues {
  282. FSTBound *bound = [self boundFromFieldValues:fieldValues isBefore:NO];
  283. return
  284. [FIRQuery referenceWithQuery:[self.query queryByAddingEndAt:bound] firestore:self.firestore];
  285. }
  286. #pragma mark - Private Methods
  287. /** Private helper for all of the queryWhereField: methods. */
  288. - (FIRQuery *)queryWithFilterOperator:(FSTRelationFilterOperator)filterOperator
  289. field:(NSString *)field
  290. value:(id)value {
  291. return [self queryWithFilterOperator:filterOperator
  292. path:[FIRFieldPath pathWithDotSeparatedString:field].internalValue
  293. value:value];
  294. }
  295. - (FIRQuery *)queryWithFilterOperator:(FSTRelationFilterOperator)filterOperator
  296. path:(FSTFieldPath *)fieldPath
  297. value:(id)value {
  298. FSTFieldValue *fieldValue;
  299. if ([fieldPath isKeyFieldPath]) {
  300. if ([value isKindOfClass:[NSString class]]) {
  301. NSString *documentKey = (NSString *)value;
  302. if ([documentKey containsString:@"/"]) {
  303. FSTThrowInvalidArgument(
  304. @"Invalid query. When querying by document ID you must provide "
  305. "a valid document ID, but '%@' contains a '/' character.",
  306. documentKey);
  307. } else if (documentKey.length == 0) {
  308. FSTThrowInvalidArgument(
  309. @"Invalid query. When querying by document ID you must provide "
  310. "a valid document ID, but it was an empty string.");
  311. }
  312. FSTResourcePath *path = [self.query.path pathByAppendingSegment:documentKey];
  313. fieldValue = [FSTReferenceValue referenceValue:[FSTDocumentKey keyWithPath:path]
  314. databaseID:self.firestore.databaseID];
  315. } else if ([value isKindOfClass:[FIRDocumentReference class]]) {
  316. FIRDocumentReference *ref = (FIRDocumentReference *)value;
  317. fieldValue = [FSTReferenceValue referenceValue:ref.key databaseID:self.firestore.databaseID];
  318. } else {
  319. FSTThrowInvalidArgument(
  320. @"Invalid query. When querying by document ID you must provide a "
  321. "valid string or DocumentReference, but it was of type: %@",
  322. NSStringFromClass([value class]));
  323. }
  324. } else {
  325. fieldValue = [self.firestore.dataConverter parsedQueryValue:value];
  326. }
  327. id<FSTFilter> filter;
  328. if ([fieldValue isEqual:[FSTNullValue nullValue]]) {
  329. if (filterOperator != FSTRelationFilterOperatorEqual) {
  330. FSTThrowInvalidUsage(@"InvalidQueryException",
  331. @"Invalid Query. You can only perform equality comparisons on nil / "
  332. "NSNull.");
  333. }
  334. filter = [[FSTNullFilter alloc] initWithField:fieldPath];
  335. } else if ([fieldValue isEqual:[FSTDoubleValue nanValue]]) {
  336. if (filterOperator != FSTRelationFilterOperatorEqual) {
  337. FSTThrowInvalidUsage(@"InvalidQueryException",
  338. @"Invalid Query. You can only perform equality comparisons on NaN.");
  339. }
  340. filter = [[FSTNanFilter alloc] initWithField:fieldPath];
  341. } else {
  342. filter = [FSTRelationFilter filterWithField:fieldPath
  343. filterOperator:filterOperator
  344. value:fieldValue];
  345. [self validateNewRelationFilter:filter];
  346. }
  347. return [FIRQuery referenceWithQuery:[self.query queryByAddingFilter:filter]
  348. firestore:self.firestore];
  349. }
  350. - (void)validateNewRelationFilter:(FSTRelationFilter *)filter {
  351. if ([filter isInequality]) {
  352. FSTFieldPath *existingField = [self.query inequalityFilterField];
  353. if (existingField && ![existingField isEqual:filter.field]) {
  354. FSTThrowInvalidUsage(
  355. @"InvalidQueryException",
  356. @"Invalid Query. All where filters with an inequality "
  357. "(lessThan, lessThanOrEqual, greaterThan, or greaterThanOrEqual) must be on the same "
  358. "field. But you have inequality filters on '%@' and '%@'",
  359. existingField, filter.field);
  360. }
  361. FSTFieldPath *firstOrderByField = [self.query firstSortOrderField];
  362. if (firstOrderByField) {
  363. [self validateOrderByField:firstOrderByField matchesInequalityField:filter.field];
  364. }
  365. }
  366. }
  367. - (void)validateNewOrderByPath:(FSTFieldPath *)fieldPath {
  368. if (![self.query firstSortOrderField]) {
  369. // This is the first order by. It must match any inequality.
  370. FSTFieldPath *inequalityField = [self.query inequalityFilterField];
  371. if (inequalityField) {
  372. [self validateOrderByField:fieldPath matchesInequalityField:inequalityField];
  373. }
  374. }
  375. }
  376. - (void)validateOrderByField:(FSTFieldPath *)orderByField
  377. matchesInequalityField:(FSTFieldPath *)inequalityField {
  378. if (!([orderByField isEqual:inequalityField])) {
  379. FSTThrowInvalidUsage(
  380. @"InvalidQueryException",
  381. @"Invalid query. You have a where filter with an "
  382. "inequality (lessThan, lessThanOrEqual, greaterThan, or greaterThanOrEqual) on field '%@' "
  383. "and so you must also use '%@' as your first queryOrderedBy field, but your first "
  384. "queryOrderedBy is currently on field '%@' instead.",
  385. inequalityField, inequalityField, orderByField);
  386. }
  387. }
  388. /**
  389. * Create a FSTBound from a query given the document.
  390. *
  391. * Note that the FSTBound will always include the key of the document and the position will be
  392. * unambiguous.
  393. *
  394. * Will throw if the document does not contain all fields of the order by of the query.
  395. */
  396. - (FSTBound *)boundFromSnapshot:(FIRDocumentSnapshot *)snapshot isBefore:(BOOL)isBefore {
  397. if (![snapshot exists]) {
  398. FSTThrowInvalidUsage(@"InvalidQueryException",
  399. @"Invalid query. You are trying to start or end a query using a document "
  400. @"that doesn't exist.");
  401. }
  402. FSTDocument *document = snapshot.internalDocument;
  403. NSMutableArray<FSTFieldValue *> *components = [NSMutableArray array];
  404. // Because people expect to continue/end a query at the exact document provided, we need to
  405. // use the implicit sort order rather than the explicit sort order, because it's guaranteed to
  406. // contain the document key. That way the position becomes unambiguous and the query
  407. // continues/ends exactly at the provided document. Without the key (by using the explicit sort
  408. // orders), multiple documents could match the position, yielding duplicate results.
  409. for (FSTSortOrder *sortOrder in self.query.sortOrders) {
  410. if ([sortOrder.field isEqual:[FSTFieldPath keyFieldPath]]) {
  411. [components addObject:[FSTReferenceValue referenceValue:document.key
  412. databaseID:self.firestore.databaseID]];
  413. } else {
  414. FSTFieldValue *value = [document fieldForPath:sortOrder.field];
  415. if (value != nil) {
  416. [components addObject:value];
  417. } else {
  418. FSTThrowInvalidUsage(@"InvalidQueryException",
  419. @"Invalid query. You are trying to start or end a query using a "
  420. "document for which the field '%@' (used as the order by) "
  421. "does not exist.",
  422. sortOrder.field.canonicalString);
  423. }
  424. }
  425. }
  426. return [FSTBound boundWithPosition:components isBefore:isBefore];
  427. }
  428. /** Converts a list of field values to an FSTBound. */
  429. - (FSTBound *)boundFromFieldValues:(NSArray<id> *)fieldValues isBefore:(BOOL)isBefore {
  430. // Use explicit sort order because it has to match the query the user made
  431. NSArray<FSTSortOrder *> *explicitSortOrders = self.query.explicitSortOrders;
  432. if (fieldValues.count > explicitSortOrders.count) {
  433. FSTThrowInvalidUsage(@"InvalidQueryException",
  434. @"Invalid query. You are trying to start or end a query using more values "
  435. @"than were specified in the order by.");
  436. }
  437. NSMutableArray<FSTFieldValue *> *components = [NSMutableArray array];
  438. [fieldValues enumerateObjectsUsingBlock:^(id rawValue, NSUInteger idx, BOOL *stop) {
  439. FSTSortOrder *sortOrder = explicitSortOrders[idx];
  440. if ([sortOrder.field isEqual:[FSTFieldPath keyFieldPath]]) {
  441. if (![rawValue isKindOfClass:[NSString class]]) {
  442. FSTThrowInvalidUsage(@"InvalidQueryException",
  443. @"Invalid query. Expected a string for the document ID.");
  444. }
  445. NSString *documentID = (NSString *)rawValue;
  446. if ([documentID containsString:@"/"]) {
  447. FSTThrowInvalidUsage(@"InvalidQueryException",
  448. @"Invalid query. Document ID '%@' contains a slash.", documentID);
  449. }
  450. FSTDocumentKey *key =
  451. [FSTDocumentKey keyWithPath:[self.query.path pathByAppendingSegment:documentID]];
  452. [components
  453. addObject:[FSTReferenceValue referenceValue:key databaseID:self.firestore.databaseID]];
  454. } else {
  455. FSTFieldValue *fieldValue = [self.firestore.dataConverter parsedQueryValue:rawValue];
  456. [components addObject:fieldValue];
  457. }
  458. }];
  459. return [FSTBound boundWithPosition:components isBefore:isBefore];
  460. }
  461. /** Converts the public API options object to the internal options object. */
  462. - (FSTListenOptions *)internalOptions:(nullable FIRQueryListenOptions *)options {
  463. return [[FSTListenOptions alloc]
  464. initWithIncludeQueryMetadataChanges:options.includeQueryMetadataChanges
  465. includeDocumentMetadataChanges:options.includeDocumentMetadataChanges
  466. waitForSyncWhenOnline:NO];
  467. }
  468. @end
  469. NS_ASSUME_NONNULL_END