This repository has been archived by the owner on Mar 9, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 66
/
CouchQuery.m
393 lines (288 loc) · 10.3 KB
/
CouchQuery.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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
//
// CouchQuery.m
// CouchCocoa
//
// Created by Jens Alfke on 5/30/11.
// Copyright 2011 Couchbase, Inc.
//
// 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.
// <http://wiki.apache.org/couchdb/HTTP_view_API#Querying_Options>
#import "CouchQuery.h"
#import "CouchDesignDocument.h"
#import "CouchInternal.h"
@interface CouchQueryEnumerator ()
- (id) initWithQuery: (CouchQuery*)query op: (RESTOperation*)op;
@end
@interface CouchQueryRow ()
- (id) initWithQuery: (CouchQuery*)query result: (id)result;
@end
@implementation CouchQuery
- (id) initWithQuery: (CouchQuery*)query {
self = [super initWithParent: query.parent relativePath: query.relativePath];
if (self) {
_limit = query.limit;
_skip = query.skip;
self.startKey = query.startKey;
self.endKey = query.endKey;
_descending = query.descending;
_prefetch = query.prefetch;
self.keys = query.keys;
_groupLevel = query.groupLevel;
}
return self;
}
@synthesize limit=_limit, skip=_skip, descending=_descending, startKey=_startKey, endKey=_endKey,
prefetch=_prefetch, keys=_keys, groupLevel=_groupLevel;
- (CouchDesignDocument*) designDocument {
// The relativePath to a view URL will look like "_design/DOCNAME/_view/VIEWNAME"
NSArray* path = [self.relativePath componentsSeparatedByString: @"/"];
if (path.count >= 4 && [[path objectAtIndex: 0] isEqualToString: @"_design"])
return [self.database designDocumentWithName: [path objectAtIndex: 1]];
else
return nil;
}
- (NSDictionary*) jsonToPost {
if (_keys)
return [NSDictionary dictionaryWithObject: _keys forKey: @"keys"];
else
return nil;
}
- (NSMutableDictionary*) requestParams {
NSMutableDictionary* params = [NSMutableDictionary dictionary];
if (_limit)
[params setObject: [NSNumber numberWithUnsignedLong: _limit] forKey: @"?limit"];
if (_skip)
[params setObject: [NSNumber numberWithUnsignedLong: _skip] forKey: @"?skip"];
if (_startKey)
[params setObject: [RESTBody stringWithJSONObject: _startKey] forKey: @"?startkey"];
if (_endKey)
[params setObject: [RESTBody stringWithJSONObject: _endKey] forKey: @"?endkey"];
if (_descending)
[params setObject: @"true" forKey: @"?descending"];
if (_prefetch)
[params setObject: @"true" forKey: @"?include_docs"];
if (_groupLevel > 0)
[params setObject: [NSNumber numberWithUnsignedLong: _groupLevel] forKey: @"?group_level"];
[params setObject: @"true" forKey: @"?update_seq"];
return params;
}
- (RESTOperation*) start {
NSDictionary* params = self.requestParams;
NSDictionary* json = self.jsonToPost;
if (json)
return [self POSTJSON: json parameters: params];
else
return [self sendHTTP: @"GET" parameters: params];
}
- (CouchQueryEnumerator*) rows {
[self cacheResponse: nil];
return [self rowsIfChanged];
}
- (CouchQueryEnumerator*) rowsIfChanged {
return [[self start] resultObject];
}
- (NSError*) operation: (RESTOperation*)op willCompleteWithError: (NSError*)error {
error = [super operation: op willCompleteWithError: error];
if (!error && op.httpStatus == 200) {
NSArray* rows = $castIf(NSArray, [op.responseBody.fromJSON objectForKey: @"rows"]);
if (rows) {
[self cacheResponse: op];
op.resultObject = [[[CouchQueryEnumerator alloc] initWithQuery: self
op: op] autorelease];
} else {
Warn(@"Couldn't parse rows from CouchDB view response");
error = [NSError errorWithDomain: CouchHTTPErrorDomain code: 500 userInfo:nil];
}
}
return error;
}
- (CouchLiveQuery*) asLiveQuery {
return [[[CouchLiveQuery alloc] initWithQuery: self] autorelease];
}
@end
@implementation CouchFunctionQuery
- (id) initWithDatabase: (CouchDatabase*)db
viewDefinition: (struct CouchViewDefinition)definition
{
self = [super initWithParent: db relativePath: @"_temp_view"];
if (self != nil) {
_viewDefinition = [[NSDictionary alloc] initWithObjectsAndKeys:
definition.mapFunction, @"map",
definition.reduceFunction, @"reduce", // may be nil
nil];
}
return self;
}
- (void) dealloc
{
[_viewDefinition release];
[super dealloc];
}
- (NSDictionary*) jsonToPost {
return _viewDefinition;
}
@end
@implementation CouchLiveQuery
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver: self];
[_op release];
[super dealloc];
}
- (CouchQueryEnumerator*) rows {
if (!_observing)
[self start];
return _rows;
}
- (void) setRows:(CouchQueryEnumerator *)rows {
[_rows autorelease];
_rows = [rows retain];
}
- (RESTOperation*) start {
if (!_op) {
if (!_observing) {
_observing = YES;
self.database.tracksChanges = YES;
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(databaseChanged)
name: kCouchDatabaseChangeNotification
object: self.database];
}
NSLog(@"CouchLiveQuery: Starting...");
_op = [[super start] retain];
[_op start];
}
return _op;
}
- (void) updateRows {
if (_op)
return; // TODO: Should probably re-run query after current _op completes, instead
if (_rows)
self.prefetch = NO; // (prefetch disables conditional GET shortcut)
[self start];
}
- (void) databaseChanged {
[self updateRows];
}
- (NSError*) operation: (RESTOperation*)op willCompleteWithError: (NSError*)error {
error = [super operation: op willCompleteWithError: error];
if (op == _op) {
NSLog(@"CouchLiveQuery: ...Finished (status=%i)", op.httpStatus);
[_op release];
_op = nil;
CouchQueryEnumerator* rows = op.resultObject;
if (rows && ![rows isEqual: _rows]) {
NSLog(@"CouchLiveQuery: ...Rows changed! (now %lu)", (unsigned long)rows.count);
self.rows = rows; // Triggers KVO notification
}
}
return error;
}
@end
@implementation CouchQueryEnumerator
@synthesize totalCount=_totalCount, sequenceNumber=_sequenceNumber;
- (id) initWithQuery: (CouchQuery*)query op: (RESTOperation*)op {
self = [super init];
if (self) {
NSDictionary* result = $castIf(NSDictionary, op.responseBody.fromJSON);
_query = [query retain];
_rows = [$castIf(NSArray, [result objectForKey: @"rows"]) retain];
if (!_rows) {
[self release];
return nil;
}
_totalCount = [[result objectForKey: @"total_rows"] intValue];
_sequenceNumber = [[result objectForKey: @"update_seq"] intValue];
}
return self;
}
- (void) dealloc
{
[_query release];
[_rows release];
[super dealloc];
}
- (BOOL) isEqual:(id)object {
if (object == self)
return YES;
if (![object isKindOfClass: [CouchQueryEnumerator class]])
return NO;
CouchQueryEnumerator* otherEnum = object;
return [otherEnum->_rows isEqual: _rows];
}
- (NSUInteger) count {
return _rows.count;
}
- (CouchQueryRow*) rowAtIndex: (NSUInteger)index {
return [[[CouchQueryRow alloc] initWithQuery: _query
result: [_rows objectAtIndex:index]]
autorelease];
}
- (CouchQueryRow*) nextRow {
if (_nextRow >= _rows.count)
return nil;
return [self rowAtIndex:_nextRow++];
}
- (id) nextObject {
return [self nextRow];
}
@end
@implementation CouchQueryRow
- (id) initWithQuery: (CouchQuery*)query result: (id)result {
self = [super init];
if (self) {
if (![result isKindOfClass: [NSDictionary class]]) {
Warn(@"Unexpected row value in view results: %@", result);
[self release];
return nil;
}
_query = [query retain];
_result = [result retain];
}
return self;
}
@synthesize query=_query;
- (id) key {return [_result objectForKey: @"key"];}
- (id) value {return [_result objectForKey: @"value"];}
- (NSString*) documentID {return [_result objectForKey: @"id"];}
- (NSDictionary*) documentProperties {return [_result objectForKey: @"doc"];}
- (NSString*) documentRevision {
// Get the revision id from either the embedded document contents,
// or the 'rev' value key:
NSString* rev = [[_result objectForKey: @"doc"] objectForKey: @"_rev"];
if (!rev)
rev = [$castIf(NSDictionary, self.value) objectForKey: @"rev"];
return rev;
}
- (id) keyAtIndex: (NSUInteger)index {
id key = [_result objectForKey: @"key"];
if ([key isKindOfClass:[NSArray class]])
return (index < [key count]) ? [key objectAtIndex: index] : nil;
else
return (index == 0) ? key : nil;
}
- (id) key0 {return [self keyAtIndex: 0];}
- (id) key1 {return [self keyAtIndex: 1];}
- (id) key2 {return [self keyAtIndex: 2];}
- (id) key3 {return [self keyAtIndex: 3];}
- (CouchDocument*) document {
NSString* docID = [_result objectForKey: @"id"];
if (!docID)
return nil;
CouchDocument* doc = [_query.database documentWithID: docID];
[doc loadCurrentRevisionFrom: self];
return doc;
}
- (NSString*) description {
return [NSString stringWithFormat: @"%@[key=%@; value=%@; id=%@]",
[self class],
[RESTBody stringWithJSONObject: self.key],
[RESTBody stringWithJSONObject: self.value],
self.documentID];
}
@end