forked from persvr/rql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
query.js
292 lines (275 loc) · 8.37 KB
/
query.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
/**
* Provides a Query constructor with chainable capability. For example:
* var Query = require("./query").Query;
* query = Query();
* query.executor = function(query){
* require("./js-array").query(query, params, data); // if we want to operate on an array
* };
* query.eq("a", 3).le("b", 4).forEach(function(object){
* // for each object that matches the query
* });
*/
if (typeof define !== 'function') { var define = require('amdefine')(module) }
define(["exports", "./parser", "./util/each"], function(exports, parser, each){
var parseQuery = parser.parseQuery;
try{
var when = require("promised-io/promise").when;
}catch(e){
when = function(value, callback){callback(value)};
}
parser.Query = function(seed, params){
if (typeof seed === 'string')
return parseQuery(seed, params);
var q = new Query();
if (seed && seed.name && seed.args)
q.name = seed.name, q.args = seed.args;
return q;
};
exports.Query = parser.Query;
//TODO:THE RIGHT WAY IS:exports.knownOperators = Object.keys(jsarray.operators || {}).concat(Object.keys(jsarray.jsOperatorMap || {}));
exports.knownOperators = ["sort", "match", "in", "out", "or", "and", "select", "contains", "excludes", "values", "limit", "distinct", "recurse", "aggregate", "between", "sum", "mean", "max", "min", "count", "first", "one", "eq", "ne", "le", "ge", "lt", "gt"];
exports.knownScalarOperators = ["mean", "sum", "min", "max", "count", "first", "one"];
exports.arrayMethods = ["forEach", "reduce", "map", "filter", "indexOf", "some", "every"];
function Query(name){
this.name = name || "and";
this.args = [];
}
function serializeArgs(array, delimiter){
var results = [];
for(var i = 0, l = array.length; i < l; i++){
results.push(queryToString(array[i]));
}
return results.join(delimiter);
}
exports.Query.prototype = Query.prototype;
Query.prototype.toString = function(){
return this.name === "and" ?
serializeArgs(this.args, "&") :
queryToString(this);
};
function queryToString(part) {
if (part instanceof Array) {
return '(' + serializeArgs(part, ",")+')';
}
if (part && part.name && part.args) {
return [
part.name,
"(",
serializeArgs(part.args, ","),
")"
].join("");
}
return exports.encodeValue(part);
};
function encodeString(s) {
if (typeof s === "string") {
s = encodeURIComponent(s);
if (s.match(/[\(\)]/)) {
s = s.replace("(","%28").replace(")","%29");
};
}
return s;
}
/**
* Encode a value of a part's argument for use in an RQL string.
* @param {*} val - The value to encode.
* @returns {string} The encoded value, URI-safe.
*/
exports.encodeValue = function(val) {
// Remember whether any encoding took place. The function force-encodes
// the value as a plain string at the end as a last resort.
var encoded = false;
// Try encoding the value. If it throws, go to our failsafe.
try {
// Check whether casting the value to a string and parsing it would
// result in the input value (i.e. if the value can be left prefix-less).
var stringVal = '' + ((val && val.toISOString) ? val.toISOString() : val);
var parsedStringVal = parser.converters["default"](stringVal);
if (val === parsedStringVal) {
return encodeString(String(val));
}
// Now, only non-trivial cases are left:
var type = typeof val;
if (val instanceof RegExp) {
// TODO: control whether to we want simpler glob() style
val = val.toString();
var i = val.lastIndexOf('/');
type = val.substring(i).indexOf('i') >= 0 ? "re" : "RE";
val = encodeString(val.substring(1, i));
encoded = true;
}
if (type === "object") {
// Assume it's a date - it's the only other object type we support:
type = "epoch";
val = val.getTime();
encoded = true;
}
if (type === "string") {
// It's a string, but it doesn't parse to its own exact value.
// This happens when the input is a String('null') for example -
// the auto-converter parses null to type null, so we need a prefix.
val = encodeString(val);
encoded = true;
}
val = [type, val].join(":");
} catch (conversionError) {
// The conversion necessity check has failed and we have not encoded the value. The next conditional block will take care of it.
}
if (!encoded && typeof val === "string") {
val = encodeString(val);
}
val = String(val);
return val;
};
exports.updateQueryMethods = function(){
each(exports.knownOperators, function(name){
Query.prototype[name] = function(){
var newQuery = new Query();
newQuery.executor = this.executor;
var newTerm = new Query(name);
newTerm.args = Array.prototype.slice.call(arguments);
newQuery.args = this.args.concat([newTerm]);
return newQuery;
};
});
each(exports.knownScalarOperators, function(name){
Query.prototype[name] = function(){
var newQuery = new Query();
newQuery.executor = this.executor;
var newTerm = new Query(name);
newTerm.args = Array.prototype.slice.call(arguments);
newQuery.args = this.args.concat([newTerm]);
return newQuery.executor(newQuery);
};
});
each(exports.arrayMethods, function(name){
// this makes no guarantee of ensuring that results supports these methods
Query.prototype[name] = function(){
var args = arguments;
return when(this.executor(this), function(results){
return results[name].apply(results, args);
});
};
});
};
exports.updateQueryMethods();
/* recursively iterate over query terms calling 'fn' for each term */
Query.prototype.walk = function(fn, options){
options = options || {};
function walk(name, terms){
terms = terms || [];
var i = 0,
l = terms.length,
term,
args,
func,
newTerm;
for (; i < l; i++) {
term = terms[i];
if (term == null) {
term = {};
}
func = term.name;
args = term.args;
if (!func || !args) {
continue;
}
if (args[0] instanceof Query) {
walk.call(this, func, args);
}
else {
newTerm = fn.call(this, func, args);
if (newTerm && newTerm.name && newTerm.ags) {
terms[i] = newTerm;
}
}
}
}
walk.call(this, this.name, this.args);
};
/* append a new term */
Query.prototype.push = function(term){
this.args.push(term);
return this;
};
/* disambiguate query */
Query.prototype.normalize = function(options){
options = options || {};
options.primaryKey = options.primaryKey || 'id';
options.map = options.map || {};
var result = {
original: this,
sort: [],
limit: [Infinity, 0, Infinity],
skip: 0,
limit: Infinity,
select: [],
values: false
};
var plusMinus = {
// [plus, minus]
sort: [1, -1],
select: [1, 0]
};
function normal(func, args){
// cache some parameters
if (func === 'sort' || func === 'select') {
result[func] = args;
var pm = plusMinus[func];
result[func+'Arr'] = result[func].map(function(x){
if (x instanceof Array) x = x.join('.');
var o = {};
var a = /([-+]*)(.+)/.exec(x);
o[a[2]] = pm[(a[1].charAt(0) === '-')*1];
return o;
});
result[func+'Obj'] = {};
result[func].forEach(function(x){
if (x instanceof Array) x = x.join('.');
var a = /([-+]*)(.+)/.exec(x);
result[func+'Obj'][a[2]] = pm[(a[1].charAt(0) === '-')*1];
});
} else if (func === 'limit') {
// validate limit() args to be numbers, with sane defaults
var limit = args;
result.skip = +limit[1] || 0;
limit = +limit[0] || 0;
if (options.hardLimit && limit > options.hardLimit)
limit = options.hardLimit;
result.limit = limit;
result.needCount = true;
} else if (func === 'values') {
// N.B. values() just signals we want array of what we select()
result.values = true;
} else if (func === 'eq') {
// cache primary key equality -- useful to distinguish between .get(id) and .query(query)
var t = typeof args[1];
//if ((args[0] instanceof Array ? args[0][args[0].length-1] : args[0]) === options.primaryKey && ['string','number'].indexOf(t) >= 0) {
if (args[0] === options.primaryKey && ('string' === t || 'number' === t)) {
result.pk = String(args[1]);
}
}
// cache search conditions
//if (options.known[func])
// map some functions
/*if (options.map[func]) {
func = options.map[func];
}*/
}
this.walk(normal);
return result;
};
/* FIXME: an example will be welcome
Query.prototype.toMongo = function(options){
return this.normalize({
primaryKey: '_id',
map: {
ge: 'gte',
le: 'lte'
},
known: ['lt','lte','gt','gte','ne','in','nin','not','mod','all','size','exists','type','elemMatch']
});
};
*/
return exports;
});