FIRQuery.mm 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  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/FSTFieldValue.h"
  33. #import "Firestore/Source/Util/FSTAssert.h"
  34. #import "Firestore/Source/Util/FSTAsyncQueryListener.h"
  35. #import "Firestore/Source/Util/FSTUsageValidation.h"
  36. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  37. #include "Firestore/core/src/firebase/firestore/model/field_path.h"
  38. #include "Firestore/core/src/firebase/firestore/model/resource_path.h"
  39. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  40. namespace util = firebase::firestore::util;
  41. using firebase::firestore::model::DocumentKey;
  42. using firebase::firestore::model::FieldPath;
  43. using firebase::firestore::model::ResourcePath;
  44. NS_ASSUME_NONNULL_BEGIN
  45. @interface FIRQueryListenOptions ()
  46. - (instancetype)initWithIncludeQueryMetadataChanges:(BOOL)includeQueryMetadataChanges
  47. includeDocumentMetadataChanges:(BOOL)includeDocumentMetadataChanges
  48. NS_DESIGNATED_INITIALIZER;
  49. @end
  50. @implementation FIRQueryListenOptions
  51. + (instancetype)options {
  52. return [[FIRQueryListenOptions alloc] init];
  53. }
  54. - (instancetype)initWithIncludeQueryMetadataChanges:(BOOL)includeQueryMetadataChanges
  55. includeDocumentMetadataChanges:(BOOL)includeDocumentMetadataChanges {
  56. if (self = [super init]) {
  57. _includeQueryMetadataChanges = includeQueryMetadataChanges;
  58. _includeDocumentMetadataChanges = includeDocumentMetadataChanges;
  59. }
  60. return self;
  61. }
  62. - (instancetype)init {
  63. return [self initWithIncludeQueryMetadataChanges:NO includeDocumentMetadataChanges:NO];
  64. }
  65. - (instancetype)includeQueryMetadataChanges:(BOOL)includeQueryMetadataChanges {
  66. return [[FIRQueryListenOptions alloc]
  67. initWithIncludeQueryMetadataChanges:includeQueryMetadataChanges
  68. includeDocumentMetadataChanges:_includeDocumentMetadataChanges];
  69. }
  70. - (instancetype)includeDocumentMetadataChanges:(BOOL)includeDocumentMetadataChanges {
  71. return [[FIRQueryListenOptions alloc]
  72. initWithIncludeQueryMetadataChanges:_includeQueryMetadataChanges
  73. includeDocumentMetadataChanges:includeDocumentMetadataChanges];
  74. }
  75. @end
  76. @interface FIRQuery ()
  77. @property(nonatomic, strong, readonly) FSTQuery *query;
  78. @end
  79. @implementation FIRQuery (Internal)
  80. + (instancetype)referenceWithQuery:(FSTQuery *)query firestore:(FIRFirestore *)firestore {
  81. return [[FIRQuery alloc] initWithQuery:query firestore:firestore];
  82. }
  83. @end
  84. @implementation FIRQuery
  85. #pragma mark - Constructor Methods
  86. - (instancetype)initWithQuery:(FSTQuery *)query firestore:(FIRFirestore *)firestore {
  87. if (self = [super init]) {
  88. _query = query;
  89. _firestore = firestore;
  90. }
  91. return self;
  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. return [self isEqualToQuery:other];
  98. }
  99. - (BOOL)isEqualToQuery:(nullable FIRQuery *)query {
  100. if (self == query) return YES;
  101. if (query == nil) return NO;
  102. return [self.firestore isEqual:query.firestore] && [self.query isEqual:query.query];
  103. }
  104. - (NSUInteger)hash {
  105. NSUInteger hash = [self.firestore hash];
  106. hash = hash * 31u + [self.query hash];
  107. return hash;
  108. }
  109. #pragma mark - Public Methods
  110. - (void)getDocumentsWithCompletion:(void (^)(FIRQuerySnapshot *_Nullable snapshot,
  111. NSError *_Nullable error))completion {
  112. FSTListenOptions *options = [[FSTListenOptions alloc] initWithIncludeQueryMetadataChanges:YES
  113. includeDocumentMetadataChanges:YES
  114. waitForSyncWhenOnline:YES];
  115. dispatch_semaphore_t registered = dispatch_semaphore_create(0);
  116. __block id<FIRListenerRegistration> listenerRegistration;
  117. FIRQuerySnapshotBlock listener = ^(FIRQuerySnapshot *snapshot, NSError *error) {
  118. if (error) {
  119. completion(nil, error);
  120. return;
  121. }
  122. // Remove query first before passing event to user to avoid user actions affecting the
  123. // now stale query.
  124. dispatch_semaphore_wait(registered, DISPATCH_TIME_FOREVER);
  125. [listenerRegistration remove];
  126. completion(snapshot, nil);
  127. };
  128. listenerRegistration = [self addSnapshotListenerInternalWithOptions:options listener:listener];
  129. dispatch_semaphore_signal(registered);
  130. }
  131. - (id<FIRListenerRegistration>)addSnapshotListener:(FIRQuerySnapshotBlock)listener {
  132. return [self addSnapshotListenerWithOptions:nil listener:listener];
  133. }
  134. - (id<FIRListenerRegistration>)addSnapshotListenerWithOptions:
  135. (nullable FIRQueryListenOptions *)options
  136. listener:(FIRQuerySnapshotBlock)listener {
  137. return [self addSnapshotListenerInternalWithOptions:[self internalOptions:options]
  138. listener:listener];
  139. }
  140. - (id<FIRListenerRegistration>)
  141. addSnapshotListenerInternalWithOptions:(FSTListenOptions *)internalOptions
  142. listener:(FIRQuerySnapshotBlock)listener {
  143. FIRFirestore *firestore = self.firestore;
  144. FSTQuery *query = self.query;
  145. FSTViewSnapshotHandler snapshotHandler = ^(FSTViewSnapshot *snapshot, NSError *error) {
  146. if (error) {
  147. listener(nil, error);
  148. return;
  149. }
  150. FIRSnapshotMetadata *metadata =
  151. [FIRSnapshotMetadata snapshotMetadataWithPendingWrites:snapshot.hasPendingWrites
  152. fromCache:snapshot.fromCache];
  153. listener([FIRQuerySnapshot snapshotWithFirestore:firestore
  154. originalQuery:query
  155. snapshot:snapshot
  156. metadata:metadata],
  157. nil);
  158. };
  159. FSTAsyncQueryListener *asyncListener =
  160. [[FSTAsyncQueryListener alloc] initWithDispatchQueue:self.firestore.client.userDispatchQueue
  161. snapshotHandler:snapshotHandler];
  162. FSTQueryListener *internalListener =
  163. [firestore.client listenToQuery:query
  164. options:internalOptions
  165. viewSnapshotHandler:[asyncListener asyncSnapshotHandler]];
  166. return [[FSTListenerRegistration alloc] initWithClient:self.firestore.client
  167. asyncListener:asyncListener
  168. internalListener:internalListener];
  169. }
  170. - (FIRQuery *)queryWhereField:(NSString *)field isEqualTo:(id)value {
  171. return [self queryWithFilterOperator:FSTRelationFilterOperatorEqual field:field value:value];
  172. }
  173. - (FIRQuery *)queryWhereFieldPath:(FIRFieldPath *)path isEqualTo:(id)value {
  174. return [self queryWithFilterOperator:FSTRelationFilterOperatorEqual
  175. path:path.internalValue
  176. value:value];
  177. }
  178. - (FIRQuery *)queryWhereField:(NSString *)field isLessThan:(id)value {
  179. return [self queryWithFilterOperator:FSTRelationFilterOperatorLessThan field:field value:value];
  180. }
  181. - (FIRQuery *)queryWhereFieldPath:(FIRFieldPath *)path isLessThan:(id)value {
  182. return [self queryWithFilterOperator:FSTRelationFilterOperatorLessThan
  183. path:path.internalValue
  184. value:value];
  185. }
  186. - (FIRQuery *)queryWhereField:(NSString *)field isLessThanOrEqualTo:(id)value {
  187. return [self queryWithFilterOperator:FSTRelationFilterOperatorLessThanOrEqual
  188. field:field
  189. value:value];
  190. }
  191. - (FIRQuery *)queryWhereFieldPath:(FIRFieldPath *)path isLessThanOrEqualTo:(id)value {
  192. return [self queryWithFilterOperator:FSTRelationFilterOperatorLessThanOrEqual
  193. path:path.internalValue
  194. value:value];
  195. }
  196. - (FIRQuery *)queryWhereField:(NSString *)field isGreaterThan:(id)value {
  197. return
  198. [self queryWithFilterOperator:FSTRelationFilterOperatorGreaterThan field:field value:value];
  199. }
  200. - (FIRQuery *)queryWhereFieldPath:(FIRFieldPath *)path isGreaterThan:(id)value {
  201. return [self queryWithFilterOperator:FSTRelationFilterOperatorGreaterThan
  202. path:path.internalValue
  203. value:value];
  204. }
  205. - (FIRQuery *)queryWhereField:(NSString *)field isGreaterThanOrEqualTo:(id)value {
  206. return [self queryWithFilterOperator:FSTRelationFilterOperatorGreaterThanOrEqual
  207. field:field
  208. value:value];
  209. }
  210. - (FIRQuery *)queryWhereFieldPath:(FIRFieldPath *)path isGreaterThanOrEqualTo:(id)value {
  211. return [self queryWithFilterOperator:FSTRelationFilterOperatorGreaterThanOrEqual
  212. path:path.internalValue
  213. value:value];
  214. }
  215. - (FIRQuery *)queryFilteredUsingComparisonPredicate:(NSPredicate *)predicate {
  216. NSComparisonPredicate *comparison = (NSComparisonPredicate *)predicate;
  217. if (comparison.comparisonPredicateModifier != NSDirectPredicateModifier) {
  218. FSTThrowInvalidArgument(@"Invalid query. Predicate cannot have an aggregate modifier.");
  219. }
  220. NSString *path;
  221. id value = nil;
  222. if ([comparison.leftExpression expressionType] == NSKeyPathExpressionType &&
  223. [comparison.rightExpression expressionType] == NSConstantValueExpressionType) {
  224. path = comparison.leftExpression.keyPath;
  225. value = comparison.rightExpression.constantValue;
  226. switch (comparison.predicateOperatorType) {
  227. case NSEqualToPredicateOperatorType:
  228. return [self queryWhereField:path isEqualTo:value];
  229. case NSLessThanPredicateOperatorType:
  230. return [self queryWhereField:path isLessThan:value];
  231. case NSLessThanOrEqualToPredicateOperatorType:
  232. return [self queryWhereField:path isLessThanOrEqualTo:value];
  233. case NSGreaterThanPredicateOperatorType:
  234. return [self queryWhereField:path isGreaterThan:value];
  235. case NSGreaterThanOrEqualToPredicateOperatorType:
  236. return [self queryWhereField:path isGreaterThanOrEqualTo:value];
  237. default:; // Fallback below to throw assertion.
  238. }
  239. } else if ([comparison.leftExpression expressionType] == NSConstantValueExpressionType &&
  240. [comparison.rightExpression expressionType] == NSKeyPathExpressionType) {
  241. path = comparison.rightExpression.keyPath;
  242. value = comparison.leftExpression.constantValue;
  243. switch (comparison.predicateOperatorType) {
  244. case NSEqualToPredicateOperatorType:
  245. return [self queryWhereField:path isEqualTo:value];
  246. case NSLessThanPredicateOperatorType:
  247. return [self queryWhereField:path isGreaterThan:value];
  248. case NSLessThanOrEqualToPredicateOperatorType:
  249. return [self queryWhereField:path isGreaterThanOrEqualTo:value];
  250. case NSGreaterThanPredicateOperatorType:
  251. return [self queryWhereField:path isLessThan:value];
  252. case NSGreaterThanOrEqualToPredicateOperatorType:
  253. return [self queryWhereField:path isLessThanOrEqualTo:value];
  254. default:; // Fallback below to throw assertion.
  255. }
  256. } else {
  257. FSTThrowInvalidArgument(
  258. @"Invalid query. Predicate comparisons must include a key path and a constant.");
  259. }
  260. // Fallback cases of unsupported comparison operator.
  261. switch (comparison.predicateOperatorType) {
  262. case NSCustomSelectorPredicateOperatorType:
  263. FSTThrowInvalidArgument(@"Invalid query. Custom predicate filters are not supported.");
  264. break;
  265. default:
  266. FSTThrowInvalidArgument(@"Invalid query. Operator type %lu is not supported.",
  267. (unsigned long)comparison.predicateOperatorType);
  268. }
  269. }
  270. - (FIRQuery *)queryFilteredUsingCompoundPredicate:(NSPredicate *)predicate {
  271. NSCompoundPredicate *compound = (NSCompoundPredicate *)predicate;
  272. if (compound.compoundPredicateType != NSAndPredicateType || compound.subpredicates.count == 0) {
  273. FSTThrowInvalidArgument(@"Invalid query. Only compound queries using AND are supported.");
  274. }
  275. FIRQuery *query = self;
  276. for (NSPredicate *pred in compound.subpredicates) {
  277. query = [query queryFilteredUsingPredicate:pred];
  278. }
  279. return query;
  280. }
  281. - (FIRQuery *)queryFilteredUsingPredicate:(NSPredicate *)predicate {
  282. if ([predicate isKindOfClass:[NSComparisonPredicate class]]) {
  283. return [self queryFilteredUsingComparisonPredicate:predicate];
  284. } else if ([predicate isKindOfClass:[NSCompoundPredicate class]]) {
  285. return [self queryFilteredUsingCompoundPredicate:predicate];
  286. } else if ([predicate isKindOfClass:[[NSPredicate
  287. predicateWithBlock:^BOOL(id obj, NSDictionary *bindings) {
  288. return true;
  289. }] class]]) {
  290. FSTThrowInvalidArgument(
  291. @"Invalid query. Block-based predicates are not "
  292. "supported. Please use predicateWithFormat to "
  293. "create predicates instead.");
  294. } else {
  295. FSTThrowInvalidArgument(
  296. @"Invalid query. Expect comparison or compound of "
  297. "comparison predicate. Please use "
  298. "predicateWithFormat to create predicates.");
  299. }
  300. }
  301. - (FIRQuery *)queryOrderedByField:(NSString *)field {
  302. return
  303. [self queryOrderedByFieldPath:[FIRFieldPath pathWithDotSeparatedString:field] descending:NO];
  304. }
  305. - (FIRQuery *)queryOrderedByFieldPath:(FIRFieldPath *)fieldPath {
  306. return [self queryOrderedByFieldPath:fieldPath descending:NO];
  307. }
  308. - (FIRQuery *)queryOrderedByField:(NSString *)field descending:(BOOL)descending {
  309. return [self queryOrderedByFieldPath:[FIRFieldPath pathWithDotSeparatedString:field]
  310. descending:descending];
  311. }
  312. - (FIRQuery *)queryOrderedByFieldPath:(FIRFieldPath *)fieldPath descending:(BOOL)descending {
  313. [self validateNewOrderByPath:fieldPath.internalValue];
  314. if (self.query.startAt) {
  315. FSTThrowInvalidUsage(
  316. @"InvalidQueryException",
  317. @"Invalid query. You must not specify a starting point before specifying the order by.");
  318. }
  319. if (self.query.endAt) {
  320. FSTThrowInvalidUsage(
  321. @"InvalidQueryException",
  322. @"Invalid query. You must not specify an ending point before specifying the order by.");
  323. }
  324. FSTSortOrder *sortOrder =
  325. [FSTSortOrder sortOrderWithFieldPath:fieldPath.internalValue ascending:!descending];
  326. return [FIRQuery referenceWithQuery:[self.query queryByAddingSortOrder:sortOrder]
  327. firestore:self.firestore];
  328. }
  329. - (FIRQuery *)queryLimitedTo:(NSInteger)limit {
  330. if (limit <= 0) {
  331. FSTThrowInvalidArgument(@"Invalid Query. Query limit (%ld) is invalid. Limit must be positive.",
  332. (long)limit);
  333. }
  334. return [FIRQuery referenceWithQuery:[self.query queryBySettingLimit:limit] firestore:_firestore];
  335. }
  336. - (FIRQuery *)queryStartingAtDocument:(FIRDocumentSnapshot *)snapshot {
  337. FSTBound *bound = [self boundFromSnapshot:snapshot isBefore:YES];
  338. return [FIRQuery referenceWithQuery:[self.query queryByAddingStartAt:bound]
  339. firestore:self.firestore];
  340. }
  341. - (FIRQuery *)queryStartingAtValues:(NSArray *)fieldValues {
  342. FSTBound *bound = [self boundFromFieldValues:fieldValues isBefore:YES];
  343. return [FIRQuery referenceWithQuery:[self.query queryByAddingStartAt:bound]
  344. firestore:self.firestore];
  345. }
  346. - (FIRQuery *)queryStartingAfterDocument:(FIRDocumentSnapshot *)snapshot {
  347. FSTBound *bound = [self boundFromSnapshot:snapshot isBefore:NO];
  348. return [FIRQuery referenceWithQuery:[self.query queryByAddingStartAt:bound]
  349. firestore:self.firestore];
  350. }
  351. - (FIRQuery *)queryStartingAfterValues:(NSArray *)fieldValues {
  352. FSTBound *bound = [self boundFromFieldValues:fieldValues isBefore:NO];
  353. return [FIRQuery referenceWithQuery:[self.query queryByAddingStartAt:bound]
  354. firestore:self.firestore];
  355. }
  356. - (FIRQuery *)queryEndingBeforeDocument:(FIRDocumentSnapshot *)snapshot {
  357. FSTBound *bound = [self boundFromSnapshot:snapshot isBefore:YES];
  358. return
  359. [FIRQuery referenceWithQuery:[self.query queryByAddingEndAt:bound] firestore:self.firestore];
  360. }
  361. - (FIRQuery *)queryEndingBeforeValues:(NSArray *)fieldValues {
  362. FSTBound *bound = [self boundFromFieldValues:fieldValues isBefore:YES];
  363. return
  364. [FIRQuery referenceWithQuery:[self.query queryByAddingEndAt:bound] firestore:self.firestore];
  365. }
  366. - (FIRQuery *)queryEndingAtDocument:(FIRDocumentSnapshot *)snapshot {
  367. FSTBound *bound = [self boundFromSnapshot:snapshot isBefore:NO];
  368. return
  369. [FIRQuery referenceWithQuery:[self.query queryByAddingEndAt:bound] firestore:self.firestore];
  370. }
  371. - (FIRQuery *)queryEndingAtValues:(NSArray *)fieldValues {
  372. FSTBound *bound = [self boundFromFieldValues:fieldValues isBefore:NO];
  373. return
  374. [FIRQuery referenceWithQuery:[self.query queryByAddingEndAt:bound] firestore:self.firestore];
  375. }
  376. #pragma mark - Private Methods
  377. /** Private helper for all of the queryWhereField: methods. */
  378. - (FIRQuery *)queryWithFilterOperator:(FSTRelationFilterOperator)filterOperator
  379. field:(NSString *)field
  380. value:(id)value {
  381. return [self queryWithFilterOperator:filterOperator
  382. path:[FIRFieldPath pathWithDotSeparatedString:field].internalValue
  383. value:value];
  384. }
  385. - (FIRQuery *)queryWithFilterOperator:(FSTRelationFilterOperator)filterOperator
  386. path:(const FieldPath &)fieldPath
  387. value:(id)value {
  388. FSTFieldValue *fieldValue;
  389. if (fieldPath.IsKeyFieldPath()) {
  390. if ([value isKindOfClass:[NSString class]]) {
  391. NSString *documentKey = (NSString *)value;
  392. if ([documentKey containsString:@"/"]) {
  393. FSTThrowInvalidArgument(
  394. @"Invalid query. When querying by document ID you must provide "
  395. "a valid document ID, but '%@' contains a '/' character.",
  396. documentKey);
  397. } else if (documentKey.length == 0) {
  398. FSTThrowInvalidArgument(
  399. @"Invalid query. When querying by document ID you must provide "
  400. "a valid document ID, but it was an empty string.");
  401. }
  402. ResourcePath path = self.query.path.Append([documentKey UTF8String]);
  403. fieldValue =
  404. [FSTReferenceValue referenceValue:DocumentKey{path} databaseID:self.firestore.databaseID];
  405. } else if ([value isKindOfClass:[FIRDocumentReference class]]) {
  406. FIRDocumentReference *ref = (FIRDocumentReference *)value;
  407. fieldValue = [FSTReferenceValue referenceValue:ref.key databaseID:self.firestore.databaseID];
  408. } else {
  409. FSTThrowInvalidArgument(
  410. @"Invalid query. When querying by document ID you must provide a "
  411. "valid string or DocumentReference, but it was of type: %@",
  412. NSStringFromClass([value class]));
  413. }
  414. } else {
  415. fieldValue = [self.firestore.dataConverter parsedQueryValue:value];
  416. }
  417. id<FSTFilter> filter;
  418. if ([fieldValue isEqual:[FSTNullValue nullValue]]) {
  419. if (filterOperator != FSTRelationFilterOperatorEqual) {
  420. FSTThrowInvalidUsage(@"InvalidQueryException",
  421. @"Invalid Query. You can only perform equality comparisons on nil / "
  422. "NSNull.");
  423. }
  424. filter = [[FSTNullFilter alloc] initWithField:fieldPath];
  425. } else if ([fieldValue isEqual:[FSTDoubleValue nanValue]]) {
  426. if (filterOperator != FSTRelationFilterOperatorEqual) {
  427. FSTThrowInvalidUsage(@"InvalidQueryException",
  428. @"Invalid Query. You can only perform equality comparisons on NaN.");
  429. }
  430. filter = [[FSTNanFilter alloc] initWithField:fieldPath];
  431. } else {
  432. filter = [FSTRelationFilter filterWithField:fieldPath
  433. filterOperator:filterOperator
  434. value:fieldValue];
  435. [self validateNewRelationFilter:filter];
  436. }
  437. return [FIRQuery referenceWithQuery:[self.query queryByAddingFilter:filter]
  438. firestore:self.firestore];
  439. }
  440. - (void)validateNewRelationFilter:(FSTRelationFilter *)filter {
  441. if ([filter isInequality]) {
  442. const FieldPath *existingField = [self.query inequalityFilterField];
  443. if (existingField && *existingField != filter.field) {
  444. FSTThrowInvalidUsage(
  445. @"InvalidQueryException",
  446. @"Invalid Query. All where filters with an inequality "
  447. "(lessThan, lessThanOrEqual, greaterThan, or greaterThanOrEqual) must be on the same "
  448. "field. But you have inequality filters on '%s' and '%s'",
  449. existingField->CanonicalString().c_str(), filter.field.CanonicalString().c_str());
  450. }
  451. const FieldPath *firstOrderByField = [self.query firstSortOrderField];
  452. if (firstOrderByField) {
  453. [self validateOrderByField:*firstOrderByField matchesInequalityField:filter.field];
  454. }
  455. }
  456. }
  457. - (void)validateNewOrderByPath:(const FieldPath &)fieldPath {
  458. if (![self.query firstSortOrderField]) {
  459. // This is the first order by. It must match any inequality.
  460. const FieldPath *inequalityField = [self.query inequalityFilterField];
  461. if (inequalityField) {
  462. [self validateOrderByField:fieldPath matchesInequalityField:*inequalityField];
  463. }
  464. }
  465. }
  466. - (void)validateOrderByField:(const FieldPath &)orderByField
  467. matchesInequalityField:(const FieldPath &)inequalityField {
  468. if (orderByField != inequalityField) {
  469. FSTThrowInvalidUsage(
  470. @"InvalidQueryException",
  471. @"Invalid query. You have a where filter with an "
  472. "inequality (lessThan, lessThanOrEqual, greaterThan, or greaterThanOrEqual) on field '%s' "
  473. "and so you must also use '%s' as your first queryOrderedBy field, but your first "
  474. "queryOrderedBy is currently on field '%s' instead.",
  475. inequalityField.CanonicalString().c_str(), inequalityField.CanonicalString().c_str(),
  476. orderByField.CanonicalString().c_str());
  477. }
  478. }
  479. /**
  480. * Create a FSTBound from a query given the document.
  481. *
  482. * Note that the FSTBound will always include the key of the document and the position will be
  483. * unambiguous.
  484. *
  485. * Will throw if the document does not contain all fields of the order by of the query.
  486. */
  487. - (FSTBound *)boundFromSnapshot:(FIRDocumentSnapshot *)snapshot isBefore:(BOOL)isBefore {
  488. if (![snapshot exists]) {
  489. FSTThrowInvalidUsage(@"InvalidQueryException",
  490. @"Invalid query. You are trying to start or end a query using a document "
  491. @"that doesn't exist.");
  492. }
  493. FSTDocument *document = snapshot.internalDocument;
  494. NSMutableArray<FSTFieldValue *> *components = [NSMutableArray array];
  495. // Because people expect to continue/end a query at the exact document provided, we need to
  496. // use the implicit sort order rather than the explicit sort order, because it's guaranteed to
  497. // contain the document key. That way the position becomes unambiguous and the query
  498. // continues/ends exactly at the provided document. Without the key (by using the explicit sort
  499. // orders), multiple documents could match the position, yielding duplicate results.
  500. for (FSTSortOrder *sortOrder in self.query.sortOrders) {
  501. if (sortOrder.field == FieldPath::KeyFieldPath()) {
  502. [components addObject:[FSTReferenceValue referenceValue:document.key
  503. databaseID:self.firestore.databaseID]];
  504. } else {
  505. FSTFieldValue *value = [document fieldForPath:sortOrder.field];
  506. if (value != nil) {
  507. [components addObject:value];
  508. } else {
  509. FSTThrowInvalidUsage(@"InvalidQueryException",
  510. @"Invalid query. You are trying to start or end a query using a "
  511. "document for which the field '%s' (used as the order by) "
  512. "does not exist.",
  513. sortOrder.field.CanonicalString().c_str());
  514. }
  515. }
  516. }
  517. return [FSTBound boundWithPosition:components isBefore:isBefore];
  518. }
  519. /** Converts a list of field values to an FSTBound. */
  520. - (FSTBound *)boundFromFieldValues:(NSArray<id> *)fieldValues isBefore:(BOOL)isBefore {
  521. // Use explicit sort order because it has to match the query the user made
  522. NSArray<FSTSortOrder *> *explicitSortOrders = self.query.explicitSortOrders;
  523. if (fieldValues.count > explicitSortOrders.count) {
  524. FSTThrowInvalidUsage(@"InvalidQueryException",
  525. @"Invalid query. You are trying to start or end a query using more values "
  526. @"than were specified in the order by.");
  527. }
  528. NSMutableArray<FSTFieldValue *> *components = [NSMutableArray array];
  529. [fieldValues enumerateObjectsUsingBlock:^(id rawValue, NSUInteger idx, BOOL *stop) {
  530. FSTSortOrder *sortOrder = explicitSortOrders[idx];
  531. if (sortOrder.field == FieldPath::KeyFieldPath()) {
  532. if (![rawValue isKindOfClass:[NSString class]]) {
  533. FSTThrowInvalidUsage(@"InvalidQueryException",
  534. @"Invalid query. Expected a string for the document ID.");
  535. }
  536. NSString *documentID = (NSString *)rawValue;
  537. if ([documentID containsString:@"/"]) {
  538. FSTThrowInvalidUsage(@"InvalidQueryException",
  539. @"Invalid query. Document ID '%@' contains a slash.", documentID);
  540. }
  541. const DocumentKey key{self.query.path.Append([documentID UTF8String])};
  542. [components
  543. addObject:[FSTReferenceValue referenceValue:key databaseID:self.firestore.databaseID]];
  544. } else {
  545. FSTFieldValue *fieldValue = [self.firestore.dataConverter parsedQueryValue:rawValue];
  546. [components addObject:fieldValue];
  547. }
  548. }];
  549. return [FSTBound boundWithPosition:components isBefore:isBefore];
  550. }
  551. /** Converts the public API options object to the internal options object. */
  552. - (FSTListenOptions *)internalOptions:(nullable FIRQueryListenOptions *)options {
  553. return [[FSTListenOptions alloc]
  554. initWithIncludeQueryMetadataChanges:options.includeQueryMetadataChanges
  555. includeDocumentMetadataChanges:options.includeDocumentMetadataChanges
  556. waitForSyncWhenOnline:NO];
  557. }
  558. @end
  559. NS_ASSUME_NONNULL_END