FSTQuery.mm 28 KB

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