1 ////////////////////////////////////////////////////////////////////////////
3 // Copyright 2014 Realm Inc.
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
9 // http://www.apache.org/licenses/LICENSE-2.0
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.
17 ////////////////////////////////////////////////////////////////////////////
19 #import "RLMObjectStore.h"
21 #import "RLMAccessor.hpp"
22 #import "RLMArray_Private.hpp"
23 #import "RLMListBase.h"
24 #import "RLMObservation.hpp"
25 #import "RLMObject_Private.hpp"
26 #import "RLMObjectSchema_Private.hpp"
27 #import "RLMOptionalBase.h"
28 #import "RLMProperty_Private.h"
29 #import "RLMQueryUtil.hpp"
30 #import "RLMRealm_Private.hpp"
31 #import "RLMSchema_Private.h"
32 #import "RLMSwiftSupport.h"
35 #import "object_store.hpp"
37 #import "shared_realm.hpp"
39 #import <objc/message.h>
41 using namespace realm;
43 void RLMRealmCreateAccessors(RLMSchema *schema) {
44 const size_t bufferSize = sizeof("RLM:Managed ") // includes null terminator
45 + std::numeric_limits<unsigned long long>::digits10
46 + realm::Group::max_table_name_length;
48 char className[bufferSize] = "RLM:Managed ";
49 char *const start = className + strlen(className);
51 for (RLMObjectSchema *objectSchema in schema.objectSchema) {
52 if (objectSchema.accessorClass != objectSchema.objectClass) {
56 static unsigned long long count = 0;
57 sprintf(start, "%llu %s", count++, objectSchema.className.UTF8String);
58 objectSchema.accessorClass = RLMManagedAccessorClassForObjectClass(objectSchema.objectClass, objectSchema, className);
62 static inline void RLMVerifyRealmRead(__unsafe_unretained RLMRealm *const realm) {
64 @throw RLMException(@"Realm must not be nil");
69 static inline void RLMVerifyInWriteTransaction(__unsafe_unretained RLMRealm *const realm) {
70 RLMVerifyRealmRead(realm);
71 // if realm is not writable throw
72 if (!realm.inWriteTransaction) {
73 @throw RLMException(@"Can only add, remove, or create objects in a Realm in a write transaction - call beginWriteTransaction on an RLMRealm instance first.");
77 void RLMInitializeSwiftAccessorGenerics(__unsafe_unretained RLMObjectBase *const object) {
78 if (!object || !object->_row || !object->_objectSchema->_isSwiftClass) {
81 if (![object isKindOfClass:object->_objectSchema.objectClass]) {
82 // It can be a different class if it's a dynamic object, and those don't
83 // require any init here (and would crash since they don't have the ivars)
87 for (RLMProperty *prop in object->_objectSchema.swiftGenericProperties) {
88 if (prop.type == RLMPropertyTypeLinkingObjects) {
89 id linkingObjects = object_getIvar(object, prop.swiftIvar);
90 [linkingObjects setObject:(id)[[RLMWeakObjectHandle alloc] initWithObject:object]];
91 [linkingObjects setProperty:prop];
93 else if (prop.array) {
94 RLMArray *array = [[RLMManagedArray alloc] initWithParent:object property:prop];
95 [object_getIvar(object, prop.swiftIvar) set_rlmArray:array];
98 RLMOptionalBase *optional = object_getIvar(object, prop.swiftIvar);
99 optional.property = prop;
100 optional.object = object;
105 void RLMAddObjectToRealm(__unsafe_unretained RLMObjectBase *const object,
106 __unsafe_unretained RLMRealm *const realm,
107 bool createOrUpdate) {
108 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");
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
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.");
122 if (object->_observationInfo && object->_observationInfo->hasObservers()) {
123 @throw RLMException(@"Cannot add an object with observers to a Realm");
126 auto& info = realm->_info[object->_objectSchema.className];
127 RLMAccessorContext c{realm, info, true};
128 object->_info = &info;
129 object->_realm = realm;
130 object->_objectSchema = info.rlmObjectSchema;
132 realm::Object::create(c, realm->_realm, *info.objectSchema, (id)object,
133 createOrUpdate, &object->_row);
135 catch (std::exception const& e) {
136 @throw RLMException(e);
138 object_setClass(object, info.rlmObjectSchema.accessorClass);
139 RLMInitializeSwiftAccessorGenerics(object);
142 RLMObjectBase *RLMCreateObjectInRealmWithValue(RLMRealm *realm, NSString *className,
143 id value, bool createOrUpdate = false) {
144 RLMVerifyInWriteTransaction(realm);
146 if (createOrUpdate && RLMIsObjectSubclass([value class])) {
147 RLMObjectBase *obj = value;
148 if (obj->_realm == realm && [obj->_objectSchema.className isEqualToString:className]) {
149 // This is a no-op if value is an RLMObject of the same type already backed by the target realm.
154 if (!value || value == NSNull.null) {
155 @throw RLMException(@"Must provide a non-nil value.");
158 auto& info = realm->_info[className];
159 if ([value isKindOfClass:[NSArray class]] && [value count] > info.objectSchema->persisted_properties.size()) {
160 @throw RLMException(@"Invalid array input: more values (%llu) than properties (%llu).",
161 (unsigned long long)[value count],
162 (unsigned long long)info.objectSchema->persisted_properties.size());
165 RLMAccessorContext c{realm, info, false};
166 RLMObjectBase *object = RLMCreateManagedAccessor(info.rlmObjectSchema.accessorClass, realm, &info);
168 object->_row = realm::Object::create(c, realm->_realm, *info.objectSchema,
169 (id)value, createOrUpdate).row();
171 catch (std::exception const& e) {
172 @throw RLMException(e);
174 RLMInitializeSwiftAccessorGenerics(object);
178 void RLMDeleteObjectFromRealm(__unsafe_unretained RLMObjectBase *const object,
179 __unsafe_unretained RLMRealm *const realm) {
180 if (realm != object->_realm) {
181 @throw RLMException(@"Can only delete an object from the Realm it belongs to.");
184 RLMVerifyInWriteTransaction(object->_realm);
186 // move last row to row we are deleting
187 if (object->_row.is_attached()) {
188 RLMTrackDeletions(realm, ^{
189 object->_row.move_last_over();
194 object->_realm = nil;
197 void RLMDeleteAllObjectsFromRealm(RLMRealm *realm) {
198 RLMVerifyInWriteTransaction(realm);
200 // clear table for each object schema
201 for (auto& info : realm->_info) {
202 RLMClearTable(info.second);
206 RLMResults *RLMGetObjects(__unsafe_unretained RLMRealm *const realm,
207 NSString *objectClassName,
208 NSPredicate *predicate) {
209 RLMVerifyRealmRead(realm);
211 // create view from table and predicate
212 RLMClassInfo& info = realm->_info[objectClassName];
214 // read-only realms may be missing tables since we can't add any
215 // missing ones on init
216 return [RLMResults resultsWithObjectInfo:info results:{}];
220 realm::Query query = RLMPredicateToQuery(predicate, info.rlmObjectSchema, realm.schema, realm.group);
221 return [RLMResults resultsWithObjectInfo:info
222 results:realm::Results(realm->_realm, std::move(query))];
225 return [RLMResults resultsWithObjectInfo:info
226 results:realm::Results(realm->_realm, *info.table())];
229 id RLMGetObject(RLMRealm *realm, NSString *objectClassName, id key) {
230 RLMVerifyRealmRead(realm);
232 RLMAccessorContext *c = nullptr;
233 auto& info = realm->_info[objectClassName];
234 if (RLMProperty *prop = info.propertyForPrimaryKey()) {
235 RLMValidateValueForProperty(key, info.rlmObjectSchema, prop);
238 auto obj = realm::Object::get_for_primary_key(*c, realm->_realm, *info.objectSchema,
242 return RLMCreateObjectAccessor(realm, info, obj.row());
244 catch (std::exception const& e) {
245 @throw RLMException(e);
249 RLMObjectBase *RLMCreateObjectAccessor(__unsafe_unretained RLMRealm *const realm,
252 return RLMCreateObjectAccessor(realm, info, (*info.table())[index]);
255 // Create accessor and register with realm
256 RLMObjectBase *RLMCreateObjectAccessor(__unsafe_unretained RLMRealm *const realm,
258 realm::RowExpr row) {
259 RLMObjectBase *accessor = RLMCreateManagedAccessor(info.rlmObjectSchema.accessorClass, realm, &info);
260 accessor->_row = row;
261 RLMInitializeSwiftAccessorGenerics(accessor);