func computeDiv(a, b types.Datum) (d types.Datum, err error) { // MySQL support integer divison Div and division operator / // we use opcode.Div for division operator and will use another for integer division later. // for division operator, we will use float64 for calculation. switch a.Kind() { case types.KindFloat64: y, err1 := b.ToFloat64() if err1 != nil { return d, errors.Trace(err1) } if y == 0 { return d, nil } x := a.GetFloat64() d.SetFloat64(x / y) return d, nil default: // the scale of the result is the scale of the first operand plus // the value of the div_precision_increment system variable (which is 4 by default) // we will use 4 here xa, err1 := a.ToDecimal() if err != nil { return d, errors.Trace(err1) } xb, err1 := b.ToDecimal() if err1 != nil { return d, errors.Trace(err1) } if f, _ := xb.Float64(); f == 0 { // division by zero return null return d, nil } d.SetMysqlDecimal(xa.Div(xb)) return d, nil } }
func computeIntDiv(a, b types.Datum) (d types.Datum, err error) { switch a.Kind() { case types.KindInt64: x := a.GetInt64() switch b.Kind() { case types.KindInt64: y := b.GetInt64() if y == 0 { return d, nil } r, err1 := types.DivInt64(x, y) d.SetInt64(r) return d, errors.Trace(err1) case types.KindUint64: y := b.GetUint64() if y == 0 { return d, nil } r, err1 := types.DivIntWithUint(x, y) d.SetUint64(r) return d, errors.Trace(err1) } case types.KindUint64: x := a.GetUint64() switch b.Kind() { case types.KindInt64: y := b.GetInt64() if y == 0 { return d, nil } r, err1 := types.DivUintWithInt(x, y) d.SetUint64(r) return d, errors.Trace(err1) case types.KindUint64: y := b.GetUint64() if y == 0 { return d, nil } d.SetUint64(x / y) return d, nil } } // if any is none integer, use decimal to calculate x, err := a.ToDecimal() if err != nil { return d, errors.Trace(err) } y, err := b.ToDecimal() if err != nil { return d, errors.Trace(err) } if f, _ := y.Float64(); f == 0 { return d, nil } d.SetInt64(x.Div(y).IntPart()) return d, nil }