construct a subquery from arg
171283
def create(cls, arg):
        
        obj = cls()
        obj._connection = arg.connection
        obj._heading = arg.heading.make_subquery_heading()
        obj._arg = arg
        return obj
979005
def selectSQL(conn, sql, args=None):
    '''
    
    '''
    with doCursor(conn) as cursor:
        cursor.execute(sql, args)
        results = cursor.fetchall()
        return results
1306424
def query_proc_row(procname, args=(), factory=None):
    
    for row in query_proc(procname, args, factory):
        return row
    return None
1205239
def query_args(self, name):
        
        sql = 'select type, id from code_items ' \
              'where kind = 22 and name = ?'
        logging.debug('%s %s', sql, (name,))
        self.cursor.execute(sql, (name,))
        func = self.cursor.fetchone()
        if func:
            sql = 'select param_number, type, name ' \
                  'from code_items where parent_id = ?'
            logging.debug('%s %s', sql, (func[1],))
            self.cursor.execute(sql, (func[1],))
            args = self.cursor.fetchall()
            ret_type = clean_ret_type(func[0])
            args = [
                (arg_number, sanitize_type(arg_type), arg_name)
                for arg_number, arg_type, arg_name in args
            ]
            return ret_type, name, args
        return None
949656
def _from_sql(self, soql):
        """"""
        # pylint:disable=too-many-branches,too-many-nested-blocks
        assert not self.soql, "Don't use _from_sql method directly"
        self.soql = soql
        soql, self.subqueries = split_subquery(soql)
        match_parse = re.match(r'SELECT (.*) FROM (\w+)\b(.*)$', soql, re.I)
        if not match_parse:
            raise ProgrammingError('Invalid SQL: %s' % self.soql)
        fields_sql, self.root_table, self.extra_soql = match_parse.groups()
        fields = [x.strip() for x in fields_sql.split(',')]
        self.is_aggregation = bool(pattern_groupby.search(self.extra_soql) or
                                   pattern_aggregation.search(fields[0]))
        self.is_plain_count = fields[0].upper() == 'COUNT()'
        consumed_subqueries = 0
        expr_alias_counter = 0
        #
        if not self.is_plain_count:
            for field in fields:
                if self.is_aggregation:
                    match = re.search(r'\b\w+$', field)
                    if match:
                        alias = match.group()
                        assert alias not in RESERVED_WORDS, "invalid alias name"
                        if match.start() > 0 and field[match.start() - 1] == ' ':
                            field = field[match.start() - 1]
                    else:
                        alias = 'expr{}'.format(expr_alias_counter)
                        expr_alias_counter += 1
                    assert '&' not in field, "Subquery not expected as field in aggregation query"
                elif '&' in field:
                    assert field == '(&)'  # verify that the subquery was in parentheses
                    subquery = QQuery(self.subqueries[consumed_subqueries][0])
                    consumed_subqueries += 1
                    self.has_child_rel_field = True
                    field = subquery
                    # TODO more child relationships to the same table
                    alias = subquery.root_table
                else:
                    alias = field
                    if '.' in alias:
                        if alias.split('.', 1)[0].lower() == self.root_table.lower():
                            alias = alias.split('.', 1)[1]
                        if '.' in alias:
                            # prepare paths for possible empty outer joins
                            subroots = self.subroots
                            root_crumbs = alias.lower().split('.')[:-1]
                            for scrumb in root_crumbs:
                                subroots.setdefault(scrumb, {})
                                subroots = subroots[scrumb]
                self.aliases.append(alias)
                self.fields.append(field)
1284561
function schema (args) {
    // get args object
    args = requireValidOptionalObject(args)
    // get colunmn and index information from database
    return Promise.all([
        this.mysql().query(sql.describe(this)),
        this.mysql().query(sql.showCreateTable(this)),
        this.mysql().query(sql.showIndexes(this)),
    ])
    // build schema from database response
    .then(res => {
        // get columns and indexes from describe and show index queries
        var columns = res[0][0]
        var createTable = res[1][0]
        var indexes = res[2][0]
        // schema data
        var schema = {
            columns: {},
            indexes: [],
        }
        // get first and only create table record
        createTable = _.get(createTable, "[0]['Create Table']", '')
        // get engine and charset from create table sql
        var engine = createTable.match(/ENGINE=(\w+)/)
        schema.engine = engine && engine[1] || ''
        var charset = createTable.match(/DEFAULT CHARSET=(\w+)/)
        schema.charset = charset && charset[1] || ''
        // build column data
        _.each(columns, dbColumn => {
            var column = schema.columns[dbColumn.Field] = {}
            // check unsigned
            if (dbColumn.Type.match(/unsigned$/)) {
                column.unsigned = true
                dbColumn.Type = dbColumn.Type.replace(/ unsigned/, '')
            }
            // char id column
            if (dbColumn.Type === 'char(32)') {
                // model must not be set for binary ids
                assert.ok(this.binaryIds === false, 'binaryIds must be disabled for char id columns')
                // set type
                column.type = 'id'
            }
            // binary id column
            else if (dbColumn.Type === 'binary(16)') {
                // model must be set for binary ids
                assert.ok(this.binaryIds === true, 'binaryIds must be enabled for binary id columns')
                // set type
                column.type = 'id'
            }
            // all other column types
            else  {
                // require valid type
                assert.ok(sql.columnTypesInverse[dbColumn.Type], 'unrecognized column type '+dbColumn.Type)
                // map database to internal type
                column.type = sql.columnTypesInverse[dbColumn.Type]
            }
            // is column nullable
            if (dbColumn.Null === 'NO') {
                column.null = false
            }
            // set default if not null
            if (dbColumn.Default) {
                column.default = dbColumn.Default
                // convert boolean
                if (column.type === 'boolean') {
                    column.default = column.default === '1' ? true : false
                }
            }
        })
        // map of indexes by key name since keys may cover multiple columns
        var indexesByKey = {}
        // build map of indexes by key name
        _.each(indexes, dbIndex => {
            // create entry for index if it does not already exist
            if (!indexesByKey[dbIndex.Key_name]) {
                indexesByKey[dbIndex.Key_name] = {
                    columns: {}
                }
            }
            // get entry for index
            var index = indexesByKey[dbIndex.Key_name]
            // add column with sequence in index
            index.columns[dbIndex.Column_name] = parseInt(dbIndex.Seq_in_index)
            // add unique flag if true
            if (dbIndex.Non_unique === '0') {
                index.unique = true
            }
        })
        // add indexes to schema
        _.each(indexesByKey, (index, name) => {
            var indexColumns = _.keys(index.columns)
            // multi-column index
            if (indexColumns.length > 1) {
                // sort index columns by the Seq_in_index value - these may
                // always be in order so this may not be needed
                indexColumns = _.sortBy(indexColumns, indexColumn => index.columns[indexColumn])
                // create schema index entry
                var schemaIndex = {
                    columns: indexColumns,
                }
                // set unique flag
                if (index.unique) {
                    schemaIndex.unique = true
                }
                // add index to schema
                schema.indexes.push(schemaIndex)
            }
            // single column index
            else {
                // get first and only column
                var indexColumn = indexColumns[0]
                // PRIMARY KEY
                if (name === 'PRIMARY') {
                    schema.columns[indexColumn].primary = true
                }
                // unique index
                else if (index.unique) {
                    schema.columns[indexColumn].unique = true
                }
                // non-unique index
                else {
                    schema.columns[indexColumn].index = true
                }
            }
        })
        // resolve with schema
        return schema
    })
    .catch(err => {
        // reject on anything besides a table does not exist error
        // if table does not exist resolve with undefined
        if (err.errno !== 1146) {
            throw err
        }
    })
}
1314355
def split_subquery(sql):
    """"""
    sql, params = mark_quoted_strings(sql)
    sql = simplify_expression(sql)
    _ = params  # NOQA
    start = 0
    out = []
    subqueries = []
    pattern = re.compile(r'\(SELECT\b', re.I)
    match = pattern.search(sql, start)
    while match:
        out.append(sql[start:match.start() + 1] + '&')
        start, pos = find_closing_parenthesis(sql, match.start())
        start, pos = start + 1, pos - 1
        subqueries.append(split_subquery(sql[start:pos]))
        start = pos
        match = pattern.search(sql, start)
    out.append(sql[start:len(sql)])
    return ''.join(out), subqueries
835005
def _query_and_op(self, tree, table, method_name, method_kwargs):
        
        result = []
        if tree.keys_in:
            if tree.using:
                raise SyntaxError("Cannot use USING with KEYS IN")
            keys = self._iter_where_in(tree)
        else:
            visitor = Visitor(self.reserved_words)
            (action, kwargs, _) = self._build_query(table, tree, visitor)
            attrs = [visitor.get_field(table.hash_key.name)]
            if table.range_key is not None:
                attrs.append(visitor.get_field(table.range_key.name))
            kwargs["attributes"] = attrs
            kwargs["expr_values"] = visitor.expression_values
            kwargs["alias"] = visitor.attribute_names
            # If there is no 'where' on this update/delete, check with the
            # caution_callback before proceeding.
            if (
                visitor.expression_values is None
                and callable(self.caution_callback)
                and not self.caution_callback(method_name)  # pylint: disable=E1102
            ):
                return False
            method = getattr(self.connection, action + "2")
            keys = method(table.name, **kwargs)
            if self._explaining:
                try:
                    list(keys)
                except ExplainSignal:
                    keys = [{}]

        method = getattr(self.connection, method_name + "2")
        count = 0
        for key in keys:
            try:
                ret = method(table.name, key, **method_kwargs)
            except CheckFailed:
                continue
            count += 1
            if ret:
                result.append(ret)
        if result:
            return result
        else:
            return count
96585
def get_args(self):
        
        for table in self.tables + self.with_tables:
            if type(table) is QueryTable:
                self._where.args.update(table.query.get_args())

        return self._where.args
62142
def query(self, expr, **kwargs):
        

        def gen_table_expr(table, expr):
            resolver = {
                name: FakeSeries(dtype.to_pandas_dtype())
                for name, dtype in zip(table.schema.names, table.schema.types)
            }
            scope = Scope(level=0, resolvers=(resolver,))
            return Expr(expr=expr, env=scope)

        import pyarrow.gandiva as gandiva

        unary_ops = {"~": "not"}
        math_calls = {"log": "log", "exp": "exp", "log10": "log10", "cbrt": "cbrt"}
        bin_ops = {
            "+": "add",
            "-": "subtract",
            "*": "multiply",
            "/": "divide",
            "**": "power",
        }
        cmp_ops = {
            "==": "equal",
            "!=": "not_equal",
            ">": "greater_than",
            "<": "less_than",
            "<=": "less_than_or_equal_to",
            ">": "greater_than",
            ">=": "greater_than_or_equal_to",
            "like": "like",
        }

        def build_node(table, terms, builder):
            if isinstance(terms, Constant):
                return builder.make_literal(
                    terms.value, (pa.from_numpy_dtype(terms.return_type))
                )

            if isinstance(terms, Term):
                return builder.make_field(table.schema.field_by_name(terms.name))

            if isinstance(terms, BinOp):
                lnode = build_node(table, terms.lhs, builder)
                rnode = build_node(table, terms.rhs, builder)
                return_type = pa.from_numpy_dtype(terms.return_type)

                if terms.op == "&":
                    return builder.make_and([lnode, rnode])
                if terms.op == "|":
                    return builder.make_or([lnode, rnode])
                if terms.op in cmp_ops:
                    assert return_type == pa.bool_()
                    return builder.make_function(
                        cmp_ops[terms.op], [lnode, rnode], return_type
                    )
                if terms.op in bin_ops:
                    return builder.make_function(
                        bin_ops[terms.op], [lnode, rnode], return_type
                    )

            if isinstance(terms, UnaryOp):
                return_type = pa.from_numpy_dtype(terms.return_type)
                return builder.make_function(
                    unary_ops[terms.op],
                    [build_node(table, terms.operand, builder)],
                    return_type,
                )

            if isinstance(terms, MathCall):
                return_type = pa.from_numpy_dtype(terms.return_type)
                childern = [
                    build_node(table, child, builder) for child in terms.operands
                ]
                return builder.make_function(
                    math_calls[terms.op], childern, return_type
                )

            raise TypeError("Unsupported term type: %s" % terms)

        def can_be_condition(expr):
            if isinstance(expr.terms, BinOp):
                if expr.terms.op in cmp_ops or expr.terms.op in ("&", "|"):
                    return True
            elif isinstance(expr.terms, UnaryOp):
                if expr.terms.op == "~":
                    return True
            return False

        def filter_with_selection_vector(table, s):
            record_batch = table.to_batches()[0]
            indices = s.to_array()  # .to_numpy()
            new_columns = [
                pa.array(c.to_numpy()[indices]) for c in record_batch.columns
            ]
            return pa.Table.from_arrays(new_columns, record_batch.schema.names)

        def gandiva_query(table, query):
            expr = gen_table_expr(table, query)
            if not can_be_condition(expr):
                raise ValueError("Root operation should be a filter.")
            builder = gandiva.TreeExprBuilder()
            root = build_node(table, expr.terms, builder)
            cond = builder.make_condition(root)
            filt = gandiva.make_filter(table.schema, cond)
            sel_vec = filt.evaluate(table.to_batches()[0], pa.default_memory_pool())
            result = filter_with_selection_vector(table, sel_vec)
            return result

        def gandiva_query2(table, query):
            expr = gen_table_expr(table, query)
            if not can_be_condition(expr):
                raise ValueError("Root operation should be a filter.")
            builder = gandiva.TreeExprBuilder()
            root = build_node(table, expr.terms, builder)
            cond = builder.make_condition(root)
            filt = gandiva.make_filter(table.schema, cond)
            return filt

        def query_builder(arrow_table, **kwargs):
            return gandiva_query(arrow_table, kwargs.get("expr", ""))

        kwargs["expr"] = expr
        func = self._prepare_method(query_builder, **kwargs)
        new_data = self._map_across_full_axis(1, func)
        # Query removes rows, so we need to update the index
        new_index = self.compute_index(0, new_data, False)
        return self.__constructor__(
            new_data, new_index, self.columns, self._dtype_cache
        )
874597
public <T> T querySingleTypedResult(String sql, String[] args, int column) {
		return db.querySingleTypedResult(sql, args, column);
	}
968144
def query(self, sql, *args, **kwargs):
        
        with self.locked() as conn:
            for row in conn.query(sql, *args, **kwargs):
                yield row
892351
public @NotNull QueryBuilder append(@NotNull String sql, @NotNull Collection<?> args) {
        query.append(requireNonNull(sql));
        addArguments(args);
        return this;
    }
386447
function runSubqueries (subQueries, callback, collection) {
        var i,
            responsesReceived = 0,
            length = subQueries.length,
            joinedSet = [];//The array where the results are going to get stuffed

        if (subQueries.length > 0) {
            for (i = 0; i < subQueries.length; i += 1) {

                collection.aggregate(subQueries[i], function (err, results) {
                    joinedSet = joinedSet.concat(results);
                    responsesReceived += 1;

                    if (responsesReceived === length) {
                        callback(joinedSet);
                    }
                });
            }
        } else {
            callback([]);
        }

        return joinedSet;
    }
871532
public <T> List<List<T>> queryTypedResults(String sql, String[] args) {
		@SuppressWarnings("unchecked")
		List<List<T>> result = (List<List<T>>) (Object) queryResults(sql, args);
		return result;
	}
743477
public @NotNull QueryBuilder append(@NotNull String sql, Object... args) {
        return append(sql, asList(args));
    }
534817
def excute_query(query, db=None, flags=None, use_sudo=False, **kwargs):
    """"""

    flags = flags or u''
    if db:
        flags = u"%s -d %s" % (flags, db)
    command = u'psql %s -c "%s"' % (flags, query)
    if use_sudo:
        sudo(command, user='postgres', **kwargs)
    else:
        run(command, **kwargs)