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;
32 var IN_PROGRESS = 101;
35 /* Update requests from plugins */
37 var SET_REMOVED = 202;
41 var STATUS_NONE = 500; // Query has not been started yet
42 var STATUS_GET_IN_PROGRESS = 501; // Query has been sent, no result has been received
43 var STATUS_GET_RECEIVED = 502; // Success
44 var STATUS_GET_ERROR = 503; // Error
45 var STATUS_UPDATE_PENDING = 504;
46 var STATUS_UPDATE_IN_PROGRESS = 505;
47 var STATUS_UPDATE_RECEIVED = 506;
48 var STATUS_UPDATE_ERROR = 507;
51 // A structure for storing queries
55 function QueryExt(query, parent_query_ext, main_query_ext, update_query_ext, disabled) {
58 if (typeof query == "undefined")
59 throw "Must pass a query in QueryExt constructor";
61 this.parent_query_ext = (typeof parent_query_ext == "undefined") ? null : parent_query_ext
62 this.main_query_ext = (typeof main_query_ext == "undefined") ? null : main_query_ext
63 this.update_query_ext = (typeof update_query_ext == "undefined") ? null : update_query_ext
64 this.disabled = (typeof update_query_ext == "undefined") ? false : disabled
68 // update_query null unless we are a main_query (aka parent_query == null); only main_query_fields can be updated...
71 function QueryStore() {
73 this.main_queries = {};
74 this.analyzed_queries = {};
78 this.insert = function(query)
80 // We expect only main_queries are inserted
82 /* If the query has not been analyzed, then we analyze it */
83 if (query.analyzed_query == null) {
84 query.analyze_subqueries();
87 /* We prepare the update query corresponding to the main query and store both */
88 /* Note: they have the same UUID */
90 // XXX query.change_action() should become deprecated
91 update_query = query.clone();
92 update_query.action = 'update';
93 update_query.analyzed_query.action = 'update';
94 update_query.params = {};
95 update_query_ext = new QueryExt(update_query);
96 console.log("Update query created from Get query", update_query);
98 /* We store the main query */
99 query_ext = new QueryExt(query, null, null, update_query_ext, false);
100 manifold.query_store.main_queries[query.query_uuid] = query_ext;
101 /* Note: the update query does not have an entry! */
104 // The query is disabled; since it is incomplete until we know the content of the set of subqueries
105 // XXX unless we have no subqueries ???
106 // we will complete with params when records are received... this has to be done by the manager
107 // SET_ADD, SET_REMOVE will change the status of the elements of the set
108 // UPDATE will change also, etc.
109 // XXX We need a proper structure to store this information...
111 // We also need to insert all queries and subqueries from the analyzed_query
112 // XXX We need the root of all subqueries
113 query.iter_subqueries(function(sq, data, parent_query) {
115 parent_query_ext = manifold.query_store.find_analyzed_query_ext(parent_query.query_uuid);
117 parent_query_ext = null;
118 // XXX parent_query_ext == false
119 // XXX main.subqueries = {} # Normal, we need analyzed_query
120 sq_ext = new QueryExt(sq, parent_query_ext, query_ext)
121 manifold.query_store.analyzed_queries[sq.query_uuid] = sq_ext;
124 // XXX We have spurious update queries...
129 this.find_query_ext = function(query_uuid)
131 return this.main_queries[query_uuid];
134 this.find_query = function(query_uuid)
136 return this.find_query_ext(query_uuid).query;
139 this.find_analyzed_query_ext = function(query_uuid)
141 return this.analyzed_queries[query_uuid];
144 this.find_analyzed_query = function(query_uuid)
146 return this.find_analyzed_query_ext(query_uuid).query;
151 * This namespace holds functions for globally managing query objects
156 /**************************************************************************
158 **************************************************************************/
164 spin: function(locator, active /*= true */) {
165 active = typeof active !== 'undefined' ? active : true;
168 $(locator).spin(manifold.spin_presets);
170 $(locator).spin(false);
172 } catch (err) { messages.debug("Cannot turn spins on/off " + err); }
175 /**************************************************************************
176 * Metadata management
177 **************************************************************************/
181 get_table: function(method)
183 var table = MANIFOLD_METADATA[method];
184 return (typeof table === 'undefined') ? null : table;
187 get_columns: function(method)
189 var table = this.get_table(method);
194 return (typeof table.column === 'undefined') ? null : table.column;
197 get_key: function(method)
199 var table = this.get_table(method);
203 return (typeof table.key === 'undefined') ? null : table.key;
207 get_column: function(method, name)
209 var columns = this.get_columns(method);
213 $.each(columns, function(i, c) {
220 get_type: function(method, name)
222 var table = this.get_table(method);
226 return (typeof table.type === 'undefined') ? null : table.type;
231 /**************************************************************************
233 **************************************************************************/
235 query_store: new QueryStore(),
237 // XXX Remaining functions are deprecated since they are replaced by the query store
240 * Associative array storing the set of queries active on the page
246 * Insert a query in the global hash table associating uuids to queries.
247 * If the query has no been analyzed yet, let's do it.
248 * \fn insert_query(query)
250 * \param ManifoldQuery query Query to be added
252 insert_query : function (query) {
254 manifold.query_store.insert(query);
257 if (query.analyzed_query == null) {
258 query.analyze_subqueries();
260 manifold.all_queries[query.query_uuid]=query;
264 * Returns the query associated to a UUID
265 * \fn find_query(query_uuid)
267 * \param string query_uuid The UUID of the query to be returned
269 find_query : function (query_uuid) {
270 return manifold.all_queries[query_uuid];
273 /**************************************************************************
275 **************************************************************************/
277 // trigger a query asynchroneously
278 proxy_url : '/manifold/proxy/json/',
280 asynchroneous_debug : true,
283 * \brief We use js function closure to be able to pass the query (array)
284 * to the callback function used when data is received
286 success_closure: function(query, publish_uuid, callback /*domid*/)
288 return function(data, textStatus) {
289 manifold.asynchroneous_success(data, query, publish_uuid, callback /*domid*/);
293 // Executes all async. queries
294 // input queries are specified as a list of {'query_uuid': <query_uuid>, 'id': <possibly null>}
295 asynchroneous_exec : function (query_publish_dom_tuples) {
298 // in case the spin stuff was not loaded, let's make sure we proceed to the exit
300 // if (manifold.asynchroneous_debug)
301 // messages.debug("Turning on spin with " + jQuery(".need-spin").length + " matches for .need-spin");
302 // jQuery('.need-spin').spin(manifold.spin_presets);
303 //} catch (err) { messages.debug("Cannot turn on spins " + err); }
305 // Loop through input array, and use publish_uuid to publish back results
306 jQuery.each(query_publish_dom_tuples, function(index, tuple) {
307 var query=manifold.find_query(tuple.query_uuid);
308 var query_json=JSON.stringify (query);
309 var publish_uuid=tuple.publish_uuid;
310 // by default we publish using the same uuid of course
311 if (publish_uuid==undefined) publish_uuid=query.query_uuid;
312 if (manifold.asynchroneous_debug) {
313 messages.debug("sending POST on " + manifold.proxy_url + " to be published on " + publish_uuid);
314 messages.debug("... ctd... with actual query= " + query.__repr());
317 query.iter_subqueries(function (sq) {
318 manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
321 // not quite sure what happens if we send a string directly, as POST data is named..
322 // this gets reconstructed on the proxy side with ManifoldQuery.fill_from_POST
323 jQuery.post(manifold.proxy_url, {'json':query_json} , manifold.success_closure(query, publish_uuid, tuple.callback /*domid*/));
328 * \brief Forward a query to the manifold backend
329 * \param query (dict) the query to be executed asynchronously
330 * \param callback (function) the function to be called when the query terminates
332 * \param domid (string) the domid to be notified about the results (null for using the pub/sub system
334 forward: function(query, callback /*domid*/) {
335 var query_json = JSON.stringify(query);
336 $.post(manifold.proxy_url, {'json': query_json} , manifold.success_closure(query, query.query_uuid, callback/*domid*/));
340 * Returns whether a query expects a unique results.
341 * This is the case when the filters contain a key of the object
342 * \fn query_expects_unique_result(query)
344 * \param ManifoldQuery query Query for which we are testing whether it expects a unique result
346 query_expects_unique_result: function(query) {
347 /* XXX we need functions to query metadata */
348 //var keys = MANIFOLD_METADATA[query.object]['keys']; /* array of array of field names */
349 /* TODO requires keys in metadata */
355 * \fn publish_result(query, results)
357 * \param ManifoldQuery query Query which has received results
358 * \param array results results corresponding to query
360 publish_result: function(query, result) {
361 if (typeof result === 'undefined')
365 manifold.raise_record_event(query.query_uuid, CLEAR_RECORDS);
366 $.each(result, function(i, record) {
367 manifold.raise_record_event(query.query_uuid, NEW_RECORD, record);
369 manifold.raise_record_event(query.query_uuid, DONE);
371 // OLD PLUGIN API BELOW
372 /* Publish an update announce */
373 var channel="/results/" + query.query_uuid + "/changed";
374 if (manifold.asynchroneous_debug)
375 messages.debug("publishing result on " + channel);
376 jQuery.publish(channel, [result, query]);
380 * Recursively publish result
381 * \fn publish_result_rec(query, result)
383 * \param ManifoldQuery query Query which has received result
384 * \param array result result corresponding to query
386 publish_result_rec: function(query, result) {
387 /* If the result is not unique, only publish the top query;
388 * otherwise, publish the main object as well as subqueries
389 * XXX how much recursive are we ?
391 if (manifold.query_expects_unique_result(query)) {
392 /* Also publish subqueries */
393 jQuery.each(query.subqueries, function(object, subquery) {
394 manifold.publish_result_rec(subquery, result[0][object]);
395 /* TODO remove object from result */
398 manifold.publish_result(query, result);
401 // if set domid allows the result to be directed to just one plugin
402 // most of the time publish_uuid will be query.query_uuid
403 // however in some cases we wish to publish the result under a different uuid
404 // e.g. an updater wants to publish its result as if from the original (get) query
405 asynchroneous_success : function (data, query, publish_uuid, callback /*domid*/) {
406 // xxx should have a nicer declaration of that enum in sync with the python code somehow
408 /* If a callback has been specified, we redirect results to it */
409 if (!!callback) { callback(data); return; }
411 if (data.code == 2) { // ERROR
412 // We need to make sense of error codes here
413 alert("Your session has expired, please log in again");
414 window.location="/logout/";
417 if (data.code == 1) { // WARNING
418 messages.error("Some errors have been received from the manifold backend at " + MANIFOLD_URL + " [" + data.description + "]");
419 // publish error code and text message on a separate channel for whoever is interested
420 jQuery.publish("/results/" + publish_uuid + "/failed", [data.code, data.description] );
422 $("#notifications").notify("create", "sticky", {
424 text: data.description
431 // once everything is checked we can use the 'value' part of the manifoldresult
432 var result=data.value;
434 //if (!!callback /* domid */) {
435 // /* Directly inform the requestor */
436 // if (manifold.asynchroneous_debug) messages.debug("directing result to callback");
438 // //if (manifold.asynchroneous_debug) messages.debug("directing result to " + domid);
439 // //jQuery('#' + domid).trigger('results', [result]);
441 /* XXX Jordan XXX I don't need publish_uuid here... What is it used for ? */
442 /* query is the query we sent to the backend; we need to find the
443 * corresponding analyezd_query in manifold.all_queries
446 // XXX We might need to update the corresponding update_query here
447 query_ext = manifold.query_store.find_query_ext(query.query_uuid);
448 query = query_ext.query;
450 // We don't prepare an update query if the result has more than 1 entry
451 if (result.length == 1) {
454 console.log("Locating update query for updating params", update_query);
455 update_query_ext = query_ext.update_query_ext;
456 update_query = update_query_ext.query;
458 // Testing whether the result has subqueries (one level deep only)
459 // iif the query has subqueries
461 var obj = query.analyzed_query.subqueries;
462 for (method in obj) {
463 if (obj.hasOwnProperty(method)) {
464 var key = manifold.metadata.get_key(method);
471 var records = res[method];
474 $.each(records, function (i, obj) {
475 sq_keys.push(obj[key]);
477 update_query.params[method] = sq_keys;
483 update_query_ext.disabled = false;
490 // We have results from the main query
491 // inspect subqueries and get the key for each
493 // XXX note that we might need the name for each relation, but
494 // this might be for SET_ADD, since we need to recursively find
495 // the path from the main query
498 tmp_query = manifold.find_query(query.query_uuid);
499 manifold.publish_result_rec(tmp_query.analyzed_query, result);
505 /**************************************************************************
507 **************************************************************************/
509 raise_event_handler: function(type, query_uuid, event_type, value)
511 if ((type != 'query') && (type != 'record'))
512 throw 'Incorrect type for manifold.raise_event()';
514 var channels = [ manifold.get_channel(type, query_uuid), manifold.get_channel(type, '*') ];
516 $.each(channels, function(i, channel) {
517 if (value === undefined)
518 $('.plugin').trigger(channel, [event_type]);
520 $('.plugin').trigger(channel, [event_type, value]);
524 raise_query_event: function(query_uuid, event_type, value)
526 manifold.raise_event_handler('query', query_uuid, event_type, value);
529 raise_record_event: function(query_uuid, event_type, value)
531 manifold.raise_event_handler('record', query_uuid, event_type, value);
535 raise_event: function(query_uuid, event_type, value)
537 // Query uuid has been updated with the key of a new element
538 query_ext = manifold.query_store.find_analyzed_query_ext(query_uuid);
539 query = query_ext.query;
543 // update is only possible is the query is not pending, etc
546 // XXX we can only update subqueries of the main query. Check !
547 // assert query_ext.parent_query == query_ext.main_query
548 update_query = query_ext.main_query_ext.update_query_ext.query;
552 while (sq.parent_query_ext) {
555 path = sq.query.object + path;
556 sq = sq.parent_query_ext;
559 update_query.params[path].push(value);
560 console.log('Updated query params', update_query);
561 // NOTE: update might modify the fields in Get
562 // NOTE : we have to modify all child queries
563 // NOTE : parts of a query might not be started (eg slice.measurements, how to handle ?)
565 // if everything is done right, update_query should not be null. It is updated when we received results from the get query
566 // object = the same as get
567 // filter = key : update a single object for now
568 // fields = the same as get
572 // Query uuid has been updated with the key of a removed element
576 update_query = query_ext.main_query_ext.update_query_ext.query;
578 manifold.asynchroneous_exec ( [ {'query_uuid': update_query.query_uuid, 'publish_uuid' : query_uuid} ], false);
586 main_query = query_ext.main_query_ext.query;
587 main_update_query = query_ext.main_query_ext.update_query;
590 // Here we need the full path through all subqueries
592 // XXX We might need the query name in the QueryExt structure
593 main_query.select(value);
595 // XXX When is an update query associated ?
596 // XXX main_update_query.select(value);
601 query = query_ext.query;
602 main_query = query_ext.main_query_ext.query;
603 main_update_query = query_ext.main_query_ext.update_query;
604 query.unselect(value);
605 main_query.unselect(value);
607 // We need to inform about changes in these queries to the respective plugins
608 // Note: query & main_query have the same UUID
609 manifold.raise_query_event(query_uuid, event_type, value);
612 // We need to inform about changes in these queries to the respective plugins
613 // Note: query, main_query & update_query have the same UUID
614 manifold.raise_query_event(query_uuid, event_type, value);
615 // We are targeting the same object with get and update
616 // The notion of query is bad, we should have a notion of destination, and issue queries on the destination
617 // NOTE: Editing a subquery == editing a local view on the destination
619 // XXX We might need to run the new query again and manage the plugins in the meantime with spinners...
620 // For the time being, we will collect all columns during the first query
623 /* Publish/subscribe channels for internal use */
624 get_channel: function(type, query_uuid)
626 if ((type !== 'query') && (type != 'record'))
628 return '/' + type + '/' + query_uuid;
631 }; // manifold object
632 /* ------------------------------------------------------------ */
636 // OLD PLUGIN API: extend jQuery/$ with pubsub capabilities
637 // https://gist.github.com/661855
639 $.subscribe = function( channel, selector, data, fn) {
640 /* borrowed from jQuery */
641 if ( data == null && fn == null ) {
644 data = selector = undefined;
645 } else if ( fn == null ) {
646 if ( typeof selector === "string" ) {
647 // ( channel, selector, fn )
651 // ( channel, data, fn )
654 selector = undefined;
659 /* We use an indirection function that will clone the object passed in
660 * parameter to the subscribe callback
662 * FIXME currently we only clone query objects which are the only ones
663 * supported and editable, we might have the same issue with results but
664 * the page load time will be severely affected...
666 o.on.apply(o, [channel, selector, data, function() {
667 for(i = 1; i < arguments.length; i++) {
668 if ( arguments[i].constructor.name == 'ManifoldQuery' )
669 arguments[i] = arguments[i].clone();
671 fn.apply(o, arguments);
675 $.unsubscribe = function() {
676 o.off.apply(o, arguments);
679 $.publish = function() {
680 o.trigger.apply(o, arguments);
685 /* ------------------------------------------------------------ */
687 //http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request
688 //make sure to expose csrf in our outcoming ajax/post requests
690 beforeSend: function(xhr, settings) {
691 function getCookie(name) {
692 var cookieValue = null;
693 if (document.cookie && document.cookie != '') {
694 var cookies = document.cookie.split(';');
695 for (var i = 0; i < cookies.length; i++) {
696 var cookie = jQuery.trim(cookies[i]);
697 // Does this cookie string begin with the name we want?
698 if (cookie.substring(0, name.length + 1) == (name + '=')) {
699 cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
706 if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
707 // Only send the token to relative URLs i.e. locally.
708 xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));