FIRQuery.mm 30 KB

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