FSTQuery.mm 26 KB

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