idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
226,900 | def _construct_location_stack_entry ( location , num_traverses ) : if not isinstance ( num_traverses , int ) or num_traverses < 0 : raise AssertionError ( u'Attempted to create a LocationStackEntry namedtuple with an invalid ' u'value for "num_traverses" {}. This is not allowed.' . format ( num_traverses ) ) if not isinstance ( location , Location ) : raise AssertionError ( u'Attempted to create a LocationStackEntry namedtuple with an invalid ' u'value for "location" {}. This is not allowed.' . format ( location ) ) return LocationStackEntry ( location = location , num_traverses = num_traverses ) | Return a LocationStackEntry namedtuple with the specified parameters . | 166 | 13 |
226,901 | def _get_fields ( ast ) : if not ast . selection_set : # There are no child fields. return [ ] , [ ] property_fields = [ ] vertex_fields = [ ] seen_field_names = set ( ) switched_to_vertices = False # Ensures that all property fields are before all vertex fields. for field_ast in ast . selection_set . selections : if not isinstance ( field_ast , Field ) : # We are getting Fields only, ignore everything else. continue name = get_ast_field_name ( field_ast ) if name in seen_field_names : # If we ever allow repeated field names, # then we have to change the Location naming scheme to reflect the repetitions # and disambiguate between Recurse and Traverse visits to a Location. raise GraphQLCompilationError ( u'Encountered repeated field name: {}' . format ( name ) ) seen_field_names . add ( name ) # Vertex fields start with 'out_' or 'in_', denoting the edge direction to that vertex. if is_vertex_field_name ( name ) : switched_to_vertices = True vertex_fields . append ( field_ast ) else : if switched_to_vertices : raise GraphQLCompilationError ( u'Encountered property field {} ' u'after vertex fields!' . format ( name ) ) property_fields . append ( field_ast ) return vertex_fields , property_fields | Return a list of vertex fields and a list of property fields for the given AST node . | 320 | 18 |
226,902 | def _get_inline_fragment ( ast ) : 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 if isinstance ( ast_node , InlineFragment ) ] if not fragments : return None if len ( fragments ) > 1 : raise GraphQLCompilationError ( u'Cannot compile GraphQL with more than one fragment in ' u'a given selection set.' ) return fragments [ 0 ] | Return the inline fragment at the current AST node or None if no fragment exists . | 115 | 16 |
226,903 | def _process_output_source_directive ( schema , current_schema_type , ast , location , context , local_unique_directives ) : # The 'ast' variable is only for function signature uniformity, and is currently not used. output_source_directive = local_unique_directives . get ( 'output_source' , None ) if output_source_directive : if has_encountered_output_source ( context ) : raise GraphQLCompilationError ( u'Cannot have more than one output source!' ) if is_in_optional_scope ( context ) : raise GraphQLCompilationError ( u'Cannot have the output source in an optional block!' ) set_output_source_data ( context , location ) return blocks . OutputSource ( ) else : return None | Process the output_source directive modifying the context as appropriate . | 177 | 12 |
226,904 | def _compile_property_ast ( schema , current_schema_type , ast , location , context , unique_local_directives ) : validate_property_directives ( unique_local_directives ) if location . field == COUNT_META_FIELD_NAME : # Verify that uses of this field are within a @fold scope. if not is_in_fold_scope ( context ) : raise GraphQLCompilationError ( u'Cannot use the "{}" meta field when not within a @fold ' u'vertex field, as counting elements only makes sense ' u'in a fold. Location: {}' . format ( COUNT_META_FIELD_NAME , location ) ) # step P-2: process property-only directives tag_directive = unique_local_directives . get ( 'tag' , None ) if tag_directive : if is_in_fold_scope ( context ) : raise GraphQLCompilationError ( u'Tagging values within a @fold vertex field is ' u'not allowed! Location: {}' . format ( location ) ) if location . field == COUNT_META_FIELD_NAME : raise AssertionError ( u'Tags are prohibited within @fold, but unexpectedly found use of ' u'a tag on the {} meta field that is only allowed within a @fold!' u'Location: {}' . format ( COUNT_META_FIELD_NAME , location ) ) # Schema validation has ensured that the fields below exist. tag_name = tag_directive . arguments [ 0 ] . value . value if tag_name in context [ 'tags' ] : raise GraphQLCompilationError ( u'Cannot reuse tag name: {}' . format ( tag_name ) ) validate_safe_string ( tag_name ) context [ 'tags' ] [ tag_name ] = { 'location' : location , 'optional' : is_in_optional_scope ( context ) , 'type' : strip_non_null_from_type ( current_schema_type ) , } context [ 'metadata' ] . record_tag_info ( tag_name , TagInfo ( location = location ) ) output_directive = unique_local_directives . get ( 'output' , None ) if output_directive : # Schema validation has ensured that the fields below exist. output_name = output_directive . arguments [ 0 ] . value . value if output_name in context [ 'outputs' ] : raise GraphQLCompilationError ( u'Cannot reuse output name: ' u'{}, {}' . format ( output_name , context ) ) validate_safe_string ( output_name ) validate_output_name ( output_name ) graphql_type = strip_non_null_from_type ( current_schema_type ) if is_in_fold_scope ( context ) : # Fold outputs are only allowed at the last level of traversal. set_fold_innermost_scope ( context ) if location . field != COUNT_META_FIELD_NAME : graphql_type = GraphQLList ( graphql_type ) context [ 'outputs' ] [ output_name ] = { 'location' : location , 'optional' : is_in_optional_scope ( context ) , 'type' : graphql_type , 'fold' : context . get ( 'fold' , None ) , } | Process property directives at this AST node updating the query context as appropriate . | 742 | 14 |
226,905 | def _get_recurse_directive_depth ( field_name , field_directives ) : recurse_directive = field_directives [ 'recurse' ] optional_directive = field_directives . get ( 'optional' , None ) if optional_directive : raise GraphQLCompilationError ( u'Found both @optional and @recurse on ' u'the same vertex field: {}' . format ( field_name ) ) recurse_args = get_uniquely_named_objects_by_name ( recurse_directive . arguments ) recurse_depth = int ( recurse_args [ 'depth' ] . value . value ) if recurse_depth < 1 : raise GraphQLCompilationError ( u'Found recurse directive with disallowed depth: ' u'{}' . format ( recurse_depth ) ) return recurse_depth | Validate and return the depth parameter of the recurse directive . | 193 | 13 |
226,906 | def _validate_recurse_directive_types ( current_schema_type , field_schema_type , context ) : # Get the set of all allowed types in the current scope. type_hints = context [ 'type_equivalence_hints' ] . get ( field_schema_type ) type_hints_inverse = context [ 'type_equivalence_hints_inverse' ] . get ( field_schema_type ) allowed_current_types = { field_schema_type } if type_hints and isinstance ( type_hints , GraphQLUnionType ) : allowed_current_types . update ( type_hints . types ) if type_hints_inverse and isinstance ( type_hints_inverse , GraphQLUnionType ) : allowed_current_types . update ( type_hints_inverse . types ) # The current scope must be of the same type as the field scope, or an acceptable subtype. current_scope_is_allowed = current_schema_type in allowed_current_types is_implemented_interface = ( isinstance ( field_schema_type , GraphQLInterfaceType ) and isinstance ( current_schema_type , GraphQLObjectType ) and field_schema_type in current_schema_type . interfaces ) if not any ( ( current_scope_is_allowed , is_implemented_interface ) ) : raise GraphQLCompilationError ( u'Edges expanded with a @recurse directive must either ' u'be of the same type as their enclosing scope, a supertype ' u'of the enclosing scope, or be of an interface type that is ' u'implemented by the type of their enclosing scope. ' u'Enclosing scope type: {}, edge type: ' u'{}' . format ( current_schema_type , field_schema_type ) ) | Perform type checks on the enclosing type and the recursed type for a recurse directive . | 427 | 20 |
226,907 | def _compile_fragment_ast ( schema , current_schema_type , ast , location , context ) : query_metadata_table = context [ 'metadata' ] # step F-2. Emit a type coercion block if appropriate, # then recurse into the fragment's selection. coerces_to_type_name = ast . type_condition . name . value coerces_to_type_obj = schema . get_type ( coerces_to_type_name ) basic_blocks = [ ] # Check if the coercion is necessary. # No coercion is necessary if coercing to the current type of the scope, # or if the scope is of union type, to the base type of the union as defined by # the type_equivalence_hints compilation parameter. is_same_type_as_scope = current_schema_type . is_same_type ( coerces_to_type_obj ) equivalent_union_type = context [ 'type_equivalence_hints' ] . get ( coerces_to_type_obj , None ) is_base_type_of_union = ( isinstance ( current_schema_type , GraphQLUnionType ) and current_schema_type . is_same_type ( equivalent_union_type ) ) if not ( is_same_type_as_scope or is_base_type_of_union ) : # Coercion is required. query_metadata_table . record_coercion_at_location ( location , coerces_to_type_obj ) basic_blocks . append ( blocks . CoerceType ( { coerces_to_type_name } ) ) inner_basic_blocks = _compile_ast_node_to_ir ( schema , coerces_to_type_obj , ast , location , context ) basic_blocks . extend ( inner_basic_blocks ) return basic_blocks | Return a list of basic blocks corresponding to the inline fragment at this AST node . | 415 | 16 |
226,908 | def _validate_all_tags_are_used ( metadata ) : 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 ) : for filter_arg in filter_info . args : if is_tag_argument ( filter_arg ) : filter_arg_names . add ( get_directive_argument_name ( filter_arg ) ) unused_tags = tag_names - filter_arg_names if unused_tags : raise GraphQLCompilationError ( u'This GraphQL query contains @tag directives whose values ' u'are not used: {}. This is not allowed. Please either use ' u'them in a filter or remove them entirely.' . format ( unused_tags ) ) | Ensure all tags are used in some filter . | 196 | 10 |
226,909 | def _compile_output_step ( outputs ) : if not outputs : raise GraphQLCompilationError ( u'No fields were selected for output! Please mark at least ' u'one field with the @output directive.' ) output_fields = { } for output_name , output_context in six . iteritems ( outputs ) : location = output_context [ 'location' ] optional = output_context [ 'optional' ] graphql_type = output_context [ 'type' ] expression = None existence_check = None # pylint: disable=redefined-variable-type if isinstance ( location , FoldScopeLocation ) : if optional : raise AssertionError ( u'Unreachable state reached, optional in fold: ' u'{}' . format ( output_context ) ) if location . field == COUNT_META_FIELD_NAME : expression = expressions . FoldCountContextField ( location ) else : expression = expressions . FoldedContextField ( location , graphql_type ) else : expression = expressions . OutputContextField ( location , graphql_type ) if optional : existence_check = expressions . ContextFieldExistence ( location . at_vertex ( ) ) if existence_check : expression = expressions . TernaryConditional ( existence_check , expression , expressions . NullLiteral ) # pylint: enable=redefined-variable-type output_fields [ output_name ] = expression return blocks . ConstructResult ( output_fields ) | Construct the final ConstructResult basic block that defines the output format of the query . | 317 | 16 |
226,910 | def _validate_schema_and_ast ( schema , ast ) : core_graphql_errors = validate ( schema , ast ) # The following directives appear in the core-graphql library, but are not supported by the # graphql compiler. unsupported_default_directives = frozenset ( [ frozenset ( [ 'include' , frozenset ( [ 'FIELD' , 'FRAGMENT_SPREAD' , 'INLINE_FRAGMENT' ] ) , frozenset ( [ 'if' ] ) ] ) , frozenset ( [ 'skip' , frozenset ( [ 'FIELD' , 'FRAGMENT_SPREAD' , 'INLINE_FRAGMENT' ] ) , frozenset ( [ 'if' ] ) ] ) , frozenset ( [ 'deprecated' , frozenset ( [ 'ENUM_VALUE' , 'FIELD_DEFINITION' ] ) , frozenset ( [ 'reason' ] ) ] ) ] ) # Directives expected by the graphql compiler. expected_directives = { frozenset ( [ directive . name , frozenset ( directive . locations ) , frozenset ( six . viewkeys ( directive . args ) ) ] ) for directive in DIRECTIVES } # Directives provided in the parsed graphql schema. actual_directives = { frozenset ( [ directive . name , frozenset ( directive . locations ) , frozenset ( six . viewkeys ( directive . args ) ) ] ) for directive in schema . get_directives ( ) } # Directives missing from the actual directives provided. missing_directives = expected_directives - actual_directives if missing_directives : missing_message = ( u'The following directives were missing from the ' u'provided schema: {}' . format ( missing_directives ) ) core_graphql_errors . append ( missing_message ) # Directives that are not specified by the core graphql library. Note that Graphql-core # automatically injects default directives into the schema, regardless of whether # the schema supports said directives. Hence, while the directives contained in # unsupported_default_directives are incompatible with the graphql-compiler, we allow them to # be present in the parsed schema string. extra_directives = actual_directives - expected_directives - unsupported_default_directives if extra_directives : extra_message = ( u'The following directives were supplied in the given schema, but are not ' u'not supported by the GraphQL compiler: {}' . format ( extra_directives ) ) core_graphql_errors . append ( extra_message ) return core_graphql_errors | Validate the supplied graphql schema and ast . | 573 | 10 |
226,911 | def graphql_to_ir ( schema , graphql_string , type_equivalence_hints = None ) : graphql_string = _preprocess_graphql_string ( graphql_string ) try : ast = parse ( graphql_string ) except GraphQLSyntaxError as e : raise GraphQLParsingError ( e ) validation_errors = _validate_schema_and_ast ( schema , ast ) if validation_errors : raise GraphQLValidationError ( u'String does not validate: {}' . format ( validation_errors ) ) if len ( ast . definitions ) != 1 : raise AssertionError ( u'Unsupported graphql string with multiple definitions, should have ' u'been caught in validation: \n{}\n{}' . format ( graphql_string , ast ) ) base_ast = ast . definitions [ 0 ] return _compile_root_ast_to_ir ( schema , base_ast , type_equivalence_hints = type_equivalence_hints ) | Convert the given GraphQL string into compiler IR using the given schema object . | 228 | 16 |
226,912 | def pretty_print_gremlin ( gremlin ) : 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 ] for i in six . moves . xrange ( 0 , len ( too_many_parts ) - 1 , 2 ) ] parts . append ( too_many_parts [ - 1 ] ) # Put the . back on. for i in six . moves . xrange ( 1 , len ( parts ) ) : parts [ i ] = '.' + parts [ i ] indentation = 0 indentation_increment = 4 output = [ ] for current_part in parts : if any ( [ current_part . startswith ( '.out' ) , current_part . startswith ( '.in' ) , current_part . startswith ( '.ifThenElse' ) ] ) : indentation += indentation_increment elif current_part . startswith ( '.back' ) or current_part . startswith ( '.optional' ) : indentation -= indentation_increment if indentation < 0 : raise AssertionError ( u'Indentation became negative: {}' . format ( indentation ) ) output . append ( ( ' ' * indentation ) + current_part ) return '\n' . join ( output ) . strip ( ) | Return a human - readable representation of a gremlin command string . | 332 | 13 |
226,913 | def pretty_print_match ( match , parameterized = True ) : left_curly = '{{' if parameterized else '{' right_curly = '}}' if parameterized else '}' match = remove_custom_formatting ( match ) parts = re . split ( '({}|{})' . format ( left_curly , right_curly ) , match ) inside_braces = False indent_size = 4 indent = ' ' * indent_size output = [ parts [ 0 ] ] for current_index , current_part in enumerate ( parts [ 1 : ] ) : if current_part == left_curly : if inside_braces : raise AssertionError ( u'Found open-braces pair while already inside braces: ' u'{} {} {}' . format ( current_index , parts , match ) ) inside_braces = True output . append ( current_part + '\n' ) elif current_part == right_curly : if not inside_braces : raise AssertionError ( u'Found close-braces pair while not inside braces: ' u'{} {} {}' . format ( current_index , parts , match ) ) inside_braces = False output . append ( current_part ) else : if not inside_braces : stripped_part = current_part . lstrip ( ) if stripped_part . startswith ( '.' ) : # Strip whitespace before traversal steps. output . append ( stripped_part ) else : # Do not strip whitespace before e.g. the RETURN keyword. output . append ( current_part ) else : # Split out the keywords, initially getting rid of commas. separate_keywords = re . split ( ', ([a-z]+:)' , current_part ) # The first item in the separated list is the full first "keyword: value" pair. # For every subsequent item, the keyword and value are separated; join them # back together, outputting the comma, newline and indentation before them. output . append ( indent + separate_keywords [ 0 ] . lstrip ( ) ) for i in six . moves . xrange ( 1 , len ( separate_keywords ) - 1 , 2 ) : output . append ( ',\n{indent}{keyword} {value}' . format ( keyword = separate_keywords [ i ] . strip ( ) , value = separate_keywords [ i + 1 ] . strip ( ) , indent = indent ) ) output . append ( '\n' ) return '' . join ( output ) . strip ( ) | Return a human - readable representation of a parameterized MATCH query string . | 562 | 15 |
226,914 | def represent_float_as_str ( value ) : # 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 # # In [3]: str(1.2345678901234567) # Out[3]: '1.23456789012' # # The best way to ensure precision is not lost is to convert to string via Decimal: # https://github.com/mogui/pyorient/pull/226/files if not isinstance ( value , float ) : raise GraphQLInvalidArgumentError ( u'Attempting to represent a non-float as a float: ' u'{}' . format ( value ) ) with decimal . localcontext ( ) as ctx : ctx . prec = 20 # floats are max 80-bits wide = 20 significant digits return u'{:f}' . format ( decimal . Decimal ( value ) ) | Represent a float as a string without losing precision . | 253 | 10 |
226,915 | def coerce_to_decimal ( value ) : if isinstance ( value , decimal . Decimal ) : return value else : try : return decimal . Decimal ( value ) except decimal . InvalidOperation as e : raise GraphQLInvalidArgumentError ( e ) | Attempt to coerce the value to a Decimal or raise an error if unable to do so . | 56 | 20 |
226,916 | def make_replacement_visitor ( find_expression , replace_expression ) : def visitor_fn ( expression ) : """Return the replacement if this expression matches the expression we're looking for.""" if expression == find_expression : return replace_expression else : return expression return visitor_fn | Return a visitor function that replaces every instance of one expression with another one . | 61 | 15 |
226,917 | def make_type_replacement_visitor ( find_types , replacement_func ) : def visitor_fn ( expression ) : """Return a replacement expression if the original expression is of the correct type.""" if isinstance ( expression , find_types ) : return replacement_func ( expression ) else : return expression return visitor_fn | Return a visitor function that replaces expressions of a given type with new expressions . | 70 | 15 |
226,918 | def _validate_operator_name ( operator , supported_operators ) : if not isinstance ( operator , six . text_type ) : raise TypeError ( u'Expected operator as unicode string, got: {} {}' . format ( type ( operator ) . __name__ , operator ) ) if operator not in supported_operators : raise GraphQLCompilationError ( u'Unrecognized operator: {}' . format ( operator ) ) | Ensure the named operator is valid and supported . | 97 | 10 |
226,919 | def validate ( self ) : # 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 correctly representable and supported. if isinstance ( self . value , six . string_types ) : validate_safe_string ( self . value ) return # Literal ints are correctly representable and supported. if isinstance ( self . value , int ) : return # Literal empty lists, and non-empty lists of safe strings, are # correctly representable and supported. if isinstance ( self . value , list ) : if len ( self . value ) > 0 : for x in self . value : validate_safe_string ( x ) return raise GraphQLCompilationError ( u'Cannot represent literal: {}' . format ( self . value ) ) | Validate that the Literal is correctly representable . | 188 | 11 |
226,920 | def validate ( self ) : # 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: ' u'{}' . format ( self . variable_name ) ) if self . variable_name in RESERVED_MATCH_KEYWORDS : raise GraphQLCompilationError ( u'Cannot use reserved MATCH keyword {} as variable ' u'name!' . format ( self . variable_name ) ) validate_safe_string ( self . variable_name [ 1 : ] ) if not is_graphql_type ( self . inferred_type ) : raise ValueError ( u'Invalid value of "inferred_type": {}' . format ( self . inferred_type ) ) if isinstance ( self . inferred_type , GraphQLNonNull ) : raise ValueError ( u'GraphQL non-null types are not supported as "inferred_type": ' u'{}' . format ( self . inferred_type ) ) if isinstance ( self . inferred_type , GraphQLList ) : inner_type = strip_non_null_from_type ( self . inferred_type . of_type ) if GraphQLDate . is_same_type ( inner_type ) or GraphQLDateTime . is_same_type ( inner_type ) : # This is a compilation error rather than a ValueError as # it can be caused by an invalid GraphQL query on an otherwise valid schema. # In other words, it's an error in writing the GraphQL query, rather than # a programming error within the library. raise GraphQLCompilationError ( u'Lists of Date or DateTime cannot currently be represented as ' u'Variable objects: {}' . format ( self . inferred_type ) ) | Validate that the Variable is correctly representable . | 411 | 10 |
226,921 | def to_match ( self ) : 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 ( variable_with_no_dollar_sign ) , ) # We can't directly pass a Date or 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/javase/7/docs/api/java/text/SimpleDateFormat.html # For the semantics of the date() OrientDB SQL function, see: # http://orientdb.com/docs/last/SQL-Functions.html#date if GraphQLDate . is_same_type ( self . inferred_type ) : return u'date(%s, "%s")' % ( match_variable_name , STANDARD_DATE_FORMAT ) elif GraphQLDateTime . is_same_type ( self . inferred_type ) : return u'date(%s, "%s")' % ( match_variable_name , STANDARD_DATETIME_FORMAT ) else : return match_variable_name | Return a unicode object with the MATCH representation of this Variable . | 286 | 14 |
226,922 | def validate ( self ) : if not isinstance ( self . location , Location ) : raise TypeError ( u'Expected Location location, got: {} {}' . format ( type ( self . location ) . __name__ , self . location ) ) if self . location . field is None : raise AssertionError ( u'Received Location without a field: {}' . format ( self . location ) ) if not is_graphql_type ( self . field_type ) : raise ValueError ( u'Invalid value of "field_type": {}' . format ( self . field_type ) ) | Validate that the GlobalContextField is correctly representable . | 129 | 12 |
226,923 | def to_match ( self ) : 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_name , field_name ) | Return a unicode object with the MATCH representation of this GlobalContextField . | 71 | 16 |
226,924 | def to_match ( self ) : 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 , ) else : validate_safe_string ( field_name ) return u'$matched.%s.%s' % ( mark_name , field_name ) | Return a unicode object with the MATCH representation of this ContextField . | 99 | 15 |
226,925 | def validate ( self ) : if not isinstance ( self . location , Location ) : raise TypeError ( u'Expected Location location, got: {} {}' . format ( type ( self . location ) . __name__ , self . location ) ) if not self . location . field : raise ValueError ( u'Expected Location object that points to a field, got: ' u'{}' . format ( self . location ) ) if not is_graphql_type ( self . field_type ) : raise ValueError ( u'Invalid value of "field_type": {}' . format ( self . field_type ) ) stripped_field_type = strip_non_null_from_type ( self . field_type ) if isinstance ( stripped_field_type , GraphQLList ) : inner_type = strip_non_null_from_type ( stripped_field_type . of_type ) if GraphQLDate . is_same_type ( inner_type ) or GraphQLDateTime . is_same_type ( inner_type ) : # This is a compilation error rather than a ValueError as # it can be caused by an invalid GraphQL query on an otherwise valid schema. # In other words, it's an error in writing the GraphQL query, rather than # a programming error within the library. raise GraphQLCompilationError ( u'Lists of Date or DateTime cannot currently be represented as ' u'OutputContextField objects: {}' . format ( self . field_type ) ) | Validate that the OutputContextField is correctly representable . | 326 | 12 |
226,926 | def validate ( self ) : if not isinstance ( self . fold_scope_location , FoldScopeLocation ) : raise TypeError ( u'Expected FoldScopeLocation fold_scope_location, got: {} {}' . format ( type ( self . fold_scope_location ) , self . fold_scope_location ) ) if self . fold_scope_location . field is None : raise ValueError ( u'Expected FoldScopeLocation at a field, but got: {}' . format ( self . fold_scope_location ) ) if self . fold_scope_location . field == COUNT_META_FIELD_NAME : if not GraphQLInt . is_same_type ( self . field_type ) : raise TypeError ( u'Expected the _x_count meta-field to be of GraphQLInt type, but ' u'encountered type {} instead: {}' . format ( self . field_type , self . fold_scope_location ) ) else : if not isinstance ( self . field_type , GraphQLList ) : raise ValueError ( u'Invalid value of "field_type" for a field that is not ' u'a meta-field, expected a list type but got: {} {}' . format ( self . field_type , self . fold_scope_location ) ) inner_type = strip_non_null_from_type ( self . field_type . of_type ) if isinstance ( inner_type , GraphQLList ) : raise GraphQLCompilationError ( u'Outputting list-valued fields in a @fold context is currently not supported: ' u'{} {}' . format ( self . fold_scope_location , self . field_type . of_type ) ) | Validate that the FoldedContextField is correctly representable . | 377 | 13 |
226,927 | def validate ( self ) : if not isinstance ( self . fold_scope_location , FoldScopeLocation ) : raise TypeError ( u'Expected FoldScopeLocation fold_scope_location, got: {} {}' . format ( type ( self . fold_scope_location ) , self . fold_scope_location ) ) if self . fold_scope_location . field != COUNT_META_FIELD_NAME : raise AssertionError ( u'Unexpected field in the FoldScopeLocation of this ' u'FoldCountContextField object: {} {}' . format ( self . fold_scope_location , self ) ) | Validate that the FoldCountContextField is correctly representable . | 135 | 13 |
226,928 | def validate ( self ) : if not isinstance ( self . location , Location ) : raise TypeError ( u'Expected Location location, got: {} {}' . format ( type ( self . location ) . __name__ , self . location ) ) if self . location . field : raise ValueError ( u'Expected location to point to a vertex, ' u'but found a field: {}' . format ( self . location ) ) | Validate that the ContextFieldExistence is correctly representable . | 93 | 13 |
226,929 | def validate ( self ) : _validate_operator_name ( self . operator , UnaryTransformation . SUPPORTED_OPERATORS ) if not isinstance ( self . inner_expression , Expression ) : raise TypeError ( u'Expected Expression inner_expression, got {} {}' . format ( type ( self . inner_expression ) . __name__ , self . inner_expression ) ) | Validate that the UnaryTransformation is correctly representable . | 84 | 13 |
226,930 | def to_match ( self ) : self . validate ( ) translation_table = { u'size' : u'size()' , } match_operator = translation_table . get ( self . operator ) if not match_operator : raise AssertionError ( u'Unrecognized operator used: ' u'{} {}' . format ( self . operator , self ) ) template = u'%(inner)s.%(operator)s' args = { 'inner' : self . inner_expression . to_match ( ) , 'operator' : match_operator , } return template % args | Return a unicode object with the MATCH representation of this UnaryTransformation . | 129 | 17 |
226,931 | def validate ( self ) : _validate_operator_name ( self . operator , BinaryComposition . SUPPORTED_OPERATORS ) if not isinstance ( self . left , Expression ) : raise TypeError ( u'Expected Expression left, got: {} {} {}' . format ( type ( self . left ) . __name__ , self . left , self ) ) if not isinstance ( self . right , Expression ) : raise TypeError ( u'Expected Expression right, got: {} {}' . format ( type ( self . right ) . __name__ , self . right ) ) | Validate that the BinaryComposition is correctly representable . | 126 | 12 |
226,932 | def to_match ( self ) : self . validate ( ) # The MATCH versions of some operators require an inverted order of arguments. # pylint: disable=unused-variable regular_operator_format = '(%(left)s %(operator)s %(right)s)' inverted_operator_format = '(%(right)s %(operator)s %(left)s)' # noqa intersects_operator_format = '(%(operator)s(%(left)s, %(right)s).asList().size() > 0)' # pylint: enable=unused-variable # Null literals use 'is/is not' as (in)equality operators, while other values use '=/<>'. if any ( ( isinstance ( self . left , Literal ) and self . left . value is None , isinstance ( self . right , Literal ) and self . right . value is None ) ) : translation_table = { u'=' : ( u'IS' , regular_operator_format ) , u'!=' : ( u'IS NOT' , regular_operator_format ) , } else : translation_table = { u'=' : ( u'=' , regular_operator_format ) , u'!=' : ( u'<>' , regular_operator_format ) , u'>=' : ( u'>=' , regular_operator_format ) , u'<=' : ( u'<=' , regular_operator_format ) , u'>' : ( u'>' , regular_operator_format ) , u'<' : ( u'<' , regular_operator_format ) , u'+' : ( u'+' , regular_operator_format ) , u'||' : ( u'OR' , regular_operator_format ) , u'&&' : ( u'AND' , regular_operator_format ) , u'contains' : ( u'CONTAINS' , regular_operator_format ) , u'intersects' : ( u'intersect' , intersects_operator_format ) , u'has_substring' : ( None , None ) , # must be lowered into compatible form using LIKE # MATCH-specific operators u'LIKE' : ( u'LIKE' , regular_operator_format ) , u'INSTANCEOF' : ( u'INSTANCEOF' , regular_operator_format ) , } match_operator , format_spec = translation_table . get ( self . operator , ( None , None ) ) if not match_operator : raise AssertionError ( u'Unrecognized operator used: ' u'{} {}' . format ( self . operator , self ) ) return format_spec % dict ( operator = match_operator , left = self . left . to_match ( ) , right = self . right . to_match ( ) ) | Return a unicode object with the MATCH representation of this BinaryComposition . | 625 | 16 |
226,933 | def validate ( self ) : if not isinstance ( self . predicate , Expression ) : raise TypeError ( u'Expected Expression predicate, got: {} {}' . format ( type ( self . predicate ) . __name__ , self . predicate ) ) if not isinstance ( self . if_true , Expression ) : raise TypeError ( u'Expected Expression if_true, got: {} {}' . format ( type ( self . if_true ) . __name__ , self . if_true ) ) if not isinstance ( self . if_false , Expression ) : raise TypeError ( u'Expected Expression if_false, got: {} {}' . format ( type ( self . if_false ) . __name__ , self . if_false ) ) | Validate that the TernaryConditional is correctly representable . | 163 | 14 |
226,934 | def to_match ( self ) : self . validate ( ) # For MATCH, an additional validation step is needed -- we currently do not support # emitting MATCH code for TernaryConditional that contains another TernaryConditional # anywhere within the predicate expression. This is because the predicate expression # must be surrounded in quotes, and it is unclear whether nested/escaped quotes would work. def visitor_fn ( expression ) : """Visitor function that ensures the predicate does not contain TernaryConditionals.""" if isinstance ( expression , TernaryConditional ) : raise ValueError ( u'Cannot emit MATCH code for TernaryConditional that contains ' u'in its predicate another TernaryConditional: ' u'{} {}' . format ( expression , self ) ) return expression self . predicate . visit_and_update ( visitor_fn ) format_spec = u'if(eval("%(predicate)s"), %(if_true)s, %(if_false)s)' predicate_string = self . predicate . to_match ( ) if u'"' in predicate_string : raise AssertionError ( u'Found a double-quote within the predicate string, this would ' u'have terminated the if(eval()) early and should be fixed: ' u'{} {}' . format ( predicate_string , self ) ) return format_spec % dict ( predicate = predicate_string , if_true = self . if_true . to_match ( ) , if_false = self . if_false . to_match ( ) ) | Return a unicode object with the MATCH representation of this TernaryConditional . | 338 | 18 |
226,935 | def sanity_check_ir_blocks_from_frontend ( ir_blocks , query_metadata_table ) : if not ir_blocks : raise AssertionError ( u'Received no ir_blocks: {}' . format ( ir_blocks ) ) _sanity_check_fold_scope_locations_are_unique ( ir_blocks ) _sanity_check_no_nested_folds ( ir_blocks ) _sanity_check_query_root_block ( ir_blocks ) _sanity_check_output_source_follower_blocks ( ir_blocks ) _sanity_check_block_pairwise_constraints ( ir_blocks ) _sanity_check_mark_location_preceding_optional_traverse ( ir_blocks ) _sanity_check_every_location_is_marked ( ir_blocks ) _sanity_check_coerce_type_outside_of_fold ( ir_blocks ) _sanity_check_all_marked_locations_are_registered ( ir_blocks , query_metadata_table ) _sanity_check_registered_locations_parent_locations ( query_metadata_table ) | Assert that IR blocks originating from the frontend do not have nonsensical structure . | 261 | 16 |
226,936 | def _sanity_check_registered_locations_parent_locations ( query_metadata_table ) : for location , location_info in query_metadata_table . registered_locations : if ( location != query_metadata_table . root_location and not query_metadata_table . root_location . is_revisited_at ( location ) ) : # If the location is not the root location and is not a revisit of the root, # then it must have a parent location. if location_info . parent_location is None : raise AssertionError ( u'Found a location that is not the root location of the query ' u'or a revisit of the root, but does not have a parent: ' u'{} {}' . format ( location , location_info ) ) if location_info . parent_location is not None : # Make sure the parent_location is also registered. # If the location is not registered, the following line will raise an error. query_metadata_table . get_location_info ( location_info . parent_location ) | Assert that all registered locations parent locations are also registered . | 230 | 12 |
226,937 | def _sanity_check_all_marked_locations_are_registered ( ir_blocks , query_metadata_table ) : # Grab all the registered locations, then make sure that: # - Any location that appears in a MarkLocation block is also registered. # - There are no registered locations that do not appear in a MarkLocation block. registered_locations = { location for location , _ in query_metadata_table . registered_locations } ir_encountered_locations = { block . location for block in ir_blocks if isinstance ( block , MarkLocation ) } unregistered_locations = ir_encountered_locations - registered_locations unencountered_locations = registered_locations - ir_encountered_locations if unregistered_locations : raise AssertionError ( u'IR blocks unexpectedly contain locations not registered in the ' u'QueryMetadataTable: {}' . format ( unregistered_locations ) ) if unencountered_locations : raise AssertionError ( u'QueryMetadataTable unexpectedly contains registered locations that ' u'never appear in the IR blocks: {}' . format ( unencountered_locations ) ) | Assert that all locations in MarkLocation blocks have registered and valid metadata . | 259 | 15 |
226,938 | def _sanity_check_fold_scope_locations_are_unique ( ir_blocks ) : observed_locations = dict ( ) for block in ir_blocks : if isinstance ( block , Fold ) : alternate = observed_locations . get ( block . fold_scope_location , None ) if alternate is not None : raise AssertionError ( u'Found two Fold blocks with identical FoldScopeLocations: ' u'{} {} {}' . format ( alternate , block , ir_blocks ) ) observed_locations [ block . fold_scope_location ] = block | Assert that every FoldScopeLocation that exists on a Fold block is unique . | 126 | 16 |
226,939 | def _sanity_check_no_nested_folds ( ir_blocks ) : fold_seen = False for block in ir_blocks : if isinstance ( block , Fold ) : if fold_seen : raise AssertionError ( u'Found a nested Fold contexts: {}' . format ( ir_blocks ) ) else : fold_seen = True elif isinstance ( block , Unfold ) : if not fold_seen : raise AssertionError ( u'Found an Unfold block without a matching Fold: ' u'{}' . format ( ir_blocks ) ) else : fold_seen = False | Assert that there are no nested Fold contexts and that every Fold has a matching Unfold . | 133 | 19 |
226,940 | def _sanity_check_query_root_block ( ir_blocks ) : 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 isinstance ( block , QueryRoot ) : raise AssertionError ( u'Found QueryRoot after the first block: {}' . format ( ir_blocks ) ) | Assert that QueryRoot is always the first block and only the first block . | 107 | 16 |
226,941 | def _sanity_check_construct_result_block ( ir_blocks ) : if not isinstance ( ir_blocks [ - 1 ] , ConstructResult ) : raise AssertionError ( u'The last block was not ConstructResult: {}' . format ( ir_blocks ) ) for block in ir_blocks [ : - 1 ] : if isinstance ( block , ConstructResult ) : raise AssertionError ( u'Found ConstructResult before the last block: ' u'{}' . format ( ir_blocks ) ) | Assert that ConstructResult is always the last block and only the last block . | 113 | 16 |
226,942 | def _sanity_check_block_pairwise_constraints ( ir_blocks ) : 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 ) : raise AssertionError ( u'Found Filter after MarkLocation block: {}' . format ( ir_blocks ) ) # There's no point in marking the same location twice in a row. if isinstance ( first_block , MarkLocation ) and isinstance ( second_block , MarkLocation ) : raise AssertionError ( u'Found consecutive MarkLocation blocks: {}' . format ( ir_blocks ) ) # Traverse blocks with optional=True are immediately followed # by a MarkLocation, CoerceType or Filter block. if isinstance ( first_block , Traverse ) and first_block . optional : if not isinstance ( second_block , ( MarkLocation , CoerceType , Filter ) ) : raise AssertionError ( u'Expected MarkLocation, CoerceType or Filter after Traverse ' u'with optional=True. Found: {}' . format ( ir_blocks ) ) # Backtrack blocks with optional=True are immediately followed by a MarkLocation block. if isinstance ( first_block , Backtrack ) and first_block . optional : if not isinstance ( second_block , MarkLocation ) : raise AssertionError ( u'Expected MarkLocation after Backtrack with optional=True, ' u'but none was found: {}' . format ( ir_blocks ) ) # Recurse blocks are immediately preceded by a MarkLocation or Backtrack block. if isinstance ( second_block , Recurse ) : if not ( isinstance ( first_block , MarkLocation ) or isinstance ( first_block , Backtrack ) ) : raise AssertionError ( u'Expected MarkLocation or Backtrack before Recurse, but none ' u'was found: {}' . format ( ir_blocks ) ) | Assert that adjacent blocks obey all invariants . | 441 | 10 |
226,943 | def _sanity_check_mark_location_preceding_optional_traverse ( ir_blocks ) : # Once all fold blocks are removed, each optional Traverse must have # a MarkLocation block immediately before it. _ , new_ir_blocks = extract_folds_from_ir_blocks ( ir_blocks ) for first_block , second_block in pairwise ( new_ir_blocks ) : # Traverse blocks with optional=True are immediately preceded by a MarkLocation block. if isinstance ( second_block , Traverse ) and second_block . optional : if not isinstance ( first_block , MarkLocation ) : raise AssertionError ( u'Expected MarkLocation before Traverse with optional=True, ' u'but none was found: {}' . format ( ir_blocks ) ) | Assert that optional Traverse blocks are preceded by a MarkLocation . | 176 | 14 |
226,944 | def _sanity_check_every_location_is_marked ( ir_blocks ) : # 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 affects a # different position in the query. Such intervals include the following examples: # - from Fold to Unfold # - from QueryRoot to Traverse/Recurse # - from one Traverse to the next Traverse # - from Traverse to Backtrack found_start_block = False mark_location_blocks_count = 0 start_interval_types = ( QueryRoot , Traverse , Recurse , Fold ) end_interval_types = ( Backtrack , ConstructResult , Recurse , Traverse , Unfold ) for block in ir_blocks : # Terminate started intervals before opening new ones. if isinstance ( block , end_interval_types ) and found_start_block : found_start_block = False if mark_location_blocks_count != 1 : raise AssertionError ( u'Expected 1 MarkLocation block between traversals, found: ' u'{} {}' . format ( mark_location_blocks_count , ir_blocks ) ) # Now consider opening new intervals or processing MarkLocation blocks. if isinstance ( block , MarkLocation ) : mark_location_blocks_count += 1 elif isinstance ( block , start_interval_types ) : found_start_block = True mark_location_blocks_count = 0 | Ensure that every new location is marked with a MarkLocation block . | 323 | 14 |
226,945 | def _sanity_check_coerce_type_outside_of_fold ( ir_blocks ) : is_in_fold = False for first_block , second_block in pairwise ( ir_blocks ) : if isinstance ( first_block , Fold ) : is_in_fold = True if not is_in_fold and isinstance ( first_block , CoerceType ) : if not isinstance ( second_block , ( MarkLocation , Filter ) ) : raise AssertionError ( u'Expected MarkLocation or Filter after CoerceType, ' u'but none was found: {}' . format ( ir_blocks ) ) if isinstance ( second_block , Unfold ) : is_in_fold = False | Ensure that CoerceType not in a | 161 | 10 |
226,946 | def validate_supported_property_type_id ( property_name , property_type_id ) : if property_type_id not in PROPERTY_TYPE_ID_TO_NAME : raise AssertionError ( u'Property "{}" has unsupported property type id: ' u'{}' . format ( property_name , property_type_id ) ) | Ensure that the given property type_id is supported by the graph . | 79 | 15 |
226,947 | def _parse_bool_default_value ( property_name , default_value_string ) : lowercased_value_string = default_value_string . lower ( ) if lowercased_value_string in { '0' , 'false' } : return False elif lowercased_value_string in { '1' , 'true' } : return True else : raise AssertionError ( u'Unsupported default value for boolean property "{}": ' u'{}' . format ( property_name , default_value_string ) ) | Parse and return the default value for a boolean property . | 121 | 12 |
226,948 | def _parse_datetime_default_value ( property_name , default_value_string ) : # 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 provided value cannot be parsed correctly. parsed_value = time . strptime ( default_value_string , ORIENTDB_DATETIME_FORMAT ) return datetime . datetime ( parsed_value . tm_year , parsed_value . tm_mon , parsed_value . tm_mday , parsed_value . tm_hour , parsed_value . tm_min , parsed_value . tm_sec , 0 , None ) | Parse and return the default value for a datetime property . | 167 | 13 |
226,949 | def _parse_date_default_value ( property_name , default_value_string ) : # 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 provided value cannot be parsed correctly. parsed_value = time . strptime ( default_value_string , ORIENTDB_DATE_FORMAT ) return datetime . date ( parsed_value . tm_year , parsed_value . tm_mon , parsed_value . tm_mday ) | Parse and return the default value for a date property . | 132 | 12 |
226,950 | def parse_default_property_value ( property_name , property_type_id , default_value_string ) : if property_type_id == PROPERTY_TYPE_EMBEDDED_SET_ID and default_value_string == '{}' : return set ( ) elif property_type_id == PROPERTY_TYPE_EMBEDDED_LIST_ID and default_value_string == '[]' : return list ( ) elif ( property_type_id == PROPERTY_TYPE_STRING_ID and isinstance ( default_value_string , six . string_types ) ) : return default_value_string elif property_type_id == PROPERTY_TYPE_BOOLEAN_ID : return _parse_bool_default_value ( property_name , default_value_string ) elif property_type_id == PROPERTY_TYPE_DATETIME_ID : return _parse_datetime_default_value ( property_name , default_value_string ) elif property_type_id == PROPERTY_TYPE_DATE_ID : return _parse_date_default_value ( property_name , default_value_string ) else : raise AssertionError ( u'Unsupported default value for property "{}" with type id {}: ' u'{}' . format ( property_name , property_type_id , default_value_string ) ) | Parse the default value string into its proper form given the property type ID . | 316 | 16 |
226,951 | def _compile_graphql_generic ( language , lowering_func , query_emitter_func , schema , graphql_string , type_equivalence_hints , compiler_metadata ) : ir_and_metadata = graphql_to_ir ( schema , graphql_string , type_equivalence_hints = type_equivalence_hints ) lowered_ir_blocks = lowering_func ( ir_and_metadata . ir_blocks , ir_and_metadata . query_metadata_table , type_equivalence_hints = type_equivalence_hints ) query = query_emitter_func ( lowered_ir_blocks , compiler_metadata ) return CompilationResult ( query = query , language = language , output_metadata = ir_and_metadata . output_metadata , input_metadata = ir_and_metadata . input_metadata ) | Compile the GraphQL input lowering and emitting the query using the given functions . | 192 | 16 |
226,952 | def scalar_leaf_only ( operator ) : def decorator ( f ) : """Decorate the supplied function with the "scalar_leaf_only" logic.""" @ wraps ( f ) def wrapper ( filter_operation_info , context , parameters , * args , * * kwargs ) : """Check that the type on which the operator operates is a scalar leaf type.""" if 'operator' in kwargs : current_operator = kwargs [ 'operator' ] else : # Because "operator" is from an enclosing scope, it is immutable in Python 2.x. current_operator = operator if not is_leaf_type ( filter_operation_info . field_type ) : raise GraphQLCompilationError ( u'Cannot apply "{}" filter to non-leaf type' u'{}' . format ( current_operator , filter_operation_info ) ) return f ( filter_operation_info , context , parameters , * args , * * kwargs ) return wrapper return decorator | Ensure the filter function is only applied to scalar leaf types . | 220 | 14 |
226,953 | def vertex_field_only ( operator ) : def decorator ( f ) : """Decorate the supplied function with the "vertex_field_only" logic.""" @ wraps ( f ) def wrapper ( filter_operation_info , context , parameters , * args , * * kwargs ) : """Check that the type on which the operator operates is a vertex field type.""" if 'operator' in kwargs : current_operator = kwargs [ 'operator' ] else : # Because "operator" is from an enclosing scope, it is immutable in Python 2.x. current_operator = operator if not is_vertex_field_type ( filter_operation_info . field_type ) : raise GraphQLCompilationError ( u'Cannot apply "{}" filter to non-vertex field: ' u'{}' . format ( current_operator , filter_operation_info . field_name ) ) return f ( filter_operation_info , context , parameters , * args , * * kwargs ) return wrapper return decorator | Ensure the filter function is only applied to vertex field types . | 226 | 13 |
226,954 | def takes_parameters ( count ) : def decorator ( f ) : """Decorate the supplied function with the "takes_parameters" logic.""" @ wraps ( f ) def wrapper ( filter_operation_info , location , context , parameters , * args , * * kwargs ) : """Check that the supplied number of parameters equals the expected number.""" if len ( parameters ) != count : raise GraphQLCompilationError ( u'Incorrect number of parameters, expected {} got ' u'{}: {}' . format ( count , len ( parameters ) , parameters ) ) return f ( filter_operation_info , location , context , parameters , * args , * * kwargs ) return wrapper return decorator | Ensure the filter function has count parameters specified . | 154 | 10 |
226,955 | def _represent_argument ( directive_location , context , argument , inferred_type ) : # Regardless of what kind of variable we are dealing with, # we want to ensure its name is valid. argument_name = argument [ 1 : ] validate_safe_string ( argument_name ) if is_variable_argument ( argument ) : existing_type = context [ 'inputs' ] . get ( argument_name , inferred_type ) if not inferred_type . is_same_type ( existing_type ) : raise GraphQLCompilationError ( u'Incompatible types inferred for argument {}. ' u'The argument cannot simultaneously be ' u'{} and {}.' . format ( argument , existing_type , inferred_type ) ) context [ 'inputs' ] [ argument_name ] = inferred_type return ( expressions . Variable ( argument , inferred_type ) , None ) elif is_tag_argument ( argument ) : argument_context = context [ 'tags' ] . get ( argument_name , None ) if argument_context is None : raise GraphQLCompilationError ( u'Undeclared argument used: {}' . format ( argument ) ) location = argument_context [ 'location' ] optional = argument_context [ 'optional' ] tag_inferred_type = argument_context [ 'type' ] if location is None : raise AssertionError ( u'Argument declared without location: {}' . format ( argument_name ) ) if location . field is None : raise AssertionError ( u'Argument location is not a property field: {}' . format ( location ) ) if not inferred_type . is_same_type ( tag_inferred_type ) : raise GraphQLCompilationError ( u'The inferred type of the matching @tag directive does ' u'not match the inferred required type for this filter: ' u'{} vs {}' . format ( tag_inferred_type , inferred_type ) ) # Check whether the argument is a field on the vertex on which the directive is applied. field_is_local = directive_location . at_vertex ( ) == location . at_vertex ( ) non_existence_expression = None if optional : if field_is_local : non_existence_expression = expressions . FalseLiteral else : non_existence_expression = expressions . BinaryComposition ( u'=' , expressions . ContextFieldExistence ( location . at_vertex ( ) ) , expressions . FalseLiteral ) if field_is_local : representation = expressions . LocalField ( argument_name ) else : representation = expressions . ContextField ( location , tag_inferred_type ) return ( representation , non_existence_expression ) else : # If we want to support literal arguments, add them here. raise GraphQLCompilationError ( u'Non-argument type found: {}' . format ( argument ) ) | Return a two - element tuple that represents the argument to the directive being processed . | 621 | 16 |
226,956 | def _process_comparison_filter_directive ( filter_operation_info , location , context , parameters , operator = None ) : comparison_operators = { u'=' , u'!=' , u'>' , u'<' , u'>=' , u'<=' } if operator not in comparison_operators : raise AssertionError ( u'Expected a valid comparison operator ({}), but got ' u'{}' . format ( comparison_operators , operator ) ) filtered_field_type = filter_operation_info . field_type filtered_field_name = filter_operation_info . field_name argument_inferred_type = strip_non_null_from_type ( filtered_field_type ) argument_expression , non_existence_expression = _represent_argument ( location , context , parameters [ 0 ] , argument_inferred_type ) comparison_expression = expressions . BinaryComposition ( operator , expressions . LocalField ( filtered_field_name ) , argument_expression ) final_expression = None if non_existence_expression is not None : # The argument comes from an optional block and might not exist, # in which case the filter expression should evaluate to True. final_expression = expressions . BinaryComposition ( u'||' , non_existence_expression , comparison_expression ) else : final_expression = comparison_expression return blocks . Filter ( final_expression ) | Return a Filter basic block that performs the given comparison against the property field . | 303 | 15 |
226,957 | def _process_has_edge_degree_filter_directive ( filter_operation_info , location , context , parameters ) : if isinstance ( filter_operation_info . field_ast , InlineFragment ) : raise AssertionError ( u'Received InlineFragment AST node in "has_edge_degree" filter ' u'handler. This should have been caught earlier: ' u'{}' . format ( filter_operation_info . field_ast ) ) filtered_field_name = filter_operation_info . field_name if filtered_field_name is None or not is_vertex_field_name ( filtered_field_name ) : raise AssertionError ( u'Invalid value for "filtered_field_name" in "has_edge_degree" ' u'filter: {}' . format ( filtered_field_name ) ) if not is_vertex_field_type ( filter_operation_info . field_type ) : raise AssertionError ( u'Invalid value for "filter_operation_info.field_type" in ' u'"has_edge_degree" filter: {}' . format ( filter_operation_info ) ) argument = parameters [ 0 ] if not is_variable_argument ( argument ) : raise GraphQLCompilationError ( u'The "has_edge_degree" filter only supports runtime ' u'variable arguments. Tagged values are not supported.' u'Argument name: {}' . format ( argument ) ) argument_inferred_type = GraphQLInt argument_expression , non_existence_expression = _represent_argument ( location , context , argument , argument_inferred_type ) if non_existence_expression is not None : raise AssertionError ( u'Since we do not support tagged values, non_existence_expression ' u'should have been None. However, it was: ' u'{}' . format ( non_existence_expression ) ) # If no edges to the vertex field exist, the edges' field in the database may be "null". # We also don't know ahead of time whether the supplied argument is zero or not. # We have to accommodate these facts in our generated comparison code. # We construct the following expression to check if the edge degree is zero: # ({argument} == 0) && (edge_field == null) argument_is_zero = expressions . BinaryComposition ( u'=' , argument_expression , expressions . ZeroLiteral ) edge_field_is_null = expressions . BinaryComposition ( u'=' , expressions . LocalField ( filtered_field_name ) , expressions . NullLiteral ) edge_degree_is_zero = expressions . BinaryComposition ( u'&&' , argument_is_zero , edge_field_is_null ) # The following expression will check for a non-zero edge degree equal to the argument. # (edge_field != null) && (edge_field.size() == {argument}) edge_field_is_not_null = expressions . BinaryComposition ( u'!=' , expressions . LocalField ( filtered_field_name ) , expressions . NullLiteral ) edge_degree = expressions . UnaryTransformation ( u'size' , expressions . LocalField ( filtered_field_name ) ) edge_degree_matches_argument = expressions . BinaryComposition ( u'=' , edge_degree , argument_expression ) edge_degree_is_non_zero = expressions . BinaryComposition ( u'&&' , edge_field_is_not_null , edge_degree_matches_argument ) # We combine the two cases with a logical-or to handle both situations: filter_predicate = expressions . BinaryComposition ( u'||' , edge_degree_is_zero , edge_degree_is_non_zero ) return blocks . Filter ( filter_predicate ) | Return a Filter basic block that checks the degree of the edge to the given vertex field . | 836 | 18 |
226,958 | def _process_name_or_alias_filter_directive ( filter_operation_info , location , context , parameters ) : filtered_field_type = filter_operation_info . field_type if isinstance ( filtered_field_type , GraphQLUnionType ) : raise GraphQLCompilationError ( u'Cannot apply "name_or_alias" to union type ' u'{}' . format ( filtered_field_type ) ) current_type_fields = filtered_field_type . fields name_field = current_type_fields . get ( 'name' , None ) alias_field = current_type_fields . get ( 'alias' , None ) if not name_field or not alias_field : raise GraphQLCompilationError ( u'Cannot apply "name_or_alias" to type {} because it lacks a ' u'"name" or "alias" field.' . format ( filtered_field_type ) ) name_field_type = strip_non_null_from_type ( name_field . type ) alias_field_type = strip_non_null_from_type ( alias_field . type ) if not isinstance ( name_field_type , GraphQLScalarType ) : raise GraphQLCompilationError ( u'Cannot apply "name_or_alias" to type {} because its "name" ' u'field is not a scalar.' . format ( filtered_field_type ) ) if not isinstance ( alias_field_type , GraphQLList ) : raise GraphQLCompilationError ( u'Cannot apply "name_or_alias" to type {} because its ' u'"alias" field is not a list.' . format ( filtered_field_type ) ) alias_field_inner_type = strip_non_null_from_type ( alias_field_type . of_type ) if alias_field_inner_type != name_field_type : raise GraphQLCompilationError ( u'Cannot apply "name_or_alias" to type {} because the ' u'"name" field and the inner type of the "alias" field ' u'do not match: {} vs {}' . format ( filtered_field_type , name_field_type , alias_field_inner_type ) ) argument_inferred_type = name_field_type argument_expression , non_existence_expression = _represent_argument ( location , context , parameters [ 0 ] , argument_inferred_type ) check_against_name = expressions . BinaryComposition ( u'=' , expressions . LocalField ( 'name' ) , argument_expression ) check_against_alias = expressions . BinaryComposition ( u'contains' , expressions . LocalField ( 'alias' ) , argument_expression ) filter_predicate = expressions . BinaryComposition ( u'||' , check_against_name , check_against_alias ) if non_existence_expression is not None : # The argument comes from an optional block and might not exist, # in which case the filter expression should evaluate to True. filter_predicate = expressions . BinaryComposition ( u'||' , non_existence_expression , filter_predicate ) return blocks . Filter ( filter_predicate ) | Return a Filter basic block that checks for a match against an Entity s name or alias . | 704 | 18 |
226,959 | def _process_between_filter_directive ( filter_operation_info , location , context , parameters ) : filtered_field_type = filter_operation_info . field_type filtered_field_name = filter_operation_info . field_name argument_inferred_type = strip_non_null_from_type ( filtered_field_type ) arg1_expression , arg1_non_existence = _represent_argument ( location , context , parameters [ 0 ] , argument_inferred_type ) arg2_expression , arg2_non_existence = _represent_argument ( location , context , parameters [ 1 ] , argument_inferred_type ) lower_bound_clause = expressions . BinaryComposition ( u'>=' , expressions . LocalField ( filtered_field_name ) , arg1_expression ) if arg1_non_existence is not None : # The argument is optional, and if it doesn't exist, this side of the check should pass. lower_bound_clause = expressions . BinaryComposition ( u'||' , arg1_non_existence , lower_bound_clause ) upper_bound_clause = expressions . BinaryComposition ( u'<=' , expressions . LocalField ( filtered_field_name ) , arg2_expression ) if arg2_non_existence is not None : # The argument is optional, and if it doesn't exist, this side of the check should pass. upper_bound_clause = expressions . BinaryComposition ( u'||' , arg2_non_existence , upper_bound_clause ) filter_predicate = expressions . BinaryComposition ( u'&&' , lower_bound_clause , upper_bound_clause ) return blocks . Filter ( filter_predicate ) | Return a Filter basic block that checks that a field is between two values inclusive . | 380 | 16 |
226,960 | def _process_in_collection_filter_directive ( filter_operation_info , location , context , parameters ) : filtered_field_type = filter_operation_info . field_type filtered_field_name = filter_operation_info . field_name argument_inferred_type = GraphQLList ( strip_non_null_from_type ( filtered_field_type ) ) argument_expression , non_existence_expression = _represent_argument ( location , context , parameters [ 0 ] , argument_inferred_type ) filter_predicate = expressions . BinaryComposition ( u'contains' , argument_expression , expressions . LocalField ( filtered_field_name ) ) if non_existence_expression is not None : # The argument comes from an optional block and might not exist, # in which case the filter expression should evaluate to True. filter_predicate = expressions . BinaryComposition ( u'||' , non_existence_expression , filter_predicate ) return blocks . Filter ( filter_predicate ) | Return a Filter basic block that checks for a value s existence in a collection . | 221 | 16 |
226,961 | def _process_has_substring_filter_directive ( filter_operation_info , location , context , parameters ) : filtered_field_type = filter_operation_info . field_type filtered_field_name = filter_operation_info . field_name if not strip_non_null_from_type ( filtered_field_type ) . is_same_type ( GraphQLString ) : raise GraphQLCompilationError ( u'Cannot apply "has_substring" to non-string ' u'type {}' . format ( filtered_field_type ) ) argument_inferred_type = GraphQLString argument_expression , non_existence_expression = _represent_argument ( location , context , parameters [ 0 ] , argument_inferred_type ) filter_predicate = expressions . BinaryComposition ( u'has_substring' , expressions . LocalField ( filtered_field_name ) , argument_expression ) if non_existence_expression is not None : # The argument comes from an optional block and might not exist, # in which case the filter expression should evaluate to True. filter_predicate = expressions . BinaryComposition ( u'||' , non_existence_expression , filter_predicate ) return blocks . Filter ( filter_predicate ) | Return a Filter basic block that checks if the directive arg is a substring of the field . | 274 | 19 |
226,962 | def _process_contains_filter_directive ( filter_operation_info , location , context , parameters ) : filtered_field_type = filter_operation_info . field_type filtered_field_name = filter_operation_info . field_name base_field_type = strip_non_null_from_type ( filtered_field_type ) if not isinstance ( base_field_type , GraphQLList ) : raise GraphQLCompilationError ( u'Cannot apply "contains" to non-list ' u'type {}' . format ( filtered_field_type ) ) argument_inferred_type = strip_non_null_from_type ( base_field_type . of_type ) argument_expression , non_existence_expression = _represent_argument ( location , context , parameters [ 0 ] , argument_inferred_type ) filter_predicate = expressions . BinaryComposition ( u'contains' , expressions . LocalField ( filtered_field_name ) , argument_expression ) if non_existence_expression is not None : # The argument comes from an optional block and might not exist, # in which case the filter expression should evaluate to True. filter_predicate = expressions . BinaryComposition ( u'||' , non_existence_expression , filter_predicate ) return blocks . Filter ( filter_predicate ) | Return a Filter basic block that checks if the directive arg is contained in the field . | 294 | 17 |
226,963 | def _process_intersects_filter_directive ( filter_operation_info , location , context , parameters ) : filtered_field_type = filter_operation_info . field_type filtered_field_name = filter_operation_info . field_name argument_inferred_type = strip_non_null_from_type ( filtered_field_type ) if not isinstance ( argument_inferred_type , GraphQLList ) : raise GraphQLCompilationError ( u'Cannot apply "intersects" to non-list ' u'type {}' . format ( filtered_field_type ) ) argument_expression , non_existence_expression = _represent_argument ( location , context , parameters [ 0 ] , argument_inferred_type ) filter_predicate = expressions . BinaryComposition ( u'intersects' , expressions . LocalField ( filtered_field_name ) , argument_expression ) if non_existence_expression is not None : # The argument comes from an optional block and might not exist, # in which case the filter expression should evaluate to True. filter_predicate = expressions . BinaryComposition ( u'||' , non_existence_expression , filter_predicate ) return blocks . Filter ( filter_predicate ) | Return a Filter basic block that checks if the directive arg and the field intersect . | 272 | 16 |
226,964 | def is_filter_with_outer_scope_vertex_field_operator ( directive ) : if directive . name . value != 'filter' : return False op_name , _ = _get_filter_op_name_and_values ( directive ) return op_name in OUTER_SCOPE_VERTEX_FIELD_OPERATORS | Return True if we have a filter directive whose operator applies to the outer scope . | 74 | 16 |
226,965 | def process_filter_directive ( filter_operation_info , location , context ) : op_name , operator_params = _get_filter_op_name_and_values ( filter_operation_info . directive ) non_comparison_filters = { u'name_or_alias' : _process_name_or_alias_filter_directive , u'between' : _process_between_filter_directive , u'in_collection' : _process_in_collection_filter_directive , u'has_substring' : _process_has_substring_filter_directive , u'contains' : _process_contains_filter_directive , u'intersects' : _process_intersects_filter_directive , u'has_edge_degree' : _process_has_edge_degree_filter_directive , } all_recognized_filters = frozenset ( non_comparison_filters . keys ( ) ) | COMPARISON_OPERATORS if all_recognized_filters != ALL_OPERATORS : unrecognized_filters = ALL_OPERATORS - all_recognized_filters raise AssertionError ( u'Some filtering operators are defined but do not have an associated ' u'processing function. This is a bug: {}' . format ( unrecognized_filters ) ) if op_name in COMPARISON_OPERATORS : process_func = partial ( _process_comparison_filter_directive , operator = op_name ) else : process_func = non_comparison_filters . get ( op_name , None ) if process_func is None : raise GraphQLCompilationError ( u'Unknown op_name for filter directive: {}' . format ( op_name ) ) # Operators that do not affect the inner scope require a field name to which they apply. # There is no field name on InlineFragment ASTs, which is why only operators that affect # the inner scope make semantic sense when applied to InlineFragments. # Here, we ensure that we either have a field name to which the filter applies, # or that the operator affects the inner scope. if ( filter_operation_info . field_name is None and op_name not in INNER_SCOPE_VERTEX_FIELD_OPERATORS ) : raise GraphQLCompilationError ( u'The filter with op_name "{}" must be applied on a field. ' u'It may not be applied on a type coercion.' . format ( op_name ) ) fields = ( ( filter_operation_info . field_name , ) if op_name != 'name_or_alias' else ( 'name' , 'alias' ) ) context [ 'metadata' ] . record_filter_info ( location , FilterInfo ( fields = fields , op_name = op_name , args = tuple ( operator_params ) ) ) return process_func ( filter_operation_info , location , context , operator_params ) | Return a Filter basic block that corresponds to the filter operation in the directive . | 661 | 15 |
226,966 | def get_schema_type_name ( node , context ) : query_path = node . query_path if query_path not in context . query_path_to_location_info : raise AssertionError ( u'Unable to find type name for query path {} with context {}.' . format ( query_path , context ) ) location_info = context . query_path_to_location_info [ query_path ] return location_info . type . name | Return the GraphQL type name of a node . | 102 | 10 |
226,967 | def get_node_at_path ( query_path , context ) : if query_path not in context . query_path_to_node : raise AssertionError ( u'Unable to find SqlNode for query path {} with context {}.' . format ( query_path , context ) ) node = context . query_path_to_node [ query_path ] return node | Return the SqlNode associated with the query path . | 83 | 11 |
226,968 | def try_get_column ( column_name , node , context ) : selectable = get_node_selectable ( node , context ) if not hasattr ( selectable , 'c' ) : raise AssertionError ( u'Selectable "{}" does not have a column collection. Context is {}.' . format ( selectable , context ) ) return selectable . c . get ( column_name , None ) | Attempt to get a column by name from the selectable . | 89 | 12 |
226,969 | def get_column ( column_name , node , context ) : column = try_get_column ( column_name , node , context ) if column is None : selectable = get_node_selectable ( node , context ) raise AssertionError ( u'Column "{}" not found in selectable "{}". Columns present are {}. ' u'Context is {}.' . format ( column_name , selectable . original , [ col . name for col in selectable . c ] , context ) ) return column | Get a column by name from the selectable . | 111 | 10 |
226,970 | def get_unique_directives ( ast ) : if not ast . directives : return dict ( ) result = dict ( ) for directive_obj in ast . directives : directive_name = directive_obj . name . value if directive_name in ALLOWED_DUPLICATED_DIRECTIVES : pass # We don't return these. elif directive_name in result : raise GraphQLCompilationError ( u'Directive was unexpectedly applied twice in the same ' u'location: {} {}' . format ( directive_name , ast . directives ) ) else : result [ directive_name ] = directive_obj return result | Return a dict of directive name to directive object for the given AST node . | 133 | 15 |
226,971 | def get_local_filter_directives ( ast , current_schema_type , inner_vertex_fields ) : result = [ ] if ast . directives : # it'll be None if the AST has no directives at that node for directive_obj in ast . directives : # Of all filters that appear *on the field itself*, only the ones that apply # to the outer scope are not considered "local" and are not to be returned. if directive_obj . name . value == 'filter' : filtered_field_name = get_ast_field_name_or_none ( ast ) if is_filter_with_outer_scope_vertex_field_operator ( directive_obj ) : # We found a filter that affects the outer scope vertex. Let's make sure # we are at a vertex field. If we are actually at a property field, # that is a compilation error. if not is_vertex_field_type ( current_schema_type ) : raise GraphQLCompilationError ( u'Found disallowed filter on a property field: {} {} ' u'{}' . format ( directive_obj , current_schema_type , filtered_field_name ) ) elif isinstance ( ast , InlineFragment ) : raise GraphQLCompilationError ( u'Found disallowed filter on a type coercion: {} ' u'{}' . format ( directive_obj , current_schema_type ) ) else : # The filter is valid and non-local, since it is applied at this AST node # but affects the outer scope vertex field. Skip over it. pass else : operation = FilterOperationInfo ( directive = directive_obj , field_name = filtered_field_name , field_type = current_schema_type , field_ast = ast ) result . append ( operation ) if inner_vertex_fields : # allow the argument to be None for inner_ast in inner_vertex_fields : for directive_obj in inner_ast . directives : # Of all filters that appear on an inner vertex field, only the ones that apply # to the outer scope are "local" to the outer field and therefore to be returned. if is_filter_with_outer_scope_vertex_field_operator ( directive_obj ) : # The inner AST must not be an InlineFragment, so it must have a field name. filtered_field_name = get_ast_field_name ( inner_ast ) filtered_field_type = get_vertex_field_type ( current_schema_type , filtered_field_name ) operation = FilterOperationInfo ( directive = directive_obj , field_name = filtered_field_name , field_type = filtered_field_type , field_ast = inner_ast ) result . append ( operation ) return result | Get all filter directives that apply to the current field . | 604 | 11 |
226,972 | def validate_property_directives ( directives ) : for directive_name in six . iterkeys ( directives ) : if directive_name in VERTEX_ONLY_DIRECTIVES : raise GraphQLCompilationError ( u'Found vertex-only directive {} set on property.' . format ( directive_name ) ) | Validate the directives that appear at a property field . | 68 | 11 |
226,973 | def validate_vertex_directives ( directives ) : for directive_name in six . iterkeys ( directives ) : if directive_name in PROPERTY_ONLY_DIRECTIVES : raise GraphQLCompilationError ( u'Found property-only directive {} set on vertex.' . format ( directive_name ) ) | Validate the directives that appear at a vertex field . | 69 | 11 |
226,974 | def validate_root_vertex_directives ( root_ast ) : directives_present_at_root = set ( ) for directive_obj in root_ast . directives : directive_name = directive_obj . name . value if is_filter_with_outer_scope_vertex_field_operator ( directive_obj ) : raise GraphQLCompilationError ( u'Found a filter directive with an operator that is not' u'allowed on the root vertex: {}' . format ( directive_obj ) ) directives_present_at_root . add ( directive_name ) disallowed_directives = directives_present_at_root & VERTEX_DIRECTIVES_PROHIBITED_ON_ROOT if disallowed_directives : raise GraphQLCompilationError ( u'Found prohibited directives on root vertex: ' u'{}' . format ( disallowed_directives ) ) | Validate the directives that appear at the root vertex field . | 196 | 12 |
226,975 | def validate_vertex_field_directive_interactions ( parent_location , vertex_field_name , directives ) : fold_directive = directives . get ( 'fold' , None ) optional_directive = directives . get ( 'optional' , None ) output_source_directive = directives . get ( 'output_source' , None ) recurse_directive = directives . get ( 'recurse' , None ) if fold_directive and optional_directive : raise GraphQLCompilationError ( u'@fold and @optional may not appear at the same ' u'vertex field! Parent location: {}, vertex field name: {}' . format ( parent_location , vertex_field_name ) ) if fold_directive and output_source_directive : raise GraphQLCompilationError ( u'@fold and @output_source may not appear at the same ' u'vertex field! Parent location: {}, vertex field name: {}' . format ( parent_location , vertex_field_name ) ) if fold_directive and recurse_directive : raise GraphQLCompilationError ( u'@fold and @recurse may not appear at the same ' u'vertex field! Parent location: {}, vertex field name: {}' . format ( parent_location , vertex_field_name ) ) if optional_directive and output_source_directive : raise GraphQLCompilationError ( u'@optional and @output_source may not appear at the same ' u'vertex field! Parent location: {}, vertex field name: {}' . format ( parent_location , vertex_field_name ) ) if optional_directive and recurse_directive : raise GraphQLCompilationError ( u'@optional and @recurse may not appear at the same ' u'vertex field! Parent location: {}, vertex field name: {}' . format ( parent_location , vertex_field_name ) ) | Ensure that the specified vertex field directives are not mutually disallowed . | 425 | 14 |
226,976 | def validate_vertex_field_directive_in_context ( parent_location , vertex_field_name , directives , context ) : fold_directive = directives . get ( 'fold' , None ) optional_directive = directives . get ( 'optional' , None ) recurse_directive = directives . get ( 'recurse' , None ) output_source_directive = directives . get ( 'output_source' , None ) fold_context = 'fold' in context optional_context = 'optional' in context output_source_context = 'output_source' in context if fold_directive and fold_context : raise GraphQLCompilationError ( u'@fold is not allowed within a @fold traversal! ' u'Parent location: {}, vertex field name: {}' . format ( parent_location , vertex_field_name ) ) if optional_directive and fold_context : raise GraphQLCompilationError ( u'@optional is not allowed within a @fold traversal! ' u'Parent location: {}, vertex field name: {}' . format ( parent_location , vertex_field_name ) ) if output_source_directive and fold_context : raise GraphQLCompilationError ( u'@output_source is not allowed within a @fold traversal! ' u'Parent location: {}, vertex field name: {}' . format ( parent_location , vertex_field_name ) ) if recurse_directive and fold_context : raise GraphQLCompilationError ( u'@recurse is not allowed within a @fold traversal! ' u'Parent location: {}, vertex field name: {}' . format ( parent_location , vertex_field_name ) ) if output_source_context and not fold_directive : raise GraphQLCompilationError ( u'Found non-fold vertex field after the vertex marked ' u'output source! Parent location: {}, vertex field name: {}' . format ( parent_location , vertex_field_name ) ) if optional_context and fold_directive : raise GraphQLCompilationError ( u'@fold is not allowed within a @optional traversal! ' u'Parent location: {}, vertex field name: {}' . format ( parent_location , vertex_field_name ) ) if optional_context and output_source_directive : raise GraphQLCompilationError ( u'@output_source is not allowed within a @optional ' u'traversal! Parent location: {}, vertex field name: {}' . format ( parent_location , vertex_field_name ) ) | Ensure that the specified vertex field directives are allowed in the current context . | 562 | 15 |
226,977 | def _safe_match_string ( value ) : if not isinstance ( value , six . string_types ) : if isinstance ( value , bytes ) : # should only happen in py3 value = value . decode ( 'utf-8' ) else : raise GraphQLInvalidArgumentError ( u'Attempting to convert a non-string into a string: ' u'{}' . format ( value ) ) # Using JSON encoding means that all unicode literals and special chars # (e.g. newlines and backslashes) are replaced by appropriate escape sequences. # JSON has the same escaping rules as MATCH / SQL, so no further escaping is necessary. return json . dumps ( value ) | Sanitize and represent a string argument in MATCH . | 150 | 12 |
226,978 | def _safe_match_date_and_datetime ( graphql_type , expected_python_types , value ) : # Python datetime.datetime is a subclass of datetime.date, # but in this case, the two are not interchangeable. # Rather than using isinstance, we will therefore check for exact type equality. value_type = type ( value ) if not any ( value_type == x for x in expected_python_types ) : raise GraphQLInvalidArgumentError ( u'Expected value to be exactly one of ' u'python types {}, but was {}: ' u'{}' . format ( expected_python_types , value_type , value ) ) # The serialize() method of GraphQLDate and GraphQLDateTime produces the correct # ISO-8601 format that MATCH expects. We then simply represent it as a regular string. try : serialized_value = graphql_type . serialize ( value ) except ValueError as e : raise GraphQLInvalidArgumentError ( e ) return _safe_match_string ( serialized_value ) | Represent date and datetime objects as MATCH strings . | 234 | 11 |
226,979 | def _safe_match_list ( inner_type , argument_value ) : stripped_type = strip_non_null_from_type ( inner_type ) if isinstance ( stripped_type , GraphQLList ) : raise GraphQLInvalidArgumentError ( u'MATCH does not currently support nested lists, ' u'but inner type was {}: ' u'{}' . format ( inner_type , argument_value ) ) if not isinstance ( argument_value , list ) : raise GraphQLInvalidArgumentError ( u'Attempting to represent a non-list as a list: ' u'{}' . format ( argument_value ) ) components = ( _safe_match_argument ( stripped_type , x ) for x in argument_value ) return u'[' + u',' . join ( components ) + u']' | Represent the list of inner_type objects in MATCH form . | 182 | 13 |
226,980 | def insert_arguments_into_match_query ( compilation_result , arguments ) : if compilation_result . language != MATCH_LANGUAGE : raise AssertionError ( u'Unexpected query output language: {}' . format ( compilation_result ) ) base_query = compilation_result . query argument_types = compilation_result . input_metadata # The arguments are assumed to have already been validated against the query. sanitized_arguments = { key : _safe_match_argument ( argument_types [ key ] , value ) for key , value in six . iteritems ( arguments ) } return base_query . format ( * * sanitized_arguments ) | Insert the arguments into the compiled MATCH query to form a complete query . | 145 | 15 |
226,981 | def get_table ( self , schema_type ) : table_name = schema_type . lower ( ) if not self . has_table ( table_name ) : raise exceptions . GraphQLCompilationError ( 'No Table found in SQLAlchemy metadata for table name "{}"' . format ( table_name ) ) return self . table_name_to_table [ table_name ] | Retrieve a SQLAlchemy table based on the supplied GraphQL schema type name . | 84 | 17 |
226,982 | def _per_location_tuple_to_step ( ir_tuple ) : root_block = ir_tuple [ 0 ] if not isinstance ( root_block , root_block_types ) : raise AssertionError ( u'Unexpected root block type for MatchStep: ' u'{} {}' . format ( root_block , ir_tuple ) ) coerce_type_block = None where_block = None as_block = None for block in ir_tuple [ 1 : ] : if isinstance ( block , CoerceType ) : if coerce_type_block is not None : raise AssertionError ( u'Unexpectedly found two blocks eligible for "class" clause: ' u'{} {} {}' . format ( block , coerce_type_block , ir_tuple ) ) coerce_type_block = block elif isinstance ( block , MarkLocation ) : if as_block is not None : raise AssertionError ( u'Unexpectedly found two blocks eligible for "as" clause: ' u'{} {} {}' . format ( block , as_block , ir_tuple ) ) as_block = block elif isinstance ( block , Filter ) : if where_block is not None : raise AssertionError ( u'Unexpectedly found two blocks eligible for "where" clause: ' u'{} {} {}' . format ( block , as_block , ir_tuple ) ) # Filter always comes before MarkLocation in a given MatchStep. if as_block is not None : raise AssertionError ( u'Unexpectedly found MarkLocation before Filter in ' u'MatchStep: {} {} {}' . format ( block , where_block , ir_tuple ) ) where_block = block else : raise AssertionError ( u'Unexpected block encountered: {} {}' . format ( block , ir_tuple ) ) step = MatchStep ( root_block = root_block , coerce_type_block = coerce_type_block , where_block = where_block , as_block = as_block ) # MatchSteps with Backtrack as the root block should only contain MarkLocation, # and not do filtering or type coercion. if isinstance ( root_block , Backtrack ) : if where_block is not None or coerce_type_block is not None : raise AssertionError ( u'Unexpected blocks in Backtrack-based MatchStep: {}' . format ( step ) ) return step | Construct a MatchStep from a tuple of its constituent blocks . | 546 | 12 |
226,983 | def _split_ir_into_match_steps ( pruned_ir_blocks ) : output = [ ] current_tuple = None for block in pruned_ir_blocks : if isinstance ( block , OutputSource ) : # OutputSource blocks do not require any MATCH code, and only serve to help # optimizations and debugging. Simply omit them at this stage. continue elif isinstance ( block , root_block_types ) : if current_tuple is not None : output . append ( current_tuple ) current_tuple = ( block , ) elif isinstance ( block , ( CoerceType , Filter , MarkLocation ) ) : current_tuple += ( block , ) else : raise AssertionError ( u'Unexpected block type when converting to MATCH query: ' u'{} {}' . format ( block , pruned_ir_blocks ) ) if current_tuple is None : raise AssertionError ( u'current_tuple was unexpectedly None: {}' . format ( pruned_ir_blocks ) ) output . append ( current_tuple ) return [ _per_location_tuple_to_step ( x ) for x in output ] | Split a list of IR blocks into per - location MATCH steps . | 258 | 14 |
226,984 | def _split_match_steps_into_match_traversals ( match_steps ) : output = [ ] current_list = None for step in match_steps : if isinstance ( step . root_block , QueryRoot ) : if current_list is not None : output . append ( current_list ) current_list = [ step ] else : current_list . append ( step ) if current_list is None : raise AssertionError ( u'current_list was unexpectedly None: {}' . format ( match_steps ) ) output . append ( current_list ) return output | Split a list of MatchSteps into multiple lists each denoting a single MATCH traversal . | 126 | 20 |
226,985 | def convert_to_match_query ( ir_blocks ) : output_block = ir_blocks [ - 1 ] if not isinstance ( output_block , ConstructResult ) : raise AssertionError ( u'Expected last IR block to be ConstructResult, found: ' u'{} {}' . format ( output_block , ir_blocks ) ) ir_except_output = ir_blocks [ : - 1 ] folds , ir_except_output_and_folds = extract_folds_from_ir_blocks ( ir_except_output ) # Extract WHERE Filter global_operation_ir_blocks_tuple = _extract_global_operations ( ir_except_output_and_folds ) global_operation_blocks , pruned_ir_blocks = global_operation_ir_blocks_tuple if len ( global_operation_blocks ) > 1 : raise AssertionError ( u'Received IR blocks with multiple global operation blocks. Only one ' u'is allowed: {} {}' . format ( global_operation_blocks , ir_blocks ) ) if len ( global_operation_blocks ) == 1 : if not isinstance ( global_operation_blocks [ 0 ] , Filter ) : raise AssertionError ( u'Received non-Filter global operation block. {}' . format ( global_operation_blocks [ 0 ] ) ) where_block = global_operation_blocks [ 0 ] else : where_block = None match_steps = _split_ir_into_match_steps ( pruned_ir_blocks ) match_traversals = _split_match_steps_into_match_traversals ( match_steps ) return MatchQuery ( match_traversals = match_traversals , folds = folds , output_block = output_block , where_block = where_block , ) | Convert the list of IR blocks into a MatchQuery object for easier manipulation . | 398 | 16 |
226,986 | def insert_arguments_into_sql_query ( compilation_result , arguments ) : if compilation_result . language != SQL_LANGUAGE : raise AssertionError ( u'Unexpected query output language: {}' . format ( compilation_result ) ) base_query = compilation_result . query return base_query . params ( * * arguments ) | Insert the arguments into the compiled SQL query to form a complete query . | 77 | 14 |
226,987 | def convert_coerce_type_to_instanceof_filter ( coerce_type_block ) : coerce_type_target = get_only_element_from_collection ( coerce_type_block . target_class ) # INSTANCEOF requires the target class to be passed in as a string, # so we make the target class a string literal. new_predicate = BinaryComposition ( u'INSTANCEOF' , LocalField ( '@this' ) , Literal ( coerce_type_target ) ) return Filter ( new_predicate ) | Create an INSTANCEOF Filter block from a CoerceType block . | 125 | 16 |
226,988 | def convert_coerce_type_and_add_to_where_block ( coerce_type_block , where_block ) : instanceof_filter = convert_coerce_type_to_instanceof_filter ( coerce_type_block ) if where_block : # There was already a Filter block -- we'll merge the two predicates together. return Filter ( BinaryComposition ( u'&&' , instanceof_filter . predicate , where_block . predicate ) ) else : return instanceof_filter | Create an INSTANCEOF Filter from a CoerceType adding to an existing Filter if any . | 113 | 21 |
226,989 | def expression_list_to_conjunction ( expression_list ) : if not isinstance ( expression_list , list ) : raise AssertionError ( u'Expected `list`, Received {}.' . format ( expression_list ) ) if len ( expression_list ) == 0 : return TrueLiteral if not isinstance ( expression_list [ 0 ] , Expression ) : raise AssertionError ( u'Non-Expression object {} found in expression_list' . format ( expression_list [ 0 ] ) ) if len ( expression_list ) == 1 : return expression_list [ 0 ] else : return BinaryComposition ( u'&&' , expression_list_to_conjunction ( expression_list [ 1 : ] ) , expression_list [ 0 ] ) | Convert a list of expressions to an Expression that is the conjunction of all of them . | 168 | 18 |
226,990 | def construct_where_filter_predicate ( query_metadata_table , simple_optional_root_info ) : inner_location_name_to_where_filter = { } for root_location , root_info_dict in six . iteritems ( simple_optional_root_info ) : inner_location_name = root_info_dict [ 'inner_location_name' ] edge_field = root_info_dict [ 'edge_field' ] optional_edge_location = root_location . navigate_to_field ( edge_field ) optional_edge_where_filter = _filter_orientdb_simple_optional_edge ( query_metadata_table , optional_edge_location , inner_location_name ) inner_location_name_to_where_filter [ inner_location_name ] = optional_edge_where_filter # Sort expressions by inner_location_name to obtain deterministic order where_filter_expressions = [ inner_location_name_to_where_filter [ key ] for key in sorted ( inner_location_name_to_where_filter . keys ( ) ) ] return expression_list_to_conjunction ( where_filter_expressions ) | Return an Expression that is True if and only if each simple optional filter is True . | 260 | 17 |
226,991 | def construct_optional_traversal_tree ( complex_optional_roots , location_to_optional_roots ) : tree = OptionalTraversalTree ( complex_optional_roots ) for optional_root_locations_stack in six . itervalues ( location_to_optional_roots ) : tree . insert ( list ( optional_root_locations_stack ) ) return tree | Return a tree of complex optional root locations . | 84 | 9 |
226,992 | def validate ( self ) : if not isinstance ( self . field , LocalField ) : raise TypeError ( u'Expected LocalField field, got: {} {}' . format ( type ( self . field ) . __name__ , self . field ) ) if not isinstance ( self . lower_bound , Expression ) : raise TypeError ( u'Expected Expression lower_bound, got: {} {}' . format ( type ( self . lower_bound ) . __name__ , self . lower_bound ) ) if not isinstance ( self . upper_bound , Expression ) : raise TypeError ( u'Expected Expression upper_bound, got: {} {}' . format ( type ( self . upper_bound ) . __name__ , self . upper_bound ) ) | Validate that the Between Expression is correctly representable . | 165 | 11 |
226,993 | def to_match ( self ) : template = u'({field_name} BETWEEN {lower_bound} AND {upper_bound})' return template . format ( field_name = self . field . to_match ( ) , lower_bound = self . lower_bound . to_match ( ) , upper_bound = self . upper_bound . to_match ( ) ) | Return a unicode object with the MATCH representation of this BetweenClause . | 83 | 16 |
226,994 | def insert ( self , optional_root_locations_path ) : encountered_simple_optional = False parent_location = self . _root_location for optional_root_location in optional_root_locations_path : if encountered_simple_optional : raise AssertionError ( u'Encountered simple optional root location {} in path, but' u'further locations are present. This should not happen: {}' . format ( optional_root_location , optional_root_locations_path ) ) if optional_root_location not in self . _location_to_children : # Simple optionals are ignored. # There should be no complex optionals after a simple optional. encountered_simple_optional = True else : self . _location_to_children [ parent_location ] . add ( optional_root_location ) parent_location = optional_root_location | Insert a path of optional Locations into the tree . | 187 | 10 |
226,995 | def emit_code_from_ir ( sql_query_tree , compiler_metadata ) : context = CompilationContext ( query_path_to_selectable = dict ( ) , query_path_to_location_info = sql_query_tree . query_path_to_location_info , query_path_to_output_fields = sql_query_tree . query_path_to_output_fields , query_path_to_filters = sql_query_tree . query_path_to_filters , query_path_to_node = sql_query_tree . query_path_to_node , compiler_metadata = compiler_metadata , ) return _query_tree_to_query ( sql_query_tree . root , context ) | Return a SQLAlchemy Query from a passed SqlQueryTree . | 166 | 14 |
226,996 | def _create_table_and_update_context ( node , context ) : schema_type_name = sql_context_helpers . get_schema_type_name ( node , context ) table = context . compiler_metadata . get_table ( schema_type_name ) . alias ( ) context . query_path_to_selectable [ node . query_path ] = table return table | Create an aliased table for a SqlNode . | 86 | 11 |
226,997 | def _create_query ( node , context ) : visited_nodes = [ node ] output_columns = _get_output_columns ( visited_nodes , context ) filters = _get_filters ( visited_nodes , context ) selectable = sql_context_helpers . get_node_selectable ( node , context ) query = select ( output_columns ) . select_from ( selectable ) . where ( and_ ( * filters ) ) return query | Create a query from a SqlNode . | 104 | 9 |
226,998 | def _get_output_columns ( nodes , context ) : columns = [ ] for node in nodes : for sql_output in sql_context_helpers . get_outputs ( node , context ) : field_name = sql_output . field_name column = sql_context_helpers . get_column ( field_name , node , context ) column = column . label ( sql_output . output_name ) columns . append ( column ) return columns | Get the output columns for a list of SqlNodes . | 99 | 13 |
226,999 | def _get_filters ( nodes , context ) : filters = [ ] for node in nodes : for filter_block in sql_context_helpers . get_filters ( node , context ) : filter_sql_expression = _transform_filter_to_sql ( filter_block , node , context ) filters . append ( filter_sql_expression ) return filters | Get filters to apply to a list of SqlNodes . | 78 | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.