RLMObjectStore.mm 10 KB

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