FSTQuery.mm 26 KB

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