Analyzes a single query
966599
def generate_query_report(self, db_uri, query, db_name, collection_name):
        """"""
        return self._query_analyzer.generate_query_report(db_uri,
                                                          query,
                                                          db_name,
                                                          collection_name)
1106007
def _find_multiple(self, match_class, **keywds):
        """"""
        self._logger.debug('find all query execution - started')
        start_time = timeit.default_timer()
        norm_keywds = self.__normalize_args(**keywds)
        decl_matcher = self.__create_matcher(match_class, **norm_keywds)
        dtype = self.__findout_decl_type(match_class, **norm_keywds)
        recursive_ = self.__findout_recursive(**norm_keywds)
        allow_empty = self.__findout_allow_empty(**norm_keywds)
        decls = self.__findout_range(norm_keywds['name'], dtype, recursive_)
        found = matcher.find(decl_matcher, decls, False)
        mfound = mdecl_wrapper.mdecl_wrapper_t(found)
        self._logger.debug('%d declaration(s) that match query', len(mfound))
        self._logger.debug(
            'find single query execution - done( %f seconds )',
            (timeit.default_timer() - start_time))
        if not mfound and not allow_empty:
            raise RuntimeError(
                "Multi declaration query returned 0 declarations.")
        return mfound
1207106
function (query) {
        return _.isString(query) ? query.split(AMPERSAND).map(QueryParam.parseSingle) : [];
    }
749053
def analyses():
    """"""
    per_page = int(request.args.get('per_page', 50))
    page = int(request.args.get('page', 1))
    query = store.analyses(status=request.args.get('status'),
                           query=request.args.get('query'),
                           is_visible=request.args.get('is_visible') == 'true' or None)

    query_page = query.paginate(page, per_page=per_page)
    data = []
    for analysis_obj in query_page.items:
        analysis_data = analysis_obj.to_dict()
        analysis_data['user'] = analysis_obj.user.to_dict() if analysis_obj.user else None
        analysis_data['failed_jobs'] = [job_obj.to_dict() for job_obj in analysis_obj.failed_jobs]
        data.append(analysis_data)

    return jsonify(analyses=data)
531952
def filter_query(key, expression):
    """"""
    if (isinstance(expression, dict)
            and len(expression) == 1
            and list(expression.keys())[0].startswith('$')):
        compiled_expression = compile_query(expression)
    elif callable(expression):
        def _filter(index, expression=expression):
            result = [store_key
                      for value, store_keys in index.get_index().items()
                      if expression(value)
                      for store_key in store_keys]
            return result
        compiled_expression = _filter
    else:
        compiled_expression = expression

    def _get(query_function, key=key, expression=compiled_expression):
        """Get document key and check against expression."""
        return query_function(key, expression)

    return _get
563452
def query(name):
    """"""
    collection = Collection.query.filter_by(name=name).one()
    click.echo(collection.dbquery)
1038649
function compactGraphQLQuery (query) {
    let lexer = new Tokenizr()

    /*  configure lexical analysis  */
    lexer.rule(/#[^\r\n]*(?=\r?\n)/,                       (ctx, match) => { ctx.accept("comment") })
    lexer.rule(/"(?:\\"|[^"])*"/,                          (ctx, match) => { ctx.accept("string") })
    lexer.rule(/$[a-zA-Z_][a-zA-Z0-9_]*/,                  (ctx, match) => { ctx.accept("var") })
    lexer.rule(/[a-zA-Z_][a-zA-Z0-9_]*/,                   (ctx, match) => { ctx.accept("id") })
    lexer.rule(/[+-]?[0-9]*\.?[0-9]+(?:[eE][+-]?[0-9]+)?/, (ctx, match) => { ctx.accept("number") })
    lexer.rule(/[ \t\r\n]+/,                               (ctx, match) => { ctx.accept("ws", " ") })
    lexer.rule(/[{}]/,                                     (ctx, match) => { ctx.accept("brace") })
    lexer.rule(/[[\]]/,                                    (ctx, match) => { ctx.accept("bracket") })
    lexer.rule(/[()]/,                                     (ctx, match) => { ctx.accept("parenthesis") })
    lexer.rule(/,/,                                        (ctx, match) => { ctx.accept("comma") })
    lexer.rule(/!/,                                        (ctx, match) => { ctx.accept("not") })
    lexer.rule(/\.\.\./,                                   (ctx, match) => { ctx.accept("ellipsis") })
    lexer.rule(/@/,                                        (ctx, match) => { ctx.accept("at") })
    lexer.rule(/:/,                                        (ctx, match) => { ctx.accept("colon") })
    lexer.rule(/./,                                        (ctx, match) => { ctx.accept("any") })
    lexer.input(query)
    lexer.debug(false)

    /*  fetch all parsed tokens  */
    let tokens = lexer.tokens()

    /*  remove whitespace tokens at harmless positions  */
    let output = ""
    let re = /^(?:brace|bracket|parenthesis|comma|colon)$/
    for (let i = 0; i < tokens.length; i++) {
        if (   tokens[i].type === "comment"
            || (   tokens[i].type === "ws"
                && (   (   i < tokens.length - 1
                        && tokens[i + 1].type.match(re))
                    || (    i > 0
                        && tokens[i - 1].type.match(re))))) {
            tokens.splice(i, 1)
            i--
        }
    }

    /*  assembly and return new query string  */
    tokens.forEach((token) => {
        output += token.value
    })
    return output
}
1167839
def _generate_query_analysis(self, parsed_query, db_name, collection_name):
        """"""

        analyzed_fields = []
        field_count = 0
        supported = True
        sort_fields = []
        query_mask = None

        if 'command' in parsed_query and parsed_query['command'] not in SUPPORTED_COMMANDS:
            supported = False
        else:
            #if 'orderby' in parsed_query:
            sort_component = parsed_query['orderby'] if 'orderby' in parsed_query else []
            sort_seq = 0
            for key in sort_component:
                sort_field = {'fieldName': key,
                              'fieldType': SORT_TYPE,
                              'seq': sort_seq}
                sort_fields.append(key)
                analyzed_fields.append(sort_field)
                field_count += 1
                sort_seq += 1

            query_component = parsed_query['query'] if 'query' in parsed_query else {}
            for key in query_component:
                if key not in sort_fields:
                    field_type = UNSUPPORTED_TYPE
                    if ((key not in UNSUPPORTED_QUERY_OPERATORS) and
                            (key not in COMPOSITE_QUERY_OPERATORS)):
                        try:
                            if query_component[key] == {}:
                                raise
                            nested_field_list = query_component[key].keys()
                        except:
                            field_type = EQUIV_TYPE
                        else:
                            for nested_field in nested_field_list:
                                if ((nested_field in RANGE_QUERY_OPERATORS) and
                                    (nested_field not in UNSUPPORTED_QUERY_OPERATORS)):
                                    field_type = RANGE_TYPE
                                else:
                                    supported = False
                                    field_type = UNSUPPORTED_TYPE
                                    break

                    if field_type is UNSUPPORTED_TYPE:
                        supported = False

                    analyzed_field = {'fieldName': key,
                                      'fieldType': field_type}
                    analyzed_fields.append(analyzed_field)
                    field_count += 1

        query_mask = parsed_query['queryMask']

        # QUERY ANALYSIS
        return OrderedDict({
            'analyzedFields': analyzed_fields,
            'fieldCount': field_count,
            'supported': supported,
            'queryMask': query_mask
        })
1064387
def _all(self, query):
        """"""
        if query.count() > 0:
            results = query.all()
            for result in results:
                if result.has_expired(self._expirations):
                    raise NotFoundError
            return results
        else:
            raise NotFoundError
554260
private void parseInputQuery(String query) {
    List<String> projectedColumns = new ArrayList<>();
    if (StringUtils.isNotBlank(query)) {
      String queryLowerCase = query.toLowerCase();
      int startIndex = queryLowerCase.indexOf("select ") + 7;
      int endIndex = queryLowerCase.indexOf(" from ");
      if (startIndex >= 0 && endIndex >= 0) {
        String columnProjection = query.substring(startIndex, endIndex);
        this.setInputColumnProjection(columnProjection);
        // parse the select list
        StringBuffer sb = new StringBuffer();
        int bracketCount = 0;
        for (int i = 0; i < columnProjection.length(); i++) {
          char c = columnProjection.charAt(i);
          if (c == '(') {
            bracketCount++;
          }

          if (c == ')') {
            bracketCount--;
          }

          if (bracketCount != 0) {
            sb.append(c);
          } else {
            if (c != ',') {
              sb.append(c);
            } else {
              projectedColumns.add(sb.toString());
              sb = new StringBuffer();
            }
          }
        }
        projectedColumns.add(sb.toString());
      }
    }

    if (this.isSelectAllColumns()) {
      List<String> columnList = this.getMetadataColumnList();
      for (String columnName : columnList) {
        ColumnAttributes col = new ColumnAttributes();
        col.setColumnName(columnName);
        col.setAliasName(columnName);
        col.setSourceColumnName(columnName);
        this.addToColumnAliasMap(col);
      }
    } else {
      for (String projectedColumn : projectedColumns) {
        String column = projectedColumn.trim();
        String alias = null;
        String sourceColumn = column;
        int spaceOccurences = StringUtils.countMatches(column.trim(), " ");
        if (spaceOccurences > 0) {
          // separate column and alias if they are separated by "as"
          // or space
          int lastSpaceIndex = column.toLowerCase().lastIndexOf(" as ");
          sourceColumn = column.substring(0, lastSpaceIndex);
          alias = column.substring(lastSpaceIndex + 4);
        }

        // extract column name if projection has table name in it
        String columnName = sourceColumn;
        if (sourceColumn.contains(".")) {
          columnName = sourceColumn.substring(sourceColumn.indexOf(".") + 1);
        }

        ColumnAttributes col = new ColumnAttributes();
        col.setColumnName(columnName);
        col.setAliasName(alias);
        col.setSourceColumnName(sourceColumn);
        this.addToColumnAliasMap(col);
      }
    }
  }
235274
def _check_query(self, query, style_cols=None):
        """"""
        try:
            self.sql_client.send(
                utils.minify_sql((
                    'EXPLAIN',
                    'SELECT',
                    '  {style_cols}{comma}',
                    '  the_geom, the_geom_webmercator',
                    'FROM ({query}) _wrap;',
                )).format(query=query,
                          comma=',' if style_cols else '',
                          style_cols=(','.join(style_cols)
                                      if style_cols else '')),
                do_post=False)
        except Exception as err:
            raise ValueError(('Layer query `{query}` and/or style column(s) '
                              '{cols} are not valid: {err}.'
                              '').format(query=query,
                                         cols=', '.join(['`{}`'.format(c)
                                                         for c in style_cols]),
                                         err=err))
516567
def emit_code_from_single_match_query(match_query):
    """"""
    query_data = deque([u'MATCH '])

    if not match_query.match_traversals:
        raise AssertionError(u'Unexpected falsy value for match_query.match_traversals received: '
                             u'{} {}'.format(match_query.match_traversals, match_query))

    # Represent and add the MATCH traversal steps.
    match_traversal_data = [
        _represent_match_traversal(x)
        for x in match_query.match_traversals
    ]
    query_data.append(match_traversal_data[0])
    for traversal_data in match_traversal_data[1:]:
        query_data.append(u', ')
        query_data.append(traversal_data)

    query_data.appendleft(u' (')            # Prepare to wrap the MATCH in a SELECT.
    query_data.append(u'RETURN $matches)')  # Finish the MATCH query and the wrapping ().

    # Represent and add the LET clauses for any @fold scopes that might be part of the query.
    # Sort for deterministic order of clauses.
    fold_data = sorted([
        _represent_fold(fold_location, fold_ir_blocks)
        for fold_location, fold_ir_blocks in six.iteritems(match_query.folds)
    ])
    if fold_data:
        query_data.append(u' LET ')
        query_data.append(fold_data[0])
        for fold_clause in fold_data[1:]:
            query_data.append(u', ')
            query_data.append(fold_clause)

    # Represent and add the SELECT clauses with the proper output data.
    query_data.appendleft(_construct_output_to_match(match_query.output_block))

    # Represent and add the WHERE clause with the proper filters.
    if match_query.where_block is not None:
        query_data.append(_construct_where_to_match(match_query.where_block))

    return u' '.join(query_data)
722535
def matches(self, query):
        
        thread_query = 'thread:{tid} AND {subquery}'.format(tid=self._id,
                                                            subquery=query)
        num_matches = self._dbman.count_messages(thread_query)
        return num_matches > 0
503216
function query (query, params) {
        let rows = [];
        let stmt = sql.prepare(query);
        params = normalizeParams(params);
        stmt.bind(params);
        while(stmt.step()) {
            rows.push(stmt.getAsObject());
        }
        stmt.free();
        return rows;
    }
484540
def sparql_query(self, query, flush=None, limit=None):
        
        return self.find_statements(query, language='sparql', type='tuples',
            flush=flush, limit=limit)
870682
def query(self, query, *parameters, **kwargs):
        """"""
        cursor = self._cursor()
        try:
            self._execute(cursor, query, parameters or None, kwargs)
            if cursor.description:
                column_names = [column.name for column in cursor.description]
                res = [Row(zip(column_names, row)) for row in cursor.fetchall()]
                cursor.close()
                return res
        except:
            cursor.close()
            raise
1291068
def query(self):
        """"""
        if self._query is None:
            query_string = self.environ.get('QUERY_STRING')
            self._query = QueryDict([
                (k.decode('utf-8'), v.decode('utf-8'))
                for k, v in urlparse.parse_qsl(
                    query_string, keep_blank_values=True)
            ])
        return self._query