Translate a project node into SQLQuery.
        :param node: a treebrd node
        :return: a SQLQuery object for the tree rooted at node
193822
def project(self, node):
        
        child_object = self.translate(node.child)
        child_object.select_block = str(node.attributes)
        return child_object
887037
def reprocess_tree_node(self, tree_node, tx_context=None):
        
        if not tx_context:
            # create transaction context if one was not provided
            # format: {process_name: {timeperiod: AbstractTreeNode} }
            tx_context = collections.defaultdict(dict)

        if tree_node.parent is None:
            # do not process 'root' - the only node that has None as 'parent'
            return tx_context
        if tree_node.timeperiod in tx_context[tree_node.process_name]:
            # the node has already been marked for re-processing
            return tx_context

        if tree_node.job_record.is_embryo:
            # the node does not require re-processing
            pass
        else:
            state_machine_name = context.process_context[tree_node.process_name].state_machine_name
            state_machine = self.state_machines[state_machine_name]
            state_machine.reprocess_job(tree_node.job_record)

        tx_context[tree_node.process_name][tree_node.timeperiod] = tree_node
        self.reprocess_tree_node(tree_node.parent, tx_context)

        dependant_nodes = self._find_dependant_tree_nodes(tree_node)
        for node in dependant_nodes:
            self.reprocess_tree_node(node, tx_context)

        return tx_context
423000
private void convertToTermsQuery(FilterJoinNode node) {
    Map<String, Object> parent = node.getParentSourceMap();
    FilterJoinTerms terms = node.getTerms();
    BytesRef bytes = terms.getEncodedTerms();

    // Remove the filter join from the parent
    parent.remove(FilterJoinBuilder.NAME);

    // Create the nested object for the parameters of the field data terms query
    Map<String, Object> queryParams = new HashMap<>();
    queryParams.put("value", bytes.bytes);
    // use the hash of the filter join source map as cache key - see #170
    queryParams.put("_cache_key", node.getCacheId());

    // Create the nested object for the field
    Map<String, Object> field = new HashMap<>();
    field.put(node.getField(), queryParams);

    // Create the nested object for the field data terms query
    Map<String, Object> termsQuery = new HashMap<>();
    // If bytes terms encoding is used, we switch to the terms enum based terms query
    if (node.getTermsEncoding().equals(TermsByQueryRequest.TermsEncoding.BYTES)) {
      termsQuery.put(TermsEnumTermsQueryParser.NAME, field);
    }
    else {
      termsQuery.put(FieldDataTermsQueryParser.NAME, field);
    }

    // Create the object for the constant score query
    Map<String, Object> constantScoreQueryParams = new HashMap<>();
    constantScoreQueryParams.put("filter", termsQuery);

    // Add the constant score query to the parent
    parent.put(ConstantScoreQueryParser.NAME, constantScoreQueryParams);
    node.setState(FilterJoinNode.State.CONVERTED);
    this.blockingQueue.poll();
  }
579274
def compile(self, node, *args, **kwargs):
        """"""
        if isinstance(node, WhereNode):
            return where_node_as_ldap(node, self, self.connection)
        return super(SQLCompiler, self).compile(node, *args, **kwargs)
858495
def convert_node(self, node):
        
        convert = getattr(self, 'convert_' + striptag(node.tag))
        return convert(node)
829240
public Object visit(QueryRootNode node, Object data) throws RepositoryException {
        StringBuilder sb = (StringBuilder) data;
        try {
            sb.append("SELECT");

            InternalQName[] selectProps = node.getSelectProperties();
            if (selectProps.length == 0) {
                sb.append(" *");
            } else {
                String comma = "";
                for (int i = 0; i < selectProps.length; i++) {
                    sb.append(comma).append(" ");
                    appendName(selectProps[i], resolver, sb);
                    comma = ",";
                }
            }

            sb.append(" FROM");

            // node type restrictions are within predicates of location nodes
            // therefore we write the where clause first to a temp string to
            // collect the node types.
            StringBuilder tmp = new StringBuilder();
            LocationStepQueryNode[] steps = node.getLocationNode().getPathSteps();
            QueryNode[] predicates = steps[steps.length - 1].getPredicates();
            // are there any relevant predicates?
            for (int i = 0; i < predicates.length; i++) {
                if (predicates[i].getType() != QueryNode.TYPE_NODETYPE) {
                    tmp.append(" WHERE ");
                }
            }
            String and = "";
            for (int i = 0; i < predicates.length; i++) {
                if (predicates[i].getType() != QueryNode.TYPE_NODETYPE) {
                    tmp.append(and);
                    and = " AND ";
                }
                predicates[i].accept(this, tmp);
            }

            // node types have been collected by now
            String comma = "";
            int ntCount = 0;
            for (Iterator<InternalQName> it = nodeTypes.iterator(); it.hasNext(); ntCount++) {
               InternalQName nt = it.next();
                sb.append(comma).append(" ");
                appendName(nt, resolver, sb);
                comma = ",";
            }

            if (ntCount == 0) {
                sb.append(" ");
                sb.append(resolver.createJCRName(Constants.NT_BASE).getAsString());
            }

            // append WHERE clause
            sb.append(tmp.toString());

            if (steps.length == 2
                    && steps[1].getIncludeDescendants()
                    && steps[1].getNameTest() == null) {
                // then this query selects all paths
            } else if (steps.length == 1
                    && steps[0].getIncludeDescendants()
                    && steps[0].getNameTest() == null) {
                // then this query selects all paths
            } else {
                if (predicates.length > 0) {
                    sb.append(" AND ");
                } else {
                    sb.append(" WHERE ");
                }
                node.getLocationNode().accept(this, sb);
            }
        } catch (NamespaceException e) {
            exceptions.add(e);
        }

        if (node.getOrderNode() != null) {
            node.getOrderNode().accept(this, sb);
        }

        return sb;
    }
1056072
function fromQueryNode(query) {
  var node = query.attrs.node.split('#')[0];
  var caps = new Caps(node);
  var identities = query.getChildren('identity');
  var features = query.getChildren('feature');

  identities.forEach(function(id) {
    caps.addIdentity(id.attrs.category, id.attrs.type, id.attrs.name, id.attrs.lang);
  });
  features.forEach(function(feature) {
    caps.addFeature(feature.attrs.var);
  });

  return caps;
}
635646
def insert_node(**kw):
    ""
    with current_app.app_context():
        result = db.execute(text(fetch_query_string('insert_node.sql')), **kw)
        # TODO: support for postgres may require using a RETURNING id; sql
        # statement and using the inserted_primary_key?
        #node_id = result.inserted_primary_key
        node_id = result.lastrowid
        if (not node_id):
            result = result.fetchall()
            node_id = result[0]['id']
        return node_id
341837
def select(self, node):
        
        child = self.translate(node.child)
        return '[.${op}_{{{conditions}}}$ {child} ]'\
            .format(op=latex_operator[node.operator],
                    conditions=node.conditions, child=child)
680677
def _normalize_branch_node(self, node):
        
        iter_node = iter(node)
        if any(iter_node) and any(iter_node):
            return node

        if node[16]:
            return [compute_leaf_key([]), node[16]]

        sub_node_idx, sub_node_hash = next(
            (idx, v)
            for idx, v
            in enumerate(node[:16])
            if v
        )
        sub_node = self.get_node(sub_node_hash)
        sub_node_type = get_node_type(sub_node)

        if sub_node_type in {NODE_TYPE_LEAF, NODE_TYPE_EXTENSION}:
            with self._prune_node(sub_node):
                new_subnode_key = encode_nibbles(tuple(itertools.chain(
                    [sub_node_idx],
                    decode_nibbles(sub_node[0]),
                )))
                return [new_subnode_key, sub_node[1]]
        elif sub_node_type == NODE_TYPE_BRANCH:
            subnode_hash = self._persist_node(sub_node)
            return [encode_nibbles([sub_node_idx]), subnode_hash]
        else:
            raise Exception("Invariant: this code block should be unreachable")
497580
def start_node(self):
        
        return db.cypher_query("MATCH (aNode) "
                               "WHERE id(aNode)={nodeid} "
                               "RETURN aNode".format(nodeid=self._start_node_id),
                               resolve_objects = True)[0][0][0]
1028082
def filter_nodes(n: Node, query: str) -> CompatNodeIterator:
    
    return CompatNodeIterator(filter(n, query)._nodeit, only_nodes=True)
220995
def get_from_clause(self):
        
        result = super(MultilingualSQLCompiler, self).get_from_clause()

        if not self.query.include_translation_data:
            return result

        from_ = result[0]
        for join in self.query.extra_join.values():
            from_.append(join)
        return (from_, result[1])
783179
def get_tables_for_query_pre_16(query):
    
    from django.db.models.sql.where import WhereNode
    from django.db.models.query import QuerySet
    tables = set([v[0] for v in getattr(query,'alias_map',{}).values()])

    def get_tables(node, tables):
        for child in node.children:
            if isinstance(child, WhereNode):  # and child.children:
                tables = get_tables(child, tables)
            elif not hasattr(child, '__iter__'):
                continue
            else:
                for item in (c for c in child if isinstance(c, QuerySet)):
                    tables |= set(get_tables_for_query(item.query))
        return tables

    if query.where and query.where.children:
        where_nodes = [c for c in query.where.children if isinstance(c, WhereNode)]
        for node in where_nodes:
            tables |= get_tables(node, tables)

    return list(tables)
1282884
def _select(self, tree, allow_select_scan):
        
        tablename = tree.table
        desc = self.describe(tablename, require=True)
        kwargs = {}
        if tree.consistent:
            kwargs["consistent"] = True

        visitor = Visitor(self.reserved_words)

        selection = SelectionExpression.from_selection(tree.attrs)
        if selection.is_count:
            kwargs["select"] = "COUNT"

        if tree.keys_in:
            if tree.limit:
                raise SyntaxError("Cannot use LIMIT with KEYS IN")
            elif tree.using:
                raise SyntaxError("Cannot use USING with KEYS IN")
            elif tree.order:
                raise SyntaxError("Cannot use DESC/ASC with KEYS IN")
            elif tree.where:
                raise SyntaxError("Cannot use WHERE with KEYS IN")
            keys = list(self._iter_where_in(tree))
            kwargs["attributes"] = selection.build(visitor)
            kwargs["alias"] = visitor.attribute_names
            return self.connection.batch_get(tablename, keys=keys, **kwargs)

        if tree.limit:
            if tree.scan_limit:
                kwargs["limit"] = Limit(
                    scan_limit=resolve(tree.scan_limit[2]),
                    item_limit=resolve(tree.limit[1]),
                    strict=True,
                )
            else:
                kwargs["limit"] = Limit(item_limit=resolve(tree.limit[1]), strict=True)
        elif tree.scan_limit:
            kwargs["limit"] = Limit(scan_limit=resolve(tree.scan_limit[2]))

        (action, query_kwargs, index) = self._build_query(desc, tree, visitor)
        if action == "scan" and not allow_select_scan:
            raise SyntaxError(
                "No index found for query. Please use a SCAN query, or "
                "set allow_select_scan=True\nopt allow_select_scan true"
            )
        order_by = None
        if tree.order_by:
            order_by = tree.order_by[0]
        reverse = tree.order == "DESC"
        if tree.order:
            if action == "scan" and not tree.order_by:
                raise SyntaxError(
                    "No index found for query, "
                    "cannot use ASC or DESC without "
                    "ORDER BY <field>"
                )
            if action == "query":
                if order_by is None or order_by == index.range_key:
                    kwargs["desc"] = reverse

        kwargs.update(query_kwargs)

        # This is a special case for when we're querying an index and selecting
        # fields that aren't projected into the index.
        # We will change the query to only fetch the primary keys, and then
        # fill in the selected attributes after the fact.
        fetch_attrs_after = False
        if index is not None and not index.projects_all_attributes(
            selection.all_fields
        ):
            kwargs["attributes"] = [
                visitor.get_field(a) for a in desc.primary_key_attributes
            ]
            fetch_attrs_after = True
        else:
            kwargs["attributes"] = selection.build(visitor)
        kwargs["expr_values"] = visitor.expression_values
        kwargs["alias"] = visitor.attribute_names

        method = getattr(self.connection, action + "2")
        result = method(tablename, **kwargs)

        # If the queried index didn't project the selected attributes, we need
        # to do a BatchGetItem to fetch all the data.
        if fetch_attrs_after:
            if not isinstance(result, list):
                result = list(result)
            # If no results, no need to batch_get
            if not result:
                return result
            visitor = Visitor(self.reserved_words)
            kwargs = {"keys": [desc.primary_key(item) for item in result]}
            kwargs["attributes"] = selection.build(visitor)
            kwargs["alias"] = visitor.attribute_names
            result = self.connection.batch_get(tablename, **kwargs)

        def order(items):
            """ Sort the items by the specified keys """
            if order_by is None:
                return items
            if index is None or order_by != index.range_key:
                if not isinstance(items, list):
                    items = list(items)
                items.sort(key=lambda x: x.get(order_by), reverse=reverse)
            return items

        # Save the data to a file
        if tree.save_file:
            if selection.is_count:
                raise Exception("Cannot use count(*) with SAVE")
            count = 0
            result = order(selection.convert(item, True) for item in result)
            filename = tree.save_file[0]
            if filename[0] in ['"', "'"]:
                filename = unwrap(filename)
            # If it's still an iterator, convert to a list so we can iterate
            # multiple times.
            if not isinstance(result, list):
                result = list(result)
            remainder, ext = os.path.splitext(filename)
            if ext.lower() in [".gz", ".gzip"]:
                ext = os.path.splitext(remainder)[1]
                opened = gzip.open(filename, "wb")
            else:
                opened = open(filename, "wb")
            if ext.lower() == ".csv":
                if selection.all_keys:
                    headers = selection.all_keys
                else:
                    # Have to do this to get all the headers :(
                    result = list(result)
                    all_headers = set()
                    for item in result:
                        all_headers.update(item.keys())
                    headers = list(all_headers)
                with opened as ofile:
                    writer = csv.DictWriter(
                        ofile, fieldnames=headers, extrasaction="ignore"
                    )
                    writer.writeheader()
                    for item in result:
                        count += 1
                        writer.writerow(item)
            elif ext.lower() == ".json":
                with opened as ofile:
                    for item in result:
                        count += 1
                        ofile.write(self._encoder.encode(item))
                        ofile.write("\n")
            else:
                with opened as ofile:
                    for item in result:
                        count += 1
                        pickle.dump(item, ofile)
            return count
        elif not selection.is_count:
            result = order(selection.convert(item) for item in result)

        return result
1218602
def _prune_node(self, node):
        
        if self.is_pruning:
            # node is mutable, so capture the key for later pruning now
            prune_key, node_body = self._node_to_db_mapping(node)
            should_prune = (node_body is not None)
        else:
            should_prune = False

        yield

        # Prune only if no exception is raised
        if should_prune:
            del self.db[prune_key]
319706
def to_qtree(self, instring, schema):
        
        root_list = self.to_syntax_tree(instring, schema)
        return qtree_translator.translate(root_list)