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
348643
def emit_code_from_ir(sql_query_tree, compiler_metadata):
    
    context = CompilationContext(
        query_path_to_selectable=dict(),
        query_path_to_location_info=sql_query_tree.query_path_to_location_info,
        query_path_to_output_fields=sql_query_tree.query_path_to_output_fields,
        query_path_to_filters=sql_query_tree.query_path_to_filters,
        query_path_to_node=sql_query_tree.query_path_to_node,
        compiler_metadata=compiler_metadata,
    )

    return _query_tree_to_query(sql_query_tree.root, context)
517097
def sql_key(self, generation, sql, params, order, result_type,
                using='default'):
        
        # these keys will always look pretty opaque
        suffix = self.keygen.gen_key(sql, params, order, result_type)
        using = settings.DB_CACHE_KEYS[using]
        return '%s_%s_query_%s.%s' % (self.prefix, using, generation, suffix)
224805
def query(self, parents=None):
        
        # TODO: benchmark single-query strategy
        q = Select([])
        q = self.project(q, parent=True)
        q = self.filter(q, parents=parents)

        if self.parent is None:
            subq = Select([self.var])
            subq = self.filter(subq, parents=parents)
            subq = subq.offset(self.node.offset)
            subq = subq.limit(self.node.limit)
            subq = subq.distinct()
            # TODO: sorting.
            subq = subq.order_by(desc(self.var))
            q = q.where(subq)

        # if hasattr(self.context, 'identifier'):
        #     q._where = graph(self.context.identifier, q._where)
        log.debug("Compiled query: %r", q.compile())
        return q
1262189
def to_sql(self):
        
        return self._sql_query_skeleton.format(
            prefix=self.prefix, select=self.select_block,
            relation=self.from_block, conditions=self.where_block)
641661
def querySQL(self, sql, args=()):
        
        if self.debug:
            result = timeinto(self.queryTimes, self._queryandfetch, sql, args)
        else:
            result = self._queryandfetch(sql, args)
        return result
481509
def query(self, query, stacked=False):
        
        from jx_base.query import QueryOp

        query = QueryOp.wrap(query)

        sql, post = self._subquery(query, isolate=False, stacked=stacked)
        query.data = post(sql)
        return query.data
1245244
def _build_query(self, table, tree, visitor):
        
        kwargs = {}
        index = None
        if tree.using:
            index_name = kwargs["index"] = tree.using[1]
            index = table.get_index(index_name)
        if tree.where:
            constraints = ConstraintExpression.from_where(tree.where)
            possible_hash = constraints.possible_hash_fields()
            possible_range = constraints.possible_range_fields()
            if index is None:
                # See if we can find an index to query on
                indexes = table.get_matching_indexes(possible_hash, possible_range)
                if not indexes:
                    action = "scan"
                    kwargs["filter"] = constraints.build(visitor)
                    kwargs["expr_values"] = visitor.expression_values
                    kwargs["alias"] = visitor.attribute_names
                elif len(indexes) == 1:
                    index = indexes[0]
                    action = "query"
                    add_query_kwargs(kwargs, visitor, constraints, index)
                else:
                    names = ", ".join([index.name for index in indexes])
                    raise SyntaxError(
                        "No index specified with USING <index>, "
                        "but multiple possibilities for query: "
                        "%s" % names
                    )
            else:
                if index.hash_key in possible_hash:
                    action = "query"
                    add_query_kwargs(kwargs, visitor, constraints, index)
                else:
                    action = "scan"
                    if not index.scannable:
                        raise SyntaxError("Cannot scan local index %r" % index_name)
                    kwargs["filter"] = constraints.build(visitor)
                    kwargs["expr_values"] = visitor.expression_values
                    kwargs["alias"] = visitor.attribute_names
        else:
            action = "scan"
        return [action, kwargs, index]
89979
def _get_queries(self, migration, method):
        
        connection = migration.get_connection()
        db = connection

        with db.pretend():
            getattr(migration, method)()

        return db.get_logged_queries()
310798
def _query_db(self, mapping):
        
        model = self.models[mapping.get("table")]

        # Use primary key instead of the field mapped to SF Id
        fields = mapping.get("fields", {}).copy()
        if mapping["oid_as_pk"]:
            del fields["Id"]
        id_column = model.__table__.primary_key.columns.keys()[0]
        columns = [getattr(model, id_column)]

        for f in fields.values():
            columns.append(model.__table__.columns[f])
        lookups = mapping.get("lookups", {}).copy()
        for lookup in lookups.values():
            lookup["aliased_table"] = aliased(
                self.metadata.tables["{}_sf_ids".format(lookup["table"])]
            )
            columns.append(lookup["aliased_table"].columns.sf_id)

        query = self.session.query(*columns)
        if "record_type" in mapping and hasattr(model, "record_type"):
            query = query.filter(model.record_type == mapping["record_type"])
        if "filters" in mapping:
            filter_args = []
            for f in mapping["filters"]:
                filter_args.append(text(f))
            query = query.filter(*filter_args)
        for sf_field, lookup in lookups.items():
            # Outer join with lookup ids table:
            # returns main obj even if lookup is null
            key_field = get_lookup_key_field(lookup, sf_field)
            value_column = getattr(model, key_field)
            query = query.outerjoin(
                lookup["aliased_table"],
                lookup["aliased_table"].columns.id == value_column,
            )
            # Order by foreign key to minimize lock contention
            # by trying to keep lookup targets in the same batch
            lookup_column = getattr(model, key_field)
            query = query.order_by(lookup_column)
        self.logger.info(str(query))
        return query
143050
def query(self):
        
        query = self._builder_class(
            self,
            self._query_grammar,
            self._post_processor,
            **self._builder_default_kwargs
        )

        return query
976739
def get_pyquery(self, tree=None, page_numbers=None):
        
        if not page_numbers:
            page_numbers = []
        if tree is None:
            if not page_numbers and self.tree is not None:
                tree = self.tree
            else:
                tree = self.get_tree(page_numbers)
        if hasattr(tree, 'getroot'):
            tree = tree.getroot()
        return PyQuery(tree, css_translator=PDFQueryTranslator())
990766
def query(self, query):
    '''
    '''
    self.logger.info('%s: query %s' % (self, query))
    return super(LoggingDatastore, self).query(query)
1263838
private String getSubQuerySQL(Query subQuery)
    {
        ClassDescriptor cld = getRoot().cld.getRepository().getDescriptorFor(subQuery.getSearchClass());
        String sql;

        if (subQuery instanceof QueryBySQL)
        {
            sql = ((QueryBySQL) subQuery).getSql();
        }
        else
        {
            sql = new SqlSelectStatement(this, m_platform, cld, subQuery, m_logger).getStatement();
        }

        return sql;
    }
1211577
def _gql(query_string, query_class=Query):
  
  from .google_imports import gql  # Late import, to avoid name conflict.
  gql_qry = gql.GQL(query_string)
  kind = gql_qry.kind()
  if kind is None:
    # The query must be lacking a "FROM <kind>" class.  Let Expando
    # stand in for the model class (it won't actually be used to
    # construct the results).
    modelclass = model.Expando
  else:
    modelclass = model.Model._lookup_model(
        kind,
        tasklets.get_context()._conn.adapter.default_model)
    # Adjust kind to the kind of the model class.
    kind = modelclass._get_kind()
  ancestor = None
  flt = gql_qry.filters()
  filters = list(modelclass._default_filters())
  for name_op in sorted(flt):
    name, op = name_op
    values = flt[name_op]
    op = op.lower()
    if op == 'is' and name == gql.GQL._GQL__ANCESTOR:
      if len(values) != 1:
        raise ValueError('"is" requires exactly one value')
      [(func, args)] = values
      ancestor = _args_to_val(func, args)
      continue
    if op not in _OPS:
      raise NotImplementedError('Operation %r is not supported.' % op)
    for (func, args) in values:
      val = _args_to_val(func, args)
      prop = _get_prop_from_modelclass(modelclass, name)
      if prop._name != name:
        raise RuntimeError('Whoa! _get_prop_from_modelclass(%s, %r) '
                           'returned a property whose name is %r?!' %
                           (modelclass.__name__, name, prop._name))
      if isinstance(val, ParameterizedThing):
        node = ParameterNode(prop, op, val)
      elif op == 'in':
        node = prop._IN(val)
      else:
        node = prop._comparison(op, val)
      filters.append(node)
  if filters:
    filters = ConjunctionNode(*filters)
  else:
    filters = None
  orders = _orderings_to_orders(gql_qry.orderings(), modelclass)
  offset = gql_qry.offset()
  limit = gql_qry.limit()
  if limit < 0:
    limit = None
  keys_only = gql_qry._keys_only
  if not keys_only:
    keys_only = None
  options = QueryOptions(offset=offset, limit=limit, keys_only=keys_only)
  projection = gql_qry.projection()
  if gql_qry.is_distinct():
    group_by = projection
  else:
    group_by = None
  qry = query_class(kind=kind,
                    ancestor=ancestor,
                    filters=filters,
                    orders=orders,
                    default_options=options,
                    projection=projection,
                    group_by=group_by)
  return qry
21385
def get_sql(self, with_default_expression=True):
        '''
        
        '''
        if with_default_expression:
            if self.alias:
                return '%s ALIAS %s' % (self.db_type, self.alias)
            elif self.materialized:
                return '%s MATERIALIZED %s' % (self.db_type, self.materialized)
            else:
                default = self.to_db_string(self.default)
                return '%s DEFAULT %s' % (self.db_type, default)
        else:
            return self.db_type
11749
def get_queryset(self, *args, **kwargs):
        
        qs = super(TreeManager, self).get_queryset(*args, **kwargs)

        # Restrict operations to pages on the current site if needed
        if settings.PAGES_HIDE_SITES and settings.PAGES_USE_SITE_ID:
            return qs.order_by(self.tree_id_attr, self.left_attr).filter(sites=settings.SITE_ID)
        else:
            return qs.order_by(self.tree_id_attr, self.left_attr)
1252542
def query( self ):
        
        if ( not self.uiQueryCHK.isChecked() ):
            return None
        
        # build a query if not searching all
        q = Q()
        for i in range(self.uiQueryTREE.topLevelItemCount()):
            item = self.uiQueryTREE.topLevelItem(i)
            q &= item.query()
        return q