gathers some info about executed query
963503
private function SetQuerySummary()
    {
        if (!$this->query_result or !$this->debug_on) {
            return;
        }

        $this->printOutStr .= "<div class=\"alert alert-info\"><b>Query:</b> " .nl2br($this->last_query) . "<br />
        <b>Rows affected:</b> " .$this->GetAffRows() . "<br />
        <b>Num rows:</b> " .$this->GetNumRows() . "<br />".
        ($this->GetLastID()?"<b>Last INSERT ID:</b> " .$this->GetLastID() . "<br />":"")."</div>";
    }
708415
private List<?> getResultList(Query query) {
        // TODO : use lazy fetch here?
        if (projection != null) {
            List<?> results = query.getResultList();
            List<Object> rv = new ArrayList<Object>(results.size());
            for (Object o : results) {
                if (o != null) {
                    Object[] arr;
                    if (!o.getClass().isArray()) {
                        arr = new Object[]{o};
                    } else {
                        arr = (Object[]) o;
                    }
                    if (projection.getArgs().size() < arr.length) {
                        Object[] shortened = new Object[projection.getArgs().size()];
                        System.arraycopy(arr, 0, shortened, 0, shortened.length);
                        arr = shortened;
                    }
                    rv.add(projection.newInstance(arr));
                } else {
                    rv.add(null);
                }
            }
            return rv;
        } else {
            return query.getResultList();
        }
    }
1143567
def query_info(self, name, like, kind):
        """"""
        kind = self._make_kind_id(kind)
        # Database from VS2015 does not have assoc_text.
        #
        # sql = 'select name, kind, file_id, type, assoc_text ' \
        #       'from code_items ' \
        #       'where name {} ?'.format('like' if like else '=')
        sql = 'select name, kind, file_id, type ' \
              'from code_items ' \
              'where name {} ?'.format('like' if like else '=')
        args = (name,)
        if like:
            sql += ' escape ?'
            args = (name, '\\')
        if kind:
            sql += ' and kind = ?'
            args = (name, kind)
        if like and kind:
            args = (name, '\\', kind)
        logging.debug('%s %s', sql, args)
        self.cursor.execute(sql, args)
        return self.cursor.fetchall(), self
1308478
private String extractQuery(Method method, Object[] args) {
        String res = null;
        String methodName = method.getName();
        if (("execute".equals(methodName) || "executeQuery".equals(methodName) || "executeUpdate".equals(methodName))
                && null != args && 1 == args.length && args[0] instanceof String) {
            res = (String) args[0];
        }
        if (("execute".equals(methodName) || "executeQuery".equals(methodName) || "executeUpdate".equals(methodName))
                && (null == args || 0 == args.length)) {
            res = query;
        }
        return res;
    }
1022858
function (query) {
        var fieldList = ['name', 'owner', 'description', 'keyword'];
        var parsedField = _.find(fieldList, function (field) {
          return query.indexOf(field + ':') === 0;
        });
        var parsedQuery = parsedField ? query.replace(new RegExp('^' + parsedField + ':'), '') : query;
        return {query: parsedQuery, field: parsedField};
      }
106892
def __execute_queries(self):
        """"""

        def func(item):
            or_check = False
            for queries in self._queries:
                and_check = True
                for query in queries:
                    and_check &= self._matcher._match(
                        item.get(query.get('key'), None),
                        query.get('operator'),
                        query.get('value')
                    )
                or_check |= and_check
            return or_check

        self._json_data = list(filter(lambda item: func(item), self._json_data))
474016
def results(self):
    
    self.wait()
    if self.failed:
      raise Exception('Query failed: %s' % str(self.errors))
    return self._table
55195
def _log_query(query):
        
        query = query.strip()

        if os.linesep in query:
            # Query is a multi line query
            MetadataDataLayer.io.log_very_verbose('Executing query:')
            MetadataDataLayer.io.log_very_verbose('<sql>{0}</sql>'.format(query))
        else:
            # Query is a single line query.
            MetadataDataLayer.io.log_very_verbose('Executing query: <sql>{0}</sql>'.format(query))
288467
def debug_query_result(rows: Sequence[Any]) -> None:
    """"""
    log.info("Retrieved {} rows", len(rows))
    for i in range(len(rows)):
        log.info("Row {}: {}", i, rows[i])
704400
def getQueryParams(url):
    """"""
    query = urlsplit(url)[3]
    out.debug(u'Extracting query parameters from %r (%r)...' % (url, query))
    return cgi.parse_qs(query)
570610
def query(self, query, param=None):
        

        with self.conn.cursor() as curs:
            print 'XXX QUERY', curs.mogrify(query, param)
            try:
                curs.execute(query, param)
            except BaseException as exc:
                msg = 'query: {}, param: {}, exc: {}'.format(query, param, exc)

                if hasattr(exc, 'pgcode'):
                    msg = '{}, exc code: {}'.format(msg, exc.pgcode)

                print msg
                handle_exc(exc)

            result = curs.fetchall()

        return result
880773
def info(dev):
    '''
    
    '''
    if 'sys' in dev:
        qtype = 'path'
    else:
        qtype = 'name'

    cmd = 'udevadm info --export --query=all --{0}={1}'.format(qtype, dev)
    udev_result = __salt__['cmd.run_all'](cmd, output_loglevel='quiet')

    if udev_result['retcode'] != 0:
        raise CommandExecutionError(udev_result['stderr'])

    return _parse_udevadm_info(udev_result['stdout'])[0]
329000
def _osquery(sql, format='json'):
    '''
    
    '''
    ret = {
        'result': True,
    }

    cmd = ['osqueryi'] + ['--json'] + [sql]
    res = __salt__['cmd.run_all'](cmd)
    if res['stderr']:
        ret['result'] = False
        ret['error'] = res['stderr']
    else:
        ret['data'] = salt.utils.json.loads(res['stdout'])
    log.debug('== %s ==', ret)
    return ret
1172030
def get_query_kwargs(**kwargs):
    """"""
    query_kwargs = {}

    query = kwargs.pop("query")
    if query:
        query_kwargs["query"] = query

    return query_kwargs
1349203
def get_query_tables(query):
    
    tables = []
    last_keyword = None
    last_token = None

    table_syntax_keywords = [
        # SELECT queries
        'FROM', 'WHERE', 'JOIN', 'INNER JOIN', 'LEFT JOIN', 'RIGHT JOIN', 'ON',
        # INSERT queries
        'INTO', 'VALUES',
        # UPDATE queries
        'UPDATE', 'SET',
        # Hive queries
        'TABLE',  # INSERT TABLE
    ]

    # print(query, get_query_tokens(query))

    for token in get_query_tokens(query):
        # print([token, token.ttype, last_token, last_keyword])
        if token.is_keyword and token.value.upper() in table_syntax_keywords:
            # keep the name of the last keyword, the next one can be a table name
            last_keyword = token.value.upper()
            # print('keyword', last_keyword)
        elif str(token) == '(':
            # reset the last_keyword for INSERT `foo` VALUES(id, bar) ...
            last_keyword = None
        elif token.is_keyword and str(token) in ['FORCE', 'ORDER']:
            # reset the last_keyword for "SELECT x FORCE INDEX" queries and "SELECT x ORDER BY"
            last_keyword = None
        elif token.is_keyword and str(token) == 'SELECT' and last_keyword in ['INTO', 'TABLE']:
            # reset the last_keyword for "INSERT INTO SELECT" and "INSERT TABLE SELECT" queries
            last_keyword = None
        elif token.ttype is Name or token.is_keyword:
            # print([last_keyword, last_token, token.value])
            # analyze the name tokens, column names and where condition values
            if last_keyword in ['FROM', 'JOIN', 'INNER JOIN', 'LEFT JOIN', 'RIGHT JOIN',
                                'INTO', 'UPDATE', 'TABLE'] \
                    and last_token not in ['AS'] \
                    and token.value not in ['AS', 'SELECT']:

                if last_token == '.':
                    # we have database.table notation example
                    # append table name to the last entry of tables
                    # as it is a database name in fact
                    database_name = tables[-1]
                    tables[-1] = '{}.{}'.format(database_name, token)
                    last_keyword = None
                elif last_token not in [',', last_keyword]:
                    # it's not a list of tables, e.g. SELECT * FROM foo, bar
                    # hence, it can be the case of alias without AS, e.g. SELECT * FROM foo bar
                    pass
                else:
                    table_name = str(token.value.strip('`'))
                    tables.append(table_name)

        last_token = token.value.upper()

    return unique(tables)
625852
function parse_query($query) {
		$operations = array('SELECT','INSERT','UPDATE','DELETE','REPLACE','RENAME','SHOW','SET','DROP','CREATE INDEX','CREATE TABLE','EXPLAIN','DESCRIBE');

		$query_ex = '/(?P<operation>'.implode("|",$operations).')\s*(?P<columns>.?)\s*(FROM|INTO)\s*(?P<table>`?.*?`?)\s*(WHERE)?\s*?(?P<where>.*?)\s*?(ORDER BY)?\s*?(?P<order>.*?)?\s*?(LIMIT)?(?P<limit>.*?)?$/i';
		preg_match($query_ex, $query, $retn);
		return $retn;	
    }
843228
def _process_query(self, query):
        """"""
        key, val = query
        field_name, field_action = split_field_action(key)

        # Boost by name__action overrides boost by name.
        boost = self.field_boosts.get(key)
        if boost is None:
            boost = self.field_boosts.get(field_name)

        handler_name = 'process_query_{0}'.format(field_action)

        if field_action and hasattr(self, handler_name):
            return getattr(self, handler_name)(field_name, val, field_action)

        elif field_action in QUERY_ACTION_MAP:
            return {
                QUERY_ACTION_MAP[field_action]: _boosted_value(
                    field_name, field_action, key, val, boost)
            }

        elif field_action == 'query_string':
            # query_string has different syntax, so it's handled
            # differently.
            #
            # Note: query_string queries are not boosted with
            # .boost()---they're boosted in the query text itself.
            return {
                'query_string': {'default_field': field_name, 'query': val}
            }

        elif field_action in RANGE_ACTIONS:
            # Ranges are special and have a different syntax, so
            # we handle them separately.
            return {
                'range': {field_name: _boosted_value(
                        field_action, field_action, key, val, boost)}
           }

        elif field_action == 'range':
            lower, upper = val
            value = {
                'gte': lower,
                'lte': upper,
            }
            if boost:
                value['boost'] = boost

            return {'range': {field_name: value}}

        raise InvalidFieldActionError(
            '%s is not a valid field action' % field_action)