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.del_state = function(query_uuid, record_key)
356 var query_ext = this.find_analyzed_query_ext(query_uuid);
357 return query_ext.state.remove(record_key);
360 this.add_record = function(query_uuid, record, new_state)
362 var query_ext, key, record_key;
363 query_ext = this.find_analyzed_query_ext(query_uuid);
365 if (typeof(record) == 'object') {
366 key = manifold.metadata.get_key(query_ext.query.object);
367 record_key = manifold.record_get_value(record, key);
372 var record_entry = query_ext.records.get(record_key);
374 query_ext.records.put(record_key, record);
376 manifold.query_store.set_record_state(query_uuid, record_key, STATE_SET, new_state);
379 this.remove_record = function(query_uuid, record, new_state)
381 var query_ext, key, record_key;
382 query_ext = this.find_analyzed_query_ext(query_uuid);
384 if (typeof(record) == 'object') {
385 key = manifold.metadata.get_key(query_ext.query.object);
386 record_key = manifold.record_get_value(record, key);
391 if ((query_ext.query.object == 'lease') && (new_state == STATE_SET_OUT)) {
392 // Leases that are marked out are in fact leases from other slices
393 // We need to _remove_ leases that we mark as OUT
394 manifold.query_store.del_record(query_uuid, record_key);
395 manifold.query_store.del_state(query_uuid, record_key);
397 manifold.query_store.set_record_state(query_uuid, record_key, STATE_SET, new_state);
401 this.iter_records = function(query_uuid, callback)
403 var query_ext = this.find_analyzed_query_ext(query_uuid);
404 query_ext.records.each(callback);
405 //callback = function(record_key, record)
408 this.iter_visible_records = function(query_uuid, callback)
410 var query_ext = this.find_analyzed_query_ext(query_uuid);
411 query_ext.records.each(function(record_key, record) {
412 if (query_ext.state.get(record_key)[STATE_VISIBLE]) // .STATE_VISIBLE would be for the string key
413 callback(record_key, record);
415 //callback = function(record_key, record)
421 this.set_record_state = function(query_uuid, result_key, state, value)
423 var query_ext = this.find_analyzed_query_ext(query_uuid);
424 var state_dict = query_ext.state.get(result_key);
426 state_dict = this.state_dict_create();
428 state_dict[state] = value;
430 query_ext.state.put(result_key, state_dict);
433 this.get_record_state = function(query_uuid, result_key, state)
435 var query_ext = this.find_analyzed_query_ext(query_uuid);
436 var state_dict = query_ext.state.get(result_key);
439 return state_dict[state];
444 this.add_filter = function(query_uuid, filter)
446 var query_ext = this.find_analyzed_query_ext(query_uuid);
447 // XXX When we update a filter
448 query_ext.filters.push(filter);
450 this.apply_filters(query_uuid);
454 this.update_filter = function(query_uuid, filter)
458 this.apply_filters(query_uuid);
461 this.remove_filter = function(query_uuid, filter)
463 var query_ext = this.find_analyzed_query_ext(query_uuid);
464 query_ext.filters = $.grep(query_ext.filters, function(x) {
468 this.apply_filters(query_uuid);
471 this.get_filters = function(query_uuid)
473 var query_ext = this.find_analyzed_query_ext(query_uuid);
474 return query_ext.filters;
477 this.recount = function(query_uuid)
480 var is_reserved, is_pending, in_set, is_unconfigured;
482 query_ext = manifold.query_store.find_analyzed_query_ext(query_uuid);
483 query_ext.num_pending = 0;
484 query_ext.num_unconfigured = 0;
486 this.iter_records(query_uuid, function(record_key, record) {
487 var record_state = manifold.query_store.get_record_state(query_uuid, record_key, STATE_SET);
488 var record_warnings = manifold.query_store.get_record_state(query_uuid, record_key, STATE_WARNINGS);
490 is_reserved = (record_state == STATE_SET_IN)
491 || (record_state == STATE_SET_OUT_PENDING)
492 || (record_state == STATE_SET_IN_SUCCESS)
493 || (record_state == STATE_SET_OUT_FAILURE);
495 is_pending = (record_state == STATE_SET_IN_PENDING)
496 || (record_state == STATE_SET_OUT_PENDING);
498 in_set = (record_state == STATE_SET_IN) // should not have warnings
499 || (record_state == STATE_SET_IN_PENDING)
500 || (record_state == STATE_SET_IN_SUCCESS)
501 || (record_state == STATE_SET_OUT_FAILURE); // should not have warnings
503 is_unconfigured = (in_set && !$.isEmptyObject(record_warnings));
505 /* Let's update num_pending and num_unconfigured at this stage */
507 query_ext.num_pending++;
509 query_ext.num_unconfigured++;
514 this.apply_filters = function(query_uuid)
516 var start = new Date().getTime();
518 // Toggle visibility of records according to the different filters.
521 var filters = this.get_filters(query_uuid);
523 /* Let's update num_pending and num_unconfigured at this stage */
525 // Adapted from querytable._querytable_filter()
527 this.iter_records(query_uuid, function(record_key, record) {
528 var is_reserved, is_pending, in_set, is_unconfigured;
531 var record_state = manifold.query_store.get_record_state(query_uuid, record_key, STATE_SET);
532 var record_warnings = manifold.query_store.get_record_state(query_uuid, record_key, STATE_WARNINGS);
534 is_reserved = (record_state == STATE_SET_IN)
535 || (record_state == STATE_SET_OUT_PENDING)
536 || (record_state == STATE_SET_IN_SUCCESS)
537 || (record_state == STATE_SET_OUT_FAILURE);
539 is_pending = (record_state == STATE_SET_IN_PENDING)
540 || (record_state == STATE_SET_OUT_PENDING);
542 in_set = (record_state == STATE_SET_IN) // should not have warnings
543 || (record_state == STATE_SET_IN_PENDING)
544 || (record_state == STATE_SET_IN_SUCCESS)
545 || (record_state == STATE_SET_OUT_FAILURE); // should not have warnings
547 is_unconfigured = (in_set && !$.isEmptyObject(record_warnings));
549 // We go through each filter and decide whether it affects the visibility of the record
550 $.each(filters, function(index, filter) {
553 var value = filter[2];
556 /* We do some special handling for the manifold:status filter
559 if (key == 'manifold:status') {
560 if (op != '=' && op != '==') {
561 // Unsupported filter, let's ignore it
562 console.log("Unsupported filter on manifold:status. Should be EQUAL only.");
563 return true; // ~ continue
568 // true => ~ continue
570 visible = is_reserved;
573 visible = is_unconfigured;
576 visible = is_pending;
579 return false; // ~ break
582 /* Normal filtering behaviour (according to the record content) follows... */
583 col_value = manifold.record_get_value(record, key);
585 // When the filter does not match, we hide the column by default
586 if (col_value === 'undefined') {
588 return false; // ~ break
591 // XXX This should accept pluggable filtering functions.
594 /* Test whether current filter is compatible with the column */
595 if (op == '=' || op == '==') {
596 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
598 }else if (op == 'included') {
599 $.each(value, function(i,x) {
602 return false; // ~ break
607 }else if (op == '!=') {
608 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
611 if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
614 if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
616 } else if(op=='<=' || op=='≤') {
617 if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
619 } else if(op=='>=' || op=='≥') {
620 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
623 // How to break out of a loop ?
624 alert("filter not supported");
625 return false; // break
630 // Set the visibility status in the query store
631 self.set_record_state(query_uuid, record_key, STATE_VISIBLE, visible);
634 var end = new Date().getTime();
635 console.log("APPLY FILTERS took", end - start, "ms");
642 * This namespace holds functions for globally managing query objects
647 /**************************************************************************
649 **************************************************************************/
653 get_type: function(variable) {
654 switch(Object.toType(variable)) {
661 if ((variable.length > 0) && (Object.toType(variable[0]) === 'object'))
662 return TYPE_LIST_OF_RECORDS;
664 return TYPE_LIST_OF_VALUES;
670 * fields: A String instance (field name), or a set of String instances
671 * (field names) # XXX tuple !!
673 * If fields is a String, return the corresponding value.
674 * If fields is a set, return a tuple of corresponding value.
677 * KeyError if at least one of the fields is not found
679 record_get_value: function(record, fields)
681 if (typeof(fields) === 'string') {
682 if (fields.indexOf('.') != -1) {
683 key_subkey = key.split('.', 2);
685 subkey = key_subkey[1];
687 if (record.indexOf(key) == -1) {
690 // Tests if the following is an array (typeof would give object)
691 if (Object.prototype.toString.call(record[key]) === '[object Array]') {
693 return $.map(record[key], function(subrecord) { return manifold.record_get_value(subrecord, subkey) });
694 } else if (typeof(record) == 'object') {
696 return manifold.record_get_value(record[key], subkey);
698 console.log('Unknown field');
701 return record[fields];
704 // see. get_map_entries
705 if (fields.length == 1)
706 return manifold.record_get_value(record, fields[0])
708 // Build a new record
710 $.each(fields, function(i, field) {
711 ret[field] = manifold.record_get_value(record, field);
713 ret.hashCode = record.hashCode;
714 ret.equals = record.equals;
716 // this was an array, we want a dictionary
717 //return $.map(fields, function(x) { manifold.record_get_value(record, x) });
722 record_hashcode: function(key_fields)
726 for (var i=0; i < key_fields.length; i++)
727 ret += "@@" + this[key_fields[i]];
732 _record_equals: function(self, other, key_fields)
734 for (var i=0; i < key_fields.length; i++) {
735 var this_value = self[key_fields[i]];
736 var other_value = other[key_fields[i]];
738 var this_type = manifold.get_type(this_value);
739 var other_type = manifold.get_type(other_value);
740 if (this_type != other_type)
745 case TYPE_LIST_OF_VALUES:
746 if (this_value != other_value)
750 if (!(_record_equals(this_value, other_value, key_fields)))
753 case TYPE_LIST_OF_RECORDS:
754 if (this_value.length != other_value.length)
756 for (var j = 0; j < this_value.length; j++)
757 if (!(_record_equals(this_value[j], other_value[j], key_fields)))
765 record_equals: function(key_fields)
767 return function(other) {
768 return manifold._record_equals(this, other, key_fields);
772 _in_array: function(element, array, key_fields)
774 if (key_fields.length > 1) {
775 for (var i = 0; i < array.length; i++) {
776 if (manifold._record_equals(element, array[i], key_fields))
781 // XXX TODO If we have a dict, extract the key first
782 return ($.inArray(element, array) != -1);
786 /**************************************************************************
787 * Metadata management
788 **************************************************************************/
792 get_table: function(method) {
793 var table = MANIFOLD_METADATA[method];
794 return (typeof table === 'undefined') ? null : table;
797 get_columns: function(method) {
798 var table = this.get_table(method);
803 return (typeof table.column === 'undefined') ? null : table.column;
806 get_field_names: function(method)
808 var columns = this.get_columns(method);
811 return $.map(columns, function (x) { return x.name });
814 get_key: function(method) {
815 var table = this.get_table(method);
819 return (typeof table.key === 'undefined') ? null : table.key;
823 get_column: function(method, name) {
824 var columns = this.get_columns(method);
828 $.each(columns, function(i, c) {
835 get_type: function(method, name) {
836 var table = this.get_table(method);
840 var match = $.grep(table.column, function(x) { return x.name == name });
841 if (match.length == 0) {
844 return match[0].type;
846 return (typeof table.type === 'undefined') ? null : table.type;
851 /**************************************************************************
853 **************************************************************************/
855 query_store: new QueryStore(),
857 // XXX Remaining functions are deprecated since they are replaced by the query store
860 * Associative array storing the set of queries active on the page
866 * Insert a query in the global hash table associating uuids to queries.
867 * If the query has no been analyzed yet, let's do it.
868 * \fn insert_query(query)
870 * \param ManifoldQuery query Query to be added
872 insert_query : function (query) {
874 manifold.query_store.insert(query);
877 $(document).ready(function() {
878 manifold.run_query(query);
882 if (query.analyzed_query == null) {
883 query.analyze_subqueries();
885 manifold.all_queries[query.query_uuid]=query;
889 * Returns the query associated to a UUID
890 * \fn find_query(query_uuid)
892 * \param string query_uuid The UUID of the query to be returned
894 find_query : function (query_uuid) {
895 return manifold.all_queries[query_uuid];
898 /**************************************************************************
900 **************************************************************************/
902 // trigger a query asynchroneously
903 proxy_url : '/manifold/proxy/json/',
905 // reasonably low-noise, shows manifold requests coming in and out
906 asynchroneous_debug : true,
907 // print our more details on result publication and related callbacks
908 pubsub_debug : false,
911 * \brief We use js function closure to be able to pass the query (array)
912 * to the callback function used when data is received
914 success_closure: function(query, publish_uuid, callback) {
915 return function(data, textStatus) {
916 manifold.asynchroneous_success(data, query, publish_uuid, callback);
920 run_query: function(query, callback)
922 // default value for callback = null
923 if (typeof callback === 'undefined')
926 var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
927 query_ext.query_state = QUERY_STATE_INPROGRESS;
929 var query_json = JSON.stringify(query);
931 // Inform plugins about the progress
932 query.iter_subqueries(function (sq) {
933 var sq_query_ext = manifold.query_store.find_analyzed_query_ext(sq.query_uuid);
934 sq_query_ext.query_state = QUERY_STATE_INPROGRESS;
936 manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
940 $.post(manifold.proxy_url, {'json': query_json} , manifold.success_closure(query, null, callback));
944 // Executes all async. queries - intended for the javascript header to initialize queries
945 // input queries are specified as a list of {'query_uuid': <query_uuid> }
946 // each plugin is responsible for managing its spinner through on_query_in_progress
947 asynchroneous_exec : function (query_exec_tuples) {
949 // Loop through input array, and use publish_uuid to publish back results
950 $.each(query_exec_tuples, function(index, tuple) {
951 var query=manifold.find_query(tuple.query_uuid);
952 var query_json=JSON.stringify (query);
953 var publish_uuid=tuple.publish_uuid;
954 // by default we publish using the same uuid of course
955 if (publish_uuid==undefined) publish_uuid=query.query_uuid;
956 if (manifold.pubsub_debug) {
957 messages.debug("sending POST on " + manifold.proxy_url + query.__repr());
960 query.iter_subqueries(function (sq) {
961 manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
964 // not quite sure what happens if we send a string directly, as POST data is named..
965 // this gets reconstructed on the proxy side with ManifoldQuery.fill_from_POST
966 $.post(manifold.proxy_url, {'json':query_json},
967 manifold.success_closure(query, publish_uuid, tuple.callback));
972 * \brief Forward a query to the manifold backend
973 * \param query (dict) the query to be executed asynchronously
974 * \param callback (function) the function to be called when the query terminates
976 forward: function(query, callback) {
977 var query_json = JSON.stringify(query);
978 $.post(manifold.proxy_url, {'json': query_json} ,
979 manifold.success_closure(query, query.query_uuid, callback));
983 * Returns whether a query expects a unique results.
984 * This is the case when the filters contain a key of the object
985 * \fn query_expects_unique_result(query)
987 * \param ManifoldQuery query Query for which we are testing whether it expects a unique result
989 query_expects_unique_result: function(query) {
990 /* XXX we need functions to query metadata */
991 //var keys = MANIFOLD_METADATA[query.object]['keys']; /* array of array of field names */
992 /* TODO requires keys in metadata */
998 * \fn publish_result(query, results)
1000 * \param ManifoldQuery query Query which has received results
1001 * \param array results results corresponding to query
1003 publish_result: function(query, result) {
1004 if (typeof result === 'undefined')
1008 manifold.raise_record_event(query.query_uuid, CLEAR_RECORDS);
1009 if (manifold.pubsub_debug)
1010 messages.debug(".. publish_result (1) ");
1012 $.each(result, function(i, record) {
1013 manifold.raise_record_event(query.query_uuid, NEW_RECORD, record);
1016 if (manifold.pubsub_debug)
1017 messages.debug(".. publish_result (2) has used NEW API on " + count + " records");
1018 manifold.raise_record_event(query.query_uuid, DONE);
1019 if (manifold.pubsub_debug)
1020 messages.debug(".. publish_result (3) has used NEW API to say DONE");
1022 // OLD PLUGIN API BELOW
1023 /* Publish an update announce */
1024 var channel="/results/" + query.query_uuid + "/changed";
1025 if (manifold.pubsub_debug)
1026 messages.debug(".. publish_result (4) OLD API on channel" + channel);
1028 $.publish(channel, [result, query]);
1030 if (manifold.pubsub_debug)
1031 messages.debug(".. publish_result (5) END q=" + query.__repr());
1034 store_records: function(query, records) {
1036 var query_ext = manifold.query_store.find_analyzed_query_ext(query.query_uuid);
1037 if (query_ext.set_query_ext) {
1038 // We have a domain query
1039 // The results are stored in the corresponding set_query
1040 manifold.query_store.set_records(query_ext.set_query_ext.query.query_uuid, records);
1042 } else if (query_ext.domain_query_ext) {
1043 // We have a set query, it is only used to determine which objects are in the set, we should only retrieve the key
1044 // Has it a domain query, and has it completed ?
1045 $.each(records, function(i, record) {
1046 var key = manifold.metadata.get_key(query.object);
1047 var record_key = manifold.record_get_value(record, key);
1048 manifold.query_store.set_record_state(query.query_uuid, record_key, STATE_SET, STATE_SET_IN);
1052 // We have a normal query
1053 manifold.query_store.set_records(query.query_uuid, records, STATE_SET_IN);
1058 * Recursively publish result
1059 * \fn publish_result_rec(query, result)
1060 * \memberof Manifold
1061 * \param ManifoldQuery query Query which has received result
1062 * \param array result result corresponding to query
1064 * Note: this function works on the analyzed query
1066 publish_result_rec: function(query, records) {
1067 /* If the result is not unique, only publish the top query;
1068 * otherwise, publish the main object as well as subqueries
1069 * XXX how much recursive are we ?
1071 if (manifold.pubsub_debug)
1072 messages.debug (">>>>> publish_result_rec " + query.object);
1073 if (manifold.query_expects_unique_result(query)) {
1074 /* Also publish subqueries */
1075 $.each(query.subqueries, function(object, subquery) {
1076 manifold.publish_result_rec(subquery, records[0][object]);
1077 /* TODO remove object from result */
1080 if (manifold.pubsub_debug)
1081 messages.debug ("===== publish_result_rec " + query.object);
1083 var query_ext = manifold.query_store.find_analyzed_query_ext(query.query_uuid);
1084 query_ext.query_state = QUERY_STATE_DONE;
1086 this.store_records(query, records);
1090 if (query_ext.set_query_ext) {
1091 if (query_ext.set_query_ext.query_state != QUERY_STATE_DONE)
1093 pub_query = query_ext.set_query_ext.query;
1094 } else if (query_ext.domain_query_ext) {
1095 if (query_ext.domain_query_ext.query_state != QUERY_STATE_DONE)
1101 // We can only publish results if the query (and its related domain query) is complete
1102 manifold.publish_result(pub_query, records);
1104 if (manifold.pubsub_debug)
1105 messages.debug ("<<<<< publish_result_rec " + query.object);
1108 setup_update_query: function(query, records)
1110 // We don't prepare an update query if the result has more than 1 entry
1111 if (records.length != 1)
1113 var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
1115 var record = records[0];
1117 var update_query_ext = query_ext.update_query_ext;
1119 if (!update_query_ext)
1122 var update_query = update_query_ext.query;
1123 var update_query_ext = query_ext.update_query_ext;
1124 var update_query_orig = query_ext.update_query_orig_ext.query;
1126 // Testing whether the result has subqueries (one level deep only)
1127 // iif the query has subqueries
1129 var obj = query.analyzed_query.subqueries;
1130 for (method in obj) {
1131 if (obj.hasOwnProperty(method)) {
1132 var key = manifold.metadata.get_key(method);
1136 var subrecords = record[method];
1139 $.each(subrecords, function (i, subrecord) {
1140 sq_keys.push(manifold.record_get_value(subrecord, key));
1142 update_query.params[method] = sq_keys;
1143 update_query_orig.params[method] = sq_keys.slice();
1149 update_query_ext.disabled = false;
1150 update_query_orig_ext.disabled = false;
1154 process_get_query_records: function(query, records) {
1155 this.setup_update_query(query, records);
1157 var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
1158 query_ext.query_state = QUERY_STATE_DONE;
1160 /* Publish full results */
1161 var tmp_query = manifold.query_store.find_analyzed_query(query.query_uuid);
1162 manifold.publish_result_rec(tmp_query, records);
1165 make_records: function(object, records)
1167 $.each(records, function(i, record) {
1168 manifold.make_record(object, record);
1172 make_record: function(object, record)
1174 // To make an object a record, we just add the hash function
1175 var key = manifold.metadata.get_key(object);
1176 record.hashCode = manifold.record_hashcode(key.sort());
1177 record.equals = manifold.record_equals(key);
1179 // Looking after subrecords
1180 for (var field in record) {
1181 var result_value = record[field];
1183 switch (this.get_type(result_value)) {
1185 var subobject = manifold.metadata.get_type(object, field);
1186 // if (subobject) XXX Bugs with fields declared string while they are not : network.version is a dict in fact
1187 if (subobject && subobject != 'string')
1188 manifold.make_record(subobject, result_value);
1190 case TYPE_LIST_OF_RECORDS:
1191 var subobject = manifold.metadata.get_type(object, field);
1193 manifold.make_records(subobject, result_value);
1201 * What we need to do when receiving results from an update query:
1202 * - differences between what we had, what we requested, and what we obtained
1203 * . what we had : update_query_orig (simple fields and set fields managed differently)
1204 * . what we requested : update_query
1205 * . what we received : records
1206 * - raise appropriate events
1208 * The normal process is that results similar to Get will be pushed in the
1209 * pubsub mechanism, thus repopulating everything while we only need
1210 * diff's. This means we need to move the publish functionalities in the
1211 * previous 'process_get_query_records' function.
1213 process_update_query_records: function(query, records) {
1214 // First issue: we request everything, and not only what we modify, so will will have to ignore some fields
1215 var query_uuid = query.query_uuid;
1216 var query_ext = manifold.query_store.find_analyzed_query_ext(query_uuid);
1217 var update_query = query_ext.main_query_ext.update_query_ext.query;
1218 var update_query_orig = query_ext.main_query_ext.update_query_orig_ext.query;
1220 // Since we update objects one at a time, we can get the first record
1221 var record = records[0];
1223 // Let's iterate over the object properties
1224 for (var field in record) {
1225 var result_value = record[field];
1226 switch (this.get_type(result_value)) {
1228 // Did we ask for a change ?
1229 var update_value = update_query[field];
1231 // Not requested, if it has changed: OUT OF SYNC
1232 // How we can know ?
1233 // We assume it won't have changed
1237 throw "Internal error";
1243 value : (update_value == result_value) ? STATE_VALUE_CHANGE_SUCCESS : STATE_VALUE_CHANGE_FAILURE,
1245 manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1249 throw "Not implemented";
1253 case TYPE_LIST_OF_VALUES:
1254 // Same as list of records, but we don't have to extract keys
1256 // The rest of exactly the same (XXX factorize)
1257 var update_keys = update_query_orig.params[field];
1258 var query_keys = update_query.params[field];
1259 var added_keys = $.grep(query_keys, function (x) { return $.inArray(x, update_keys) == -1 });
1260 var removed_keys = $.grep(update_keys, function (x) { return $.inArray(x, query_keys) == -1 });
1263 $.each(added_keys, function(i, key) {
1264 if ($.inArray(key, result_value) == -1) {
1266 request: FIELD_REQUEST_ADD,
1269 status: FIELD_REQUEST_FAILURE,
1273 request: FIELD_REQUEST_ADD,
1276 status: FIELD_REQUEST_SUCCESS,
1279 manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1281 $.each(removed_keys, function(i, key) {
1282 if ($.inArray(key, result_keys) == -1) {
1284 request: FIELD_REQUEST_REMOVE,
1287 status: FIELD_REQUEST_SUCCESS,
1291 request: FIELD_REQUEST_REMOVE,
1294 status: FIELD_REQUEST_FAILURE,
1297 manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1303 case TYPE_LIST_OF_VALUES: // XXX Until fixed
1304 case TYPE_LIST_OF_RECORDS:
1305 var new_state,cur_query_uuid;
1307 cur_query_uuid = query.analyzed_query.subqueries[field].query_uuid;
1309 // example: slice.resource
1310 // - update_query_orig.params.resource = resources in slice before update
1311 // - update_query.params.resource = resource requested in slice
1312 // - keys from field = resources obtained
1313 var key = manifold.metadata.get_key(field);
1317 if (key.length > 1) {
1318 throw "Not implemented";
1324 /* XXX should be modified for multiple keys */
1325 var result_keys = $.map(record[field], function(x) { return manifold.record_get_value(x, key); });
1327 // XXX All this could be deduced from record state : STATE_IN_PENDING and STATE_OUT_PENDING
1328 // what we had at the begining
1329 var update_keys = update_query_orig.params[field];
1331 var query_keys = update_query.params[field];
1332 // what we added and removed
1333 var added_keys = $.grep(query_keys, function (x) { return (!(manifold._in_array(x, update_keys, key))); });
1334 var removed_keys = $.grep(update_keys, function (x) { return (!(manifold._in_array(x, query_keys, key))); });
1336 // Send events related to parent query
1337 $.each(added_keys, function(i, added_key) {
1338 new_state = (manifold._in_array(added_key, result_keys, key)) ? STATE_SET_IN_SUCCESS : STATE_SET_IN_FAILURE;
1340 // Update record state for children queries
1341 manifold.query_store.set_record_state(cur_query_uuid, added_key, STATE_SET, new_state);
1343 // XXX This could be optimized
1344 manifold.query_store.recount(cur_query_uuid);
1346 data = { state: STATE_SET, key : field, op : new_state, value: added_key }
1347 manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1349 // Inform subquery also
1351 manifold.raise_record_event(cur_query_uuid, FIELD_STATE_CHANGED, data);
1352 // XXX Passing no parameters so that they can redraw everything would
1353 // be more efficient but is currently not supported
1354 // XXX We could also need to inform plugins about nodes IN (not pending) that are no more, etc.
1355 // XXX refactor all this when suppressing update_queries, and relying on state instead !
1357 $.each(removed_keys, function(i, removed_key) {
1358 new_state = (manifold._in_array(removed_key, result_keys, key)) ? STATE_SET_OUT_FAILURE : STATE_SET_OUT_SUCCESS;
1360 // Update record state for children queries
1361 manifold.query_store.set_record_state(cur_query_uuid, removed_key, STATE_SET, new_state);
1363 // XXX This could be optimized
1364 manifold.query_store.recount(cur_query_uuid);
1366 data = { state: STATE_SET, key : field, op : new_state, value: removed_key }
1367 manifold.raise_record_event(query_uuid, FIELD_STATE_CHANGED, data);
1369 // Inform subquery also
1371 manifold.raise_record_event(cur_query_uuid, FIELD_STATE_CHANGED, data);
1378 // XXX Now we need to adapt 'update' and 'update_orig' queries as if we had done a get
1379 this.setup_update_query(query, records);
1381 var query_ext = manifold.query_store.find_query_ext(query.query_uuid);
1382 query_ext.query_state = QUERY_STATE_DONE;
1385 // Send DONE message to plugins
1386 query.iter_subqueries(function(sq, data, parent_query) {
1387 manifold.raise_record_event(sq.query_uuid, DONE);
1392 process_query_records: function(query, records) {
1393 if (query.action == 'get') {
1394 this.process_get_query_records(query, records);
1395 } else if (query.action == 'update') {
1396 this.process_update_query_records(query, records);
1400 // if set callback is provided it is called
1401 // most of the time publish_uuid will be query.query_uuid
1402 // however in some cases we wish to publish the result under a different uuid
1403 // e.g. an updater wants to publish its result as if from the original (get) query
1404 asynchroneous_success : function (data, query, publish_uuid, callback) {
1405 // xxx should have a nicer declaration of that enum in sync with the python code somehow
1407 var start = new Date();
1408 if (manifold.asynchroneous_debug)
1409 messages.debug(">>>>>>>>>> asynchroneous_success query.object=" + query.object);
1411 if (data.code == 2) { // ERROR
1412 // We need to make sense of error codes here
1413 alert("Your session has expired, please log in again");
1414 localStorage.removeItem('user');
1415 window.location="/logout/";
1416 if (manifold.asynchroneous_debug) {
1417 duration=new Date()-start;
1418 messages.debug ("<<<<<<<<<< asynchroneous_success " + query.object + " -- error returned - logging out " + duration + " ms");
1422 if (data.code == 1) { // WARNING
1423 messages.error("Some errors have been received from the manifold backend at " + MANIFOLD_URL + " [" + data.description + "]");
1424 // publish error code and text message on a separate channel for whoever is interested
1426 $.publish("/results/" + publish_uuid + "/failed", [data.code, data.description] );
1430 // If a callback has been specified, we redirect results to it
1433 if (manifold.asynchroneous_debug) {
1434 duration=new Date()-start;
1435 messages.debug ("<<<<<<<<<< asynchroneous_success " + query.object + " -- callback ended " + duration + " ms");
1440 if (manifold.asynchroneous_debug)
1441 messages.debug ("========== asynchroneous_success " + query.object + " -- before process_query_records [" + query.query_uuid +"]");
1443 // once everything is checked we can use the 'value' part of the manifoldresult
1444 var result=data.value;
1446 /* Eventually update the content of related queries (update, etc) */
1447 manifold.make_records(query.object, result);
1448 this.process_query_records(query, result);
1450 /* Publish results: disabled here, done in the previous call */
1451 //tmp_query = manifold.find_query(query.query_uuid);
1452 //manifold.publish_result_rec(tmp_query.analyzed_query, result);
1454 if (manifold.asynchroneous_debug) {
1455 duration=new Date()-start;
1456 messages.debug ("<<<<<<<<<< asynchroneous_success " + query.object + " -- done " + duration + " ms");
1461 /**************************************************************************
1462 * Plugin API helpers
1463 **************************************************************************/
1465 raise_event_handler: function(type, query_uuid, event_type, value) {
1466 if (manifold.pubsub_debug)
1467 messages.debug("raise_event_handler, quuid="+query_uuid+" type="+type+" event_type="+event_type);
1468 if ((type != 'query') && (type != 'record'))
1469 throw 'Incorrect type for manifold.raise_event()';
1470 // xxx we observe quite a lot of incoming calls with an undefined query_uuid
1471 // this should be fixed upstream in manifold I expect
1472 if (query_uuid === undefined) {
1473 messages.warning("undefined query in raise_event_handler");
1477 // notify the change to objects that either listen to this channel specifically,
1478 // or to the wildcard channel
1479 var channels = [ manifold.get_channel(type, query_uuid), manifold.get_channel(type, '*') ];
1481 $.each(channels, function(i, channel) {
1482 if (value === undefined) {
1483 if (manifold.pubsub_debug) messages.debug("triggering [no value] on channel="+channel+" and event_type="+event_type);
1484 $('.pubsub').trigger(channel, [event_type]);
1486 if (manifold.pubsub_debug) messages.debug("triggering [value="+value+"] on channel="+channel+" and event_type="+event_type);
1487 $('.pubsub').trigger(channel, [event_type, value]);
1492 raise_query_event: function(query_uuid, event_type, value) {
1493 manifold.raise_event_handler('query', query_uuid, event_type, value);
1496 raise_record_event: function(query_uuid, event_type, value) {
1497 manifold.raise_event_handler('record', query_uuid, event_type, value);
1501 * Event handler helpers
1503 _get_next_state_add: function(prev_state)
1505 switch (prev_state) {
1507 case STATE_SET_OUT_SUCCESS:
1508 case STATE_SET_IN_FAILURE:
1509 new_state = STATE_SET_IN_PENDING;
1512 case STATE_SET_OUT_PENDING:
1513 new_state = STATE_SET_IN;
1517 case STATE_SET_IN_PENDING:
1518 case STATE_SET_IN_SUCCESS:
1519 case STATE_SET_OUT_FAILURE:
1520 console.log("Inconsistent state: already in");
1526 _get_next_state_remove: function(prev_state)
1528 switch (prev_state) {
1530 case STATE_SET_IN_SUCCESS:
1531 case STATE_SET_OUT_FAILURE:
1532 new_state = STATE_SET_OUT_PENDING;
1535 case STATE_SET_IN_PENDING:
1536 new_state = STATE_SET_OUT;
1540 case STATE_SET_OUT_PENDING:
1541 case STATE_SET_OUT_SUCCESS:
1542 case STATE_SET_IN_FAILURE:
1543 console.log("Inconsistent state: already out");
1549 _grep_active_lease_callback: function(lease_query, resource_key) {
1550 return function(lease_key_lease) {
1551 var state, lease_key, lease;
1553 lease_key = lease_key_lease[0];
1554 lease = lease_key_lease[1];
1556 if (lease['resource'] != resource_key)
1559 state = manifold.query_store.get_record_state(lease_query.query_uuid, lease_key, STATE_SET);;
1562 case STATE_SET_IN_PENDING:
1563 case STATE_SET_IN_SUCCESS:
1564 case STATE_SET_OUT_FAILURE:
1567 case STATE_SET_OUT_PENDING:
1568 case STATE_SET_OUT_SUCCESS:
1569 case STATE_SET_IN_FAILURE:
1575 _enforce_constraints: function(query_ext, record, record_key, event_type)
1579 query = query_ext.query;
1581 switch(query.object) {
1584 // CONSTRAINT_RESERVABLE_LEASE
1586 // +) If a reservable node is added to the slice, then it should have a corresponding lease
1587 // XXX Not always a resource
1588 var is_reservable = (record.exclusive == true);
1589 if (is_reservable) {
1590 var warnings = manifold.query_store.get_record_state(query.query_uuid, record_key, STATE_WARNINGS);
1592 if (event_type == STATE_SET_ADD) {
1593 // We should have a lease_query associated
1594 var lease_query = query_ext.parent_query_ext.query.subqueries['lease']; // in options
1595 var lease_query_ext = manifold.query_store.find_analyzed_query_ext(lease_query.query_uuid);
1596 // Do we have lease records (in) with this resource
1597 var lease_records = $.grep(lease_query_ext.records.entries(), this._grep_active_lease_callback(lease_query, record_key));
1598 if (lease_records.length == 0) {
1600 // XXX Need for a better function to manage warnings
1601 var warn = CONSTRAINT_RESERVABLE_LEASE_MSG;
1602 warnings[CONSTRAINT_RESERVABLE_LEASE] = warn;
1604 // Lease are defined, delete the warning in case it was set previously
1605 delete warnings[CONSTRAINT_RESERVABLE_LEASE];
1608 // Remove warnings attached to this resource
1609 delete warnings[CONSTRAINT_RESERVABLE_LEASE];
1612 manifold.query_store.set_record_state(query.query_uuid, record_key, STATE_WARNINGS, warnings);
1615 /* This was redundant */
1616 // manifold.query_store.recount(query.query_uuid);
1618 // Signal the change to plugins (even if the constraint does not apply, so that the plugin can display a checkmark)
1620 state: STATE_WARNINGS,
1625 manifold.raise_record_event(query.query_uuid, FIELD_STATE_CHANGED, data);
1629 var resource_key = record_key.resource;
1630 var resource_query = query_ext.parent_query_ext.query.subqueries['resource'];
1631 var warnings = manifold.query_store.get_record_state(resource_query.query_uuid, resource_key, STATE_WARNINGS);
1633 if (event_type == STATE_SET_ADD) {
1634 // A lease is added, it removes the constraint
1635 delete warnings[CONSTRAINT_RESERVABLE_LEASE];
1637 // A lease is removed, it might trigger the warning
1638 var lease_records = $.grep(query_ext.records.entries(), this._grep_active_lease_callback(query, resource_key));
1639 if (lease_records.length == 0) { // XXX redundant cases
1641 // XXX Need for a better function to manage warnings
1642 var warn = CONSTRAINT_RESERVABLE_LEASE_MSG;
1643 warnings[CONSTRAINT_RESERVABLE_LEASE] = warn;
1645 // Lease are defined, delete the warning in case it was set previously
1646 delete warnings[CONSTRAINT_RESERVABLE_LEASE];
1651 manifold.query_store.recount(resource_query.query_uuid);
1653 // Signal the change to plugins (even if the constraint does not apply, so that the plugin can display a checkmark)
1655 state: STATE_WARNINGS,
1660 manifold.raise_record_event(resource_query.query_uuid, FIELD_STATE_CHANGED, data);
1664 // -) When a lease is added, it might remove the warning associated to a reservable node
1666 // If a NITOS node is reserved, then at least a NITOS channel should be reserved
1667 // - When a NITOS channel is added, it might remove a warning associated to all NITOS nodes
1669 // If a NITOS channel is reserved, then at least a NITOS node should be reserved
1670 // - When a NITOS node is added, it might remove a warning associated to all NITOS channels
1672 // A lease is present while the resource has been removed => Require warnings on nodes not in set !
1676 _get_query_path: function(query_ext) {
1679 while (sq.parent_query_ext) {
1682 path = sq.query.object + path;
1683 sq = sq.parent_query_ext;
1690 * Handling events raised by plugins
1692 raise_event: function(query_uuid, event_type, data)
1694 var query, query_ext;
1696 // Query uuid has been updated with the key of a new element
1697 query_ext = manifold.query_store.find_analyzed_query_ext(query_uuid);
1698 query = query_ext.query;
1700 switch(event_type) {
1702 // XXX At some point, should be renamed to RECORD_STATE_CHANGED
1703 case FIELD_STATE_CHANGED:
1705 // value is an object (request, key, value, status)
1706 // update is only possible is the query is not pending, etc
1707 // SET_ADD is on a subquery, FIELD_STATE_CHANGED on the query itself
1708 // we should map SET_ADD on this...
1710 // 1. Update internal query store about the change in status
1712 // 2. Update the update query
1713 update_query = query_ext.main_query_ext.update_query_ext.query;
1714 update_query_orig = query_ext.main_query_ext.update_query_orig_ext.query;
1716 switch(data.state) {
1721 /* Set parameter data.key in the update_query to VALUE */
1722 if (update_query.params[data.key] === undefined)
1723 update_query.params[data.key] = Array();
1724 update_query.params[data.key] = value.value;
1731 var prev_state, new_state;
1732 var main_query, record, new_data, path;
1734 // We only track state in the analyzed query
1735 prev_state = manifold.query_store.get_record_state(query_uuid, data.value, STATE_SET);
1736 if (prev_state === null)
1737 prev_state = STATE_SET_OUT;
1741 new_state = this._get_next_state_add(prev_state);
1743 /* data.value containts the resource key */
1744 manifold.query_store.add_record(query_uuid, data.value, new_state);
1745 record = manifold.query_store.get_record(query_uuid, data.value);
1746 this._enforce_constraints(query_ext, record, data.value, STATE_SET_ADD);
1748 /* Process update query in parent */
1749 path = this._get_query_path(query_ext);
1750 if (update_query.params[path] === undefined)
1751 update_query.params[path] = Array();
1752 update_query.params[path].push(data.value);
1756 case STATE_SET_REMOVE:
1757 new_state = this._get_next_state_remove(prev_state);
1759 /* data.value contains the resource key */
1760 manifold.query_store.remove_record(query_uuid, data.value, new_state);
1761 record = manifold.query_store.get_record(query_uuid, data.value);
1762 this._enforce_constraints(query_ext, record, data.value, STATE_SET_REMOVE);
1764 /* Process update query in parent */
1765 path = this._get_query_path(query_ext);
1766 arr = update_query.params[path];
1768 var key = manifold.metadata.get_key(query.object);
1769 arr = $.grep(arr, function(x) { return (!(manifold._record_equals(x, data.value, key))); });
1770 if (update_query.params[path] === undefined)
1771 update_query.params[path] = Array();
1772 update_query.params[path] = arr;
1776 /* Inform the parent query: important for update */
1783 main_query = query_ext.main_query_ext.query;
1784 manifold.raise_record_event(main_query.query_uuid, event_type, new_data);
1785 /* Propagate the event to other plugins subscribed to the query */
1786 manifold.query_store.recount(query_uuid);
1788 manifold.raise_record_event(query_uuid, event_type, new_data);
1793 // 3. Inform others about the change
1794 // a) the main query...
1795 manifold.raise_record_event(query_uuid, event_type, data);
1797 // b) subqueries eventually (dot in the key)
1800 var cur_query = query;
1801 if (cur_query.analyzed_query)
1802 cur_query = cur_query.analyzed_query;
1805 var path_array = data.key.split('.');
1806 var value_key = data.key.split('.');
1807 $.each(path_array, function(i, method) {
1808 cur_query = cur_query.subqueries[method];
1809 value_key.shift(); // XXX check that method is indeed shifted
1811 data.key = value_key;
1813 manifold.raise_record_event(cur_query.query_uuid, event_type, data);
1819 manifold.run_query(query_ext.main_query_ext.update_query_ext.query);
1822 /* QUERY STATE CHANGED */
1827 /* Update internal record state */
1828 manifold.query_store.add_filter(query_uuid, data);
1830 /* Propagate the message to plugins */
1831 manifold.raise_query_event(query_uuid, event_type, data);
1835 case FILTER_REMOVED:
1836 /* Update internal record state */
1837 manifold.query_store.remove_filter(query_uuid, data);
1839 /* Propagate the message to plugins */
1840 manifold.raise_query_event(query_uuid, event_type, data);
1845 main_query = query_ext.main_query_ext.query;
1846 main_update_query = query_ext.main_query_ext.update_query;
1849 // Here we need the full path through all subqueries
1851 // XXX We might need the query name in the QueryExt structure
1852 main_query.select(data);
1854 // XXX When is an update query associated ?
1855 // XXX main_update_query.select(value);
1857 manifold.raise_query_event(query_uuid, event_type, data);
1861 query = query_ext.query;
1862 main_query = query_ext.main_query_ext.query;
1863 main_update_query = query_ext.main_query_ext.update_query;
1864 query.unselect(data);
1865 main_query.unselect(data);
1867 // We need to inform about changes in these queries to the respective plugins
1868 // Note: query & main_query have the same UUID
1869 manifold.raise_query_event(query_uuid, event_type, data);
1872 // We need to inform about changes in these queries to the respective plugins
1873 // Note: query, main_query & update_query have the same UUID
1875 // http://trac.myslice.info/ticket/32
1876 // Avoid multiple calls to the same event
1877 //manifold.raise_query_event(query_uuid, event_type, value);
1879 // We are targeting the same object with get and update
1880 // The notion of query is bad, we should have a notion of destination, and issue queries on the destination
1881 // NOTE: Editing a subquery == editing a local view on the destination
1883 // XXX We might need to run the new query again and manage the plugins in the meantime with spinners...
1884 // For the time being, we will collect all columns during the first query
1887 /* Publish/subscribe channels for internal use */
1888 get_channel: function(type, query_uuid) {
1889 if ((type !== 'query') && (type != 'record'))
1891 return '/' + type + '/' + query_uuid;
1894 }; // manifold object
1895 /* ------------------------------------------------------------ */
1899 // OLD PLUGIN API: extend jQuery/$ with pubsub capabilities
1900 // https://gist.github.com/661855
1902 $.subscribe = function( channel, selector, data, fn) {
1903 /* borrowed from jQuery */
1904 if ( data == null && fn == null ) {
1907 data = selector = undefined;
1908 } else if ( fn == null ) {
1909 if ( typeof selector === "string" ) {
1910 // ( channel, selector, fn )
1914 // ( channel, data, fn )
1917 selector = undefined;
1922 /* We use an indirection function that will clone the object passed in
1923 * parameter to the subscribe callback
1925 * FIXME currently we only clone query objects which are the only ones
1926 * supported and editable, we might have the same issue with results but
1927 * the page load time will be severely affected...
1929 o.on.apply(o, [channel, selector, data, function() {
1930 for(i = 1; i < arguments.length; i++) {
1931 if ( arguments[i].constructor.name == 'ManifoldQuery' )
1932 arguments[i] = arguments[i].clone();
1934 fn.apply(o, arguments);
1938 $.unsubscribe = function() {
1939 o.off.apply(o, arguments);
1942 $.publish = function() {
1943 o.trigger.apply(o, arguments);
1948 /* ------------------------------------------------------------ */
1950 //http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request
1951 //make sure to expose csrf in our outcoming ajax/post requests
1953 beforeSend: function(xhr, settings) {
1954 function getCookie(name) {
1955 var cookieValue = null;
1956 if (document.cookie && document.cookie != '') {
1957 var cookies = document.cookie.split(';');
1958 for (var i = 0; i < cookies.length; i++) {
1959 var cookie = jQuery.trim(cookies[i]);
1960 // Does this cookie string begin with the name we want?
1961 if (cookie.substring(0, name.length + 1) == (name + '=')) {
1962 cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
1969 if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
1970 // Only send the token to relative URLs i.e. locally.
1971 xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));