From 5988e567fbf69bccfbcce5cea4d16e83ac3ccec1 Mon Sep 17 00:00:00 2001 From: siddontang Date: Mon, 21 Sep 2015 12:30:15 +0800 Subject: [PATCH] types: check overflow for bit type --- util/types/convert.go | 21 ++++++++++++++++++++- util/types/convert_test.go | 13 +++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/util/types/convert.go b/util/types/convert.go index 3ef0470549..edf9ddc4ed 100644 --- a/util/types/convert.go +++ b/util/types/convert.go @@ -370,7 +370,26 @@ func Convert(val interface{}, target *FieldType) (v interface{}, err error) { // } return convertToInt(val, target) case mysql.TypeBit: - return convertToUint(val, target) + x, err := convertToUint(val, target) + if err != nil { + return x, errors.Trace(err) + } + + // check bit boundary, if bit has n width, the boundary is + // in [0, (1 << n) - 1] + width := target.Flen + if width == 0 { + width = mysql.MinBitWidth + } else if width == mysql.UnspecifiedBitWidth { + width = mysql.MaxBitWidth + } + + maxValue := uint64(1)< maxValue { + return maxValue, overflow(val, tp) + } + return x, nil case mysql.TypeDecimal, mysql.TypeNewDecimal: x, err := ToDecimal(val) if err != nil { diff --git a/util/types/convert_test.go b/util/types/convert_test.go index 89ace25281..ba8cabbe48 100644 --- a/util/types/convert_test.go +++ b/util/types/convert_test.go @@ -169,6 +169,7 @@ func (s *testTypeConvertSuite) TestConvertType(c *C) { // For TypeBit ft = NewFieldType(mysql.TypeBit) + ft.Flen = 8 v, err = Convert("100", ft) c.Assert(err, IsNil) c.Assert(v, Equals, uint64(100)) @@ -181,6 +182,18 @@ func (s *testTypeConvertSuite) TestConvertType(c *C) { c.Assert(err, IsNil) c.Assert(v, Equals, uint64(100)) + ft.Flen = 1 + v, err = Convert(1, ft) + c.Assert(err, IsNil) + c.Assert(v, Equals, uint64(1)) + + _, err = Convert(2, ft) + c.Assert(err, NotNil) + + ft.Flen = 0 + _, err = Convert(2, ft) + c.Assert(err, NotNil) + // For TypeNewDecimal ft = NewFieldType(mysql.TypeNewDecimal) ft.Decimal = 5