Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

parser: Don't support parser sql like t. [reservedKeyWord] #46789

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion parser/ast/format_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,8 @@ func TestAstFormat(t *testing.T) {
expr := fmt.Sprintf("select %s", tt.input)
charset, collation := getDefaultCharsetAndCollate()
stmts, _, err := parser.New().Parse(expr, charset, collation)
node := stmts[0].(*ast.SelectStmt).Fields.Fields[0].Expr
require.NoError(t, err)
node := stmts[0].(*ast.SelectStmt).Fields.Fields[0].Expr

writer := bytes.NewBufferString("")
node.Format(writer)
Expand Down
7 changes: 7 additions & 0 deletions parser/consistent_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
package parser

import (
"fmt"
gio "io"
"os"
"sort"
Expand Down Expand Up @@ -46,6 +47,12 @@ func TestKeywordConsistent(t *testing.T) {
requires.NotEqual(t, k, v)
requires.Equal(t, tokenMap[v], tokenMap[k])
}

for _, v := range reservedKeywords {
requires.NotEqual(t, reservedTokenMap[v], 0, fmt.Sprintf("Not found %s in reservedTokenMap", v))
}
requires.Len(t, reservedKeywords, len(reservedTokenMap))

keywordCount := len(reservedKeywords) + len(unreservedKeywords) + len(notKeywordTokens) + len(tidbKeywords)
requires.Equal(t, keywordCount-len(windowFuncTokenMap), len(tokenMap)-len(aliases))

Expand Down
272 changes: 261 additions & 11 deletions parser/misc.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,252 @@ func isInTokenMap(target string) bool {
return ok
}

func isInReservedTokenMap(target string) bool {
_, ok := reservedTokenMap[target]
return ok
}

func isInWindowFuncTokenMap(target string) bool {
_, ok := windowFuncTokenMap[target]
return ok
}

var reservedTokenMap = map[string]int{
"ADD": add,
"ALL": all,
"ALTER": alter,
"ANALYZE": analyze,
"AND": and,
"ARRAY": array,
"AS": as,
"ASC": asc,
"BETWEEN": between,
"BIGINT": bigIntType,
"BINARY": binaryType,
"BLOB": blobType,
"BOTH": both,
"BY": by,
"CALL": call,
"CASCADE": cascade,
"CASE": caseKwd,
"CHANGE": change,
"CHARACTER": character,
"CHAR": charType,
"CHECK": check,
"COLLATE": collate,
"COLUMN": column,
"CONSTRAINT": constraint,
"CONTINUE": continueKwd,
"CONVERT": convert,
"CREATE": create,
"CROSS": cross,
"CUME_DIST": cumeDist,
"CURRENT_DATE": currentDate,
"CURRENT_TIME": currentTime,
"CURRENT_TIMESTAMP": currentTs,
"CURRENT_USER": currentUser,
"CURRENT_ROLE": currentRole,
"CURSOR": cursor,
"DATABASE": database,
"DATABASES": databases,
"DAY_HOUR": dayHour,
"DAY_MICROSECOND": dayMicrosecond,
"DAY_MINUTE": dayMinute,
"DAY_SECOND": daySecond,
"DECIMAL": decimalType,
"DEFAULT": defaultKwd,
"DELAYED": delayed,
"DELETE": deleteKwd,
"DENSE_RANK": denseRank,
"DESC": desc,
"DESCRIBE": describe,
"DISTINCT": distinct,
"DISTINCTROW": distinctRow,
"DIV": div,
"DOUBLE": doubleType,
"DROP": drop,
"DUAL": dual,
"ELSEIF": elseIfKwd,
"ELSE": elseKwd,
"ENCLOSED": enclosed,
"ESCAPED": escaped,
"EXISTS": exists,
"EXIT": exit,
"EXPLAIN": explain,
"EXCEPT": except,
"FALSE": falseKwd,
"FETCH": fetch,
"FIRST_VALUE": firstValue,
"FLOAT": floatType,
"FLOAT4": float4Type,
"FLOAT8": float8Type,
"FOR": forKwd,
"FORCE": force,
"FOREIGN": foreign,
"FROM": from,
"FULLTEXT": fulltext,
"GENERATED": generated,
"GRANT": grant,
"GROUP": group,
"GROUPS": groups,
"HAVING": having,
"HIGH_PRIORITY": highPriority,
"HOUR_MICROSECOND": hourMicrosecond,
"HOUR_MINUTE": hourMinute,
"HOUR_SECOND": hourSecond,
"IF": ifKwd,
"IGNORE": ignore,
"IN": in,
"INDEX": index,
"INFILE": infile,
"INNER": inner,
"INOUT": inout,
"INTEGER": integerType,
"INTERSECT": intersect,
"INTERVAL": interval,
"INTO": into,
"OUTFILE": outfile,
"IS": is,
"INSERT": insert,
"INT": intType,
"INT1": int1Type,
"INT2": int2Type,
"INT3": int3Type,
"INT4": int4Type,
"INT8": int8Type,
"ITERATE": iterate,
"JOIN": join,
"KEY": key,
"KEYS": keys,
"KILL": kill,
"LAG": lag,
"LAST_VALUE": lastValue,
"LEAD": lead,
"LEADING": leading,
"LEAVE": leave,
"LEFT": left,
"LIKE": like,
"ILIKE": ilike,
"LIMIT": limit,
"LINES": lines,
"LINEAR": linear,
"LOAD": load,
"LOCALTIME": localTime,
"LOCALTIMESTAMP": localTs,
"LOCK": lock,
"LONGBLOB": longblobType,
"LONGTEXT": longtextType,
"LOW_PRIORITY": lowPriority,
"MATCH": match,
"MAXVALUE": maxValue,
"MEDIUMBLOB": mediumblobType,
"MEDIUMINT": mediumIntType,
"MEDIUMTEXT": mediumtextType,
"MIDDLEINT": middleIntType,
"MINUTE_MICROSECOND": minuteMicrosecond,
"MINUTE_SECOND": minuteSecond,
"MOD": mod,
"NOT": not,
"NO_WRITE_TO_BINLOG": noWriteToBinLog,
"NTH_VALUE": nthValue,
"NTILE": ntile,
"NULL": null,
"NUMERIC": numericType,
"OF": of,
"ON": on,
"OPTIMIZE": optimize,
"OPTION": option,
"OPTIONALLY": optionally,
"OR": or,
"ORDER": order,
"OUT": out,
"OUTER": outer,
"OVER": over,
"PARTITION": partition,
"PERCENT_RANK": percentRank,
"PRECISION": precisionType,
"PRIMARY": primary,
"PROCEDURE": procedure,
"RANGE": rangeKwd,
"RANK": rank,
"READ": read,
"REAL": realType,
"RECURSIVE": recursive,
"REFERENCES": references,
"REGEXP": regexpKwd,
"RELEASE": release,
"RENAME": rename,
"REPEAT": repeat,
"REPLACE": replace,
"REQUIRE": require,
"RESTRICT": restrict,
"REVOKE": revoke,
"RIGHT": right,
"RLIKE": rlike,
"ROW": row,
"ROWS": rows,
"ROW_NUMBER": rowNumber,
"SECOND_MICROSECOND": secondMicrosecond,
"SELECT": selectKwd,
"SET": set,
"SHOW": show,
"SMALLINT": smallIntType,
"SPATIAL": spatial,
"SQL": sql,
"SQL_BIG_RESULT": sqlBigResult,
"SQL_CALC_FOUND_ROWS": sqlCalcFoundRows,
"SQL_SMALL_RESULT": sqlSmallResult,
"SQLEXCEPTION": sqlexception,
"SQLSTATE": sqlstate,
"SQLWARNING": sqlwarning,
"SSL": ssl,
"STARTING": starting,
"STATS_EXTENDED": statsExtended,
"STRAIGHT_JOIN": straightJoin,
"TiDB_CURRENT_TSO": tidbCurrentTSO,
"TABLE": tableKwd,
"TABLESAMPLE": tableSample,
"STORED": stored,
"TERMINATED": terminated,
"THEN": then,
"TINYBLOB": tinyblobType,
"TINYINT": tinyIntType,
"TINYTEXT": tinytextType,
"TO": to,
"TRAILING": trailing,
"TRIGGER": trigger,
"TRUE": trueKwd,
"UNIQUE": unique,
"UNION": union,
"UNLOCK": unlock,
"UNSIGNED": unsigned,
"UNTIL": until,
"UPDATE": update,
"USAGE": usage,
"USE": use,
"USING": using,
"UTC_DATE": utcDate,
"UTC_TIMESTAMP": utcTimestamp,
"UTC_TIME": utcTime,
"VALUES": values,
"LONG": long,
"VARCHAR": varcharType,
"VARCHARACTER": varcharacter,
"VARBINARY": varbinaryType,
"VARYING": varying,
"VIRTUAL": virtual,
"WHEN": when,
"WHERE": where,
"WHILE": while,
"WRITE": write,
"WINDOW": window,
"WITH": with,
"XOR": xor,
"YEAR_MONTH": yearMonth,
"ZEROFILL": zerofill,
"NATURAL": natural,
}

// tokenMap is a map of known identifiers to the parser token ID.
// Please try to keep the map in alphabetical order.
var tokenMap = map[string]int{
Expand Down Expand Up @@ -1069,20 +1315,10 @@ var hintTokenMap = map[string]int{
func (s *Scanner) isTokenIdentifier(lit string, offset int) int {
// An identifier before or after '.' means it is part of a qualified identifier.
// We do not parse it as keyword.
if s.r.peek() == '.' {
if s.r.peek() == '.' || (offset != 0 && s.r.s[offset-1] == '.') {
return 0
}

for idx := offset - 1; idx >= 0; idx-- {
if s.r.s[idx] == ' ' {
continue
} else if s.r.s[idx] == '.' {
return 0
} else {
break
}
}

buf := &s.buf
buf.Reset()
buf.Grow(len(lit))
Expand All @@ -1097,6 +1333,20 @@ func (s *Scanner) isTokenIdentifier(lit string, offset int) int {
}
}

// select * from t where t. status = 1; -- parse ok, unreserved keyword.
// select * from t where t. and = 1; -- parse failed, reserved keyword.
if !isInReservedTokenMap(string(data)) || (!s.supportWindowFunc && isInWindowFuncTokenMap(string(data))) {
for idx := offset - 1; idx >= 0; idx-- {
if s.r.s[idx] == ' ' {
continue
} else if s.r.s[idx] == '.' {
return 0
} else {
break
}
}
}

checkBtFuncToken := s.r.peek() == '('
if !checkBtFuncToken && s.sqlMode.HasIgnoreSpaceMode() {
s.skipWhitespace()
Expand Down
13 changes: 13 additions & 0 deletions parser/parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1058,6 +1058,9 @@ AAAAAAAAAAAA5gm5Mg==

{"select `t`.`1a`.1 from t;", true, "SELECT `t`.`1a`.`1` FROM `t`"},
{"select * from 1db.1table;", true, "SELECT * FROM `1db`.`1table`"},
{"select * from t where t.and = 1;", true, "SELECT * FROM `t` WHERE `t`.`and`=1"},
{"select * from t where t. and = 1;", false, ""},
{"select * from t where t.status = 1;", true, "SELECT * FROM `t` WHERE `t`.`status`=1"},
{"select * from t where t. status = 1;", true, "SELECT * FROM `t` WHERE `t`.`status`=1"},

// for show placement
Expand Down Expand Up @@ -7464,6 +7467,16 @@ func TestMultiStmt(t *testing.T) {
require.Equal(t, "1", stmt4.Fields.Fields[0].Text())
}

func TestIssue46789(t *testing.T) {
p := parser.New()
// parse `1.` get a datum with type decimal,
// parse and restore `1.` get a datumn with type int,
// so add a new test case here.
sql := "select * from t where a between 1. and 2"
_, _, err := p.Parse(sql, "", "")
require.NoError(t, err)
}

// https://dev.mysql.com/doc/refman/8.1/en/other-vendor-data-types.html
func TestCompatTypes(t *testing.T) {
table := []testCase{
Expand Down