added iOS source code
[wl-app.git] / iOS / Pods / Realm / Realm / RLMObjectStore.mm
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
19 #import "RLMObjectStore.h"
20
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"
33 #import "RLMUtil.hpp"
34
35 #import "object_store.hpp"
36 #import "results.hpp"
37 #import "shared_realm.hpp"
38
39 #import <objc/message.h>
40
41 using namespace realm;
42
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;
47
48     char className[bufferSize] = "RLM:Managed ";
49     char *const start = className + strlen(className);
50
51     for (RLMObjectSchema *objectSchema in schema.objectSchema) {
52         if (objectSchema.accessorClass != objectSchema.objectClass) {
53             continue;
54         }
55
56         static unsigned long long count = 0;
57         sprintf(start, "%llu %s", count++, objectSchema.className.UTF8String);
58         objectSchema.accessorClass = RLMManagedAccessorClassForObjectClass(objectSchema.objectClass, objectSchema, className);
59     }
60 }
61
62 static inline void RLMVerifyRealmRead(__unsafe_unretained RLMRealm *const realm) {
63     if (!realm) {
64         @throw RLMException(@"Realm must not be nil");
65     }
66     [realm verifyThread];
67 }
68
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.");
74     }
75 }
76
77 void RLMInitializeSwiftAccessorGenerics(__unsafe_unretained RLMObjectBase *const object) {
78     if (!object || !object->_row || !object->_objectSchema->_isSwiftClass) {
79         return;
80     }
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)
84         return;
85     }
86
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];
92         }
93         else if (prop.array) {
94             RLMArray *array = [[RLMManagedArray alloc] initWithParent:object property:prop];
95             [object_getIvar(object, prop.swiftIvar) set_rlmArray:array];
96         }
97         else {
98             RLMOptionalBase *optional = object_getIvar(object, prop.swiftIvar);
99             optional.property = prop;
100             optional.object = object;
101         }
102     }
103 }
104
105 void RLMAddObjectToRealm(__unsafe_unretained RLMObjectBase *const object,
106                          __unsafe_unretained RLMRealm *const realm,
107                          bool createOrUpdate) {
108     RLMVerifyInWriteTransaction(realm);
109
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
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;
131     try {
132         realm::Object::create(c, realm->_realm, *info.objectSchema, (id)object,
133                               createOrUpdate, &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
142 RLMObjectBase *RLMCreateObjectInRealmWithValue(RLMRealm *realm, NSString *className,
143                                                id value, bool createOrUpdate = false) {
144     RLMVerifyInWriteTransaction(realm);
145
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.
150             return value;
151         }
152     }
153
154     if (!value || value == NSNull.null) {
155         @throw RLMException(@"Must provide a non-nil value.");
156     }
157
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());
163     }
164
165     RLMAccessorContext c{realm, info, false};
166     RLMObjectBase *object = RLMCreateManagedAccessor(info.rlmObjectSchema.accessorClass, realm, &info);
167     try {
168         object->_row = realm::Object::create(c, realm->_realm, *info.objectSchema,
169                                              (id)value, createOrUpdate).row();
170     }
171     catch (std::exception const& e) {
172         @throw RLMException(e);
173     }
174     RLMInitializeSwiftAccessorGenerics(object);
175     return object;
176 }
177
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.");
182     }
183
184     RLMVerifyInWriteTransaction(object->_realm);
185
186     // move last row to row we are deleting
187     if (object->_row.is_attached()) {
188         RLMTrackDeletions(realm, ^{
189             object->_row.move_last_over();
190         });
191     }
192
193     // set realm to nil
194     object->_realm = nil;
195 }
196
197 void RLMDeleteAllObjectsFromRealm(RLMRealm *realm) {
198     RLMVerifyInWriteTransaction(realm);
199
200     // clear table for each object schema
201     for (auto& info : realm->_info) {
202         RLMClearTable(info.second);
203     }
204 }
205
206 RLMResults *RLMGetObjects(__unsafe_unretained RLMRealm *const realm,
207                           NSString *objectClassName,
208                           NSPredicate *predicate) {
209     RLMVerifyRealmRead(realm);
210
211     // create view from table and predicate
212     RLMClassInfo& info = realm->_info[objectClassName];
213     if (!info.table()) {
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:{}];
217     }
218
219     if (predicate) {
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))];
223     }
224
225     return [RLMResults resultsWithObjectInfo:info
226                                      results:realm::Results(realm->_realm, *info.table())];
227 }
228
229 id RLMGetObject(RLMRealm *realm, NSString *objectClassName, id key) {
230     RLMVerifyRealmRead(realm);
231
232     RLMAccessorContext *c = nullptr;
233     auto& info = realm->_info[objectClassName];
234     if (RLMProperty *prop = info.propertyForPrimaryKey()) {
235         RLMValidateValueForProperty(key, info.rlmObjectSchema, prop);
236     }
237     try {
238         auto obj = realm::Object::get_for_primary_key(*c, realm->_realm, *info.objectSchema,
239                                                       key ?: NSNull.null);
240         if (!obj.is_valid())
241             return nil;
242         return RLMCreateObjectAccessor(realm, info, obj.row());
243     }
244     catch (std::exception const& e) {
245         @throw RLMException(e);
246     }
247 }
248
249 RLMObjectBase *RLMCreateObjectAccessor(__unsafe_unretained RLMRealm *const realm,
250                                        RLMClassInfo& info,
251                                        NSUInteger index) {
252     return RLMCreateObjectAccessor(realm, info, (*info.table())[index]);
253 }
254
255 // Create accessor and register with realm
256 RLMObjectBase *RLMCreateObjectAccessor(__unsafe_unretained RLMRealm *const realm,
257                                        RLMClassInfo& info,
258                                        realm::RowExpr row) {
259     RLMObjectBase *accessor = RLMCreateManagedAccessor(info.rlmObjectSchema.accessorClass, realm, &info);
260     accessor->_row = row;
261     RLMInitializeSwiftAccessorGenerics(accessor);
262     return accessor;
263 }