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><IN... | 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'... | 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_... | 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>.... | 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_na... | 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_... | 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... | 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_edg... | 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 Tr... | 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 wher... | 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
Retu... | 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... | 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><D... | 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 fie... | 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>... | 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
... | 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>... | 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'<... | 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_i... | 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_inf... | 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, cur... | 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
loca... | 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... | 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... | 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 e... | 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... | 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.
Retu... | 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_sq... | 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.
... | 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_LI... | 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:
E... | 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:
... | 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:
... | 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 i... | 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 As... | 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... | 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 me... | 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><INDE... | 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 l... | 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[loc... | 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 opt... | 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_equ... | 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 ... | 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=que... | 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 Assertion... | 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_... | 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... | 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... | 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)<EO... | 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'... | 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.d... | 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)<E... | 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-s... | 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 GraphQLInvalidArgu... | 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_int... | 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 ... | 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)<EO... | 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 GraphQLInvalidArg... | 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.dec... | 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>f... | 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... | 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... | 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.... | 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 Selectabl... | 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... | 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_L... | 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,... | f12696:m0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.