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 from plugins */
38 var SET_REMOVED = 202;
42 var FIELD_REQUEST_CHANGE = 301;
43 var FIELD_REQUEST_ADD = 302;
44 var FIELD_REQUEST_REMOVE = 303;
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;
62 // A structure for storing queries
66 function QueryExt(query, parent_query_ext, main_query_ext, update_query_ext, disabled) {
69 if (typeof query == "undefined")
70 throw "Must pass a query in QueryExt constructor";
72 this.parent_query_ext = (typeof parent_query_ext == "undefined") ? null : parent_query_ext
73 this.main_query_ext = (typeof main_query_ext == "undefined") ? null : main_query_ext
74 this.update_query_ext = (typeof update_query_ext == "undefined") ? null : update_query_ext
75 this.disabled = (typeof update_query_ext == "undefined") ? false : disabled
79 // update_query null unless we are a main_query (aka parent_query == null); only main_query_fields can be updated...
82 function QueryStore() {
84 this.main_queries = {};
85 this.analyzed_queries = {};
89 this.insert = function(query)
91 // We expect only main_queries are inserted
93 /* If the query has not been analyzed, then we analyze it */
94 if (query.analyzed_query == null) {
95 query.analyze_subqueries();
98 /* We prepare the update query corresponding to the main query and store both */
99 /* Note: they have the same UUID */
101 // XXX query.change_action() should become deprecated
102 update_query = query.clone();
103 update_query.action = 'update';
104 update_query.analyzed_query.action = 'update';
105 update_query.params = {};
106 update_query_ext = new QueryExt(update_query);
107 console.log("Update query created from Get query", update_query);
109 /* We store the main query */
110 query_ext = new QueryExt(query, null, null, update_query_ext, false);
111 manifold.query_store.main_queries[query.query_uuid] = query_ext;
112 /* Note: the update query does not have an entry! */
115 // The query is disabled; since it is incomplete until we know the content of the set of subqueries
116 // XXX unless we have no subqueries ???
117 // we will complete with params when records are received... this has to be done by the manager
118 // SET_ADD, SET_REMOVE will change the status of the elements of the set
119 // UPDATE will change also, etc.
120 // XXX We need a proper structure to store this information...
122 // We also need to insert all queries and subqueries from the analyzed_query
123 // XXX We need the root of all subqueries
124 query.iter_subqueries(function(sq, data, parent_query) {
126 parent_query_ext = manifold.query_store.find_analyzed_query_ext(parent_query.query_uuid);
128 parent_query_ext = null;
129 // XXX parent_query_ext == false
130 // XXX main.subqueries = {} # Normal, we need analyzed_query
131 sq_ext = new QueryExt(sq, parent_query_ext, query_ext)
132 manifold.query_store.analyzed_queries[sq.query_uuid] = sq_ext;
135 // XXX We have spurious update queries...
140 this.find_query_ext = function(query_uuid)
142 return this.main_queries[query_uuid];
145 this.find_query = function(query_uuid)
147 return this.find_query_ext(query_uuid).query;
150 this.find_analyzed_query_ext = function(query_uuid)
152 return this.analyzed_queries[query_uuid];
155 this.find_analyzed_query = function(query_uuid)
157 return this.find_analyzed_query_ext(query_uuid).query;
162 * This namespace holds functions for globally managing query objects
167 /**************************************************************************
169 **************************************************************************/
175 spin: function(locator, active /*= true */) {
176 active = typeof active !== 'undefined' ? active : true;
179 $(locator).spin(manifold.spin_presets);
181 $(locator).spin(false);
183 } catch (err) { messages.debug("Cannot turn spins on/off " + err); }
186 /**************************************************************************
187 * Metadata management
188 **************************************************************************/
192 get_table: function(method)
194 var table = MANIFOLD_METADATA[method];
195 return (typeof table === 'undefined') ? null : table;
198 get_columns: function(method)
200 var table = this.get_table(method);
205 return (typeof table.column === 'undefined') ? null : table.column;
208 get_key: function(method)
210 var table = this.get_table(method);
214 return (typeof table.key === 'undefined') ? null : table.key;
218 get_column: function(method, name)
220 var columns = this.get_columns(method);
224 $.each(columns, function(i, c) {
231 get_type: function(method, name)
233 var table = this.get_table(method);
237 return (typeof table.type === 'undefined') ? null : table.type;
242 /**************************************************************************
244 **************************************************************************/
246 query_store: new QueryStore(),
248 // XXX Remaining functions are deprecated since they are replaced by the query store
251 * Associative array storing the set of queries active on the page
257 * Insert a query in the global hash table associating uuids to queries.
258 * If the query has no been analyzed yet, let's do it.
259 * \fn insert_query(query)
261 * \param ManifoldQuery query Query to be added
263 insert_query : function (query) {
265 manifold.query_store.insert(query);
268 if (query.analyzed_query == null) {
269 query.analyze_subqueries();
271 manifold.all_queries[query.query_uuid]=query;
275 * Returns the query associated to a UUID
276 * \fn find_query(query_uuid)
278 * \param string query_uuid The UUID of the query to be returned
280 find_query : function (query_uuid) {
281 return manifold.all_queries[query_uuid];
284 /**************************************************************************
286 **************************************************************************/
288 // trigger a query asynchroneously
289 proxy_url : '/manifold/proxy/json/',
291 asynchroneous_debug : true,
294 * \brief We use js function closure to be able to pass the query (array)
295 * to the callback function used when data is received
297 success_closure: function(query, publish_uuid, callback /*domid*/)
299 return function(data, textStatus) {
300 manifold.asynchroneous_success(data, query, publish_uuid, callback /*domid*/);
304 // Executes all async. queries
305 // input queries are specified as a list of {'query_uuid': <query_uuid>, 'id': <possibly null>}
306 asynchroneous_exec : function (query_publish_dom_tuples) {
309 // in case the spin stuff was not loaded, let's make sure we proceed to the exit
311 // if (manifold.asynchroneous_debug)
312 // messages.debug("Turning on spin with " + jQuery(".need-spin").length + " matches for .need-spin");
313 // jQuery('.need-spin').spin(manifold.spin_presets);
314 //} catch (err) { messages.debug("Cannot turn on spins " + err); }
316 // Loop through input array, and use publish_uuid to publish back results
317 jQuery.each(query_publish_dom_tuples, function(index, tuple) {
318 var query=manifold.find_query(tuple.query_uuid);
319 var query_json=JSON.stringify (query);
320 var publish_uuid=tuple.publish_uuid;
321 // by default we publish using the same uuid of course
322 if (publish_uuid==undefined) publish_uuid=query.query_uuid;
323 if (manifold.asynchroneous_debug) {
324 messages.debug("sending POST on " + manifold.proxy_url + " to be published on " + publish_uuid);
325 messages.debug("... ctd... with actual query= " + query.__repr());
328 query.iter_subqueries(function (sq) {
329 manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
332 // not quite sure what happens if we send a string directly, as POST data is named..
333 // this gets reconstructed on the proxy side with ManifoldQuery.fill_from_POST
334 jQuery.post(manifold.proxy_url, {'json':query_json} , manifold.success_closure(query, publish_uuid, tuple.callback /*domid*/));
339 * \brief Forward a query to the manifold backend
340 * \param query (dict) the query to be executed asynchronously
341 * \param callback (function) the function to be called when the query terminates
343 * \param domid (string) the domid to be notified about the results (null for using the pub/sub system
345 forward: function(query, callback /*domid*/) {
346 var query_json = JSON.stringify(query);
347 $.post(manifold.proxy_url, {'json': query_json} , manifold.success_closure(query, query.query_uuid, callback/*domid*/));
351 * Returns whether a query expects a unique results.
352 * This is the case when the filters contain a key of the object
353 * \fn query_expects_unique_result(query)
355 * \param ManifoldQuery query Query for which we are testing whether it expects a unique result
357 query_expects_unique_result: function(query) {
358 /* XXX we need functions to query metadata */
359 //var keys = MANIFOLD_METADATA[query.object]['keys']; /* array of array of field names */
360 /* TODO requires keys in metadata */
366 * \fn publish_result(query, results)
368 * \param ManifoldQuery query Query which has received results
369 * \param array results results corresponding to query
371 publish_result: function(query, result) {
372 if (typeof result === 'undefined')
376 manifold.raise_record_event(query.query_uuid, CLEAR_RECORDS);
377 $.each(result, function(i, record) {
378 manifold.raise_record_event(query.query_uuid, NEW_RECORD, record);
380 manifold.raise_record_event(query.query_uuid, DONE);
382 // OLD PLUGIN API BELOW
383 /* Publish an update announce */
384 var channel="/results/" + query.query_uuid + "/changed";
385 if (manifold.asynchroneous_debug)
386 messages.debug("publishing result on " + channel);
387 jQuery.publish(channel, [result, query]);
391 * Recursively publish result
392 * \fn publish_result_rec(query, result)
394 * \param ManifoldQuery query Query which has received result
395 * \param array result result corresponding to query
397 publish_result_rec: function(query, result) {
398 /* If the result is not unique, only publish the top query;
399 * otherwise, publish the main object as well as subqueries
400 * XXX how much recursive are we ?
402 if (manifold.query_expects_unique_result(query)) {
403 /* Also publish subqueries */
404 jQuery.each(query.subqueries, function(object, subquery) {
405 manifold.publish_result_rec(subquery, result[0][object]);
406 /* TODO remove object from result */
409 manifold.publish_result(query, result);
412 // if set domid allows the result to be directed to just one plugin
413 // most of the time publish_uuid will be query.query_uuid
414 // however in some cases we wish to publish the result under a different uuid
415 // e.g. an updater wants to publish its result as if from the original (get) query
416 asynchroneous_success : function (data, query, publish_uuid, callback /*domid*/) {
417 // xxx should have a nicer declaration of that enum in sync with the python code somehow
419 /* If a callback has been specified, we redirect results to it */
420 if (!!callback) { callback(data); return; }
422 if (data.code == 2) { // ERROR
423 // We need to make sense of error codes here
424 alert("Your session has expired, please log in again");
425 window.location="/logout/";
428 if (data.code == 1) { // WARNING
429 messages.error("Some errors have been received from the manifold backend at " + MANIFOLD_URL + " [" + data.description + "]");
430 // publish error code and text message on a separate channel for whoever is interested
431 jQuery.publish("/results/" + publish_uuid + "/failed", [data.code, data.description] );
433 $("#notifications").notify("create", "sticky", {
435 text: data.description
442 // once everything is checked we can use the 'value' part of the manifoldresult
443 var result=data.value;
445 //if (!!callback /* domid */) {
446 // /* Directly inform the requestor */
447 // if (manifold.asynchroneous_debug) messages.debug("directing result to callback");
449 // //if (manifold.asynchroneous_debug) messages.debug("directing result to " + domid);
450 // //jQuery('#' + domid).trigger('results', [result]);
452 /* XXX Jordan XXX I don't need publish_uuid here... What is it used for ? */
453 /* query is the query we sent to the backend; we need to find the
454 * corresponding analyezd_query in manifold.all_queries
457 // XXX We might need to update the corresponding update_query here
458 query_ext = manifold.query_store.find_query_ext(query.query_uuid);
459 query = query_ext.query;
461 // We don't prepare an update query if the result has more than 1 entry
462 if (result.length == 1) {
465 console.log("Locating update query for updating params", update_query);
466 update_query_ext = query_ext.update_query_ext;
467 update_query = update_query_ext.query;
469 // Testing whether the result has subqueries (one level deep only)
470 // iif the query has subqueries
472 var obj = query.analyzed_query.subqueries;
473 for (method in obj) {
474 if (obj.hasOwnProperty(method)) {
475 var key = manifold.metadata.get_key(method);
482 var records = res[method];
485 $.each(records, function (i, obj) {
486 sq_keys.push(obj[key]);
488 update_query.params[method] = sq_keys;
494 update_query_ext.disabled = false;
501 // We have results from the main query
502 // inspect subqueries and get the key for each
504 // XXX note that we might need the name for each relation, but
505 // this might be for SET_ADD, since we need to recursively find
506 // the path from the main query
509 tmp_query = manifold.find_query(query.query_uuid);
510 manifold.publish_result_rec(tmp_query.analyzed_query, result);
516 /**************************************************************************
518 **************************************************************************/
520 raise_event_handler: function(type, query_uuid, event_type, value)
522 if ((type != 'query') && (type != 'record'))
523 throw 'Incorrect type for manifold.raise_event()';
525 var channels = [ manifold.get_channel(type, query_uuid), manifold.get_channel(type, '*') ];
527 $.each(channels, function(i, channel) {
528 if (value === undefined)
529 $('.plugin').trigger(channel, [event_type]);
531 $('.plugin').trigger(channel, [event_type, value]);
535 raise_query_event: function(query_uuid, event_type, value)
537 manifold.raise_event_handler('query', query_uuid, event_type, value);
540 raise_record_event: function(query_uuid, event_type, value)
542 manifold.raise_event_handler('record', query_uuid, event_type, value);
546 raise_event: function(query_uuid, event_type, value)
548 // Query uuid has been updated with the key of a new element
549 query_ext = manifold.query_store.find_analyzed_query_ext(query_uuid);
550 query = query_ext.query;
553 case FIELD_STATE_CHANGED:
554 // value is an object (request, key, value, status)
555 // update is only possible is the query is not pending, etc
556 // SET_ADD is on a subquery, FIELD_STATE_CHANGED on the query itself
557 // we should map SET_ADD on this...
559 // 1. Update internal query store about the change in status
561 // 2. Update the update query
562 update_query = query_ext.main_query_ext.update_query_ext.query;
563 update_query.params[value.key].push(value.value);
565 // 3. Inform others about the change
566 // a) the main query...
567 manifold.raise_record_event(query_uuid, event_type, value);
569 // b) subqueries eventually (dot in the key)
570 // XXX make this DOT a global variable... could be '/'
576 // update is only possible is the query is not pending, etc
579 // XXX we can only update subqueries of the main query. Check !
580 // assert query_ext.parent_query == query_ext.main_query
581 // old // update_query = query_ext.main_query_ext.update_query_ext.query;
583 // This SET_ADD is called on a subquery, so we have to
584 // recontruct the path of the key in the main_query
585 // We then call FIELD_STATE_CHANGED which is the equivalent for the main query
589 while (sq.parent_query_ext) {
592 path = sq.query.object + path;
593 sq = sq.parent_query_ext;
596 main_query = query_ext.main_query_ext.query;
598 request: (event_type == SET_ADD) ? FIELD_REQUEST_ADD : FIELD_REQUEST_REMOVE,
601 status: FIELD_REQUEST_PENDING,
603 this.raise_event(main_query.query_uuid, FIELD_STATE_CHANGED, data);
605 // old //update_query.params[path].push(value);
606 // old // console.log('Updated query params', update_query);
607 // NOTE: update might modify the fields in Get
608 // NOTE : we have to modify all child queries
609 // NOTE : parts of a query might not be started (eg slice.measurements, how to handle ?)
611 // if everything is done right, update_query should not be null. It is updated when we received results from the get query
612 // object = the same as get
613 // filter = key : update a single object for now
614 // fields = the same as get
615 manifold.raise_query_event(query_uuid, event_type, value);
620 update_query = query_ext.main_query_ext.update_query_ext.query;
622 manifold.asynchroneous_exec ( [ {'query_uuid': update_query.query_uuid, 'publish_uuid' : query_uuid} ], false);
626 manifold.raise_query_event(query_uuid, event_type, value);
629 manifold.raise_query_event(query_uuid, event_type, value);
632 main_query = query_ext.main_query_ext.query;
633 main_update_query = query_ext.main_query_ext.update_query;
636 // Here we need the full path through all subqueries
638 // XXX We might need the query name in the QueryExt structure
639 main_query.select(value);
641 // XXX When is an update query associated ?
642 // XXX main_update_query.select(value);
644 manifold.raise_query_event(query_uuid, event_type, value);
648 query = query_ext.query;
649 main_query = query_ext.main_query_ext.query;
650 main_update_query = query_ext.main_query_ext.update_query;
651 query.unselect(value);
652 main_query.unselect(value);
654 // We need to inform about changes in these queries to the respective plugins
655 // Note: query & main_query have the same UUID
656 manifold.raise_query_event(query_uuid, event_type, value);
659 // We need to inform about changes in these queries to the respective plugins
660 // Note: query, main_query & update_query have the same UUID
661 manifold.raise_query_event(query_uuid, event_type, value);
662 // We are targeting the same object with get and update
663 // The notion of query is bad, we should have a notion of destination, and issue queries on the destination
664 // NOTE: Editing a subquery == editing a local view on the destination
666 // XXX We might need to run the new query again and manage the plugins in the meantime with spinners...
667 // For the time being, we will collect all columns during the first query
670 /* Publish/subscribe channels for internal use */
671 get_channel: function(type, query_uuid)
673 if ((type !== 'query') && (type != 'record'))
675 return '/' + type + '/' + query_uuid;
678 }; // manifold object
679 /* ------------------------------------------------------------ */
683 // OLD PLUGIN API: extend jQuery/$ with pubsub capabilities
684 // https://gist.github.com/661855
686 $.subscribe = function( channel, selector, data, fn) {
687 /* borrowed from jQuery */
688 if ( data == null && fn == null ) {
691 data = selector = undefined;
692 } else if ( fn == null ) {
693 if ( typeof selector === "string" ) {
694 // ( channel, selector, fn )
698 // ( channel, data, fn )
701 selector = undefined;
706 /* We use an indirection function that will clone the object passed in
707 * parameter to the subscribe callback
709 * FIXME currently we only clone query objects which are the only ones
710 * supported and editable, we might have the same issue with results but
711 * the page load time will be severely affected...
713 o.on.apply(o, [channel, selector, data, function() {
714 for(i = 1; i < arguments.length; i++) {
715 if ( arguments[i].constructor.name == 'ManifoldQuery' )
716 arguments[i] = arguments[i].clone();
718 fn.apply(o, arguments);
722 $.unsubscribe = function() {
723 o.off.apply(o, arguments);
726 $.publish = function() {
727 o.trigger.apply(o, arguments);
732 /* ------------------------------------------------------------ */
734 //http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request
735 //make sure to expose csrf in our outcoming ajax/post requests
737 beforeSend: function(xhr, settings) {
738 function getCookie(name) {
739 var cookieValue = null;
740 if (document.cookie && document.cookie != '') {
741 var cookies = document.cookie.split(';');
742 for (var i = 0; i < cookies.length; i++) {
743 var cookie = jQuery.trim(cookies[i]);
744 // Does this cookie string begin with the name we want?
745 if (cookie.substring(0, name.length + 1) == (name + '=')) {
746 cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
753 if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
754 // Only send the token to relative URLs i.e. locally.
755 xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));