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.del_record = function(query_uuid, record_key)
350 var query_ext = this.find_analyzed_query_ext(query_uuid);
351 return query_ext.records.remove(record_key);
354 this.add_record = function(query_uuid, record, new_state)
356 var query_ext, key, record_key;
357 query_ext = this.find_analyzed_query_ext(query_uuid);
359 if (typeof(record) == 'object') {
360 key = manifold.metadata.get_key(query_ext.query.object);
361 record_key = manifold.record_get_value(record, key);
366 var record_entry = query_ext.records.get(record_key);
368 query_ext.records.put(record_key, record);
370 manifold.query_store.set_record_state(query_uuid, record_key, STATE_SET, new_state);
373 this.remove_record = function(query_uuid, record, new_state)
375 var query_ext, key, record_key;
376 query_ext = this.find_analyzed_query_ext(query_uuid);
378 if (typeof(record) == 'object') {
379 key = manifold.metadata.get_key(query_ext.query.object);
380 record_key = manifold.record_get_value(record, key);
385 if ((query_ext.query.object == 'lease') && (new_state == STATE_SET_OUT)) {
386 // Leases that are marked out are in fact leases from other slices
387 // We need to _remove_ leases that we mark as OUT
388 manifold.query_store.del_record(query_uuid, record_key);
390 manifold.query_store.set_record_state(query_uuid, record_key, STATE_SET, new_state);
394 this.iter_records = function(query_uuid, callback)
396 var query_ext = this.find_analyzed_query_ext(query_uuid);
397 query_ext.records.each(callback);
398 //callback = function(record_key, record)
401 this.iter_visible_records = function(query_uuid, callback)
403 var query_ext = this.find_analyzed_query_ext(query_uuid);
404 query_ext.records.each(function(record_key, record) {
405 if (query_ext.state.get(record_key)[STATE_VISIBLE]) // .STATE_VISIBLE would be for the string key
406 callback(record_key, record);
408 //callback = function(record_key, record)
414 this.set_record_state = function(query_uuid, result_key, state, value)
416 var query_ext = this.find_analyzed_query_ext(query_uuid);
417 var state_dict = query_ext.state.get(result_key);
419 state_dict = this.state_dict_create();
421 state_dict[state] = value;
423 query_ext.state.put(result_key, state_dict);
426 this.get_record_state = function(query_uuid, result_key, state)
428 var query_ext = this.find_analyzed_query_ext(query_uuid);
429 var state_dict = query_ext.state.get(result_key);
432 return state_dict[state];
437 this.add_filter = function(query_uuid, filter)
439 var query_ext = this.find_analyzed_query_ext(query_uuid);
440 // XXX When we update a filter
441 query_ext.filters.push(filter);
443 this.apply_filters(query_uuid);
447 this.update_filter = function(query_uuid, filter)
451 this.apply_filters(query_uuid);
454 this.remove_filter = function(query_uuid, filter)
456 var query_ext = this.find_analyzed_query_ext(query_uuid);
457 query_ext.filters = $.grep(query_ext.filters, function(x) {
461 this.apply_filters(query_uuid);
464 this.get_filters = function(query_uuid)
466 var query_ext = this.find_analyzed_query_ext(query_uuid);
467 return query_ext.filters;
470 this.recount = function(query_uuid)
473 var is_reserved, is_pending, in_set, is_unconfigured;
475 query_ext = manifold.query_store.find_analyzed_query_ext(query_uuid);
476 query_ext.num_pending = 0;
477 query_ext.num_unconfigured = 0;
479 this.iter_records(query_uuid, function(record_key, record) {
480 var record_state = manifold.query_store.get_record_state(query_uuid, record_key, STATE_SET);
481 var record_warnings = manifold.query_store.get_record_state(query_uuid, record_key, STATE_WARNINGS);
483 is_reserved = (record_state == STATE_SET_IN)
484 || (record_state == STATE_SET_OUT_PENDING)
485 || (record_state == STATE_SET_IN_SUCCESS)
486 || (record_state == STATE_SET_OUT_FAILURE);
488 is_pending = (record_state == STATE_SET_IN_PENDING)
489 || (record_state == STATE_SET_OUT_PENDING);
491 in_set = (record_state == STATE_SET_IN) // should not have warnings
492 || (record_state == STATE_SET_IN_PENDING)
493 || (record_state == STATE_SET_IN_SUCCESS)
494 || (record_state == STATE_SET_OUT_FAILURE); // should not have warnings
496 is_unconfigured = (in_set && !$.isEmptyObject(record_warnings));
498 /* Let's update num_pending and num_unconfigured at this stage */
500 query_ext.num_pending++;
502 query_ext.num_unconfigured++;
507 this.apply_filters = function(query_uuid)
509 var start = new Date().getTime();
511 // Toggle visibility of records according to the different filters.
514 var filters = this.get_filters(query_uuid);
516 /* Let's update num_pending and num_unconfigured at this stage */
518 // Adapted from querytable._querytable_filter()
520 this.iter_records(query_uuid, function(record_key, record) {
521 var is_reserved, is_pending, in_set, is_unconfigured;
524 var record_state = manifold.query_store.get_record_state(query_uuid, record_key, STATE_SET);
525 var record_warnings = manifold.query_store.get_record_state(query_uuid, record_key, STATE_WARNINGS);
527 is_reserved = (record_state == STATE_SET_IN)
528 || (record_state == STATE_SET_OUT_PENDING)
529 || (record_state == STATE_SET_IN_SUCCESS)
530 || (record_state == STATE_SET_OUT_FAILURE);
532 is_pending = (record_state == STATE_SET_IN_PENDING)
533 || (record_state == STATE_SET_OUT_PENDING);
535 in_set = (record_state == STATE_SET_IN) // should not have warnings
536 || (record_state == STATE_SET_IN_PENDING)
537 || (record_state == STATE_SET_IN_SUCCESS)
538 || (record_state == STATE_SET_OUT_FAILURE); // should not have warnings
540 is_unconfigured = (in_set && !$.isEmptyObject(record_warnings));
542 // We go through each filter and decide whether it affects the visibility of the record
543 $.each(filters, function(index, filter) {
546 var value = filter[2];
549 /* We do some special handling for the manifold:status filter
552 if (key == 'manifold:status') {
553 if (op != '=' && op != '==') {
554 // Unsupported filter, let's ignore it
555 console.log("Unsupported filter on manifold:status. Should be EQUAL only.");
556 return true; // ~ continue
561 // true => ~ continue
563 visible = is_reserved;
566 visible = is_unconfigured;
569 visible = is_pending;
572 return false; // ~ break
575 /* Normal filtering behaviour (according to the record content) follows... */
576 col_value = manifold.record_get_value(record, key);
578 // When the filter does not match, we hide the column by default
579 if (col_value === 'undefined') {
581 return false; // ~ break
584 // XXX This should accept pluggable filtering functions.
587 /* Test whether current filter is compatible with the column */
588 if (op == '=' || op == '==') {
589 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
591 }else if (op == 'included') {
592 $.each(value, function(i,x) {
595 return false; // ~ break
600 }else if (op == '!=') {
601 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
604 if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
607 if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
609 } else if(op=='<=' || op=='≤') {
610 if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
612 } else if(op=='>=' || op=='≥') {
613 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
616 // How to break out of a loop ?
617 alert("filter not supported");
618 return false; // break
623 // Set the visibility status in the query store
624 self.set_record_state(query_uuid, record_key, STATE_VISIBLE, visible);
627 var end = new Date().getTime();
628 console.log("APPLY FILTERS took", end - start, "ms");
635 * This namespace holds functions for globally managing query objects
640 /**************************************************************************
642 **************************************************************************/
646 get_type: function(variable) {
647 switch(Object.toType(variable)) {
654 if ((variable.length > 0) && (Object.toType(variable[0]) === 'object'))
655 return TYPE_LIST_OF_RECORDS;
657 return TYPE_LIST_OF_VALUES;
663 * fields: A String instance (field name), or a set of String instances
664 * (field names) # XXX tuple !!
666 * If fields is a String, return the corresponding value.
667 * If fields is a set, return a tuple of corresponding value.
670 * KeyError if at least one of the fields is not found
672 record_get_value: function(record, fields)
674 if (typeof(fields) === 'string') {
675 if (fields.indexOf('.') != -1) {
676 key_subkey = key.split('.', 2);
678 subkey = key_subkey[1];
680 if (record.indexOf(key) == -1) {
683 // Tests if the following is an array (typeof would give object)
684 if (Object.prototype.toString.call(record[key]) === '[object Array]') {
686 return $.map(record[key], function(subrecord) { return manifold.record_get_value(subrecord, subkey) });
687 } else if (typeof(record) == 'object') {
689 return manifold.record_get_value(record[key], subkey);
691 console.log('Unknown field');
694 return record[fields];
697 // see. get_map_entries
698 if (fields.length == 1)
699 return manifold.record_get_value(record, fields[0])
701 // Build a new record
703 $.each(fields, function(i, field) {
704 ret[field] = manifold.record_get_value(record, field);
706 ret.hashCode = record.hashCode;
707 ret.equals = record.equals;
709 // this was an array, we want a dictionary
710 //return $.map(fields, function(x) { manifold.record_get_value(record, x) });
715 record_hashcode: function(key_fields)
719 for (var i=0; i < key_fields.length; i++)
720 ret += "@@" + this[key_fields[i]];
725 _record_equals: function(self, other, key_fields)
727 for (var i=0; i < key_fields.length; i++) {
728 var this_value = self[key_fields[i]];
729 var other_value = other[key_fields[i]];
731 var this_type = manifold.get_type(this_value);
732 var other_type = manifold.get_type(other_value);
733 if (this_type != other_type)
738 case TYPE_LIST_OF_VALUES:
739 if (this_value != other_value)
743 if (!(_record_equals(this_value, other_value, key_fields)))
746 case TYPE_LIST_OF_RECORDS:
747 if (this_value.length != other_value.length)
749 for (var j = 0; j < this_value.length; j++)
750 if (!(_record_equals(this_value[j], other_value[j], key_fields)))
758 record_equals: function(key_fields)
760 return function(other) {
761 return manifold._record_equals(this, other, key_fields);
765 _in_array: function(element, array, key_fields)
767 if (key_fields.length > 1) {
768 for (var i = 0; i < array.length; i++) {
769 if (manifold._record_equals(element, array[i], key_fields))
774 // XXX TODO If we have a dict, extract the key first
775 return ($.inArray(element, array) != -1);
779 /**************************************************************************
780 * Metadata management
781 **************************************************************************/
785 get_table: function(method) {
786 var table = MANIFOLD_METADATA[method];
787 return (typeof table === 'undefined') ? null : table;
790 get_columns: function(method) {
791 var table = this.get_table(method);
796 return (typeof table.column === 'undefined') ? null : table.column;
799 get_field_names: function(method)
801 var columns = this.get_columns(method);
804 return $.map(columns, function (x) { return x.name });
807 get_key: function(method) {
808 var table = this.get_table(method);
812 return (typeof table.key === 'undefined') ? null : table.key;
816 get_column: function(method, name) {
817 var columns = this.get_columns(method);
821 $.each(columns, function(i, c) {
828 get_type: function(method, name) {
829 var table = this.get_table(method);
833 var match = $.grep(table.column, function(x) { return x.name == name });
834 if (match.length == 0) {
837 return match[0].type;
839 return (typeof table.type === 'undefined') ? null : table.type;
844 /**************************************************************************
846 **************************************************************************/
848 query_store: new QueryStore(),
850 // XXX Remaining functions are deprecated since they are replaced by the query store
853 * Associative array storing the set of queries active on the page
859 * Insert a query in the global hash table associating uuids to queries.
860 * If the query has no been analyzed yet, let's do it.
861 * \fn insert_query(query)
863 * \param ManifoldQuery query Query to be added
865 insert_query : function (query) {
867 manifold.query_store.insert(query);
870 $(document).ready(function() {
871 manifold.run_query(query);
875 if (query.analyzed_query == null) {
876 query.analyze_subqueries();
878 manifold.all_queries[query.query_uuid]=query;
882 * Returns the query associated to a UUID
883 * \fn find_query(query_uuid)
885 * \param string query_uuid The UUID of the query to be returned
887 find_query : function (query_uuid) {
888 return manifold.all_queries[query_uuid];
891 /**************************************************************************
893 **************************************************************************/
895 // trigger a query asynchroneously
896 proxy_url : '/manifold/proxy/json/',
898 // reasonably low-noise, shows manifold requests coming in and out
899 asynchroneous_debug : true,
900 // print our more details on result publication and related callbacks
901 pubsub_debug : false,
904 * \brief We use js function closure to be able to pass the query (array)
905 * to the callback function used when data is received
907 success_closure: function(query, publish_uuid, callback) {
908 return function(data, textStatus) {
909 manifold.asynchroneous_success(data, query, publish_uuid, callback);
913 run_query: function(query, callback)
915 // default value for callback = null
916 if (typeof callback === 'undefined')
919 var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
920 query_ext.query_state = QUERY_STATE_INPROGRESS;
922 var query_json = JSON.stringify(query);
924 // Inform plugins about the progress
925 query.iter_subqueries(function (sq) {
926 var sq_query_ext = manifold.query_store.find_analyzed_query_ext(sq.query_uuid);
927 sq_query_ext.query_state = QUERY_STATE_INPROGRESS;
929 manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
933 $.post(manifold.proxy_url, {'json': query_json} , manifold.success_closure(query, null, callback));
937 // Executes all async. queries - intended for the javascript header to initialize queries
938 // input queries are specified as a list of {'query_uuid': <query_uuid> }
939 // each plugin is responsible for managing its spinner through on_query_in_progress
940 asynchroneous_exec : function (query_exec_tuples) {
942 // Loop through input array, and use publish_uuid to publish back results
943 $.each(query_exec_tuples, function(index, tuple) {
944 var query=manifold.find_query(tuple.query_uuid);
945 var query_json=JSON.stringify (query);
946 var publish_uuid=tuple.publish_uuid;
947 // by default we publish using the same uuid of course
948 if (publish_uuid==undefined) publish_uuid=query.query_uuid;
949 if (manifold.pubsub_debug) {
950 messages.debug("sending POST on " + manifold.proxy_url + query.__repr());
953 query.iter_subqueries(function (sq) {
954 manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
957 // not quite sure what happens if we send a string directly, as POST data is named..
958 // this gets reconstructed on the proxy side with ManifoldQuery.fill_from_POST
959 $.post(manifold.proxy_url, {'json':query_json},
960 manifold.success_closure(query, publish_uuid, tuple.callback));
965 * \brief Forward a query to the manifold backend
966 * \param query (dict) the query to be executed asynchronously
967 * \param callback (function) the function to be called when the query terminates
969 forward: function(query, callback) {
970 var query_json = JSON.stringify(query);
971 $.post(manifold.proxy_url, {'json': query_json} ,
972 manifold.success_closure(query, query.query_uuid, callback));
976 * Returns whether a query expects a unique results.
977 * This is the case when the filters contain a key of the object
978 * \fn query_expects_unique_result(query)
980 * \param ManifoldQuery query Query for which we are testing whether it expects a unique result
982 query_expects_unique_result: function(query) {
983 /* XXX we need functions to query metadata */
984 //var keys = MANIFOLD_METADATA[query.object]['keys']; /* array of array of field names */
985 /* TODO requires keys in metadata */
991 * \fn publish_result(query, results)
993 * \param ManifoldQuery query Query which has received results
994 * \param array results results corresponding to query
996 publish_result: function(query, result) {
997 if (typeof result === 'undefined')
1001 manifold.raise_record_event(query.query_uuid, CLEAR_RECORDS);
1002 if (manifold.pubsub_debug)
1003 messages.debug(".. publish_result (1) ");
1005 $.each(result, function(i, record) {
1006 manifold.raise_record_event(query.query_uuid, NEW_RECORD, record);
1009 if (manifold.pubsub_debug)
1010 messages.debug(".. publish_result (2) has used NEW API on " + count + " records");
1011 manifold.raise_record_event(query.query_uuid, DONE);
1012 if (manifold.pubsub_debug)
1013 messages.debug(".. publish_result (3) has used NEW API to say DONE");
1015 // OLD PLUGIN API BELOW
1016 /* Publish an update announce */
1017 var channel="/results/" + query.query_uuid + "/changed";
1018 if (manifold.pubsub_debug)
1019 messages.debug(".. publish_result (4) OLD API on channel" + channel);
1021 $.publish(channel, [result, query]);
1023 if (manifold.pubsub_debug)
1024 messages.debug(".. publish_result (5) END q=" + query.__repr());
1027 store_records: function(query, records) {
1029 var query_ext = manifold.query_store.find_analyzed_query_ext(query.query_uuid);
1030 if (query_ext.set_query_ext) {
1031 // We have a domain query
1032 // The results are stored in the corresponding set_query
1033 manifold.query_store.set_records(query_ext.set_query_ext.query.query_uuid, records);
1035 } else if (query_ext.domain_query_ext) {
1036 // We have a set query, it is only used to determine which objects are in the set, we should only retrieve the key
1037 // Has it a domain query, and has it completed ?
1038 $.each(records, function(i, record) {
1039 var key = manifold.metadata.get_key(query.object);
1040 var record_key = manifold.record_get_value(record, key);
1041 manifold.query_store.set_record_state(query.query_uuid, record_key, STATE_SET, STATE_SET_IN);
1045 // We have a normal query
1046 manifold.query_store.set_records(query.query_uuid, records, STATE_SET_IN);
1051 * Recursively publish result
1052 * \fn publish_result_rec(query, result)
1053 * \memberof Manifold
1054 * \param ManifoldQuery query Query which has received result
1055 * \param array result result corresponding to query
1057 * Note: this function works on the analyzed query
1059 publish_result_rec: function(query, records) {
1060 /* If the result is not unique, only publish the top query;
1061 * otherwise, publish the main object as well as subqueries
1062 * XXX how much recursive are we ?
1064 if (manifold.pubsub_debug)
1065 messages.debug (">>>>> publish_result_rec " + query.object);
1066 if (manifold.query_expects_unique_result(query)) {
1067 /* Also publish subqueries */
1068 $.each(query.subqueries, function(object, subquery) {
1069 manifold.publish_result_rec(subquery, records[0][object]);
1070 /* TODO remove object from result */
1073 if (manifold.pubsub_debug)
1074 messages.debug ("===== publish_result_rec " + query.object);
1076 var query_ext = manifold.query_store.find_analyzed_query_ext(query.query_uuid);
1077 query_ext.query_state = QUERY_STATE_DONE;
1079 this.store_records(query, records);
1083 if (query_ext.set_query_ext) {
1084 if (query_ext.set_query_ext.query_state != QUERY_STATE_DONE)
1086 pub_query = query_ext.set_query_ext.query;
1087 } else if (query_ext.domain_query_ext) {
1088 if (query_ext.domain_query_ext.query_state != QUERY_STATE_DONE)
1094 // We can only publish results if the query (and its related domain query) is complete
1095 manifold.publish_result(pub_query, records);
1097 if (manifold.pubsub_debug)
1098 messages.debug ("<<<<< publish_result_rec " + query.object);
1101 setup_update_query: function(query, records)
1103 // We don't prepare an update query if the result has more than 1 entry
1104 if (records.length != 1)
1106 var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
1108 var record = records[0];
1110 var update_query_ext = query_ext.update_query_ext;
1112 if (!update_query_ext)
1115 var update_query = update_query_ext.query;
1116 var update_query_ext = query_ext.update_query_ext;
1117 var update_query_orig = query_ext.update_query_orig_ext.query;
1119 // Testing whether the result has subqueries (one level deep only)
1120 // iif the query has subqueries
1122 var obj = query.analyzed_query.subqueries;
1123 for (method in obj) {
1124 if (obj.hasOwnProperty(method)) {
1125 var key = manifold.metadata.get_key(method);
1129 var subrecords = record[method];
1132 $.each(subrecords, function (i, subrecord) {
1133 sq_keys.push(manifold.record_get_value(subrecord, key));
1135 update_query.params[method] = sq_keys;
1136 update_query_orig.params[method] = sq_keys.slice();
1142 update_query_ext.disabled = false;
1143 update_query_orig_ext.disabled = false;
1147 process_get_query_records: function(query, records) {
1148 this.setup_update_query(query, records);
1150 var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
1151 query_ext.query_state = QUERY_STATE_DONE;
1153 /* Publish full results */
1154 var tmp_query = manifold.query_store.find_analyzed_query(query.query_uuid);
1155 manifold.publish_result_rec(tmp_query, records);
1158 make_records: function(object, records)
1160 $.each(records, function(i, record) {
1161 manifold.make_record(object, record);
1165 make_record: function(object, record)
1167 // To make an object a record, we just add the hash function
1168 var key = manifold.metadata.get_key(object);
1169 record.hashCode = manifold.record_hashcode(key.sort());
1170 record.equals = manifold.record_equals(key);
1172 // Looking after subrecords
1173 for (var field in record) {
1174 var result_value = record[field];
1176 switch (this.get_type(result_value)) {
1178 var subobject = manifold.metadata.get_type(object, field);
1179 // if (subobject) XXX Bugs with fields declared string while they are not : network.version is a dict in fact
1180 if (subobject && subobject != 'string')
1181 manifold.make_record(subobject, result_value);
1183 case TYPE_LIST_OF_RECORDS:
1184 var subobject = manifold.metadata.get_type(object, field);
1186 manifold.make_records(subobject, result_value);
1194 * What we need to do when receiving results from an update query:
1195 * - differences between what we had, what we requested, and what we obtained
1196 * . what we had : update_query_orig (simple fields and set fields managed differently)
1197 * . what we requested : update_query
1198 * . what we received : records
1199 * - raise appropriate events
1201 * The normal process is that results similar to Get will be pushed in the
1202 * pubsub mechanism, thus repopulating everything while we only need
1203 * diff's. This means we need to move the publish functionalities in the
1204 * previous 'process_get_query_records' function.
1206 process_update_query_records: function(query, records) {
1207 // First issue: we request everything, and not only what we modify, so will will have to ignore some fields
1208 var query_uuid = query.query_uuid;
1209 var query_ext = manifold.query_store.find_analyzed_query_ext(query_uuid);
1210 var update_query = query_ext.main_query_ext.update_query_ext.query;
1211 var update_query_orig = query_ext.main_query_ext.update_query_orig_ext.query;
1213 // Since we update objects one at a time, we can get the first record
1214 var record = records[0];
1216 // Let's iterate over the object properties
1217 for (var field in record) {
1218 var result_value = record[field];
1219 switch (this.get_type(result_value)) {
1221 // Did we ask for a change ?
1222 var update_value = update_query[field];
1224 // Not requested, if it has changed: OUT OF SYNC
1225 // How we can know ?
1226 // We assume it won't have changed
1230 throw "Internal error";
1236 value : (update_value == result_value) ? STATE_VALUE_CHANGE_SUCCESS : STATE_VALUE_CHANGE_FAILURE,
1238 manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1242 throw "Not implemented";
1246 case TYPE_LIST_OF_VALUES:
1247 // Same as list of records, but we don't have to extract keys
1249 // The rest of exactly the same (XXX factorize)
1250 var update_keys = update_query_orig.params[field];
1251 var query_keys = update_query.params[field];
1252 var added_keys = $.grep(query_keys, function (x) { return $.inArray(x, update_keys) == -1 });
1253 var removed_keys = $.grep(update_keys, function (x) { return $.inArray(x, query_keys) == -1 });
1256 $.each(added_keys, function(i, key) {
1257 if ($.inArray(key, result_value) == -1) {
1259 request: FIELD_REQUEST_ADD,
1262 status: FIELD_REQUEST_FAILURE,
1266 request: FIELD_REQUEST_ADD,
1269 status: FIELD_REQUEST_SUCCESS,
1272 manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1274 $.each(removed_keys, function(i, key) {
1275 if ($.inArray(key, result_keys) == -1) {
1277 request: FIELD_REQUEST_REMOVE,
1280 status: FIELD_REQUEST_SUCCESS,
1284 request: FIELD_REQUEST_REMOVE,
1287 status: FIELD_REQUEST_FAILURE,
1290 manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1296 case TYPE_LIST_OF_VALUES: // XXX Until fixed
1297 case TYPE_LIST_OF_RECORDS:
1298 var new_state,cur_query_uuid;
1300 cur_query_uuid = query.analyzed_query.subqueries[field].query_uuid;
1302 // example: slice.resource
1303 // - update_query_orig.params.resource = resources in slice before update
1304 // - update_query.params.resource = resource requested in slice
1305 // - keys from field = resources obtained
1306 var key = manifold.metadata.get_key(field);
1310 if (key.length > 1) {
1311 throw "Not implemented";
1317 /* XXX should be modified for multiple keys */
1318 var result_keys = $.map(record[field], function(x) { return manifold.record_get_value(x, key); });
1320 // XXX All this could be deduced from record state : STATE_IN_PENDING and STATE_OUT_PENDING
1321 // what we had at the begining
1322 var update_keys = update_query_orig.params[field];
1324 var query_keys = update_query.params[field];
1325 // what we added and removed
1326 var added_keys = $.grep(query_keys, function (x) { return (!(manifold._in_array(x, update_keys, key))); });
1327 var removed_keys = $.grep(update_keys, function (x) { return (!(manifold._in_array(x, query_keys, key))); });
1329 // Send events related to parent query
1330 $.each(added_keys, function(i, added_key) {
1331 new_state = (manifold._in_array(added_key, result_keys, key)) ? STATE_SET_IN_SUCCESS : STATE_SET_IN_FAILURE;
1333 // Update record state for children queries
1334 manifold.query_store.set_record_state(cur_query_uuid, added_key, STATE_SET, new_state);
1336 // XXX This could be optimized
1337 manifold.query_store.recount(cur_query_uuid);
1339 data = { state: STATE_SET, key : field, op : new_state, value: added_key }
1340 manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1342 // Inform subquery also
1344 manifold.raise_record_event(cur_query_uuid, FIELD_STATE_CHANGED, data);
1345 // XXX Passing no parameters so that they can redraw everything would
1346 // be more efficient but is currently not supported
1347 // XXX We could also need to inform plugins about nodes IN (not pending) that are no more, etc.
1348 // XXX refactor all this when suppressing update_queries, and relying on state instead !
1350 $.each(removed_keys, function(i, removed_key) {
1351 new_state = (manifold._in_array(removed_key, result_keys, key)) ? STATE_SET_OUT_FAILURE : STATE_SET_OUT_SUCCESS;
1353 // Update record state for children queries
1354 manifold.query_store.set_record_state(cur_query_uuid, removed_key, STATE_SET, new_state);
1356 // XXX This could be optimized
1357 manifold.query_store.recount(cur_query_uuid);
1359 data = { state: STATE_SET, key : field, op : new_state, value: removed_key }
1360 manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1362 // Inform subquery also
1364 manifold.raise_record_event(cur_query_uuid, FIELD_STATE_CHANGED, data);
1371 // XXX Now we need to adapt 'update' and 'update_orig' queries as if we had done a get
1372 this.setup_update_query(query, records);
1374 var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
1375 query_ext.query_state = QUERY_STATE_DONE;
1378 // Send DONE message to plugins
1379 query.iter_subqueries(function(sq, data, parent_query) {
1380 manifold.raise_record_event(sq.query_uuid, DONE);
1385 process_query_records: function(query, records) {
1386 if (query.action == 'get') {
1387 this.process_get_query_records(query, records);
1388 } else if (query.action == 'update') {
1389 this.process_update_query_records(query, records);
1393 // if set callback is provided it is called
1394 // most of the time publish_uuid will be query.query_uuid
1395 // however in some cases we wish to publish the result under a different uuid
1396 // e.g. an updater wants to publish its result as if from the original (get) query
1397 asynchroneous_success : function (data, query, publish_uuid, callback) {
1398 // xxx should have a nicer declaration of that enum in sync with the python code somehow
1400 var start = new Date();
1401 if (manifold.asynchroneous_debug)
1402 messages.debug(">>>>>>>>>> asynchroneous_success query.object=" + query.object);
1404 if (data.code == 2) { // ERROR
1405 // We need to make sense of error codes here
1406 alert("Your session has expired, please log in again");
1407 localStorage.removeItem('user');
1408 window.location="/logout/";
1409 if (manifold.asynchroneous_debug) {
1410 duration=new Date()-start;
1411 messages.debug ("<<<<<<<<<< asynchroneous_success " + query.object + " -- error returned - logging out " + duration + " ms");
1415 if (data.code == 1) { // WARNING
1416 messages.error("Some errors have been received from the manifold backend at " + MANIFOLD_URL + " [" + data.description + "]");
1417 // publish error code and text message on a separate channel for whoever is interested
1419 $.publish("/results/" + publish_uuid + "/failed", [data.code, data.description] );
1423 // If a callback has been specified, we redirect results to it
1426 if (manifold.asynchroneous_debug) {
1427 duration=new Date()-start;
1428 messages.debug ("<<<<<<<<<< asynchroneous_success " + query.object + " -- callback ended " + duration + " ms");
1433 if (manifold.asynchroneous_debug)
1434 messages.debug ("========== asynchroneous_success " + query.object + " -- before process_query_records [" + query.query_uuid +"]");
1436 // once everything is checked we can use the 'value' part of the manifoldresult
1437 var result=data.value;
1439 /* Eventually update the content of related queries (update, etc) */
1440 manifold.make_records(query.object, result);
1441 this.process_query_records(query, result);
1443 /* Publish results: disabled here, done in the previous call */
1444 //tmp_query = manifold.find_query(query.query_uuid);
1445 //manifold.publish_result_rec(tmp_query.analyzed_query, result);
1447 if (manifold.asynchroneous_debug) {
1448 duration=new Date()-start;
1449 messages.debug ("<<<<<<<<<< asynchroneous_success " + query.object + " -- done " + duration + " ms");
1454 /**************************************************************************
1455 * Plugin API helpers
1456 **************************************************************************/
1458 raise_event_handler: function(type, query_uuid, event_type, value) {
1459 if (manifold.pubsub_debug)
1460 messages.debug("raise_event_handler, quuid="+query_uuid+" type="+type+" event_type="+event_type);
1461 if ((type != 'query') && (type != 'record'))
1462 throw 'Incorrect type for manifold.raise_event()';
1463 // xxx we observe quite a lot of incoming calls with an undefined query_uuid
1464 // this should be fixed upstream in manifold I expect
1465 if (query_uuid === undefined) {
1466 messages.warning("undefined query in raise_event_handler");
1470 // notify the change to objects that either listen to this channel specifically,
1471 // or to the wildcard channel
1472 var channels = [ manifold.get_channel(type, query_uuid), manifold.get_channel(type, '*') ];
1474 $.each(channels, function(i, channel) {
1475 if (value === undefined) {
1476 if (manifold.pubsub_debug) messages.debug("triggering [no value] on channel="+channel+" and event_type="+event_type);
1477 $('.pubsub').trigger(channel, [event_type]);
1479 if (manifold.pubsub_debug) messages.debug("triggering [value="+value+"] on channel="+channel+" and event_type="+event_type);
1480 $('.pubsub').trigger(channel, [event_type, value]);
1485 raise_query_event: function(query_uuid, event_type, value) {
1486 manifold.raise_event_handler('query', query_uuid, event_type, value);
1489 raise_record_event: function(query_uuid, event_type, value) {
1490 manifold.raise_event_handler('record', query_uuid, event_type, value);
1494 * Event handler helpers
1496 _get_next_state_add: function(prev_state)
1498 switch (prev_state) {
1500 case STATE_SET_OUT_SUCCESS:
1501 case STATE_SET_IN_FAILURE:
1502 new_state = STATE_SET_IN_PENDING;
1505 case STATE_SET_OUT_PENDING:
1506 new_state = STATE_SET_IN;
1510 case STATE_SET_IN_PENDING:
1511 case STATE_SET_IN_SUCCESS:
1512 case STATE_SET_OUT_FAILURE:
1513 console.log("Inconsistent state: already in");
1519 _get_next_state_remove: function(prev_state)
1521 switch (prev_state) {
1523 case STATE_SET_IN_SUCCESS:
1524 case STATE_SET_OUT_FAILURE:
1525 new_state = STATE_SET_OUT_PENDING;
1528 case STATE_SET_IN_PENDING:
1529 new_state = STATE_SET_OUT;
1533 case STATE_SET_OUT_PENDING:
1534 case STATE_SET_OUT_SUCCESS:
1535 case STATE_SET_IN_FAILURE:
1536 console.log("Inconsistent state: already out");
1542 _grep_active_lease_callback: function(lease_query, resource_key) {
1543 return function(lease_key_lease) {
1544 var state, lease_key, lease;
1546 lease_key = lease_key_lease[0];
1547 lease = lease_key_lease[1];
1549 if (lease['resource'] != resource_key)
1552 state = manifold.query_store.get_record_state(lease_query.query_uuid, lease_key, STATE_SET);;
1555 case STATE_SET_IN_PENDING:
1556 case STATE_SET_IN_SUCCESS:
1557 case STATE_SET_OUT_FAILURE:
1560 case STATE_SET_OUT_PENDING:
1561 case STATE_SET_OUT_SUCCESS:
1562 case STATE_SET_IN_FAILURE:
1568 _enforce_constraints: function(query_ext, record, record_key, event_type)
1572 query = query_ext.query;
1574 switch(query.object) {
1577 // CONSTRAINT_RESERVABLE_LEASE
1579 // +) If a reservable node is added to the slice, then it should have a corresponding lease
1580 // XXX Not always a resource
1581 var is_reservable = (record.exclusive == true);
1582 if (is_reservable) {
1583 var warnings = manifold.query_store.get_record_state(query.query_uuid, record_key, STATE_WARNINGS);
1585 if (event_type == STATE_SET_ADD) {
1586 // We should have a lease_query associated
1587 var lease_query = query_ext.parent_query_ext.query.subqueries['lease']; // in options
1588 var lease_query_ext = manifold.query_store.find_analyzed_query_ext(lease_query.query_uuid);
1589 // Do we have lease records (in) with this resource
1590 var lease_records = $.grep(lease_query_ext.records.entries(), this._grep_active_lease_callback(lease_query, record_key));
1591 if (lease_records.length == 0) {
1593 // XXX Need for a better function to manage warnings
1594 var warn = CONSTRAINT_RESERVABLE_LEASE_MSG;
1595 warnings[CONSTRAINT_RESERVABLE_LEASE] = warn;
1597 // Lease are defined, delete the warning in case it was set previously
1598 delete warnings[CONSTRAINT_RESERVABLE_LEASE];
1601 // Remove warnings attached to this resource
1602 delete warnings[CONSTRAINT_RESERVABLE_LEASE];
1605 manifold.query_store.set_record_state(query.query_uuid, record_key, STATE_WARNINGS, warnings);
1608 /* This was redundant */
1609 // manifold.query_store.recount(query.query_uuid);
1611 // Signal the change to plugins (even if the constraint does not apply, so that the plugin can display a checkmark)
1613 state: STATE_WARNINGS,
1618 manifold.raise_record_event(query.query_uuid, FIELD_STATE_CHANGED, data);
1622 var resource_key = record_key.resource;
1623 var resource_query = query_ext.parent_query_ext.query.subqueries['resource'];
1624 var warnings = manifold.query_store.get_record_state(resource_query.query_uuid, resource_key, STATE_WARNINGS);
1626 if (event_type == STATE_SET_ADD) {
1627 // A lease is added, it removes the constraint
1628 delete warnings[CONSTRAINT_RESERVABLE_LEASE];
1630 // A lease is removed, it might trigger the warning
1631 var lease_records = $.grep(query_ext.records.entries(), this._grep_active_lease_callback(query, resource_key));
1632 if (lease_records.length == 0) { // XXX redundant cases
1634 // XXX Need for a better function to manage warnings
1635 var warn = CONSTRAINT_RESERVABLE_LEASE_MSG;
1636 warnings[CONSTRAINT_RESERVABLE_LEASE] = warn;
1638 // Lease are defined, delete the warning in case it was set previously
1639 delete warnings[CONSTRAINT_RESERVABLE_LEASE];
1644 manifold.query_store.recount(resource_query.query_uuid);
1646 // Signal the change to plugins (even if the constraint does not apply, so that the plugin can display a checkmark)
1648 state: STATE_WARNINGS,
1653 manifold.raise_record_event(resource_query.query_uuid, FIELD_STATE_CHANGED, data);
1657 // -) When a lease is added, it might remove the warning associated to a reservable node
1659 // If a NITOS node is reserved, then at least a NITOS channel should be reserved
1660 // - When a NITOS channel is added, it might remove a warning associated to all NITOS nodes
1662 // If a NITOS channel is reserved, then at least a NITOS node should be reserved
1663 // - When a NITOS node is added, it might remove a warning associated to all NITOS channels
1665 // A lease is present while the resource has been removed => Require warnings on nodes not in set !
1669 _get_query_path: function(query_ext) {
1672 while (sq.parent_query_ext) {
1675 path = sq.query.object + path;
1676 sq = sq.parent_query_ext;
1683 * Handling events raised by plugins
1685 raise_event: function(query_uuid, event_type, data)
1687 var query, query_ext;
1689 // Query uuid has been updated with the key of a new element
1690 query_ext = manifold.query_store.find_analyzed_query_ext(query_uuid);
1691 query = query_ext.query;
1693 switch(event_type) {
1695 // XXX At some point, should be renamed to RECORD_STATE_CHANGED
1696 case FIELD_STATE_CHANGED:
1698 // value is an object (request, key, value, status)
1699 // update is only possible is the query is not pending, etc
1700 // SET_ADD is on a subquery, FIELD_STATE_CHANGED on the query itself
1701 // we should map SET_ADD on this...
1703 // 1. Update internal query store about the change in status
1705 // 2. Update the update query
1706 update_query = query_ext.main_query_ext.update_query_ext.query;
1707 update_query_orig = query_ext.main_query_ext.update_query_orig_ext.query;
1709 switch(data.state) {
1714 /* Set parameter data.key in the update_query to VALUE */
1715 if (update_query.params[data.key] === undefined)
1716 update_query.params[data.key] = Array();
1717 update_query.params[data.key] = value.value;
1724 var prev_state, new_state;
1725 var main_query, record, new_data, path;
1727 // We only track state in the analyzed query
1728 prev_state = manifold.query_store.get_record_state(query_uuid, data.value, STATE_SET);
1729 if (prev_state === null)
1730 prev_state = STATE_SET_OUT;
1734 new_state = this._get_next_state_add(prev_state);
1736 /* data.value containts the resource key */
1737 manifold.query_store.add_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_ADD);
1741 /* Process update query in parent */
1742 path = this._get_query_path(query_ext);
1743 if (update_query.params[path] === undefined)
1744 update_query.params[path] = Array();
1745 update_query.params[path].push(data.value);
1749 case STATE_SET_REMOVE:
1750 new_state = this._get_next_state_remove(prev_state);
1752 /* data.value contains the resource key */
1753 manifold.query_store.remove_record(query_uuid, data.value, new_state);
1754 record = manifold.query_store.get_record(query_uuid, data.value);
1755 this._enforce_constraints(query_ext, record, data.value, STATE_SET_REMOVE);
1757 /* Process update query in parent */
1758 path = this._get_query_path(query_ext);
1759 arr = update_query.params[path];
1761 var key = manifold.metadata.get_key(query.object);
1762 arr = $.grep(arr, function(x) { return (!(manifold._record_equals(x, data.value, key))); });
1763 if (update_query.params[path] === undefined)
1764 update_query.params[path] = Array();
1765 update_query.params[path] = arr;
1769 /* Inform the parent query: important for update */
1776 main_query = query_ext.main_query_ext.query;
1777 manifold.raise_record_event(main_query.query_uuid, event_type, new_data);
1778 /* Propagate the event to other plugins subscribed to the query */
1779 manifold.query_store.recount(query_uuid);
1781 manifold.raise_record_event(query_uuid, event_type, new_data);
1786 // 3. Inform others about the change
1787 // a) the main query...
1788 manifold.raise_record_event(query_uuid, event_type, data);
1790 // b) subqueries eventually (dot in the key)
1793 var cur_query = query;
1794 if (cur_query.analyzed_query)
1795 cur_query = cur_query.analyzed_query;
1798 var path_array = data.key.split('.');
1799 var value_key = data.key.split('.');
1800 $.each(path_array, function(i, method) {
1801 cur_query = cur_query.subqueries[method];
1802 value_key.shift(); // XXX check that method is indeed shifted
1804 data.key = value_key;
1806 manifold.raise_record_event(cur_query.query_uuid, event_type, data);
1812 manifold.run_query(query_ext.main_query_ext.update_query_ext.query);
1815 /* QUERY STATE CHANGED */
1820 /* Update internal record state */
1821 manifold.query_store.add_filter(query_uuid, data);
1823 /* Propagate the message to plugins */
1824 manifold.raise_query_event(query_uuid, event_type, data);
1828 case FILTER_REMOVED:
1829 /* Update internal record state */
1830 manifold.query_store.remove_filter(query_uuid, data);
1832 /* Propagate the message to plugins */
1833 manifold.raise_query_event(query_uuid, event_type, data);
1838 main_query = query_ext.main_query_ext.query;
1839 main_update_query = query_ext.main_query_ext.update_query;
1842 // Here we need the full path through all subqueries
1844 // XXX We might need the query name in the QueryExt structure
1845 main_query.select(data);
1847 // XXX When is an update query associated ?
1848 // XXX main_update_query.select(value);
1850 manifold.raise_query_event(query_uuid, event_type, data);
1854 query = query_ext.query;
1855 main_query = query_ext.main_query_ext.query;
1856 main_update_query = query_ext.main_query_ext.update_query;
1857 query.unselect(data);
1858 main_query.unselect(data);
1860 // We need to inform about changes in these queries to the respective plugins
1861 // Note: query & main_query have the same UUID
1862 manifold.raise_query_event(query_uuid, event_type, data);
1865 // We need to inform about changes in these queries to the respective plugins
1866 // Note: query, main_query & update_query have the same UUID
1868 // http://trac.myslice.info/ticket/32
1869 // Avoid multiple calls to the same event
1870 //manifold.raise_query_event(query_uuid, event_type, value);
1872 // We are targeting the same object with get and update
1873 // The notion of query is bad, we should have a notion of destination, and issue queries on the destination
1874 // NOTE: Editing a subquery == editing a local view on the destination
1876 // XXX We might need to run the new query again and manage the plugins in the meantime with spinners...
1877 // For the time being, we will collect all columns during the first query
1880 /* Publish/subscribe channels for internal use */
1881 get_channel: function(type, query_uuid) {
1882 if ((type !== 'query') && (type != 'record'))
1884 return '/' + type + '/' + query_uuid;
1887 }; // manifold object
1888 /* ------------------------------------------------------------ */
1892 // OLD PLUGIN API: extend jQuery/$ with pubsub capabilities
1893 // https://gist.github.com/661855
1895 $.subscribe = function( channel, selector, data, fn) {
1896 /* borrowed from jQuery */
1897 if ( data == null && fn == null ) {
1900 data = selector = undefined;
1901 } else if ( fn == null ) {
1902 if ( typeof selector === "string" ) {
1903 // ( channel, selector, fn )
1907 // ( channel, data, fn )
1910 selector = undefined;
1915 /* We use an indirection function that will clone the object passed in
1916 * parameter to the subscribe callback
1918 * FIXME currently we only clone query objects which are the only ones
1919 * supported and editable, we might have the same issue with results but
1920 * the page load time will be severely affected...
1922 o.on.apply(o, [channel, selector, data, function() {
1923 for(i = 1; i < arguments.length; i++) {
1924 if ( arguments[i].constructor.name == 'ManifoldQuery' )
1925 arguments[i] = arguments[i].clone();
1927 fn.apply(o, arguments);
1931 $.unsubscribe = function() {
1932 o.off.apply(o, arguments);
1935 $.publish = function() {
1936 o.trigger.apply(o, arguments);
1941 /* ------------------------------------------------------------ */
1943 //http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request
1944 //make sure to expose csrf in our outcoming ajax/post requests
1946 beforeSend: function(xhr, settings) {
1947 function getCookie(name) {
1948 var cookieValue = null;
1949 if (document.cookie && document.cookie != '') {
1950 var cookies = document.cookie.split(';');
1951 for (var i = 0; i < cookies.length; i++) {
1952 var cookie = jQuery.trim(cookies[i]);
1953 // Does this cookie string begin with the name we want?
1954 if (cookie.substring(0, name.length + 1) == (name + '=')) {
1955 cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
1962 if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
1963 // Only send the token to relative URLs i.e. locally.
1964 xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));