RLMObjectStore.mm 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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. static_assert(RLMUpdatePolicyError == static_cast<int>(CreatePolicy::ForceCreate), "");
  39. static_assert(RLMUpdatePolicyUpdateAll == static_cast<int>(CreatePolicy::UpdateAll), "");
  40. static_assert(RLMUpdatePolicyUpdateChanged == static_cast<int>(CreatePolicy::UpdateModified), "");
  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. if (realm->_realm->is_closed()) {
  62. // This message may seem overly specific, but frozen Realms are currently
  63. // the only ones which we outright close.
  64. @throw RLMException(@"Cannot read from a frozen Realm which has been invalidated.");
  65. }
  66. }
  67. static inline void RLMVerifyInWriteTransaction(__unsafe_unretained RLMRealm *const realm) {
  68. RLMVerifyRealmRead(realm);
  69. // if realm is not writable throw
  70. if (!realm.inWriteTransaction) {
  71. @throw RLMException(@"Can only add, remove, or create objects in a Realm in a write transaction - call beginWriteTransaction on an RLMRealm instance first.");
  72. }
  73. }
  74. void RLMInitializeSwiftAccessorGenerics(__unsafe_unretained RLMObjectBase *const object) {
  75. if (!object || !object->_row || !object->_objectSchema->_isSwiftClass) {
  76. return;
  77. }
  78. if (![object isKindOfClass:object->_objectSchema.objectClass]) {
  79. // It can be a different class if it's a dynamic object, and those don't
  80. // require any init here (and would crash since they don't have the ivars)
  81. return;
  82. }
  83. for (RLMProperty *prop in object->_objectSchema.swiftGenericProperties) {
  84. if (prop.type == RLMPropertyTypeLinkingObjects) {
  85. [prop.swiftAccessor initializeObject:(char *)(__bridge void *)object + ivar_getOffset(prop.swiftIvar)
  86. parent:object property:prop];
  87. }
  88. else if (prop.array) {
  89. id ivar = object_getIvar(object, prop.swiftIvar);
  90. RLMArray *array = [[RLMManagedArray alloc] initWithParent:object property:prop];
  91. [ivar set_rlmArray:array];
  92. }
  93. else {
  94. id ivar = object_getIvar(object, prop.swiftIvar);
  95. RLMInitializeManagedOptional(ivar, object, prop);
  96. }
  97. }
  98. }
  99. void RLMVerifyHasPrimaryKey(Class cls) {
  100. RLMObjectSchema *schema = [cls sharedSchema];
  101. if (!schema.primaryKeyProperty) {
  102. NSString *reason = [NSString stringWithFormat:@"'%@' does not have a primary key and can not be updated", schema.className];
  103. @throw [NSException exceptionWithName:@"RLMException" reason:reason userInfo:nil];
  104. }
  105. }
  106. void RLMAddObjectToRealm(__unsafe_unretained RLMObjectBase *const object,
  107. __unsafe_unretained RLMRealm *const realm,
  108. RLMUpdatePolicy updatePolicy) {
  109. RLMVerifyInWriteTransaction(realm);
  110. // verify that object is unmanaged
  111. if (object.invalidated) {
  112. @throw RLMException(@"Adding a deleted or invalidated object to a Realm is not permitted");
  113. }
  114. if (object->_realm) {
  115. if (object->_realm == realm) {
  116. // Adding an object to the Realm it's already manged by is a no-op
  117. return;
  118. }
  119. // for differing realms users must explicitly create the object in the second realm
  120. @throw RLMException(@"Object is already managed by another Realm. Use create instead to copy it into this Realm.");
  121. }
  122. if (object->_observationInfo && object->_observationInfo->hasObservers()) {
  123. @throw RLMException(@"Cannot add an object with observers to a Realm");
  124. }
  125. auto& info = realm->_info[object->_objectSchema.className];
  126. RLMAccessorContext c{info, true};
  127. object->_info = &info;
  128. object->_realm = realm;
  129. object->_objectSchema = info.rlmObjectSchema;
  130. try {
  131. realm::Object::create(c, realm->_realm, *info.objectSchema, (id)object,
  132. static_cast<CreatePolicy>(updatePolicy),
  133. {}, &object->_row);
  134. }
  135. catch (std::exception const& e) {
  136. @throw RLMException(e);
  137. }
  138. object_setClass(object, info.rlmObjectSchema.accessorClass);
  139. RLMInitializeSwiftAccessorGenerics(object);
  140. }
  141. RLMObjectBase *RLMCreateObjectInRealmWithValue(RLMRealm *realm, NSString *className,
  142. id value, RLMUpdatePolicy updatePolicy) {
  143. RLMVerifyInWriteTransaction(realm);
  144. if (updatePolicy != RLMUpdatePolicyError && RLMIsObjectSubclass([value class])) {
  145. RLMObjectBase *obj = value;
  146. if (obj->_realm == realm && [obj->_objectSchema.className isEqualToString:className]) {
  147. // This is a no-op if value is an RLMObject of the same type already backed by the target realm.
  148. return value;
  149. }
  150. }
  151. if (!value || value == NSNull.null) {
  152. @throw RLMException(@"Must provide a non-nil value.");
  153. }
  154. auto& info = realm->_info[className];
  155. if ([value isKindOfClass:[NSArray class]] && [value count] > info.objectSchema->persisted_properties.size()) {
  156. @throw RLMException(@"Invalid array input: more values (%llu) than properties (%llu).",
  157. (unsigned long long)[value count],
  158. (unsigned long long)info.objectSchema->persisted_properties.size());
  159. }
  160. RLMAccessorContext c{info, false};
  161. RLMObjectBase *object = RLMCreateManagedAccessor(info.rlmObjectSchema.accessorClass, &info);
  162. try {
  163. object->_row = realm::Object::create(c, realm->_realm, *info.objectSchema, (id)value,
  164. static_cast<CreatePolicy>(updatePolicy)).obj();
  165. }
  166. catch (std::exception const& e) {
  167. @throw RLMException(e);
  168. }
  169. RLMInitializeSwiftAccessorGenerics(object);
  170. return object;
  171. }
  172. void RLMDeleteObjectFromRealm(__unsafe_unretained RLMObjectBase *const object,
  173. __unsafe_unretained RLMRealm *const realm) {
  174. if (realm != object->_realm) {
  175. @throw RLMException(@"Can only delete an object from the Realm it belongs to.");
  176. }
  177. RLMVerifyInWriteTransaction(object->_realm);
  178. // move last row to row we are deleting
  179. if (object->_row.is_valid()) {
  180. RLMTrackDeletions(realm, ^{
  181. object->_row.remove();
  182. });
  183. }
  184. // set realm to nil
  185. object->_realm = nil;
  186. }
  187. void RLMDeleteAllObjectsFromRealm(RLMRealm *realm) {
  188. RLMVerifyInWriteTransaction(realm);
  189. // clear table for each object schema
  190. for (auto& info : realm->_info) {
  191. RLMClearTable(info.second);
  192. }
  193. }
  194. RLMResults *RLMGetObjects(__unsafe_unretained RLMRealm *const realm,
  195. NSString *objectClassName,
  196. NSPredicate *predicate) {
  197. RLMVerifyRealmRead(realm);
  198. // create view from table and predicate
  199. RLMClassInfo& info = realm->_info[objectClassName];
  200. if (!info.table()) {
  201. // read-only realms may be missing tables since we can't add any
  202. // missing ones on init
  203. return [RLMResults resultsWithObjectInfo:info results:{}];
  204. }
  205. if (predicate) {
  206. realm::Query query = RLMPredicateToQuery(predicate, info.rlmObjectSchema, realm.schema, realm.group);
  207. return [RLMResults resultsWithObjectInfo:info
  208. results:realm::Results(realm->_realm, std::move(query))];
  209. }
  210. return [RLMResults resultsWithObjectInfo:info
  211. results:realm::Results(realm->_realm, info.table())];
  212. }
  213. id RLMGetObject(RLMRealm *realm, NSString *objectClassName, id key) {
  214. RLMVerifyRealmRead(realm);
  215. auto& info = realm->_info[objectClassName];
  216. if (RLMProperty *prop = info.propertyForPrimaryKey()) {
  217. RLMValidateValueForProperty(key, info.rlmObjectSchema, prop);
  218. }
  219. try {
  220. RLMAccessorContext c{info};
  221. auto obj = realm::Object::get_for_primary_key(c, realm->_realm, *info.objectSchema,
  222. key ?: NSNull.null);
  223. if (!obj.is_valid())
  224. return nil;
  225. return RLMCreateObjectAccessor(info, obj.obj());
  226. }
  227. catch (std::exception const& e) {
  228. @throw RLMException(e);
  229. }
  230. }
  231. RLMObjectBase *RLMCreateObjectAccessor(RLMClassInfo& info, int64_t key) {
  232. return RLMCreateObjectAccessor(info, info.table()->get_object(realm::ObjKey(key)));
  233. }
  234. // Create accessor and register with realm
  235. RLMObjectBase *RLMCreateObjectAccessor(RLMClassInfo& info, realm::Obj&& obj) {
  236. RLMObjectBase *accessor = RLMCreateManagedAccessor(info.rlmObjectSchema.accessorClass, &info);
  237. accessor->_row = std::move(obj);
  238. RLMInitializeSwiftAccessorGenerics(accessor);
  239. return accessor;
  240. }