/
MongoDBCollection.m
327 lines (282 loc) · 13.3 KB
/
MongoDBCollection.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
//
// MongoDBCollection.m
// ObjCMongoDB
//
// Copyright 2012 Paul Melnikow and other contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import "MongoDBCollection.h"
#import "ObjCMongoDB.h"
#import "mongo.h"
#import "BSON_Helper.h"
#import "Mongo_PrivateInterfaces.h"
#import "Mongo_Helper.h"
@interface MongoDBCollection ()
@property (copy, nonatomic) NSString * privateFullyQualifiedName;
@end
@implementation MongoDBCollection
#pragma mark - Initialization
- (id) initWithConnection:(MongoConnection *) connectionParam fullyQualifiedName:(NSString *) nameParam {
if (self = [super init]) {
self.connection = connectionParam;
self.fullyQualifiedName = nameParam;
}
return self;
}
- (void) dealloc {
maybe_release(_connection);
maybe_release(_privateFullyQualifiedName);
maybe_release(_databaseName);
maybe_release(_namespaceName);
super_dealloc;
}
+ (MongoDBCollection *) collectionWithConnection:(MongoConnection *) connection
fullyQualifiedName:(NSString *) name {
MongoDBCollection *result = [[self alloc] initWithConnection:connection fullyQualifiedName:name];
maybe_autorelease_and_return(result);
}
- (void) setFullyQualifiedName:(NSString *) value {
self.privateFullyQualifiedName = value;
NSRange firstDot = [value rangeOfString:@"."];
if (NSNotFound == firstDot.location)
[NSException raise:NSInvalidArgumentException
format:@"Collection name must have a database prefix – mydb.mycollection, or mydb.somecollections.mycollection"];
self.databaseName = [value substringToIndex:firstDot.location];
self.namespaceName = [value substringFromIndex:1+firstDot.location];
}
- (NSString *) fullyQualifiedName {
return self.privateFullyQualifiedName;
}
#pragma mark - Insert
- (BOOL) insertDocument:(BSONDocument *) document
writeConcern:(MongoWriteConcern *) writeConcern
error:(NSError * __autoreleasing *) error {
if (MONGO_OK == mongo_insert(self.connection.connValue,
self.fullyQualifiedName.bsonString,
document.bsonValue,
[[self _coalesceWriteConcern:writeConcern] nativeWriteConcern]))
return YES;
else
set_error_and_return_NO;
}
- (BOOL) insertDictionary:(NSDictionary *) dictionary
writeConcern:(MongoWriteConcern *) writeConcern
error:(NSError * __autoreleasing *) error {
return [self insertDocument:[dictionary BSONDocument] writeConcern:writeConcern error:error];
}
- (BOOL) insertObject:(id) object
writeConcern:(MongoWriteConcern *) writeConcern
error:(NSError * __autoreleasing *) error {
return [self insertDocument:[BSONEncoder documentForObject:object] writeConcern:writeConcern error:error];
}
- (BOOL) insertDocuments:(NSArray *) documentArray
continueOnError:(BOOL) continueOnError
writeConcern:(MongoWriteConcern *) writeConcern
error:(NSError * __autoreleasing *) error {
if (documentArray.count > INT_MAX)
[NSException raise:NSInvalidArgumentException
format:@"That's a lot of documents! Keep it to %i",
INT_MAX];
int documentsToInsert = (int) documentArray.count;
const bson *bsonArray[documentsToInsert];
const bson **current = bsonArray;
for (__strong BSONDocument *document in documentArray) {
if(![document isKindOfClass:[BSONDocument class]]) {
document = [BSONEncoder documentForObject:document];
}
*current++ = document.bsonValue;
}
int flags = continueOnError ? MONGO_CONTINUE_ON_ERROR : 0;
if (MONGO_OK == mongo_insert_batch(self.connection.connValue,
self.fullyQualifiedName.bsonString,
bsonArray,
documentsToInsert,
[[self _coalesceWriteConcern:writeConcern] nativeWriteConcern],
flags))
return YES;
else
set_error_and_return_NO;
}
#pragma mark - Update
- (BOOL) updateWithRequest:(MongoUpdateRequest *) updateRequest
error:(NSError * __autoreleasing *) error {
if (MONGO_OK == mongo_update(self.connection.connValue,
self.fullyQualifiedName.bsonString,
updateRequest.conditionDocumentValue.bsonValue,
updateRequest.operationDocumentValue.bsonValue,
updateRequest.flags,
[[self _coalesceWriteConcern:updateRequest.writeConcern] nativeWriteConcern]))
return YES;
else
set_error_and_return_NO;
}
#pragma mark - Remove
- (BOOL) removeWithPredicate:(MongoPredicate *) predicate
writeConcern:(MongoWriteConcern *) writeConcern
error:(NSError * __autoreleasing *) error {
if (!predicate)
[NSException raise:NSInvalidArgumentException
format:@"For safety, remove with nil predicate is not allowed - use removeAllWithWriteConcern:error: instead"];
return [self _removeWithCond:predicate.BSONDocument
writeConcern:writeConcern
error:error];
}
- (BOOL) removeAllWithWriteConcern:(MongoWriteConcern *) writeConcern
error:(NSError * __autoreleasing *) error {
return [self _removeWithCond:[BSONDocument document]
writeConcern:writeConcern
error:error];
}
- (BOOL) _removeWithCond:(BSONDocument *) cond
writeConcern:(MongoWriteConcern *) writeConcern
error:(NSError * __autoreleasing *) error {
int result = mongo_remove(self.connection.connValue,
self.fullyQualifiedName.bsonString,
cond.bsonValue,
[[self _coalesceWriteConcern:writeConcern] nativeWriteConcern]);
if (MONGO_OK == result)
return YES;
else
set_error_and_return_NO;
}
#pragma mark - Find
- (NSArray *) findWithRequest:(MongoFindRequest *) findRequest
error:(NSError * __autoreleasing *) error {
return [[self cursorForFindRequest:findRequest error:error] allObjects];
}
- (MongoCursor *) cursorForFindRequest:(MongoFindRequest *) findRequest
error:(NSError * __autoreleasing *) error {
mongo_cursor *cursor = mongo_find(self.connection.connValue,
self.fullyQualifiedName.bsonString,
findRequest.queryDocument.bsonValue,
findRequest.fieldsDocument.bsonValue,
findRequest.limitResults,
findRequest.skipResults,
findRequest.options);
if (!cursor) set_error_and_return_nil;
return [MongoCursor cursorWithNativeCursor:cursor];
}
- (BSONDocument *) findOneWithRequest:(MongoFindRequest *) findRequest
error:(NSError * __autoreleasing *) error {
bson *newBson = bson_alloc();
int result = mongo_find_one(self.connection.connValue,
self.fullyQualifiedName.bsonString,
findRequest.queryDocument.bsonValue,
findRequest.fieldsDocument.bsonValue,
newBson);
if (BSON_OK != result) {
bson_dealloc(newBson);
set_error_and_return_nil;
}
// newBson contains a copy of the data
return [BSONDocument documentWithNativeDocument:newBson dependentOn:nil];
}
- (NSArray *) findWithPredicate:(MongoPredicate *) predicate
error:(NSError * __autoreleasing *) error {
return [[self cursorForFindWithPredicate:predicate error:error] allObjects];
}
- (MongoCursor *) cursorForFindWithPredicate:(MongoPredicate *) predicate
error:(NSError * __autoreleasing *) error {
return [self cursorForFindRequest:[MongoFindRequest findRequestWithPredicate:predicate] error:error];
}
- (BSONDocument *) findOneWithPredicate:(MongoPredicate *) predicate
error:(NSError * __autoreleasing *) error {
return [self findOneWithRequest:[MongoFindRequest findRequestWithPredicate:predicate] error:error];
}
- (NSArray *) findAllWithError:(NSError * __autoreleasing *) error {
return [[self cursorForFindAllWithError:error] allObjects];
}
- (MongoCursor *) cursorForFindAllWithError:(NSError * __autoreleasing *) error {
return [self cursorForFindWithPredicate:[MongoPredicate predicate] error:error];
}
- (BSONDocument *) findOneWithError:(NSError * __autoreleasing *) error {
return [self findOneWithPredicate:[MongoPredicate predicate] error:error];
}
- (NSUInteger) countWithPredicate:(MongoPredicate *) predicate
error:(NSError * __autoreleasing *) error {
if (!predicate) predicate = [MongoPredicate predicate];
NSUInteger result = mongo_count(self.connection.connValue,
self.databaseName.bsonString, self.namespaceName.bsonString,
predicate.BSONDocument.bsonValue);
if (BSON_ERROR == result) set_error_and_return_BSON_ERROR;
return result;
}
#pragma mark - Create indexes
- (NSArray *) allIndexesWithError:(NSError * __autoreleasing *) error {
MongoDBCollection *indexesCollection =
[self.connection collectionWithName:[self.databaseName stringByAppendingString:@".system.indexes"]];
MongoKeyedPredicate *predicate = [MongoKeyedPredicate predicate];
[predicate keyPath:@"ns" matches:self.fullyQualifiedName];
NSArray *indexDocuments = [indexesCollection findWithPredicate:predicate error:error];
if (indexDocuments) {
NSMutableArray *result = [NSMutableArray array];
for (BSONDocument *indexDocument in indexDocuments)
[result addObject:[MongoIndex indexWithDictionary:[indexDocument dictionaryValue]]];
return result;
} else
return nil;
}
- (BOOL) ensureIndex:(MongoMutableIndex *) index error:(NSError * __autoreleasing *) error {
if (!index) [NSException raise:NSInvalidArgumentException format:@"Nil parameter"];
if (!index.fields.allKeys.count) [NSException raise:NSInvalidArgumentException format:@"No fields in index"];
bson *tempBson = bson_alloc();
int result = mongo_create_index(self.connection.connValue,
self.fullyQualifiedName.bsonString,
index.fields.BSONDocument.bsonValue,
index.name ? index.name.bsonString : NULL,
index.options,
tempBson);
// BSON object is destroyed and deallocated when document is autoreleased
NSDictionary *resultDict = [[BSONDocument documentWithNativeDocument:tempBson dependentOn:nil] dictionaryValue];
if (MONGO_OK != result) {
if (error) {
NSString *message = [resultDict objectForKey:@"err"];
*error = [NSError errorWithDomain:MongoDBErrorDomain
code:MongoCreateIndexError
userInfo:message ? @{ NSLocalizedDescriptionKey : message } : nil];
}
return NO;
}
return YES;
}
#pragma mark - Administration
// Handle commands of the form { "commandName" : "namespace.collection" }
- (NSDictionary *) _runCommandWithName:(NSString *) commandName
error:(NSError * __autoreleasing *) outError {
if (commandName == nil) [NSException raise:NSInvalidArgumentException format:@"Nil parameter"];
return [self.connection runCommandWithDictionary:@{ commandName : self.namespaceName }
onDatabaseName:self.databaseName
error:outError];
}
- (BOOL) dropCollectionWithError:(NSError *__autoreleasing *) outError {
id result = [self _runCommandWithName:@"drop" error:outError];
return result ? YES : NO;
}
#pragma mark - Helper methods
- (MongoWriteConcern *) _coalesceWriteConcern:(MongoWriteConcern *) writeConcern {
return writeConcern ? writeConcern : self.connection.writeConcern;
}
- (BOOL) lastOperationWasSuccessful:(NSError * __autoreleasing *) error {
return [self.connection lastOperationWasSuccessful:error];
}
- (NSDictionary *) lastOperationDictionary {
return [self.connection lastOperationDictionary];
}
- (NSError *) error {
return [self.connection error];
}
- (NSError *) serverError {
return [self.connection serverError];
}
@end