Skip to content

Commit

Permalink
fix crash on x % 0`
Browse files Browse the repository at this point in the history
1 % 0 now returns an error (as does Postgres 9.3; MySQL goes for NULL)

found via go-fuzz
  • Loading branch information
tbg committed Jul 24, 2015
1 parent 4e09492 commit 73b5e5c
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
7 changes: 6 additions & 1 deletion sql/parser/eval.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ package parser

import (
"bytes"
"errors"
"fmt"
"math"
"reflect"
Expand Down Expand Up @@ -231,7 +232,11 @@ var binOps = map[binArgs]func(Datum, Datum) (Datum, error){
},

binArgs{Mod, intType, intType}: func(left Datum, right Datum) (Datum, error) {
return left.(DInt) % right.(DInt), nil
r := right.(DInt)
if r == 0 {
return nil, errors.New("zero modulus")
}
return left.(DInt) % r, nil
},
binArgs{Mod, floatType, floatType}: func(left Datum, right Datum) (Datum, error) {
return DFloat(math.Mod(float64(left.(DFloat)), float64(right.(DFloat)))), nil
Expand Down
4 changes: 4 additions & 0 deletions sql/parser/eval_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ func TestEvalExpr(t *testing.T) {
{`5 % 3`, `2`, nil},
// Division is always done on floats.
{`4 / 5`, `0.8`, nil},
{`1 / 0`, `+Inf`, nil},
{`-1.0 * (1.0 / 0.0)`, `-Inf`, nil},
// Grouping
{`1 + 2 + (3 * 4)`, `15`, nil},
// Unary operators.
Expand Down Expand Up @@ -204,9 +206,11 @@ func TestEvalExprError(t *testing.T) {
expr string
expected string
}{
{`1 % 0`, `zero modulus`},
{`'1' + '2'`, `unsupported binary operator:`},
{`'a' + 0`, `unsupported binary operator:`},
{`1.1 # 3.1`, `unsupported binary operator:`},
{`1/0.0`, `unsupported binary operator:`},
{`~0.1`, `unsupported unary operator:`},
{`'10' > 2`, `unsupported comparison operator:`},
{`1 IN ('a', 'b')`, `unsupported comparison operator:`},
Expand Down

0 comments on commit 73b5e5c

Please sign in to comment.