Skip to content

Commit

Permalink
types: add overflow truncate when convert str to float (pingcap#5130)
Browse files Browse the repository at this point in the history
  • Loading branch information
mccxj authored and winoros committed Nov 22, 2017
1 parent 8892bdf commit 9921f41
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
15 changes: 15 additions & 0 deletions expression/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3017,6 +3017,21 @@ func (s *testIntegrationSuite) TestIssues(c *C) {
tk.MustExec("insert into tb(v) (select v from tb);")
r = tk.MustQuery(`SELECT * FROM tb;`)
r.Check(testkit.Rows("1 hello", "2 hello"))

// for issue #5111
tk.MustExec(`drop table if exists t`)
tk.MustExec("create table t(c varchar(32));")
tk.MustExec("insert into t values('1e649'),('-1e649');")
r = tk.MustQuery(`SELECT * FROM t where c < 1;`)
r.Check(testkit.Rows("-1e649"))
tk.MustQuery("show warnings").Check(testutil.RowsWithSep("|",
"Warning|1292|Truncated incorrect DOUBLE value: '1e649'",
"Warning|1292|Truncated incorrect DOUBLE value: '-1e649'"))
r = tk.MustQuery(`SELECT * FROM t where c > 1;`)
r.Check(testkit.Rows("1e649"))
tk.MustQuery("show warnings").Check(testutil.RowsWithSep("|",
"Warning|1292|Truncated incorrect DOUBLE value: '1e649'",
"Warning|1292|Truncated incorrect DOUBLE value: '-1e649'"))
}

func newStoreWithBootstrap() (kv.Storage, *domain.Domain, error) {
Expand Down
11 changes: 11 additions & 0 deletions types/convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,17 @@ func StrToFloat(sc *stmtctx.StatementContext, str string) (float64, error) {
validStr, err := getValidFloatPrefix(sc, str)
f, err1 := strconv.ParseFloat(validStr, 64)
if err1 != nil {
if err2, ok := err1.(*strconv.NumError); ok {
// value will truncate to MAX/MIN if out of range.
if err2.Err == strconv.ErrRange {
err1 = sc.HandleTruncate(ErrTruncatedWrongVal.GenByArgs("DOUBLE", str))
if math.IsInf(f, 1) {
f = math.MaxFloat64
} else if math.IsInf(f, -1) {
f = -math.MaxFloat64
}
}
}
return f, errors.Trace(err1)
}
return f, errors.Trace(err)
Expand Down
6 changes: 6 additions & 0 deletions types/convert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -448,6 +448,12 @@ func (s *testTypeConvertSuite) TestStrToNum(c *C) {
testStrToFloat(c, "11.xx", 11.0, false, nil)
testStrToFloat(c, "11.xx", 11.0, true, ErrTruncated)
testStrToFloat(c, "xx.11", 0.0, false, nil)

// for issue #5111
testStrToFloat(c, "1e649", math.MaxFloat64, true, ErrTruncatedWrongVal)
testStrToFloat(c, "1e649", math.MaxFloat64, false, nil)
testStrToFloat(c, "-1e649", -math.MaxFloat64, true, ErrTruncatedWrongVal)
testStrToFloat(c, "-1e649", -math.MaxFloat64, false, nil)
}

func (s *testTypeConvertSuite) TestFieldTypeToStr(c *C) {
Expand Down

0 comments on commit 9921f41

Please sign in to comment.