FSTQuery.mm 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  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 <limits>
  18. #include <memory>
  19. #include <string>
  20. #include <utility>
  21. #include <vector>
  22. #import "Firestore/Source/API/FIRFirestore+Internal.h"
  23. #import "Firestore/Source/Model/FSTDocument.h"
  24. #import "Firestore/Source/Util/FSTClasses.h"
  25. #include "Firestore/core/src/firebase/firestore/api/input_validation.h"
  26. #include "Firestore/core/src/firebase/firestore/core/field_filter.h"
  27. #include "Firestore/core/src/firebase/firestore/core/filter.h"
  28. #include "Firestore/core/src/firebase/firestore/core/query.h"
  29. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  30. #include "Firestore/core/src/firebase/firestore/model/field_path.h"
  31. #include "Firestore/core/src/firebase/firestore/model/field_value.h"
  32. #include "Firestore/core/src/firebase/firestore/model/resource_path.h"
  33. #include "Firestore/core/src/firebase/firestore/objc/objc_compatibility.h"
  34. #include "Firestore/core/src/firebase/firestore/util/comparison.h"
  35. #include "Firestore/core/src/firebase/firestore/util/equality.h"
  36. #include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
  37. #include "Firestore/core/src/firebase/firestore/util/hashing.h"
  38. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  39. #include "absl/algorithm/container.h"
  40. namespace core = firebase::firestore::core;
  41. namespace objc = firebase::firestore::objc;
  42. namespace util = firebase::firestore::util;
  43. using firebase::firestore::api::ThrowInvalidArgument;
  44. using firebase::firestore::core::Filter;
  45. using firebase::firestore::core::Query;
  46. using firebase::firestore::model::Document;
  47. using firebase::firestore::model::DocumentComparator;
  48. using firebase::firestore::model::DocumentKey;
  49. using firebase::firestore::model::FieldPath;
  50. using firebase::firestore::model::FieldValue;
  51. using firebase::firestore::model::ResourcePath;
  52. using firebase::firestore::util::ComparisonResult;
  53. NS_ASSUME_NONNULL_BEGIN
  54. #pragma mark - FSTSortOrder
  55. @interface FSTSortOrder () {
  56. /** The field to sort by. */
  57. FieldPath _field;
  58. }
  59. /** Creates a new sort order with the given field and direction. */
  60. - (instancetype)initWithFieldPath:(FieldPath)fieldPath ascending:(BOOL)ascending;
  61. - (NSString *)canonicalID;
  62. @end
  63. @implementation FSTSortOrder
  64. #pragma mark - Constructor methods
  65. + (instancetype)sortOrderWithFieldPath:(FieldPath)fieldPath ascending:(BOOL)ascending {
  66. return [[FSTSortOrder alloc] initWithFieldPath:std::move(fieldPath) ascending:ascending];
  67. }
  68. - (instancetype)initWithFieldPath:(FieldPath)fieldPath ascending:(BOOL)ascending {
  69. self = [super init];
  70. if (self) {
  71. _field = std::move(fieldPath);
  72. _ascending = ascending;
  73. }
  74. return self;
  75. }
  76. - (const FieldPath &)field {
  77. return _field;
  78. }
  79. #pragma mark - Public methods
  80. - (ComparisonResult)compareDocument:(FSTDocument *)document1 toDocument:(FSTDocument *)document2 {
  81. ComparisonResult result;
  82. if (_field == FieldPath::KeyFieldPath()) {
  83. result = util::Compare(document1.key, document2.key);
  84. } else {
  85. absl::optional<FieldValue> value1 = [document1 fieldForPath:self.field];
  86. absl::optional<FieldValue> value2 = [document2 fieldForPath:self.field];
  87. HARD_ASSERT(value1.has_value() && value2.has_value(),
  88. "Trying to compare documents on fields that don't exist.");
  89. result = value1->CompareTo(*value2);
  90. }
  91. if (!self.isAscending) {
  92. result = util::ReverseOrder(result);
  93. }
  94. return result;
  95. }
  96. - (NSString *)canonicalID {
  97. return [NSString stringWithFormat:@"%s%@", _field.CanonicalString().c_str(),
  98. self.isAscending ? @"asc" : @"desc"];
  99. }
  100. - (BOOL)isEqualToSortOrder:(FSTSortOrder *)other {
  101. return _field == other->_field && self.isAscending == other.isAscending;
  102. }
  103. #pragma mark - NSObject methods
  104. - (NSString *)description {
  105. return [NSString stringWithFormat:@"<FSTSortOrder: path:%s dir:%@>",
  106. _field.CanonicalString().c_str(),
  107. self.ascending ? @"asc" : @"desc"];
  108. }
  109. - (BOOL)isEqual:(NSObject *)other {
  110. if (self == other) {
  111. return YES;
  112. }
  113. if (![other isKindOfClass:[FSTSortOrder class]]) {
  114. return NO;
  115. }
  116. return [self isEqualToSortOrder:(FSTSortOrder *)other];
  117. }
  118. - (NSUInteger)hash {
  119. return [self.canonicalID hash];
  120. }
  121. - (instancetype)copyWithZone:(nullable NSZone *)zone {
  122. return self;
  123. }
  124. @end
  125. #pragma mark - FSTBound
  126. @implementation FSTBound {
  127. std::vector<FieldValue> _position;
  128. }
  129. - (instancetype)initWithPosition:(std::vector<FieldValue>)position isBefore:(bool)isBefore {
  130. if (self = [super init]) {
  131. _position = std::move(position);
  132. _before = isBefore;
  133. }
  134. return self;
  135. }
  136. + (instancetype)boundWithPosition:(std::vector<FieldValue>)position isBefore:(bool)isBefore {
  137. return [[FSTBound alloc] initWithPosition:position isBefore:isBefore];
  138. }
  139. - (NSString *)canonicalString {
  140. // TODO(b/29183165): Make this collision robust.
  141. NSMutableString *string = [NSMutableString string];
  142. if (self.isBefore) {
  143. [string appendString:@"b:"];
  144. } else {
  145. [string appendString:@"a:"];
  146. }
  147. for (const FieldValue &component : _position) {
  148. [string appendFormat:@"%s", component.ToString().c_str()];
  149. }
  150. return string;
  151. }
  152. - (bool)sortsBeforeDocument:(FSTDocument *)document
  153. usingSortOrder:(NSArray<FSTSortOrder *> *)sortOrder {
  154. HARD_ASSERT(_position.size() <= sortOrder.count,
  155. "FSTIndexPosition has more components than provided sort order.");
  156. ComparisonResult result = ComparisonResult::Same;
  157. for (size_t idx = 0; idx < _position.size(); ++idx) {
  158. const FieldValue &fieldValue = _position[idx];
  159. FSTSortOrder *sortOrderComponent = sortOrder[idx];
  160. ComparisonResult comparison;
  161. if (sortOrderComponent.field == FieldPath::KeyFieldPath()) {
  162. HARD_ASSERT(fieldValue.type() == FieldValue::Type::Reference,
  163. "FSTBound has a non-key value where the key path is being used %s",
  164. fieldValue.ToString());
  165. const auto &ref = fieldValue.reference_value();
  166. comparison = ref.key().CompareTo(document.key);
  167. } else {
  168. absl::optional<FieldValue> docValue = [document fieldForPath:sortOrderComponent.field];
  169. HARD_ASSERT(docValue.has_value(),
  170. "Field should exist since document matched the orderBy already.");
  171. comparison = fieldValue.CompareTo(*docValue);
  172. }
  173. if (!sortOrderComponent.isAscending) {
  174. comparison = util::ReverseOrder(comparison);
  175. }
  176. if (!util::Same(comparison)) {
  177. result = comparison;
  178. break;
  179. }
  180. }
  181. return self.isBefore ? result <= ComparisonResult::Same : result < ComparisonResult::Same;
  182. }
  183. #pragma mark - NSObject methods
  184. - (NSString *)description {
  185. return
  186. [NSString stringWithFormat:@"<FSTBound: position:%s before:%@>",
  187. util::ToString(_position).c_str(), self.isBefore ? @"YES" : @"NO"];
  188. }
  189. - (BOOL)isEqual:(NSObject *)other {
  190. if (self == other) {
  191. return YES;
  192. }
  193. if (![other isKindOfClass:[FSTBound class]]) {
  194. return NO;
  195. }
  196. FSTBound *otherBound = (FSTBound *)other;
  197. return _position == otherBound->_position && self.isBefore == otherBound.isBefore;
  198. }
  199. - (NSUInteger)hash {
  200. return util::Hash(self.position, self.isBefore);
  201. }
  202. - (instancetype)copyWithZone:(nullable NSZone *)zone {
  203. return self;
  204. }
  205. @end
  206. #pragma mark - FSTQuery
  207. @interface FSTQuery () {
  208. // Cached value of the canonicalID property.
  209. NSString *_canonicalID;
  210. // The C++ implementation of this query to which FSTQuery delegates.
  211. Query _query;
  212. }
  213. /** A list of fields given to sort by. This does not include the implicit key sort at the end. */
  214. @property(nonatomic, strong, readonly) NSArray<FSTSortOrder *> *explicitSortOrders;
  215. /** The memoized list of sort orders */
  216. @property(nonatomic, nullable, strong, readwrite) NSArray<FSTSortOrder *> *memoizedSortOrders;
  217. @end
  218. @implementation FSTQuery
  219. #pragma mark - Constructors
  220. + (instancetype)queryWithPath:(ResourcePath)path {
  221. return [FSTQuery queryWithPath:std::move(path) collectionGroup:nullptr];
  222. }
  223. + (instancetype)queryWithPath:(ResourcePath)path
  224. collectionGroup:(std::shared_ptr<const std::string>)collectionGroup {
  225. return [[self alloc] initWithQuery:Query(std::move(path), std::move(collectionGroup))
  226. orderBy:@[]
  227. limit:Query::kNoLimit
  228. startAt:nil
  229. endAt:nil];
  230. }
  231. - (instancetype)initWithQuery:(core::Query)query
  232. orderBy:(NSArray<FSTSortOrder *> *)sortOrders
  233. limit:(int32_t)limit
  234. startAt:(nullable FSTBound *)startAtBound
  235. endAt:(nullable FSTBound *)endAtBound {
  236. if (self = [super init]) {
  237. _query = std::move(query);
  238. _explicitSortOrders = sortOrders;
  239. _limit = limit;
  240. _startAt = startAtBound;
  241. _endAt = endAtBound;
  242. }
  243. return self;
  244. }
  245. #pragma mark - NSObject methods
  246. - (NSString *)description {
  247. return [NSString stringWithFormat:@"<FSTQuery: canonicalID:%@>", self.canonicalID];
  248. }
  249. - (BOOL)isEqual:(id)object {
  250. if (self == object) {
  251. return YES;
  252. }
  253. if (![object isKindOfClass:[FSTQuery class]]) {
  254. return NO;
  255. }
  256. return [self isEqualToQuery:(FSTQuery *)object];
  257. }
  258. - (NSUInteger)hash {
  259. return [self.canonicalID hash];
  260. }
  261. - (instancetype)copyWithZone:(nullable NSZone *)zone {
  262. return self;
  263. }
  264. #pragma mark - Public methods
  265. - (const Query::FilterList &)filters {
  266. return _query.filters();
  267. }
  268. - (NSArray *)sortOrders {
  269. if (self.memoizedSortOrders == nil) {
  270. const FieldPath *inequalityField = [self inequalityFilterField];
  271. const FieldPath *firstSortOrderField = [self firstSortOrderField];
  272. if (inequalityField && !firstSortOrderField) {
  273. // In order to implicitly add key ordering, we must also add the inequality filter field for
  274. // it to be a valid query. Note that the default inequality field and key ordering is
  275. // ascending.
  276. if (inequalityField->IsKeyFieldPath()) {
  277. self.memoizedSortOrders = @[ [FSTSortOrder sortOrderWithFieldPath:FieldPath::KeyFieldPath()
  278. ascending:YES] ];
  279. } else {
  280. self.memoizedSortOrders = @[
  281. [FSTSortOrder sortOrderWithFieldPath:*inequalityField ascending:YES],
  282. [FSTSortOrder sortOrderWithFieldPath:FieldPath::KeyFieldPath() ascending:YES]
  283. ];
  284. }
  285. } else {
  286. HARD_ASSERT(!inequalityField || *inequalityField == *firstSortOrderField,
  287. "First orderBy %s should match inequality field %s.",
  288. firstSortOrderField->CanonicalString(), inequalityField->CanonicalString());
  289. __block BOOL foundKeyOrder = NO;
  290. NSMutableArray *result = [NSMutableArray array];
  291. for (FSTSortOrder *sortOrder in self.explicitSortOrders) {
  292. [result addObject:sortOrder];
  293. if (sortOrder.field == FieldPath::KeyFieldPath()) {
  294. foundKeyOrder = YES;
  295. }
  296. }
  297. if (!foundKeyOrder) {
  298. // The direction of the implicit key ordering always matches the direction of the last
  299. // explicit sort order
  300. BOOL lastIsAscending =
  301. self.explicitSortOrders.count > 0 ? self.explicitSortOrders.lastObject.ascending : YES;
  302. [result addObject:[FSTSortOrder sortOrderWithFieldPath:FieldPath::KeyFieldPath()
  303. ascending:lastIsAscending]];
  304. }
  305. self.memoizedSortOrders = result;
  306. }
  307. }
  308. return self.memoizedSortOrders;
  309. }
  310. - (instancetype)queryByAddingFilter:(std::shared_ptr<Filter>)filter {
  311. return [[FSTQuery alloc] initWithQuery:_query.AddingFilter(std::move(filter))
  312. orderBy:self.explicitSortOrders
  313. limit:self.limit
  314. startAt:self.startAt
  315. endAt:self.endAt];
  316. }
  317. - (instancetype)queryByAddingSortOrder:(FSTSortOrder *)sortOrder {
  318. HARD_ASSERT(![self isDocumentQuery], "No ordering is allowed for a document query.");
  319. // TODO(klimt): Validate that the same key isn't added twice.
  320. return [[FSTQuery alloc] initWithQuery:_query
  321. orderBy:[self.explicitSortOrders arrayByAddingObject:sortOrder]
  322. limit:self.limit
  323. startAt:self.startAt
  324. endAt:self.endAt];
  325. }
  326. - (instancetype)queryBySettingLimit:(int32_t)limit {
  327. return [[FSTQuery alloc] initWithQuery:_query
  328. orderBy:self.explicitSortOrders
  329. limit:limit
  330. startAt:self.startAt
  331. endAt:self.endAt];
  332. }
  333. - (instancetype)queryByAddingStartAt:(FSTBound *)bound {
  334. return [[FSTQuery alloc] initWithQuery:_query
  335. orderBy:self.explicitSortOrders
  336. limit:self.limit
  337. startAt:bound
  338. endAt:self.endAt];
  339. }
  340. - (instancetype)queryByAddingEndAt:(FSTBound *)bound {
  341. return [[FSTQuery alloc] initWithQuery:_query
  342. orderBy:self.explicitSortOrders
  343. limit:self.limit
  344. startAt:self.startAt
  345. endAt:bound];
  346. }
  347. - (instancetype)collectionQueryAtPath:(ResourcePath)path {
  348. return [[FSTQuery alloc] initWithQuery:_query.AsCollectionQueryAtPath(std::move(path))
  349. orderBy:self.explicitSortOrders
  350. limit:self.limit
  351. startAt:self.startAt
  352. endAt:self.endAt];
  353. }
  354. - (BOOL)isDocumentQuery {
  355. return _query.IsDocumentQuery();
  356. }
  357. - (BOOL)isCollectionGroupQuery {
  358. return self.collectionGroup != nil;
  359. }
  360. - (BOOL)matchesDocument:(FSTDocument *)document {
  361. return [self pathAndCollectionGroupMatchDocument:document] &&
  362. [self orderByMatchesDocument:document] && [self filtersMatchDocument:document] &&
  363. [self boundsMatchDocument:document];
  364. }
  365. - (DocumentComparator)comparator {
  366. NSArray<FSTSortOrder *> *sortOrders = self.sortOrders;
  367. return DocumentComparator([sortOrders](id document1, id document2) {
  368. bool didCompareOnKeyField = false;
  369. for (FSTSortOrder *orderBy in sortOrders) {
  370. ComparisonResult comp = [orderBy compareDocument:document1 toDocument:document2];
  371. if (!util::Same(comp)) return comp;
  372. didCompareOnKeyField = didCompareOnKeyField || orderBy.field == FieldPath::KeyFieldPath();
  373. }
  374. HARD_ASSERT(didCompareOnKeyField, "sortOrder of query did not include key ordering");
  375. return ComparisonResult::Same;
  376. });
  377. }
  378. - (nullable const FieldPath *)inequalityFilterField {
  379. return _query.InequalityFilterField();
  380. }
  381. - (BOOL)hasArrayContainsFilter {
  382. return _query.HasArrayContainsFilter();
  383. }
  384. - (nullable const FieldPath *)firstSortOrderField {
  385. if (self.explicitSortOrders.count > 0) {
  386. return &self.explicitSortOrders.firstObject.field;
  387. }
  388. return nullptr;
  389. }
  390. /** The base path of the query. */
  391. - (const ResourcePath &)path {
  392. return _query.path();
  393. }
  394. - (const std::shared_ptr<const std::string> &)collectionGroup {
  395. return _query.collection_group();
  396. }
  397. #pragma mark - Private properties
  398. - (NSString *)canonicalID {
  399. if (_canonicalID) {
  400. return _canonicalID;
  401. }
  402. NSMutableString *canonicalID = [NSMutableString string];
  403. [canonicalID appendFormat:@"%s", self.path.CanonicalString().c_str()];
  404. if (self.collectionGroup) {
  405. [canonicalID appendFormat:@"|cg:%s", self.collectionGroup->c_str()];
  406. }
  407. // Add filters.
  408. [canonicalID appendString:@"|f:"];
  409. for (const auto &filter : self.filters) {
  410. [canonicalID appendFormat:@"%s", filter->CanonicalId().c_str()];
  411. }
  412. // Add order by.
  413. [canonicalID appendString:@"|ob:"];
  414. for (FSTSortOrder *orderBy in self.sortOrders) {
  415. [canonicalID appendString:orderBy.canonicalID];
  416. }
  417. // Add limit.
  418. if (self.limit != Query::kNoLimit) {
  419. [canonicalID appendFormat:@"|l:%ld", (long)self.limit];
  420. }
  421. if (self.startAt) {
  422. [canonicalID appendFormat:@"|lb:%@", self.startAt.canonicalString];
  423. }
  424. if (self.endAt) {
  425. [canonicalID appendFormat:@"|ub:%@", self.endAt.canonicalString];
  426. }
  427. _canonicalID = canonicalID;
  428. return canonicalID;
  429. }
  430. #pragma mark - Private methods
  431. - (BOOL)isEqualToQuery:(FSTQuery *)other {
  432. return _query == other->_query && self.limit == other.limit &&
  433. objc::Equals(self.sortOrders, other.sortOrders) &&
  434. objc::Equals(self.startAt, other.startAt) && objc::Equals(self.endAt, other.endAt);
  435. }
  436. /* Returns YES if the document matches the path and collection group for the receiver. */
  437. - (BOOL)pathAndCollectionGroupMatchDocument:(FSTDocument *)document {
  438. const ResourcePath &documentPath = document.key.path();
  439. if (self.collectionGroup) {
  440. // NOTE: self.path is currently always empty since we don't expose Collection Group queries
  441. // rooted at a document path yet.
  442. return document.key.HasCollectionId(*self.collectionGroup) &&
  443. self.path.IsPrefixOf(documentPath);
  444. } else if (DocumentKey::IsDocumentKey(self.path)) {
  445. // Exact match for document queries.
  446. return self.path == documentPath;
  447. } else {
  448. // Shallow ancestor queries by default.
  449. return self.path.IsPrefixOf(documentPath) && self.path.size() == documentPath.size() - 1;
  450. }
  451. }
  452. /**
  453. * A document must have a value for every ordering clause in order to show up in the results.
  454. */
  455. - (BOOL)orderByMatchesDocument:(FSTDocument *)document {
  456. for (FSTSortOrder *orderBy in self.explicitSortOrders) {
  457. const FieldPath &fieldPath = orderBy.field;
  458. // order by key always matches
  459. if (fieldPath != FieldPath::KeyFieldPath() &&
  460. [document fieldForPath:fieldPath] == absl::nullopt) {
  461. return NO;
  462. }
  463. }
  464. return YES;
  465. }
  466. /** Returns YES if the document matches all of the filters in the receiver. */
  467. - (BOOL)filtersMatchDocument:(FSTDocument *)document {
  468. Document converted(document);
  469. for (const auto &filter : self.filters) {
  470. if (!filter->Matches(converted)) {
  471. return NO;
  472. }
  473. }
  474. return YES;
  475. }
  476. - (BOOL)boundsMatchDocument:(FSTDocument *)document {
  477. if (self.startAt && ![self.startAt sortsBeforeDocument:document usingSortOrder:self.sortOrders]) {
  478. return NO;
  479. }
  480. if (self.endAt && [self.endAt sortsBeforeDocument:document usingSortOrder:self.sortOrders]) {
  481. return NO;
  482. }
  483. return YES;
  484. }
  485. @end
  486. NS_ASSUME_NONNULL_END