RLMObjectStore.mm 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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 "RLMObjectStore.h"
  19. #import "RLMAccessor.hpp"
  20. #import "RLMArray_Private.hpp"
  21. #import "RLMListBase.h"
  22. #import "RLMObservation.hpp"
  23. #import "RLMObject_Private.hpp"
  24. #import "RLMObjectSchema_Private.hpp"
  25. #import "RLMOptionalBase.h"
  26. #import "RLMProperty_Private.h"
  27. #import "RLMQueryUtil.hpp"
  28. #import "RLMRealm_Private.hpp"
  29. #import "RLMSchema_Private.h"
  30. #import "RLMSwiftSupport.h"
  31. #import "RLMUtil.hpp"
  32. #import "object_store.hpp"
  33. #import "results.hpp"
  34. #import "shared_realm.hpp"
  35. #import <realm/group.hpp>
  36. #import <objc/message.h>
  37. using namespace realm;
  38. @interface LinkingObjectsBase : NSObject
  39. @property (nonatomic, nullable) RLMWeakObjectHandle *object;
  40. @property (nonatomic, nullable) RLMProperty *property;
  41. @end
  42. void RLMRealmCreateAccessors(RLMSchema *schema) {
  43. const size_t bufferSize = sizeof("RLM:Managed ") // includes null terminator
  44. + std::numeric_limits<unsigned long long>::digits10
  45. + realm::Group::max_table_name_length;
  46. char className[bufferSize] = "RLM:Managed ";
  47. char *const start = className + strlen(className);
  48. for (RLMObjectSchema *objectSchema in schema.objectSchema) {
  49. if (objectSchema.accessorClass != objectSchema.objectClass) {
  50. continue;
  51. }
  52. static unsigned long long count = 0;
  53. sprintf(start, "%llu %s", count++, objectSchema.className.UTF8String);
  54. objectSchema.accessorClass = RLMManagedAccessorClassForObjectClass(objectSchema.objectClass, objectSchema, className);
  55. }
  56. }
  57. static inline void RLMVerifyRealmRead(__unsafe_unretained RLMRealm *const realm) {
  58. if (!realm) {
  59. @throw RLMException(@"Realm must not be nil");
  60. }
  61. [realm verifyThread];
  62. }
  63. static inline void RLMVerifyInWriteTransaction(__unsafe_unretained RLMRealm *const realm) {
  64. RLMVerifyRealmRead(realm);
  65. // if realm is not writable throw
  66. if (!realm.inWriteTransaction) {
  67. @throw RLMException(@"Can only add, remove, or create objects in a Realm in a write transaction - call beginWriteTransaction on an RLMRealm instance first.");
  68. }
  69. }
  70. void RLMInitializeSwiftAccessorGenerics(__unsafe_unretained RLMObjectBase *const object) {
  71. if (!object || !object->_row || !object->_objectSchema->_isSwiftClass) {
  72. return;
  73. }
  74. if (![object isKindOfClass:object->_objectSchema.objectClass]) {
  75. // It can be a different class if it's a dynamic object, and those don't
  76. // require any init here (and would crash since they don't have the ivars)
  77. return;
  78. }
  79. for (RLMProperty *prop in object->_objectSchema.swiftGenericProperties) {
  80. if (prop.swiftIvar == RLMDummySwiftIvar) {
  81. // FIXME: this should actually be an error as it's the result of an
  82. // invalid object definition, but that's a breaking change so
  83. // instead preserve the old behavior until the next major version bump
  84. // https://github.com/realm/realm-cocoa/issues/5784
  85. continue;
  86. }
  87. id ivar = object_getIvar(object, prop.swiftIvar);
  88. if (prop.type == RLMPropertyTypeLinkingObjects) {
  89. [ivar setObject:(id)[[RLMWeakObjectHandle alloc] initWithObject:object]];
  90. [ivar setProperty:prop];
  91. }
  92. else if (prop.array) {
  93. RLMArray *array = [[RLMManagedArray alloc] initWithParent:object property:prop];
  94. [ivar set_rlmArray:array];
  95. }
  96. else {
  97. RLMInitializeManagedOptional(ivar, object, prop);
  98. }
  99. }
  100. }
  101. void RLMVerifyHasPrimaryKey(Class cls) {
  102. RLMObjectSchema *schema = [cls sharedSchema];
  103. if (!schema.primaryKeyProperty) {
  104. NSString *reason = [NSString stringWithFormat:@"'%@' does not have a primary key and can not be updated", schema.className];
  105. @throw [NSException exceptionWithName:@"RLMException" reason:reason userInfo:nil];
  106. }
  107. }
  108. void RLMAddObjectToRealm(__unsafe_unretained RLMObjectBase *const object,
  109. __unsafe_unretained RLMRealm *const realm,
  110. RLMUpdatePolicy updatePolicy) {
  111. RLMVerifyInWriteTransaction(realm);
  112. // verify that object is unmanaged
  113. if (object.invalidated) {
  114. @throw RLMException(@"Adding a deleted or invalidated object to a Realm is not permitted");
  115. }
  116. if (object->_realm) {
  117. if (object->_realm == realm) {
  118. // Adding an object to the Realm it's already manged by is a no-op
  119. return;
  120. }
  121. // for differing realms users must explicitly create the object in the second realm
  122. @throw RLMException(@"Object is already managed by another Realm. Use create instead to copy it into this Realm.");
  123. }
  124. if (object->_observationInfo && object->_observationInfo->hasObservers()) {
  125. @throw RLMException(@"Cannot add an object with observers to a Realm");
  126. }
  127. auto& info = realm->_info[object->_objectSchema.className];
  128. RLMAccessorContext c{realm, info, true};
  129. object->_info = &info;
  130. object->_realm = realm;
  131. object->_objectSchema = info.rlmObjectSchema;
  132. try {
  133. realm::Object::create(c, realm->_realm, *info.objectSchema, (id)object,
  134. updatePolicy != RLMUpdatePolicyError,
  135. updatePolicy == RLMUpdatePolicyUpdateChanged,
  136. -1, &object->_row);
  137. }
  138. catch (std::exception const& e) {
  139. @throw RLMException(e);
  140. }
  141. object_setClass(object, info.rlmObjectSchema.accessorClass);
  142. RLMInitializeSwiftAccessorGenerics(object);
  143. }
  144. RLMObjectBase *RLMCreateObjectInRealmWithValue(RLMRealm *realm, NSString *className,
  145. id value, RLMUpdatePolicy updatePolicy) {
  146. RLMVerifyInWriteTransaction(realm);
  147. if (updatePolicy != RLMUpdatePolicyError && RLMIsObjectSubclass([value class])) {
  148. RLMObjectBase *obj = value;
  149. if (obj->_realm == realm && [obj->_objectSchema.className isEqualToString:className]) {
  150. // This is a no-op if value is an RLMObject of the same type already backed by the target realm.
  151. return value;
  152. }
  153. }
  154. if (!value || value == NSNull.null) {
  155. @throw RLMException(@"Must provide a non-nil value.");
  156. }
  157. auto& info = realm->_info[className];
  158. if ([value isKindOfClass:[NSArray class]] && [value count] > info.objectSchema->persisted_properties.size()) {
  159. @throw RLMException(@"Invalid array input: more values (%llu) than properties (%llu).",
  160. (unsigned long long)[value count],
  161. (unsigned long long)info.objectSchema->persisted_properties.size());
  162. }
  163. RLMAccessorContext c{realm, info, false};
  164. RLMObjectBase *object = RLMCreateManagedAccessor(info.rlmObjectSchema.accessorClass, realm, &info);
  165. try {
  166. object->_row = realm::Object::create(c, realm->_realm, *info.objectSchema,
  167. (id)value, updatePolicy != RLMUpdatePolicyError,
  168. updatePolicy == RLMUpdatePolicyUpdateChanged).row();
  169. }
  170. catch (std::exception const& e) {
  171. @throw RLMException(e);
  172. }
  173. RLMInitializeSwiftAccessorGenerics(object);
  174. return object;
  175. }
  176. void RLMDeleteObjectFromRealm(__unsafe_unretained RLMObjectBase *const object,
  177. __unsafe_unretained RLMRealm *const realm) {
  178. if (realm != object->_realm) {
  179. @throw RLMException(@"Can only delete an object from the Realm it belongs to.");
  180. }
  181. RLMVerifyInWriteTransaction(object->_realm);
  182. // move last row to row we are deleting
  183. if (object->_row.is_attached()) {
  184. RLMTrackDeletions(realm, ^{
  185. object->_row.move_last_over();
  186. });
  187. }
  188. // set realm to nil
  189. object->_realm = nil;
  190. }
  191. void RLMDeleteAllObjectsFromRealm(RLMRealm *realm) {
  192. RLMVerifyInWriteTransaction(realm);
  193. // clear table for each object schema
  194. for (auto& info : realm->_info) {
  195. RLMClearTable(info.second);
  196. }
  197. }
  198. RLMResults *RLMGetObjects(__unsafe_unretained RLMRealm *const realm,
  199. NSString *objectClassName,
  200. NSPredicate *predicate) {
  201. RLMVerifyRealmRead(realm);
  202. // create view from table and predicate
  203. RLMClassInfo& info = realm->_info[objectClassName];
  204. if (!info.table()) {
  205. // read-only realms may be missing tables since we can't add any
  206. // missing ones on init
  207. return [RLMResults resultsWithObjectInfo:info results:{}];
  208. }
  209. if (predicate) {
  210. realm::Query query = RLMPredicateToQuery(predicate, info.rlmObjectSchema, realm.schema, realm.group);
  211. return [RLMResults resultsWithObjectInfo:info
  212. results:realm::Results(realm->_realm, std::move(query))];
  213. }
  214. return [RLMResults resultsWithObjectInfo:info
  215. results:realm::Results(realm->_realm, *info.table())];
  216. }
  217. id RLMGetObject(RLMRealm *realm, NSString *objectClassName, id key) {
  218. RLMVerifyRealmRead(realm);
  219. auto& info = realm->_info[objectClassName];
  220. if (RLMProperty *prop = info.propertyForPrimaryKey()) {
  221. RLMValidateValueForProperty(key, info.rlmObjectSchema, prop);
  222. }
  223. try {
  224. RLMAccessorContext c{realm, info};
  225. auto obj = realm::Object::get_for_primary_key(c, realm->_realm, *info.objectSchema,
  226. key ?: NSNull.null);
  227. if (!obj.is_valid())
  228. return nil;
  229. return RLMCreateObjectAccessor(realm, info, obj.row());
  230. }
  231. catch (std::exception const& e) {
  232. @throw RLMException(e);
  233. }
  234. }
  235. RLMObjectBase *RLMCreateObjectAccessor(__unsafe_unretained RLMRealm *const realm,
  236. RLMClassInfo& info,
  237. NSUInteger index) {
  238. return RLMCreateObjectAccessor(realm, info, (*info.table())[index]);
  239. }
  240. // Create accessor and register with realm
  241. RLMObjectBase *RLMCreateObjectAccessor(__unsafe_unretained RLMRealm *const realm,
  242. RLMClassInfo& info,
  243. realm::RowExpr row) {
  244. RLMObjectBase *accessor = RLMCreateManagedAccessor(info.rlmObjectSchema.accessorClass, realm, &info);
  245. accessor->_row = row;
  246. RLMInitializeSwiftAccessorGenerics(accessor);
  247. return accessor;
  248. }