Reduces multiple queries into a single usable query
7682
def generate_query(self):
        
        query = Q()
        ORed = []
        for form in self._non_deleted_forms:
            if not hasattr(form, 'cleaned_data'):
                continue
            if form.cleaned_data['field'] == "_OR":
                ORed.append(query)
                query = Q()
            else:
                query = query & form.make_query()
        if ORed:
            if query:  # add last query for OR if any
                ORed.append(query)
            query = reduce(operator.or_, ORed)
        return query
430301
def dmql(query):
        """"""
        if isinstance(query, dict):
            raise ValueError("You supplied a dictionary to the dmql_query parameter, but a string is required."
                                " Did you mean to pass this to the search_filter parameter? ")

        # automatically surround the given query with parentheses if it doesn't have them already
        if len(query) > 0 and query != "*" and query[0] != '(' and query[-1] != ')':
            query = '({})'.format(query)
        return query
1222328
def get(self, query, *parameters, **kwargs):
        """"""
        rows = self.query(query, *parameters, **kwargs)
        if not rows:
            return None
        elif len(rows) > 1:
            raise ValueError('Multiple rows returned for get() query')
        else:
            return rows[0]
1294273
function getSubqueries (inQueries, orQueries, otherQuery, pageSize, rightKeys) {
        var subqueries = [],
            numberOfChunks,
            i,
            inQuery,
            orQuery,
            queryArray,
            from,
            to;
        //                                                   this is a stupid way to turn numbers into 1
        numberOfChunks = (orQueries.length / pageSize) + (!!(orQueries.length % pageSize));

        for (i = 0; i < numberOfChunks; i += 1) {
            inQuery = {};
            from = i * pageSize;
            to = from + pageSize;

            rightKeys.forEach(function (key, index) {
                inQuery[rightKeys[index]] = {$in: inQueries[index].slice(from, to)};
            });

            orQuery = { $or: orQueries.slice(from, to)};

            queryArray = [ { $match: inQuery }, { $match: orQuery } ];

            if(otherQuery) {
                queryArray.push({ $match: otherQuery });
                //Push this to the end on the assumption that the join properties will be indexed, and the arbitrary 
                //filter properties won't be indexed.
            }
            subqueries.push(queryArray);
        }
        return subqueries;
    }
1169698
def getquery(query):
	''
	try:
		conn = connection.cursor()
		conn.execute(query)
		data = conn.fetchall()
		conn.close()
	except: data = list()
	return data
568192
private void pruneExpiredQueries()
    {
        if (expirationQueue.size() <= maxQueryHistory) {
            return;
        }

        int count = 0;
        // we're willing to keep full info for up to maxQueryHistory queries
        for (T query : expirationQueue) {
            if (expirationQueue.size() - count <= maxQueryHistory) {
                break;
            }
            query.pruneInfo();
            count++;
        }
    }
507487
def query(self, search, query):
        
        if query:
            if self.fields:
                return search.query('multi_match', fields=self.fields, query=query)
            else:
                return search.query('multi_match', query=query)
        return search
703621
def get_find_all_query(self, table_name, constraints=None, *, columns=None, order_by=None,
                         limiting=(None, None)):
    
    where, params = self.parse_constraints(constraints)

    if columns:
      if isinstance(columns, str):
        pass
      else:
        columns = ", ".join(columns)
    else:
      columns = "*"

    if order_by:
      order = " order by {0}".format(order_by)
    else:
      order = ""

    paging = ""
    if limiting is not None:
      limit, offset = limiting
      if limit is not None:
        paging += " limit {0}".format(limit)
      if offset is not None:
        paging += " offset {0}".format(offset)

    return ("select {0} from {1} where {2}{3}{4}".format(
      columns,
      table_name,
      where or "1 = 1",
      order,
      paging
    ), params)
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
356580
def _normalize_query(self, query):
        

        for k, v in query.items():
            if isinstance(v, list):
                query[k] = ','.join([str(e) for e in v])
877003
def simpleQuery(self, queryType, rawResults = False, **queryArgs) :
        
        return SimpleQuery(self, queryType, rawResults, **queryArgs)
1006006
def query(self):
        
        if self._rawquery==True:
            return self.__query
        return flatten(self.__query)
446353
private void cleanupQueryStates() {
        completeRequestSpan(currentRequest());
        finishedDecoding();
        queryInfoObservable = null;
        queryRowObservable = null;
        queryErrorObservable = null;
        queryStatusObservable = null;
        querySignatureObservable = null;
        queryParsingState = QUERY_STATE_INITIAL;
    }
1181662
def _aggop(self, query):
        
        if isinstance(query.select, list):
            # RETURN SINGLE OBJECT WITH AGGREGATES
            for s in query.select:
                if s.aggregate not in aggregates:
                    Log.error("Expecting all columns to have an aggregate: {{select}}", select=s)

            selects = FlatList()
            for s in query.select:
                selects.append(sql_alias(aggregates[s.aggregate].replace("{{code}}", s.value),quote_column(s.name)))

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

            return sql, lambda sql: self.db.column(sql)[0]  # RETURNING SINGLE OBJECT WITH AGGREGATE VALUES
        else:
            # RETURN SINGLE VALUE
            s0 = query.select
            if s0.aggregate not in aggregates:
                Log.error("Expecting all columns to have an aggregate: {{select}}", select=s0)

            select = sql_alias(aggregates[s0.aggregate].replace("{{code}}", s0.value) , quote_column(s0.name))

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

            def post(sql):
                result = self.db.column_query(sql)
                return result[0][0]

            return sql, post
849012
def _duplicate_queries(self, output):
        """"""
        if QC_SETTINGS['DISPLAY_DUPLICATES']:
            for query, count in self.queries.most_common(QC_SETTINGS['DISPLAY_DUPLICATES']):
                lines = ['\nRepeated {0} times.'.format(count)]
                lines += wrap(query)
                lines = "\n".join(lines) + "\n"
                output += self._colorize(lines, count)
        return output
1124108
def clean_query(query, replace=chr(26)):
        
        accum = []
        any_invalid = False
        tokens = _quote_re.findall(query)
        for token in tokens:
            if token.startswith('"') and token.endswith('"'):
                accum.append(token)
                continue
            token_set = set(token)
            invalid_for_token = token_set & _invalid_ascii
            if invalid_for_token:
                any_invalid = True
                for c in invalid_for_token:
                    token = token.replace(c, replace)
            accum.append(token)

        if any_invalid:
            return ' '.join(accum)
        return query
1214231
function querySearch( query, single, embed, callback ) {
    var embd = '';
        if ( single ) {
        for ( var key in embed ) {
            if (  embed.hasOwnProperty(key) ) {
                embd += '&embed[]=' + embed[key];
            }
        }
    }

    var url = apiBaseUrl + ( single ? endpoints['query']['single'] : endpoints['query']['multi'] ) + query + embd;

    fetch(url, function(result) {
        callback(result);
    });
}