FSTQuery.mm 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817
  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 "Firestore/Source/Core/FSTQuery.h"
  17. #include <memory>
  18. #include <utility>
  19. #import "Firestore/Source/API/FIRFirestore+Internal.h"
  20. #import "Firestore/Source/Model/FSTDocument.h"
  21. #import "Firestore/Source/Model/FSTFieldValue.h"
  22. #import "Firestore/Source/Util/FSTAssert.h"
  23. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  24. #include "Firestore/core/src/firebase/firestore/model/field_path.h"
  25. #include "Firestore/core/src/firebase/firestore/model/resource_path.h"
  26. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  27. namespace util = firebase::firestore::util;
  28. using firebase::firestore::model::DocumentKey;
  29. using firebase::firestore::model::FieldPath;
  30. using firebase::firestore::model::ResourcePath;
  31. NS_ASSUME_NONNULL_BEGIN
  32. #pragma mark - FSTRelationFilterOperator functions
  33. /**
  34. * Returns the reverse order (i.e. Ascending => Descending) etc.
  35. */
  36. static constexpr NSComparisonResult ReverseOrder(NSComparisonResult result) {
  37. return static_cast<NSComparisonResult>(-static_cast<NSInteger>(result));
  38. }
  39. NSString *FSTStringFromQueryRelationOperator(FSTRelationFilterOperator filterOperator) {
  40. switch (filterOperator) {
  41. case FSTRelationFilterOperatorLessThan:
  42. return @"<";
  43. case FSTRelationFilterOperatorLessThanOrEqual:
  44. return @"<=";
  45. case FSTRelationFilterOperatorEqual:
  46. return @"==";
  47. case FSTRelationFilterOperatorGreaterThanOrEqual:
  48. return @">=";
  49. case FSTRelationFilterOperatorGreaterThan:
  50. return @">";
  51. default:
  52. FSTCFail(@"Unknown FSTRelationFilterOperator %lu", (unsigned long)filterOperator);
  53. }
  54. }
  55. #pragma mark - FSTRelationFilter
  56. @interface FSTRelationFilter () {
  57. /** The left hand side of the relation. A path into a document field. */
  58. firebase::firestore::model::FieldPath _field;
  59. }
  60. /**
  61. * Initializes the receiver relation filter.
  62. *
  63. * @param field A path to a field in the document to filter on. The LHS of the expression.
  64. * @param filterOperator The binary operator to apply.
  65. * @param value A constant value to compare @a field to. The RHS of the expression.
  66. */
  67. - (instancetype)initWithField:(FieldPath)field
  68. filterOperator:(FSTRelationFilterOperator)filterOperator
  69. value:(FSTFieldValue *)value NS_DESIGNATED_INITIALIZER;
  70. /** Returns YES if @a document matches the receiver's constraint. */
  71. - (BOOL)matchesDocument:(FSTDocument *)document;
  72. /**
  73. * A canonical string identifying the filter. Two different instances of equivalent filters will
  74. * return the same canonicalID.
  75. */
  76. - (NSString *)canonicalID;
  77. @end
  78. @implementation FSTRelationFilter
  79. #pragma mark - Constructor methods
  80. + (instancetype)filterWithField:(FieldPath)field
  81. filterOperator:(FSTRelationFilterOperator)filterOperator
  82. value:(FSTFieldValue *)value {
  83. return [[FSTRelationFilter alloc] initWithField:std::move(field)
  84. filterOperator:filterOperator
  85. value:value];
  86. }
  87. - (instancetype)initWithField:(FieldPath)field
  88. filterOperator:(FSTRelationFilterOperator)filterOperator
  89. value:(FSTFieldValue *)value {
  90. self = [super init];
  91. if (self) {
  92. _field = std::move(field);
  93. _filterOperator = filterOperator;
  94. _value = value;
  95. }
  96. return self;
  97. }
  98. #pragma mark - Public Methods
  99. - (BOOL)isInequality {
  100. return self.filterOperator != FSTRelationFilterOperatorEqual;
  101. }
  102. - (const firebase::firestore::model::FieldPath &)field {
  103. return _field;
  104. }
  105. #pragma mark - NSObject methods
  106. - (NSString *)description {
  107. return [NSString stringWithFormat:@"%s %@ %@", _field.CanonicalString().c_str(),
  108. FSTStringFromQueryRelationOperator(self.filterOperator),
  109. self.value];
  110. }
  111. - (BOOL)isEqual:(id)other {
  112. if (self == other) {
  113. return YES;
  114. }
  115. if (![other isKindOfClass:[FSTRelationFilter class]]) {
  116. return NO;
  117. }
  118. return [self isEqualToFilter:(FSTRelationFilter *)other];
  119. }
  120. #pragma mark - Private methods
  121. - (BOOL)matchesDocument:(FSTDocument *)document {
  122. if (_field.IsKeyFieldPath()) {
  123. FSTAssert([self.value isKindOfClass:[FSTReferenceValue class]],
  124. @"Comparing on key, but filter value not a FSTReferenceValue.");
  125. FSTReferenceValue *refValue = (FSTReferenceValue *)self.value;
  126. NSComparisonResult comparison = FSTDocumentKeyComparator(document.key, refValue.value);
  127. return [self matchesComparison:comparison];
  128. } else {
  129. return [self matchesValue:[document fieldForPath:self.field]];
  130. }
  131. }
  132. - (NSString *)canonicalID {
  133. // TODO(b/37283291): This should be collision robust and avoid relying on |description| methods.
  134. return [NSString stringWithFormat:@"%s%@%@", _field.CanonicalString().c_str(),
  135. FSTStringFromQueryRelationOperator(self.filterOperator),
  136. [self.value value]];
  137. }
  138. - (BOOL)isEqualToFilter:(FSTRelationFilter *)other {
  139. if (self.filterOperator != other.filterOperator) {
  140. return NO;
  141. }
  142. if (_field != other.field) {
  143. return NO;
  144. }
  145. if (![self.value isEqual:other.value]) {
  146. return NO;
  147. }
  148. return YES;
  149. }
  150. /** Returns YES if receiver is true with the given value as its LHS. */
  151. - (BOOL)matchesValue:(FSTFieldValue *)other {
  152. // Only compare types with matching backend order (such as double and int).
  153. return self.value.typeOrder == other.typeOrder &&
  154. [self matchesComparison:[other compare:self.value]];
  155. }
  156. - (BOOL)matchesComparison:(NSComparisonResult)comparison {
  157. switch (self.filterOperator) {
  158. case FSTRelationFilterOperatorLessThan:
  159. return comparison == NSOrderedAscending;
  160. case FSTRelationFilterOperatorLessThanOrEqual:
  161. return comparison == NSOrderedAscending || comparison == NSOrderedSame;
  162. case FSTRelationFilterOperatorEqual:
  163. return comparison == NSOrderedSame;
  164. case FSTRelationFilterOperatorGreaterThanOrEqual:
  165. return comparison == NSOrderedDescending || comparison == NSOrderedSame;
  166. case FSTRelationFilterOperatorGreaterThan:
  167. return comparison == NSOrderedDescending;
  168. default:
  169. FSTFail(@"Unknown operator: %ld", (long)self.filterOperator);
  170. }
  171. }
  172. @end
  173. #pragma mark - FSTNullFilter
  174. @interface FSTNullFilter () {
  175. FieldPath _field;
  176. }
  177. @end
  178. @implementation FSTNullFilter
  179. - (instancetype)initWithField:(FieldPath)field {
  180. if (self = [super init]) {
  181. _field = std::move(field);
  182. }
  183. return self;
  184. }
  185. - (BOOL)matchesDocument:(FSTDocument *)document {
  186. FSTFieldValue *fieldValue = [document fieldForPath:self.field];
  187. return fieldValue != nil && [fieldValue isEqual:[FSTNullValue nullValue]];
  188. }
  189. - (NSString *)canonicalID {
  190. return [NSString stringWithFormat:@"%s IS NULL", _field.CanonicalString().c_str()];
  191. }
  192. - (const firebase::firestore::model::FieldPath &)field {
  193. return _field;
  194. }
  195. - (NSString *)description {
  196. return [self canonicalID];
  197. }
  198. - (BOOL)isEqual:(id)other {
  199. if (other == self) return YES;
  200. if (![[other class] isEqual:[self class]]) return NO;
  201. return _field == ((FSTNullFilter *)other)->_field;
  202. }
  203. - (NSUInteger)hash {
  204. return _field.Hash();
  205. }
  206. @end
  207. #pragma mark - FSTNanFilter
  208. @interface FSTNanFilter () {
  209. FieldPath _field;
  210. }
  211. @end
  212. @implementation FSTNanFilter
  213. - (instancetype)initWithField:(FieldPath)field {
  214. if (self = [super init]) {
  215. _field = std::move(field);
  216. }
  217. return self;
  218. }
  219. - (BOOL)matchesDocument:(FSTDocument *)document {
  220. FSTFieldValue *fieldValue = [document fieldForPath:self.field];
  221. return fieldValue != nil && [fieldValue isEqual:[FSTDoubleValue nanValue]];
  222. }
  223. - (NSString *)canonicalID {
  224. return [NSString stringWithFormat:@"%s IS NaN", _field.CanonicalString().c_str()];
  225. }
  226. - (const firebase::firestore::model::FieldPath &)field {
  227. return _field;
  228. }
  229. - (NSString *)description {
  230. return [self canonicalID];
  231. }
  232. - (BOOL)isEqual:(id)other {
  233. if (other == self) return YES;
  234. if (![[other class] isEqual:[self class]]) return NO;
  235. return _field == ((FSTNanFilter *)other)->_field;
  236. }
  237. - (NSUInteger)hash {
  238. return _field.Hash();
  239. }
  240. @end
  241. #pragma mark - FSTSortOrder
  242. @interface FSTSortOrder () {
  243. /** The field to sort by. */
  244. firebase::firestore::model::FieldPath _field;
  245. }
  246. /** Creates a new sort order with the given field and direction. */
  247. - (instancetype)initWithFieldPath:(FieldPath)fieldPath ascending:(BOOL)ascending;
  248. - (NSString *)canonicalID;
  249. @end
  250. @implementation FSTSortOrder
  251. #pragma mark - Constructor methods
  252. + (instancetype)sortOrderWithFieldPath:(FieldPath)fieldPath ascending:(BOOL)ascending {
  253. return [[FSTSortOrder alloc] initWithFieldPath:std::move(fieldPath) ascending:ascending];
  254. }
  255. - (instancetype)initWithFieldPath:(FieldPath)fieldPath ascending:(BOOL)ascending {
  256. self = [super init];
  257. if (self) {
  258. _field = std::move(fieldPath);
  259. _ascending = ascending;
  260. }
  261. return self;
  262. }
  263. - (const firebase::firestore::model::FieldPath &)field {
  264. return _field;
  265. }
  266. #pragma mark - Public methods
  267. - (NSComparisonResult)compareDocument:(FSTDocument *)document1 toDocument:(FSTDocument *)document2 {
  268. NSComparisonResult result;
  269. if (_field == FieldPath::KeyFieldPath()) {
  270. result = FSTDocumentKeyComparator(document1.key, document2.key);
  271. } else {
  272. FSTFieldValue *value1 = [document1 fieldForPath:self.field];
  273. FSTFieldValue *value2 = [document2 fieldForPath:self.field];
  274. FSTAssert(value1 != nil && value2 != nil,
  275. @"Trying to compare documents on fields that don't exist.");
  276. result = [value1 compare:value2];
  277. }
  278. if (!self.isAscending) {
  279. result = ReverseOrder(result);
  280. }
  281. return result;
  282. }
  283. - (NSString *)canonicalID {
  284. return [NSString stringWithFormat:@"%s%@", _field.CanonicalString().c_str(),
  285. self.isAscending ? @"asc" : @"desc"];
  286. }
  287. - (BOOL)isEqualToSortOrder:(FSTSortOrder *)other {
  288. return _field == other->_field && self.isAscending == other.isAscending;
  289. }
  290. #pragma mark - NSObject methods
  291. - (NSString *)description {
  292. return [NSString stringWithFormat:@"<FSTSortOrder: path:%s dir:%@>",
  293. _field.CanonicalString().c_str(),
  294. self.ascending ? @"asc" : @"desc"];
  295. }
  296. - (BOOL)isEqual:(NSObject *)other {
  297. if (self == other) {
  298. return YES;
  299. }
  300. if (![other isKindOfClass:[FSTSortOrder class]]) {
  301. return NO;
  302. }
  303. return [self isEqualToSortOrder:(FSTSortOrder *)other];
  304. }
  305. - (NSUInteger)hash {
  306. return [self.canonicalID hash];
  307. }
  308. - (instancetype)copyWithZone:(nullable NSZone *)zone {
  309. return self;
  310. }
  311. @end
  312. #pragma mark - FSTBound
  313. @implementation FSTBound
  314. - (instancetype)initWithPosition:(NSArray<FSTFieldValue *> *)position isBefore:(BOOL)isBefore {
  315. if (self = [super init]) {
  316. _position = position;
  317. _before = isBefore;
  318. }
  319. return self;
  320. }
  321. + (instancetype)boundWithPosition:(NSArray<FSTFieldValue *> *)position isBefore:(BOOL)isBefore {
  322. return [[FSTBound alloc] initWithPosition:position isBefore:isBefore];
  323. }
  324. - (NSString *)canonicalString {
  325. // TODO(b/29183165): Make this collision robust.
  326. NSMutableString *string = [NSMutableString string];
  327. if (self.isBefore) {
  328. [string appendString:@"b:"];
  329. } else {
  330. [string appendString:@"a:"];
  331. }
  332. for (FSTFieldValue *component in self.position) {
  333. [string appendFormat:@"%@", component];
  334. }
  335. return string;
  336. }
  337. - (BOOL)sortsBeforeDocument:(FSTDocument *)document
  338. usingSortOrder:(NSArray<FSTSortOrder *> *)sortOrder {
  339. FSTAssert(self.position.count <= sortOrder.count,
  340. @"FSTIndexPosition has more components than provided sort order.");
  341. __block NSComparisonResult result = NSOrderedSame;
  342. [self.position enumerateObjectsUsingBlock:^(FSTFieldValue *fieldValue, NSUInteger idx,
  343. BOOL *stop) {
  344. FSTSortOrder *sortOrderComponent = sortOrder[idx];
  345. NSComparisonResult comparison;
  346. if (sortOrderComponent.field == FieldPath::KeyFieldPath()) {
  347. FSTAssert([fieldValue isKindOfClass:[FSTReferenceValue class]],
  348. @"FSTBound has a non-key value where the key path is being used %@", fieldValue);
  349. FSTReferenceValue *refValue = (FSTReferenceValue *)fieldValue;
  350. comparison = [refValue.value compare:document.key];
  351. } else {
  352. FSTFieldValue *docValue = [document fieldForPath:sortOrderComponent.field];
  353. FSTAssert(docValue != nil, @"Field should exist since document matched the orderBy already.");
  354. comparison = [fieldValue compare:docValue];
  355. }
  356. if (!sortOrderComponent.isAscending) {
  357. comparison = ReverseOrder(comparison);
  358. }
  359. if (comparison != 0) {
  360. result = comparison;
  361. *stop = YES;
  362. }
  363. }];
  364. return self.isBefore ? result <= NSOrderedSame : result < NSOrderedSame;
  365. }
  366. #pragma mark - NSObject methods
  367. - (NSString *)description {
  368. return [NSString stringWithFormat:@"<FSTBound: position:%@ before:%@>", self.position,
  369. self.isBefore ? @"YES" : @"NO"];
  370. }
  371. - (BOOL)isEqual:(NSObject *)other {
  372. if (self == other) {
  373. return YES;
  374. }
  375. if (![other isKindOfClass:[FSTBound class]]) {
  376. return NO;
  377. }
  378. FSTBound *otherBound = (FSTBound *)other;
  379. return [self.position isEqualToArray:otherBound.position] && self.isBefore == otherBound.isBefore;
  380. }
  381. - (NSUInteger)hash {
  382. return 31 * self.position.hash + (self.isBefore ? 0 : 1);
  383. }
  384. - (instancetype)copyWithZone:(nullable NSZone *)zone {
  385. return self;
  386. }
  387. @end
  388. #pragma mark - FSTQuery
  389. @interface FSTQuery () {
  390. // Cached value of the canonicalID property.
  391. NSString *_canonicalID;
  392. /** The base path of the query. */
  393. ResourcePath _path;
  394. }
  395. /**
  396. * Initializes the receiver with the given query constraints.
  397. *
  398. * @param path The base path of the query.
  399. * @param filters Filters specify which documents to include in the results.
  400. * @param sortOrders The fields and directions to sort the results.
  401. * @param limit If not NSNotFound, only this many results will be returned.
  402. */
  403. - (instancetype)initWithPath:(ResourcePath)path
  404. filterBy:(NSArray<id<FSTFilter>> *)filters
  405. orderBy:(NSArray<FSTSortOrder *> *)sortOrders
  406. limit:(NSInteger)limit
  407. startAt:(nullable FSTBound *)startAtBound
  408. endAt:(nullable FSTBound *)endAtBound NS_DESIGNATED_INITIALIZER;
  409. /** A list of fields given to sort by. This does not include the implicit key sort at the end. */
  410. @property(nonatomic, strong, readonly) NSArray<FSTSortOrder *> *explicitSortOrders;
  411. /** The memoized list of sort orders */
  412. @property(nonatomic, nullable, strong, readwrite) NSArray<FSTSortOrder *> *memoizedSortOrders;
  413. @end
  414. @implementation FSTQuery
  415. #pragma mark - Constructors
  416. + (instancetype)queryWithPath:(ResourcePath)path {
  417. return [[FSTQuery alloc] initWithPath:std::move(path)
  418. filterBy:@[]
  419. orderBy:@[]
  420. limit:NSNotFound
  421. startAt:nil
  422. endAt:nil];
  423. }
  424. - (instancetype)initWithPath:(ResourcePath)path
  425. filterBy:(NSArray<id<FSTFilter>> *)filters
  426. orderBy:(NSArray<FSTSortOrder *> *)sortOrders
  427. limit:(NSInteger)limit
  428. startAt:(nullable FSTBound *)startAtBound
  429. endAt:(nullable FSTBound *)endAtBound {
  430. if (self = [super init]) {
  431. _path = std::move(path);
  432. _filters = filters;
  433. _explicitSortOrders = sortOrders;
  434. _limit = limit;
  435. _startAt = startAtBound;
  436. _endAt = endAtBound;
  437. }
  438. return self;
  439. }
  440. #pragma mark - NSObject methods
  441. - (NSString *)description {
  442. return [NSString stringWithFormat:@"<FSTQuery: canonicalID:%@>", self.canonicalID];
  443. }
  444. - (BOOL)isEqual:(id)object {
  445. if (self == object) {
  446. return YES;
  447. }
  448. if (![object isKindOfClass:[FSTQuery class]]) {
  449. return NO;
  450. }
  451. return [self isEqualToQuery:(FSTQuery *)object];
  452. }
  453. - (NSUInteger)hash {
  454. return [self.canonicalID hash];
  455. }
  456. - (instancetype)copyWithZone:(nullable NSZone *)zone {
  457. return self;
  458. }
  459. #pragma mark - Public methods
  460. - (NSArray *)sortOrders {
  461. if (self.memoizedSortOrders == nil) {
  462. const FieldPath *inequalityField = [self inequalityFilterField];
  463. const FieldPath *firstSortOrderField = [self firstSortOrderField];
  464. if (inequalityField && !firstSortOrderField) {
  465. // In order to implicitly add key ordering, we must also add the inequality filter field for
  466. // it to be a valid query. Note that the default inequality field and key ordering is
  467. // ascending.
  468. if (inequalityField->IsKeyFieldPath()) {
  469. self.memoizedSortOrders =
  470. @[ [FSTSortOrder sortOrderWithFieldPath:FieldPath::KeyFieldPath() ascending:YES] ];
  471. } else {
  472. self.memoizedSortOrders = @[
  473. [FSTSortOrder sortOrderWithFieldPath:*inequalityField ascending:YES],
  474. [FSTSortOrder sortOrderWithFieldPath:FieldPath::KeyFieldPath() ascending:YES]
  475. ];
  476. }
  477. } else {
  478. FSTAssert(!inequalityField || *inequalityField == *firstSortOrderField,
  479. @"First orderBy %s should match inequality field %s.",
  480. firstSortOrderField->CanonicalString().c_str(),
  481. inequalityField->CanonicalString().c_str());
  482. __block BOOL foundKeyOrder = NO;
  483. NSMutableArray *result = [NSMutableArray array];
  484. for (FSTSortOrder *sortOrder in self.explicitSortOrders) {
  485. [result addObject:sortOrder];
  486. if (sortOrder.field == FieldPath::KeyFieldPath()) {
  487. foundKeyOrder = YES;
  488. }
  489. }
  490. if (!foundKeyOrder) {
  491. // The direction of the implicit key ordering always matches the direction of the last
  492. // explicit sort order
  493. BOOL lastIsAscending =
  494. self.explicitSortOrders.count > 0 ? self.explicitSortOrders.lastObject.ascending : YES;
  495. [result addObject:[FSTSortOrder sortOrderWithFieldPath:FieldPath::KeyFieldPath()
  496. ascending:lastIsAscending]];
  497. }
  498. self.memoizedSortOrders = result;
  499. }
  500. }
  501. return self.memoizedSortOrders;
  502. }
  503. - (instancetype)queryByAddingFilter:(id<FSTFilter>)filter {
  504. FSTAssert(!DocumentKey::IsDocumentKey(_path), @"No filtering allowed for document query");
  505. const FieldPath *newInequalityField = nullptr;
  506. if ([filter isKindOfClass:[FSTRelationFilter class]] &&
  507. [((FSTRelationFilter *)filter)isInequality]) {
  508. newInequalityField = &filter.field;
  509. }
  510. const FieldPath *queryInequalityField = [self inequalityFilterField];
  511. FSTAssert(
  512. !queryInequalityField || !newInequalityField || *queryInequalityField == *newInequalityField,
  513. @"Query must only have one inequality field.");
  514. return [[FSTQuery alloc] initWithPath:self.path
  515. filterBy:[self.filters arrayByAddingObject:filter]
  516. orderBy:self.explicitSortOrders
  517. limit:self.limit
  518. startAt:self.startAt
  519. endAt:self.endAt];
  520. }
  521. - (instancetype)queryByAddingSortOrder:(FSTSortOrder *)sortOrder {
  522. FSTAssert(!DocumentKey::IsDocumentKey(_path), @"No ordering is allowed for a document query.");
  523. // TODO(klimt): Validate that the same key isn't added twice.
  524. return [[FSTQuery alloc] initWithPath:self.path
  525. filterBy:self.filters
  526. orderBy:[self.explicitSortOrders arrayByAddingObject:sortOrder]
  527. limit:self.limit
  528. startAt:self.startAt
  529. endAt:self.endAt];
  530. }
  531. - (instancetype)queryBySettingLimit:(NSInteger)limit {
  532. return [[FSTQuery alloc] initWithPath:self.path
  533. filterBy:self.filters
  534. orderBy:self.explicitSortOrders
  535. limit:limit
  536. startAt:self.startAt
  537. endAt:self.endAt];
  538. }
  539. - (instancetype)queryByAddingStartAt:(FSTBound *)bound {
  540. return [[FSTQuery alloc] initWithPath:self.path
  541. filterBy:self.filters
  542. orderBy:self.explicitSortOrders
  543. limit:self.limit
  544. startAt:bound
  545. endAt:self.endAt];
  546. }
  547. - (instancetype)queryByAddingEndAt:(FSTBound *)bound {
  548. return [[FSTQuery alloc] initWithPath:self.path
  549. filterBy:self.filters
  550. orderBy:self.explicitSortOrders
  551. limit:self.limit
  552. startAt:self.startAt
  553. endAt:bound];
  554. }
  555. - (BOOL)isDocumentQuery {
  556. return DocumentKey::IsDocumentKey(_path) && self.filters.count == 0;
  557. }
  558. - (BOOL)matchesDocument:(FSTDocument *)document {
  559. return [self pathMatchesDocument:document] && [self orderByMatchesDocument:document] &&
  560. [self filtersMatchDocument:document] && [self boundsMatchDocument:document];
  561. }
  562. - (NSComparator)comparator {
  563. return ^NSComparisonResult(id document1, id document2) {
  564. BOOL didCompareOnKeyField = NO;
  565. for (FSTSortOrder *orderBy in self.sortOrders) {
  566. NSComparisonResult comp = [orderBy compareDocument:document1 toDocument:document2];
  567. if (comp != NSOrderedSame) {
  568. return comp;
  569. }
  570. didCompareOnKeyField = didCompareOnKeyField || orderBy.field == FieldPath::KeyFieldPath();
  571. }
  572. FSTAssert(didCompareOnKeyField, @"sortOrder of query did not include key ordering");
  573. return NSOrderedSame;
  574. };
  575. }
  576. - (const FieldPath *)inequalityFilterField {
  577. for (id<FSTFilter> filter in self.filters) {
  578. if ([filter isKindOfClass:[FSTRelationFilter class]] &&
  579. ((FSTRelationFilter *)filter).filterOperator != FSTRelationFilterOperatorEqual) {
  580. return &filter.field;
  581. }
  582. }
  583. return nullptr;
  584. }
  585. - (const FieldPath *)firstSortOrderField {
  586. if (self.explicitSortOrders.count > 0) {
  587. return &self.explicitSortOrders.firstObject.field;
  588. }
  589. return nullptr;
  590. }
  591. /** The base path of the query. */
  592. - (const firebase::firestore::model::ResourcePath &)path {
  593. return _path;
  594. }
  595. #pragma mark - Private properties
  596. - (NSString *)canonicalID {
  597. if (_canonicalID) {
  598. return _canonicalID;
  599. }
  600. NSMutableString *canonicalID = [util::WrapNSStringNoCopy(_path.CanonicalString()) mutableCopy];
  601. // Add filters.
  602. [canonicalID appendString:@"|f:"];
  603. for (id<FSTFilter> predicate in self.filters) {
  604. [canonicalID appendFormat:@"%@", [predicate canonicalID]];
  605. }
  606. // Add order by.
  607. [canonicalID appendString:@"|ob:"];
  608. for (FSTSortOrder *orderBy in self.sortOrders) {
  609. [canonicalID appendString:orderBy.canonicalID];
  610. }
  611. // Add limit.
  612. if (self.limit != NSNotFound) {
  613. [canonicalID appendFormat:@"|l:%ld", (long)self.limit];
  614. }
  615. if (self.startAt) {
  616. [canonicalID appendFormat:@"|lb:%@", self.startAt.canonicalString];
  617. }
  618. if (self.endAt) {
  619. [canonicalID appendFormat:@"|ub:%@", self.endAt.canonicalString];
  620. }
  621. _canonicalID = canonicalID;
  622. return canonicalID;
  623. }
  624. #pragma mark - Private methods
  625. - (BOOL)isEqualToQuery:(FSTQuery *)other {
  626. return self.path == other.path && self.limit == other.limit &&
  627. [self.filters isEqual:other.filters] && [self.sortOrders isEqual:other.sortOrders] &&
  628. (self.startAt == other.startAt || [self.startAt isEqual:other.startAt]) &&
  629. (self.endAt == other.endAt || [self.endAt isEqual:other.endAt]);
  630. }
  631. /* Returns YES if the document matches the path for the receiver. */
  632. - (BOOL)pathMatchesDocument:(FSTDocument *)document {
  633. const ResourcePath &documentPath = document.key.path();
  634. if (DocumentKey::IsDocumentKey(_path)) {
  635. // Exact match for document queries.
  636. return self.path == documentPath;
  637. } else {
  638. // Shallow ancestor queries by default.
  639. return self.path.IsPrefixOf(documentPath) && _path.size() == documentPath.size() - 1;
  640. }
  641. }
  642. /**
  643. * A document must have a value for every ordering clause in order to show up in the results.
  644. */
  645. - (BOOL)orderByMatchesDocument:(FSTDocument *)document {
  646. for (FSTSortOrder *orderBy in self.explicitSortOrders) {
  647. const FieldPath &fieldPath = orderBy.field;
  648. // order by key always matches
  649. if (fieldPath != FieldPath::KeyFieldPath() && [document fieldForPath:fieldPath] == nil) {
  650. return NO;
  651. }
  652. }
  653. return YES;
  654. }
  655. /** Returns YES if the document matches all of the filters in the receiver. */
  656. - (BOOL)filtersMatchDocument:(FSTDocument *)document {
  657. for (id<FSTFilter> filter in self.filters) {
  658. if (![filter matchesDocument:document]) {
  659. return NO;
  660. }
  661. }
  662. return YES;
  663. }
  664. - (BOOL)boundsMatchDocument:(FSTDocument *)document {
  665. if (self.startAt && ![self.startAt sortsBeforeDocument:document usingSortOrder:self.sortOrders]) {
  666. return NO;
  667. }
  668. if (self.endAt && [self.endAt sortsBeforeDocument:document usingSortOrder:self.sortOrders]) {
  669. return NO;
  670. }
  671. return YES;
  672. }
  673. @end
  674. NS_ASSUME_NONNULL_END