Find the last sql keyword in an SQL statement
    Returns the value of the last keyword, and the text of the query with
    everything after the last keyword stripped
334243
def find_prev_keyword(sql):
    
    if not sql.strip():
        return None, ''

    parsed = sqlparse.parse(sql)[0]
    flattened = list(parsed.flatten())

    logical_operators = ('AND', 'OR', 'NOT', 'BETWEEN')

    for t in reversed(flattened):
        if t.value == '(' or (t.is_keyword and (
                              t.value.upper() not in logical_operators)):
            # Find the location of token t in the original parsed statement
            # We can't use parsed.token_index(t) because t may be a child token
            # inside a TokenList, in which case token_index thows an error
            # Minimal example:
            #   p = sqlparse.parse('select * from foo where bar')
            #   t = list(p.flatten())[-3]  # The "Where" token
            #   p.token_index(t)  # Throws ValueError: not in list
            idx = flattened.index(t)

            # Combine the string values of all tokens in the original list
            # up to and including the target keyword token t, to produce a
            # query string with everything after the keyword token removed
            text = ''.join(tok.value for tok in flattened[:idx+1])
            return t, text

    return None, ''
365369
def get_last(self, n=1):
        
        rows = []
        # Get values from the partial db first
        if self.tracker.dbcon_part and check_table_exists(self.tracker.dbcon_part, self.name):
            rows.extend(get_last_row(self.tracker.dbcon_part, self.name, n))
        # Then add rows from the master if required
        if len(rows) < n and check_table_exists(self.tracker.dbcon_master, self.name):
            rows.extend(get_last_row(self.tracker.dbcon_master, self.name, n))
        return rows[-n:]
1191573
def extract_signature(sql):
    
    sql = force_text(sql)
    sql = sql.strip()
    first_space = sql.find(" ")
    if first_space < 0:
        return sql

    second_space = sql.find(" ", first_space + 1)

    sql_type = sql[0:first_space].upper()

    if sql_type in ["INSERT", "DELETE"]:
        keyword = "INTO" if sql_type == "INSERT" else "FROM"
        sql_type = sql_type + " " + keyword

        table_name = look_for_table(sql, keyword)
    elif sql_type in ["CREATE", "DROP"]:
        # 2nd word is part of SQL type
        sql_type = sql_type + sql[first_space:second_space]
        table_name = ""
    elif sql_type == "UPDATE":
        table_name = look_for_table(sql, "UPDATE")
    elif sql_type == "SELECT":
        # Name is first table
        try:
            sql_type = "SELECT FROM"
            table_name = look_for_table(sql, "FROM")
        except Exception:
            table_name = ""
    else:
        # No name
        table_name = ""

    signature = " ".join(filter(bool, [sql_type, table_name]))
    return signature
864293
def get_query_tokens(query):
    
    query = preprocess_query(query)
    parsed = sqlparse.parse(query)

    # handle empty queries (#12)
    if not parsed:
        return []

    tokens = TokenList(parsed[0].tokens).flatten()
    # print([(token.value, token.ttype) for token in tokens])

    return [token for token in tokens if token.ttype is not Whitespace]
336423
def find_holes(db_module, db, table_name, column_name, _range, filter=None):
    
    if not filter:
        filter = {"match_all": {}}

    _range = wrap(_range)
    params = {
        "min": _range.min,
        "max": _range.max - 1,
        "column_name": db_module.quote_column(column_name),
        "table_name": db_module.quote_column(table_name),
        "filter": esfilter2sqlwhere(filter)
    }

    min_max = db.query("""
        SELECT
            min({{column_name}}) `min`,
            max({{column_name}})+1 `max`
        FROM
            {{table_name}} a
        WHERE
            a.{{column_name}} BETWEEN {{min}} AND {{max}} AND
            {{filter}}
    """, params)[0]

    db.execute("SET @last={{min}}-1", {"min": _range.min})
    ranges = db.query("""
        SELECT
            prev_rev+1 `min`,
            curr_rev `max`
        FROM (
            SELECT
                a.{{column_name}}-@last diff,
                @last prev_rev,
                @last:=a.{{column_name}} curr_rev
            FROM
                {{table_name}} a
            WHERE
                a.{{column_name}} BETWEEN {{min}} AND {{max}} AND
                {{filter}}
            ORDER BY
                a.{{column_name}}
        ) a
        WHERE
            diff>1
    """, params)

    if ranges:
        ranges.append({"min": min_max.max, "max": _range.max})
    else:
        if min_max.min:
            ranges.append({"min": _range.min, "max": min_max.min})
            ranges.append({"min": min_max.max, "max": _range.max})
        else:
            ranges.append(_range)

    return ranges
712121
def get_last_sequence(self, cur=None):
        
        sql = 'SELECT sequence FROM {} ORDER BY sequence DESC LIMIT 1;'.format(self.subdomain_table)
        cursor = None
        if cur is None:
            cursor = self.conn.cursor()
        else:
            cursor = cur

        db_query_execute(cursor, sql, ())
        last_seq = None
        try:
            last_seq = cursor.fetchone()[0]
        except:
            last_seq = 0
        
        return int(last_seq)
589815
def get_sql(self):
        
        # reset arg index and args
        self.arg_index = 0
        self.args = {}

        # build the WHERE sql portion if needed
        if len(self.wheres):
            where = self.build_where_part(self.wheres)
            return 'WHERE {0} '.format(where)
        return ''
133579
def get_editor_query(sql):
    """"""
    sql = sql.strip()

    # The reason we can't simply do .strip('\e') is that it strips characters,
    # not a substring. So it'll strip "e" in the end of the sql also!
    # Ex: "select * from style\e" -> "select * from styl".
    pattern = re.compile('(^\\\e|\\\e$)')
    while pattern.search(sql):
        sql = pattern.sub('', sql)

    return sql
413507
@Override
    public boolean previous() throws SQLException {
        checkClosed();
        if (cursorPosition == Position.afterLast) {
            return last();
        }
        if (cursorPosition == Position.beforeFirst || table.getActiveRowIndex() <= 0) {
            beforeFirst();
            return false;
        }
        try {
            int tempRowIndex = table.getActiveRowIndex();
            table.resetRowPosition();
            table.advanceToRow(0);
            return table.advanceToRow(tempRowIndex - 1);
        } catch (Exception x) {
            throw SQLError.get(x);
        }
    }
612072
def find_one_sql(table, filter, fields=None):
    '''
    
    '''
    keys, values = _split_dict(filter)
    fields = ', '.join(fields) if fields else '*'
    where = _pairs(keys)
    sql = 'SELECT {} FROM {} WHERE {}'.format(fields, table, where)
    return sql, values
541259
private String trimSlash(final String sql) {
		String trimedSql = sql.trim();
		if (trimedSql.endsWith(PATH_SEPARATOR) && !trimedSql.endsWith("*/")) {
			return StringUtils.stripEnd(trimedSql, PATH_SEPARATOR);
		} else {
			return sql;
		}
	}
401286
def get_last_field(self, field, table=None):
        '''
        '''
        field = field if is_array(field) else [field]
        table = self.get_table(table, except_=False)
        if table is None:
            last = None
        else:
            is_defined(field, 'field must be defined!')
            last = self.find(table=table, fields=field, scalar=True,
                             sort=field, limit=1, descending=True,
                             date='~', default_fields=False)
        logger.debug("last %s.%s: %s" % (table, list2str(field), last))
        return last
302669
def get_sql(self):
        """"""
        test_method = [
            self.is_time,
            self.is_date,
            self.is_datetime,
            self.is_decimal,
            self.is_year,
            self.is_tinyint,
            self.is_smallint,
            self.is_mediumint,
            self.is_int,
            self.is_bigint,
            self.is_tinytext,
            self.is_varchar,
            self.is_mediumtext,
            self.is_longtext,
        ]
        # Loop through test methods until a test returns True
        for method in test_method:
            if method():
                return self.sql
425305
public SqlStatement parse(String sql) {

        // does a cached parse result exist for this statement?
        if (_cachedSqlStatements.containsKey(sql)) {
            return _cachedSqlStatements.get(sql);
        }

        SqlGrammar _parser = new SqlGrammar(new StringReader(sql));
        SqlStatement parsed = null;
        try {
            parsed = _parser.parse();
        } catch (ParseException e) {
            throw new ControlException("Error parsing SQL statment." + e.getMessage(), e);
        } catch (TokenMgrError tme) {
            throw new ControlException("Error parsing SQL statment. " + tme.getMessage(), tme);
        }

        if (parsed.isCacheable()) {
            _cachedSqlStatements.put(sql, parsed);
        }
        return parsed;
    }
362525
def get_query_with_new_limit(self, new_limit):
        """does not change the underlying query"""
        if not self._limit:
            return self.sql + ' LIMIT ' + str(new_limit)
        limit_pos = None
        tokens = self._parsed[0].tokens
        # Add all items to before_str until there is a limit
        for pos, item in enumerate(tokens):
            if item.ttype in Keyword and item.value.lower() == 'limit':
                limit_pos = pos
                break
        limit = tokens[limit_pos + 2]
        if limit.ttype == sqlparse.tokens.Literal.Number.Integer:
            tokens[limit_pos + 2].value = new_limit
        elif limit.is_group:
            tokens[limit_pos + 2].value = (
                '{}, {}'.format(next(limit.get_identifiers()), new_limit)
            )

        str_res = ''
        for i in tokens:
            str_res += str(i.value)
        return str_res
525559
def generalize_sql(sql):
    
    if sql is None:
        return None

    # multiple spaces
    sql = re.sub(r'\s{2,}', ' ', sql)

    # MW comments
    # e.g. /* CategoryDataService::getMostVisited N.N.N.N */
    sql = remove_comments_from_sql(sql)

    # handle LIKE statements
    sql = normalize_likes(sql)

    sql = re.sub(r"\\\\", '', sql)
    sql = re.sub(r"\\'", '', sql)
    sql = re.sub(r'\\"', '', sql)
    sql = re.sub(r"'[^\']*'", 'X', sql)
    sql = re.sub(r'"[^\"]*"', 'X', sql)

    # All newlines, tabs, etc replaced by single space
    sql = re.sub(r'\s+', ' ', sql)

    # All numbers => N
    sql = re.sub(r'-?[0-9]+', 'N', sql)

    # WHERE foo IN ('880987','882618','708228','522330')
    sql = re.sub(r' (IN|VALUES)\s*\([^,]+,[^)]+\)', ' \\1 (XYZ)', sql, flags=re.IGNORECASE)

    return sql.strip()
90101
public function get_lastQuery() {
		$retval = null;
		if(is_object($this->sth)) {
			$retval = $this->sth->queryString;
		}
		else {
			throw new \Exception(__METHOD__ .': statement handle not set');
		}
		return($retval);
	}