FIRQuery.mm 28 KB

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