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 // http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/
21 Object.toType = (function toType(global) {
22 return function(obj) {
26 return ({}).toString.call(obj).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
30 /* ------------------------------------------------------------ */
32 // Constants that should be somehow moved to a plugin.js file
34 var FILTER_REMOVED = 2;
35 var CLEAR_FILTERS = 3;
37 var FIELD_REMOVED = 5;
40 var CLEAR_RECORDS = 8;
43 * event: FIELD_STATE_CHANGED
47 * .state : ???? used to be FIELD_REQUEST_ADD / FIELD_REQUEST_REMOVE
48 * .key : ??? the key fields of the record
49 * .op : the key of the record who has received an update
50 * .value : the new state of the record
52 var FIELD_STATE_CHANGED = 9;
54 var IN_PROGRESS = 101;
55 var DONE = 102; //XXX Should be harmonized with query state
57 /* Update requests related to subqueries */
61 var SET_REMOVED = 202;
66 var FIELD_REQUEST_CHANGE = 301;
67 var FIELD_REQUEST_ADD = 302;
68 var FIELD_REQUEST_REMOVE = 303;
69 var FIELD_REQUEST_ADD_RESET = 304;
70 var FIELD_REQUEST_REMOVE_RESET = 305;
72 // status (XXX Should be deprecated)
73 var FIELD_REQUEST_PENDING = 401;
74 var FIELD_REQUEST_SUCCESS = 402;
75 var FIELD_REQUEST_FAILURE = 403;
76 var STATUS_OKAY = 404;
77 var STATUS_SET_WARNING = 405;
78 var STATUS_ADD_WARNING = 406;
79 var STATUS_REMOVE_WARNING = 407;
80 var STATUS_RESET = 408;
82 /* Requests for query cycle */
88 var TYPE_LIST_OF_VALUES = 3;
89 var TYPE_LIST_OF_RECORDS = 4;
91 /******************************************************************************
92 * QUERY STATUS (for manifold events)
93 ******************************************************************************/
95 var STATUS_NONE = 500; // Query has not been started yet
96 var STATUS_GET_IN_PROGRESS = 501; // Query has been sent, no result has been received
97 var STATUS_GET_RECEIVED = 502; // Success
98 var STATUS_GET_ERROR = 503; // Error
99 var STATUS_UPDATE_PENDING = 504;
100 var STATUS_UPDATE_IN_PROGRESS = 505;
101 var STATUS_UPDATE_RECEIVED = 506;
102 var STATUS_UPDATE_ERROR = 507;
104 /******************************************************************************
105 * QUERY STATE (for query_store)
106 ******************************************************************************/
108 // XXX Rendundant with query status ?
110 var QUERY_STATE_INIT = 0;
111 var QUERY_STATE_INPROGRESS = 1;
112 var QUERY_STATE_DONE = 2;
114 /******************************************************************************
115 * RECORD STATES (for query_store)
116 ******************************************************************************/
120 var STATE_WARNINGS = 2;
121 var STATE_VISIBLE = 3;
124 var STATE_SET_CHANGE = 0;
125 var STATE_SET_ADD = 1;
126 var STATE_SET_REMOVE = 2;
127 var STATE_SET_CLEAR = 3;
130 var STATE_SET_IN = 0;
131 var STATE_SET_OUT = 1;
132 var STATE_SET_IN_PENDING = 2;
133 var STATE_SET_OUT_PENDING = 3;
134 var STATE_SET_IN_SUCCESS = 4;
135 var STATE_SET_OUT_SUCCESS = 5;
136 var STATE_SET_IN_FAILURE = 6;
137 var STATE_SET_OUT_FAILURE = 7;
138 var STATE_VALUE_CHANGE_PENDING = 8;
139 var STATE_VALUE_CHANGE_SUCCESS = 9;
140 var STATE_VALUE_CHANGE_FAILURE = 10;
142 // STATE_WARNINGS : dict
144 // STATE_VISIBLE : boolean
146 /******************************************************************************
148 ******************************************************************************/
150 var CONSTRAINT_RESERVABLE_LEASE = 0;
152 var CONSTRAINT_RESERVABLE_LEASE_MSG = "Configuration required: this resource needs to be scheduled";
154 // A structure for storing queries
156 function QueryExt(query, parent_query_ext, main_query_ext, update_query_ext, disabled, domain_query_ext) {
159 if (typeof query == "undefined")
160 throw "Must pass a query in QueryExt constructor";
162 this.parent_query_ext = (typeof parent_query_ext == "undefined") ? null : parent_query_ext;
163 this.main_query_ext = (typeof main_query_ext == "undefined") ? null : main_query_ext;
164 this.update_query_ext = (typeof update_query_ext == "undefined") ? null : update_query_ext;
165 this.update_query_orig_ext = (typeof update_query_orig_ext == "undefined") ? null : update_query_orig_ext;
166 this.disabled = (typeof disabled == "undefined") ? false : disabled;
168 // A domain query is a query that is issued to retrieve all possible values for a set
169 // eg. all resources that can be attached to a slice
170 // It is null unless we are a subquery for which a domain query has been issued
171 this.domain_query_ext = (typeof domain_query_ext == "undefined") ? null : domain_query_ext;
173 // Set members to buffer until the domain query is completed
175 this.set_members = [];
177 // The set query is the query for which the domain query has been issued.
178 // It is null unless the query is a domain query
179 this.set_query_ext = (typeof set_query_ext == "undefined") ? null : domain_query_ext;
181 this.query_state = QUERY_STATE_INIT;
183 // Results from a query consists in a dict that maps keys to records
184 this.records = new Hashtable();
186 // Status is a dict that maps keys to record status
187 this.state = new Hashtable();
189 // Filters that impact visibility in the local interface
192 // XXX Until we find a better solution
193 this.num_pending = 0;
194 this.num_unconfigured = 0;
196 // update_query null unless we are a main_query (aka parent_query == null); only main_query_fields can be updated...
199 function QueryStore() {
201 this.main_queries = {};
202 this.analyzed_queries = {};
206 this.insert = function(query) {
207 // We expect only main_queries are inserted
209 /* If the query has not been analyzed, then we analyze it */
210 if (query.analyzed_query == null) {
211 query.analyze_subqueries();
214 /* We prepare the update query corresponding to the main query and store both */
215 /* Note: they have the same UUID */
217 // XXX query.change_action() should become deprecated
218 update_query = query.clone();
219 update_query.action = 'update';
220 update_query.analyzed_query.action = 'update';
221 update_query.params = {};
222 update_query_ext = new QueryExt(update_query);
224 /* We remember the original query to be able to reset it */
225 update_query_orig_ext = new QueryExt(update_query.clone());
228 /* We store the main query */
229 query_ext = new QueryExt(query, null, null, update_query_ext, update_query_orig_ext, false);
230 manifold.query_store.main_queries[query.query_uuid] = query_ext;
231 /* Note: the update query does not have an entry! */
234 // The query is disabled; since it is incomplete until we know the content of the set of subqueries
235 // XXX unless we have no subqueries ???
236 // we will complete with params when records are received... this has to be done by the manager
237 // SET_ADD, SET_REMOVE will change the status of the elements of the set
238 // UPDATE will change also, etc.
239 // XXX We need a proper structure to store this information...
241 // We also need to insert all queries and subqueries from the analyzed_query
242 // XXX We need the root of all subqueries
243 query.iter_subqueries(function(sq, data, parent_query) {
244 var parent_query_ext;
246 parent_query_ext = manifold.query_store.find_analyzed_query_ext(parent_query.query_uuid);
248 parent_query_ext = null;
250 // XXX parent_query_ext == false
251 // XXX main.subqueries = {} # Normal, we need analyzed_query
252 sq_ext = new QueryExt(sq, parent_query_ext, query_ext)
255 /* Let's issue a query for the subquery domain. This query will not need any update etc.
256 eg. for resources in a slice, we also query all resources */
257 var all_fields = manifold.metadata.get_field_names(sq.object);
258 var domain_query = new ManifoldQuery('get', sq.object, 'now', [], {}, all_fields);
259 //var domain_query = new ManifoldQuery('get', sq.object);
261 console.log("Created domain query", domain_query);
262 var domain_query_ext = new QueryExt(domain_query);
264 domain_query_ext.set_query_ext = sq_ext;
265 sq_ext.domain_query_ext = domain_query_ext;
267 // One of these two is useless ?
268 manifold.query_store.main_queries[domain_query.query_uuid] = domain_query_ext;
269 manifold.query_store.analyzed_queries[domain_query.query_uuid] = domain_query_ext;
271 // XXX This query is run before the plugins are initialized and listening
272 manifold.run_query(domain_query);
275 manifold.query_store.analyzed_queries[sq.query_uuid] = sq_ext;
278 // XXX We have spurious update queries...
283 this.find_query_ext = function(query_uuid)
285 return this.main_queries[query_uuid];
288 this.find_query = function(query_uuid)
290 return this.find_query_ext(query_uuid).query;
293 this.find_analyzed_query_ext = function(query_uuid)
295 return this.analyzed_queries[query_uuid];
298 this.find_analyzed_query = function(query_uuid)
300 return this.find_analyzed_query_ext(query_uuid).query;
303 this.state_dict_create = function(default_set)
305 default_set = (default_set === undefined) ? STATE_SET_OUT : default_set;
307 // We cannot use constants in literal definition, so...
308 state_dict[STATE_WARNINGS] = {};
309 state_dict[STATE_SET] = default_set;
310 state_dict[STATE_VISIBLE] = true;
316 this.set_records = function(query_uuid, records, default_set)
318 default_set = (default_set === undefined) ? STATE_SET_OUT : default_set;
321 var query_ext = this.find_analyzed_query_ext(query_uuid);
322 var record_key = manifold.metadata.get_key(query_ext.query.object);
323 $.each(records, function(i, record) {
324 var key = manifold.metadata.get_key(query_ext.query.object);
325 // ["start_time", "resource", "end_time"]
328 var record_key_value = manifold.record_get_value(record, record_key);
329 query_ext.records.put(record_key_value, record);
331 if (!(query_ext.state.get(record_key_value)))
332 query_ext.state.put(record_key_value, self.state_dict_create(default_set));
336 this.get_records = function(query_uuid)
338 var query_ext = this.find_analyzed_query_ext(query_uuid);
339 return query_ext.records.values();
342 this.get_record = function(query_uuid, record_key)
344 var query_ext = this.find_analyzed_query_ext(query_uuid);
345 return query_ext.records.get(record_key);
348 this.add_record = function(query_uuid, record, new_state)
350 var query_ext, key, record_key;
351 query_ext = this.find_analyzed_query_ext(query_uuid);
353 if (typeof(record) == 'object') {
354 key = manifold.metadata.get_key(query_ext.query.object);
355 record_key = manifold.record_get_value(record, key);
360 var record_entry = query_ext.records.get(record_key);
362 query_ext.records.put(record_key, record);
364 manifold.query_store.set_record_state(query_uuid, record_key, STATE_SET, new_state);
367 this.remove_record = function(query_uuid, record, new_state)
369 var query_ext, key, record_key;
370 query_ext = this.find_analyzed_query_ext(query_uuid);
372 if (typeof(record) == 'object') {
373 key = manifold.metadata.get_key(query_ext.query.object);
374 record_key = manifold.record_get_value(record, key);
379 manifold.query_store.set_record_state(query_uuid, record_key, STATE_SET, new_state);
382 this.iter_records = function(query_uuid, callback)
384 var query_ext = this.find_analyzed_query_ext(query_uuid);
385 query_ext.records.each(callback);
386 //callback = function(record_key, record)
389 this.iter_visible_records = function(query_uuid, callback)
391 var query_ext = this.find_analyzed_query_ext(query_uuid);
392 query_ext.records.each(function(record_key, record) {
393 if (query_ext.state.get(record_key)[STATE_VISIBLE]) // .STATE_VISIBLE would be for the string key
394 callback(record_key, record);
396 //callback = function(record_key, record)
402 this.set_record_state = function(query_uuid, result_key, state, value)
404 var query_ext = this.find_analyzed_query_ext(query_uuid);
405 var state_dict = query_ext.state.get(result_key);
407 state_dict = this.state_dict_create();
409 state_dict[state] = value;
411 query_ext.state.put(result_key, state_dict);
414 this.get_record_state = function(query_uuid, result_key, state)
416 var query_ext = this.find_analyzed_query_ext(query_uuid);
417 var state_dict = query_ext.state.get(result_key);
420 return state_dict[state];
425 this.add_filter = function(query_uuid, filter)
427 var query_ext = this.find_analyzed_query_ext(query_uuid);
428 // XXX When we update a filter
429 query_ext.filters.push(filter);
431 this.apply_filters(query_uuid);
435 this.update_filter = function(query_uuid, filter)
439 this.apply_filters(query_uuid);
442 this.remove_filter = function(query_uuid, filter)
444 var query_ext = this.find_analyzed_query_ext(query_uuid);
445 query_ext.filters = $.grep(query_ext.filters, function(x) {
449 this.apply_filters(query_uuid);
452 this.get_filters = function(query_uuid)
454 var query_ext = this.find_analyzed_query_ext(query_uuid);
455 return query_ext.filters;
458 this.recount = function(query_uuid)
461 var is_reserved, is_pending, in_set, is_unconfigured;
463 query_ext = manifold.query_store.find_analyzed_query_ext(query_uuid);
464 query_ext.num_pending = 0;
465 query_ext.num_unconfigured = 0;
467 this.iter_records(query_uuid, function(record_key, record) {
468 var record_state = manifold.query_store.get_record_state(query_uuid, record_key, STATE_SET);
469 var record_warnings = manifold.query_store.get_record_state(query_uuid, record_key, STATE_WARNINGS);
471 is_reserved = (record_state == STATE_SET_IN)
472 || (record_state == STATE_SET_OUT_PENDING)
473 || (record_state == STATE_SET_IN_SUCCESS)
474 || (record_state == STATE_SET_OUT_FAILURE);
476 is_pending = (record_state == STATE_SET_IN_PENDING)
477 || (record_state == STATE_SET_OUT_PENDING);
479 in_set = (record_state == STATE_SET_IN) // should not have warnings
480 || (record_state == STATE_SET_IN_PENDING)
481 || (record_state == STATE_SET_IN_SUCCESS)
482 || (record_state == STATE_SET_OUT_FAILURE); // should not have warnings
484 is_unconfigured = (in_set && !$.isEmptyObject(record_warnings));
486 /* Let's update num_pending and num_unconfigured at this stage */
488 query_ext.num_pending++;
490 query_ext.num_unconfigured++;
495 this.apply_filters = function(query_uuid)
497 var start = new Date().getTime();
499 // Toggle visibility of records according to the different filters.
502 var filters = this.get_filters(query_uuid);
504 /* Let's update num_pending and num_unconfigured at this stage */
506 // Adapted from querytable._querytable_filter()
508 this.iter_records(query_uuid, function(record_key, record) {
509 var is_reserved, is_pending, in_set, is_unconfigured;
512 var record_state = manifold.query_store.get_record_state(query_uuid, record_key, STATE_SET);
513 var record_warnings = manifold.query_store.get_record_state(query_uuid, record_key, STATE_WARNINGS);
515 is_reserved = (record_state == STATE_SET_IN)
516 || (record_state == STATE_SET_OUT_PENDING)
517 || (record_state == STATE_SET_IN_SUCCESS)
518 || (record_state == STATE_SET_OUT_FAILURE);
520 is_pending = (record_state == STATE_SET_IN_PENDING)
521 || (record_state == STATE_SET_OUT_PENDING);
523 in_set = (record_state == STATE_SET_IN) // should not have warnings
524 || (record_state == STATE_SET_IN_PENDING)
525 || (record_state == STATE_SET_IN_SUCCESS)
526 || (record_state == STATE_SET_OUT_FAILURE); // should not have warnings
528 is_unconfigured = (in_set && !$.isEmptyObject(record_warnings));
530 // We go through each filter and decide whether it affects the visibility of the record
531 $.each(filters, function(index, filter) {
534 var value = filter[2];
537 /* We do some special handling for the manifold:status filter
540 if (key == 'manifold:status') {
541 if (op != '=' && op != '==') {
542 // Unsupported filter, let's ignore it
543 console.log("Unsupported filter on manifold:status. Should be EQUAL only.");
544 return true; // ~ continue
549 // true => ~ continue
551 visible = is_reserved;
554 visible = is_unconfigured;
557 visible = is_pending;
560 return false; // ~ break
563 /* Normal filtering behaviour (according to the record content) follows... */
564 col_value = manifold.record_get_value(record, key);
566 // When the filter does not match, we hide the column by default
567 if (col_value === 'undefined') {
569 return false; // ~ break
572 // XXX This should accept pluggable filtering functions.
575 /* Test whether current filter is compatible with the column */
576 if (op == '=' || op == '==') {
577 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
579 }else if (op == 'included') {
580 $.each(value, function(i,x) {
583 return false; // ~ break
588 }else if (op == '!=') {
589 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
592 if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
595 if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
597 } else if(op=='<=' || op=='≤') {
598 if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
600 } else if(op=='>=' || op=='≥') {
601 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
604 // How to break out of a loop ?
605 alert("filter not supported");
606 return false; // break
611 // Set the visibility status in the query store
612 self.set_record_state(query_uuid, record_key, STATE_VISIBLE, visible);
615 var end = new Date().getTime();
616 console.log("APPLY FILTERS took", end - start, "ms");
623 * This namespace holds functions for globally managing query objects
628 /**************************************************************************
630 **************************************************************************/
634 get_type: function(variable) {
635 switch(Object.toType(variable)) {
642 if ((variable.length > 0) && (Object.toType(variable[0]) === 'object'))
643 return TYPE_LIST_OF_RECORDS;
645 return TYPE_LIST_OF_VALUES;
651 * fields: A String instance (field name), or a set of String instances
652 * (field names) # XXX tuple !!
654 * If fields is a String, return the corresponding value.
655 * If fields is a set, return a tuple of corresponding value.
658 * KeyError if at least one of the fields is not found
660 record_get_value: function(record, fields)
662 if (typeof(fields) === 'string') {
663 if (fields.indexOf('.') != -1) {
664 key_subkey = key.split('.', 2);
666 subkey = key_subkey[1];
668 if (record.indexOf(key) == -1) {
671 // Tests if the following is an array (typeof would give object)
672 if (Object.prototype.toString.call(record[key]) === '[object Array]') {
674 return $.map(record[key], function(subrecord) { return manifold.record_get_value(subrecord, subkey) });
675 } else if (typeof(record) == 'object') {
677 return manifold.record_get_value(record[key], subkey);
679 console.log('Unknown field');
682 return record[fields];
685 // see. get_map_entries
686 if (fields.length == 1)
687 return manifold.record_get_value(record, fields[0])
689 // Build a new record
691 $.each(fields, function(i, field) {
692 ret[field] = manifold.record_get_value(record, field);
694 ret.hashCode = record.hashCode;
695 ret.equals = record.equals;
697 // this was an array, we want a dictionary
698 //return $.map(fields, function(x) { manifold.record_get_value(record, x) });
703 record_hashcode: function(key_fields)
707 for (var i=0; i < key_fields.length; i++)
708 ret += "@@" + this[key_fields[i]];
713 _record_equals: function(self, other, key_fields)
715 for (var i=0; i < key_fields.length; i++) {
716 var this_value = self[key_fields[i]];
717 var other_value = other[key_fields[i]];
719 var this_type = manifold.get_type(this_value);
720 var other_type = manifold.get_type(other_value);
721 if (this_type != other_type)
726 case TYPE_LIST_OF_VALUES:
727 if (this_value != other_value)
731 if (!(_record_equals(this_value, other_value, key_fields)))
734 case TYPE_LIST_OF_RECORDS:
735 if (this_value.length != other_value.length)
737 for (var j = 0; j < this_value.length; j++)
738 if (!(_record_equals(this_value[j], other_value[j], key_fields)))
746 record_equals: function(key_fields)
748 return function(other) {
749 return manifold._record_equals(this, other, key_fields);
753 _in_array: function(element, array, key_fields)
755 if (key_fields.length > 1) {
756 for (var i = 0; i < array.length; i++) {
757 if (manifold._record_equals(element, array[i], key_fields))
762 // XXX TODO If we have a dict, extract the key first
763 return ($.inArray(element, array) != -1);
767 /**************************************************************************
768 * Metadata management
769 **************************************************************************/
773 get_table: function(method) {
774 var table = MANIFOLD_METADATA[method];
775 return (typeof table === 'undefined') ? null : table;
778 get_columns: function(method) {
779 var table = this.get_table(method);
784 return (typeof table.column === 'undefined') ? null : table.column;
787 get_field_names: function(method)
789 var columns = this.get_columns(method);
792 return $.map(columns, function (x) { return x.name });
795 get_key: function(method) {
796 var table = this.get_table(method);
800 return (typeof table.key === 'undefined') ? null : table.key;
804 get_column: function(method, name) {
805 var columns = this.get_columns(method);
809 $.each(columns, function(i, c) {
816 get_type: function(method, name) {
817 var table = this.get_table(method);
821 var match = $.grep(table.column, function(x) { return x.name == name });
822 if (match.length == 0) {
825 return match[0].type;
827 return (typeof table.type === 'undefined') ? null : table.type;
832 /**************************************************************************
834 **************************************************************************/
836 query_store: new QueryStore(),
838 // XXX Remaining functions are deprecated since they are replaced by the query store
841 * Associative array storing the set of queries active on the page
847 * Insert a query in the global hash table associating uuids to queries.
848 * If the query has no been analyzed yet, let's do it.
849 * \fn insert_query(query)
851 * \param ManifoldQuery query Query to be added
853 insert_query : function (query) {
855 manifold.query_store.insert(query);
858 $(document).ready(function() {
859 manifold.run_query(query);
863 if (query.analyzed_query == null) {
864 query.analyze_subqueries();
866 manifold.all_queries[query.query_uuid]=query;
870 * Returns the query associated to a UUID
871 * \fn find_query(query_uuid)
873 * \param string query_uuid The UUID of the query to be returned
875 find_query : function (query_uuid) {
876 return manifold.all_queries[query_uuid];
879 /**************************************************************************
881 **************************************************************************/
883 // trigger a query asynchroneously
884 proxy_url : '/manifold/proxy/json/',
886 // reasonably low-noise, shows manifold requests coming in and out
887 asynchroneous_debug : true,
888 // print our more details on result publication and related callbacks
889 pubsub_debug : false,
892 * \brief We use js function closure to be able to pass the query (array)
893 * to the callback function used when data is received
895 success_closure: function(query, publish_uuid, callback) {
896 return function(data, textStatus) {
897 manifold.asynchroneous_success(data, query, publish_uuid, callback);
901 run_query: function(query, callback)
903 // default value for callback = null
904 if (typeof callback === 'undefined')
907 var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
908 query_ext.query_state = QUERY_STATE_INPROGRESS;
910 var query_json = JSON.stringify(query);
912 // Inform plugins about the progress
913 query.iter_subqueries(function (sq) {
914 var sq_query_ext = manifold.query_store.find_analyzed_query_ext(sq.query_uuid);
915 sq_query_ext.query_state = QUERY_STATE_INPROGRESS;
917 manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
921 $.post(manifold.proxy_url, {'json': query_json} , manifold.success_closure(query, null, callback));
925 // Executes all async. queries - intended for the javascript header to initialize queries
926 // input queries are specified as a list of {'query_uuid': <query_uuid> }
927 // each plugin is responsible for managing its spinner through on_query_in_progress
928 asynchroneous_exec : function (query_exec_tuples) {
930 // Loop through input array, and use publish_uuid to publish back results
931 $.each(query_exec_tuples, function(index, tuple) {
932 var query=manifold.find_query(tuple.query_uuid);
933 var query_json=JSON.stringify (query);
934 var publish_uuid=tuple.publish_uuid;
935 // by default we publish using the same uuid of course
936 if (publish_uuid==undefined) publish_uuid=query.query_uuid;
937 if (manifold.pubsub_debug) {
938 messages.debug("sending POST on " + manifold.proxy_url + query.__repr());
941 query.iter_subqueries(function (sq) {
942 manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
945 // not quite sure what happens if we send a string directly, as POST data is named..
946 // this gets reconstructed on the proxy side with ManifoldQuery.fill_from_POST
947 $.post(manifold.proxy_url, {'json':query_json},
948 manifold.success_closure(query, publish_uuid, tuple.callback));
953 * \brief Forward a query to the manifold backend
954 * \param query (dict) the query to be executed asynchronously
955 * \param callback (function) the function to be called when the query terminates
957 forward: function(query, callback) {
958 var query_json = JSON.stringify(query);
959 $.post(manifold.proxy_url, {'json': query_json} ,
960 manifold.success_closure(query, query.query_uuid, callback));
964 * Returns whether a query expects a unique results.
965 * This is the case when the filters contain a key of the object
966 * \fn query_expects_unique_result(query)
968 * \param ManifoldQuery query Query for which we are testing whether it expects a unique result
970 query_expects_unique_result: function(query) {
971 /* XXX we need functions to query metadata */
972 //var keys = MANIFOLD_METADATA[query.object]['keys']; /* array of array of field names */
973 /* TODO requires keys in metadata */
979 * \fn publish_result(query, results)
981 * \param ManifoldQuery query Query which has received results
982 * \param array results results corresponding to query
984 publish_result: function(query, result) {
985 if (typeof result === 'undefined')
989 manifold.raise_record_event(query.query_uuid, CLEAR_RECORDS);
990 if (manifold.pubsub_debug)
991 messages.debug(".. publish_result (1) ");
993 $.each(result, function(i, record) {
994 manifold.raise_record_event(query.query_uuid, NEW_RECORD, record);
997 if (manifold.pubsub_debug)
998 messages.debug(".. publish_result (2) has used NEW API on " + count + " records");
999 manifold.raise_record_event(query.query_uuid, DONE);
1000 if (manifold.pubsub_debug)
1001 messages.debug(".. publish_result (3) has used NEW API to say DONE");
1003 // OLD PLUGIN API BELOW
1004 /* Publish an update announce */
1005 var channel="/results/" + query.query_uuid + "/changed";
1006 if (manifold.pubsub_debug)
1007 messages.debug(".. publish_result (4) OLD API on channel" + channel);
1009 $.publish(channel, [result, query]);
1011 if (manifold.pubsub_debug)
1012 messages.debug(".. publish_result (5) END q=" + query.__repr());
1015 store_records: function(query, records) {
1017 var query_ext = manifold.query_store.find_analyzed_query_ext(query.query_uuid);
1018 if (query_ext.set_query_ext) {
1019 // We have a domain query
1020 // The results are stored in the corresponding set_query
1021 if (query.object == 'lease') {
1022 // temp fix for leases_all
1023 manifold.query_store.set_records(query_ext.set_query_ext.query.query_uuid, records, STATE_SET_IN);
1025 manifold.query_store.set_records(query_ext.set_query_ext.query.query_uuid, records);
1028 } else if (query_ext.domain_query_ext) {
1029 // We have a set query, it is only used to determine which objects are in the set, we should only retrieve the key
1030 // Has it a domain query, and has it completed ?
1031 if (query.object == 'lease') {
1032 $.noop(); // slice leases should be included in the results from the domain query lease_all
1034 $.each(records, function(i, record) {
1035 var key = manifold.metadata.get_key(query.object);
1036 var record_key = manifold.record_get_value(record, key);
1037 manifold.query_store.set_record_state(query.query_uuid, record_key, STATE_SET, STATE_SET_IN);
1042 // We have a normal query
1043 manifold.query_store.set_records(query.query_uuid, records, STATE_SET_IN);
1048 * Recursively publish result
1049 * \fn publish_result_rec(query, result)
1050 * \memberof Manifold
1051 * \param ManifoldQuery query Query which has received result
1052 * \param array result result corresponding to query
1054 * Note: this function works on the analyzed query
1056 publish_result_rec: function(query, records) {
1057 /* If the result is not unique, only publish the top query;
1058 * otherwise, publish the main object as well as subqueries
1059 * XXX how much recursive are we ?
1061 if (manifold.pubsub_debug)
1062 messages.debug (">>>>> publish_result_rec " + query.object);
1063 if (manifold.query_expects_unique_result(query)) {
1064 /* Also publish subqueries */
1065 $.each(query.subqueries, function(object, subquery) {
1066 manifold.publish_result_rec(subquery, records[0][object]);
1067 /* TODO remove object from result */
1070 if (manifold.pubsub_debug)
1071 messages.debug ("===== publish_result_rec " + query.object);
1073 var query_ext = manifold.query_store.find_analyzed_query_ext(query.query_uuid);
1074 query_ext.query_state = QUERY_STATE_DONE;
1076 this.store_records(query, records);
1080 if (query_ext.set_query_ext) {
1081 if (query_ext.set_query_ext.query_state != QUERY_STATE_DONE)
1083 pub_query = query_ext.set_query_ext.query;
1084 } else if (query_ext.domain_query_ext) {
1085 if (query_ext.domain_query_ext.query_state != QUERY_STATE_DONE)
1091 // We can only publish results if the query (and its related domain query) is complete
1092 manifold.publish_result(pub_query, records);
1094 if (manifold.pubsub_debug)
1095 messages.debug ("<<<<< publish_result_rec " + query.object);
1098 setup_update_query: function(query, records)
1100 // We don't prepare an update query if the result has more than 1 entry
1101 if (records.length != 1)
1103 var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
1105 var record = records[0];
1107 var update_query_ext = query_ext.update_query_ext;
1109 if (!update_query_ext)
1112 var update_query = update_query_ext.query;
1113 var update_query_ext = query_ext.update_query_ext;
1114 var update_query_orig = query_ext.update_query_orig_ext.query;
1116 // Testing whether the result has subqueries (one level deep only)
1117 // iif the query has subqueries
1119 var obj = query.analyzed_query.subqueries;
1120 for (method in obj) {
1121 if (obj.hasOwnProperty(method)) {
1122 var key = manifold.metadata.get_key(method);
1126 var subrecords = record[method];
1129 $.each(subrecords, function (i, subrecord) {
1130 sq_keys.push(manifold.record_get_value(subrecord, key));
1132 update_query.params[method] = sq_keys;
1133 update_query_orig.params[method] = sq_keys.slice();
1139 update_query_ext.disabled = false;
1140 update_query_orig_ext.disabled = false;
1144 process_get_query_records: function(query, records) {
1145 this.setup_update_query(query, records);
1147 var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
1148 query_ext.query_state = QUERY_STATE_DONE;
1150 /* Publish full results */
1151 var tmp_query = manifold.query_store.find_analyzed_query(query.query_uuid);
1152 manifold.publish_result_rec(tmp_query, records);
1155 make_records: function(object, records)
1157 $.each(records, function(i, record) {
1158 manifold.make_record(object, record);
1162 make_record: function(object, record)
1164 // To make an object a record, we just add the hash function
1165 var key = manifold.metadata.get_key(object);
1166 record.hashCode = manifold.record_hashcode(key.sort());
1167 record.equals = manifold.record_equals(key);
1169 // Looking after subrecords
1170 for (var field in record) {
1171 var result_value = record[field];
1173 switch (this.get_type(result_value)) {
1175 var subobject = manifold.metadata.get_type(object, field);
1176 // if (subobject) XXX Bugs with fields declared string while they are not : network.version is a dict in fact
1177 if (subobject && subobject != 'string')
1178 manifold.make_record(subobject, result_value);
1180 case TYPE_LIST_OF_RECORDS:
1181 var subobject = manifold.metadata.get_type(object, field);
1183 manifold.make_records(subobject, result_value);
1191 * What we need to do when receiving results from an update query:
1192 * - differences between what we had, what we requested, and what we obtained
1193 * . what we had : update_query_orig (simple fields and set fields managed differently)
1194 * . what we requested : update_query
1195 * . what we received : records
1196 * - raise appropriate events
1198 * The normal process is that results similar to Get will be pushed in the
1199 * pubsub mechanism, thus repopulating everything while we only need
1200 * diff's. This means we need to move the publish functionalities in the
1201 * previous 'process_get_query_records' function.
1203 process_update_query_records: function(query, records) {
1204 // First issue: we request everything, and not only what we modify, so will will have to ignore some fields
1205 var query_uuid = query.query_uuid;
1206 var query_ext = manifold.query_store.find_analyzed_query_ext(query_uuid);
1207 var update_query = query_ext.main_query_ext.update_query_ext.query;
1208 var update_query_orig = query_ext.main_query_ext.update_query_orig_ext.query;
1210 // Since we update objects one at a time, we can get the first record
1211 var record = records[0];
1213 // Let's iterate over the object properties
1214 for (var field in record) {
1215 var result_value = record[field];
1216 switch (this.get_type(result_value)) {
1218 // Did we ask for a change ?
1219 var update_value = update_query[field];
1221 // Not requested, if it has changed: OUT OF SYNC
1222 // How we can know ?
1223 // We assume it won't have changed
1227 throw "Internal error";
1233 value : (update_value == result_value) ? STATE_VALUE_CHANGE_SUCCESS : STATE_VALUE_CHANGE_FAILURE,
1235 manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1239 throw "Not implemented";
1243 case TYPE_LIST_OF_VALUES:
1244 // Same as list of records, but we don't have to extract keys
1246 // The rest of exactly the same (XXX factorize)
1247 var update_keys = update_query_orig.params[field];
1248 var query_keys = update_query.params[field];
1249 var added_keys = $.grep(query_keys, function (x) { return $.inArray(x, update_keys) == -1 });
1250 var removed_keys = $.grep(update_keys, function (x) { return $.inArray(x, query_keys) == -1 });
1253 $.each(added_keys, function(i, key) {
1254 if ($.inArray(key, result_value) == -1) {
1256 request: FIELD_REQUEST_ADD,
1259 status: FIELD_REQUEST_FAILURE,
1263 request: FIELD_REQUEST_ADD,
1266 status: FIELD_REQUEST_SUCCESS,
1269 manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1271 $.each(removed_keys, function(i, key) {
1272 if ($.inArray(key, result_keys) == -1) {
1274 request: FIELD_REQUEST_REMOVE,
1277 status: FIELD_REQUEST_SUCCESS,
1281 request: FIELD_REQUEST_REMOVE,
1284 status: FIELD_REQUEST_FAILURE,
1287 manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1293 case TYPE_LIST_OF_VALUES: // XXX Until fixed
1294 case TYPE_LIST_OF_RECORDS:
1295 var new_state,cur_query_uuid;
1297 cur_query_uuid = query.analyzed_query.subqueries[field].query_uuid;
1299 // example: slice.resource
1300 // - update_query_orig.params.resource = resources in slice before update
1301 // - update_query.params.resource = resource requested in slice
1302 // - keys from field = resources obtained
1303 var key = manifold.metadata.get_key(field);
1307 if (key.length > 1) {
1308 throw "Not implemented";
1314 /* XXX should be modified for multiple keys */
1315 var result_keys = $.map(record[field], function(x) { return manifold.record_get_value(x, key); });
1317 // XXX All this could be deduced from record state : STATE_IN_PENDING and STATE_OUT_PENDING
1318 // what we had at the begining
1319 var update_keys = update_query_orig.params[field];
1321 var query_keys = update_query.params[field];
1322 // what we added and removed
1323 var added_keys = $.grep(query_keys, function (x) { return (!(manifold._in_array(x, update_keys, key))); });
1324 var removed_keys = $.grep(update_keys, function (x) { return (!(manifold._in_array(x, query_keys, key))); });
1326 // Send events related to parent query
1327 $.each(added_keys, function(i, added_key) {
1328 new_state = (manifold._in_array(added_key, result_keys, key)) ? STATE_SET_IN_SUCCESS : STATE_SET_IN_FAILURE;
1330 // Update record state for children queries
1331 manifold.query_store.set_record_state(cur_query_uuid, added_key, STATE_SET, new_state);
1333 // XXX This could be optimized
1334 manifold.query_store.recount(cur_query_uuid);
1336 data = { state: STATE_SET, key : field, op : new_state, value: added_key }
1337 manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1339 $.each(removed_keys, function(i, removed_key) {
1340 new_state = (manifold._in_array(removed_key, result_keys, key)) ? STATE_SET_OUT_FAILURE : STATE_SET_OUT_SUCCESS;
1342 // Update record state for children queries
1343 manifold.query_store.set_record_state(cur_query_uuid, removed_key, STATE_SET, new_state);
1345 // XXX This could be optimized
1346 manifold.query_store.recount(cur_query_uuid);
1348 data = { state: STATE_SET, key : field, op : new_state, value: removed_key }
1349 manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1356 // XXX Now we need to adapt 'update' and 'update_orig' queries as if we had done a get
1357 this.setup_update_query(query, records);
1359 var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
1360 query_ext.query_state = QUERY_STATE_DONE;
1362 // Send DONE message to plugins
1363 query.iter_subqueries(function(sq, data, parent_query) {
1364 manifold.raise_record_event(sq.query_uuid, DONE);
1369 process_query_records: function(query, records) {
1370 if (query.action == 'get') {
1371 this.process_get_query_records(query, records);
1372 } else if (query.action == 'update') {
1373 this.process_update_query_records(query, records);
1377 // if set callback is provided it is called
1378 // most of the time publish_uuid will be query.query_uuid
1379 // however in some cases we wish to publish the result under a different uuid
1380 // e.g. an updater wants to publish its result as if from the original (get) query
1381 asynchroneous_success : function (data, query, publish_uuid, callback) {
1382 // xxx should have a nicer declaration of that enum in sync with the python code somehow
1384 var start = new Date();
1385 if (manifold.asynchroneous_debug)
1386 messages.debug(">>>>>>>>>> asynchroneous_success query.object=" + query.object);
1388 if (data.code == 2) { // ERROR
1389 // We need to make sense of error codes here
1390 alert("Your session has expired, please log in again");
1391 localStorage.removeItem('user');
1392 window.location="/logout/";
1393 if (manifold.asynchroneous_debug) {
1394 duration=new Date()-start;
1395 messages.debug ("<<<<<<<<<< asynchroneous_success " + query.object + " -- error returned - logging out " + duration + " ms");
1399 if (data.code == 1) { // WARNING
1400 messages.error("Some errors have been received from the manifold backend at " + MANIFOLD_URL + " [" + data.description + "]");
1401 // publish error code and text message on a separate channel for whoever is interested
1403 $.publish("/results/" + publish_uuid + "/failed", [data.code, data.description] );
1407 // If a callback has been specified, we redirect results to it
1410 if (manifold.asynchroneous_debug) {
1411 duration=new Date()-start;
1412 messages.debug ("<<<<<<<<<< asynchroneous_success " + query.object + " -- callback ended " + duration + " ms");
1417 if (manifold.asynchroneous_debug)
1418 messages.debug ("========== asynchroneous_success " + query.object + " -- before process_query_records [" + query.query_uuid +"]");
1420 // once everything is checked we can use the 'value' part of the manifoldresult
1421 var result=data.value;
1423 /* Eventually update the content of related queries (update, etc) */
1424 manifold.make_records(query.object, result);
1425 this.process_query_records(query, result);
1427 /* Publish results: disabled here, done in the previous call */
1428 //tmp_query = manifold.find_query(query.query_uuid);
1429 //manifold.publish_result_rec(tmp_query.analyzed_query, result);
1431 if (manifold.asynchroneous_debug) {
1432 duration=new Date()-start;
1433 messages.debug ("<<<<<<<<<< asynchroneous_success " + query.object + " -- done " + duration + " ms");
1438 /**************************************************************************
1439 * Plugin API helpers
1440 **************************************************************************/
1442 raise_event_handler: function(type, query_uuid, event_type, value) {
1443 if (manifold.pubsub_debug)
1444 messages.debug("raise_event_handler, quuid="+query_uuid+" type="+type+" event_type="+event_type);
1445 if ((type != 'query') && (type != 'record'))
1446 throw 'Incorrect type for manifold.raise_event()';
1447 // xxx we observe quite a lot of incoming calls with an undefined query_uuid
1448 // this should be fixed upstream in manifold I expect
1449 if (query_uuid === undefined) {
1450 messages.warning("undefined query in raise_event_handler");
1454 // notify the change to objects that either listen to this channel specifically,
1455 // or to the wildcard channel
1456 var channels = [ manifold.get_channel(type, query_uuid), manifold.get_channel(type, '*') ];
1458 $.each(channels, function(i, channel) {
1459 if (value === undefined) {
1460 if (manifold.pubsub_debug) messages.debug("triggering [no value] on channel="+channel+" and event_type="+event_type);
1461 $('.pubsub').trigger(channel, [event_type]);
1463 if (manifold.pubsub_debug) messages.debug("triggering [value="+value+"] on channel="+channel+" and event_type="+event_type);
1464 $('.pubsub').trigger(channel, [event_type, value]);
1469 raise_query_event: function(query_uuid, event_type, value) {
1470 manifold.raise_event_handler('query', query_uuid, event_type, value);
1473 raise_record_event: function(query_uuid, event_type, value) {
1474 manifold.raise_event_handler('record', query_uuid, event_type, value);
1478 * Event handler helpers
1480 _get_next_state_add: function(prev_state)
1482 switch (prev_state) {
1484 case STATE_SET_OUT_SUCCESS:
1485 case STATE_SET_IN_FAILURE:
1486 new_state = STATE_SET_IN_PENDING;
1489 case STATE_SET_OUT_PENDING:
1490 new_state = STATE_SET_IN;
1494 case STATE_SET_IN_PENDING:
1495 case STATE_SET_IN_SUCCESS:
1496 case STATE_SET_OUT_FAILURE:
1497 console.log("Inconsistent state: already in");
1503 _get_next_state_remove: function(prev_state)
1505 switch (prev_state) {
1507 case STATE_SET_IN_SUCCESS:
1508 case STATE_SET_OUT_FAILURE:
1509 new_state = STATE_SET_OUT_PENDING;
1512 case STATE_SET_IN_PENDING:
1513 new_state = STATE_SET_OUT;
1517 case STATE_SET_OUT_PENDING:
1518 case STATE_SET_OUT_SUCCESS:
1519 case STATE_SET_IN_FAILURE:
1520 console.log("Inconsistent state: already out");
1526 _grep_active_lease_callback: function(lease_query, resource_key) {
1527 return function(lease_key_lease) {
1528 var state, lease_key, lease;
1530 lease_key = lease_key_lease[0];
1531 lease = lease_key_lease[1];
1533 if (lease['resource'] != resource_key)
1536 state = manifold.query_store.get_record_state(lease_query.query_uuid, lease_key, STATE_SET);;
1539 case STATE_SET_IN_PENDING:
1540 case STATE_SET_IN_SUCCESS:
1541 case STATE_SET_OUT_FAILURE:
1544 case STATE_SET_OUT_PENDING:
1545 case STATE_SET_OUT_SUCCESS:
1546 case STATE_SET_IN_FAILURE:
1552 _enforce_constraints: function(query_ext, record, resource_key, event_type)
1556 query = query_ext.query;
1558 switch(query.object) {
1561 // CONSTRAINT_RESERVABLE_LEASE
1563 // +) If a reservable node is added to the slice, then it should have a corresponding lease
1564 // XXX Not always a resource
1565 var is_reservable = (record.exclusive == true);
1566 if (is_reservable) {
1567 var warnings = manifold.query_store.get_record_state(query.query_uuid, resource_key, STATE_WARNINGS);
1569 if (event_type == STATE_SET_ADD) {
1570 // We should have a lease_query associated
1571 var lease_query = query_ext.parent_query_ext.query.subqueries['lease']; // in options
1572 var lease_query_ext = manifold.query_store.find_analyzed_query_ext(lease_query.query_uuid);
1573 // Do we have lease records (in) with this resource
1574 var lease_records = $.grep(lease_query_ext.records.entries(), this._grep_active_lease_callback(lease_query, resource_key));
1575 if (lease_records.length == 0) {
1577 // XXX Need for a better function to manage warnings
1578 var warn = CONSTRAINT_RESERVABLE_LEASE_MSG;
1579 warnings[CONSTRAINT_RESERVABLE_LEASE] = warn;
1581 // Lease are defined, delete the warning in case it was set previously
1582 delete warnings[CONSTRAINT_RESERVABLE_LEASE];
1585 // Remove warnings attached to this resource
1586 delete warnings[CONSTRAINT_RESERVABLE_LEASE];
1589 manifold.query_store.set_record_state(query.query_uuid, resource_key, STATE_WARNINGS, warnings);
1592 /* This was redundant */
1593 // manifold.query_store.recount(query.query_uuid);
1595 // Signal the change to plugins (even if the constraint does not apply, so that the plugin can display a checkmark)
1597 state: STATE_WARNINGS,
1602 manifold.raise_record_event(query.query_uuid, FIELD_STATE_CHANGED, data);
1606 var resource_key = record.resource;
1607 var resource_query = query_ext.parent_query_ext.query.subqueries['resource'];
1608 var warnings = manifold.query_store.get_record_state(resource_query.query_uuid, resource_key, STATE_WARNINGS);
1610 if (event_type == STATE_SET_ADD) {
1611 // A lease is added, it removes the constraint
1612 delete warnings[CONSTRAINT_RESERVABLE_LEASE];
1614 // A lease is removed, it might trigger the warning
1615 var lease_records = $.grep(query_ext.records.entries(), this._grep_active_lease_callback(query, resource_key));
1616 if (lease_records.length == 0) { // XXX redundant cases
1618 // XXX Need for a better function to manage warnings
1619 var warn = CONSTRAINT_RESERVABLE_LEASE_MSG;
1620 warnings[CONSTRAINT_RESERVABLE_LEASE] = warn;
1622 // Lease are defined, delete the warning in case it was set previously
1623 delete warnings[CONSTRAINT_RESERVABLE_LEASE];
1628 manifold.query_store.recount(resource_query.query_uuid);
1630 // Signal the change to plugins (even if the constraint does not apply, so that the plugin can display a checkmark)
1632 state: STATE_WARNINGS,
1637 manifold.raise_record_event(resource_query.query_uuid, FIELD_STATE_CHANGED, data);
1641 // -) When a lease is added, it might remove the warning associated to a reservable node
1643 // If a NITOS node is reserved, then at least a NITOS channel should be reserved
1644 // - When a NITOS channel is added, it might remove a warning associated to all NITOS nodes
1646 // If a NITOS channel is reserved, then at least a NITOS node should be reserved
1647 // - When a NITOS node is added, it might remove a warning associated to all NITOS channels
1649 // A lease is present while the resource has been removed => Require warnings on nodes not in set !
1653 _get_query_path: function(query_ext) {
1656 while (sq.parent_query_ext) {
1659 path = sq.query.object + path;
1660 sq = sq.parent_query_ext;
1667 * Handling events raised by plugins
1669 raise_event: function(query_uuid, event_type, data)
1671 var query, query_ext;
1673 // Query uuid has been updated with the key of a new element
1674 query_ext = manifold.query_store.find_analyzed_query_ext(query_uuid);
1675 query = query_ext.query;
1677 switch(event_type) {
1679 // XXX At some point, should be renamed to RECORD_STATE_CHANGED
1680 case FIELD_STATE_CHANGED:
1682 // value is an object (request, key, value, status)
1683 // update is only possible is the query is not pending, etc
1684 // SET_ADD is on a subquery, FIELD_STATE_CHANGED on the query itself
1685 // we should map SET_ADD on this...
1687 // 1. Update internal query store about the change in status
1689 // 2. Update the update query
1690 update_query = query_ext.main_query_ext.update_query_ext.query;
1691 update_query_orig = query_ext.main_query_ext.update_query_orig_ext.query;
1693 switch(data.state) {
1698 /* Set parameter data.key in the update_query to VALUE */
1699 if (update_query.params[data.key] === undefined)
1700 update_query.params[data.key] = Array();
1701 update_query.params[data.key] = value.value;
1708 var prev_state, new_state;
1709 var main_query, record, new_data, path;
1711 // We only track state in the analyzed query
1712 prev_state = manifold.query_store.get_record_state(query_uuid, data.value, STATE_SET);
1713 if (prev_state === null)
1714 prev_state = STATE_SET_OUT;
1718 new_state = this._get_next_state_add(prev_state);
1720 /* data.value containts the resource key */
1721 manifold.query_store.add_record(query_uuid, data.value, new_state);
1722 record = manifold.query_store.get_record(query_uuid, data.value);
1723 this._enforce_constraints(query_ext, record, data.value, STATE_SET_ADD);
1725 /* Process update query in parent */
1726 path = this._get_query_path(query_ext);
1727 if (update_query.params[path] === undefined)
1728 update_query.params[path] = Array();
1729 update_query.params[path].push(data.value);
1733 case STATE_SET_REMOVE:
1734 new_state = this._get_next_state_remove(prev_state);
1736 /* data.value contains the resource key */
1737 manifold.query_store.remove_record(query_uuid, data.value, new_state);
1738 record = manifold.query_store.get_record(query_uuid, data.value);
1739 this._enforce_constraints(query_ext, record, data.value, STATE_SET_REMOVE);
1741 /* Process update query in parent */
1742 path = this._get_query_path(query_ext);
1743 arr = update_query.params[path];
1745 var key = manifold.metadata.get_key(query.object);
1746 arr = $.grep(arr, function(x) { return (!(manifold._record_equals(x, data.value, key))); });
1747 if (update_query.params[path] === undefined)
1748 update_query.params[path] = Array();
1749 update_query.params[path] = arr;
1753 /* Inform the parent query: important for update */
1760 main_query = query_ext.main_query_ext.query;
1761 manifold.raise_record_event(main_query.query_uuid, event_type, new_data);
1762 /* Propagate the event to other plugins subscribed to the query */
1763 manifold.query_store.recount(query_uuid);
1765 manifold.raise_record_event(query_uuid, event_type, new_data);
1770 // 3. Inform others about the change
1771 // a) the main query...
1772 manifold.raise_record_event(query_uuid, event_type, data);
1774 // b) subqueries eventually (dot in the key)
1777 var cur_query = query;
1778 if (cur_query.analyzed_query)
1779 cur_query = cur_query.analyzed_query;
1782 var path_array = data.key.split('.');
1783 var value_key = data.key.split('.');
1784 $.each(path_array, function(i, method) {
1785 cur_query = cur_query.subqueries[method];
1786 value_key.shift(); // XXX check that method is indeed shifted
1788 data.key = value_key;
1790 manifold.raise_record_event(cur_query.query_uuid, event_type, data);
1796 manifold.run_query(query_ext.main_query_ext.update_query_ext.query);
1799 /* QUERY STATE CHANGED */
1804 /* Update internal record state */
1805 manifold.query_store.add_filter(query_uuid, data);
1807 /* Propagate the message to plugins */
1808 manifold.raise_query_event(query_uuid, event_type, data);
1812 case FILTER_REMOVED:
1813 /* Update internal record state */
1814 manifold.query_store.remove_filter(query_uuid, data);
1816 /* Propagate the message to plugins */
1817 manifold.raise_query_event(query_uuid, event_type, data);
1822 main_query = query_ext.main_query_ext.query;
1823 main_update_query = query_ext.main_query_ext.update_query;
1826 // Here we need the full path through all subqueries
1828 // XXX We might need the query name in the QueryExt structure
1829 main_query.select(data);
1831 // XXX When is an update query associated ?
1832 // XXX main_update_query.select(value);
1834 manifold.raise_query_event(query_uuid, event_type, data);
1838 query = query_ext.query;
1839 main_query = query_ext.main_query_ext.query;
1840 main_update_query = query_ext.main_query_ext.update_query;
1841 query.unselect(data);
1842 main_query.unselect(data);
1844 // We need to inform about changes in these queries to the respective plugins
1845 // Note: query & main_query have the same UUID
1846 manifold.raise_query_event(query_uuid, event_type, data);
1849 // We need to inform about changes in these queries to the respective plugins
1850 // Note: query, main_query & update_query have the same UUID
1852 // http://trac.myslice.info/ticket/32
1853 // Avoid multiple calls to the same event
1854 //manifold.raise_query_event(query_uuid, event_type, value);
1856 // We are targeting the same object with get and update
1857 // The notion of query is bad, we should have a notion of destination, and issue queries on the destination
1858 // NOTE: Editing a subquery == editing a local view on the destination
1860 // XXX We might need to run the new query again and manage the plugins in the meantime with spinners...
1861 // For the time being, we will collect all columns during the first query
1864 /* Publish/subscribe channels for internal use */
1865 get_channel: function(type, query_uuid) {
1866 if ((type !== 'query') && (type != 'record'))
1868 return '/' + type + '/' + query_uuid;
1871 }; // manifold object
1872 /* ------------------------------------------------------------ */
1876 // OLD PLUGIN API: extend jQuery/$ with pubsub capabilities
1877 // https://gist.github.com/661855
1879 $.subscribe = function( channel, selector, data, fn) {
1880 /* borrowed from jQuery */
1881 if ( data == null && fn == null ) {
1884 data = selector = undefined;
1885 } else if ( fn == null ) {
1886 if ( typeof selector === "string" ) {
1887 // ( channel, selector, fn )
1891 // ( channel, data, fn )
1894 selector = undefined;
1899 /* We use an indirection function that will clone the object passed in
1900 * parameter to the subscribe callback
1902 * FIXME currently we only clone query objects which are the only ones
1903 * supported and editable, we might have the same issue with results but
1904 * the page load time will be severely affected...
1906 o.on.apply(o, [channel, selector, data, function() {
1907 for(i = 1; i < arguments.length; i++) {
1908 if ( arguments[i].constructor.name == 'ManifoldQuery' )
1909 arguments[i] = arguments[i].clone();
1911 fn.apply(o, arguments);
1915 $.unsubscribe = function() {
1916 o.off.apply(o, arguments);
1919 $.publish = function() {
1920 o.trigger.apply(o, arguments);
1925 /* ------------------------------------------------------------ */
1927 //http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request
1928 //make sure to expose csrf in our outcoming ajax/post requests
1930 beforeSend: function(xhr, settings) {
1931 function getCookie(name) {
1932 var cookieValue = null;
1933 if (document.cookie && document.cookie != '') {
1934 var cookies = document.cookie.split(';');
1935 for (var i = 0; i < cookies.length; i++) {
1936 var cookie = jQuery.trim(cookies[i]);
1937 // Does this cookie string begin with the name we want?
1938 if (cookie.substring(0, name.length + 1) == (name + '=')) {
1939 cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
1946 if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
1947 // Only send the token to relative URLs i.e. locally.
1948 xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));