forked from pingcap/tidb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
78 lines (71 loc) · 1.88 KB
/
util.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package aggregation
import (
"github.com/juju/errors"
"github.com/pingcap/tidb/sessionctx/variable"
"github.com/pingcap/tidb/util/codec"
"github.com/pingcap/tidb/util/mvmap"
"github.com/pingcap/tidb/util/types"
)
// distinctChecker stores existing keys and checks if given data is distinct.
type distinctChecker struct {
existingKeys *mvmap.MVMap
buf []byte
}
// createDistinctChecker creates a new distinct checker.
func createDistinctChecker() *distinctChecker {
return &distinctChecker{
existingKeys: mvmap.NewMVMap(),
}
}
// Check checks if values is distinct.
func (d *distinctChecker) Check(values []types.Datum) (bool, error) {
d.buf = d.buf[:0]
var err error
d.buf, err = codec.EncodeValue(d.buf, values...)
if err != nil {
return false, errors.Trace(err)
}
v := d.existingKeys.Get(d.buf)
if v != nil {
return false, nil
}
d.existingKeys.Put(d.buf, []byte{})
return true, nil
}
// calculateSum adds v to sum.
func calculateSum(sc *variable.StatementContext, sum, v types.Datum) (data types.Datum, err error) {
// for avg and sum calculation
// avg and sum use decimal for integer and decimal type, use float for others
// see https://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html
switch v.Kind() {
case types.KindNull:
case types.KindInt64, types.KindUint64:
var d *types.MyDecimal
d, err = v.ToDecimal(sc)
if err == nil {
data = types.NewDecimalDatum(d)
}
case types.KindMysqlDecimal:
data = v
default:
var f float64
f, err = v.ToFloat64(sc)
if err == nil {
data = types.NewFloat64Datum(f)
}
}
if err != nil {
return data, errors.Trace(err)
}
if data.IsNull() {
return sum, nil
}
switch sum.Kind() {
case types.KindNull:
return data, nil
case types.KindFloat64, types.KindMysqlDecimal:
return types.ComputePlus(sum, data)
default:
return data, errors.Errorf("invalid value %v for aggregate", sum.Kind())
}
}