Skip to content

Commit

Permalink
*: fix cast decimal allocates large memory. (#2146)
Browse files Browse the repository at this point in the history
If precision is too large, encode decimal allocates large amount of memory.
This commit set cast decimal unspecified length to default decimal length (10),
also add check on precision and frac on `MyDecimal.ToBin`.
  • Loading branch information
coocood authored Dec 1, 2016
1 parent 28a7bac commit 3a721da
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 0 deletions.
2 changes: 2 additions & 0 deletions executor/executor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -982,6 +982,8 @@ func (s *testSuite) TestBuiltin(c *C) {
result.Check(testkit.Rows("1991-09-05 11:11:11"))
result = tk.MustQuery("select cast('11:11:11' as time)")
result.Check(testkit.Rows("11:11:11"))
result = tk.MustQuery("select * from t where a > cast(2 as decimal)")
result.Check(testkit.Rows("3 2"))

// test unhex and hex
result = tk.MustQuery("select unhex('4D7953514C')")
Expand Down
4 changes: 4 additions & 0 deletions parser/parser.y
Original file line number Diff line number Diff line change
Expand Up @@ -3115,6 +3115,10 @@ CastType:
x := types.NewFieldType(mysql.TypeNewDecimal)
x.Flen = fopt.Flen
x.Decimal = fopt.Decimal
if fopt.Flen == types.UnspecifiedLength {
x.Flen = mysql.GetDefaultFieldLength(mysql.TypeNewDecimal)
x.Decimal = mysql.GetDefaultDecimal(mysql.TypeNewDecimal)
}
$$ = x
}
| "TIME" OptFieldLen
Expand Down
3 changes: 3 additions & 0 deletions util/types/mydecimal.go
Original file line number Diff line number Diff line change
Expand Up @@ -1040,6 +1040,9 @@ with the correct -1/0/+1 result
7E F2 04 C7 2D FB 2D
*/
func (d *MyDecimal) ToBin(precision, frac int) ([]byte, error) {
if precision > digitsPerWord*maxWordBufLen || precision < 0 || frac > MaxFraction || frac < 0 {
return nil, ErrBadNumber
}
var err error
var mask int32
if d.negative {
Expand Down
15 changes: 15 additions & 0 deletions util/types/mydecimal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,21 @@ func (s *testMyDecimalSuite) TestToBinFromBin(c *C) {
str := dec2.ToString()
c.Assert(string(str), Equals, ca.output)
}
var dec MyDecimal
dec.FromInt(1)
errCases := []struct {
prec int
frac int
}{
{82, 1},
{-1, 1},
{10, 31},
{10, -1},
}
for _, ca := range errCases {
_, err := dec.ToBin(ca.prec, ca.frac)
c.Assert(ErrBadNumber.Equal(err), IsTrue)
}
}

func (s *testMyDecimalSuite) TestCompare(c *C) {
Expand Down

0 comments on commit 3a721da

Please sign in to comment.