INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Return a MATCH query string from a list of MatchQuery namedtuples.
def emit_code_from_multiple_match_queries(match_queries): """Return a MATCH query string from a list of MatchQuery namedtuples.""" optional_variable_base_name = '$optional__' union_variable_name = '$result' query_data = deque([u'SELECT EXPAND(', union_variable_name, u')', u' LET ']) optional_variab...
Return a MATCH query string from a CompoundMatchQuery.
def emit_code_from_ir(compound_match_query, compiler_metadata): """Return a MATCH query string from a CompoundMatchQuery.""" # If the compound match query contains only one match query, # just call `emit_code_from_single_match_query` # If there are multiple match queries, construct the query string for ...
Serialize a Date object to its proper ISO-8601 representation.
def _serialize_date(value): """Serialize a Date object to its proper ISO-8601 representation.""" if not isinstance(value, date): raise ValueError(u'The received object was not a date: ' u'{} {}'.format(type(value), value)) return value.isoformat()
Serialize a DateTime object to its proper ISO-8601 representation.
def _serialize_datetime(value): """Serialize a DateTime object to its proper ISO-8601 representation.""" if not isinstance(value, (datetime, arrow.Arrow)): raise ValueError(u'The received object was not a datetime: ' u'{} {}'.format(type(value), value)) return value.isoforma...
Deserialize a DateTime object from its proper ISO-8601 representation.
def _parse_datetime_value(value): """Deserialize a DateTime object from its proper ISO-8601 representation.""" if value.endswith('Z'): # Arrow doesn't support the "Z" literal to denote UTC time. # Strip the "Z" and add an explicit time zone instead. value = value[:-1] + '+00:00' ret...
Add compiler-specific meta-fields into all interfaces and types of the specified schema. It is preferable to use the EXTENDED_META_FIELD_DEFINITIONS constant above to directly inject the meta-fields during the initial process of building the schema, as that approach is more robust. This function does its b...
def insert_meta_fields_into_existing_schema(graphql_schema): """Add compiler-specific meta-fields into all interfaces and types of the specified schema. It is preferable to use the EXTENDED_META_FIELD_DEFINITIONS constant above to directly inject the meta-fields during the initial process of building the s...
Ensure that the current context allows for visiting a vertex field.
def validate_context_for_visiting_vertex_field(parent_location, vertex_field_name, context): """Ensure that the current context allows for visiting a vertex field.""" if is_in_fold_innermost_scope(context): raise GraphQLCompilationError( u'Traversing inside a @fold block after filtering on {...
Take a GraphQL query, pretty print it, and return it.
def pretty_print_graphql(query, use_four_spaces=True): """Take a GraphQL query, pretty print it, and return it.""" # Use our custom visitor, which fixes directive argument order # to get the canonical representation output = visit(parse(query), CustomPrintingVisitor()) # Using four spaces for inden...
Make indentation use 4 spaces, rather than the 2 spaces GraphQL normally uses.
def fix_indentation_depth(query): """Make indentation use 4 spaces, rather than the 2 spaces GraphQL normally uses.""" lines = query.split('\n') final_lines = [] for line in lines: consecutive_spaces = 0 for char in line: if char == ' ': consecutive_spaces +=...
Call when exiting a directive node in the ast.
def leave_Directive(self, node, *args): """Call when exiting a directive node in the ast.""" name_to_arg_value = { # Taking [0] is ok here because the GraphQL parser checks for the # existence of ':' in directive arguments. arg.split(':', 1)[0]: arg for ar...
Lower the IR into an IR form that can be represented in MATCH queries. Args: ir_blocks: list of IR blocks to lower into MATCH-compatible form query_metadata_table: QueryMetadataTable object containing all metadata collected during query processing, including location m...
def lower_ir(ir_blocks, query_metadata_table, type_equivalence_hints=None): """Lower the IR into an IR form that can be represented in MATCH queries. Args: ir_blocks: list of IR blocks to lower into MATCH-compatible form query_metadata_table: QueryMetadataTable object containing all metadata co...
Sort class metadatas so that a superclass is always before the subclass
def toposort_classes(classes): """Sort class metadatas so that a superclass is always before the subclass""" def get_class_topolist(class_name, name_to_class, processed_classes, current_trace): """Return a topologically sorted list of this class's dependencies and class itself Args: ...
Return a list of the superclasses of the given class
def _list_superclasses(class_def): """Return a list of the superclasses of the given class""" superclasses = class_def.get('superClasses', []) if superclasses: # Make sure to duplicate the list return list(superclasses) sup = class_def.get('superClass', None) if sup: return ...
Return a LocationStackEntry namedtuple with the specified parameters.
def _construct_location_stack_entry(location, num_traverses): """Return a LocationStackEntry namedtuple with the specified parameters.""" if not isinstance(num_traverses, int) or num_traverses < 0: raise AssertionError(u'Attempted to create a LocationStackEntry namedtuple with an invalid ' ...
Return a list of vertex fields, and a list of property fields, for the given AST node. Also verifies that all property fields for the AST node appear before all vertex fields, raising GraphQLCompilationError if that is not the case. Args: ast: GraphQL AST node, obtained from the graphql library ...
def _get_fields(ast): """Return a list of vertex fields, and a list of property fields, for the given AST node. Also verifies that all property fields for the AST node appear before all vertex fields, raising GraphQLCompilationError if that is not the case. Args: ast: GraphQL AST node, obtaine...
Return the inline fragment at the current AST node, or None if no fragment exists.
def _get_inline_fragment(ast): """Return the inline fragment at the current AST node, or None if no fragment exists.""" if not ast.selection_set: # There is nothing selected here, so no fragment. return None fragments = [ ast_node for ast_node in ast.selection_set.selections...
Process the output_source directive, modifying the context as appropriate. Args: schema: GraphQL schema object, obtained from the graphql library current_schema_type: GraphQLType, the schema type at the current location ast: GraphQL AST node, obtained from the graphql library locati...
def _process_output_source_directive(schema, current_schema_type, ast, location, context, local_unique_directives): """Process the output_source directive, modifying the context as appropriate. Args: schema: GraphQL schema object, obtained from the graphql library ...
Process property directives at this AST node, updating the query context as appropriate. Args: schema: GraphQL schema object, obtained from the graphql library current_schema_type: GraphQLType, the schema type at the current location ast: GraphQL AST node, obtained from the graphql library....
def _compile_property_ast(schema, current_schema_type, ast, location, context, unique_local_directives): """Process property directives at this AST node, updating the query context as appropriate. Args: schema: GraphQL schema object, obtained from the graphql library c...
Validate and return the depth parameter of the recurse directive.
def _get_recurse_directive_depth(field_name, field_directives): """Validate and return the depth parameter of the recurse directive.""" recurse_directive = field_directives['recurse'] optional_directive = field_directives.get('optional', None) if optional_directive: raise GraphQLCompilationErro...
Perform type checks on the enclosing type and the recursed type for a recurse directive. Args: current_schema_type: GraphQLType, the schema type at the current location field_schema_type: GraphQLType, the schema type at the inner scope context: dict, various per-compilation data (e.g. decla...
def _validate_recurse_directive_types(current_schema_type, field_schema_type, context): """Perform type checks on the enclosing type and the recursed type for a recurse directive. Args: current_schema_type: GraphQLType, the schema type at the current location field_schema_type: GraphQLType, the...
Return a list of basic blocks corresponding to the vertex AST node. Args: schema: GraphQL schema object, obtained from the graphql library current_schema_type: GraphQLType, the schema type at the current location ast: GraphQL AST node, obtained from the graphql library location: Loc...
def _compile_vertex_ast(schema, current_schema_type, ast, location, context, unique_local_directives, fields): """Return a list of basic blocks corresponding to the vertex AST node. Args: schema: GraphQL schema object, obtained from the graphql library current_schema_typ...
Ensure the @fold scope has at least one output, or filters on the size of the fold.
def _validate_fold_has_outputs_or_count_filter(fold_scope_location, fold_has_count_filter, outputs): """Ensure the @fold scope has at least one output, or filters on the size of the fold.""" # This function makes sure that the @fold scope has an effect. # Folds either output data, or filter the data enclosi...
Return a list of basic blocks corresponding to the inline fragment at this AST node. Args: schema: GraphQL schema object, obtained from the graphql library current_schema_type: GraphQLType, the schema type at the current location ast: GraphQL AST node, obtained from the graphql library. ...
def _compile_fragment_ast(schema, current_schema_type, ast, location, context): """Return a list of basic blocks corresponding to the inline fragment at this AST node. Args: schema: GraphQL schema object, obtained from the graphql library current_schema_type: GraphQLType, the schema type at the...
Compile the given GraphQL AST node into a list of basic blocks. Args: schema: GraphQL schema object, obtained from the graphql library current_schema_type: GraphQLType, the schema type at the current location ast: the current GraphQL AST node, obtained from the graphql library locat...
def _compile_ast_node_to_ir(schema, current_schema_type, ast, location, context): """Compile the given GraphQL AST node into a list of basic blocks. Args: schema: GraphQL schema object, obtained from the graphql library current_schema_type: GraphQLType, the schema type at the current location ...
Ensure all tags are used in some filter.
def _validate_all_tags_are_used(metadata): """Ensure all tags are used in some filter.""" tag_names = set([tag_name for tag_name, _ in metadata.tags]) filter_arg_names = set() for location, _ in metadata.registered_locations: for filter_info in metadata.get_filter_infos(location): fo...
Compile a full GraphQL abstract syntax tree (AST) to intermediate representation. Args: schema: GraphQL schema object, obtained from the graphql library ast: the root GraphQL AST node for the query, obtained from the graphql library, and already validated against the schema for type-co...
def _compile_root_ast_to_ir(schema, ast, type_equivalence_hints=None): """Compile a full GraphQL abstract syntax tree (AST) to intermediate representation. Args: schema: GraphQL schema object, obtained from the graphql library ast: the root GraphQL AST node for the query, obtained from the grap...
Construct the final ConstructResult basic block that defines the output format of the query. Args: outputs: dict, output name (string) -> output data dict, specifying the location from where to get the data, and whether the data is optional (and therefore may be missing); ...
def _compile_output_step(outputs): """Construct the final ConstructResult basic block that defines the output format of the query. Args: outputs: dict, output name (string) -> output data dict, specifying the location from where to get the data, and whether the data is optional (and th...
Validate the supplied graphql schema and ast. This method wraps around graphql-core's validation to enforce a stricter requirement of the schema -- all directives supported by the compiler must be declared by the schema, regardless of whether each directive is used in the query or not. Args: s...
def _validate_schema_and_ast(schema, ast): """Validate the supplied graphql schema and ast. This method wraps around graphql-core's validation to enforce a stricter requirement of the schema -- all directives supported by the compiler must be declared by the schema, regardless of whether each directive...
Convert the given GraphQL string into compiler IR, using the given schema object. Args: schema: GraphQL schema object, created using the GraphQL library graphql_string: string containing the GraphQL to compile to compiler IR type_equivalence_hints: optional dict of GraphQL interface or type...
def graphql_to_ir(schema, graphql_string, type_equivalence_hints=None): """Convert the given GraphQL string into compiler IR, using the given schema object. Args: schema: GraphQL schema object, created using the GraphQL library graphql_string: string containing the GraphQL to compile to compile...
Return a human-readable representation of a gremlin command string.
def pretty_print_gremlin(gremlin): """Return a human-readable representation of a gremlin command string.""" gremlin = remove_custom_formatting(gremlin) too_many_parts = re.split(r'([)}]|scatter)[ ]?\.', gremlin) # Put the ) and } back on. parts = [ too_many_parts[i] + too_many_parts[i + 1]...
Return a human-readable representation of a parameterized MATCH query string.
def pretty_print_match(match, parameterized=True): """Return a human-readable representation of a parameterized MATCH query string.""" left_curly = '{{' if parameterized else '{' right_curly = '}}' if parameterized else '}' match = remove_custom_formatting(match) parts = re.split('({}|{})'.format(le...
Represent a float as a string without losing precision.
def represent_float_as_str(value): """Represent a float as a string without losing precision.""" # In Python 2, calling str() on a float object loses precision: # # In [1]: 1.23456789012345678 # Out[1]: 1.2345678901234567 # # In [2]: 1.2345678901234567 # Out[2]: 1.2345678901234567 # ...
Type-check the value, and then just return str(value).
def type_check_and_str(python_type, value): """Type-check the value, and then just return str(value).""" if not isinstance(value, python_type): raise GraphQLInvalidArgumentError(u'Attempting to represent a non-{type} as a {type}: ' u'{value}'.format(type=python_...
Attempt to coerce the value to a Decimal, or raise an error if unable to do so.
def coerce_to_decimal(value): """Attempt to coerce the value to a Decimal, or raise an error if unable to do so.""" if isinstance(value, decimal.Decimal): return value else: try: return decimal.Decimal(value) except decimal.InvalidOperation as e: raise GraphQL...
Return a visitor function that replaces every instance of one expression with another one.
def make_replacement_visitor(find_expression, replace_expression): """Return a visitor function that replaces every instance of one expression with another one.""" def visitor_fn(expression): """Return the replacement if this expression matches the expression we're looking for.""" if expression ...
Return a visitor function that replaces expressions of a given type with new expressions.
def make_type_replacement_visitor(find_types, replacement_func): """Return a visitor function that replaces expressions of a given type with new expressions.""" def visitor_fn(expression): """Return a replacement expression if the original expression is of the correct type.""" if isinstance(expr...
Ensure the named operator is valid and supported.
def _validate_operator_name(operator, supported_operators): """Ensure the named operator is valid and supported.""" if not isinstance(operator, six.text_type): raise TypeError(u'Expected operator as unicode string, got: {} {}'.format( type(operator).__name__, operator)) if operator not ...
Validate that the Literal is correctly representable.
def validate(self): """Validate that the Literal is correctly representable.""" # Literals representing boolean values or None are correctly representable and supported. if self.value is None or self.value is True or self.value is False: return # Literal safe strings are cor...
Return a unicode object with the Gremlin/MATCH representation of this Literal.
def _to_output_code(self): """Return a unicode object with the Gremlin/MATCH representation of this Literal.""" # All supported Literal objects serialize to identical strings both in Gremlin and MATCH. self.validate() if self.value is None: return u'null' elif self.va...
Validate that the Variable is correctly representable.
def validate(self): """Validate that the Variable is correctly representable.""" # Get the first letter, or empty string if it doesn't exist. if not self.variable_name.startswith(u'$'): raise GraphQLCompilationError(u'Expected variable name to start with $, but was: ' ...
Return a unicode object with the MATCH representation of this Variable.
def to_match(self): """Return a unicode object with the MATCH representation of this Variable.""" self.validate() # We don't want the dollar sign as part of the variable name. variable_with_no_dollar_sign = self.variable_name[1:] match_variable_name = '{%s}' % (six.text_type(va...
Return a unicode object with the Gremlin representation of this expression.
def to_gremlin(self): """Return a unicode object with the Gremlin representation of this expression.""" # We can't directly pass a Date or a DateTime object, so we have to pass it as a string # and then parse it inline. For date format parameter meanings, see: # http://docs.oracle.com/ja...
Return a unicode object with the Gremlin representation of this expression.
def to_gremlin(self): """Return a unicode object with the Gremlin representation of this expression.""" self.validate() local_object_name = self.get_local_object_gremlin_name() if self.field_name == '@this': return local_object_name if '@' in self.field_name: ...
Validate that the GlobalContextField is correctly representable.
def validate(self): """Validate that the GlobalContextField is correctly representable.""" if not isinstance(self.location, Location): raise TypeError(u'Expected Location location, got: {} {}' .format(type(self.location).__name__, self.location)) if self....
Return a unicode object with the MATCH representation of this GlobalContextField.
def to_match(self): """Return a unicode object with the MATCH representation of this GlobalContextField.""" self.validate() mark_name, field_name = self.location.get_location_name() validate_safe_string(mark_name) validate_safe_string(field_name) return u'%s.%s' % (mark...
Return a unicode object with the MATCH representation of this ContextField.
def to_match(self): """Return a unicode object with the MATCH representation of this ContextField.""" self.validate() mark_name, field_name = self.location.get_location_name() validate_safe_string(mark_name) if field_name is None: return u'$matched.%s' % (mark_name,...
Return a unicode object with the Gremlin representation of this expression.
def to_gremlin(self): """Return a unicode object with the Gremlin representation of this expression.""" self.validate() mark_name, field_name = self.location.get_location_name() if field_name is not None: validate_safe_string(field_name) if '@' in field_name: ...
Validate that the OutputContextField is correctly representable.
def validate(self): """Validate that the OutputContextField is correctly representable.""" if not isinstance(self.location, Location): raise TypeError(u'Expected Location location, got: {} {}'.format( type(self.location).__name__, self.location)) if not self.location...
Return a unicode object with the MATCH representation of this expression.
def to_match(self): """Return a unicode object with the MATCH representation of this expression.""" self.validate() mark_name, field_name = self.location.get_location_name() validate_safe_string(mark_name) validate_safe_string(field_name) stripped_field_type = strip_non...
Return a unicode object with the Gremlin representation of this expression.
def to_gremlin(self): """Return a unicode object with the Gremlin representation of this expression.""" self.validate() mark_name, field_name = self.location.get_location_name() validate_safe_string(mark_name) validate_safe_string(field_name) if '@' in field_name: ...
Validate that the FoldedContextField is correctly representable.
def validate(self): """Validate that the FoldedContextField is correctly representable.""" if not isinstance(self.fold_scope_location, FoldScopeLocation): raise TypeError(u'Expected FoldScopeLocation fold_scope_location, got: {} {}'.format( type(self.fold_scope_location), sel...
Return a unicode object with the MATCH representation of this expression.
def to_match(self): """Return a unicode object with the MATCH representation of this expression.""" self.validate() mark_name, field_name = self.fold_scope_location.get_location_name() validate_safe_string(mark_name) template = u'$%(mark_name)s.%(field_name)s' template_...
Validate that the FoldCountContextField is correctly representable.
def validate(self): """Validate that the FoldCountContextField is correctly representable.""" if not isinstance(self.fold_scope_location, FoldScopeLocation): raise TypeError(u'Expected FoldScopeLocation fold_scope_location, got: {} {}'.format( type(self.fold_scope_location), ...
Return a unicode object with the MATCH representation of this expression.
def to_match(self): """Return a unicode object with the MATCH representation of this expression.""" self.validate() mark_name, _ = self.fold_scope_location.get_location_name() validate_safe_string(mark_name) template = u'$%(mark_name)s.size()' template_data = { ...
Validate that the ContextFieldExistence is correctly representable.
def validate(self): """Validate that the ContextFieldExistence is correctly representable.""" if not isinstance(self.location, Location): raise TypeError(u'Expected Location location, got: {} {}'.format( type(self.location).__name__, self.location)) if self.location....
Validate that the UnaryTransformation is correctly representable.
def validate(self): """Validate that the UnaryTransformation is correctly representable.""" _validate_operator_name(self.operator, UnaryTransformation.SUPPORTED_OPERATORS) if not isinstance(self.inner_expression, Expression): raise TypeError(u'Expected Expression inner_expression, g...
Create an updated version (if needed) of UnaryTransformation via the visitor pattern.
def visit_and_update(self, visitor_fn): """Create an updated version (if needed) of UnaryTransformation via the visitor pattern.""" new_inner = self.inner_expression.visit_and_update(visitor_fn) if new_inner is not self.inner_expression: return visitor_fn(UnaryTransformation(self.op...
Return a unicode object with the MATCH representation of this UnaryTransformation.
def to_match(self): """Return a unicode object with the MATCH representation of this UnaryTransformation.""" self.validate() translation_table = { u'size': u'size()', } match_operator = translation_table.get(self.operator) if not match_operator: r...
Return a unicode object with the Gremlin representation of this expression.
def to_gremlin(self): """Return a unicode object with the Gremlin representation of this expression.""" translation_table = { u'size': u'count()', } gremlin_operator = translation_table.get(self.operator) if not gremlin_operator: raise AssertionError(u'Unr...
Validate that the BinaryComposition is correctly representable.
def validate(self): """Validate that the BinaryComposition is correctly representable.""" _validate_operator_name(self.operator, BinaryComposition.SUPPORTED_OPERATORS) if not isinstance(self.left, Expression): raise TypeError(u'Expected Expression left, got: {} {} {}'.format( ...
Create an updated version (if needed) of BinaryComposition via the visitor pattern.
def visit_and_update(self, visitor_fn): """Create an updated version (if needed) of BinaryComposition via the visitor pattern.""" new_left = self.left.visit_and_update(visitor_fn) new_right = self.right.visit_and_update(visitor_fn) if new_left is not self.left or new_right is not self.r...
Return a unicode object with the MATCH representation of this BinaryComposition.
def to_match(self): """Return a unicode object with the MATCH representation of this BinaryComposition.""" self.validate() # The MATCH versions of some operators require an inverted order of arguments. # pylint: disable=unused-variable regular_operator_format = '(%(left)s %(oper...
Return a unicode object with the Gremlin representation of this expression.
def to_gremlin(self): """Return a unicode object with the Gremlin representation of this expression.""" self.validate() immediate_operator_format = u'({left} {operator} {right})' dotted_operator_format = u'{left}.{operator}({right})' intersects_operator_format = u'(!{left}.{oper...
Validate that the TernaryConditional is correctly representable.
def validate(self): """Validate that the TernaryConditional is correctly representable.""" if not isinstance(self.predicate, Expression): raise TypeError(u'Expected Expression predicate, got: {} {}'.format( type(self.predicate).__name__, self.predicate)) if not isinst...
Create an updated version (if needed) of TernaryConditional via the visitor pattern.
def visit_and_update(self, visitor_fn): """Create an updated version (if needed) of TernaryConditional via the visitor pattern.""" new_predicate = self.predicate.visit_and_update(visitor_fn) new_if_true = self.if_true.visit_and_update(visitor_fn) new_if_false = self.if_false.visit_and_up...
Return a unicode object with the MATCH representation of this TernaryConditional.
def to_match(self): """Return a unicode object with the MATCH representation of this TernaryConditional.""" self.validate() # For MATCH, an additional validation step is needed -- we currently do not support # emitting MATCH code for TernaryConditional that contains another TernaryCondi...
Return a unicode object with the Gremlin representation of this expression.
def to_gremlin(self): """Return a unicode object with the Gremlin representation of this expression.""" self.validate() return u'({predicate} ? {if_true} : {if_false})'.format( predicate=self.predicate.to_gremlin(), if_true=self.if_true.to_gremlin(), if_false=...
Assert that IR blocks originating from the frontend do not have nonsensical structure. Args: ir_blocks: list of BasicBlocks representing the IR to sanity-check Raises: AssertionError, if the IR has unexpected structure. If the IR produced by the front-end cannot be successfully and cor...
def sanity_check_ir_blocks_from_frontend(ir_blocks, query_metadata_table): """Assert that IR blocks originating from the frontend do not have nonsensical structure. Args: ir_blocks: list of BasicBlocks representing the IR to sanity-check Raises: AssertionError, if the IR has unexpected str...
Assert that all registered locations' parent locations are also registered.
def _sanity_check_registered_locations_parent_locations(query_metadata_table): """Assert that all registered locations' parent locations are also registered.""" for location, location_info in query_metadata_table.registered_locations: if (location != query_metadata_table.root_location and ...
Assert that all locations in MarkLocation blocks have registered and valid metadata.
def _sanity_check_all_marked_locations_are_registered(ir_blocks, query_metadata_table): """Assert that all locations in MarkLocation blocks have registered and valid metadata.""" # Grab all the registered locations, then make sure that: # - Any location that appears in a MarkLocation block is also registere...
Assert that every FoldScopeLocation that exists on a Fold block is unique.
def _sanity_check_fold_scope_locations_are_unique(ir_blocks): """Assert that every FoldScopeLocation that exists on a Fold block is unique.""" observed_locations = dict() for block in ir_blocks: if isinstance(block, Fold): alternate = observed_locations.get(block.fold_scope_location, Non...
Assert that there are no nested Fold contexts, and that every Fold has a matching Unfold.
def _sanity_check_no_nested_folds(ir_blocks): """Assert that there are no nested Fold contexts, and that every Fold has a matching Unfold.""" fold_seen = False for block in ir_blocks: if isinstance(block, Fold): if fold_seen: raise AssertionError(u'Found a nested Fold con...
Assert that QueryRoot is always the first block, and only the first block.
def _sanity_check_query_root_block(ir_blocks): """Assert that QueryRoot is always the first block, and only the first block.""" if not isinstance(ir_blocks[0], QueryRoot): raise AssertionError(u'The first block was not QueryRoot: {}'.format(ir_blocks)) for block in ir_blocks[1:]: if isinstan...
Assert that ConstructResult is always the last block, and only the last block.
def _sanity_check_construct_result_block(ir_blocks): """Assert that ConstructResult is always the last block, and only the last block.""" if not isinstance(ir_blocks[-1], ConstructResult): raise AssertionError(u'The last block was not ConstructResult: {}'.format(ir_blocks)) for block in ir_blocks[:-...
Ensure there are no Traverse / Backtrack / Recurse blocks after an OutputSource block.
def _sanity_check_output_source_follower_blocks(ir_blocks): """Ensure there are no Traverse / Backtrack / Recurse blocks after an OutputSource block.""" seen_output_source = False for block in ir_blocks: if isinstance(block, OutputSource): seen_output_source = True elif seen_outp...
Assert that adjacent blocks obey all invariants.
def _sanity_check_block_pairwise_constraints(ir_blocks): """Assert that adjacent blocks obey all invariants.""" for first_block, second_block in pairwise(ir_blocks): # Always Filter before MarkLocation, never after. if isinstance(first_block, MarkLocation) and isinstance(second_block, Filter): ...
Ensure that every new location is marked with a MarkLocation block.
def _sanity_check_every_location_is_marked(ir_blocks): """Ensure that every new location is marked with a MarkLocation block.""" # Exactly one MarkLocation block is found between any block that starts an interval of blocks # that all affect the same query position, and the first subsequent block that affect...
Assert that optional Traverse blocks are preceded by a MarkLocation.
def _sanity_check_mark_location_preceding_optional_traverse(ir_blocks): """Assert that optional Traverse blocks are preceded by a MarkLocation.""" # Once all fold blocks are removed, each optional Traverse must have # a MarkLocation block immediately before it. _, new_ir_blocks = extract_folds_from_ir_b...
Ensure that CoerceType not in a @fold are followed by a MarkLocation or Filter block.
def _sanity_check_coerce_type_outside_of_fold(ir_blocks): """Ensure that CoerceType not in a @fold are followed by a MarkLocation or Filter block.""" is_in_fold = False for first_block, second_block in pairwise(ir_blocks): if isinstance(first_block, Fold): is_in_fold = True if n...
Ensure that the given property type_id is supported by the graph.
def validate_supported_property_type_id(property_name, property_type_id): """Ensure that the given property type_id is supported by the graph.""" if property_type_id not in PROPERTY_TYPE_ID_TO_NAME: raise AssertionError(u'Property "{}" has unsupported property type id: ' u'{...
Parse and return the default value for a boolean property.
def _parse_bool_default_value(property_name, default_value_string): """Parse and return the default value for a boolean property.""" lowercased_value_string = default_value_string.lower() if lowercased_value_string in {'0', 'false'}: return False elif lowercased_value_string in {'1', 'true'}: ...
Parse and return the default value for a datetime property.
def _parse_datetime_default_value(property_name, default_value_string): """Parse and return the default value for a datetime property.""" # OrientDB doesn't use ISO-8601 datetime format, so we have to parse it manually # and then turn it into a python datetime object. strptime() will raise an exception ...
Parse and return the default value for a date property.
def _parse_date_default_value(property_name, default_value_string): """Parse and return the default value for a date property.""" # OrientDB doesn't use ISO-8601 datetime format, so we have to parse it manually # and then turn it into a python datetime object. strptime() will raise an exception # if the...
Parse the default value string into its proper form given the property type ID. Args: property_name: string, the name of the property whose default value is being parsed. Used primarily to construct meaningful error messages, should the default value prove inva...
def parse_default_property_value(property_name, property_type_id, default_value_string): """Parse the default value string into its proper form given the property type ID. Args: property_name: string, the name of the property whose default value is being parsed. Used primarily to...
Compile the GraphQL input using the schema into a MATCH query and associated metadata. Args: schema: GraphQL schema object describing the schema of the graph to be queried graphql_string: the GraphQL query to compile to MATCH, as a string type_equivalence_hints: optional dict of GraphQL int...
def compile_graphql_to_match(schema, graphql_string, type_equivalence_hints=None): """Compile the GraphQL input using the schema into a MATCH query and associated metadata. Args: schema: GraphQL schema object describing the schema of the graph to be queried graphql_string: the GraphQL query to ...
Compile the GraphQL input using the schema into a Gremlin query and associated metadata. Args: schema: GraphQL schema object describing the schema of the graph to be queried graphql_string: the GraphQL query to compile to Gremlin, as a string type_equivalence_hints: optional dict of GraphQL...
def compile_graphql_to_gremlin(schema, graphql_string, type_equivalence_hints=None): """Compile the GraphQL input using the schema into a Gremlin query and associated metadata. Args: schema: GraphQL schema object describing the schema of the graph to be queried graphql_string: the GraphQL query...
Compile the GraphQL input using the schema into a SQL query and associated metadata. Args: schema: GraphQL schema object describing the schema of the graph to be queried graphql_string: the GraphQL query to compile to SQL, as a string compiler_metadata: SQLAlchemy metadata containing tables...
def compile_graphql_to_sql(schema, graphql_string, compiler_metadata, type_equivalence_hints=None): """Compile the GraphQL input using the schema into a SQL query and associated metadata. Args: schema: GraphQL schema object describing the schema of the graph to be queried graphql_string: the Gr...
Compile the GraphQL input, lowering and emitting the query using the given functions. Args: language: string indicating the target language to compile to. lowering_func: Function to lower the compiler IR into a compatible form for the target language backend. query_em...
def _compile_graphql_generic(language, lowering_func, query_emitter_func, schema, graphql_string, type_equivalence_hints, compiler_metadata): """Compile the GraphQL input, lowering and emitting the query using the given functions. Args: language: string indicating the targe...
Ensure the filter function is only applied to scalar leaf types.
def scalar_leaf_only(operator): """Ensure the filter function is only applied to scalar leaf types.""" def decorator(f): """Decorate the supplied function with the "scalar_leaf_only" logic.""" @wraps(f) def wrapper(filter_operation_info, context, parameters, *args, **kwargs): ...
Ensure the filter function is only applied to vertex field types.
def vertex_field_only(operator): """Ensure the filter function is only applied to vertex field types.""" def decorator(f): """Decorate the supplied function with the "vertex_field_only" logic.""" @wraps(f) def wrapper(filter_operation_info, context, parameters, *args, **kwargs): ...
Ensure the filter function has "count" parameters specified.
def takes_parameters(count): """Ensure the filter function has "count" parameters specified.""" def decorator(f): """Decorate the supplied function with the "takes_parameters" logic.""" @wraps(f) def wrapper(filter_operation_info, location, context, parameters, *args, **kwargs): ...
Return a two-element tuple that represents the argument to the directive being processed. Args: directive_location: Location where the directive is used. context: dict, various per-compilation data (e.g. declared tags, whether the current block is optional, etc.). May be mutated in...
def _represent_argument(directive_location, context, argument, inferred_type): """Return a two-element tuple that represents the argument to the directive being processed. Args: directive_location: Location where the directive is used. context: dict, various per-compilation data (e.g. declared ...
Return a Filter basic block that performs the given comparison against the property field. Args: filter_operation_info: FilterOperationInfo object, containing the directive and field info of the field where the filter is to be applied. location: Location where this fi...
def _process_comparison_filter_directive(filter_operation_info, location, context, parameters, operator=None): """Return a Filter basic block that performs the given comparison against the property field. Args: filter_operation_info: FilterOperationInfo object, ...
Return a Filter basic block that checks the degree of the edge to the given vertex field. Args: filter_operation_info: FilterOperationInfo object, containing the directive and field info of the field where the filter is to be applied. location: Location where this fil...
def _process_has_edge_degree_filter_directive(filter_operation_info, location, context, parameters): """Return a Filter basic block that checks the degree of the edge to the given vertex field. Args: filter_operation_info: FilterOperationInfo object, containing the directive and field info ...
Return a Filter basic block that checks for a match against an Entity's name or alias. Args: filter_operation_info: FilterOperationInfo object, containing the directive and field info of the field where the filter is to be applied. location: Location where this filter...
def _process_name_or_alias_filter_directive(filter_operation_info, location, context, parameters): """Return a Filter basic block that checks for a match against an Entity's name or alias. Args: filter_operation_info: FilterOperationInfo object, containing the directive and field info ...
Return a Filter basic block that checks that a field is between two values, inclusive. Args: filter_operation_info: FilterOperationInfo object, containing the directive and field info of the field where the filter is to be applied. location: Location where this filter...
def _process_between_filter_directive(filter_operation_info, location, context, parameters): """Return a Filter basic block that checks that a field is between two values, inclusive. Args: filter_operation_info: FilterOperationInfo object, containing the directive and field info ...
Return a Filter basic block that checks for a value's existence in a collection. Args: filter_operation_info: FilterOperationInfo object, containing the directive and field info of the field where the filter is to be applied. location: Location where this filter is us...
def _process_in_collection_filter_directive(filter_operation_info, location, context, parameters): """Return a Filter basic block that checks for a value's existence in a collection. Args: filter_operation_info: FilterOperationInfo object, containing the directive and field info ...
Return a Filter basic block that checks if the directive arg is a substring of the field. Args: filter_operation_info: FilterOperationInfo object, containing the directive and field info of the field where the filter is to be applied. location: Location where this fil...
def _process_has_substring_filter_directive(filter_operation_info, location, context, parameters): """Return a Filter basic block that checks if the directive arg is a substring of the field. Args: filter_operation_info: FilterOperationInfo object, containing the directive and field info ...
Return a Filter basic block that checks if the directive arg is contained in the field. Args: filter_operation_info: FilterOperationInfo object, containing the directive and field info of the field where the filter is to be applied. location: Location where this filte...
def _process_contains_filter_directive(filter_operation_info, location, context, parameters): """Return a Filter basic block that checks if the directive arg is contained in the field. Args: filter_operation_info: FilterOperationInfo object, containing the directive and field info ...
Return a Filter basic block that checks if the directive arg and the field intersect. Args: filter_operation_info: FilterOperationInfo object, containing the directive and field info of the field where the filter is to be applied. location: Location where this filter ...
def _process_intersects_filter_directive(filter_operation_info, location, context, parameters): """Return a Filter basic block that checks if the directive arg and the field intersect. Args: filter_operation_info: FilterOperationInfo object, containing the directive and field info ...