This method is used for SELECT * or x.* queries
196145
public List<Field> resolveFieldsWithPrefix(Optional<QualifiedName> prefix)
    {
        return visibleFields.stream()
                .filter(input -> input.matchesPrefix(prefix))
                .collect(toImmutableList());
    }
1294145
def _query(self, x, result):
        '''
        
        '''
        if self.single_interval is None: # Empty
            return
        elif self.single_interval != 0:  # Single interval, just check whether x is in it
            if self.single_interval[0] <= x < self.single_interval[1]:
                result.append(self.single_interval)
        elif x < self.center:            # Normal tree, query point to the left of center
            if self.left_subtree is not None:
                self.left_subtree._query(x, result)
            for int in self.mid_sorted_by_start:
                if int[0] <= x:
                    result.append(int)
                else:
                    break
        else:  # Normal tree, query point to the right of center
            for int in self.mid_sorted_by_end:
                if int[1] > x:
                    result.append(int)
                else:
                    break
            if self.right_subtree is not None:
                self.right_subtree._query(x, result)
789923
def query( self ):
        
        # create the query compound
        if ( self.childCount() ):
            q = Q()
            operator = 'and'
            for i in range(self.childCount()):
                item = self.child(i)
                if ( isinstance(item, XQueryItem) ):
                    if ( operator == 'and' ):
                        q &= item.query()
                    else:
                        q |= item.query()
                else:
                    operator = nativestring(item.text(0))
            return q
        
        # create the query for this individual item
        else:
            q = Q(self.columnName())
            q.setOperatorType(self.operatorType())
            q.setValue(self.value())
            return q
322769
@When("^I query the database with '(.+?)'$")
    public void selectData(String query) throws Exception {
        Statement myStatement = null;
        //postgres table
        List<String> sqlTable = new ArrayList<String>();
        List<String> sqlTableAux = new ArrayList<String>();
        Connection myConnection = this.commonspec.getConnection();
        java.sql.ResultSet rs = null;
        try {
            myStatement = myConnection.createStatement();
            rs = myStatement.executeQuery(query);
            //column names
            ResultSetMetaData resultSetMetaData = rs.getMetaData();
            int count = resultSetMetaData.getColumnCount();
            for (int i = 1; i <= count; i++) {
                sqlTable.add(resultSetMetaData.getColumnName(i).toString());
            }
            //takes column names and column count
            while (rs.next()) {
                for (int i = 1; i <= count; i++) {
                    //aux list without column names
                    sqlTableAux.add(rs.getObject(i).toString());
                }
            }
            sqlTable.addAll(sqlTableAux);

            //sends raws to environment variable
            for (int i = 0; i < sqlTable.size(); i++) {
                ThreadProperty.set("queryresponse" + i, sqlTable.get(i));
            }
            ThreadProperty.remove("queryresponse" + sqlTable.size());
            rs.close();
            myStatement.close();
        } catch (Exception e) {
            e.printStackTrace();
            Assertions.assertThat(rs).as("There are no response from SELECT").isNotNull();
        }
    }
895491
def _setop(self, query):
        
        if isinstance(query.select, list):
            # RETURN BORING RESULT SET
            selects = FlatList()
            for s in listwrap(query.select):
                if isinstance(s.value, Mapping):
                    for k, v in s.value.items:
                        selects.append(sql_alias(v, quote_column(s.name + "." + k)))
                if isinstance(s.value, list):
                    for i, ss in enumerate(s.value):
                        selects.append(sql_alias(s.value, quote_column(s.name + "," + str(i))))
                else:
                    selects.append(sql_alias(s.value, quote_column(s.name)))

            sql = expand_template("""
                SELECT
                    {{selects}}
                FROM
                    {{table}}
                {{where}}
                {{sort}}
                {{limit}}
            """, {
                "selects": SQL(",\n".join(selects)),
                "table": self._subquery(query["from"])[0],
                "where": self._where2sql(query.where),
                "limit": self._limit2sql(query.limit),
                "sort": self._sort2sql(query.sort)
            })

            def post_process(sql):
                result = self.db.query(sql)
                for s in listwrap(query.select):
                    if isinstance(s.value, Mapping):
                        for r in result:
                            r[s.name] = {}
                            for k, v in s.value:
                                r[s.name][k] = r[s.name + "." + k]
                                r[s.name + "." + k] = None

                    if isinstance(s.value, list):
                        # REWRITE AS TUPLE
                        for r in result:
                            r[s.name] = tuple(r[s.name + "," + str(i)] for i, ss in enumerate(s.value))
                            for i, ss in enumerate(s.value):
                                r[s.name + "," + str(i)] = None

                expand_json(result)
                return result

            return sql, post_process  # RETURN BORING RESULT SET
        else:
            # RETURN LIST OF VALUES
            if query.select.value == ".":
                select = "*"
            else:
                name = query.select.name
                select = sql_alias(query.select.value, quote_column(name))

            sql = expand_template("""
                SELECT
                    {{selects}}
                FROM
                    {{table}}
                {{where}}
                {{sort}}
                {{limit}}
            """, {
                "selects": SQL(select),
                "table": self._subquery(query["from"])[0],
                "where": self._where2sql(query.where),
                "limit": self._limit2sql(query.limit),
                "sort": self._sort2sql(query.sort)
            })

            if query.select.value == ".":
                def post(sql):
                    result = self.db.query(sql)
                    expand_json(result)
                    return result

                return sql, post
            else:
                return sql, lambda sql: [r[name] for r in self.db.query(sql)]
298509
def get_x():
    '''
    
    '''
    cmd = 'setxkbmap -query | grep layout'
    out = __salt__['cmd.run'](cmd, python_shell=True).split(':')
    return out[1].strip()
266927
def select(self, fields=['rowid', '*'], offset=None, limit=None):
        ''' 
        '''
        # base SQL
        SQL = 'SELECT %s FROM %s' % (','.join(fields), self._table)
        
        # selectors
        if self._selectors:
            SQL = ' '.join([SQL, 'WHERE', self._selectors]).strip()
        
        # modifiers
        if self._modifiers:
            SQL = ' '.join([SQL, self._modifiers])

        # limit
        if limit is not None and isinstance(limit, int):
            SQL = ' '.join((SQL, 'LIMIT %s' % limit))

        # offset
        if (limit is not None) and (offset is not None) and isinstance(offset, int):
            SQL = ' '.join((SQL, 'OFFSET %s' % offset))

        return ''.join((SQL, ';'))
166024
def select(self, to_select, where=None, sql_params=None):
        '''
        
        '''
        if sql_params is None:
            sql_params = []
        query = '''
        SELECT %s FROM %s
        ''' % (to_select, self._name)
        if where:
            query = '%s WHERE %s' % (query, where)
        return self._cursor.execute(query, tuple(sql_params))
832582
def select_all(*str_or_rx)
      results = str_or_rx.flatten.map { |v| select_all_by v }
      results.first
    end
622389
public Either<String, Either<Joiner4All, Mapper4All>> query(String sqlQuery, Map<String, String> reqHeaders) {
        return query(sqlQuery, null, reqHeaders, false, "sql");
    }
816585
private Status runQuery(QueryOptions options, QueryRowBlock block) {
        if (options == null)
            options = new QueryOptions();

        // OPT: It would be faster to use separate tables for raw-or ascii-collated views so that
        // they could be indexed with the right collation, instead of having to specify it here.
        String collationStr = "";
        if (collation == View.TDViewCollation.TDViewCollationASCII)
            collationStr += " COLLATE JSON_ASCII";
        else if (collation == View.TDViewCollation.TDViewCollationRaw)
            collationStr += " COLLATE JSON_RAW";


        StringBuilder sql = new StringBuilder("SELECT key, value, docid, revs.sequence");
        if (options.isIncludeDocs()) {
            sql.append(", revid, json");
        }
        sql.append(String.format(Locale.ENGLISH, " FROM 'maps_%s', revs, docs", mapTableName()));
        sql.append(" WHERE 1");

        List<String> argsList = new ArrayList<String>();

        if (options.getKeys() != null && options.getKeys().size() > 0) {
            sql.append(" AND key in (");
            String item = "?";
            for (Object key : options.getKeys()) {
                // null key should be ignored
                if (key != null) {
                    sql.append(item);
                    item = ", ?";
                    argsList.add(toJSONString(key));
                }
            }
            sql.append(')');
        }

        Object minKey = options.getStartKey();
        Object maxKey = options.getEndKey();
        String minKeyDocId = options.getStartKeyDocId();
        String maxKeyDocId = options.getEndKeyDocId();

        boolean inclusiveMin = options.isInclusiveStart();
        boolean inclusiveMax = options.isInclusiveEnd();
        if (options.isDescending()) {
            Object min = minKey;
            minKey = maxKey;
            maxKey = min;
            inclusiveMin = inclusiveMax;
            inclusiveMax = true;
            minKeyDocId = options.getEndKeyDocId();
            maxKeyDocId = options.getStartKeyDocId();
        }

        if (minKey != null) {
            String minKeyJSON = toJSONString(minKey);
            sql.append(inclusiveMin ? " AND key >= ?" : " AND key > ?");
            sql.append(collationStr);
            argsList.add(minKeyJSON);
            if (minKeyDocId != null && inclusiveMin) {
                //OPT: This calls the JSON collator a 2nd time unnecessarily.
                sql.append(String.format(Locale.ENGLISH, " AND (key > ? %s OR docid >= ?)", collationStr));
                argsList.add(minKeyJSON);
                argsList.add(minKeyDocId);
            }
        }

        if (maxKey != null) {
            maxKey = View.keyForPrefixMatch(maxKey, options.getPrefixMatchLevel());
            String maxKeyJSON = toJSONString(maxKey);
            sql.append(inclusiveMax ? " AND key <= ?" : " AND key < ?");
            sql.append(collationStr);
            argsList.add(maxKeyJSON);
            if (maxKeyDocId != null && inclusiveMax) {
                sql.append(String.format(Locale.ENGLISH, " AND (key < ? %s OR docid <= ?)", collationStr));
                argsList.add(maxKeyJSON);
                argsList.add(maxKeyDocId);
            }
        }

        sql.append(String.format(Locale.ENGLISH,
                " AND revs.sequence = 'maps_%s'.sequence AND docs.doc_id = revs.doc_id ORDER BY key",
                mapTableName()));
        sql.append(collationStr);
        if (options.isDescending()) {
            sql.append(" DESC");
        }
        sql.append(options.isDescending() ? ", docid DESC" : ", docid");

        sql.append(" LIMIT ? OFFSET ?");
        argsList.add(Integer.toString(options.getLimit()));
        argsList.add(Integer.toString(options.getSkip()));

        Log.v(Log.TAG_VIEW, "Query %s: %s | args: %s", name, sql.toString(), argsList);

        Status status = new Status(Status.OK);
        Cursor cursor = null;
        try {
            cursor = store.getStorageEngine().rawQuery(sql.toString(),
                    argsList.toArray(new String[argsList.size()]));
            // regular query
            cursor.moveToNext();
            while (!cursor.isAfterLast()) {
                // Call the block!
                byte[] keyData = cursor.getBlob(0);
                byte[] valueData = cursor.getBlob(1);
                String docID = cursor.getString(2);
                status = block.onRow(keyData, valueData, docID, cursor);
                if (status.isError())
                    break;
                else if (status.getCode() <= 0) {
                    status = new Status(Status.OK);
                    break;
                }
                cursor.moveToNext();
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return status;
    }
224853
function where(column, operator, value) {

    // Support "where true || where false"
    if (column === false || column === true) {
      return this.where(1, '=', column ? 1 : 0);
    }

    // Check if the column is a function, in which case it's
    // a where statement wrapped in parens.
    if (typeof column === 'function') {
      return this.whereWrapped(column);
    }

    // Allow a raw statement to be passed along to the query.
    if (column instanceof Raw && arguments.length === 1) {
      return this.whereRaw(column);
    }

    // Allows `where({id: 2})` syntax.
    if (typeof column === 'object' && !(column instanceof Raw)) {
      return this._objectWhere(column);
    }

    // Enable the where('key', value) syntax, only when there
    // are explicitly two arguments passed, so it's not possible to
    // do where('key', '!=') and have that turn into where key != null
    if (arguments.length === 2) {
      value = operator;
      operator = '=';

      // If the value is null, and it's a two argument query,
      // we assume we're going for a `whereNull`.
      if (value === null) {
        return this.whereNull(column);
      }
    }

    // lower case the operator for comparison purposes
    var checkOperator = ('' + operator).toLowerCase().trim();

    // If there are 3 arguments, check whether 'in' is one of them.
    if (arguments.length === 3) {
      if (checkOperator === 'in' || checkOperator === 'not in') {
        return this._not(checkOperator === 'not in').whereIn(arguments[0], arguments[2]);
      }
      if (checkOperator === 'between' || checkOperator === 'not between') {
        return this._not(checkOperator === 'not between').whereBetween(arguments[0], arguments[2]);
      }
    }

    // If the value is still null, check whether they're meaning
    // where value is null
    if (value === null) {

      // Check for .where(key, 'is', null) or .where(key, 'is not', 'null');
      if (checkOperator === 'is' || checkOperator === 'is not') {
        return this._not(checkOperator === 'is not').whereNull(column);
      }
    }

    // Push onto the where statement stack.
    this._statements.push({
      grouping: 'where',
      type: 'whereBasic',
      column: column,
      operator: operator,
      value: value,
      not: this._not(),
      bool: this._bool()
    });
    return this;
  }
847409
public static <T> JDOQuery<T> select(Expression<T> expr) {
        return new JDOQuery<Void>().select(expr);
    }
718382
def compile_select(self, query):
        
        sql = super(MySqlQueryGrammar, self).compile_select(query)

        if query.unions:
            sql = '(%s) %s' % (sql, self._compile_unions(query))

        return sql
1094228
private void get(final StringBuilder sql) {
        sql.append("SELECT * FROM ").append(getName()).append(" WHERE ").append(JdbcRepositories.getDefaultKeyName()).append(" = ?");
    }
1263740
function selectById () {
    // always select all columns
    _.each(this.model.columnNames, columnName => {
        // get column spec
        var spec = this.model.columns[columnName]
        // add select column sql
        this.select.push(
            this.selectColumnSql(this.model, columnName, spec, this.table)
        )
    })
    // build query parts
    this.selectSql = `SELECT ${this.select.join(', ')}`
    this.fromSql = `FROM ${this.quoteName(this.table)} ${this.alias}`
    this.whereSql = this.selectByIdWhereSql()
    // build full query
    this.sql = `${this.selectSql} ${this.fromSql} ${this.whereSql}`
}
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