signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def _lower_non_existent_context_field_filters(match_traversals, visitor_fn):
new_match_traversals = []<EOL>for match_traversal in match_traversals:<EOL><INDENT>new_match_traversal = []<EOL>for step in match_traversal:<EOL><INDENT>if step.where_block is not None:<EOL><INDENT>new_filter = step.where_block.visit_and_update_expressions(visitor_fn)<EOL>if new_filter.predicate == TrueLiteral:<EOL><INDENT>new_filter = None<EOL><DEDENT>new_step = step._replace(where_block=new_filter)<EOL><DEDENT>else:<EOL><INDENT>new_step = step<EOL><DEDENT>new_match_traversal.append(new_step)<EOL><DEDENT>new_match_traversals.append(new_match_traversal)<EOL><DEDENT>return new_match_traversals<EOL>
Return new match traversals, lowering filters involving non-existent ContextFields. Expressions involving non-existent ContextFields are evaluated to TrueLiteral. BinaryCompositions, where one of the operands is lowered to a TrueLiteral, are lowered appropriately based on the present operator (u'||' and u'&&' are affected). TernaryConditionals, where the predicate is lowered to a TrueLiteral, are replaced by their if_true predicate. The `visitor_fn` implements these behaviors (see `_update_context_field_expression`). Args: match_traversals: list of match traversal enitities to be lowered visitor_fn: visit_and_update function for lowering expressions in given match traversal Returns: new list of match_traversals, with all filter expressions lowered
f12679:m12
def lower_context_field_expressions(compound_match_query):
if len(compound_match_query.match_queries) == <NUM_LIT:0>:<EOL><INDENT>raise AssertionError(u'<STR_LIT>'<EOL>.format(compound_match_query))<EOL><DEDENT>elif len(compound_match_query.match_queries) == <NUM_LIT:1>:<EOL><INDENT>return compound_match_query<EOL><DEDENT>else:<EOL><INDENT>new_match_queries = []<EOL>for match_query in compound_match_query.match_queries:<EOL><INDENT>match_traversals = match_query.match_traversals<EOL>present_locations, _ = _get_present_locations(match_traversals)<EOL>current_visitor_fn = partial(_update_context_field_expression, present_locations)<EOL>new_match_traversals = _lower_non_existent_context_field_filters(<EOL>match_traversals, current_visitor_fn)<EOL>new_match_queries.append(<EOL>MatchQuery(<EOL>match_traversals=new_match_traversals,<EOL>folds=match_query.folds,<EOL>output_block=match_query.output_block,<EOL>where_block=match_query.where_block,<EOL>)<EOL>)<EOL><DEDENT><DEDENT>return CompoundMatchQuery(match_queries=new_match_queries)<EOL>
Lower Expressons involving non-existent ContextFields.
f12679:m13
def convert_coerce_type_to_instanceof_filter(coerce_type_block):
coerce_type_target = get_only_element_from_collection(coerce_type_block.target_class)<EOL>new_predicate = BinaryComposition(<EOL>u'<STR_LIT>', LocalField('<STR_LIT>'), Literal(coerce_type_target))<EOL>return Filter(new_predicate)<EOL>
Create an "INSTANCEOF" Filter block from a CoerceType block.
f12680:m0
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)<EOL>if where_block:<EOL><INDENT>return Filter(BinaryComposition(u'<STR_LIT>', instanceof_filter.predicate, where_block.predicate))<EOL><DEDENT>else:<EOL><INDENT>return instanceof_filter<EOL><DEDENT>
Create an "INSTANCEOF" Filter from a CoerceType, adding to an existing Filter if any.
f12680:m1
def expression_list_to_conjunction(expression_list):
if not isinstance(expression_list, list):<EOL><INDENT>raise AssertionError(u'<STR_LIT>'.format(expression_list))<EOL><DEDENT>if len(expression_list) == <NUM_LIT:0>:<EOL><INDENT>return TrueLiteral<EOL><DEDENT>if not isinstance(expression_list[<NUM_LIT:0>], Expression):<EOL><INDENT>raise AssertionError(u'<STR_LIT>'<EOL>.format(expression_list[<NUM_LIT:0>]))<EOL><DEDENT>if len(expression_list) == <NUM_LIT:1>:<EOL><INDENT>return expression_list[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>return BinaryComposition(u'<STR_LIT>',<EOL>expression_list_to_conjunction(expression_list[<NUM_LIT:1>:]),<EOL>expression_list[<NUM_LIT:0>])<EOL><DEDENT>
Convert a list of expressions to an Expression that is the conjunction of all of them.
f12680:m2
def filter_edge_field_non_existence(edge_expression):
<EOL>if not isinstance(edge_expression, (LocalField, GlobalContextField)):<EOL><INDENT>raise AssertionError(u'<STR_LIT>'<EOL>u'<STR_LIT>'<EOL>.format(edge_expression, type(edge_expression).__name__))<EOL><DEDENT>if isinstance(edge_expression, LocalField):<EOL><INDENT>if not is_vertex_field_name(edge_expression.field_name):<EOL><INDENT>raise AssertionError(u'<STR_LIT>'<EOL>u'<STR_LIT>'.format(edge_expression, edge_expression.field_name))<EOL><DEDENT><DEDENT>field_null_check = BinaryComposition(u'<STR_LIT:=>', edge_expression, NullLiteral)<EOL>local_field_size = UnaryTransformation(u'<STR_LIT:size>', edge_expression)<EOL>field_size_check = BinaryComposition(u'<STR_LIT:=>', local_field_size, ZeroLiteral)<EOL>return BinaryComposition(u'<STR_LIT>', field_null_check, field_size_check)<EOL>
Return an Expression that is True iff the specified edge (edge_expression) does not exist.
f12680:m3
def _filter_orientdb_simple_optional_edge(<EOL>query_metadata_table, optional_edge_location, inner_location_name):
inner_local_field = LocalField(inner_location_name)<EOL>inner_location_existence = BinaryComposition(u'<STR_LIT>', inner_local_field, NullLiteral)<EOL>vertex_location = (<EOL>optional_edge_location.at_vertex().navigate_to_subpath(optional_edge_location.field)<EOL>)<EOL>location_type = query_metadata_table.get_location_info(vertex_location).type<EOL>edge_context_field = GlobalContextField(optional_edge_location, location_type)<EOL>edge_field_non_existence = filter_edge_field_non_existence(edge_context_field)<EOL>return BinaryComposition(u'<STR_LIT>', edge_field_non_existence, inner_location_existence)<EOL>
Return an Expression that is False for rows that don't follow the @optional specification. OrientDB does not filter correctly within optionals. Namely, a result where the optional edge DOES EXIST will be returned regardless of whether the inner filter is satisfed. To mitigate this, we add a final filter to reject such results. A valid result must satisfy either of the following: - The location within the optional exists (the filter will have been applied in this case) - The optional edge field does not exist at the root location of the optional traverse So, if the inner location within the optional was never visited, it must be the case that the corresponding edge field does not exist at all. Example: A MATCH traversal which starts at location `Animal___1`, and follows the optional edge `out_Animal_ParentOf` to the location `Animal__out_Animal_ParentOf___1` results in the following filtering Expression: ( ( (Animal___1.out_Animal_ParentOf IS null) OR (Animal___1.out_Animal_ParentOf.size() = 0) ) OR (Animal__out_Animal_ParentOf___1 IS NOT null) ) Here, the `optional_edge_location` is `Animal___1.out_Animal_ParentOf`. Args: query_metadata_table: QueryMetadataTable object containing all metadata collected during query processing, including location metadata (e.g. which locations are folded or optional). optional_edge_location: Location object representing the optional edge field inner_location_name: string representing location within the corresponding optional traverse Returns: Expression that evaluates to False for rows that do not follow the @optional specification
f12680:m4
def construct_where_filter_predicate(query_metadata_table, simple_optional_root_info):
inner_location_name_to_where_filter = {}<EOL>for root_location, root_info_dict in six.iteritems(simple_optional_root_info):<EOL><INDENT>inner_location_name = root_info_dict['<STR_LIT>']<EOL>edge_field = root_info_dict['<STR_LIT>']<EOL>optional_edge_location = root_location.navigate_to_field(edge_field)<EOL>optional_edge_where_filter = _filter_orientdb_simple_optional_edge(<EOL>query_metadata_table, optional_edge_location, inner_location_name)<EOL>inner_location_name_to_where_filter[inner_location_name] = optional_edge_where_filter<EOL><DEDENT>where_filter_expressions = [<EOL>inner_location_name_to_where_filter[key]<EOL>for key in sorted(inner_location_name_to_where_filter.keys())<EOL>]<EOL>return expression_list_to_conjunction(where_filter_expressions)<EOL>
Return an Expression that is True if and only if each simple optional filter is True. Construct filters for each simple optional, that are True if and only if `edge_field` does not exist in the `simple_optional_root_location` OR the `inner_location` is not defined. Return an Expression that evaluates to True if and only if *all* of the aforementioned filters evaluate to True (conjunction). Args: query_metadata_table: QueryMetadataTable object containing all metadata collected during query processing, including location metadata (e.g. which locations are folded or optional). simple_optional_root_info: dict mapping from simple_optional_root_location -> dict containing keys - 'inner_location_name': Location object correspoding to the unique MarkLocation present within a simple @optional (one that does not expands vertex fields) scope - 'edge_field': string representing the optional edge being traversed where simple_optional_root_to_inner_location is the location preceding the @optional scope Returns: a new Expression object
f12680:m5
def construct_optional_traversal_tree(complex_optional_roots, location_to_optional_roots):
tree = OptionalTraversalTree(complex_optional_roots)<EOL>for optional_root_locations_stack in six.itervalues(location_to_optional_roots):<EOL><INDENT>tree.insert(list(optional_root_locations_stack))<EOL><DEDENT>return tree<EOL>
Return a tree of complex optional root locations. Args: complex_optional_roots: list of @optional locations (location immmediately preceding an @optional Traverse) that expand vertex fields location_to_optional_roots: dict mapping from location -> optional_roots where location is within some number of @optionals and optional_roots is a list of optional root locations preceding the successive @optional scopes within which the location resides Returns: OptionalTraversalTree object representing the tree of complex optional roots
f12680:m6
def __init__(self, field, lower_bound, upper_bound):
super(BetweenClause, self).__init__(field, lower_bound, upper_bound)<EOL>self.field = field<EOL>self.lower_bound = lower_bound<EOL>self.upper_bound = upper_bound<EOL>self.validate()<EOL>
Construct an expression that is true when the field value is within the given bounds. Args: field: LocalField Expression, denoting the field in consideration lower_bound: lower bound constraint for given field upper_bound: upper bound constraint for given field Returns: a new BetweenClause object
f12680:c0:m0
def validate(self):
if not isinstance(self.field, LocalField):<EOL><INDENT>raise TypeError(u'<STR_LIT>'.format(<EOL>type(self.field).__name__, self.field))<EOL><DEDENT>if not isinstance(self.lower_bound, Expression):<EOL><INDENT>raise TypeError(u'<STR_LIT>'.format(<EOL>type(self.lower_bound).__name__, self.lower_bound))<EOL><DEDENT>if not isinstance(self.upper_bound, Expression):<EOL><INDENT>raise TypeError(u'<STR_LIT>'.format(<EOL>type(self.upper_bound).__name__, self.upper_bound))<EOL><DEDENT>
Validate that the Between Expression is correctly representable.
f12680:c0:m1
def visit_and_update(self, visitor_fn):
new_lower_bound = self.lower_bound.visit_and_update(visitor_fn)<EOL>new_upper_bound = self.upper_bound.visit_and_update(visitor_fn)<EOL>if new_lower_bound is not self.lower_bound or new_upper_bound is not self.upper_bound:<EOL><INDENT>return visitor_fn(BetweenClause(self.field, new_lower_bound, new_upper_bound))<EOL><DEDENT>else:<EOL><INDENT>return visitor_fn(self)<EOL><DEDENT>
Create an updated version (if needed) of BetweenClause via the visitor pattern.
f12680:c0:m2
def to_match(self):
template = u'<STR_LIT>'<EOL>return template.format(<EOL>field_name=self.field.to_match(),<EOL>lower_bound=self.lower_bound.to_match(),<EOL>upper_bound=self.upper_bound.to_match())<EOL>
Return a unicode object with the MATCH representation of this BetweenClause.
f12680:c0:m3
def to_gremlin(self):
raise NotImplementedError()<EOL>
Must never be called.
f12680:c0:m4
def __init__(self, complex_optional_roots):
self._location_to_children = {<EOL>optional_root_location: set()<EOL>for optional_root_location in complex_optional_roots<EOL>}<EOL>self._root_location = None<EOL>self._location_to_children[self._root_location] = set()<EOL>
Initialize empty tree of optional root Locations (elements of complex_optional_roots). This object construst a tree of complex optional roots. These are locations preceding an @optional traverse that expand vertex fields within. Simple @optional traverses i.e. ones that do not expand vertex fields within them are excluded. Args: complex_optional_roots: list of @optional locations (location preceding an @optional traverse) that expand vertex fields within
f12680:c1:m0
def insert(self, optional_root_locations_path):
encountered_simple_optional = False<EOL>parent_location = self._root_location<EOL>for optional_root_location in optional_root_locations_path:<EOL><INDENT>if encountered_simple_optional:<EOL><INDENT>raise AssertionError(u'<STR_LIT>'<EOL>u'<STR_LIT>'<EOL>.format(optional_root_location, optional_root_locations_path))<EOL><DEDENT>if optional_root_location not in self._location_to_children:<EOL><INDENT>encountered_simple_optional = True<EOL><DEDENT>else:<EOL><INDENT>self._location_to_children[parent_location].add(optional_root_location)<EOL>parent_location = optional_root_location<EOL><DEDENT><DEDENT>
Insert a path of optional Locations into the tree. Each OptionalTraversalTree object contains child Location objects as keys mapping to other OptionalTraversalTree objects. Args: optional_root_locations_path: list of optional root Locations all except the last of which must be present in complex_optional_roots
f12680:c1:m1
def get_all_rooted_subtrees_as_lists(self, start_location=None):
if start_location is not None and start_location not in self._location_to_children:<EOL><INDENT>raise AssertionError(u'<STR_LIT>'<EOL>u'<STR_LIT>'<EOL>u'<STR_LIT>'<EOL>.format(start_location, self._location_to_children.keys()))<EOL><DEDENT>if start_location is None:<EOL><INDENT>start_location = self._root_location<EOL><DEDENT>if len(self._location_to_children[start_location]) == <NUM_LIT:0>:<EOL><INDENT>return [[]]<EOL><DEDENT>current_children = sorted(self._location_to_children[start_location])<EOL>location_to_list_of_subtrees = {<EOL>location: list(self.get_all_rooted_subtrees_as_lists(location))<EOL>for location in current_children<EOL>}<EOL>all_location_subsets = [<EOL>list(subset)<EOL>for subset in itertools.chain(*[<EOL>itertools.combinations(current_children, x)<EOL>for x in range(<NUM_LIT:0>, len(current_children) + <NUM_LIT:1>)<EOL>])<EOL>]<EOL>new_subtrees_as_lists = []<EOL>for location_subset in all_location_subsets:<EOL><INDENT>all_child_subtree_possibilities = [<EOL>location_to_list_of_subtrees[location]<EOL>for location in location_subset<EOL>]<EOL>all_child_subtree_combinations = itertools.product(*all_child_subtree_possibilities)<EOL>for child_subtree_combination in all_child_subtree_combinations:<EOL><INDENT>merged_child_subtree_combination = list(itertools.chain(*child_subtree_combination))<EOL>new_subtree_as_list = location_subset + merged_child_subtree_combination<EOL>new_subtrees_as_lists.append(new_subtree_as_list)<EOL><DEDENT><DEDENT>return new_subtrees_as_lists<EOL>
Return a list of all rooted subtrees (each as a list of Location objects).
f12680:c1:m2
def __init__(self, root_location, root_location_info):
if not isinstance(root_location, Location):<EOL><INDENT>raise AssertionError(u'<STR_LIT>'<EOL>u'<STR_LIT>'<EOL>u'<STR_LIT>'.format(type(root_location).__name__, root_location))<EOL><DEDENT>if len(root_location.query_path) != <NUM_LIT:1> or root_location.visit_counter != <NUM_LIT:1>:<EOL><INDENT>raise AssertionError(u'<STR_LIT>'<EOL>u'<STR_LIT>'.format(root_location))<EOL><DEDENT>self._root_location = root_location <EOL>self._locations = dict() <EOL>self._inputs = dict() <EOL>self._outputs = dict() <EOL>self._tags = dict() <EOL>self._filter_infos = dict() <EOL>self._recurse_infos = dict() <EOL>self._revisit_origins = dict()<EOL>self._revisits = dict()<EOL>self._child_locations = dict()<EOL>self.register_location(root_location, root_location_info)<EOL>
Create a new empty QueryMetadataTable object.
f12681:c0:m0
@property<EOL><INDENT>def root_location(self):<DEDENT>
return self._root_location<EOL>
Return the root location of the query.
f12681:c0:m1
def register_location(self, location, location_info):
old_info = self._locations.get(location, None)<EOL>if old_info is not None:<EOL><INDENT>raise AssertionError(u'<STR_LIT>'<EOL>u'<STR_LIT>'<EOL>.format(location, old_info, location_info))<EOL><DEDENT>if location.field is not None:<EOL><INDENT>raise AssertionError(u'<STR_LIT>'<EOL>u'<STR_LIT>'.format(location, location_info))<EOL><DEDENT>if location_info.parent_location is None:<EOL><INDENT>is_root_location = location == self._root_location<EOL>is_revisit_of_root_location = self._root_location.is_revisited_at(location)<EOL>if not (is_root_location or is_revisit_of_root_location):<EOL><INDENT>raise AssertionError(u'<STR_LIT>'<EOL>u'<STR_LIT>'<EOL>u'<STR_LIT>'.format(location, location_info))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self._child_locations.setdefault(location_info.parent_location, set()).add(location)<EOL><DEDENT>self._locations[location] = location_info<EOL>
Record a new location's metadata in the metadata table.
f12681:c0:m2
def revisit_location(self, location):
<EOL>revisited_location = location.revisit()<EOL>revisit_origin = self._revisit_origins.get(location, location)<EOL>self._revisit_origins[revisited_location] = revisit_origin<EOL>self._revisits.setdefault(revisit_origin, set()).add(revisited_location)<EOL>self.register_location(revisited_location, self.get_location_info(location))<EOL>return revisited_location<EOL>
Revisit a location, returning the revisited location after setting its metadata.
f12681:c0:m3
def record_coercion_at_location(self, location, coerced_to_type):
current_info = self._locations.get(location, None)<EOL>if current_info is None:<EOL><INDENT>raise AssertionError(u'<STR_LIT>'<EOL>u'<STR_LIT>'.format(location, coerced_to_type))<EOL><DEDENT>if current_info.coerced_from_type is not None:<EOL><INDENT>raise AssertionError(u'<STR_LIT>'<EOL>u'<STR_LIT>'.format(location, current_info, coerced_to_type))<EOL><DEDENT>new_info = current_info._replace(<EOL>type=coerced_to_type,<EOL>coerced_from_type=current_info.type)<EOL>self._locations[location] = new_info<EOL>
Record that a particular location is getting coerced to a different type.
f12681:c0:m4
def get_location_info(self, location):
location_info = self._locations.get(location, None)<EOL>if location_info is None:<EOL><INDENT>raise AssertionError(u'<STR_LIT>'<EOL>u'<STR_LIT:{}>'.format(location))<EOL><DEDENT>return location_info<EOL>
Return the LocationInfo object for a given location.
f12681:c0:m5
@property<EOL><INDENT>def tags(self):<DEDENT>
for tag_name, tag_info in six.iteritems(self._tags):<EOL><INDENT>yield tag_name, tag_info<EOL><DEDENT>
Return an iterable of (tag_name, tag_info) tuples for all tags in the query.
f12681:c0:m6
def record_tag_info(self, tag_name, tag_info):
old_info = self._tags.get(tag_name, None)<EOL>if old_info is not None:<EOL><INDENT>raise AssertionError(u'<STR_LIT>'<EOL>u'<STR_LIT>'<EOL>.format(tag_name, old_info, tag_info))<EOL><DEDENT>self._tags[tag_name] = tag_info<EOL>
Record information about the tag.
f12681:c0:m7
def get_tag_info(self, tag_name):
return self._tags.get(tag_name, None)<EOL>
Get information about a tag.
f12681:c0:m8
def record_filter_info(self, location, filter_info):
record_location = location.at_vertex()<EOL>self._filter_infos.setdefault(record_location, []).append(filter_info)<EOL>
Record filter information about the location.
f12681:c0:m9
def get_filter_infos(self, location):
return self._filter_infos.get(location, [])<EOL>
Get information about filters at the location.
f12681:c0:m10
def record_recurse_info(self, location, recurse_info):
record_location = location.at_vertex()<EOL>self._recurse_infos.setdefault(record_location, []).append(recurse_info)<EOL>
Record recursion information about the location.
f12681:c0:m11
def get_recurse_infos(self, location):
return self._recurse_infos.get(location, [])<EOL>
Get information about recursions at the location.
f12681:c0:m12
def get_child_locations(self, location):
self.get_location_info(location) <EOL>for child_location in self._child_locations.get(location, []):<EOL><INDENT>yield child_location<EOL><DEDENT>
Yield an iterable of child locations for a given Location/FoldScopeLocation object.
f12681:c0:m13
def get_all_revisits(self, location):
self.get_location_info(location) <EOL>for revisit_location in self._revisits.get(location, []):<EOL><INDENT>yield revisit_location<EOL><DEDENT>
Yield an iterable of locations that revisit that location or another of its revisits.
f12681:c0:m14
def get_revisit_origin(self, location):
self.get_location_info(location) <EOL>return self._revisit_origins.get(location, location)<EOL>
Return the original location that this location revisits, or None if it isn't a revisit. Args: location: Location/FoldScopeLocation object whose revisit origin to get Returns: Location object representing the first location with the same query path as the given location. Returns the given location itself if that location is the first one with that query path. Guaranteed to return the input location if it is a FoldScopeLocation.
f12681:c0:m15
@property<EOL><INDENT>def registered_locations(self):<DEDENT>
for location, location_info in six.iteritems(self._locations):<EOL><INDENT>yield location, location_info<EOL><DEDENT>
Return an iterable of (location, location_info) tuples for all registered locations.
f12681:c0:m16
def __str__(self):
return (<EOL>u'<STR_LIT>'<EOL>.format(self._root_location, self._locations, self._inputs, self._outputs, self._tags)<EOL>)<EOL>
Return a human-readable str representation of the QueryMetadataTable object.
f12681:c0:m17
def __repr__(self):
return self.__str__()<EOL>
Return a human-readable str representation of the QueryMetadataTable object.
f12681:c0:m18
def emit_code_from_ir(sql_query_tree, compiler_metadata):
context = CompilationContext(<EOL>query_path_to_selectable=dict(),<EOL>query_path_to_location_info=sql_query_tree.query_path_to_location_info,<EOL>query_path_to_output_fields=sql_query_tree.query_path_to_output_fields,<EOL>query_path_to_filters=sql_query_tree.query_path_to_filters,<EOL>query_path_to_node=sql_query_tree.query_path_to_node,<EOL>compiler_metadata=compiler_metadata,<EOL>)<EOL>return _query_tree_to_query(sql_query_tree.root, context)<EOL>
Return a SQLAlchemy Query from a passed SqlQueryTree. Args: sql_query_tree: SqlQueryTree, tree representation of the query to emit. compiler_metadata: SqlMetadata, SQLAlchemy specific metadata. Returns: SQLAlchemy Query
f12682:m0
def _query_tree_to_query(node, context):
_create_table_and_update_context(node, context)<EOL>return _create_query(node, context)<EOL>
Convert this node into its corresponding SQL representation. Args: node: SqlNode, the node to convert to SQL. context: CompilationContext, compilation specific metadata Returns: Query, the compiled SQL query
f12682:m1
def _create_table_and_update_context(node, context):
schema_type_name = sql_context_helpers.get_schema_type_name(node, context)<EOL>table = context.compiler_metadata.get_table(schema_type_name).alias()<EOL>context.query_path_to_selectable[node.query_path] = table<EOL>return table<EOL>
Create an aliased table for a SqlNode. Updates the relevant Selectable global context. Args: node: SqlNode, the current node. context: CompilationContext, global compilation state and metadata. Returns: Table, the newly aliased SQLAlchemy table.
f12682:m2
def _create_query(node, context):
visited_nodes = [node]<EOL>output_columns = _get_output_columns(visited_nodes, context)<EOL>filters = _get_filters(visited_nodes, context)<EOL>selectable = sql_context_helpers.get_node_selectable(node, context)<EOL>query = select(output_columns).select_from(selectable).where(and_(*filters))<EOL>return query<EOL>
Create a query from a SqlNode. Args: node: SqlNode, the current node. context: CompilationContext, global compilation state and metadata. Returns: Selectable, selectable of the generated query.
f12682:m3
def _get_output_columns(nodes, context):
columns = []<EOL>for node in nodes:<EOL><INDENT>for sql_output in sql_context_helpers.get_outputs(node, context):<EOL><INDENT>field_name = sql_output.field_name<EOL>column = sql_context_helpers.get_column(field_name, node, context)<EOL>column = column.label(sql_output.output_name)<EOL>columns.append(column)<EOL><DEDENT><DEDENT>return columns<EOL>
Get the output columns for a list of SqlNodes. Args: nodes: List[SqlNode], the nodes to get output columns from. context: CompilationContext, global compilation state and metadata. Returns: List[Column], list of SqlAlchemy Columns to output for this query.
f12682:m4
def _get_filters(nodes, context):
filters = []<EOL>for node in nodes:<EOL><INDENT>for filter_block in sql_context_helpers.get_filters(node, context):<EOL><INDENT>filter_sql_expression = _transform_filter_to_sql(filter_block, node, context)<EOL>filters.append(filter_sql_expression)<EOL><DEDENT><DEDENT>return filters<EOL>
Get filters to apply to a list of SqlNodes. Args: nodes: List[SqlNode], the SqlNodes to get filters for. context: CompilationContext, global compilation state and metadata. Returns: List[Expression], list of SQLAlchemy expressions.
f12682:m5
def _transform_filter_to_sql(filter_block, node, context):
expression = filter_block.predicate<EOL>return _expression_to_sql(expression, node, context)<EOL>
Transform a Filter block to its corresponding SQLAlchemy expression. Args: filter_block: Filter, the Filter block to transform. node: SqlNode, the node Filter block applies to. context: CompilationContext, global compilation state and metadata. Returns: Expression, SQLAlchemy expression equivalent to the Filter.predicate expression.
f12682:m6
def _expression_to_sql(expression, node, context):
_expression_transformers = {<EOL>expressions.LocalField: _transform_local_field_to_expression,<EOL>expressions.Variable: _transform_variable_to_expression,<EOL>expressions.Literal: _transform_literal_to_expression,<EOL>expressions.BinaryComposition: _transform_binary_composition_to_expression,<EOL>}<EOL>expression_type = type(expression)<EOL>if expression_type not in _expression_transformers:<EOL><INDENT>raise NotImplementedError(<EOL>u'<STR_LIT>'<EOL>u'<STR_LIT>'.format(expression, type(expression)))<EOL><DEDENT>return _expression_transformers[expression_type](expression, node, context)<EOL>
Recursively transform a Filter block predicate to its SQLAlchemy expression representation. Args: expression: expression, the compiler expression to transform. node: SqlNode, the SqlNode the expression applies to. context: CompilationContext, global compilation state and metadata. Returns: Expression, SQLAlchemy Expression equivalent to the passed compiler expression.
f12682:m7
def _transform_binary_composition_to_expression(expression, node, context):
if expression.operator not in constants.SUPPORTED_OPERATORS:<EOL><INDENT>raise NotImplementedError(<EOL>u'<STR_LIT>'.format(<EOL>expression.operator))<EOL><DEDENT>sql_operator = constants.SUPPORTED_OPERATORS[expression.operator]<EOL>left = _expression_to_sql(expression.left, node, context)<EOL>right = _expression_to_sql(expression.right, node, context)<EOL>if sql_operator.cardinality == constants.CARDINALITY_UNARY:<EOL><INDENT>left, right = _get_column_and_bindparam(left, right, sql_operator)<EOL>clause = getattr(left, sql_operator.name)(right)<EOL>return clause<EOL><DEDENT>elif sql_operator.cardinality == constants.CARDINALITY_BINARY:<EOL><INDENT>clause = getattr(sql_expressions, sql_operator.name)(left, right)<EOL>return clause<EOL><DEDENT>elif sql_operator.cardinality == constants.CARDINALITY_LIST_VALUED:<EOL><INDENT>left, right = _get_column_and_bindparam(left, right, sql_operator)<EOL>right.expanding = True<EOL>clause = getattr(left, sql_operator.name)(right)<EOL>return clause<EOL><DEDENT>raise AssertionError(u'<STR_LIT>'<EOL>u'<STR_LIT>'.format(sql_operator.cardinality, expression))<EOL>
Transform a BinaryComposition compiler expression into a SQLAlchemy expression. Recursively calls _expression_to_sql to convert its left and right sub-expressions. Args: expression: expression, BinaryComposition compiler expression. node: SqlNode, the SqlNode the expression applies to. context: CompilationContext, global compilation state and metadata. Returns: Expression, SQLAlchemy expression.
f12682:m8
def _get_column_and_bindparam(left, right, operator):
if not isinstance(left, Column):<EOL><INDENT>left, right = right, left<EOL><DEDENT>if not isinstance(left, Column):<EOL><INDENT>raise AssertionError(<EOL>u'<STR_LIT>'<EOL>u'<STR_LIT>'.format(operator, left, type(left)))<EOL><DEDENT>if not isinstance(right, BindParameter):<EOL><INDENT>raise AssertionError(<EOL>u'<STR_LIT>'<EOL>u'<STR_LIT>'.format(operator, right, type(right)))<EOL><DEDENT>return left, right<EOL>
Return left and right expressions in (Column, BindParameter) order.
f12682:m9
def _transform_literal_to_expression(expression, node, context):
return expression.value<EOL>
Transform a Literal compiler expression into its SQLAlchemy expression representation. Args: expression: expression, Literal compiler expression. node: SqlNode, the SqlNode the expression applies to. context: CompilationContext, global compilation state and metadata. Returns: Expression, SQLAlchemy expression.
f12682:m10
def _transform_variable_to_expression(expression, node, context):
variable_name = expression.variable_name<EOL>if not variable_name.startswith(u'<STR_LIT:$>'):<EOL><INDENT>raise AssertionError(u'<STR_LIT>'<EOL>u'<STR_LIT>'.format(variable_name))<EOL><DEDENT>return bindparam(variable_name[<NUM_LIT:1>:])<EOL>
Transform a Variable compiler expression into its SQLAlchemy expression representation. Args: expression: expression, Variable compiler expression. node: SqlNode, the SqlNode the expression applies to. context: CompilationContext, global compilation state and metadata. Returns: Expression, SQLAlchemy expression.
f12682:m11
def _transform_local_field_to_expression(expression, node, context):
column_name = expression.field_name<EOL>column = sql_context_helpers.get_column(column_name, node, context)<EOL>return column<EOL>
Transform a LocalField compiler expression into its SQLAlchemy expression representation. Args: expression: expression, LocalField compiler expression. node: SqlNode, the SqlNode the expression applies to. context: CompilationContext, global compilation state and metadata. Returns: Expression, SQLAlchemy expression.
f12682:m12
def get_schema_type_name(node, context):
query_path = node.query_path<EOL>if query_path not in context.query_path_to_location_info:<EOL><INDENT>raise AssertionError(<EOL>u'<STR_LIT>'.format(<EOL>query_path, context))<EOL><DEDENT>location_info = context.query_path_to_location_info[query_path]<EOL>return location_info.type.name<EOL>
Return the GraphQL type name of a node.
f12683:m0
def get_node_selectable(node, context):
query_path = node.query_path<EOL>if query_path not in context.query_path_to_selectable:<EOL><INDENT>raise AssertionError(<EOL>u'<STR_LIT>'.format(<EOL>query_path, context))<EOL><DEDENT>selectable = context.query_path_to_selectable[query_path]<EOL>return selectable<EOL>
Return the Selectable Union[Table, CTE] associated with the node.
f12683:m1
def get_node_at_path(query_path, context):
if query_path not in context.query_path_to_node:<EOL><INDENT>raise AssertionError(<EOL>u'<STR_LIT>'.format(<EOL>query_path, context))<EOL><DEDENT>node = context.query_path_to_node[query_path]<EOL>return node<EOL>
Return the SqlNode associated with the query path.
f12683:m2
def try_get_column(column_name, node, context):
selectable = get_node_selectable(node, context)<EOL>if not hasattr(selectable, '<STR_LIT:c>'):<EOL><INDENT>raise AssertionError(<EOL>u'<STR_LIT>'.format(<EOL>selectable, context))<EOL><DEDENT>return selectable.c.get(column_name, None)<EOL>
Attempt to get a column by name from the selectable. Args: column_name: str, name of the column to retrieve. node: SqlNode, the node the column is being retrieved for. context: CompilationContext, compilation specific metadata. Returns: Optional[column], the SQLAlchemy column if found, None otherwise.
f12683:m3
def get_column(column_name, node, context):
column = try_get_column(column_name, node, context)<EOL>if column is None:<EOL><INDENT>selectable = get_node_selectable(node, context)<EOL>raise AssertionError(<EOL>u'<STR_LIT>'<EOL>u'<STR_LIT>'.format(column_name, selectable.original,<EOL>[col.name for col in selectable.c], context))<EOL><DEDENT>return column<EOL>
Get a column by name from the selectable. Args: column_name: str, name of the column to retrieve. node: SqlNode, the node the column is being retrieved for. context: CompilationContext, compilation specific metadata. Returns: column, the SQLAlchemy column if found. Raises an AssertionError otherwise.
f12683:m4
def get_filters(node, context):
return context.query_path_to_filters.get(node.query_path, [])<EOL>
Return the filters applied to a SqlNode.
f12683:m5
def get_outputs(node, context):
return context.query_path_to_output_fields.get(node.query_path, [])<EOL>
Return the SqlOutputs for a SqlNode.
f12683:m6
def __init__(self, backend):
self._backend = backend<EOL>
Create a new SqlBackend to manage backend specific properties for compilation.
f12684:c0:m0
@property<EOL><INDENT>def backend(self):<DEDENT>
return self._backend<EOL>
Return the backend as a string.
f12684:c0:m1
def lower_ir(ir_blocks, query_metadata_table, type_equivalence_hints=None):
_validate_all_blocks_supported(ir_blocks, query_metadata_table)<EOL>construct_result = _get_construct_result(ir_blocks)<EOL>query_path_to_location_info = _map_query_path_to_location_info(query_metadata_table)<EOL>query_path_to_output_fields = _map_query_path_to_outputs(<EOL>construct_result, query_path_to_location_info)<EOL>block_index_to_location = _map_block_index_to_location(ir_blocks)<EOL>ir_blocks = lower_unary_transformations(ir_blocks)<EOL>ir_blocks = lower_unsupported_metafield_expressions(ir_blocks)<EOL>query_path_to_node = {}<EOL>query_path_to_filters = {}<EOL>tree_root = None<EOL>for index, block in enumerate(ir_blocks):<EOL><INDENT>if isinstance(block, constants.SKIPPABLE_BLOCK_TYPES):<EOL><INDENT>continue<EOL><DEDENT>location = block_index_to_location[index]<EOL>if isinstance(block, (blocks.QueryRoot,)):<EOL><INDENT>query_path = location.query_path<EOL>if tree_root is not None:<EOL><INDENT>raise AssertionError(<EOL>u'<STR_LIT>'<EOL>u'<STR_LIT>'<EOL>u'<STR_LIT>'.format(<EOL>block, tree_root, ir_blocks, query_metadata_table))<EOL><DEDENT>tree_root = SqlNode(block=block, query_path=query_path)<EOL>query_path_to_node[query_path] = tree_root<EOL><DEDENT>elif isinstance(block, blocks.Filter):<EOL><INDENT>query_path_to_filters.setdefault(query_path, []).append(block)<EOL><DEDENT>else:<EOL><INDENT>raise AssertionError(<EOL>u'<STR_LIT>'<EOL>u'<STR_LIT>'.format(block, ir_blocks, query_metadata_table))<EOL><DEDENT><DEDENT>return SqlQueryTree(tree_root, query_path_to_location_info, query_path_to_output_fields,<EOL>query_path_to_filters, query_path_to_node)<EOL>
Lower the IR blocks into a form that can be represented by a SQL query. Args: ir_blocks: list of IR blocks to lower into SQL-compatible form query_metadata_table: QueryMetadataTable object containing all metadata collected during query processing, including location metadata (e.g. which locations are folded or optional). type_equivalence_hints: optional dict of GraphQL interface or type -> GraphQL union. Used as a workaround for GraphQL's lack of support for inheritance across "types" (i.e. non-interfaces), as well as a workaround for Gremlin's total lack of inheritance-awareness. The key-value pairs in the dict specify that the "key" type is equivalent to the "value" type, i.e. that the GraphQL type or interface in the key is the most-derived common supertype of every GraphQL type in the "value" GraphQL union. Recursive expansion of type equivalence hints is not performed, and only type-level correctness of this argument is enforced. See README.md for more details on everything this parameter does. ***** Be very careful with this option, as bad input here will lead to incorrect output queries being generated. ***** Returns: tree representation of IR blocks for recursive traversal by SQL backend.
f12685:m0
def _validate_all_blocks_supported(ir_blocks, query_metadata_table):
if len(ir_blocks) < <NUM_LIT:3>:<EOL><INDENT>raise AssertionError(<EOL>u'<STR_LIT>'<EOL>u'<STR_LIT>'<EOL>u'<STR_LIT>'.format(query_metadata_table))<EOL><DEDENT>construct_result = _get_construct_result(ir_blocks)<EOL>unsupported_blocks = []<EOL>unsupported_fields = []<EOL>for block in ir_blocks[:-<NUM_LIT:1>]:<EOL><INDENT>if isinstance(block, constants.SUPPORTED_BLOCK_TYPES):<EOL><INDENT>continue<EOL><DEDENT>if isinstance(block, constants.SKIPPABLE_BLOCK_TYPES):<EOL><INDENT>continue<EOL><DEDENT>unsupported_blocks.append(block)<EOL><DEDENT>for field_name, field in six.iteritems(construct_result.fields):<EOL><INDENT>if not isinstance(field, constants.SUPPORTED_OUTPUT_EXPRESSION_TYPES):<EOL><INDENT>unsupported_fields.append((field_name, field))<EOL><DEDENT>elif field.location.field in constants.UNSUPPORTED_META_FIELDS:<EOL><INDENT>unsupported_fields.append((field_name, field))<EOL><DEDENT><DEDENT>if len(unsupported_blocks) > <NUM_LIT:0> or len(unsupported_fields) > <NUM_LIT:0>:<EOL><INDENT>raise NotImplementedError(<EOL>u'<STR_LIT>'<EOL>u'<STR_LIT>'.format(<EOL>unsupported_blocks, unsupported_fields, ir_blocks, query_metadata_table))<EOL><DEDENT>
Validate that all IR blocks and ConstructResult fields passed to the backend are supported. Args: ir_blocks: List[BasicBlock], IR blocks to validate. query_metadata_table: QueryMetadataTable, object containing all metadata collected during query processing, including location metadata (e.g. which locations are folded or optional). Raises: NotImplementedError, if any block or ConstructResult field is unsupported.
f12685:m1
def _get_construct_result(ir_blocks):
last_block = ir_blocks[-<NUM_LIT:1>]<EOL>if not isinstance(last_block, blocks.ConstructResult):<EOL><INDENT>raise AssertionError(<EOL>u'<STR_LIT>'<EOL>u'<STR_LIT>'.format(last_block, ir_blocks))<EOL><DEDENT>return last_block<EOL>
Return the ConstructResult block from a list of IR blocks.
f12685:m2
def _map_query_path_to_location_info(query_metadata_table):
query_path_to_location_info = {}<EOL>for location, location_info in query_metadata_table.registered_locations:<EOL><INDENT>if not isinstance(location, Location):<EOL><INDENT>continue<EOL><DEDENT>if location.query_path in query_path_to_location_info:<EOL><INDENT>equivalent_location_info = query_path_to_location_info[location.query_path]<EOL>if not _location_infos_equal(location_info, equivalent_location_info):<EOL><INDENT>raise AssertionError(<EOL>u'<STR_LIT>'<EOL>u'<STR_LIT>'<EOL>u'<STR_LIT>'.format(<EOL>location.query_path, location_info, equivalent_location_info))<EOL><DEDENT><DEDENT>query_path_to_location_info[location.query_path] = location_info<EOL><DEDENT>return query_path_to_location_info<EOL>
Create a map from each query path to a LocationInfo at that path. Args: query_metadata_table: QueryMetadataTable, object containing all metadata collected during query processing, including location metadata (e.g. which locations are folded or optional). Returns: Dict[Tuple[str], LocationInfo], dictionary mapping query path to LocationInfo at that path.
f12685:m3
def _location_infos_equal(left, right):
if not isinstance(left, LocationInfo) or not isinstance(right, LocationInfo):<EOL><INDENT>raise AssertionError(<EOL>u'<STR_LIT>'<EOL>u'<STR_LIT>'.format(type(left), type(right), left, right))<EOL><DEDENT>optional_scopes_depth_equal = (left.optional_scopes_depth == right.optional_scopes_depth)<EOL>parent_query_paths_equal = (<EOL>(left.parent_location is None and right.parent_location is None) or<EOL>(left.parent_location.query_path == right.parent_location.query_path))<EOL>recursive_scopes_depths_equal = (left.recursive_scopes_depth == right.recursive_scopes_depth)<EOL>types_equal = left.type == right.type<EOL>return all([<EOL>optional_scopes_depth_equal,<EOL>parent_query_paths_equal,<EOL>recursive_scopes_depths_equal,<EOL>types_equal,<EOL>])<EOL>
Return True if LocationInfo objects are equivalent for the SQL backend, False otherwise. LocationInfo objects are considered equal for the SQL backend iff the optional scopes depth, recursive scopes depth, types and parent query paths are equal. Args: left: LocationInfo, left location info object to compare. right: LocationInfo, right location info object to compare. Returns: bool, True if LocationInfo objects equivalent, False otherwise.
f12685:m4
def _map_query_path_to_outputs(construct_result, query_path_to_location_info):
query_path_to_output_fields = {}<EOL>for output_name, field in six.iteritems(construct_result.fields):<EOL><INDENT>field_name = field.location.field<EOL>output_query_path = field.location.query_path<EOL>output_field_info = constants.SqlOutput(<EOL>field_name=field_name,<EOL>output_name=output_name,<EOL>graphql_type=query_path_to_location_info[output_query_path].type)<EOL>output_field_mapping = query_path_to_output_fields.setdefault(output_query_path, [])<EOL>output_field_mapping.append(output_field_info)<EOL><DEDENT>return query_path_to_output_fields<EOL>
Assign the output fields of a ConstructResult block to their respective query_path.
f12685:m5
def _map_block_index_to_location(ir_blocks):
block_index_to_location = {}<EOL>current_block_ixs = []<EOL>for num, ir_block in enumerate(ir_blocks):<EOL><INDENT>if isinstance(ir_block, blocks.GlobalOperationsStart):<EOL><INDENT>if len(current_block_ixs) > <NUM_LIT:0>:<EOL><INDENT>unassociated_blocks = [ir_blocks[ix] for ix in current_block_ixs]<EOL>raise AssertionError(<EOL>u'<STR_LIT>'<EOL>u'<STR_LIT>'.format(unassociated_blocks))<EOL><DEDENT>break<EOL><DEDENT>current_block_ixs.append(num)<EOL>if isinstance(ir_block, blocks.MarkLocation):<EOL><INDENT>for ix in current_block_ixs:<EOL><INDENT>block_index_to_location[ix] = ir_block.location<EOL><DEDENT>current_block_ixs = []<EOL><DEDENT><DEDENT>return block_index_to_location<EOL>
Associate each IR block with its corresponding location, by index.
f12685:m6
def lower_unary_transformations(ir_blocks):
def visitor_fn(expression):<EOL><INDENT>"""<STR_LIT>"""<EOL>if not isinstance(expression, expressions.UnaryTransformation):<EOL><INDENT>return expression<EOL><DEDENT>raise NotImplementedError(<EOL>u'<STR_LIT>'<EOL>u'<STR_LIT>'.format(expression, ir_blocks)<EOL>)<EOL><DEDENT>new_ir_blocks = [<EOL>block.visit_and_update_expressions(visitor_fn)<EOL>for block in ir_blocks<EOL>]<EOL>return new_ir_blocks<EOL>
Raise exception if any unary transformation block encountered.
f12685:m7
def lower_unsupported_metafield_expressions(ir_blocks):
def visitor_fn(expression):<EOL><INDENT>"""<STR_LIT>"""<EOL>if not isinstance(expression, expressions.LocalField):<EOL><INDENT>return expression<EOL><DEDENT>if expression.field_name not in constants.UNSUPPORTED_META_FIELDS:<EOL><INDENT>return expression<EOL><DEDENT>raise NotImplementedError(<EOL>u'<STR_LIT>'<EOL>u'<STR_LIT>'.format(<EOL>constants.UNSUPPORTED_META_FIELDS[expression.field_name], expression, ir_blocks))<EOL><DEDENT>new_ir_blocks = [<EOL>block.visit_and_update_expressions(visitor_fn)<EOL>for block in ir_blocks<EOL>]<EOL>return new_ir_blocks<EOL>
Raise exception if an unsupported metafield is encountered in any LocalField expression.
f12685:m8
def __init__(self, root, query_path_to_location_info,<EOL>query_path_to_output_fields, query_path_to_filters, query_path_to_node):
self.root = root<EOL>self.query_path_to_location_info = query_path_to_location_info<EOL>self.query_path_to_output_fields = query_path_to_output_fields<EOL>self.query_path_to_filters = query_path_to_filters<EOL>self.query_path_to_node = query_path_to_node<EOL>
Wrap a SqlNode root with additional location_info metadata.
f12686:c0:m0
def __init__(self, block, query_path):
self.query_path = query_path<EOL>self.block = block<EOL>
Create a new SqlNode wrapping a QueryRoot block at a query_path.
f12686:c1:m0
def __str__(self):
return u'<STR_LIT>'.format(self.query_path)<EOL>
Return a string representation of a SqlNode.
f12686:c1:m1
def __repr__(self):
return self.__str__()<EOL>
Return the repr of a SqlNode.
f12686:c1:m2
def __init__(self, dialect, sqlalchemy_metadata):
self.sqlalchemy_metadata = sqlalchemy_metadata<EOL>self._db_backend = SqlBackend(dialect)<EOL>self.table_name_to_table = {<EOL>name.lower(): table<EOL>for name, table in six.iteritems(self.sqlalchemy_metadata.tables)<EOL>}<EOL>
Initialize a new SQL metadata manager.
f12687:c0:m0
def get_table(self, schema_type):
table_name = schema_type.lower()<EOL>if not self.has_table(table_name):<EOL><INDENT>raise exceptions.GraphQLCompilationError(<EOL>'<STR_LIT>'.format(table_name)<EOL>)<EOL><DEDENT>return self.table_name_to_table[table_name]<EOL>
Retrieve a SQLAlchemy table based on the supplied GraphQL schema type name.
f12687:c0:m1
def has_table(self, schema_type):
table_name = schema_type.lower()<EOL>return table_name in self.table_name_to_table<EOL>
Retrieve a SQLAlchemy table based on the supplied GraphQL schema type name.
f12687:c0:m2
@property<EOL><INDENT>def db_backend(self):<DEDENT>
return self._db_backend<EOL>
Retrieve this compiler's DB backend.
f12687:c0:m3
def _safe_gremlin_string(value):
if not isinstance(value, six.string_types):<EOL><INDENT>if isinstance(value, bytes): <EOL><INDENT>value = value.decode('<STR_LIT:utf-8>')<EOL><DEDENT>else:<EOL><INDENT>raise GraphQLInvalidArgumentError(u'<STR_LIT>'<EOL>u'<STR_LIT:{}>'.format(value))<EOL><DEDENT><DEDENT>escaped_and_quoted = json.dumps(value)<EOL>if not escaped_and_quoted[<NUM_LIT:0>] == escaped_and_quoted[-<NUM_LIT:1>] == '<STR_LIT:">':<EOL><INDENT>raise AssertionError(u'<STR_LIT>'.format(value, escaped_and_quoted))<EOL><DEDENT>no_quotes = escaped_and_quoted[<NUM_LIT:1>:-<NUM_LIT:1>]<EOL>re_escaped = no_quotes.replace('<STR_LIT>', '<STR_LIT:">').replace('<STR_LIT>', '<STR_LIT>')<EOL>final_escaped_value = '<STR_LIT>' + re_escaped + '<STR_LIT>'<EOL>return final_escaped_value<EOL>
Sanitize and represent a string argument in Gremlin.
f12688:m0
def _safe_gremlin_decimal(value):
decimal_value = coerce_to_decimal(value)<EOL>return str(decimal_value) + '<STR_LIT>'<EOL>
Represent decimal objects as Gremlin strings.
f12688:m1
def _safe_gremlin_date_and_datetime(graphql_type, expected_python_types, value):
<EOL>value_type = type(value)<EOL>if not any(value_type == x for x in expected_python_types):<EOL><INDENT>raise GraphQLInvalidArgumentError(u'<STR_LIT>'<EOL>u'<STR_LIT>'<EOL>u'<STR_LIT:{}>'.format(expected_python_types, value_type, value))<EOL><DEDENT>try:<EOL><INDENT>serialized_value = graphql_type.serialize(value)<EOL><DEDENT>except ValueError as e:<EOL><INDENT>raise GraphQLInvalidArgumentError(e)<EOL><DEDENT>return _safe_gremlin_string(serialized_value)<EOL>
Represent date and datetime objects as Gremlin strings.
f12688:m2
def _safe_gremlin_list(inner_type, argument_value):
if not isinstance(argument_value, list):<EOL><INDENT>raise GraphQLInvalidArgumentError(u'<STR_LIT>'<EOL>u'<STR_LIT:{}>'.format(argument_value))<EOL><DEDENT>stripped_type = strip_non_null_from_type(inner_type)<EOL>components = (<EOL>_safe_gremlin_argument(stripped_type, x)<EOL>for x in argument_value<EOL>)<EOL>return u'<STR_LIT:[>' + u'<STR_LIT:U+002C>'.join(components) + u'<STR_LIT:]>'<EOL>
Represent the list of "inner_type" objects in Gremlin form.
f12688:m3
def _safe_gremlin_argument(expected_type, argument_value):
if GraphQLString.is_same_type(expected_type):<EOL><INDENT>return _safe_gremlin_string(argument_value)<EOL><DEDENT>elif GraphQLID.is_same_type(expected_type):<EOL><INDENT>if not isinstance(argument_value, six.string_types):<EOL><INDENT>if isinstance(argument_value, bytes): <EOL><INDENT>argument_value = argument_value.decode('<STR_LIT:utf-8>')<EOL><DEDENT>else:<EOL><INDENT>argument_value = six.text_type(argument_value)<EOL><DEDENT><DEDENT>return _safe_gremlin_string(argument_value)<EOL><DEDENT>elif GraphQLFloat.is_same_type(expected_type):<EOL><INDENT>return represent_float_as_str(argument_value)<EOL><DEDENT>elif GraphQLInt.is_same_type(expected_type):<EOL><INDENT>if isinstance(argument_value, bool):<EOL><INDENT>raise GraphQLInvalidArgumentError(u'<STR_LIT>'<EOL>u'<STR_LIT:{}>'.format(argument_value))<EOL><DEDENT>return type_check_and_str(int, argument_value)<EOL><DEDENT>elif GraphQLBoolean.is_same_type(expected_type):<EOL><INDENT>return type_check_and_str(bool, argument_value)<EOL><DEDENT>elif GraphQLDecimal.is_same_type(expected_type):<EOL><INDENT>return _safe_gremlin_decimal(argument_value)<EOL><DEDENT>elif GraphQLDate.is_same_type(expected_type):<EOL><INDENT>return _safe_gremlin_date_and_datetime(expected_type, (datetime.date,), argument_value)<EOL><DEDENT>elif GraphQLDateTime.is_same_type(expected_type):<EOL><INDENT>return _safe_gremlin_date_and_datetime(expected_type,<EOL>(datetime.datetime, arrow.Arrow), argument_value)<EOL><DEDENT>elif isinstance(expected_type, GraphQLList):<EOL><INDENT>return _safe_gremlin_list(expected_type.of_type, argument_value)<EOL><DEDENT>else:<EOL><INDENT>raise AssertionError(u'<STR_LIT>'<EOL>u'<STR_LIT>'.format(expected_type, argument_value))<EOL><DEDENT>
Return a Gremlin string representing the given argument value.
f12688:m4
def insert_arguments_into_gremlin_query(compilation_result, arguments):
if compilation_result.language != GREMLIN_LANGUAGE:<EOL><INDENT>raise AssertionError(u'<STR_LIT>'.format(compilation_result))<EOL><DEDENT>base_query = compilation_result.query<EOL>argument_types = compilation_result.input_metadata<EOL>sanitized_arguments = {<EOL>key: _safe_gremlin_argument(argument_types[key], value)<EOL>for key, value in six.iteritems(arguments)<EOL>}<EOL>return Template(base_query).substitute(sanitized_arguments)<EOL>
Insert the arguments into the compiled Gremlin query to form a complete query. The GraphQL compiler attempts to use single-quoted string literals ('abc') in Gremlin output. Double-quoted strings allow inline interpolation with the $ symbol, see here for details: http://www.groovy-lang.org/syntax.html#all-strings If the compiler needs to emit a literal '$' character as part of the Gremlin query, it must be doubled ('$$') to avoid being interpreted as a query parameter. Args: compilation_result: a CompilationResult object derived from the GraphQL compiler arguments: dict, mapping argument name to its value, for every parameter the query expects. Returns: string, a Gremlin query with inserted argument data
f12688:m5
def _ensure_arguments_are_provided(expected_types, arguments):
<EOL>expected_arg_names = set(six.iterkeys(expected_types))<EOL>provided_arg_names = set(six.iterkeys(arguments))<EOL>if expected_arg_names != provided_arg_names:<EOL><INDENT>missing_args = expected_arg_names - provided_arg_names<EOL>unexpected_args = provided_arg_names - expected_arg_names<EOL>raise GraphQLInvalidArgumentError(u'<STR_LIT>'<EOL>u'<STR_LIT>'<EOL>u'<STR_LIT:{}>'.format(missing_args, unexpected_args))<EOL><DEDENT>
Ensure that all arguments expected by the query were actually provided.
f12689:m0
def insert_arguments_into_query(compilation_result, arguments):
_ensure_arguments_are_provided(compilation_result.input_metadata, arguments)<EOL>if compilation_result.language == MATCH_LANGUAGE:<EOL><INDENT>return insert_arguments_into_match_query(compilation_result, arguments)<EOL><DEDENT>elif compilation_result.language == GREMLIN_LANGUAGE:<EOL><INDENT>return insert_arguments_into_gremlin_query(compilation_result, arguments)<EOL><DEDENT>elif compilation_result.language == SQL_LANGUAGE:<EOL><INDENT>return insert_arguments_into_sql_query(compilation_result, arguments)<EOL><DEDENT>else:<EOL><INDENT>raise AssertionError(u'<STR_LIT>'<EOL>u'<STR_LIT:{}>'.format(compilation_result))<EOL><DEDENT>
Insert the arguments into the compiled GraphQL query to form a complete query. Args: compilation_result: a CompilationResult object derived from the GraphQL compiler arguments: dict, mapping argument name to its value, for every parameter the query expects. Returns: string, a query in the appropriate output language, with inserted argument data
f12689:m1
def _safe_match_string(value):
if not isinstance(value, six.string_types):<EOL><INDENT>if isinstance(value, bytes): <EOL><INDENT>value = value.decode('<STR_LIT:utf-8>')<EOL><DEDENT>else:<EOL><INDENT>raise GraphQLInvalidArgumentError(u'<STR_LIT>'<EOL>u'<STR_LIT:{}>'.format(value))<EOL><DEDENT><DEDENT>return json.dumps(value)<EOL>
Sanitize and represent a string argument in MATCH.
f12691:m0
def _safe_match_date_and_datetime(graphql_type, expected_python_types, value):
<EOL>value_type = type(value)<EOL>if not any(value_type == x for x in expected_python_types):<EOL><INDENT>raise GraphQLInvalidArgumentError(u'<STR_LIT>'<EOL>u'<STR_LIT>'<EOL>u'<STR_LIT:{}>'.format(expected_python_types, value_type, value))<EOL><DEDENT>try:<EOL><INDENT>serialized_value = graphql_type.serialize(value)<EOL><DEDENT>except ValueError as e:<EOL><INDENT>raise GraphQLInvalidArgumentError(e)<EOL><DEDENT>return _safe_match_string(serialized_value)<EOL>
Represent date and datetime objects as MATCH strings.
f12691:m1
def _safe_match_decimal(value):
decimal_value = coerce_to_decimal(value)<EOL>return '<STR_LIT>' + _safe_match_string(str(decimal_value)) + '<STR_LIT:)>'<EOL>
Represent decimal objects as MATCH strings.
f12691:m2
def _safe_match_list(inner_type, argument_value):
stripped_type = strip_non_null_from_type(inner_type)<EOL>if isinstance(stripped_type, GraphQLList):<EOL><INDENT>raise GraphQLInvalidArgumentError(u'<STR_LIT>'<EOL>u'<STR_LIT>'<EOL>u'<STR_LIT:{}>'.format(inner_type, argument_value))<EOL><DEDENT>if not isinstance(argument_value, list):<EOL><INDENT>raise GraphQLInvalidArgumentError(u'<STR_LIT>'<EOL>u'<STR_LIT:{}>'.format(argument_value))<EOL><DEDENT>components = (<EOL>_safe_match_argument(stripped_type, x)<EOL>for x in argument_value<EOL>)<EOL>return u'<STR_LIT:[>' + u'<STR_LIT:U+002C>'.join(components) + u'<STR_LIT:]>'<EOL>
Represent the list of "inner_type" objects in MATCH form.
f12691:m3
def _safe_match_argument(expected_type, argument_value):
if GraphQLString.is_same_type(expected_type):<EOL><INDENT>return _safe_match_string(argument_value)<EOL><DEDENT>elif GraphQLID.is_same_type(expected_type):<EOL><INDENT>if not isinstance(argument_value, six.string_types):<EOL><INDENT>if isinstance(argument_value, bytes): <EOL><INDENT>argument_value = argument_value.decode('<STR_LIT:utf-8>')<EOL><DEDENT>else:<EOL><INDENT>argument_value = six.text_type(argument_value)<EOL><DEDENT><DEDENT>return _safe_match_string(argument_value)<EOL><DEDENT>elif GraphQLFloat.is_same_type(expected_type):<EOL><INDENT>return represent_float_as_str(argument_value)<EOL><DEDENT>elif GraphQLInt.is_same_type(expected_type):<EOL><INDENT>if isinstance(argument_value, bool):<EOL><INDENT>raise GraphQLInvalidArgumentError(u'<STR_LIT>'<EOL>u'<STR_LIT:{}>'.format(argument_value))<EOL><DEDENT>return type_check_and_str(int, argument_value)<EOL><DEDENT>elif GraphQLBoolean.is_same_type(expected_type):<EOL><INDENT>return type_check_and_str(bool, argument_value)<EOL><DEDENT>elif GraphQLDecimal.is_same_type(expected_type):<EOL><INDENT>return _safe_match_decimal(argument_value)<EOL><DEDENT>elif GraphQLDate.is_same_type(expected_type):<EOL><INDENT>return _safe_match_date_and_datetime(expected_type, (datetime.date,), argument_value)<EOL><DEDENT>elif GraphQLDateTime.is_same_type(expected_type):<EOL><INDENT>return _safe_match_date_and_datetime(expected_type,<EOL>(datetime.datetime, arrow.Arrow), argument_value)<EOL><DEDENT>elif isinstance(expected_type, GraphQLList):<EOL><INDENT>return _safe_match_list(expected_type.of_type, argument_value)<EOL><DEDENT>else:<EOL><INDENT>raise AssertionError(u'<STR_LIT>'<EOL>u'<STR_LIT>'.format(expected_type, argument_value))<EOL><DEDENT>
Return a MATCH (SQL) string representing the given argument value.
f12691:m4
def insert_arguments_into_match_query(compilation_result, arguments):
if compilation_result.language != MATCH_LANGUAGE:<EOL><INDENT>raise AssertionError(u'<STR_LIT>'.format(compilation_result))<EOL><DEDENT>base_query = compilation_result.query<EOL>argument_types = compilation_result.input_metadata<EOL>sanitized_arguments = {<EOL>key: _safe_match_argument(argument_types[key], value)<EOL>for key, value in six.iteritems(arguments)<EOL>}<EOL>return base_query.format(**sanitized_arguments)<EOL>
Insert the arguments into the compiled MATCH query to form a complete query. Args: compilation_result: a CompilationResult object derived from the GraphQL compiler arguments: dict, mapping argument name to its value, for every parameter the query expects. Returns: string, a MATCH query with inserted argument data
f12691:m5
def represent_float_as_str(value):
<EOL>if not isinstance(value, float):<EOL><INDENT>raise GraphQLInvalidArgumentError(u'<STR_LIT>'<EOL>u'<STR_LIT:{}>'.format(value))<EOL><DEDENT>with decimal.localcontext() as ctx:<EOL><INDENT>ctx.prec = <NUM_LIT:20> <EOL>return u'<STR_LIT>'.format(decimal.Decimal(value))<EOL><DEDENT>
Represent a float as a string without losing precision.
f12692:m0
def type_check_and_str(python_type, value):
if not isinstance(value, python_type):<EOL><INDENT>raise GraphQLInvalidArgumentError(u'<STR_LIT>'<EOL>u'<STR_LIT>'.format(type=python_type, value=value))<EOL><DEDENT>return str(value)<EOL>
Type-check the value, and then just return str(value).
f12692:m1
def coerce_to_decimal(value):
if isinstance(value, decimal.Decimal):<EOL><INDENT>return value<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>return decimal.Decimal(value)<EOL><DEDENT>except decimal.InvalidOperation as e:<EOL><INDENT>raise GraphQLInvalidArgumentError(e)<EOL><DEDENT><DEDENT>
Attempt to coerce the value to a Decimal, or raise an error if unable to do so.
f12692:m2
def pretty_print_graphql(query, use_four_spaces=True):
<EOL>output = visit(parse(query), CustomPrintingVisitor())<EOL>if use_four_spaces:<EOL><INDENT>return fix_indentation_depth(output)<EOL><DEDENT>return output<EOL>
Take a GraphQL query, pretty print it, and return it.
f12693:m0
def fix_indentation_depth(query):
lines = query.split('<STR_LIT:\n>')<EOL>final_lines = []<EOL>for line in lines:<EOL><INDENT>consecutive_spaces = <NUM_LIT:0><EOL>for char in line:<EOL><INDENT>if char == '<STR_LIT:U+0020>':<EOL><INDENT>consecutive_spaces += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>if consecutive_spaces % <NUM_LIT:2> != <NUM_LIT:0>:<EOL><INDENT>raise AssertionError(u'<STR_LIT>'<EOL>u'<STR_LIT:{}>'.format(consecutive_spaces))<EOL><DEDENT>final_lines.append(('<STR_LIT:U+0020>' * consecutive_spaces) + line[consecutive_spaces:])<EOL><DEDENT>return '<STR_LIT:\n>'.join(final_lines)<EOL>
Make indentation use 4 spaces, rather than the 2 spaces GraphQL normally uses.
f12693:m1
def leave_Directive(self, node, *args):
name_to_arg_value = {<EOL>arg.split('<STR_LIT::>', <NUM_LIT:1>)[<NUM_LIT:0>]: arg<EOL>for arg in node.arguments<EOL>}<EOL>ordered_args = node.arguments<EOL>directive = DIRECTIVES_BY_NAME.get(node.name)<EOL>if directive:<EOL><INDENT>sorted_args = []<EOL>encountered_argument_names = set()<EOL>for defined_arg_name in six.iterkeys(directive.args):<EOL><INDENT>if defined_arg_name in name_to_arg_value:<EOL><INDENT>encountered_argument_names.add(defined_arg_name)<EOL>sorted_args.append(name_to_arg_value[defined_arg_name])<EOL><DEDENT><DEDENT>unsorted_args = [<EOL>value<EOL>for name, value in six.iteritems(name_to_arg_value)<EOL>if name not in encountered_argument_names<EOL>]<EOL>ordered_args = sorted_args + unsorted_args<EOL><DEDENT>return '<STR_LIT:@>' + node.name + wrap('<STR_LIT:(>', join(ordered_args, '<STR_LIT:U+002CU+0020>'), '<STR_LIT:)>')<EOL>
Call when exiting a directive node in the ast.
f12693:c0:m0
def insert_arguments_into_sql_query(compilation_result, arguments):
if compilation_result.language != SQL_LANGUAGE:<EOL><INDENT>raise AssertionError(u'<STR_LIT>'.format(compilation_result))<EOL><DEDENT>base_query = compilation_result.query<EOL>return base_query.params(**arguments)<EOL>
Insert the arguments into the compiled SQL query to form a complete query. Args: compilation_result: CompilationResult, compilation result from the GraphQL compiler. arguments: Dict[str, Any], parameter name -> value, for every parameter the query expects. Returns: SQLAlchemy Selectable, a executable SQL query with parameters bound.
f12694:m0
def remove_custom_formatting(query):
query = re.sub('<STR_LIT>', '<STR_LIT:U+0020>', query)<EOL>return query.replace('<STR_LIT>', '<STR_LIT:(>').replace('<STR_LIT>', '<STR_LIT:)>')<EOL>
Prepare the query string for pretty-printing by removing all unusual formatting.
f12695:m0
def pretty_print_gremlin(gremlin):
gremlin = remove_custom_formatting(gremlin)<EOL>too_many_parts = re.split(r'<STR_LIT>', gremlin)<EOL>parts = [<EOL>too_many_parts[i] + too_many_parts[i + <NUM_LIT:1>]<EOL>for i in six.moves.xrange(<NUM_LIT:0>, len(too_many_parts) - <NUM_LIT:1>, <NUM_LIT:2>)<EOL>]<EOL>parts.append(too_many_parts[-<NUM_LIT:1>])<EOL>for i in six.moves.xrange(<NUM_LIT:1>, len(parts)):<EOL><INDENT>parts[i] = '<STR_LIT:.>' + parts[i]<EOL><DEDENT>indentation = <NUM_LIT:0><EOL>indentation_increment = <NUM_LIT:4><EOL>output = []<EOL>for current_part in parts:<EOL><INDENT>if any([current_part.startswith('<STR_LIT>'),<EOL>current_part.startswith('<STR_LIT>'),<EOL>current_part.startswith('<STR_LIT>')]):<EOL><INDENT>indentation += indentation_increment<EOL><DEDENT>elif current_part.startswith('<STR_LIT>') or current_part.startswith('<STR_LIT>'):<EOL><INDENT>indentation -= indentation_increment<EOL>if indentation < <NUM_LIT:0>:<EOL><INDENT>raise AssertionError(u'<STR_LIT>'.format(indentation))<EOL><DEDENT><DEDENT>output.append(('<STR_LIT:U+0020>' * indentation) + current_part)<EOL><DEDENT>return '<STR_LIT:\n>'.join(output).strip()<EOL>
Return a human-readable representation of a gremlin command string.
f12695:m1
def pretty_print_match(match, parameterized=True):
left_curly = '<STR_LIT>' if parameterized else '<STR_LIT:{>'<EOL>right_curly = '<STR_LIT>' if parameterized else '<STR_LIT:}>'<EOL>match = remove_custom_formatting(match)<EOL>parts = re.split('<STR_LIT>'.format(left_curly, right_curly), match)<EOL>inside_braces = False<EOL>indent_size = <NUM_LIT:4><EOL>indent = '<STR_LIT:U+0020>' * indent_size<EOL>output = [parts[<NUM_LIT:0>]]<EOL>for current_index, current_part in enumerate(parts[<NUM_LIT:1>:]):<EOL><INDENT>if current_part == left_curly:<EOL><INDENT>if inside_braces:<EOL><INDENT>raise AssertionError(u'<STR_LIT>'<EOL>u'<STR_LIT>'.format(current_index, parts, match))<EOL><DEDENT>inside_braces = True<EOL>output.append(current_part + '<STR_LIT:\n>')<EOL><DEDENT>elif current_part == right_curly:<EOL><INDENT>if not inside_braces:<EOL><INDENT>raise AssertionError(u'<STR_LIT>'<EOL>u'<STR_LIT>'.format(current_index, parts, match))<EOL><DEDENT>inside_braces = False<EOL>output.append(current_part)<EOL><DEDENT>else:<EOL><INDENT>if not inside_braces:<EOL><INDENT>stripped_part = current_part.lstrip()<EOL>if stripped_part.startswith('<STR_LIT:.>'):<EOL><INDENT>output.append(stripped_part)<EOL><DEDENT>else:<EOL><INDENT>output.append(current_part)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>separate_keywords = re.split('<STR_LIT>', current_part)<EOL>output.append(indent + separate_keywords[<NUM_LIT:0>].lstrip())<EOL>for i in six.moves.xrange(<NUM_LIT:1>, len(separate_keywords) - <NUM_LIT:1>, <NUM_LIT:2>):<EOL><INDENT>output.append('<STR_LIT>'.format(<EOL>keyword=separate_keywords[i].strip(),<EOL>value=separate_keywords[i + <NUM_LIT:1>].strip(),<EOL>indent=indent))<EOL><DEDENT>output.append('<STR_LIT:\n>')<EOL><DEDENT><DEDENT><DEDENT>return '<STR_LIT>'.join(output).strip()<EOL>
Return a human-readable representation of a parameterized MATCH query string.
f12695:m2
def graphql_to_match(schema, graphql_query, parameters, type_equivalence_hints=None):
compilation_result = compile_graphql_to_match(<EOL>schema, graphql_query, type_equivalence_hints=type_equivalence_hints)<EOL>return compilation_result._replace(<EOL>query=insert_arguments_into_query(compilation_result, parameters))<EOL>
Compile the GraphQL input using the schema into a MATCH query and associated metadata. Args: schema: GraphQL schema object describing the schema of the graph to be queried graphql_query: the GraphQL query to compile to MATCH, as a string parameters: dict, mapping argument name to its value, for every parameter the query expects. type_equivalence_hints: optional dict of GraphQL interface or type -> GraphQL union. Used as a workaround for GraphQL's lack of support for inheritance across "types" (i.e. non-interfaces), as well as a workaround for Gremlin's total lack of inheritance-awareness. The key-value pairs in the dict specify that the "key" type is equivalent to the "value" type, i.e. that the GraphQL type or interface in the key is the most-derived common supertype of every GraphQL type in the "value" GraphQL union. Recursive expansion of type equivalence hints is not performed, and only type-level correctness of this argument is enforced. See README.md for more details on everything this parameter does. ***** Be very careful with this option, as bad input here will lead to incorrect output queries being generated. ***** Returns: a CompilationResult object, containing: - query: string, the resulting compiled and parameterized query string - language: string, specifying the language to which the query was compiled - output_metadata: dict, output name -> OutputMetadata namedtuple object - input_metadata: dict, name of input variables -> inferred GraphQL type, based on use
f12696:m0