-
Notifications
You must be signed in to change notification settings - Fork 0
/
distinct.go
executable file
·107 lines (83 loc) · 2.15 KB
/
distinct.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package expression
import (
"fmt"
"github.com/mitchellh/hashstructure"
"github.com/Rock-liyi/p2pdb-store/sql"
)
type DistinctExpression struct {
seen sql.KeyValueCache
dispose sql.DisposeFunc
Child sql.Expression
}
var _ sql.Disposable = (*DistinctExpression)(nil)
func NewDistinctExpression(e sql.Expression) *DistinctExpression {
return &DistinctExpression{
Child: e,
}
}
func (de *DistinctExpression) seenValue(ctx *sql.Context, value interface{}) (bool, error) {
if de.seen == nil {
cache, dispose := ctx.Memory.NewHistoryCache()
de.seen = cache
de.dispose = dispose
}
hash, err := hashstructure.Hash(value, nil)
if err != nil {
return false, err
}
if _, err := de.seen.Get(hash); err == nil {
return false, nil
}
if err := de.seen.Put(hash, struct{}{}); err != nil {
return false, err
}
return true, nil
}
func (de *DistinctExpression) Dispose() {
if de.dispose != nil {
de.dispose()
}
de.dispose = nil
de.seen = nil
}
func (de *DistinctExpression) Resolved() bool {
return de.Child.Resolved()
}
func (de *DistinctExpression) String() string {
return fmt.Sprintf("DISTINCT %s", de.Child.String())
}
func (de *DistinctExpression) Type() sql.Type {
return de.Child.Type()
}
func (de *DistinctExpression) IsNullable() bool {
return false
}
// Returns the child value if the cache hasn't seen the value before otherwise returns nil.
// Since NULLs are ignored in aggregate expressions that use DISTINCT this is a valid return scheme.
func (de *DistinctExpression) Eval(ctx *sql.Context, row sql.Row) (interface{}, error) {
val, err := de.Child.Eval(ctx, row)
if err != nil {
return nil, err
}
should, err := de.seenValue(ctx, val)
if err != nil {
return nil, err
}
if should {
return val, nil
}
return nil, nil
}
func (de *DistinctExpression) Children() []sql.Expression {
return []sql.Expression{de.Child}
}
func (de *DistinctExpression) WithChildren(children ...sql.Expression) (sql.Expression, error) {
if len(children) != 1 {
return nil, fmt.Errorf("DistinctExpression has an invalid number of children")
}
return &DistinctExpression{
seen: nil,
dispose: nil,
Child: children[0],
}, nil
}