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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997 |
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
9×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1111×
1×
3214×
1×
16×
16×
9×
9×
1×
3299×
3299×
16×
16×
1×
548×
548×
1×
74×
74×
14×
60×
8×
52×
1×
284×
284×
284×
1×
4×
20×
20×
10×
10×
10×
10×
1×
533×
477×
4×
477×
1×
6×
6×
1×
78×
78×
179×
179×
10×
6×
6×
14×
14×
2×
12×
6×
6×
4×
169×
167×
2×
72×
1×
13×
52×
1×
6×
6×
9×
9×
6×
8×
1×
8528×
8528×
512×
171×
512×
1×
1944×
183×
183×
171×
12×
1×
648×
648×
648×
648×
1×
1572×
77×
6×
71×
6×
1×
536×
536×
536×
2×
534×
98×
2×
96×
4×
528×
1572×
1572×
12×
1×
533×
533×
533×
533×
533×
533×
533×
533×
533×
533×
533×
533×
533×
533×
533×
533×
533×
533×
533×
533×
533×
533×
53×
53×
53×
51×
2×
2×
1×
1×
533×
323×
323×
210×
210×
263×
1×
262×
210×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1929×
1427×
1427×
1×
1×
3214×
3214×
3214×
3214×
3214×
1×
3214×
1753×
1461×
1×
3214×
2840×
374×
1×
3214×
3214×
3214×
656×
656×
656×
255×
401×
401×
401×
401×
309×
309×
289×
3214×
3214×
3386×
3077×
3077×
3077×
1672×
3077×
3214×
3214×
3214×
3214×
3214×
3214×
1×
413×
413×
413×
413×
3214×
413×
413×
413×
413×
1×
1250×
1250×
1250×
80×
1250×
1×
511×
511×
1×
511×
511×
1×
3386×
3386×
1961×
3386×
511×
511×
1×
1×
2×
510×
511×
1×
413×
413×
511×
511×
1×
511×
511×
511×
1×
547×
547×
547×
134×
413×
413×
3759×
3759×
3214×
3214×
3214×
3162×
3214×
3214×
3214×
3214×
3386×
3386×
3386×
2127×
3386×
3386×
3386×
3214×
3759×
413×
413×
377×
36×
1×
1×
511×
1×
80×
2×
80×
80×
80×
40×
40×
80×
80×
80×
296×
296×
296×
30×
296×
157×
157×
157×
139×
80×
137×
137×
137×
6×
131×
131×
74×
1×
516×
516×
1×
516×
516×
516×
516×
6×
6×
1×
1192×
1192×
1192×
1192×
3831×
120×
120×
120×
1×
3831×
3831×
1×
516×
516×
80×
436×
510×
54×
54×
54×
54×
132×
129×
54×
142×
142×
142×
139×
54×
456×
516×
43×
43×
719×
719×
43×
473×
473×
6×
473×
6×
473×
81×
473×
53×
53×
8×
53×
473×
43×
43×
43×
2×
2×
41×
41×
473×
399×
23×
399×
473×
1×
53×
1×
55×
52×
52×
458×
458×
458×
458×
458×
52×
52×
52×
52×
456×
456×
458×
458×
1×
458×
458×
458×
460×
52×
301×
52×
223×
223×
52×
52×
1×
108×
108×
53×
55×
1×
55×
1×
1100×
533×
567×
1×
567×
237×
227×
227×
227×
1×
227×
227×
227×
227×
330×
330×
330×
330×
330×
305×
305×
6×
299×
289×
289×
289×
8×
3×
3×
8×
281×
281×
1×
1100×
9×
9×
1100×
1100×
20×
1100×
1100×
1100×
1100×
1100×
1×
20×
20×
20×
20×
20×
20×
1×
1×
6×
6×
6×
6×
6×
6×
1×
1×
6×
6×
6×
6×
6×
6×
1×
1×
1× | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _base64StringToBlobOrBuffer = require('../deps/binary/base64StringToBlobOrBuffer');
var _base64StringToBlobOrBuffer2 = _interopRequireDefault(_base64StringToBlobOrBuffer);
var _pouchdbCollate = require('pouchdb-collate');
var _pouchdbCollate2 = _interopRequireDefault(_pouchdbCollate);
var _taskqueue = require('./taskqueue');
var _taskqueue2 = _interopRequireDefault(_taskqueue);
var _createView = require('./createView');
var _createView2 = _interopRequireDefault(_createView);
var _evalfunc = require('./evalfunc');
var _evalfunc2 = _interopRequireDefault(_evalfunc);
var _utils = require('./utils');
var _utils2 = _interopRequireDefault(_utils);
var _promise = require('../deps/promise');
var _promise2 = _interopRequireDefault(_promise);
var _flatten = require('../deps/flatten');
var _flatten2 = _interopRequireDefault(_flatten);
var _inherits = require('inherits');
var _inherits2 = _interopRequireDefault(_inherits);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var collate = _pouchdbCollate2.default.collate;
var toIndexableString = _pouchdbCollate2.default.toIndexableString;
var normalizeKey = _pouchdbCollate2.default.normalizeKey;
var parseIndexableString = _pouchdbCollate2.default.parseIndexableString;
var log;
/* istanbul ignore else */
Eif (typeof console !== 'undefined' && typeof console.log === 'function') {
log = Function.prototype.bind.call(console.log, console);
} else {
log = function () {};
}
var callbackify = _utils2.default.callbackify;
var sequentialize = _utils2.default.sequentialize;
var uniq = _utils2.default.uniq;
var fin = _utils2.default.fin;
var promisedCallback = _utils2.default.promisedCallback;
var persistentQueues = {};
var tempViewQueue = new _taskqueue2.default();
var CHANGES_BATCH_SIZE = 50;
function parseViewName(name) {
// can be either 'ddocname/viewname' or just 'viewname'
// (where the ddoc name is the same)
return name.indexOf('/') === -1 ? [name, name] : name.split('/');
}
function isGenOne(changes) {
// only return true if the current change is 1-
// and there are no other leafs
return changes.length === 1 && /^1-/.test(changes[0].rev);
}
function emitError(db, e) {
try {
db.emit('error', e);
} catch (err) {
console.error('The user\'s map/reduce function threw an uncaught error.\n' + 'You can debug this error by doing:\n' + 'myDatabase.on(\'error\', function (err) { debugger; });\n' + 'Please double-check your map/reduce function.');
console.error(e);
}
}
function tryCode(db, fun, args) {
// emit an event if there was an error thrown by a map/reduce function.
// putting try/catches in a single function also avoids deoptimizations.
try {
return {
output: fun.apply(null, args)
};
} catch (e) {
emitError(db, e);
return { error: e };
}
}
function sortByKeyThenValue(x, y) {
var keyCompare = collate(x.key, y.key);
return keyCompare !== 0 ? keyCompare : collate(x.value, y.value);
}
function sliceResults(results, limit, skip) {
skip = skip || 0;
if (typeof limit === 'number') {
return results.slice(skip, limit + skip);
} else if (skip > 0) {
return results.slice(skip);
}
return results;
}
function rowToDocId(row) {
var val = row.value;
// Users can explicitly specify a joined doc _id, or it
// defaults to the doc _id that emitted the key/value.
var docId = val && typeof val === 'object' && val._id || row.id;
return docId;
}
function readAttachmentsAsBlobOrBuffer(res) {
res.rows.forEach(function (row) {
var atts = row.doc && row.doc._attachments;
if (!atts) {
return;
}
Object.keys(atts).forEach(function (filename) {
var att = atts[filename];
atts[filename].data = (0, _base64StringToBlobOrBuffer2.default)(att.data, att.content_type);
});
});
}
function postprocessAttachments(opts) {
return function (res) {
if (opts.include_docs && opts.attachments && opts.binary) {
readAttachmentsAsBlobOrBuffer(res);
}
return res;
};
}
function createBuiltInError(name) {
var message = 'builtin ' + name + ' function requires map values to be numbers' + ' or number arrays';
return new BuiltInError(message);
}
function sum(values) {
var result = 0;
for (var i = 0, len = values.length; i < len; i++) {
var num = values[i];
if (typeof num !== 'number') {
if (Array.isArray(num)) {
// lists of numbers are also allowed, sum them separately
result = typeof result === 'number' ? [result] : result;
for (var j = 0, jLen = num.length; j < jLen; j++) {
var jNum = num[j];
if (typeof jNum !== 'number') {
throw createBuiltInError('_sum');
} else if (typeof result[j] === 'undefined') {
result.push(jNum);
} else {
result[j] += jNum;
}
}
} else {
// not array/number
throw createBuiltInError('_sum');
}
} else if (typeof result === 'number') {
result += num;
} else {
// add number to array
result[0] += num;
}
}
return result;
}
var builtInReduce = {
_sum: function (keys, values) {
return sum(values);
},
_count: function (keys, values) {
return values.length;
},
_stats: function (keys, values) {
// no need to implement rereduce=true, because Pouch
// will never call it
function sumsqr(values) {
var _sumsqr = 0;
for (var i = 0, len = values.length; i < len; i++) {
var num = values[i];
_sumsqr += num * num;
}
return _sumsqr;
}
return {
sum: sum(values),
min: Math.min.apply(null, values),
max: Math.max.apply(null, values),
count: values.length,
sumsqr: sumsqr(values)
};
}
};
function addHttpParam(paramName, opts, params, asJson) {
// add an http param from opts to params, optionally json-encoded
var val = opts[paramName];
if (typeof val !== 'undefined') {
if (asJson) {
val = encodeURIComponent(JSON.stringify(val));
}
params.push(paramName + '=' + val);
}
}
function coerceInteger(integerCandidate) {
if (typeof integerCandidate !== 'undefined') {
var asNumber = Number(integerCandidate);
// prevents e.g. '1foo' or '1.1' being coerced to 1
if (!isNaN(asNumber) && asNumber === parseInt(integerCandidate, 10)) {
return asNumber;
} else {
return integerCandidate;
}
}
}
function coerceOptions(opts) {
opts.group_level = coerceInteger(opts.group_level);
opts.limit = coerceInteger(opts.limit);
opts.skip = coerceInteger(opts.skip);
return opts;
}
function checkPositiveInteger(number) {
if (number) {
if (typeof number !== 'number') {
return new QueryParseError('Invalid value for integer: "' + number + '"');
}
if (number < 0) {
return new QueryParseError('Invalid value for positive integer: ' + '"' + number + '"');
}
}
}
function checkQueryParseError(options, fun) {
var startkeyName = options.descending ? 'endkey' : 'startkey';
var endkeyName = options.descending ? 'startkey' : 'endkey';
if (typeof options[startkeyName] !== 'undefined' && typeof options[endkeyName] !== 'undefined' && collate(options[startkeyName], options[endkeyName]) > 0) {
throw new QueryParseError('No rows can match your key range, ' + 'reverse your start_key and end_key or set {descending : true}');
} else if (fun.reduce && options.reduce !== false) {
if (options.include_docs) {
throw new QueryParseError('{include_docs:true} is invalid for reduce');
} else if (options.keys && options.keys.length > 1 && !options.group && !options.group_level) {
throw new QueryParseError('Multi-key fetches for reduce views must use ' + '{group: true}');
}
}
['group_level', 'limit', 'skip'].forEach(function (optionName) {
var error = checkPositiveInteger(options[optionName]);
if (error) {
throw error;
}
});
}
function httpQuery(db, fun, opts) {
// List of parameters to add to the PUT request
var params = [];
var body;
var method = 'GET';
// If opts.reduce exists and is defined, then add it to the list
// of parameters.
// If reduce=false then the results are that of only the map function
// not the final result of map and reduce.
addHttpParam('reduce', opts, params);
addHttpParam('include_docs', opts, params);
addHttpParam('attachments', opts, params);
addHttpParam('limit', opts, params);
addHttpParam('descending', opts, params);
addHttpParam('group', opts, params);
addHttpParam('group_level', opts, params);
addHttpParam('skip', opts, params);
addHttpParam('stale', opts, params);
addHttpParam('conflicts', opts, params);
addHttpParam('startkey', opts, params, true);
addHttpParam('start_key', opts, params, true);
addHttpParam('endkey', opts, params, true);
addHttpParam('end_key', opts, params, true);
addHttpParam('inclusive_end', opts, params);
addHttpParam('key', opts, params, true);
// Format the list of parameters into a valid URI query string
params = params.join('&');
params = params === '' ? '' : '?' + params;
// If keys are supplied, issue a POST to circumvent GET query string limits
// see http://wiki.apache.org/couchdb/HTTP_view_API#Querying_Options
if (typeof opts.keys !== 'undefined') {
var MAX_URL_LENGTH = 2000;
// according to http://stackoverflow.com/a/417184/680742,
// the de facto URL length limit is 2000 characters
var keysAsString = 'keys=' + encodeURIComponent(JSON.stringify(opts.keys));
if (keysAsString.length + params.length + 1 <= MAX_URL_LENGTH) {
// If the keys are short enough, do a GET. we do this to work around
// Safari not understanding 304s on POSTs (see pouchdb/pouchdb#1239)
params += (params[0] === '?' ? '&' : '?') + keysAsString;
} else {
method = 'POST';
if (typeof fun === 'string') {
body = { keys: opts.keys };
} else {
// fun is {map : mapfun}, so append to this
fun.keys = opts.keys;
}
}
}
// We are referencing a query defined in the design doc
if (typeof fun === 'string') {
var parts = parseViewName(fun);
return db.request({
method: method,
url: '_design/' + parts[0] + '/_view/' + parts[1] + params,
body: body
}).then(postprocessAttachments(opts));
}
// We are using a temporary view, terrible for performance, good for testing
body = body || {};
Object.keys(fun).forEach(function (key) {
if (Array.isArray(fun[key])) {
body[key] = fun[key];
} else {
body[key] = fun[key].toString();
}
});
return db.request({
method: 'POST',
url: '_temp_view' + params,
body: body
}).then(postprocessAttachments(opts));
}
// custom adapters can define their own api._query
// and override the default behavior
/* istanbul ignore next */
function customQuery(db, fun, opts) {
return new _promise2.default(function (resolve, reject) {
db._query(fun, opts, function (err, res) {
if (err) {
return reject(err);
}
resolve(res);
});
});
}
// custom adapters can define their own api._viewCleanup
// and override the default behavior
/* istanbul ignore next */
function customViewCleanup(db) {
return new _promise2.default(function (resolve, reject) {
db._viewCleanup(function (err, res) {
if (err) {
return reject(err);
}
resolve(res);
});
});
}
function defaultsTo(value) {
return function (reason) {
/* istanbul ignore else */
Eif (reason.status === 404) {
return value;
} else {
throw reason;
}
};
}
// returns a promise for a list of docs to update, based on the input docId.
// the order doesn't matter, because post-3.2.0, bulkDocs
// is an atomic operation in all three adapters.
function getDocsToPersist(docId, view, docIdsToChangesAndEmits) {
var metaDocId = '_local/doc_' + docId;
var defaultMetaDoc = { _id: metaDocId, keys: [] };
var docData = docIdsToChangesAndEmits[docId];
var indexableKeysToKeyValues = docData.indexableKeysToKeyValues;
var changes = docData.changes;
function getMetaDoc() {
if (isGenOne(changes)) {
// generation 1, so we can safely assume initial state
// for performance reasons (avoids unnecessary GETs)
return _promise2.default.resolve(defaultMetaDoc);
}
return view.db.get(metaDocId).catch(defaultsTo(defaultMetaDoc));
}
function getKeyValueDocs(metaDoc) {
if (!metaDoc.keys.length) {
// no keys, no need for a lookup
return _promise2.default.resolve({ rows: [] });
}
return view.db.allDocs({
keys: metaDoc.keys,
include_docs: true
});
}
function processKvDocs(metaDoc, kvDocsRes) {
var kvDocs = [];
var oldKeysMap = {};
for (var i = 0, len = kvDocsRes.rows.length; i < len; i++) {
var row = kvDocsRes.rows[i];
var doc = row.doc;
if (!doc) {
// deleted
continue;
}
kvDocs.push(doc);
oldKeysMap[doc._id] = true;
doc._deleted = !indexableKeysToKeyValues[doc._id];
if (!doc._deleted) {
var keyValue = indexableKeysToKeyValues[doc._id];
if ('value' in keyValue) {
doc.value = keyValue.value;
}
}
}
var newKeys = Object.keys(indexableKeysToKeyValues);
newKeys.forEach(function (key) {
if (!oldKeysMap[key]) {
// new doc
var kvDoc = {
_id: key
};
var keyValue = indexableKeysToKeyValues[key];
if ('value' in keyValue) {
kvDoc.value = keyValue.value;
}
kvDocs.push(kvDoc);
}
});
metaDoc.keys = uniq(newKeys.concat(metaDoc.keys));
kvDocs.push(metaDoc);
return kvDocs;
}
return getMetaDoc().then(function (metaDoc) {
return getKeyValueDocs(metaDoc).then(function (kvDocsRes) {
return processKvDocs(metaDoc, kvDocsRes);
});
});
}
// updates all emitted key/value docs and metaDocs in the mrview database
// for the given batch of documents from the source database
function saveKeyValues(view, docIdsToChangesAndEmits, seq) {
var seqDocId = '_local/lastSeq';
return view.db.get(seqDocId).catch(defaultsTo({ _id: seqDocId, seq: 0 })).then(function (lastSeqDoc) {
var docIds = Object.keys(docIdsToChangesAndEmits);
return _promise2.default.all(docIds.map(function (docId) {
return getDocsToPersist(docId, view, docIdsToChangesAndEmits);
})).then(function (listOfDocsToPersist) {
var docsToPersist = (0, _flatten2.default)(listOfDocsToPersist);
lastSeqDoc.seq = seq;
docsToPersist.push(lastSeqDoc);
// write all docs in a single operation, update the seq once
return view.db.bulkDocs({ docs: docsToPersist });
});
});
}
function getQueue(view) {
var viewName = typeof view === 'string' ? view : view.name;
var queue = persistentQueues[viewName];
if (!queue) {
queue = persistentQueues[viewName] = new _taskqueue2.default();
}
return queue;
}
function updateView(view) {
return sequentialize(getQueue(view), function () {
return updateViewInQueue(view);
})();
}
function updateViewInQueue(view) {
// bind the emit function once
var mapResults;
var doc;
function emit(key, value) {
var output = { id: doc._id, key: normalizeKey(key) };
// Don't explicitly store the value unless it's defined and non-null.
// This saves on storage space, because often people don't use it.
if (typeof value !== 'undefined' && value !== null) {
output.value = normalizeKey(value);
}
mapResults.push(output);
}
var mapFun;
// for temp_views one can use emit(doc, emit), see #38
if (typeof view.mapFun === "function" && view.mapFun.length === 2) {
var origMap = view.mapFun;
mapFun = function (doc) {
return origMap(doc, emit);
};
} else {
mapFun = (0, _evalfunc2.default)(view.mapFun.toString(), emit, sum, log, Array.isArray, JSON.parse);
}
var currentSeq = view.seq || 0;
function processChange(docIdsToChangesAndEmits, seq) {
return function () {
return saveKeyValues(view, docIdsToChangesAndEmits, seq);
};
}
var queue = new _taskqueue2.default();
// TODO(neojski): https://github.com/daleharvey/pouchdb/issues/1521
return new _promise2.default(function (resolve, reject) {
function complete() {
queue.finish().then(function () {
view.seq = currentSeq;
resolve();
});
}
function processNextBatch() {
view.sourceDB.changes({
conflicts: true,
include_docs: true,
style: 'all_docs',
since: currentSeq,
limit: CHANGES_BATCH_SIZE
}).on('complete', function (response) {
var results = response.results;
if (!results.length) {
return complete();
}
var docIdsToChangesAndEmits = {};
for (var i = 0, l = results.length; i < l; i++) {
var change = results[i];
if (change.doc._id[0] !== '_') {
mapResults = [];
doc = change.doc;
if (!doc._deleted) {
tryCode(view.sourceDB, mapFun, [doc]);
}
mapResults.sort(sortByKeyThenValue);
var indexableKeysToKeyValues = {};
var lastKey;
for (var j = 0, jl = mapResults.length; j < jl; j++) {
var obj = mapResults[j];
var complexKey = [obj.key, obj.id];
if (collate(obj.key, lastKey) === 0) {
complexKey.push(j); // dup key+id, so make it unique
}
var indexableKey = toIndexableString(complexKey);
indexableKeysToKeyValues[indexableKey] = obj;
lastKey = obj.key;
}
docIdsToChangesAndEmits[change.doc._id] = {
indexableKeysToKeyValues: indexableKeysToKeyValues,
changes: change.changes
};
}
currentSeq = change.seq;
}
queue.add(processChange(docIdsToChangesAndEmits, currentSeq));
if (results.length < CHANGES_BATCH_SIZE) {
return complete();
}
return processNextBatch();
}).on('error', onError);
/* istanbul ignore next */
function onError(err) {
reject(err);
}
}
processNextBatch();
});
}
function reduceView(view, results, options) {
if (options.group_level === 0) {
delete options.group_level;
}
var shouldGroup = options.group || options.group_level;
var reduceFun;
if (builtInReduce[view.reduceFun]) {
reduceFun = builtInReduce[view.reduceFun];
} else {
reduceFun = (0, _evalfunc2.default)(view.reduceFun.toString(), null, sum, log, Array.isArray, JSON.parse);
}
var groups = [];
var lvl = options.group_level;
results.forEach(function (e) {
var last = groups[groups.length - 1];
var key = shouldGroup ? e.key : null;
// only set group_level for array keys
if (shouldGroup && Array.isArray(key) && typeof lvl === 'number') {
key = key.length > lvl ? key.slice(0, lvl) : key;
}
if (last && collate(last.key[0][0], key) === 0) {
last.key.push([key, e.id]);
last.value.push(e.value);
return;
}
groups.push({ key: [[key, e.id]], value: [e.value] });
});
for (var i = 0, len = groups.length; i < len; i++) {
var e = groups[i];
var reduceTry = tryCode(view.sourceDB, reduceFun, [e.key, e.value, false]);
if (reduceTry.error && reduceTry.error instanceof BuiltInError) {
// CouchDB returns an error if a built-in errors out
throw reduceTry.error;
}
// CouchDB just sets the value to null if a non-built-in errors out
e.value = reduceTry.error ? null : reduceTry.output;
e.key = e.key[0][0];
}
// no total_rows/offset when reducing
return { rows: sliceResults(groups, options.limit, options.skip) };
}
function queryView(view, opts) {
return sequentialize(getQueue(view), function () {
return queryViewInQueue(view, opts);
})();
}
function queryViewInQueue(view, opts) {
var totalRows;
var shouldReduce = view.reduceFun && opts.reduce !== false;
var skip = opts.skip || 0;
if (typeof opts.keys !== 'undefined' && !opts.keys.length) {
// equivalent query
opts.limit = 0;
delete opts.keys;
}
function fetchFromView(viewOpts) {
viewOpts.include_docs = true;
return view.db.allDocs(viewOpts).then(function (res) {
totalRows = res.total_rows;
return res.rows.map(function (result) {
// implicit migration - in older versions of PouchDB,
// we explicitly stored the doc as {id: ..., key: ..., value: ...}
// this is tested in a migration test
/* istanbul ignore next */
if ('value' in result.doc && typeof result.doc.value === 'object' && result.doc.value !== null) {
var keys = Object.keys(result.doc.value).sort();
// this detection method is not perfect, but it's unlikely the user
// emitted a value which was an object with these 3 exact keys
var expectedKeys = ['id', 'key', 'value'];
Iif (!(keys < expectedKeys || keys > expectedKeys)) {
return result.doc.value;
}
}
var parsedKeyAndDocId = parseIndexableString(result.doc._id);
return {
key: parsedKeyAndDocId[0],
id: parsedKeyAndDocId[1],
value: 'value' in result.doc ? result.doc.value : null
};
});
});
}
function onMapResultsReady(rows) {
var finalResults;
if (shouldReduce) {
finalResults = reduceView(view, rows, opts);
} else {
finalResults = {
total_rows: totalRows,
offset: skip,
rows: rows
};
}
if (opts.include_docs) {
var docIds = uniq(rows.map(rowToDocId));
return view.sourceDB.allDocs({
keys: docIds,
include_docs: true,
conflicts: opts.conflicts,
attachments: opts.attachments,
binary: opts.binary
}).then(function (allDocsRes) {
var docIdsToDocs = {};
allDocsRes.rows.forEach(function (row) {
if (row.doc) {
docIdsToDocs['$' + row.id] = row.doc;
}
});
rows.forEach(function (row) {
var docId = rowToDocId(row);
var doc = docIdsToDocs['$' + docId];
if (doc) {
row.doc = doc;
}
});
return finalResults;
});
} else {
return finalResults;
}
}
if (typeof opts.keys !== 'undefined') {
var keys = opts.keys;
var fetchPromises = keys.map(function (key) {
var viewOpts = {
startkey: toIndexableString([key]),
endkey: toIndexableString([key, {}])
};
return fetchFromView(viewOpts);
});
return _promise2.default.all(fetchPromises).then(_flatten2.default).then(onMapResultsReady);
} else {
// normal query, no 'keys'
var viewOpts = {
descending: opts.descending
};
if (opts.start_key) {
opts.startkey = opts.start_key;
}
if (opts.end_key) {
opts.endkey = opts.end_key;
}
if (typeof opts.startkey !== 'undefined') {
viewOpts.startkey = opts.descending ? toIndexableString([opts.startkey, {}]) : toIndexableString([opts.startkey]);
}
if (typeof opts.endkey !== 'undefined') {
var inclusiveEnd = opts.inclusive_end !== false;
if (opts.descending) {
inclusiveEnd = !inclusiveEnd;
}
viewOpts.endkey = toIndexableString(inclusiveEnd ? [opts.endkey, {}] : [opts.endkey]);
}
if (typeof opts.key !== 'undefined') {
var keyStart = toIndexableString([opts.key]);
var keyEnd = toIndexableString([opts.key, {}]);
if (viewOpts.descending) {
viewOpts.endkey = keyStart;
viewOpts.startkey = keyEnd;
} else {
viewOpts.startkey = keyStart;
viewOpts.endkey = keyEnd;
}
}
if (!shouldReduce) {
if (typeof opts.limit === 'number') {
viewOpts.limit = opts.limit;
}
viewOpts.skip = skip;
}
return fetchFromView(viewOpts).then(onMapResultsReady);
}
}
function httpViewCleanup(db) {
return db.request({
method: 'POST',
url: '_view_cleanup'
});
}
function localViewCleanup(db) {
return db.get('_local/mrviews').then(function (metaDoc) {
var docsToViews = {};
Object.keys(metaDoc.views).forEach(function (fullViewName) {
var parts = parseViewName(fullViewName);
var designDocName = '_design/' + parts[0];
var viewName = parts[1];
docsToViews[designDocName] = docsToViews[designDocName] || {};
docsToViews[designDocName][viewName] = true;
});
var opts = {
keys: Object.keys(docsToViews),
include_docs: true
};
return db.allDocs(opts).then(function (res) {
var viewsToStatus = {};
res.rows.forEach(function (row) {
var ddocName = row.key.substring(8);
Object.keys(docsToViews[row.key]).forEach(function (viewName) {
var fullViewName = ddocName + '/' + viewName;
/* istanbul ignore if */
Iif (!metaDoc.views[fullViewName]) {
// new format, without slashes, to support PouchDB 2.2.0
// migration test in pouchdb's browser.migration.js verifies this
fullViewName = viewName;
}
var viewDBNames = Object.keys(metaDoc.views[fullViewName]);
// design doc deleted, or view function nonexistent
var statusIsGood = row.doc && row.doc.views && row.doc.views[viewName];
viewDBNames.forEach(function (viewDBName) {
viewsToStatus[viewDBName] = viewsToStatus[viewDBName] || statusIsGood;
});
});
});
var dbsToDelete = Object.keys(viewsToStatus).filter(function (viewDBName) {
return !viewsToStatus[viewDBName];
});
var destroyPromises = dbsToDelete.map(function (viewDBName) {
return sequentialize(getQueue(viewDBName), function () {
return new db.constructor(viewDBName, db.__opts).destroy();
})();
});
return _promise2.default.all(destroyPromises).then(function () {
return { ok: true };
});
});
}, defaultsTo({ ok: true }));
}
var viewCleanup = callbackify(function () {
var db = this;
if (db.type() === 'http') {
return httpViewCleanup(db);
}
/* istanbul ignore next */
Iif (typeof db._viewCleanup === 'function') {
return customViewCleanup(db);
}
return localViewCleanup(db);
});
function queryPromised(db, fun, opts) {
if (db.type() === 'http') {
return httpQuery(db, fun, opts);
}
/* istanbul ignore next */
Iif (typeof db._query === 'function') {
return customQuery(db, fun, opts);
}
if (typeof fun !== 'string') {
// temp_view
checkQueryParseError(opts, fun);
var createViewOpts = {
db: db,
viewName: 'temp_view/temp_view',
map: fun.map,
reduce: fun.reduce,
temporary: true
};
tempViewQueue.add(function () {
return (0, _createView2.default)(createViewOpts).then(function (view) {
function cleanup() {
return view.db.destroy();
}
return fin(updateView(view).then(function () {
return queryView(view, opts);
}), cleanup);
});
});
return tempViewQueue.finish();
} else {
// persistent view
var fullViewName = fun;
var parts = parseViewName(fullViewName);
var designDocName = parts[0];
var viewName = parts[1];
return db.get('_design/' + designDocName).then(function (doc) {
var fun = doc.views && doc.views[viewName];
if (!fun || typeof fun.map !== 'string') {
throw new NotFoundError('ddoc ' + designDocName + ' has no view named ' + viewName);
}
checkQueryParseError(opts, fun);
var createViewOpts = {
db: db,
viewName: fullViewName,
map: fun.map,
reduce: fun.reduce
};
return (0, _createView2.default)(createViewOpts).then(function (view) {
if (opts.stale === 'ok' || opts.stale === 'update_after') {
if (opts.stale === 'update_after') {
process.nextTick(function () {
updateView(view);
});
}
return queryView(view, opts);
} else {
// stale not ok
return updateView(view).then(function () {
return queryView(view, opts);
});
}
});
});
}
}
var query = function (fun, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
opts = opts ? coerceOptions(opts) : {};
if (typeof fun === 'function') {
fun = { map: fun };
}
var db = this;
var promise = _promise2.default.resolve().then(function () {
return queryPromised(db, fun, opts);
});
promisedCallback(promise, callback);
return promise;
};
function QueryParseError(message) {
this.status = 400;
this.name = 'query_parse_error';
this.message = message;
this.error = true;
try {
Error.captureStackTrace(this, QueryParseError);
} catch (e) {}
}
(0, _inherits2.default)(QueryParseError, Error);
function NotFoundError(message) {
this.status = 404;
this.name = 'not_found';
this.message = message;
this.error = true;
try {
Error.captureStackTrace(this, NotFoundError);
} catch (e) {}
}
(0, _inherits2.default)(NotFoundError, Error);
function BuiltInError(message) {
this.status = 500;
this.name = 'invalid_value';
this.message = message;
this.error = true;
try {
Error.captureStackTrace(this, BuiltInError);
} catch (e) {}
}
(0, _inherits2.default)(BuiltInError, Error);
exports.default = {
query: query,
viewCleanup: viewCleanup
};
module.exports = exports['default']; |