RLMResults.mm 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. ////////////////////////////////////////////////////////////////////////////
  2. //
  3. // Copyright 2014 Realm Inc.
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License");
  6. // you may not use this file except in compliance with the License.
  7. // You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. //
  17. ////////////////////////////////////////////////////////////////////////////
  18. #import "RLMResults_Private.hpp"
  19. #import "RLMAccessor.hpp"
  20. #import "RLMArray_Private.hpp"
  21. #import "RLMCollection_Private.hpp"
  22. #import "RLMObjectSchema_Private.hpp"
  23. #import "RLMObjectStore.h"
  24. #import "RLMObject_Private.hpp"
  25. #import "RLMObservation.hpp"
  26. #import "RLMProperty_Private.h"
  27. #import "RLMQueryUtil.hpp"
  28. #import "RLMRealm_Private.hpp"
  29. #import "RLMSchema_Private.h"
  30. #import "RLMThreadSafeReference_Private.hpp"
  31. #import "RLMUtil.hpp"
  32. #import "results.hpp"
  33. #import "shared_realm.hpp"
  34. #import <objc/message.h>
  35. #import <realm/table_view.hpp>
  36. using namespace realm;
  37. #pragma clang diagnostic push
  38. #pragma clang diagnostic ignored "-Wincomplete-implementation"
  39. @implementation RLMNotificationToken
  40. @end
  41. #pragma clang diagnostic pop
  42. @interface RLMResults () <RLMThreadConfined_Private>
  43. @end
  44. //
  45. // RLMResults implementation
  46. //
  47. @implementation RLMResults {
  48. RLMRealm *_realm;
  49. RLMClassInfo *_info;
  50. }
  51. - (instancetype)initPrivate {
  52. self = [super init];
  53. return self;
  54. }
  55. - (instancetype)initWithResults:(Results)results {
  56. if (self = [super init]) {
  57. _results = std::move(results);
  58. }
  59. return self;
  60. }
  61. static void assertKeyPathIsNotNested(NSString *keyPath) {
  62. if ([keyPath rangeOfString:@"."].location != NSNotFound) {
  63. @throw RLMException(@"Nested key paths are not supported yet for KVC collection operators.");
  64. }
  65. }
  66. void RLMThrowResultsError(NSString *aggregateMethod) {
  67. try {
  68. throw;
  69. }
  70. catch (realm::InvalidTransactionException const&) {
  71. @throw RLMException(@"Cannot modify Results outside of a write transaction.");
  72. }
  73. catch (realm::IncorrectThreadException const&) {
  74. @throw RLMException(@"Realm accessed from incorrect thread.");
  75. }
  76. catch (realm::Results::InvalidatedException const&) {
  77. @throw RLMException(@"RLMResults has been invalidated.");
  78. }
  79. catch (realm::Results::DetatchedAccessorException const&) {
  80. @throw RLMException(@"Object has been invalidated.");
  81. }
  82. catch (realm::Results::IncorrectTableException const& e) {
  83. @throw RLMException(@"Object of type '%s' does not match RLMResults type '%s'.",
  84. e.actual.data(), e.expected.data());
  85. }
  86. catch (realm::Results::OutOfBoundsIndexException const& e) {
  87. @throw RLMException(@"Index %zu is out of bounds (must be less than %zu).",
  88. e.requested, e.valid_count);
  89. }
  90. catch (realm::Results::UnsupportedColumnTypeException const& e) {
  91. @throw RLMException(@"%@ is not supported for %s%s property '%s'.",
  92. aggregateMethod,
  93. string_for_property_type(e.property_type),
  94. is_nullable(e.property_type) ? "?" : "",
  95. e.column_name.data());
  96. }
  97. catch (std::exception const& e) {
  98. @throw RLMException(e);
  99. }
  100. }
  101. - (instancetype)initWithObjectInfo:(RLMClassInfo&)info
  102. results:(realm::Results&&)results {
  103. if (self = [super init]) {
  104. _results = std::move(results);
  105. _realm = info.realm;
  106. _info = &info;
  107. }
  108. return self;
  109. }
  110. + (instancetype)resultsWithObjectInfo:(RLMClassInfo&)info
  111. results:(realm::Results&&)results {
  112. return [[self alloc] initWithObjectInfo:info results:std::move(results)];
  113. }
  114. + (instancetype)emptyDetachedResults {
  115. return [[self alloc] initPrivate];
  116. }
  117. - (instancetype)subresultsWithResults:(realm::Results)results {
  118. return [self.class resultsWithObjectInfo:*_info results:std::move(results)];
  119. }
  120. static inline void RLMResultsValidateInWriteTransaction(__unsafe_unretained RLMResults *const ar) {
  121. ar->_realm->_realm->verify_thread();
  122. ar->_realm->_realm->verify_in_write();
  123. }
  124. - (BOOL)isInvalidated {
  125. return translateRLMResultsErrors([&] { return !_results.is_valid(); });
  126. }
  127. - (NSUInteger)count {
  128. return translateRLMResultsErrors([&] { return _results.size(); });
  129. }
  130. - (RLMPropertyType)type {
  131. return translateRLMResultsErrors([&] {
  132. return static_cast<RLMPropertyType>(_results.get_type() & ~realm::PropertyType::Nullable);
  133. });
  134. }
  135. - (BOOL)isOptional {
  136. return translateRLMResultsErrors([&] {
  137. return is_nullable(_results.get_type());
  138. });
  139. }
  140. - (NSString *)objectClassName {
  141. return translateRLMResultsErrors([&] {
  142. if (_info && _results.get_type() == realm::PropertyType::Object) {
  143. return _info->rlmObjectSchema.className;
  144. }
  145. return (NSString *)nil;
  146. });
  147. }
  148. - (RLMClassInfo *)objectInfo {
  149. return _info;
  150. }
  151. - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state
  152. objects:(__unused __unsafe_unretained id [])buffer
  153. count:(NSUInteger)len {
  154. if (!_info) {
  155. return 0;
  156. }
  157. return RLMFastEnumerate(state, len, self);
  158. }
  159. - (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat, ... {
  160. va_list args;
  161. va_start(args, predicateFormat);
  162. NSUInteger index = [self indexOfObjectWhere:predicateFormat args:args];
  163. va_end(args);
  164. return index;
  165. }
  166. - (NSUInteger)indexOfObjectWhere:(NSString *)predicateFormat args:(va_list)args {
  167. return [self indexOfObjectWithPredicate:[NSPredicate predicateWithFormat:predicateFormat
  168. arguments:args]];
  169. }
  170. - (NSUInteger)indexOfObjectWithPredicate:(NSPredicate *)predicate {
  171. if (_results.get_mode() == Results::Mode::Empty) {
  172. return NSNotFound;
  173. }
  174. return translateRLMResultsErrors([&] {
  175. if (_results.get_type() != realm::PropertyType::Object) {
  176. @throw RLMException(@"Querying is currently only implemented for arrays of Realm Objects");
  177. }
  178. return RLMConvertNotFound(_results.index_of(RLMPredicateToQuery(predicate, _info->rlmObjectSchema, _realm.schema, _realm.group)));
  179. });
  180. }
  181. - (id)objectAtIndex:(NSUInteger)index {
  182. RLMAccessorContext ctx(_realm, *_info);
  183. return translateRLMResultsErrors([&] {
  184. return _results.get(ctx, index);
  185. });
  186. }
  187. - (id)firstObject {
  188. if (!_info) {
  189. return nil;
  190. }
  191. RLMAccessorContext ctx(_realm, *_info);
  192. return translateRLMResultsErrors([&] {
  193. return _results.first(ctx);
  194. });
  195. }
  196. - (id)lastObject {
  197. if (!_info) {
  198. return nil;
  199. }
  200. RLMAccessorContext ctx(_realm, *_info);
  201. return translateRLMResultsErrors([&] {
  202. return _results.last(ctx);
  203. });
  204. }
  205. - (NSUInteger)indexOfObject:(RLMObject *)object {
  206. if (!_info || !object || (!object->_realm && !object.invalidated)) {
  207. return NSNotFound;
  208. }
  209. RLMAccessorContext ctx(_realm, *_info);
  210. return translateRLMResultsErrors([&] {
  211. return RLMConvertNotFound(_results.index_of(ctx, object));
  212. });
  213. }
  214. - (id)valueForKeyPath:(NSString *)keyPath {
  215. if ([keyPath characterAtIndex:0] != '@') {
  216. return [super valueForKeyPath:keyPath];
  217. }
  218. if ([keyPath isEqualToString:@"@count"]) {
  219. return @(self.count);
  220. }
  221. NSRange operatorRange = [keyPath rangeOfString:@"." options:NSLiteralSearch];
  222. NSUInteger keyPathLength = keyPath.length;
  223. NSUInteger separatorIndex = operatorRange.location != NSNotFound ? operatorRange.location : keyPathLength;
  224. NSString *operatorName = [keyPath substringWithRange:NSMakeRange(1, separatorIndex - 1)];
  225. SEL opSelector = NSSelectorFromString([NSString stringWithFormat:@"_%@ForKeyPath:", operatorName]);
  226. if (![self respondsToSelector:opSelector]) {
  227. @throw RLMException(@"Unsupported KVC collection operator found in key path '%@'", keyPath);
  228. }
  229. if (separatorIndex >= keyPathLength - 1) {
  230. @throw RLMException(@"Missing key path for KVC collection operator %@ in key path '%@'",
  231. operatorName, keyPath);
  232. }
  233. NSString *operatorKeyPath = [keyPath substringFromIndex:separatorIndex + 1];
  234. return ((id(*)(id, SEL, id))objc_msgSend)(self, opSelector, operatorKeyPath);
  235. }
  236. - (id)valueForKey:(NSString *)key {
  237. if (!_info) {
  238. return @[];
  239. }
  240. return translateRLMResultsErrors([&] {
  241. return RLMCollectionValueForKey(_results, key, _realm, *_info);
  242. });
  243. }
  244. - (void)setValue:(id)value forKey:(NSString *)key {
  245. translateRLMResultsErrors([&] { RLMResultsValidateInWriteTransaction(self); });
  246. RLMCollectionSetValueForKey(self, key, value);
  247. }
  248. - (NSNumber *)_aggregateForKeyPath:(NSString *)keyPath
  249. method:(util::Optional<Mixed> (Results::*)(size_t))method
  250. methodName:(NSString *)methodName returnNilForEmpty:(BOOL)returnNilForEmpty {
  251. assertKeyPathIsNotNested(keyPath);
  252. return [self aggregate:keyPath method:method methodName:methodName returnNilForEmpty:returnNilForEmpty];
  253. }
  254. - (NSNumber *)_minForKeyPath:(NSString *)keyPath {
  255. return [self _aggregateForKeyPath:keyPath method:&Results::min methodName:@"@min" returnNilForEmpty:YES];
  256. }
  257. - (NSNumber *)_maxForKeyPath:(NSString *)keyPath {
  258. return [self _aggregateForKeyPath:keyPath method:&Results::max methodName:@"@max" returnNilForEmpty:YES];
  259. }
  260. - (NSNumber *)_sumForKeyPath:(NSString *)keyPath {
  261. return [self _aggregateForKeyPath:keyPath method:&Results::sum methodName:@"@sum" returnNilForEmpty:NO];
  262. }
  263. - (NSNumber *)_avgForKeyPath:(NSString *)keyPath {
  264. assertKeyPathIsNotNested(keyPath);
  265. return [self averageOfProperty:keyPath];
  266. }
  267. - (NSArray *)_unionOfObjectsForKeyPath:(NSString *)keyPath {
  268. assertKeyPathIsNotNested(keyPath);
  269. return translateRLMResultsErrors([&] {
  270. return RLMCollectionValueForKey(_results, keyPath, _realm, *_info);
  271. });
  272. }
  273. - (NSArray *)_distinctUnionOfObjectsForKeyPath:(NSString *)keyPath {
  274. return [NSSet setWithArray:[self _unionOfObjectsForKeyPath:keyPath]].allObjects;
  275. }
  276. - (NSArray *)_unionOfArraysForKeyPath:(NSString *)keyPath {
  277. assertKeyPathIsNotNested(keyPath);
  278. if ([keyPath isEqualToString:@"self"]) {
  279. @throw RLMException(@"self is not a valid key-path for a KVC array collection operator as 'unionOfArrays'.");
  280. }
  281. return translateRLMResultsErrors([&] {
  282. NSMutableArray *flatArray = [NSMutableArray new];
  283. for (id<NSFastEnumeration> array in RLMCollectionValueForKey(_results, keyPath, _realm, *_info)) {
  284. for (id value in array) {
  285. [flatArray addObject:value];
  286. }
  287. }
  288. return flatArray;
  289. });
  290. }
  291. - (NSArray *)_distinctUnionOfArraysForKeyPath:(__unused NSString *)keyPath {
  292. return [NSSet setWithArray:[self _unionOfArraysForKeyPath:keyPath]].allObjects;
  293. }
  294. - (RLMResults *)objectsWhere:(NSString *)predicateFormat, ... {
  295. va_list args;
  296. va_start(args, predicateFormat);
  297. RLMResults *results = [self objectsWhere:predicateFormat args:args];
  298. va_end(args);
  299. return results;
  300. }
  301. - (RLMResults *)objectsWhere:(NSString *)predicateFormat args:(va_list)args {
  302. return [self objectsWithPredicate:[NSPredicate predicateWithFormat:predicateFormat arguments:args]];
  303. }
  304. - (RLMResults *)objectsWithPredicate:(NSPredicate *)predicate {
  305. return translateRLMResultsErrors([&] {
  306. if (_results.get_mode() == Results::Mode::Empty) {
  307. return self;
  308. }
  309. if (_results.get_type() != realm::PropertyType::Object) {
  310. @throw RLMException(@"Querying is currently only implemented for arrays of Realm Objects");
  311. }
  312. auto query = RLMPredicateToQuery(predicate, _info->rlmObjectSchema, _realm.schema, _realm.group);
  313. return [self subresultsWithResults:_results.filter(std::move(query))];
  314. });
  315. }
  316. - (RLMResults *)sortedResultsUsingKeyPath:(NSString *)keyPath ascending:(BOOL)ascending {
  317. return [self sortedResultsUsingDescriptors:@[[RLMSortDescriptor sortDescriptorWithKeyPath:keyPath ascending:ascending]]];
  318. }
  319. - (RLMResults *)sortedResultsUsingDescriptors:(NSArray<RLMSortDescriptor *> *)properties {
  320. if (properties.count == 0) {
  321. return self;
  322. }
  323. return translateRLMResultsErrors([&] {
  324. if (_results.get_mode() == Results::Mode::Empty) {
  325. return self;
  326. }
  327. return [self subresultsWithResults:_results.sort(RLMSortDescriptorsToKeypathArray(properties))];
  328. });
  329. }
  330. - (RLMResults *)distinctResultsUsingKeyPaths:(NSArray<NSString *> *)keyPaths {
  331. for (NSString *keyPath in keyPaths) {
  332. if ([keyPath rangeOfString:@"@"].location != NSNotFound) {
  333. @throw RLMException(@"Cannot distinct on keypath '%@': KVC collection operators are not supported.", keyPath);
  334. }
  335. }
  336. return translateRLMResultsErrors([&] {
  337. if (_results.get_mode() == Results::Mode::Empty) {
  338. return self;
  339. }
  340. std::vector<std::string> keyPathsVector;
  341. for (NSString *keyPath in keyPaths) {
  342. keyPathsVector.push_back(keyPath.UTF8String);
  343. }
  344. return [self subresultsWithResults:_results.distinct(keyPathsVector)];
  345. });
  346. }
  347. - (id)objectAtIndexedSubscript:(NSUInteger)index {
  348. return [self objectAtIndex:index];
  349. }
  350. - (id)aggregate:(NSString *)property method:(util::Optional<Mixed> (Results::*)(size_t))method
  351. methodName:(NSString *)methodName returnNilForEmpty:(BOOL)returnNilForEmpty {
  352. if (_results.get_mode() == Results::Mode::Empty) {
  353. return returnNilForEmpty ? nil : @0;
  354. }
  355. size_t column = 0;
  356. if (self.type == RLMPropertyTypeObject || ![property isEqualToString:@"self"]) {
  357. column = _info->tableColumn(property);
  358. }
  359. auto value = translateRLMResultsErrors([&] { return (_results.*method)(column); }, methodName);
  360. return value ? RLMMixedToObjc(*value) : nil;
  361. }
  362. - (id)minOfProperty:(NSString *)property {
  363. return [self aggregate:property method:&Results::min
  364. methodName:@"minOfProperty" returnNilForEmpty:YES];
  365. }
  366. - (id)maxOfProperty:(NSString *)property {
  367. return [self aggregate:property method:&Results::max
  368. methodName:@"maxOfProperty" returnNilForEmpty:YES];
  369. }
  370. - (id)sumOfProperty:(NSString *)property {
  371. return [self aggregate:property method:&Results::sum
  372. methodName:@"sumOfProperty" returnNilForEmpty:NO];
  373. }
  374. - (id)averageOfProperty:(NSString *)property {
  375. if (_results.get_mode() == Results::Mode::Empty) {
  376. return nil;
  377. }
  378. size_t column = 0;
  379. if (self.type == RLMPropertyTypeObject || ![property isEqualToString:@"self"]) {
  380. column = _info->tableColumn(property);
  381. }
  382. auto value = translateRLMResultsErrors([&] { return _results.average(column); }, @"averageOfProperty");
  383. return value ? @(*value) : nil;
  384. }
  385. - (void)deleteObjectsFromRealm {
  386. if (self.type != RLMPropertyTypeObject) {
  387. @throw RLMException(@"Cannot delete objects from RLMResults<%@>: only RLMObjects can be deleted.",
  388. RLMTypeToString(self.type));
  389. }
  390. return translateRLMResultsErrors([&] {
  391. if (_results.get_mode() == Results::Mode::Table) {
  392. RLMResultsValidateInWriteTransaction(self);
  393. RLMClearTable(*_info);
  394. }
  395. else {
  396. RLMTrackDeletions(_realm, [&] { _results.clear(); });
  397. }
  398. });
  399. }
  400. - (NSString *)description {
  401. return RLMDescriptionWithMaxDepth(@"RLMResults", self, RLMDescriptionMaxDepth);
  402. }
  403. - (realm::TableView)tableView {
  404. return translateRLMResultsErrors([&] { return _results.get_tableview(); });
  405. }
  406. - (RLMFastEnumerator *)fastEnumerator {
  407. return translateRLMResultsErrors([&] {
  408. return [[RLMFastEnumerator alloc] initWithResults:_results collection:self
  409. realm:_realm classInfo:*_info];
  410. });
  411. }
  412. // The compiler complains about the method's argument type not matching due to
  413. // it not having the generic type attached, but it doesn't seem to be possible
  414. // to actually include the generic type
  415. // http://www.openradar.me/radar?id=6135653276319744
  416. #pragma clang diagnostic push
  417. #pragma clang diagnostic ignored "-Wmismatched-parameter-types"
  418. - (RLMNotificationToken *)addNotificationBlock:(void (^)(RLMResults *, RLMCollectionChange *, NSError *))block {
  419. if (!_realm) {
  420. @throw RLMException(@"Linking objects notifications are only supported on managed objects.");
  421. }
  422. [_realm verifyNotificationsAreSupported:true];
  423. return RLMAddNotificationBlock(self, _results, block, true);
  424. }
  425. #pragma clang diagnostic pop
  426. - (BOOL)isAttached
  427. {
  428. return !!_realm;
  429. }
  430. #pragma mark - Thread Confined Protocol Conformance
  431. - (std::unique_ptr<realm::ThreadSafeReferenceBase>)makeThreadSafeReference {
  432. return std::make_unique<realm::ThreadSafeReference<Results>>(_realm->_realm->obtain_thread_safe_reference(_results));
  433. }
  434. - (id)objectiveCMetadata {
  435. return nil;
  436. }
  437. + (instancetype)objectWithThreadSafeReference:(std::unique_ptr<realm::ThreadSafeReferenceBase>)reference
  438. metadata:(__unused id)metadata
  439. realm:(RLMRealm *)realm {
  440. REALM_ASSERT_DEBUG(dynamic_cast<realm::ThreadSafeReference<Results> *>(reference.get()));
  441. auto results_reference = static_cast<realm::ThreadSafeReference<Results> *>(reference.get());
  442. Results results = realm->_realm->resolve_thread_safe_reference(std::move(*results_reference));
  443. return [RLMResults resultsWithObjectInfo:realm->_info[RLMStringDataToNSString(results.get_object_type())]
  444. results:std::move(results)];
  445. }
  446. @end
  447. @implementation RLMLinkingObjects
  448. - (NSString *)description {
  449. return RLMDescriptionWithMaxDepth(@"RLMLinkingObjects", self, RLMDescriptionMaxDepth);
  450. }
  451. @end