"""Utility module DB entities.""" import datetime import neo4j.time as neo_time from permissions.constants import constants from permissions.types import TenantType def node_to_dict(resource_node, **kwargs): """Convert neo4j Node instance to python dict. Args: resource_node (Node): A graph node with properties and label info. kwargs (dict): extra data that needs to be appended to this node info. Returns: dict: of metadata from node and extra kwargs. """ data = {} for attribute, value in resource_node.items(): if isinstance(value, (datetime.date, datetime.datetime, neo_time.DateTime)): data[attribute] = value.__str__() else: data[attribute] = value common = list(set(constants.PROFILE_TYPES) & resource_node.labels) # remove it from GET result resource name till we fix all references. valid_types = set(constants.RESOURCE_TYPES) valid_types.discard(constants.LABEL_RESOURCE_TYPE) resource_type = list(valid_types & resource_node.labels) if common: data['profile_type'] = common.pop() elif resource_type: # for resources with multiple labels like Vendor:Label:Orchard # return value from valid resource type data['type'] = resource_type.pop() else: all_labels = list(set(resource_node.labels)) data['type'] = all_labels[0] if all_labels else '' data.update(kwargs) return data def cast_numeric_string_to_int(str_value): """Convert numeric string to int if possible. Data in DB is type sensitive, but data from request url is string. So cast it where exact match is required in queries. Args: str_value (str): String value. """ if not str_value: return str_value try: return int(str_value) except ValueError: return str_value def get_tenant_type_from_neo4j_labels(labels: frozenset) -> TenantType: """ Convert Neo4j node labels to a TenantType. Args: labels (set): Set of Neo4j node labels Returns: TenantType: The corresponding tenant type or raises if no mapping exists """ for label in labels: if label in constants.ADMIN_ASSIGNABLE_NEO_TYPES: return TenantType(constants.NEO_TO_TENANT_TYPE_MAPPING.get(label)) raise ValueError(f'No valid tenant type found in labels: {labels}')