2 function debug_dict_keys (msg, o) {
4 for (var k in o) keys.push(k);
5 messages.debug ("debug_dict_keys: " + msg + " keys= " + keys);
7 function debug_dict (msg, o) {
8 for (var k in o) messages.debug ("debug_dict: " + msg + " [" + k + "]=" + o[k]);
10 function debug_value (msg, value) {
11 messages.debug ("debug_value: " + msg + " " + value);
13 function debug_query (msg, query) {
14 if (query === undefined) messages.debug ("debug_query: " + msg + " -> undefined");
15 else if (query == null) messages.debug ("debug_query: " + msg + " -> null");
16 else if ('query_uuid' in query) messages.debug ("debug_query: " + msg + query.__repr());
17 else messages.debug ("debug_query: " + msg + " query= " + query);
20 /* ------------------------------------------------------------ */
22 // Constants that should be somehow moved to a plugin.js file
24 var FILTER_REMOVED = 2;
25 var CLEAR_FILTERS = 3;
27 var FIELD_REMOVED = 5;
30 var CLEAR_RECORDS = 8;
31 var FIELD_STATE_CHANGED = 9;
33 var IN_PROGRESS = 101;
36 /* Update requests related to subqueries */
38 var SET_REMOVED = 202;
41 var FIELD_REQUEST_CHANGE = 301;
42 var FIELD_REQUEST_ADD = 302;
43 var FIELD_REQUEST_REMOVE = 303;
44 var FIELD_REQUEST_RESET = 304;
46 var FIELD_REQUEST_PENDING = 301;
47 var FIELD_REQUEST_SUCCESS = 302;
48 var FIELD_REQUEST_FAILURE = 303;
51 var STATUS_NONE = 500; // Query has not been started yet
52 var STATUS_GET_IN_PROGRESS = 501; // Query has been sent, no result has been received
53 var STATUS_GET_RECEIVED = 502; // Success
54 var STATUS_GET_ERROR = 503; // Error
55 var STATUS_UPDATE_PENDING = 504;
56 var STATUS_UPDATE_IN_PROGRESS = 505;
57 var STATUS_UPDATE_RECEIVED = 506;
58 var STATUS_UPDATE_ERROR = 507;
60 /* Requests for query cycle */
63 // A structure for storing queries
67 function QueryExt(query, parent_query_ext, main_query_ext, update_query_ext, disabled) {
70 if (typeof query == "undefined")
71 throw "Must pass a query in QueryExt constructor";
73 this.parent_query_ext = (typeof parent_query_ext == "undefined") ? null : parent_query_ext
74 this.main_query_ext = (typeof main_query_ext == "undefined") ? null : main_query_ext
75 this.update_query_ext = (typeof update_query_ext == "undefined") ? null : update_query_ext
76 this.disabled = (typeof update_query_ext == "undefined") ? false : disabled
80 // update_query null unless we are a main_query (aka parent_query == null); only main_query_fields can be updated...
83 function QueryStore() {
85 this.main_queries = {};
86 this.analyzed_queries = {};
90 this.insert = function(query)
92 // We expect only main_queries are inserted
94 /* If the query has not been analyzed, then we analyze it */
95 if (query.analyzed_query == null) {
96 query.analyze_subqueries();
99 /* We prepare the update query corresponding to the main query and store both */
100 /* Note: they have the same UUID */
102 // XXX query.change_action() should become deprecated
103 update_query = query.clone();
104 update_query.action = 'update';
105 update_query.analyzed_query.action = 'update';
106 update_query.params = {};
107 update_query_ext = new QueryExt(update_query);
108 console.log("Update query created from Get query", update_query);
110 /* We store the main query */
111 query_ext = new QueryExt(query, null, null, update_query_ext, false);
112 manifold.query_store.main_queries[query.query_uuid] = query_ext;
113 /* Note: the update query does not have an entry! */
116 // The query is disabled; since it is incomplete until we know the content of the set of subqueries
117 // XXX unless we have no subqueries ???
118 // we will complete with params when records are received... this has to be done by the manager
119 // SET_ADD, SET_REMOVE will change the status of the elements of the set
120 // UPDATE will change also, etc.
121 // XXX We need a proper structure to store this information...
123 // We also need to insert all queries and subqueries from the analyzed_query
124 // XXX We need the root of all subqueries
125 query.iter_subqueries(function(sq, data, parent_query) {
127 parent_query_ext = manifold.query_store.find_analyzed_query_ext(parent_query.query_uuid);
129 parent_query_ext = null;
130 // XXX parent_query_ext == false
131 // XXX main.subqueries = {} # Normal, we need analyzed_query
132 sq_ext = new QueryExt(sq, parent_query_ext, query_ext)
133 manifold.query_store.analyzed_queries[sq.query_uuid] = sq_ext;
136 // XXX We have spurious update queries...
141 this.find_query_ext = function(query_uuid)
143 return this.main_queries[query_uuid];
146 this.find_query = function(query_uuid)
148 return this.find_query_ext(query_uuid).query;
151 this.find_analyzed_query_ext = function(query_uuid)
153 return this.analyzed_queries[query_uuid];
156 this.find_analyzed_query = function(query_uuid)
158 return this.find_analyzed_query_ext(query_uuid).query;
163 * This namespace holds functions for globally managing query objects
168 /**************************************************************************
170 **************************************************************************/
176 spin: function(locator, active /*= true */) {
177 active = typeof active !== 'undefined' ? active : true;
180 $(locator).spin(manifold.spin_presets);
182 $(locator).spin(false);
184 } catch (err) { messages.debug("Cannot turn spins on/off " + err); }
187 /**************************************************************************
188 * Metadata management
189 **************************************************************************/
193 get_table: function(method)
195 var table = MANIFOLD_METADATA[method];
196 return (typeof table === 'undefined') ? null : table;
199 get_columns: function(method)
201 var table = this.get_table(method);
206 return (typeof table.column === 'undefined') ? null : table.column;
209 get_key: function(method)
211 var table = this.get_table(method);
215 return (typeof table.key === 'undefined') ? null : table.key;
219 get_column: function(method, name)
221 var columns = this.get_columns(method);
225 $.each(columns, function(i, c) {
232 get_type: function(method, name)
234 var table = this.get_table(method);
238 return (typeof table.type === 'undefined') ? null : table.type;
243 /**************************************************************************
245 **************************************************************************/
247 query_store: new QueryStore(),
249 // XXX Remaining functions are deprecated since they are replaced by the query store
252 * Associative array storing the set of queries active on the page
258 * Insert a query in the global hash table associating uuids to queries.
259 * If the query has no been analyzed yet, let's do it.
260 * \fn insert_query(query)
262 * \param ManifoldQuery query Query to be added
264 insert_query : function (query) {
266 manifold.query_store.insert(query);
269 if (query.analyzed_query == null) {
270 query.analyze_subqueries();
272 manifold.all_queries[query.query_uuid]=query;
276 * Returns the query associated to a UUID
277 * \fn find_query(query_uuid)
279 * \param string query_uuid The UUID of the query to be returned
281 find_query : function (query_uuid) {
282 return manifold.all_queries[query_uuid];
285 /**************************************************************************
287 **************************************************************************/
289 // trigger a query asynchroneously
290 proxy_url : '/manifold/proxy/json/',
292 asynchroneous_debug : true,
295 * \brief We use js function closure to be able to pass the query (array)
296 * to the callback function used when data is received
298 success_closure: function(query, publish_uuid, callback /*domid*/)
300 return function(data, textStatus) {
301 manifold.asynchroneous_success(data, query, publish_uuid, callback /*domid*/);
305 run_query: function(query, callback)
307 // default value for callback = null
308 if (typeof callback === 'undefined')
311 var query_json = JSON.stringify(query);
313 /* Nothing related to pubsub here... for the moment at least. */
314 //query.iter_subqueries(function (sq) {
315 // manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
318 $.post(manifold.proxy_url, {'json': query_json} , manifold.success_closure(query, null, callback /*domid*/));
321 // Executes all async. queries
322 // input queries are specified as a list of {'query_uuid': <query_uuid>, 'id': <possibly null>}
323 asynchroneous_exec : function (query_publish_dom_tuples) {
326 // in case the spin stuff was not loaded, let's make sure we proceed to the exit
328 // if (manifold.asynchroneous_debug)
329 // messages.debug("Turning on spin with " + jQuery(".need-spin").length + " matches for .need-spin");
330 // jQuery('.need-spin').spin(manifold.spin_presets);
331 //} catch (err) { messages.debug("Cannot turn on spins " + err); }
333 // Loop through input array, and use publish_uuid to publish back results
334 jQuery.each(query_publish_dom_tuples, function(index, tuple) {
335 var query=manifold.find_query(tuple.query_uuid);
336 var query_json=JSON.stringify (query);
337 var publish_uuid=tuple.publish_uuid;
338 // by default we publish using the same uuid of course
339 if (publish_uuid==undefined) publish_uuid=query.query_uuid;
340 if (manifold.asynchroneous_debug) {
341 messages.debug("sending POST on " + manifold.proxy_url + " to be published on " + publish_uuid);
342 messages.debug("... ctd... with actual query= " + query.__repr());
345 query.iter_subqueries(function (sq) {
346 manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
349 // not quite sure what happens if we send a string directly, as POST data is named..
350 // this gets reconstructed on the proxy side with ManifoldQuery.fill_from_POST
351 jQuery.post(manifold.proxy_url, {'json':query_json} , manifold.success_closure(query, publish_uuid, tuple.callback /*domid*/));
356 * \brief Forward a query to the manifold backend
357 * \param query (dict) the query to be executed asynchronously
358 * \param callback (function) the function to be called when the query terminates
360 * \param domid (string) the domid to be notified about the results (null for using the pub/sub system
362 forward: function(query, callback /*domid*/) {
363 var query_json = JSON.stringify(query);
364 $.post(manifold.proxy_url, {'json': query_json} , manifold.success_closure(query, query.query_uuid, callback/*domid*/));
368 * Returns whether a query expects a unique results.
369 * This is the case when the filters contain a key of the object
370 * \fn query_expects_unique_result(query)
372 * \param ManifoldQuery query Query for which we are testing whether it expects a unique result
374 query_expects_unique_result: function(query) {
375 /* XXX we need functions to query metadata */
376 //var keys = MANIFOLD_METADATA[query.object]['keys']; /* array of array of field names */
377 /* TODO requires keys in metadata */
383 * \fn publish_result(query, results)
385 * \param ManifoldQuery query Query which has received results
386 * \param array results results corresponding to query
388 publish_result: function(query, result) {
389 if (typeof result === 'undefined')
393 manifold.raise_record_event(query.query_uuid, CLEAR_RECORDS);
394 $.each(result, function(i, record) {
395 manifold.raise_record_event(query.query_uuid, NEW_RECORD, record);
397 manifold.raise_record_event(query.query_uuid, DONE);
399 // OLD PLUGIN API BELOW
400 /* Publish an update announce */
401 var channel="/results/" + query.query_uuid + "/changed";
402 if (manifold.asynchroneous_debug)
403 messages.debug("publishing result on " + channel);
404 jQuery.publish(channel, [result, query]);
408 * Recursively publish result
409 * \fn publish_result_rec(query, result)
411 * \param ManifoldQuery query Query which has received result
412 * \param array result result corresponding to query
414 publish_result_rec: function(query, result) {
415 /* If the result is not unique, only publish the top query;
416 * otherwise, publish the main object as well as subqueries
417 * XXX how much recursive are we ?
419 if (manifold.query_expects_unique_result(query)) {
420 /* Also publish subqueries */
421 jQuery.each(query.subqueries, function(object, subquery) {
422 manifold.publish_result_rec(subquery, result[0][object]);
423 /* TODO remove object from result */
426 manifold.publish_result(query, result);
429 // if set domid allows the result to be directed to just one plugin
430 // most of the time publish_uuid will be query.query_uuid
431 // however in some cases we wish to publish the result under a different uuid
432 // e.g. an updater wants to publish its result as if from the original (get) query
433 asynchroneous_success : function (data, query, publish_uuid, callback /*domid*/) {
434 // xxx should have a nicer declaration of that enum in sync with the python code somehow
436 /* If a callback has been specified, we redirect results to it */
437 if (!!callback) { callback(data); return; }
439 if (data.code == 2) { // ERROR
440 // We need to make sense of error codes here
441 alert("Your session has expired, please log in again");
442 window.location="/logout/";
445 if (data.code == 1) { // WARNING
446 messages.error("Some errors have been received from the manifold backend at " + MANIFOLD_URL + " [" + data.description + "]");
447 // publish error code and text message on a separate channel for whoever is interested
449 $.publish("/results/" + publish_uuid + "/failed", [data.code, data.description] );
451 $("#notifications").notify("create", "sticky", {
453 text: data.description
460 // once everything is checked we can use the 'value' part of the manifoldresult
461 var result=data.value;
463 //if (!!callback /* domid */) {
464 // /* Directly inform the requestor */
465 // if (manifold.asynchroneous_debug) messages.debug("directing result to callback");
467 // //if (manifold.asynchroneous_debug) messages.debug("directing result to " + domid);
468 // //jQuery('#' + domid).trigger('results', [result]);
470 /* XXX Jordan XXX I don't need publish_uuid here... What is it used for ? */
471 /* query is the query we sent to the backend; we need to find the
472 * corresponding analyezd_query in manifold.all_queries
475 // XXX We might need to update the corresponding update_query here
476 query_ext = manifold.query_store.find_query_ext(query.query_uuid);
477 query = query_ext.query;
479 // We don't prepare an update query if the result has more than 1 entry
480 if (result.length == 1) {
483 console.log("Locating update query for updating params", update_query);
484 update_query_ext = query_ext.update_query_ext;
485 update_query = update_query_ext.query;
487 // Testing whether the result has subqueries (one level deep only)
488 // iif the query has subqueries
490 var obj = query.analyzed_query.subqueries;
491 for (method in obj) {
492 if (obj.hasOwnProperty(method)) {
493 var key = manifold.metadata.get_key(method);
500 var records = res[method];
503 $.each(records, function (i, obj) {
504 sq_keys.push(obj[key]);
506 update_query.params[method] = sq_keys;
512 update_query_ext.disabled = false;
519 // We have results from the main query
520 // inspect subqueries and get the key for each
522 // XXX note that we might need the name for each relation, but
523 // this might be for SET_ADD, since we need to recursively find
524 // the path from the main query
527 tmp_query = manifold.find_query(query.query_uuid);
528 manifold.publish_result_rec(tmp_query.analyzed_query, result);
534 /**************************************************************************
536 **************************************************************************/
538 raise_event_handler: function(type, query_uuid, event_type, value)
540 if ((type != 'query') && (type != 'record'))
541 throw 'Incorrect type for manifold.raise_event()';
543 var channels = [ manifold.get_channel(type, query_uuid), manifold.get_channel(type, '*') ];
545 $.each(channels, function(i, channel) {
546 if (value === undefined)
547 $('.plugin').trigger(channel, [event_type]);
549 $('.plugin').trigger(channel, [event_type, value]);
553 raise_query_event: function(query_uuid, event_type, value)
555 manifold.raise_event_handler('query', query_uuid, event_type, value);
558 raise_record_event: function(query_uuid, event_type, value)
560 manifold.raise_event_handler('record', query_uuid, event_type, value);
564 raise_event: function(query_uuid, event_type, value)
566 // Query uuid has been updated with the key of a new element
567 query_ext = manifold.query_store.find_analyzed_query_ext(query_uuid);
568 query = query_ext.query;
571 case FIELD_STATE_CHANGED:
572 // value is an object (request, key, value, status)
573 // update is only possible is the query is not pending, etc
574 // SET_ADD is on a subquery, FIELD_STATE_CHANGED on the query itself
575 // we should map SET_ADD on this...
577 // 1. Update internal query store about the change in status
579 // 2. Update the update query
580 update_query = query_ext.main_query_ext.update_query_ext.query;
581 update_query.params[value.key].push(value.value);
583 // 3. Inform others about the change
584 // a) the main query...
585 manifold.raise_record_event(query_uuid, event_type, value);
587 // b) subqueries eventually (dot in the key)
588 // XXX make this DOT a global variable... could be '/'
594 // update is only possible is the query is not pending, etc
597 // XXX we can only update subqueries of the main query. Check !
598 // assert query_ext.parent_query == query_ext.main_query
599 // old // update_query = query_ext.main_query_ext.update_query_ext.query;
601 // This SET_ADD is called on a subquery, so we have to
602 // recontruct the path of the key in the main_query
603 // We then call FIELD_STATE_CHANGED which is the equivalent for the main query
607 while (sq.parent_query_ext) {
610 path = sq.query.object + path;
611 sq = sq.parent_query_ext;
614 main_query = query_ext.main_query_ext.query;
616 request: (event_type == SET_ADD) ? FIELD_REQUEST_ADD : FIELD_REQUEST_REMOVE,
619 status: FIELD_REQUEST_PENDING,
621 this.raise_event(main_query.query_uuid, FIELD_STATE_CHANGED, data);
623 // old //update_query.params[path].push(value);
624 // old // console.log('Updated query params', update_query);
625 // NOTE: update might modify the fields in Get
626 // NOTE : we have to modify all child queries
627 // NOTE : parts of a query might not be started (eg slice.measurements, how to handle ?)
629 // if everything is done right, update_query should not be null. It is updated when we received results from the get query
630 // object = the same as get
631 // filter = key : update a single object for now
632 // fields = the same as get
633 manifold.raise_query_event(query_uuid, event_type, value);
638 manifold.run_query(query_ext.main_query_ext.update_query_ext.query);
642 manifold.raise_query_event(query_uuid, event_type, value);
645 manifold.raise_query_event(query_uuid, event_type, value);
648 main_query = query_ext.main_query_ext.query;
649 main_update_query = query_ext.main_query_ext.update_query;
652 // Here we need the full path through all subqueries
654 // XXX We might need the query name in the QueryExt structure
655 main_query.select(value);
657 // XXX When is an update query associated ?
658 // XXX main_update_query.select(value);
660 manifold.raise_query_event(query_uuid, event_type, value);
664 query = query_ext.query;
665 main_query = query_ext.main_query_ext.query;
666 main_update_query = query_ext.main_query_ext.update_query;
667 query.unselect(value);
668 main_query.unselect(value);
670 // We need to inform about changes in these queries to the respective plugins
671 // Note: query & main_query have the same UUID
672 manifold.raise_query_event(query_uuid, event_type, value);
675 // We need to inform about changes in these queries to the respective plugins
676 // Note: query, main_query & update_query have the same UUID
677 manifold.raise_query_event(query_uuid, event_type, value);
678 // We are targeting the same object with get and update
679 // The notion of query is bad, we should have a notion of destination, and issue queries on the destination
680 // NOTE: Editing a subquery == editing a local view on the destination
682 // XXX We might need to run the new query again and manage the plugins in the meantime with spinners...
683 // For the time being, we will collect all columns during the first query
686 /* Publish/subscribe channels for internal use */
687 get_channel: function(type, query_uuid)
689 if ((type !== 'query') && (type != 'record'))
691 return '/' + type + '/' + query_uuid;
694 }; // manifold object
695 /* ------------------------------------------------------------ */
699 // OLD PLUGIN API: extend jQuery/$ with pubsub capabilities
700 // https://gist.github.com/661855
702 $.subscribe = function( channel, selector, data, fn) {
703 /* borrowed from jQuery */
704 if ( data == null && fn == null ) {
707 data = selector = undefined;
708 } else if ( fn == null ) {
709 if ( typeof selector === "string" ) {
710 // ( channel, selector, fn )
714 // ( channel, data, fn )
717 selector = undefined;
722 /* We use an indirection function that will clone the object passed in
723 * parameter to the subscribe callback
725 * FIXME currently we only clone query objects which are the only ones
726 * supported and editable, we might have the same issue with results but
727 * the page load time will be severely affected...
729 o.on.apply(o, [channel, selector, data, function() {
730 for(i = 1; i < arguments.length; i++) {
731 if ( arguments[i].constructor.name == 'ManifoldQuery' )
732 arguments[i] = arguments[i].clone();
734 fn.apply(o, arguments);
738 $.unsubscribe = function() {
739 o.off.apply(o, arguments);
742 $.publish = function() {
743 o.trigger.apply(o, arguments);
748 /* ------------------------------------------------------------ */
750 //http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request
751 //make sure to expose csrf in our outcoming ajax/post requests
753 beforeSend: function(xhr, settings) {
754 function getCookie(name) {
755 var cookieValue = null;
756 if (document.cookie && document.cookie != '') {
757 var cookies = document.cookie.split(';');
758 for (var i = 0; i < cookies.length; i++) {
759 var cookie = jQuery.trim(cookies[i]);
760 // Does this cookie string begin with the name we want?
761 if (cookie.substring(0, name.length + 1) == (name + '=')) {
762 cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
769 if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
770 // Only send the token to relative URLs i.e. locally.
771 xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));