forked from vitessio/vitess
-
Notifications
You must be signed in to change notification settings - Fork 2
/
ordered_aggregate.go
243 lines (211 loc) · 6.48 KB
/
ordered_aggregate.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
/*
Copyright 2017 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package engine
import (
"fmt"
"github.com/xsec-lab/go/sqltypes"
querypb "github.com/xsec-lab/go/vt/proto/query"
)
var _ Primitive = (*OrderedAggregate)(nil)
// OrderedAggregate is a primitive that expects the underlying primitive
// to feed results in an order sorted by the Keys. Rows with duplicate
// keys are aggregated using the Aggregate functions. The assumption
// is that the underlying primitive is a scatter select with pre-sorted
// rows.
type OrderedAggregate struct {
// Aggregates specifies the aggregation parameters for each
// aggregation function: function opcode and input column number.
Aggregates []AggregateParams
// Keys specifies the input values that must be used for
// the aggregation key.
Keys []int
// TruncateColumnCount specifies the number of columns to return
// in the final result. Rest of the columns are truncated
// from the result received. If 0, no truncation happens.
TruncateColumnCount int `json:",omitempty"`
// Input is the primitive that will feed into this Primitive.
Input Primitive
}
// AggregateParams specify the parameters for each aggregation.
// It contains the opcode and input column number.
type AggregateParams struct {
Opcode AggregateOpcode
Col int
}
// AggregateOpcode is the aggregation Opcode.
type AggregateOpcode int
// These constants list the possible aggregate opcodes.
const (
AggregateCount = AggregateOpcode(iota)
AggregateSum
AggregateMin
AggregateMax
)
// SupportedAggregates maps the list of supported aggregate
// functions to their opcodes.
var SupportedAggregates = map[string]AggregateOpcode{
"count": AggregateCount,
"sum": AggregateSum,
"min": AggregateMin,
"max": AggregateMax,
}
func (code AggregateOpcode) String() string {
for k, v := range SupportedAggregates {
if v == code {
return k
}
}
panic("unreachable")
}
// MarshalJSON serializes the AggregateOpcode as a JSON string.
// It's used for testing and diagnostics.
func (code AggregateOpcode) MarshalJSON() ([]byte, error) {
return ([]byte)(fmt.Sprintf("\"%s\"", code.String())), nil
}
// RouteType returns a description of the query routing type used by the primitive
func (oa *OrderedAggregate) RouteType() string {
return oa.Input.RouteType()
}
// Execute is a Primitive function.
func (oa *OrderedAggregate) Execute(vcursor VCursor, bindVars map[string]*querypb.BindVariable, wantfields bool) (*sqltypes.Result, error) {
qr, err := oa.execute(vcursor, bindVars, wantfields)
if err != nil {
return nil, err
}
return qr.Truncate(oa.TruncateColumnCount), nil
}
func (oa *OrderedAggregate) execute(vcursor VCursor, bindVars map[string]*querypb.BindVariable, wantfields bool) (*sqltypes.Result, error) {
result, err := oa.Input.Execute(vcursor, bindVars, wantfields)
if err != nil {
return nil, err
}
out := &sqltypes.Result{
Fields: result.Fields,
Rows: make([][]sqltypes.Value, 0, len(result.Rows)),
Extras: result.Extras,
}
// This code is similar to the one in StreamExecute.
var current []sqltypes.Value
for _, row := range result.Rows {
if current == nil {
current = row
continue
}
equal, err := oa.keysEqual(current, row)
if err != nil {
return nil, err
}
if equal {
current, err = oa.merge(result.Fields, current, row)
if err != nil {
return nil, err
}
continue
}
out.Rows = append(out.Rows, current)
current = row
}
if current != nil {
out.Rows = append(out.Rows, current)
}
out.RowsAffected = uint64(len(out.Rows))
return out, nil
}
// StreamExecute is a Primitive function.
func (oa *OrderedAggregate) StreamExecute(vcursor VCursor, bindVars map[string]*querypb.BindVariable, wantfields bool, callback func(*sqltypes.Result) error) error {
var current []sqltypes.Value
var fields []*querypb.Field
cb := func(qr *sqltypes.Result) error {
return callback(qr.Truncate(oa.TruncateColumnCount))
}
err := oa.Input.StreamExecute(vcursor, bindVars, wantfields, func(qr *sqltypes.Result) error {
if len(qr.Fields) != 0 {
fields = qr.Fields
if err := cb(&sqltypes.Result{Fields: fields}); err != nil {
return err
}
}
// This code is similar to the one in Execute.
for _, row := range qr.Rows {
if current == nil {
current = row
continue
}
equal, err := oa.keysEqual(current, row)
if err != nil {
return err
}
if equal {
current, err = oa.merge(fields, current, row)
if err != nil {
return err
}
continue
}
if err := cb(&sqltypes.Result{Rows: [][]sqltypes.Value{current}}); err != nil {
return err
}
current = row
}
return nil
})
if err != nil {
return err
}
if current != nil {
if err := cb(&sqltypes.Result{Rows: [][]sqltypes.Value{current}}); err != nil {
return err
}
}
return nil
}
// GetFields is a Primitive function.
func (oa *OrderedAggregate) GetFields(vcursor VCursor, bindVars map[string]*querypb.BindVariable) (*sqltypes.Result, error) {
qr, err := oa.Input.GetFields(vcursor, bindVars)
if err != nil {
return nil, err
}
return qr.Truncate(oa.TruncateColumnCount), nil
}
func (oa *OrderedAggregate) keysEqual(row1, row2 []sqltypes.Value) (bool, error) {
for _, key := range oa.Keys {
cmp, err := sqltypes.NullsafeCompare(row1[key], row2[key])
if err != nil {
return false, err
}
if cmp != 0 {
return false, nil
}
}
return true, nil
}
func (oa *OrderedAggregate) merge(fields []*querypb.Field, row1, row2 []sqltypes.Value) ([]sqltypes.Value, error) {
result := sqltypes.CopyRow(row1)
for _, aggr := range oa.Aggregates {
var err error
switch aggr.Opcode {
case AggregateCount, AggregateSum:
result[aggr.Col], err = sqltypes.NullsafeAdd(row1[aggr.Col], row2[aggr.Col], fields[aggr.Col].Type)
case AggregateMin:
result[aggr.Col], err = sqltypes.Min(row1[aggr.Col], row2[aggr.Col])
case AggregateMax:
result[aggr.Col], err = sqltypes.Max(row1[aggr.Col], row2[aggr.Col])
default:
return nil, fmt.Errorf("BUG: Unexpected opcode: %v", aggr.Opcode)
}
if err != nil {
return nil, err
}
}
return result, nil
}