-
Notifications
You must be signed in to change notification settings - Fork 132
/
selector.js
735 lines (662 loc) · 23 KB
/
selector.js
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
/*
========================================
Meteor is licensed under the MIT License
========================================
Copyright (C) 2011--2012 Meteor Development Group
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
====================================================================
This license applies to all code in Meteor that is not an externally
maintained library. Externally maintained libraries have their own
licenses, included below:
====================================================================
*/
LocalCollection = {};
EJSON = require("./EJSON");
var _ = require('lodash');
// Like _.isArray, but doesn't regard polyfilled Uint8Arrays on old browsers as
// arrays.
var isArray = function (x) {
return _.isArray(x) && !EJSON.isBinary(x);
};
var _anyIfArray = function (x, f) {
if (isArray(x))
return _.any(x, f);
return f(x);
};
var _anyIfArrayPlus = function (x, f) {
if (f(x))
return true;
return isArray(x) && _.any(x, f);
};
var hasOperators = function(valueSelector) {
var theseAreOperators = undefined;
for (var selKey in valueSelector) {
var thisIsOperator = selKey.substr(0, 1) === '$';
if (theseAreOperators === undefined) {
theseAreOperators = thisIsOperator;
} else if (theseAreOperators !== thisIsOperator) {
throw new Error("Inconsistent selector: " + valueSelector);
}
}
return !!theseAreOperators; // {} has no operators
};
var compileValueSelector = function (valueSelector) {
if (valueSelector == null) { // undefined or null
return function (value) {
return _anyIfArray(value, function (x) {
return x == null; // undefined or null
});
};
}
// Selector is a non-null primitive (and not an array or RegExp either).
if (!_.isObject(valueSelector)) {
return function (value) {
return _anyIfArray(value, function (x) {
return x === valueSelector;
});
};
}
if (valueSelector instanceof RegExp) {
return function (value) {
if (value === undefined)
return false;
return _anyIfArray(value, function (x) {
return valueSelector.test(x);
});
};
}
// Arrays match either identical arrays or arrays that contain it as a value.
if (isArray(valueSelector)) {
return function (value) {
if (!isArray(value))
return false;
return _anyIfArrayPlus(value, function (x) {
return LocalCollection._f._equal(valueSelector, x);
});
};
}
// It's an object, but not an array or regexp.
if (hasOperators(valueSelector)) {
var operatorFunctions = [];
_.each(valueSelector, function (operand, operator) {
if (!_.has(VALUE_OPERATORS, operator))
throw new Error("Unrecognized operator: " + operator);
operatorFunctions.push(VALUE_OPERATORS[operator](
operand, valueSelector.$options));
});
return function (value) {
return _.all(operatorFunctions, function (f) {
return f(value);
});
};
}
// It's a literal; compare value (or element of value array) directly to the
// selector.
return function (value) {
return _anyIfArray(value, function (x) {
return LocalCollection._f._equal(valueSelector, x);
});
};
};
// XXX can factor out common logic below
var LOGICAL_OPERATORS = {
"$and": function(subSelector) {
if (!isArray(subSelector) || _.isEmpty(subSelector))
throw Error("$and/$or/$nor must be nonempty array");
var subSelectorFunctions = _.map(
subSelector, compileDocumentSelector);
return function (doc) {
return _.all(subSelectorFunctions, function (f) {
return f(doc);
});
};
},
"$or": function(subSelector) {
if (!isArray(subSelector) || _.isEmpty(subSelector))
throw Error("$and/$or/$nor must be nonempty array");
var subSelectorFunctions = _.map(
subSelector, compileDocumentSelector);
return function (doc) {
return _.any(subSelectorFunctions, function (f) {
return f(doc);
});
};
},
"$nor": function(subSelector) {
if (!isArray(subSelector) || _.isEmpty(subSelector))
throw Error("$and/$or/$nor must be nonempty array");
var subSelectorFunctions = _.map(
subSelector, compileDocumentSelector);
return function (doc) {
return _.all(subSelectorFunctions, function (f) {
return !f(doc);
});
};
},
"$where": function(selectorValue) {
if (!(selectorValue instanceof Function)) {
selectorValue = Function("return " + selectorValue);
}
return function (doc) {
return selectorValue.call(doc);
};
}
};
var VALUE_OPERATORS = {
"$in": function (operand) {
if (!isArray(operand))
throw new Error("Argument to $in must be array");
return function (value) {
return _anyIfArrayPlus(value, function (x) {
return _.any(operand, function (operandElt) {
return LocalCollection._f._equal(operandElt, x);
});
});
};
},
"$all": function (operand) {
if (!isArray(operand))
throw new Error("Argument to $all must be array");
return function (value) {
if (!isArray(value))
return false;
return _.all(operand, function (operandElt) {
return _.any(value, function (valueElt) {
return LocalCollection._f._equal(operandElt, valueElt);
});
});
};
},
"$lt": function (operand) {
return function (value) {
return _anyIfArray(value, function (x) {
return LocalCollection._f._cmp(x, operand) < 0;
});
};
},
"$lte": function (operand) {
return function (value) {
return _anyIfArray(value, function (x) {
return LocalCollection._f._cmp(x, operand) <= 0;
});
};
},
"$gt": function (operand) {
return function (value) {
return _anyIfArray(value, function (x) {
return LocalCollection._f._cmp(x, operand) > 0;
});
};
},
"$gte": function (operand) {
return function (value) {
return _anyIfArray(value, function (x) {
return LocalCollection._f._cmp(x, operand) >= 0;
});
};
},
"$ne": function (operand) {
return function (value) {
return ! _anyIfArrayPlus(value, function (x) {
return LocalCollection._f._equal(x, operand);
});
};
},
"$nin": function (operand) {
if (!isArray(operand))
throw new Error("Argument to $nin must be array");
var inFunction = VALUE_OPERATORS.$in(operand);
return function (value) {
// Field doesn't exist, so it's not-in operand
if (value === undefined)
return true;
return !inFunction(value);
};
},
"$exists": function (operand) {
return function (value) {
return operand === (value !== undefined);
};
},
"$mod": function (operand) {
var divisor = operand[0],
remainder = operand[1];
return function (value) {
return _anyIfArray(value, function (x) {
return x % divisor === remainder;
});
};
},
"$size": function (operand) {
return function (value) {
return isArray(value) && operand === value.length;
};
},
"$type": function (operand) {
return function (value) {
// A nonexistent field is of no type.
if (value === undefined)
return false;
// Definitely not _anyIfArrayPlus: $type: 4 only matches arrays that have
// arrays as elements according to the Mongo docs.
return _anyIfArray(value, function (x) {
return LocalCollection._f._type(x) === operand;
});
};
},
"$regex": function (operand, options) {
if (options !== undefined) {
// Options passed in $options (even the empty string) always overrides
// options in the RegExp object itself.
// Be clear that we only support the JS-supported options, not extended
// ones (eg, Mongo supports x and s). Ideally we would implement x and s
// by transforming the regexp, but not today...
if (/[^gim]/.test(options))
throw new Error("Only the i, m, and g regexp options are supported");
var regexSource = operand instanceof RegExp ? operand.source : operand;
operand = new RegExp(regexSource, options);
} else if (!(operand instanceof RegExp)) {
operand = new RegExp(operand);
}
return function (value) {
if (value === undefined)
return false;
return _anyIfArray(value, function (x) {
return operand.test(x);
});
};
},
"$options": function (operand) {
// evaluation happens at the $regex function above
return function (value) { return true; };
},
"$elemMatch": function (operand) {
var matcher = compileDocumentSelector(operand);
return function (value) {
if (!isArray(value))
return false;
return _.any(value, function (x) {
return matcher(x);
});
};
},
"$not": function (operand) {
var matcher = compileValueSelector(operand);
return function (value) {
return !matcher(value);
};
},
"$near": function (operand) {
// Always returns true. Must be handled in post-filter/sort/limit
return function (value) {
return true;
}
},
"$geoIntersects": function (operand) {
// Always returns true. Must be handled in post-filter/sort/limit
return function (value) {
return true;
}
}
};
// helpers used by compiled selector code
LocalCollection._f = {
// XXX for _all and _in, consider building 'inquery' at compile time..
_type: function (v) {
if (typeof v === "number")
return 1;
if (typeof v === "string")
return 2;
if (typeof v === "boolean")
return 8;
if (isArray(v))
return 4;
if (v === null)
return 10;
if (v instanceof RegExp)
return 11;
if (typeof v === "function")
// note that typeof(/x/) === "function"
return 13;
if (v instanceof Date)
return 9;
if (EJSON.isBinary(v))
return 5;
if (v instanceof Meteor.Collection.ObjectID)
return 7;
return 3; // object
// XXX support some/all of these:
// 14, symbol
// 15, javascript code with scope
// 16, 18: 32-bit/64-bit integer
// 17, timestamp
// 255, minkey
// 127, maxkey
},
// deep equality test: use for literal document and array matches
_equal: function (a, b) {
return EJSON.equals(a, b, {keyOrderSensitive: true});
},
// maps a type code to a value that can be used to sort values of
// different types
_typeorder: function (t) {
// http://www.mongodb.org/display/DOCS/What+is+the+Compare+Order+for+BSON+Types
// XXX what is the correct sort position for Javascript code?
// ('100' in the matrix below)
// XXX minkey/maxkey
return [-1, // (not a type)
1, // number
2, // string
3, // object
4, // array
5, // binary
-1, // deprecated
6, // ObjectID
7, // bool
8, // Date
0, // null
9, // RegExp
-1, // deprecated
100, // JS code
2, // deprecated (symbol)
100, // JS code
1, // 32-bit int
8, // Mongo timestamp
1 // 64-bit int
][t];
},
// compare two values of unknown type according to BSON ordering
// semantics. (as an extension, consider 'undefined' to be less than
// any other value.) return negative if a is less, positive if b is
// less, or 0 if equal
_cmp: function (a, b) {
if (a === undefined)
return b === undefined ? 0 : -1;
if (b === undefined)
return 1;
var ta = LocalCollection._f._type(a);
var tb = LocalCollection._f._type(b);
var oa = LocalCollection._f._typeorder(ta);
var ob = LocalCollection._f._typeorder(tb);
if (oa !== ob)
return oa < ob ? -1 : 1;
if (ta !== tb)
// XXX need to implement this if we implement Symbol or integers, or
// Timestamp
throw Error("Missing type coercion logic in _cmp");
if (ta === 7) { // ObjectID
// Convert to string.
ta = tb = 2;
a = a.toHexString();
b = b.toHexString();
}
if (ta === 9) { // Date
// Convert to millis.
ta = tb = 1;
a = a.getTime();
b = b.getTime();
}
if (ta === 1) // double
return a - b;
if (tb === 2) // string
return a < b ? -1 : (a === b ? 0 : 1);
if (ta === 3) { // Object
// this could be much more efficient in the expected case ...
var to_array = function (obj) {
var ret = [];
for (var key in obj) {
ret.push(key);
ret.push(obj[key]);
}
return ret;
};
return LocalCollection._f._cmp(to_array(a), to_array(b));
}
if (ta === 4) { // Array
for (var i = 0; ; i++) {
if (i === a.length)
return (i === b.length) ? 0 : -1;
if (i === b.length)
return 1;
var s = LocalCollection._f._cmp(a[i], b[i]);
if (s !== 0)
return s;
}
}
if (ta === 5) { // binary
// Surprisingly, a small binary blob is always less than a large one in
// Mongo.
if (a.length !== b.length)
return a.length - b.length;
for (i = 0; i < a.length; i++) {
if (a[i] < b[i])
return -1;
if (a[i] > b[i])
return 1;
}
return 0;
}
if (ta === 8) { // boolean
if (a) return b ? 0 : 1;
return b ? -1 : 0;
}
if (ta === 10) // null
return 0;
if (ta === 11) // regexp
throw Error("Sorting not supported on regular expression"); // XXX
// 13: javascript code
// 14: symbol
// 15: javascript code with scope
// 16: 32-bit integer
// 17: timestamp
// 18: 64-bit integer
// 255: minkey
// 127: maxkey
if (ta === 13) // javascript code
throw Error("Sorting not supported on Javascript code"); // XXX
throw Error("Unknown type to sort");
}
};
// For unit tests. True if the given document matches the given
// selector.
LocalCollection._matches = function (selector, doc) {
return (LocalCollection._compileSelector(selector))(doc);
};
// _makeLookupFunction(key) returns a lookup function.
//
// A lookup function takes in a document and returns an array of matching
// values. This array has more than one element if any segment of the key other
// than the last one is an array. ie, any arrays found when doing non-final
// lookups result in this function "branching"; each element in the returned
// array represents the value found at this branch. If any branch doesn't have a
// final value for the full key, its element in the returned list will be
// undefined. It always returns a non-empty array.
//
// _makeLookupFunction('a.x')({a: {x: 1}}) returns [1]
// _makeLookupFunction('a.x')({a: {x: [1]}}) returns [[1]]
// _makeLookupFunction('a.x')({a: 5}) returns [undefined]
// _makeLookupFunction('a.x')({a: [{x: 1},
// {x: [2]},
// {y: 3}]})
// returns [1, [2], undefined]
LocalCollection._makeLookupFunction = function (key) {
var dotLocation = key.indexOf('.');
var first, lookupRest, nextIsNumeric;
if (dotLocation === -1) {
first = key;
} else {
first = key.substr(0, dotLocation);
var rest = key.substr(dotLocation + 1);
lookupRest = LocalCollection._makeLookupFunction(rest);
// Is the next (perhaps final) piece numeric (ie, an array lookup?)
nextIsNumeric = /^\d+(\.|$)/.test(rest);
}
return function (doc) {
if (doc == null) // null or undefined
return [undefined];
var firstLevel = doc[first];
// We don't "branch" at the final level.
if (!lookupRest)
return [firstLevel];
// It's an empty array, and we're not done: we won't find anything.
if (isArray(firstLevel) && firstLevel.length === 0)
return [undefined];
// For each result at this level, finish the lookup on the rest of the key,
// and return everything we find. Also, if the next result is a number,
// don't branch here.
//
// Technically, in MongoDB, we should be able to handle the case where
// objects have numeric keys, but Mongo doesn't actually handle this
// consistently yet itself, see eg
// https://jira.mongodb.org/browse/SERVER-2898
// https://github.com/mongodb/mongo/blob/master/jstests/array_match2.js
if (!isArray(firstLevel) || nextIsNumeric)
firstLevel = [firstLevel];
return Array.prototype.concat.apply([], _.map(firstLevel, lookupRest));
};
};
// The main compilation function for a given selector.
var compileDocumentSelector = function (docSelector) {
var perKeySelectors = [];
_.each(docSelector, function (subSelector, key) {
if (key.substr(0, 1) === '$') {
// Outer operators are either logical operators (they recurse back into
// this function), or $where.
if (!_.has(LOGICAL_OPERATORS, key))
throw new Error("Unrecognized logical operator: " + key);
perKeySelectors.push(LOGICAL_OPERATORS[key](subSelector));
} else {
var lookUpByIndex = LocalCollection._makeLookupFunction(key);
var valueSelectorFunc = compileValueSelector(subSelector);
perKeySelectors.push(function (doc) {
var branchValues = lookUpByIndex(doc);
// We apply the selector to each "branched" value and return true if any
// match. This isn't 100% consistent with MongoDB; eg, see:
// https://jira.mongodb.org/browse/SERVER-8585
return _.any(branchValues, valueSelectorFunc);
});
}
});
return function (doc) {
return _.all(perKeySelectors, function (f) {
return f(doc);
});
};
};
// Given a selector, return a function that takes one argument, a
// document, and returns true if the document matches the selector,
// else false.
LocalCollection._compileSelector = function (selector) {
// you can pass a literal function instead of a selector
if (selector instanceof Function)
return function (doc) {return selector.call(doc);};
// shorthand -- scalars match _id
if (LocalCollection._selectorIsId(selector)) {
return function (doc) {
return EJSON.equals(doc._id, selector);
};
}
// protect against dangerous selectors. falsey and {_id: falsey} are both
// likely programmer error, and not what you want, particularly for
// destructive operations.
if (!selector || (('_id' in selector) && !selector._id))
return function (doc) {return false;};
// Top level can't be an array or true or binary.
if (typeof(selector) === 'boolean' || isArray(selector) ||
EJSON.isBinary(selector))
throw new Error("Invalid selector: " + selector);
return compileDocumentSelector(selector);
};
// Give a sort spec, which can be in any of these forms:
// {"key1": 1, "key2": -1}
// [["key1", "asc"], ["key2", "desc"]]
// ["key1", ["key2", "desc"]]
//
// (.. with the first form being dependent on the key enumeration
// behavior of your javascript VM, which usually does what you mean in
// this case if the key names don't look like integers ..)
//
// return a function that takes two objects, and returns -1 if the
// first object comes first in order, 1 if the second object comes
// first, or 0 if neither object comes before the other.
LocalCollection._compileSort = function (spec) {
var sortSpecParts = [];
if (spec instanceof Array) {
for (var i = 0; i < spec.length; i++) {
if (typeof spec[i] === "string") {
sortSpecParts.push({
lookup: LocalCollection._makeLookupFunction(spec[i]),
ascending: true
});
} else {
sortSpecParts.push({
lookup: LocalCollection._makeLookupFunction(spec[i][0]),
ascending: spec[i][1] !== "desc"
});
}
}
} else if (typeof spec === "object") {
for (var key in spec) {
sortSpecParts.push({
lookup: LocalCollection._makeLookupFunction(key),
ascending: spec[key] >= 0
});
}
} else {
throw Error("Bad sort specification: ", JSON.stringify(spec));
}
if (sortSpecParts.length === 0)
return function () {return 0;};
// reduceValue takes in all the possible values for the sort key along various
// branches, and returns the min or max value (according to the bool
// findMin). Each value can itself be an array, and we look at its values
// too. (ie, we do a single level of flattening on branchValues, then find the
// min/max.)
var reduceValue = function (branchValues, findMin) {
var reduced;
var first = true;
// Iterate over all the values found in all the branches, and if a value is
// an array itself, iterate over the values in the array separately.
_.each(branchValues, function (branchValue) {
// Value not an array? Pretend it is.
if (!isArray(branchValue))
branchValue = [branchValue];
// Value is an empty array? Pretend it was missing, since that's where it
// should be sorted.
if (isArray(branchValue) && branchValue.length === 0)
branchValue = [undefined];
_.each(branchValue, function (value) {
// We should get here at least once: lookup functions return non-empty
// arrays, so the outer loop runs at least once, and we prevented
// branchValue from being an empty array.
if (first) {
reduced = value;
first = false;
} else {
// Compare the value we found to the value we found so far, saving it
// if it's less (for an ascending sort) or more (for a descending
// sort).
var cmp = LocalCollection._f._cmp(reduced, value);
if ((findMin && cmp > 0) || (!findMin && cmp < 0))
reduced = value;
}
});
});
return reduced;
};
return function (a, b) {
for (var i = 0; i < sortSpecParts.length; ++i) {
var specPart = sortSpecParts[i];
var aValue = reduceValue(specPart.lookup(a), specPart.ascending);
var bValue = reduceValue(specPart.lookup(b), specPart.ascending);
var compare = LocalCollection._f._cmp(aValue, bValue);
if (compare !== 0)
return specPart.ascending ? compare : -compare;
};
return 0;
};
};
exports.compileDocumentSelector = compileDocumentSelector;
exports.compileSort = LocalCollection._compileSort;