FSTQuery.m 24 KB

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