-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
scalar_aggregation.go
240 lines (207 loc) · 7.02 KB
/
scalar_aggregation.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
/*
Copyright 2022 The Vitess Authors.
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 (
"context"
"sync"
"vitess.io/vitess/go/sqltypes"
querypb "vitess.io/vitess/go/vt/proto/query"
"vitess.io/vitess/go/vt/proto/vtrpc"
"vitess.io/vitess/go/vt/vterrors"
. "vitess.io/vitess/go/vt/vtgate/engine/opcode"
)
var _ Primitive = (*ScalarAggregate)(nil)
// ScalarAggregate is a primitive used to do aggregations without grouping keys
type ScalarAggregate struct {
// PreProcess is true if one of the aggregates needs preprocessing.
PreProcess bool `json:",omitempty"`
AggrOnEngine bool
// Aggregates specifies the aggregation parameters for each
// aggregation function: function opcode and input column number.
Aggregates []*AggregateParams
// 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
}
// RouteType implements the Primitive interface
func (sa *ScalarAggregate) RouteType() string {
return sa.Input.RouteType()
}
// GetKeyspaceName implements the Primitive interface
func (sa *ScalarAggregate) GetKeyspaceName() string {
return sa.Input.GetKeyspaceName()
}
// GetTableName implements the Primitive interface
func (sa *ScalarAggregate) GetTableName() string {
return sa.Input.GetTableName()
}
// GetFields implements the Primitive interface
func (sa *ScalarAggregate) GetFields(ctx context.Context, vcursor VCursor, bindVars map[string]*querypb.BindVariable) (*sqltypes.Result, error) {
qr, err := sa.Input.GetFields(ctx, vcursor, bindVars)
if err != nil {
return nil, err
}
qr = &sqltypes.Result{Fields: convertFields(qr.Fields, sa.PreProcess, sa.Aggregates, sa.AggrOnEngine)}
return qr.Truncate(sa.TruncateColumnCount), nil
}
// NeedsTransaction implements the Primitive interface
func (sa *ScalarAggregate) NeedsTransaction() bool {
return sa.Input.NeedsTransaction()
}
// TryExecute implements the Primitive interface
func (sa *ScalarAggregate) TryExecute(ctx context.Context, vcursor VCursor, bindVars map[string]*querypb.BindVariable, wantfields bool) (*sqltypes.Result, error) {
result, err := vcursor.ExecutePrimitive(ctx, sa.Input, bindVars, wantfields)
if err != nil {
return nil, err
}
out := &sqltypes.Result{
Fields: convertFields(result.Fields, sa.PreProcess, sa.Aggregates, sa.AggrOnEngine),
}
var resultRow []sqltypes.Value
var curDistincts []sqltypes.Value
for _, row := range result.Rows {
if resultRow == nil {
resultRow, curDistincts = convertRow(row, sa.PreProcess, sa.Aggregates, sa.AggrOnEngine)
continue
}
resultRow, curDistincts, err = merge(result.Fields, resultRow, row, curDistincts, sa.Aggregates)
if err != nil {
return nil, err
}
}
if resultRow == nil {
// When doing aggregation without grouping keys, we need to produce a single row containing zero-value for the
// different aggregation functions
resultRow, err = sa.createEmptyRow()
if err != nil {
return nil, err
}
} else {
resultRow, err = convertFinal(resultRow, sa.Aggregates)
if err != nil {
return nil, err
}
}
out.Rows = [][]sqltypes.Value{resultRow}
return out.Truncate(sa.TruncateColumnCount), nil
}
// TryStreamExecute implements the Primitive interface
func (sa *ScalarAggregate) TryStreamExecute(ctx context.Context, vcursor VCursor, bindVars map[string]*querypb.BindVariable, wantfields bool, callback func(*sqltypes.Result) error) error {
cb := func(qr *sqltypes.Result) error {
return callback(qr.Truncate(sa.TruncateColumnCount))
}
var current []sqltypes.Value
var curDistincts []sqltypes.Value
var fields []*querypb.Field
fieldsSent := false
var mu sync.Mutex
err := vcursor.StreamExecutePrimitive(ctx, sa.Input, bindVars, wantfields, func(result *sqltypes.Result) error {
// as the underlying primitive call is not sync
// and here scalar aggregate is using shared variables we have to sync the callback
// for correct aggregation.
mu.Lock()
defer mu.Unlock()
if len(result.Fields) != 0 && !fieldsSent {
fields = convertFields(result.Fields, sa.PreProcess, sa.Aggregates, sa.AggrOnEngine)
if err := cb(&sqltypes.Result{Fields: fields}); err != nil {
return err
}
fieldsSent = true
}
// this code is very similar to the TryExecute method
for _, row := range result.Rows {
if current == nil {
current, curDistincts = convertRow(row, sa.PreProcess, sa.Aggregates, sa.AggrOnEngine)
continue
}
var err error
current, curDistincts, err = merge(fields, current, row, curDistincts, sa.Aggregates)
if err != nil {
return err
}
}
return nil
})
if err != nil {
return err
}
if current == nil {
// When doing aggregation without grouping keys, we need to produce a single row containing zero-value for the
// different aggregation functions
current, err = sa.createEmptyRow()
if err != nil {
return err
}
} else {
current, err = convertFinal(current, sa.Aggregates)
if err != nil {
return err
}
}
return cb(&sqltypes.Result{Rows: [][]sqltypes.Value{current}})
}
// creates the empty row for the case when we are missing grouping keys and have empty input table
func (sa *ScalarAggregate) createEmptyRow() ([]sqltypes.Value, error) {
out := make([]sqltypes.Value, len(sa.Aggregates))
for i, aggr := range sa.Aggregates {
op := aggr.Opcode
if aggr.OrigOpcode != AggregateUnassigned {
op = aggr.OrigOpcode
}
value, err := createEmptyValueFor(op)
if err != nil {
return nil, err
}
out[i] = value
}
return out, nil
}
func createEmptyValueFor(opcode AggregateOpcode) (sqltypes.Value, error) {
switch opcode {
case
AggregateCountDistinct,
AggregateCount,
AggregateCountStar:
return countZero, nil
case
AggregateSumDistinct,
AggregateSum,
AggregateMin,
AggregateMax,
AggregateRandom:
return sqltypes.NULL, nil
}
return sqltypes.NULL, vterrors.Errorf(vtrpc.Code_INVALID_ARGUMENT, "unknown aggregation %v", opcode)
}
// Inputs implements the Primitive interface
func (sa *ScalarAggregate) Inputs() []Primitive {
return []Primitive{sa.Input}
}
// description implements the Primitive interface
func (sa *ScalarAggregate) description() PrimitiveDescription {
aggregates := GenericJoin(sa.Aggregates, aggregateParamsToString)
other := map[string]any{
"Aggregates": aggregates,
}
if sa.TruncateColumnCount > 0 {
other["ResultColumns"] = sa.TruncateColumnCount
}
return PrimitiveDescription{
OperatorType: "Aggregate",
Variant: "Scalar",
Other: other,
}
}