def test_execute_query_data_ordering(self): # Arrange query = {} ascending_order_by_field = ["+title"] descending_order_by_field = ["-title"] # Act ascending_result = Data.execute_query(query, ascending_order_by_field) descending_result = Data.execute_query(query, descending_order_by_field) # Assert for i in range(len(ascending_result)): self.assertTrue(ascending_result.all()[i].title == descending_result.all()[len(ascending_result) - i - 1].title)
def test_execute_query_multi_field_sorting(self): # Arrange ascending_order_by_multi_field = ["+title", "+user_id"] descending_order_by_multi_field = ["+title", "-user_id"] query = {} # Act ascending_result = Data.execute_query(query, ascending_order_by_multi_field) descending_result = Data.execute_query(query, descending_order_by_multi_field) # Assert self.assertEqual(self.fixture.data_4.user_id, ascending_result.all()[4].user_id) self.assertEqual(self.fixture.data_5.user_id, ascending_result.all()[3].user_id) self.assertEqual(self.fixture.data_4.user_id, descending_result.all()[3].user_id) self.assertEqual(self.fixture.data_5.user_id, descending_result.all()[4].user_id)
def test_execute_query_data_descending_sorting(self): # Arrange descending_order_by_field = ["-title"] query = {} # Act descending_result = Data.execute_query(query, descending_order_by_field) # Assert self.assertTrue(self.fixture.data_2.title == descending_result.all()[len(descending_result)-2].title) self.assertTrue(self.fixture.data_1.title == descending_result.all()[len(descending_result)-1].title)
def test_execute_query_data_ascending_sorting(self): # Arrange ascending_order_by_field = ["+title"] query = {} # Act ascending_result = Data.execute_query(query, ascending_order_by_field) # Assert self.assertTrue(self.fixture.data_1.title == ascending_result.all()[0].title) self.assertTrue(self.fixture.data_2.title == ascending_result.all()[1].title)
def execute_query_with_projection(query, projection): """ Execute a given query with a projection. Args: query: projection: Returns: """ return Data.execute_query(query).only(projection)
def is_local_id_already_used(local_id): """ Check if the local id given already exist in db Args: local_id: Returns: """ return len( Data.execute_query({'dict_content.Resource.@localid': str(local_id) })) > 0
def execute_query(query, user, order_by_field=DATA_SORTING_FIELDS): """Execute a query on the Data collection. Args: query: user: order_by_field: Returns: """ return Data.execute_query(query, order_by_field)
def execute_query(query, user, order_by_field=None): """Execute a query on the Data collection. Args: query: user: order_by_field Returns: """ return Data.execute_query(query, order_by_field)
def is_pid_defined(pid): """Determine if a given PID already exists. Params: pid: Returns: """ json_pid_path = "dict_content.%s" % PID_XPATH query_result = Data.execute_query({json_pid_path: pid}, order_by_field=[]) return len(query_result) == 1
def process_cross_query(navigation_root_id, document_id, query, json_content): """ Args: navigation_root_id: document_id: query: json_content: Return: """ doc_query = {"_id": ObjectId(document_id)} doc_projection = {query.values()[0]: 1} document_list = Data.execute_query(doc_query).only( doc_projection.keys()[0]) document_projection_value = get_projection(document_list[0]) cross_query = {query.keys()[0]: document_projection_value} cross_projection = {"id": 1} cross_documents = Data.execute_query(cross_query).only( cross_projection.keys()[0]) cross_documents_ids = [ get_projection(cross_doc) for cross_doc in cross_documents ] # Gives the crossed documents and their id global ids_docs_to_querys ids_docs_to_querys = cross_documents_ids # FIXME won't work for the case where we need several item from a same document cross_document_data = processviewdocidlist(navigation_root_id, cross_documents_ids, json_content) return [ content for contents in cross_document_data for content in contents ]
def is_pid_defined_for_document(pid, document_id): """Determine if a given PID match the document ID provided. Params: pid: document_id: Returns: """ json_pid_path = "dict_content.%s" % PID_XPATH query_result = Data.execute_query({json_pid_path: pid}, order_by_field=[]) return len(query_result) == 1 and query_result[0].pk == document_id
def execute_query_with_projection(query, projection, order_by_field=DATA_SORTING_FIELDS): """Execute a given query with a projection. Args: query: projection: order_by_field: Returns: """ return Data.execute_query(query, order_by_field).only(projection)
def get_data_by_pid(pid): """Return data object with the given pid. Parameters: pid: Returns: data object """ json_pid_path = "dict_content.%s" % PID_XPATH query_result = Data.execute_query({json_pid_path: pid}, order_by_field=[]) query_result_length = len(query_result) if query_result_length == 0: raise DoesNotExist("PID is not attached to any data.") elif query_result_length != 1: raise ApiError("PID must be unique.") else: return query_result[0]
def _load_data_view(node_id, nav_id, data_id, from_tree=True): """ Load view for a data, from a tree or a link Args: node_id: nav_id: data_id: from_tree: Returns: """ if not from_tree: navigation_node = navigation_operations.get_navigation_node_for_document( node_id, data_id) else: navigation_node = navigation_api.get_by_id(node_id) # Initialize parameters in order to download later some information xml_document = Data.get_by_id(data_id) projection_views = json.loads(navigation_node.options["projection_view"]) view_data = { "header": xml_document.title, "type": "leaf", "views": [], "download": [] } # Initialize parameters in order to download later some information # dict of doc_id and queries done of cross documents : {id_doc1: [list of queries1], id_doc2: [list of queries2]} dict_id_and_queries_cross_docs = dict() # dict of doc_id and queries results for a cross document : {id_doc: [list of queries results]} dict_id_and_queryresults_cross_docs = dict() # dict of queried parameter and associated result for the queries done on the main doc : { queried parameter: value} dict_tags_values_main_doc = dict() values_of_items_from_main_doc = [] list_values_of_items_from_main_doc = [] # Send the annotation to the processor and collect the data for projection_view in projection_views: result_data = {"title": projection_view["title"], "data": None} # FIXME better handling of x-queries # Get info from other doc (without the main queried document) if "query" in projection_view.keys(): doc_projections = [] # Get the names of the tags tag need to be displayed for value in projection_view["data"]: doc_projections.append(value.get('path')) result_data["data"] = parser_processview.process_cross_query( nav_id, data_id, projection_view["query"], projection_view["data"]) # Get all the queried documents (without the main queried document) queried_docs = parser_processview.ids_docs_to_querys for id_doc in queried_docs: other_doc_query = {"_id": ObjectId(id_doc)} # list of queries done on the current document query_list = list() # list of queries results done on the current document result_list = list() for projection in doc_projections: # Get the MongoDB query path for the parameter that need to be displayed # eg: query_path = dict_content.a.b.c.d.e query_path = { doc_projections[doc_projections.index(projection)]: 1 } # Get the Data corresponding to the id queried_data = Data.execute_query(other_doc_query).only( query_path.keys()[0]) # Add the query to the query list for the current doc query_list.append(query_path.keys()[0].replace( "dict_content.", "")) try: # Get the result of the query result_query = get_projection(queried_data[0]) # Add the result of the query to the result list for the current doc result_list.append(str(result_query)) except: pass dict_id_and_queries_cross_docs[id_doc] = query_list dict_id_and_queryresults_cross_docs[id_doc] = result_list # Get info from main doc else: # list of queries done on the current document (Main doc) query_list = [] doc_projections = [ value.get('path') for value in projection_view["data"] ] query_list = [ doc_projections[doc_projections.index(projection)] for projection in doc_projections ] # Get all results of the queries. type(result_data["data"]) = dict or instance of dict result_data["data"] = parser_processview.processview( nav_id, data_id, projection_view["data"]) for query_path, dict_result in zip(query_list, result_data["data"]): # eg: query_path = a.b.c.d # We have only one value as result for the query dict_result_value = dict_result.get("value", None) if dict_result_value is not None: tag = query_path.split(".")[ -1] # Get only d (the needed tag) if tag in dict_tags_values_main_doc: v = dict_tags_values_main_doc[tag] if isinstance(v, list): dict_tags_values_main_doc[tag].append( dict_result_value) else: dict_tags_values_main_doc[tag] = [ dict_tags_values_main_doc[tag], dict_result_value ] else: dict_tags_values_main_doc[tag] = dict_result_value # We have multiple values for this result: all the chemical components # (dict_result[key] is an inclusion of dicts) dict_result_item, dict_result_items = [ dict_result.get(_, None) for _ in ["item", "items"] ] if dict_result_item or dict_result_items: dict_result_item_v = dict_result_item if dict_result_item is not None else dict_result_items #dict_result_item_v = [dict_result_item, dict_result_items][dict_result_item not None] # From the inclusion of dict, process the dict into a list and get all the needed values # values_of_items_from_main_doc = list[list[value1 for dict i,value2 for dict 2, ..]] # eg: values_of_items_from_main_doc= [l1,l2] # l1 = [["location", "NIST"], ["Build location X", "59"], "EWI_Build1"]] # l2 = [["location", "NIST"], ["Build location X", "47"], "EWI_Build2"]] get_values_items(dict_result_item_v, values_of_items_from_main_doc) for list_of_values in values_of_items_from_main_doc: for value in list_of_values: # We have a list :value= [displayed parameter, value] # eg : ["Build location X", "59"] if len(value) == 2: # list_tag_of_items_from_main_doc.append(value[0]) list_values_of_items_from_main_doc.append( value[1]) # Get the value. eg: 59 # We have only one value (last value in the list. eg: EWI_Build1 in l1) else: list_values_of_items_from_main_doc.append( value) view_data["views"].append(result_data) # Get the displayed data as an XML format in order to download it later # # STEP 1: Build the XML based on initial tags for the crossed documents: # Go into the dict of doc_id and queries of cross documents and build the xml for each document # dict_id_and_queries_cross_docs = {id_doc1: [list of queries1], id_doc2: [list of queries2]} xml_cross_queries_string = "" for key in dict_id_and_queries_cross_docs: # key = doc_id # Get all queries for the current doc_id. # eg: query_list = ["a.b.c.d","a.b.c.e","a.b.f.g"] query_list = dict_id_and_queries_cross_docs[key] # For the doc_id get all the results of the queries done # results = ["D","E","G"] results = dict_id_and_queryresults_cross_docs[key] # Build a xml string for the doc associated to doc_id thanks to the list of queries and the result list xml_string = queryNode.tree_to_xml_string( queryNode.aggregate_query(query_list, results)) xml_object = XSDTree.fromstring(xml_string + "</data>") # Add the XML part to create an XML resulting of tag and values of crossed documents xml_cross_queries_string += XSDTree.tostring(xml_object, pretty=True) # STEP 2: Build the XML for the main document with only the needed tags: # Get the Data associated to the main document data = Data.get_by_id(data_id) # Get the XML content file_content = data.xml_content xml_main_doc = XSDTree.fromstring(file_content) # Transform all the result value into a string to help while testing equality of values with the original XML for key, value in dict_tags_values_main_doc.items(): if isinstance(value, list): dict_tags_values_main_doc[key] = map( lambda x: x if isinstance(x, unicode) else str(x), value) else: try: dict_tags_values_main_doc[key] = str(value) except: dict_tags_values_main_doc[key] = u''.join(value).encode( 'utf-8') v = dict_tags_values_main_doc[key] # Process the XML structure that represents the main document to keep only the needed tags and information for child in xml_main_doc.iter(): # Transform all values into a string try: text = str(child.text) except: text = u''.join(child.text).encode('utf-8') # If the xml tag is in our dict of tags and values from the main document # and its value = dict_tags_values_main_doc[child.tag] we keep the text in the XML structure # else we remove the text if child.tag in dict_tags_values_main_doc.keys(): # Fixme # if text != str(dict_tags_values_main_doc[child.tag]) or dict_tags_values_main_doc[child.tag] not in text: (caution: does not keep all needed values if we replace by this line) if isinstance(dict_tags_values_main_doc[child.tag], list): display_value = False for value in dict_tags_values_main_doc[child.tag]: if value == text or value in text: display_value = True break if not display_value: child.text = "" else: if text == str( dict_tags_values_main_doc[child.tag] ) or dict_tags_values_main_doc[child.tag] in text: pass else: child.text = "" else: # If text is in our list of items of the main doc we keep the value and remove it from our list of items if text in list_values_of_items_from_main_doc: list_values_of_items_from_main_doc.remove(text) else: display_text = False # v = processed name of the tag as appears in the rendered data after clicking a doc of the tree # If this name is in our list of items from the main doc we keep the value (text) in the XML tree # else we remove this value for v in list_values_of_items_from_main_doc: if v in text: display_text = True break if not display_text: child.text = "" xml_f_main_doc = xml_main_doc # Remove empty leafs of the tree (all child where child.text="") while check_empty_nodes(xml_main_doc): remove_empty_nodes(xml_f_main_doc) # Build the final XML string result of the main doc and the crossed docs xml_main_doc = XSDTree.tostring(xml_f_main_doc, pretty="TRUE") xml = xml_main_doc + xml_cross_queries_string xml_final = "<xml>\n" + xml + "</xml>" xml_final = u''.join(xml_final).encode('utf-8') xml_final = str(xml_final) view_data["download"] = xml_final return view_data