forked from kriszyp/rql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.js
294 lines (281 loc) · 8.31 KB
/
parser.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
/**
* This module provides RQL parsing. For example:
* var parsed = require("./parser").parse("b=3&le(c,5)");
*/
({define:typeof define!="undefined"?define:function(deps, factory){module.exports = factory(exports, require("./util/contains"));}}).
define(["exports", "./util/contains"], function(exports, contains){
var operatorMap = {
"=": "eq",
"==": "eq",
">": "gt",
">=": "ge",
"<": "lt",
"<=": "le",
"!=": "ne"
};
exports.primaryKeyName = 'id';
exports.lastSeen = ['sort', 'select', 'values', 'limit'];
exports.jsonQueryCompatible = true;
function parse(/*String|Object*/query, parameters){
if (typeof query === "undefined" || query === null)
query = '';
var term = new exports.Query();
var topTerm = term;
topTerm.cache = {}; // room for lastSeen params
var topTermName = topTerm.name;
topTerm.name = '';
if(typeof query === "object"){
if(query instanceof exports.Query){
return query;
}
for(var i in query){
var term = new exports.Query();
topTerm.args.push(term);
term.name = "eq";
term.args = [i, query[i]];
}
return topTerm;
}
if(query.charAt(0) == "?"){
throw new URIError("Query must not start with ?");
}
if(exports.jsonQueryCompatible){
query = query.replace(/%3C=/g,"=le=").replace(/%3E=/g,"=ge=").replace(/%3C/g,"=lt=").replace(/%3E/g,"=gt=");
}
if(query.indexOf("/") > -1){ // performance guard
// convert slash delimited text to arrays
query = query.replace(/[\+\*\$\-:\w%\._]*\/[\+\*\$\-:\w%\._\/]*/g, function(slashed){
return "(" + slashed.replace(/\//g, ",") + ")";
});
}
// convert FIQL to normalized call syntax form
query = query.replace(/(\([\+\*\$\-:\w%\._,]+\)|[\+\*\$\-:\w%\._]*|)([<>!]?=(?:[\w]*=)?|>|<)(\([\+\*\$\-:\w%\._,]+\)|[\+\*\$\-:\w%\._]*|)/g,
// <--------- property -----------><------ operator -----><---------------- value ------------------>
function(t, property, operator, value){
if(operator.length < 3){
if(!operatorMap[operator]){
throw new URIError("Illegal operator " + operator);
}
operator = operatorMap[operator];
}
else{
operator = operator.substring(1, operator.length - 1);
}
return operator + '(' + property + "," + value + ")";
});
if(query.charAt(0)=="?"){
query = query.substring(1);
}
var leftoverCharacters = query.replace(/(\))|([&\|,])?([\+\*\$\-:\w%\._]*)(\(?)/g,
// <-closedParan->|<-delim-- propertyOrValue -----(> |
function(t, closedParan, delim, propertyOrValue, openParan){
if(delim){
if(delim === "&"){
setConjunction("and");
}
if(delim === "|"){
setConjunction("or");
}
}
if(openParan){
var newTerm = new exports.Query();
newTerm.name = propertyOrValue;
newTerm.parent = term;
call(newTerm);
}
else if(closedParan){
var isArray = !term.name;
term = term.parent;
if(!term){
throw new URIError("Closing paranthesis without an opening paranthesis");
}
if(isArray){
term.args.push(term.args.pop().args);
}
}
else if(propertyOrValue || delim === ','){
term.args.push(stringToValue(propertyOrValue, parameters));
// cache the last seen sort(), select(), values() and limit()
if (contains(exports.lastSeen, term.name)) {
topTerm.cache[term.name] = term.args;
}
// cache the last seen id equality
if (term.name === 'eq' && term.args[0] === exports.primaryKeyName) {
var id = term.args[1];
if (id && !(id instanceof RegExp)) id = id.toString();
topTerm.cache[exports.primaryKeyName] = id;
}
}
return "";
});
if(term.parent){
throw new URIError("Opening paranthesis without a closing paranthesis");
}
if(leftoverCharacters){
// any extra characters left over from the replace indicates invalid syntax
throw new URIError("Illegal character in query string encountered " + leftoverCharacters);
}
function call(newTerm){
term.args.push(newTerm);
term = newTerm;
// cache the last seen sort(), select(), values() and limit()
if (contains(exports.lastSeen, term.name)) {
topTerm.cache[term.name] = term.args;
}
}
function setConjunction(operator){
if(!term.name){
term.name = operator;
}
else if(term.name !== operator){
throw new Error("Can not mix conjunctions within a group, use paranthesis around each set of same conjuctions (& and |)");
}
}
function removeParentProperty(obj) {
if(obj && obj.args){
delete obj.parent;
var args = obj.args;
for(var i = 0, l = args.length; i < l; i++){
removeParentProperty(args[i]);
}
}
return obj;
};
removeParentProperty(topTerm);
if (!topTerm.name) {
topTerm.name = topTermName;
}
return topTerm;
};
exports.parse = exports.parseQuery = parse;
/* dumps undesirable exceptions to Query().error */
exports.parseGently = function(){
var terms;
try {
terms = parse.apply(this, arguments);
} catch(err) {
terms = new exports.Query();
terms.error = err.message;
}
return terms;
}
exports.commonOperatorMap = {
"and" : "&",
"or" : "|",
"eq" : "=",
"ne" : "!=",
"le" : "<=",
"ge" : ">=",
"lt" : "<",
"gt" : ">"
}
function stringToValue(string, parameters){
var converter = exports.converters['default'];
if(string.charAt(0) === "$"){
var param_index = parseInt(string.substring(1)) - 1;
return param_index >= 0 && parameters ? parameters[param_index] : undefined;
}
if(string.indexOf(":") > -1){
var parts = string.split(":");
converter = exports.converters[parts[0]];
if(!converter){
throw new URIError("Unknown converter " + parts[0]);
}
string = parts.slice(1).join(':');
}
return converter(string);
};
var autoConverted = exports.autoConverted = {
"true": true,
"false": false,
"null": null,
"undefined": undefined,
"Infinity": Infinity,
"-Infinity": -Infinity
};
exports.converters = {
auto: function(string){
if(autoConverted.hasOwnProperty(string)){
return autoConverted[string];
}
var number = +string;
if(isNaN(number) || number.toString() !== string){
/*var isoDate = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?Z$/.exec(x);
if (isoDate) {
date = new Date(Date.UTC(+isoDate[1], +isoDate[2] - 1, +isoDate[3], +isoDate[4], +isoDate[5], +isoDate[6], +isoDate[7] || 0));
}*/
string = decodeURIComponent(string);
if(exports.jsonQueryCompatible){
if(string.charAt(0) == "'" && string.charAt(string.length-1) == "'"){
return JSON.parse('"' + string.substring(1,string.length-1) + '"');
}
}
return string;
}
return number;
},
number: function(x){
var number = +x;
if(isNaN(number)){
throw new URIError("Invalid number " + number);
}
return number;
},
epoch: function(x){
var date = new Date(+x);
if (isNaN(date.getTime())) {
throw new URIError("Invalid date " + x);
}
return date;
},
isodate: function(x){
// four-digit year
var date = '0000'.substr(0,4-x.length)+x;
// pattern for partial dates
date += '0000-01-01T00:00:00Z'.substring(date.length);
return exports.converters.date(date);
},
date: function(x){
var isoDate = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?Z$/.exec(x);
var date;
if (isoDate) {
date = new Date(Date.UTC(+isoDate[1], +isoDate[2] - 1, +isoDate[3], +isoDate[4], +isoDate[5], +isoDate[6], +isoDate[7] || 0));
}else{
date = new Date(x);
}
if (isNaN(date.getTime())){
throw new URIError("Invalid date " + x);
}
return date;
},
"boolean": function(x){
return x === "true";
},
string: function(string){
return decodeURIComponent(string);
},
re: function(x){
return new RegExp(decodeURIComponent(x), 'i');
},
RE: function(x){
return new RegExp(decodeURIComponent(x));
},
glob: function(x){
var s = decodeURIComponent(x).replace(/([\\|\||\(|\)|\[|\{|\^|\$|\*|\+|\?|\.|\<|\>])/g, function(x){return '\\'+x;}).replace(/\\\*/g,'.*').replace(/\\\?/g,'.?');
if (s.substring(0,2) !== '.*') s = '^'+s; else s = s.substring(2);
if (s.substring(s.length-2) !== '.*') s = s+'$'; else s = s.substring(0, s.length-2);
return new RegExp(s, 'i');
}
};
// exports.converters["default"] can be changed to a different converter if you want
// a different default converter, for example:
// RP = require("rql/parser");
// RP.converters["default"] = RQ.converter.string;
exports.converters["default"] = exports.converters.auto;
// this can get replaced by the chainable query if query.js is loaded
exports.Query = function(){
this.name = "and";
this.args = [];
};
return exports;
});