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