blob: 6d633992d7c0e4fa028aba4c7f79a69fcb443dde [file] [log] [blame]
Eugenia Gabrielova12de0302013-10-18 02:25:39 -07001/**
2* Asterix SDK - Beta Version
3* @author Eugenia Gabrielov <genia.likes.science@gmail.com>
4*
5* This is a Javascript helper file for generating AQL queries for AsterixDB (https://code.google.com/p/asterixdb/)
6*/
7
8/**
9* AsterixDBConnection
10*
11* This is a handler for connections to a local AsterixDB REST API Endpoint.
12* This initialization takes as input a configuraiton object, and initializes
13* same basic functionality.
14*/
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -070015function AsterixDBConnection(configuration) {
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -070016 // Initialize AsterixDBConnection properties
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -070017 this._properties = {};
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -070018
19 // Set dataverse as null for now, this needs to be set by the user.
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -070020 this._properties["dataverse"] = "";
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -070021
22 // By default, we will wait for calls to the REST API to complete. The query method
23 // sends a different setting when executed asynchronously. Calls that do not specify a mode
24 // will be executed synchronously.
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -070025 this._properties["mode"] = "synchronous";
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -070026
27 // These are the default error behaviors for Asterix and ajax errors, respectively.
28 // They can be overridden by calling initializing your AsterixDBConnection like so:
29 // adb = new AsterixDBConnection({
30 // "error" : function(data) {
31 // // override here...
32 // });
33 // and similarly for ajax_error, just pass in the configuration as a json object.
34 this._properties["error"] = function(data) {
35 alert("Asterix REST API Error:\n" + data["error-code"][0] + "\n" + data["error-code"][1]);
36 };
37
38 this._properties["ajax_error"] = function(message) {
39 alert("[Ajax Error]\n" + message);
40 };
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -070041
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -070042 // This is the default path to the local Asterix REST API. Can be overwritten for remote configurations
43 // or for demo setup purposes (such as with a proxy handler with Python or PHP.
44 this._properties["endpoint_root"] = "http://localhost:19002/";
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -070045
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -070046 // If we have passed in a configuration, we will update the internal properties
47 // using that configuration. You can do things such as include a new endpoint_root,
48 // a new error function, a new dataverse, etc. You can even store extra info.
49 //
50 // NOTE Long-term, this should have more strict limits.
51 var configuration = configuration || {};
52
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -070053 for (var key in configuration) {
54 this._properties[key] = configuration[key];
55 }
56
57 return this;
58}
59
60
Eugenia Gabrielova12de0302013-10-18 02:25:39 -070061/**
62* dataverse
63*
64* Sets dataverse for execution for the AsterixDBConnection.
65*/
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -070066AsterixDBConnection.prototype.dataverse = function(dataverseName) {
67 this._properties["dataverse"] = dataverseName;
68
69 return this;
70};
71
72
Eugenia Gabrielova12de0302013-10-18 02:25:39 -070073/**
74* query (http://asterix.ics.uci.edu/documentation/api.html#QueryApi)
75*
76* @param statements, statements of an AQL query
77* @param successFn, a function to execute if this query is run successfully
78* @param mode, a string either "synchronous" or "asynchronous", depending on preferred
79* execution mode.
80*/
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -070081AsterixDBConnection.prototype.query = function(statements, successFn, mode) {
82
83 if ( typeof statements === 'string') {
84 statements = [ statements ];
85 }
86
87 var m = typeof mode ? mode : "synchronous";
Eugenia Gabrielova12de0302013-10-18 02:25:39 -070088
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -070089 var query = "use dataverse " + this._properties["dataverse"] + ";\n" + statements.join("\n");
90
91 this._api(
92 {
93 "query" : query,
94 "mode" : m
95 },
96 successFn,
97 "query"
98 );
99
100 return this;
101};
102
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700103/**
104* query_status (http://asterix.ics.uci.edu/documentation/api.html#QueryStatusApi)
105*
106* @param handle, a json object of the form {"handle" : handleObject}, where
107* the handle object is an opaque handle previously returned
108* from an asynchronous call.
109* @param successFn, a function to call on successful execution of this API call.
110*/
111AsterixDBConnection.prototype.query_status = function(handle, successFn) {
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700112 this._api(
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700113 handle,
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700114 successFn,
115 "query/status"
116 );
117
118 return this;
119};
120
121
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700122/**
123* query_result (http://asterix.ics.uci.edu/documentation/api.html#AsynchronousResultApi)
124*
125* handle, a json object of the form {"handle" : handleObject}, where
126* the handle object is an opaque handle previously returned
127* from an asynchronous call.
128* successFn, a function to call on successful execution of this API call.
129*/
130AsterixDBConnection.prototype.query_result = function(handle, successFn) {
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700131 this._api(
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700132 handle,
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700133 successFn,
134 "query/result"
135 );
136
137 return this;
138};
139
140
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700141/**
142* ddl (http://asterix.ics.uci.edu/documentation/api.html#DdlApi)
143*
144* @param statements, statements to run through ddl api
145* @param successFn, a function to execute if they are successful
146*/
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700147AsterixDBConnection.prototype.ddl = function(statements, successFn) {
148 if ( typeof statements === 'string') {
149 statements = [ statements ];
150 }
151
152 this._api(
153 {
154 "ddl" : "use dataverse " + this._properties["dataverse"] + ";\n" + statements.join("\n")
155 },
156 successFn,
157 "ddl"
158 );
159}
160
161
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700162/**
163* update (http://asterix.ics.uci.edu/documentation/api.html#UpdateApi)
164*
165* @param statements, statement(s) for an update API call
166* @param successFn, a function to run if this is executed successfully.
167*
168* This is an AsterixDBConnection handler for the update API. It passes statements provided
169* to the internal API endpoint handler.
170*/
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700171AsterixDBConnection.prototype.update = function(statements, successFn) {
172 if ( typeof statements === 'string') {
173 statements = [ statements ];
174 }
175
176 this._api(
177 {
178 "statements" : "use dataverse " + this._properties["dataverse"] + ";\n" + statements.join("\n")
179 },
180 successFn,
181 "update"
182 );
183}
184
185
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700186/**
187* meta
188* @param statements, a string or a list of strings representing an Asterix query object
189* @param successFn, a function to execute if call succeeds
190*
191* Queries without a dataverse. This is a work-around for an Asterix REST API behavior
192* that sometiems throws an error. This is handy for Asterix Metadata queries.
193*/
194AsterixDBConnection.prototype.meta = function(statements, successFn) {
195
196 if ( typeof statements === 'string') {
197 statements = [ statements ];
198 }
199
200 var query = statements.join("\n");
201
202 this._api(
203 {
204 "query" : query,
205 "mode" : "synchronous"
206 },
207 successFn,
208 "query"
209 );
210
211 return this;
212}
213
214
215/**
216* _api
217*
218* @param json, the data to be passed with the request
219* @param onSuccess, the success function to be run if this succeeds
220* @param endpoint, a string representing one of the Asterix API endpoints
221*
222* Documentation of endpoints is here:
223* http://asterix.ics.uci.edu/documentation/api.html
224*
225* This is treated as an internal method for making the actual call to the API.
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700226*/
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700227AsterixDBConnection.prototype._api = function(json, onSuccess, endpoint) {
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -0700228
229 // The success function is called if the response is successful and returns data,
230 // or is just OK.
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700231 var success_fn = onSuccess;
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -0700232
233 // This is the error function. Called if something breaks either on the Asterix side
234 // or in the Ajax call.
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700235 var error_fn = this._properties["error"];
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -0700236 var ajax_error_fn = this._properties["ajax_error"];
237
238 // This is the target endpoint from the REST api, called as a string.
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700239 var endpoint_url = this._properties["endpoint_root"] + endpoint;
240
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -0700241 // This SDK does not rely on jQuery, but utilizes its Ajax capabilities when present.
242 if (window.jQuery) {
243 $.ajax({
244
245 // The Asterix API does not accept post requests.
246 type : 'GET',
247
248 // This is the endpoint url provided by combining the default
249 // or reconfigured endpoint root along with the appropriate api endpoint
250 // such as "query" or "update".
251 url : endpoint_url,
252
253 // This is the data in the format specified on the API documentation.
254 data : json,
255
256 // We send out the json datatype to make sure our data is parsed correctly.
257 dataType : "json",
258
259 // The success option calls a function on success, which in this case means
260 // something was returned from the API. However, this does not mean the call succeeded
261 // on the REST API side, it just means we got something back. This also contains the
262 // error return codes, which need to be handled before we call th success function.
263 success : function(data) {
Eugenia Gabrielovaf9fcd712013-10-20 02:37:35 -0700264
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -0700265 // Check Asterix Response for errors
266 // See http://asterix.ics.uci.edu/documentation/api.html#ErrorCodes
267 if (data["error-code"]) {
268 error_fn(data);
269
270 // Otherwise, run our provided success function
271 } else {
272 success_fn(data);
273 }
274 },
275
276 // This is the function that gets called if there is an ajax-related (non-Asterix)
277 // error. Network errors, empty response bodies, syntax errors, and a number of others
278 // can pop up.
279 error : function(data) {
Eugenia Gabrielovaf9fcd712013-10-20 02:37:35 -0700280
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -0700281 // Some of the Asterix API endpoints return empty responses on success.
282 // However, the ajax function treats these as errors while reporting a
283 // 200 OK code with no payload. So we will check for that, otherwise
284 // alert of an error. An example response is as follows:
285 // {"readyState":4,"responseText":"","status":200,"statusText":"OK"}
286 if (data["status"] == 200 && data["responseText"] == "") {
287 success_fn(data);
288 } else {
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700289 // TODO more graceful errors
Eugenia Gabrielovaf9fcd712013-10-20 02:37:35 -0700290 alert("[Ajax Error]\n" + JSON.stringify(data));
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -0700291 }
292 }
293 });
294 } else {
295 alert("no jquery");
296 var xmlhttp;
297 }
298 // XML Http Request
299 /*var xmlhttp;
300
301 xmlhttp = new XMLHttpRequest();
302 xmlhttp.onreadystatechange = function(){
303 if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
304 alert(xmlhttp.responseText);
305 //callback(xmlhttp.responseText);
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700306 }
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -0700307 }
308 xmlhttp.open("GET", endpoint_url, true);
309 xmlhttp.send();*/
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700310
311 return this;
312};
313
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700314// Asterix Expressions - Base
315function AExpression () {
316
317 this._properties = {};
318 this._success = function() {};
319
320 if (arguments.length == 1) {
321 this._properties["value"] = arguments[0];
322 }
323
324 return this;
325}
326
327
328AExpression.prototype.bind = function(options) {
329 var options = options || {};
330
331 if (options.hasOwnProperty("success")) {
332 this._success = options["success"];
333 }
334
335 if (options.hasOwnProperty("return")) {
336 this._properties["return"] = " return " + options["return"].val();
337 }
338};
339
340
341AExpression.prototype.run = function(successFn) {
342 return this;
343};
344
345
346AExpression.prototype.val = function() {
347
348 var value = "";
349
350 // If there is a dataverse defined, provide it.
351 if (this._properties.hasOwnProperty("dataverse")) {
352 value += "use dataverse " + this._properties["dataverse"] + ";\n";
353 };
354
355 if (this._properties.hasOwnProperty("value")) {
356 value += this._properties["value"].toString();
357 }
358
359 return value;
360};
361
362
363// @param expressionValue [String]
364AExpression.prototype.set = function(expressionValue) {
365 this._properties["value"] = expressionValue;
366 return this;
367};
368
369
370// AQL Statements
371// SingleStatement ::= DataverseDeclaration
372// | FunctionDeclaration
373// | CreateStatement
374// | DropStatement
375// | LoadStatement
376// | SetStatement
377// | InsertStatement
378// | DeleteStatement
379// | Query
380function InsertStatement(quantifiedName, query) {
381 AExpression.call(this);
382
383 var innerQuery = "";
384 if (query instanceof AExpression) {
385 innerQuery = query.val();
386 } else if (typeof query == "object" && Object.getPrototypeOf( query ) === Object.prototype ) {
387
388 var insertStatements = [];
389 for (querykey in query) {
390 if (query[querykey] instanceof AExpression) {
391 insertStatements.push('"' + querykey + '" : ' + query[querykey].val());
392 } else if (typeof query[querykey] == "string") {
393 insertStatements.push('"' + querykey + '" : ' + query[querykey]);
394 } else {
395 insertStatements.push('"' + querykey + '" : ' + query[querykey].toString());
396 }
397 }
398
399 innerQuery = "{" + insertStatements.join(', ') + "}";
400 }
401
402 var statement = "insert into dataset " + quantifiedName + "(" + innerQuery + ");";
403
404 AExpression.prototype.set.call(this, statement);
405
406 return this;
407}
408
409InsertStatement.prototype = Object.create(AExpression.prototype);
410InsertStatement.prototype.constructor = InsertStatement;
411
412
413// Delete Statement
414// DeleteStatement ::= "delete" Variable "from" "dataset" QualifiedName ( "where" Expression )?
415function DeleteStatement (variable, quantifiedName, whereExpression) {
416 AExpression.call(this);
417
418 var statement = "delete " + variable + " from dataset " + quantifiedName;
419
420 if (whereExpression instanceof AExpression) {
421 statement += " where " + whereExpression.val();
422 }
423
424 AExpression.prototype.set.call(this, statement);
425
426 return this;
427}
428
429DeleteStatement.prototype = Object.create(AExpression.prototype);
430DeleteStatement.prototype.constructor = DeleteStatement;
431
432// SetStatement
433//
434// Grammar
435// "set" Identifier StringLiteral
436function SetStatement (identifier, stringLiteral) {
437 AExpression.call(this);
438
439 var statement = "set " + identifier + ' "' + stringLiteral + '";';
440
441 AExpression.prototype.set.call(this, statement);
442
443 return this;
444}
445
446SetStatement.prototype = Object.create(AExpression.prototype);
447SetStatement.prototype.constructor = SetStatement;
448
449
450// Other Expressions
451
452// FunctionExpression
453// Parent: AsterixExpression
454//
455// @param options [Various],
456// @key function [String], a function to be applid to the expression
457// @key expression [AsterixExpression or AQLClause] an AsterixExpression/Clause to which the fn will be applied
458function FunctionExpression() {
459
460 // Initialize superclass
461 AExpression.call(this);
462
463 this._properties["function"] = "";
464 this._properties["expressions"] = [];
465
466 // Check for fn/expression input
467 if (arguments.length >= 2 && typeof arguments[0] == "string") {
468
469 this._properties["function"] = arguments[0];
470
471 for (i = 1; i < arguments.length; i++) {
472 if (arguments[i] instanceof AExpression || arguments[i] instanceof AQLClause) {
473 this._properties["expressions"].push(arguments[i]);
474 } else {
475 this._properties["expressions"].push(new AExpression(arguments[i]));
476 }
477 }
478 }
479
480 // Return FunctionCallExpression object
481 return this;
482}
483
484
485FunctionExpression.prototype = Object.create(AExpression.prototype);
486FunctionExpression.prototype.constructor = FunctionExpression;
487
488
489FunctionExpression.prototype.val = function () {
490 var fn_args = [];
491 for (var i = 0; i < this._properties["expressions"].length; i++) {
492 fn_args.push(this._properties["expressions"][i].val());
493 }
494
495 return this._properties["function"] + "(" + fn_args.join(", ") + ")";
496};
497
498
499// FLWOGRExpression
500//
501// FLWOGRExpression ::= ( ForClause | LetClause ) ( Clause )* "return" Expression
502function FLWOGRExpression (options) {
503 // Initialize superclass
504 AExpression.call(this);
505
506 this._properties["clauses"] = [];
507 this._properties["minSize"] = 0;
508
509 // Bind options and return
510 this.bind(options);
511 return this;
512}
513
514
515FLWOGRExpression.prototype = Object.create(AExpression.prototype);
516FLWOGRExpression.prototype.constructor = FLWOGRExpression;
517
518
519FLWOGRExpression.prototype.bind = function(options) {
520 AExpression.prototype.bind.call(this, options);
521
522 var options = options || {};
523
524 if (options instanceof SetStatement) {
525 this._properties["clauses"].push(options);
526 this._properties["minSize"] += 1;
527 }
528
529 if (this._properties["clauses"].length <= this._properties["minSize"]) {
530 // Needs to start with for or let clause
531 if (options instanceof ForClause || options instanceof LetClause) {
532 this._properties["clauses"].push(options);
533 }
534 } else {
535 if (options instanceof AQLClause) {
536 this._properties["clauses"].push(options);
537 }
538 }
539
540 return this;
541};
542
543
544FLWOGRExpression.prototype.val = function() {
545 var value = AExpression.prototype.val.call(this);
546
547 var clauseValues = [];
548 for (var c in this._properties["clauses"]) {
549 clauseValues.push(this._properties["clauses"][c].val());
550 }
551
552 return value + clauseValues.join("\n");// + ";";
553};
554
555// Pretty Expression Shorthand
556
557FLWOGRExpression.prototype.ReturnClause = function(expression) {
558 return this.bind(new ReturnClause(expression));
559};
560
561FLWOGRExpression.prototype.ForClause = function() {
562 return this.bind(new ForClause(Array.prototype.slice.call(arguments)));
563};
564
565FLWOGRExpression.prototype.LetClause = function() {
566 return this.bind(new LetClause(Array.prototype.slice.call(arguments)));
567};
568
569FLWOGRExpression.prototype.WhereClause = function() {
570 return this.bind(new WhereClause(Array.prototype.slice.call(arguments)));
571};
572
573FLWOGRExpression.prototype.and = function() {
574 var args = Array.prototype.slice.call(arguments);
575 args.push(true);
576 return this.bind(new WhereClause().and(args));
577};
578
579FLWOGRExpression.prototype.or = function() {
580 var args = Array.prototype.slice.call(arguments);
581 args.push(true);
582 return this.bind(new WhereClause().or(args));
583};
584
585FLWOGRExpression.prototype.OrderbyClause = function() {
586 return this.bind(new OrderbyClause(Array.prototype.slice.call(arguments)));
587};
588
589
590FLWOGRExpression.prototype.GroupClause = function() {
591 return this.bind(new GroupClause(Array.prototype.slice.call(arguments)));
592};
593
594FLWOGRExpression.prototype.LimitClause = function() {
595 return this.bind(new LimitClause(Array.prototype.slice.call(arguments)));
596};
597
598FLWOGRExpression.prototype.DistinctClause = function() {
599 return this.bind(new DistinctClause(Array.prototype.slice.call(arguments)));
600};
601
602FLWOGRExpression.prototype.AQLClause = function() {
603 return this.bind(new AQLClause(Array.prototype.slice.call(arguments)));
604};
605
606
607// AQLClause
608//
609// Base Clause ::= ForClause | LetClause | WhereClause | OrderbyClause | GroupClause | LimitClause | DistinctClause
610function AQLClause() {
611 this._properties = {};
612 this._properties["clause"] = "";
613 this._properties["stack"] = [];
614 if (typeof arguments[0] == 'string') {
615 this._properties["clause"] = arguments[0];
616 }
617 return this;
618}
619
620AQLClause.prototype.val = function() {
621 var value = this._properties["clause"];
622
623 return value;
624};
625
626AQLClause.prototype.bind = function(options) {
627
628 if (options instanceof AQLClause) {
629 this._properties["clause"] += " " + options.val();
630 }
631
632 return this;
633};
634
635AQLClause.prototype.set = function(value) {
636 this._properties["clause"] = value;
637 return this;
638};
639
640
641// ForClause
642//
643// Grammar:
644// "for" Variable ( "at" Variable )? "in" ( Expression )
645//
646// @param for_variable [String], REQUIRED, first variable in clause
647// @param at_variable [String], NOT REQUIRED, first variable in clause
648// @param expression [AsterixExpression], REQUIRED, expression to evaluate
649function ForClause(for_variable, at_variable, expression) {
650 AQLClause.call(this);
651
652 var parameters = [];
653 if (arguments[0] instanceof Array) {
654 parameters = arguments[0];
655 } else {
656 parameters = arguments;
657 }
658
659 this._properties["clause"] = "for " + parameters[0];
660
661 if (parameters.length == 3) {
662 this._properties["clause"] += " at " + parameters[1];
663 this._properties["clause"] += " in " + parameters[2].val();
664 } else if (parameters.length == 2) {
665 this._properties["clause"] += " in " + parameters[1].val();
666 }
667
668 return this;
669}
670
671ForClause.prototype = Object.create(AQLClause.prototype);
672ForClause.prototype.constructor = ForClause;
673
674
675// LetClause
676//
677// Grammar:
678// LetClause ::= "let" Variable ":=" Expression
679//
680// @param let_variable [String]
681// @param expression [AExpression]
682//
683// TODO Vigorous error checking
684function LetClause(let_variable, expression) {
685 AQLClause.call(this);
686
687 var parameters = [];
688 if (arguments[0] instanceof Array) {
689 parameters = arguments[0];
690 } else {
691 parameters = arguments;
692 }
693
694 this._properties["clause"] = "let " + parameters[0] + " := ";
695 this._properties["clause"] += parameters[1].val();
696
697 return this;
698}
699
700LetClause.prototype = Object.create(AQLClause.prototype);
701LetClause.prototype.constructor = LetClause;
702
703
704// ReturnClause
705//
706// Grammar:
707// return [AQLExpression]
708function ReturnClause(expression) {
709 AQLClause.call(this);
710
711 this._properties["clause"] = "return ";
712
713 if (expression instanceof AExpression || expression instanceof AQLClause) {
714 this._properties["clause"] += expression.val();
715
716 } else if ( typeof expression == "object" && Object.getPrototypeOf( expression ) === Object.prototype ) {
717
718 this._properties["clause"] += "\n{\n";
719 var returnStatements = [];
720 for (returnValue in expression) {
721
722 if (expression[returnValue] instanceof AExpression) {
723 returnStatements.push('"' + returnValue + '" ' + " : " + expression[returnValue].val());
724 } else if (typeof expression[returnValue] == "string") {
725 returnStatements.push('"' + returnValue + '" ' + " : " + expression[returnValue]);
726 }
727 }
728 this._properties["clause"] += returnStatements.join(",\n");
729 this._properties["clause"] += "\n}";
730
731 } else {
732 this._properties["clause"] += new AQLClause().set(expression).val();
733 }
734
735 return this;
736}
737
738
739ReturnClause.prototype = Object.create(AQLClause.prototype);
740ReturnClause.prototype.constructor = ReturnClause;
741
742
743// WhereClause
744//
745// Grammar:
746// ::= "where" Expression
747//
748// @param expression [BooleanExpression], pushes this expression onto the stack
749function WhereClause(expression) {
750 AQLClause.call(this);
751
752 this._properties["stack"] = [];
753
754 if (expression instanceof Array) {
755 this.bind(expression[0]);
756 } else {
757 this.bind(expression);
758 }
759
760 return this;
761}
762
763
764WhereClause.prototype = Object.create(AQLClause.prototype);
765WhereClause.prototype.constructor = WhereClause;
766
767
768WhereClause.prototype.bind = function(expression) {
769 if (expression instanceof AExpression) {
770 this._properties["stack"].push(expression);
771 }
772 return this;
773};
774
775
776WhereClause.prototype.val = function() {
777 var value = "";
778
779 if (this._properties["stack"].length == 0) {
780 return value;
781 }
782
783 var count = this._properties["stack"].length - 1;
784 while (count >= 0) {
785 value += this._properties["stack"][count].val() + " ";
786 count -= 1;
787 }
788
789 return "where " + value;
790};
791
792
793WhereClause.prototype.and = function() {
794
795 var parameters = [];
796 if (arguments[0] instanceof Array) {
797 parameters = arguments[0];
798 } else {
799 parameters = arguments;
800 }
801
802 var andClauses = [];
803 for (var expression in parameters) {
804
805 if (parameters[expression] instanceof AExpression) {
806 andClauses.push(parameters[expression].val());
807 }
808 }
809
810 if (andClauses.length > 0) {
811 this._properties["stack"].push(new AExpression().set(andClauses.join(" and ")));
812 }
813
814 return this;
815};
816
817
818WhereClause.prototype.or = function() {
819
820 var parameters = [];
821 if (arguments[0] instanceof Array) {
822 parameters = arguments[0];
823 } else {
824 parameters = arguments;
825 }
826
827 var orClauses = [];
828 for (var expression in parameters) {
829
830 if (parameters[expression] instanceof AExpression) {
831 orClauses.push(parameters[expression].val());
832 }
833 }
834
835 if (andClauses.length > 0) {
836 this._properties["stack"].push(new AExpression().set(orClauses.join(" and ")));
837 }
838
839 return this;
840};
841
842// LimitClause
843// Grammar:
844// LimitClause ::= "limit" Expression ( "offset" Expression )?
845//
846// @param limitExpression [REQUIRED, AQLExpression]
847// @param offsetExpression [OPTIONAL, AQLExpression]
848function LimitClause(limitExpression, offsetExpression) {
849
850 AQLClause.call(this);
851
852 var parameters = [];
853 if (arguments[0] instanceof Array) {
854 parameters = arguments[0];
855 } else {
856 parameters = arguments;
857 }
858
859 // limitExpression required
860 this._properties["clause"] = "limit " + parameters[0].val();
861
862 // Optional: Offset
863 if (parameters.length == 2) {
864 this._properties["clause"] += " offset " + parameters[1].val();
865 }
866
867 return this;
868}
869
870LimitClause.prototype = Object.create(AQLClause.prototype);
871LimitClause.prototype.constructor = LimitClause;
872
873
874// OrderbyClause
875//
876// Grammar:
877// OrderbyClause ::= "order" "by" Expression ( ( "asc" ) | ( "desc" ) )? ( "," Expression ( ( "asc" ) | ( "desc" ) )? )*
878//
879// @params AQLExpressions and asc/desc strings, in any quantity. At least one required.
880function OrderbyClause() {
881
882 AQLClause.call(this);
883
884 // At least one argument expression is required, and first should be expression
885 if (arguments.length == 0) {
886 this._properties["clause"] = null;
887 return this;
888 }
889
890 var parameters = [];
891 if (arguments[0] instanceof Array) {
892 parameters = arguments[0];
893 } else {
894 parameters = arguments;
895 }
896
897 var expc = 0;
898 var expressions = [];
899
900 while (expc < parameters.length) {
901
902 var expression = "";
903
904 if (parameters[expc] instanceof AExpression) {
905 expression += parameters[expc].val();
906 }
907
908 var next = expc + 1;
909 if (next < parameters.length && (parameters[next] == "asc" || parameters[next] == "desc")) {
910 expc++;
911 expression += " " + parameters[expc];
912 }
913
914 expressions.push(expression);
915
916 expc++;
917 }
918
919 this._properties["clause"] = "order by " + expressions.join(", ");
920 return this;
921}
922
923OrderbyClause.prototype = Object.create(AQLClause.prototype);
924OrderbyClause.prototype.constructor = OrderbyClause;
925
926
927// GroupClause
928//
929// Grammar:
930// GroupClause ::= "group" "by" ( Variable ":=" )? Expression ( "," ( Variable ":=" )? Expression )* ( "decor" Variable ":=" Expression ( "," "decor" Variable ":=" Expression )* )? "with" VariableRef ( "," VariableRef )*
931function GroupClause() {
932 AQLClause.call(this);
933
934 if (arguments.length == 0) {
935 this._properties["clause"] = null;
936 return this;
937 }
938
939 var parameters = [];
940 if (arguments[0] instanceof Array) {
941 parameters = arguments[0];
942 } else {
943 parameters = arguments;
944 }
945
946 var expc = 0;
947 var expressions = [];
948 var variableRefs = [];
949 var isDecor = false;
950
951 while (expc < parameters.length) {
952
953 if (parameters[expc] instanceof AExpression) {
954
955 isDecor = false;
956 expressions.push(parameters[expc].val());
957
958 } else if (typeof parameters[expc] == "string") {
959
960 // Special keywords, decor & with
961 if (parameters[expc] == "decor") {
962 isDecor = true;
963 } else if (parameters[expc] == "with") {
964 isDecor = false;
965 expc++;
966 while (expc < parameters.length) {
967 variableRefs.push(parameters[expc]);
968 expc++;
969 }
970
971 // Variables and variable refs
972 } else {
973
974 var nextc = expc + 1;
975 var expression = "";
976
977 if (isDecor) {
978 expression += "decor ";
979 isDecor = false;
980 }
981
982 expression += parameters[expc] + " := " + parameters[nextc].val();
983 expressions.push(expression);
984 expc++;
985 }
986 }
987
988 expc++;
989 }
990
991 this._properties["clause"] = "group by " + expressions.join(", ") + " with " + variableRefs.join(", ");
992 return this;
993}
994
995GroupClause.prototype = Object.create(AQLClause.prototype);
996GroupClause.prototype.constructor = GroupClause;
997
998
999// Quantified Expression
1000//
1001// Grammar
1002// QuantifiedExpression ::= ( ( "some" ) | ( "every" ) ) Variable "in" Expression ( "," Variable "in" Expression )* "satisfies" Expression
1003//
1004// @param String some/every
1005// @param [AExpression]
1006// @param [Aexpression] satisfiesExpression
1007function QuantifiedExpression (keyword, expressions, satisfiesExpression) {
1008 AExpression.call(this);
1009
1010 var expression = keyword + " ";
1011 var varsInExpressions = [];
1012
1013 for (var varInExpression in expressions) {
1014 varsInExpressions.push(varInExpression + " in " + expressions[varInExpression].val());
1015 }
1016 expression += varsInExpressions.join(", ") + " satisfies " + satisfiesExpression.val();
1017
1018 AExpression.prototype.set.call(this, expression);
1019
1020 return this;
1021}
1022
1023QuantifiedExpression.prototype = Object.create(AExpression.prototype);
1024QuantifiedExpression.prototype.constructor = QuantifiedExpression;
1025
1026QuantifiedExpression.prototype.val = function() {
1027 var value = AExpression.prototype.val.call(this);
1028 return "(" + value + ")";
1029};