FSTQuery.mm 24 KB

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