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

expression: fix #3762, signed integer overflow handle in minus unary scalar function #3780

Merged
merged 24 commits into from
Jul 26, 2017
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
7762b8b
expression: handle int builtinUnaryOpSig overflow
winkyao Jul 17, 2017
f87e0af
expression: fix #3762, signed integer overflow handle in minus unary …
winkyao Jul 17, 2017
465dd1b
expression: fix #3762, add builtin_op_test.go, some builtin test cases
winkyao Jul 17, 2017
17f1e5f
*: tiny cleanup
winkyao Jul 17, 2017
1d15330
expression: set the correct unary minus function ScalarFunction.RetType
winkyao Jul 17, 2017
a803f9d
expression: rewrite unary minus builtin function to handle overflow.
winkyao Jul 19, 2017
d6e6c25
plan: fix popRowArg bug: when get expression.Constatn and getRowLen i…
winkyao Jul 20, 2017
ae342fc
*:git stash
winkyao Jul 24, 2017
869e1f6
Merge branch 'master' of https://github.com/pingcap/tidb into winkyao…
winkyao Jul 25, 2017
b305a4f
expression: base #3868 pr, and rewrite builtin function unary minus t…
winkyao Jul 25, 2017
bedd270
expression: refactor builtin unary minus function
winkyao Jul 25, 2017
0e5de09
expression: tiny refactor
winkyao Jul 25, 2017
4045075
expression: tiny cleanup
winkyao Jul 25, 2017
636170d
expression: cleanup
winkyao Jul 25, 2017
33bf09c
expresion: cleanup
winkyao Jul 25, 2017
eb58c48
expression: tiny cleanup
winkyao Jul 25, 2017
b199772
Merge branch 'master' of https://github.com/pingcap/tidb into winkyao…
winkyao Jul 25, 2017
6005a18
Merge branch 'master' into winkyao/fix_issue_3762
winkyao Jul 26, 2017
e2aa622
expression: add some comment
winkyao Jul 26, 2017
d0395bf
Merge branch 'winkyao/fix_issue_3762' of https://github.com/pingcap/t…
winkyao Jul 26, 2017
ffc0df7
Merge branch 'master' into winkyao/fix_issue_3762
winkyao Jul 26, 2017
27202d6
Merge branch 'master' of https://github.com/pingcap/tidb into winkyao…
winkyao Jul 26, 2017
03dc0e5
Merge branch 'winkyao/fix_issue_3762' of https://github.com/pingcap/t…
winkyao Jul 26, 2017
7f01b42
expression: adjust commet
winkyao Jul 26, 2017
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
6 changes: 6 additions & 0 deletions executor/executor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1034,6 +1034,12 @@ func (s *testSuite) TestBuiltin(c *C) {
result = tk.MustQuery("select cast(a as signed) from t")
result.Check(testkit.Rows("130000"))

// fixed issue #3762
result = tk.MustQuery("select -9223372036854775809;")
result.Check(testkit.Rows("-9223372036854775809"))
result = tk.MustQuery("select -9223372036854775808;")
result.Check(testkit.Rows("-9223372036854775808"))

// test unhex and hex
result = tk.MustQuery("select unhex('4D7953514C')")
result.Check(testkit.Rows("MySQL"))
Expand Down
13 changes: 12 additions & 1 deletion expression/builtin_op.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
package expression

import (
"fmt"
"math"

"github.com/juju/errors"
"github.com/pingcap/tidb/context"
"github.com/pingcap/tidb/parser/opcode"
Expand Down Expand Up @@ -353,7 +356,15 @@ func (b *builtinUnaryOpSig) eval(row []types.Datum) (d types.Datum, err error) {
case types.KindInt64:
d.SetInt64(-aDatum.GetInt64())
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess opcode.Minus operation on math.MinInt64 would get wrong result as range of negative is greater then range of positive by 1.

case types.KindUint64:
d.SetInt64(-int64(aDatum.GetUint64()))
uval := aDatum.GetUint64()
minInt64 := math.MinInt64
absMinInt64 := uint64(-minInt64) // 9223372036854775808
if uval > absMinInt64 {
// -uval will overflow
err = types.ErrOverflow.GenByArgs("BIGINT", fmt.Sprintf("-%v", uval))
} else {
d.SetInt64(-int64(uval))
}
case types.KindFloat64:
d.SetFloat64(-aDatum.GetFloat64())
case types.KindFloat32:
Expand Down
54 changes: 54 additions & 0 deletions expression/builtin_op_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// Copyright 2017 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.

package expression

import (
. "github.com/pingcap/check"
"github.com/pingcap/tidb/ast"
"github.com/pingcap/tidb/mysql"
"github.com/pingcap/tidb/util/testleak"
)

func (s *testEvaluatorSuite) TestUnary(c *C) {
defer testleak.AfterTest(c)()
cases := []struct {
args interface{}
expected interface{}
expectedType byte
overflow bool
getErr bool
}{
{uint64(9223372036854775809), "-9223372036854775809", mysql.TypeNewDecimal, true, false},
{uint64(9223372036854775810), "-9223372036854775810", mysql.TypeNewDecimal, true, false},
{uint64(9223372036854775808), "-9223372036854775808", mysql.TypeLonglong, false, false},
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what's the result of int64(-9223372036854775808) ?

}

for _, t := range cases {
f, err := newFunctionForTest(s.ctx, ast.UnaryMinus, primitiveValsToConstants([]interface{}{t.args})...)

c.Assert(err, IsNil)
d, err := f.Eval(nil)
if t.getErr {
c.Assert(err, NotNil)
} else {
c.Assert(err, IsNil)
if !t.overflow {
c.Assert(d.GetString(), Equals, t.expected)
} else {
c.Assert(d.GetMysqlDecimal().String(), Equals, t.expected)
c.Assert(f.GetType().Tp, Equals, t.expectedType)
}
}
}
}
1 change: 1 addition & 0 deletions expression/constant_fold.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ func FoldConstant(expr Expression) Expression {
log.Warnf("There may exist an error during constant folding. The function name is %s, args are %s", scalarFunc.FuncName, args)
return expr
}

return &Constant{
Value: value,
RetType: scalarFunc.RetType,
Expand Down
46 changes: 44 additions & 2 deletions expression/scalar_function.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"github.com/pingcap/tidb/model"
"github.com/pingcap/tidb/mysql"
"github.com/pingcap/tidb/sessionctx/variable"
"github.com/pingcap/tidb/terror"
"github.com/pingcap/tidb/util/codec"
"github.com/pingcap/tidb/util/types"
)
Expand Down Expand Up @@ -157,12 +158,40 @@ func (sf *ScalarFunction) Decorrelate(schema *Schema) Expression {
return sf
}

func (sf *ScalarFunction) convertArgsToDecimal(sc *variable.StatementContext) error {
ft := types.NewFieldType(mysql.TypeNewDecimal)
for _, arg := range sf.GetArgs() {
if constArg, ok := arg.(*Constant); ok {
val, err := constArg.Value.ConvertTo(sc, ft)
if err != nil {
return err
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

errors.Trace(err)

}
constArg.Value = val
}
}

return nil
}

// Eval implements Expression interface.
func (sf *ScalarFunction) Eval(row []types.Datum) (d types.Datum, err error) {
sc := sf.GetCtx().GetSessionVars().StmtCtx
if !TurnOnNewExprEval {
return sf.Function.eval(row)
d, err = sf.Function.eval(row)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

any difference?

// TODO: fix #3762, maybe better way
if err != nil && terror.ErrorEqual(err, types.ErrOverflow) && sf.GetTypeClass() == types.ClassInt &&
sf.FuncName.L == ast.UnaryMinus && !sc.InUpdateOrDeleteStmt {
err = sf.convertArgsToDecimal(sc)
if err != nil {
return d, errors.Trace(err)
}
d, err = sf.Function.eval(row)
// change return type
decVal, _ := d.ToDecimal(sc)
types.DefaultTypeForValue(decVal, sf.RetType)
}
return
}
sc := sf.GetCtx().GetSessionVars().StmtCtx
var (
res interface{}
isNull bool
Expand All @@ -172,6 +201,7 @@ func (sf *ScalarFunction) Eval(row []types.Datum) (d types.Datum, err error) {
case types.ClassInt:
var intRes int64
intRes, isNull, err = sf.EvalInt(row, sc)

if mysql.HasUnsignedFlag(tp.Flag) {
res = uint64(intRes)
} else {
Expand All @@ -191,6 +221,18 @@ func (sf *ScalarFunction) Eval(row []types.Datum) (d types.Datum, err error) {
res, isNull, err = sf.EvalString(row, sc)
}
}

if err != nil && terror.ErrorEqual(err, types.ErrOverflow) &&
sf.FuncName.L == ast.UnaryMinus && !sc.InUpdateOrDeleteStmt {
// TODO: fix #3762, overflow convert it to decimal
err = sf.convertArgsToDecimal(sc)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there any reference to this rule?
How about Add function and others?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no, mysql did not have any document refer to it, but there is some relevent doc: https://dev.mysql.com/doc/refman/5.7/en/out-of-range-and-overflow.html,

if err != nil {
return d, errors.Trace(err)
}
res, isNull, err = sf.EvalDecimal(row, sc)
types.DefaultTypeForValue(res, sf.RetType)
}

if isNull || err != nil {
d.SetValue(nil)
return d, errors.Trace(err)
Expand Down