Skip to content

Commit

Permalink
types: fix convert str -00* to uint (#46721)
Browse files Browse the repository at this point in the history
close #44359
  • Loading branch information
solotzg authored Sep 11, 2023
1 parent aac330b commit 6397d47
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 4 deletions.
7 changes: 7 additions & 0 deletions expression/integration_test/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -849,6 +849,13 @@ func TestStringBuiltin(t *testing.T) {
result = tk.MustQuery("select a,b,concat_ws(',',a,b) from t")
result.Check(testkit.Rows("114.57011441 38.04620115 114.57011441,38.04620115",
"-38.04620119 38.04620115 -38.04620119,38.04620115"))

// issue 44359
tk.MustExec("drop table if exists t1")
tk.MustExec("CREATE TABLE t1 (c1 INT UNSIGNED NOT NULL )")
tk.MustExec("INSERT INTO t1 VALUES (0)")
tk.MustQuery("SELECT c1 FROM t1 WHERE c1 <> CAST(POW(-'0', 1) AS BINARY)").Check(testkit.Rows())
tk.MustQuery("SELECT c1 FROM t1 WHERE c1 = CAST('-000' AS BINARY)").Check(testkit.Rows("0"))
}

func TestInvalidStrings(t *testing.T) {
Expand Down
23 changes: 19 additions & 4 deletions types/convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -290,11 +290,26 @@ func StrToInt(sc *stmtctx.StatementContext, str string, isFuncCast bool) (int64,
func StrToUint(sc *stmtctx.StatementContext, str string, isFuncCast bool) (uint64, error) {
str = strings.TrimSpace(str)
validPrefix, err := getValidIntPrefix(sc, str, isFuncCast)
if validPrefix[0] == '+' {
validPrefix = validPrefix[1:]
uVal := uint64(0)
hasParseErr := false

if validPrefix[0] == '-' {
// only `-000*` is valid to be converted into unsigned integer
for _, v := range validPrefix[1:] {
if v != '0' {
hasParseErr = true
break
}
}
} else {
if validPrefix[0] == '+' {
validPrefix = validPrefix[1:]
}
v, e := strconv.ParseUint(validPrefix, 10, 64)
uVal, hasParseErr = v, e != nil
}
uVal, err1 := strconv.ParseUint(validPrefix, 10, 64)
if err1 != nil {

if hasParseErr {
return uVal, ErrOverflow.GenWithStackByArgs("BIGINT UNSIGNED", validPrefix)
}
return uVal, errors.Trace(err)
Expand Down
3 changes: 3 additions & 0 deletions types/convert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -533,6 +533,9 @@ func TestStrToNum(t *testing.T) {
testStrToUint(t, "11xx", 11, true, ErrTruncatedWrongVal)
testStrToUint(t, "xx11", 0, true, ErrTruncatedWrongVal)

// for issue #44359
testStrToUint(t, "-00", 0, true, nil)

// TODO: makes StrToFloat return truncated value instead of zero to make it pass.
testStrToFloat(t, "", 0, true, ErrTruncatedWrongVal)
testStrToFloat(t, "-1", -1.0, true, nil)
Expand Down

0 comments on commit 6397d47

Please sign in to comment.