-
Notifications
You must be signed in to change notification settings - Fork 2k
/
ordered_aggregate.go
406 lines (370 loc) · 13.3 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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
/*
Copyright 2019 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 planbuilder
import (
"fmt"
"strconv"
"vitess.io/vitess/go/mysql/collations"
"vitess.io/vitess/go/sqltypes"
vtrpcpb "vitess.io/vitess/go/vt/proto/vtrpc"
"vitess.io/vitess/go/vt/vterrors"
"vitess.io/vitess/go/vt/vtgate/semantics"
"vitess.io/vitess/go/vt/sqlparser"
"vitess.io/vitess/go/vt/vtgate/engine"
)
var _ logicalPlan = (*orderedAggregate)(nil)
// orderedAggregate is the logicalPlan for engine.OrderedAggregate.
// This gets built if there are aggregations on a SelectScatter
// route. The primitive requests the underlying route to order
// the results by the grouping columns. This will allow the
// engine code to aggregate the results as they come.
// For example: 'select col1, col2, count(*) from t group by col1, col2'
// will be sent to the scatter route as:
// 'select col1, col2, count(*) from t group by col1, col2 order by col1, col2`
// The orderAggregate primitive built for this will be:
// &engine.OrderedAggregate {
// // Aggregates has one column. It computes the count
// // using column 2 of the underlying route.
// Aggregates: []AggregateParams{{
// Opcode: AggregateCount,
// Col: 2,
// }},
//
// // Keys has the two group by values for col1 and col2.
// // The column numbers are from the underlying route.
// // These values will be used to perform the grouping
// // of the ordered results as they come from the underlying
// // route.
// Keys: []int{0, 1},
// Input: (Scatter Route with the order by request),
// }
type orderedAggregate struct {
resultsBuilder
extraDistinct *sqlparser.ColName
// preProcess is true if one of the aggregates needs preprocessing.
preProcess bool
aggrOnEngine bool
// aggregates specifies the aggregation parameters for each
// aggregation function: function opcode and input column number.
aggregates []*engine.AggregateParams
// groupByKeys specifies the input values that must be used for
// the aggregation key.
groupByKeys []*engine.GroupByParams
truncateColumnCount int
}
// checkAggregates analyzes the select expression for aggregates. If it determines
// that a primitive is needed to handle the aggregation, it builds an orderedAggregate
// primitive and returns it. It returns a groupByHandler if there is aggregation it
// can handle.
func (pb *primitiveBuilder) checkAggregates(sel *sqlparser.Select) error {
rb, isRoute := pb.plan.(*route)
if isRoute && rb.isSingleShard() {
// since we can push down all of the aggregation to the route,
// we don't need to do anything else here
return nil
}
// Check if we can allow aggregates.
hasAggregates := sqlparser.ContainsAggregation(sel.SelectExprs) || len(sel.GroupBy) > 0
if !hasAggregates && !sel.Distinct {
return nil
}
// The query has aggregates. We can proceed only
// if the underlying primitive is a route because
// we need the ability to push down group by and
// order by clauses.
if !isRoute {
if hasAggregates {
return vterrors.New(vtrpcpb.Code_UNIMPLEMENTED, "unsupported: cross-shard query with aggregates")
}
pb.plan = newDistinctV3(pb.plan)
return nil
}
// If there is a distinct clause, we can check the select list
// to see if it has a unique vindex reference. For example,
// if the query was 'select distinct id, col from t' (with id
// as a unique vindex), then the distinct operation can be
// safely pushed down because the unique vindex guarantees
// that each id can only be in a single shard. Without the
// unique vindex property, the id could come from multiple
// shards, which will require us to perform the grouping
// at the vtgate level.
if sel.Distinct {
for _, selectExpr := range sel.SelectExprs {
switch selectExpr := selectExpr.(type) {
case *sqlparser.AliasedExpr:
vindex := pb.st.Vindex(selectExpr.Expr, rb)
if vindex != nil && vindex.IsUnique() {
return nil
}
}
}
}
// The group by clause could also reference a unique vindex. The above
// example could itself have been written as
// 'select id, col from t group by id, col', or a query could be like
// 'select id, count(*) from t group by id'. In the above cases,
// the grouping can be done at the shard level, which allows the entire query
// to be pushed down. In order to perform this analysis, we're going to look
// ahead at the group by clause to see if it references a unique vindex.
if pb.groupByHasUniqueVindex(sel, rb) {
return nil
}
// We need an aggregator primitive.
oa := &orderedAggregate{}
oa.resultsBuilder = newResultsBuilder(rb, oa)
pb.plan = oa
pb.plan.Reorder(0)
return nil
}
// groupbyHasUniqueVindex looks ahead at the group by expression to see if
// it references a unique vindex.
//
// The vitess group by rules are different from MySQL because it's not possible
// to match the MySQL behavior without knowing the schema. For example:
// 'select id as val from t group by val' will have different interpretations
// under MySQL depending on whether t has a val column or not.
// In vitess, we always assume that 'val' references 'id'. This is achieved
// by the symbol table resolving against the select list before searching
// the tables.
//
// In order to look ahead, we have to overcome the chicken-and-egg problem:
// group by needs the select aliases to be built. Select aliases are built
// on push-down. But push-down decision depends on whether group by expressions
// reference a vindex.
// To overcome this, the look-ahead has to perform a search that matches
// the group by analyzer. The flow is similar to oa.PushGroupBy, except that
// we don't search the ResultColumns because they're not created yet. Also,
// error conditions are treated as no match for simplicity; They will be
// subsequently caught downstream.
func (pb *primitiveBuilder) groupByHasUniqueVindex(sel *sqlparser.Select, rb *route) bool {
for _, expr := range sel.GroupBy {
var matchedExpr sqlparser.Expr
switch node := expr.(type) {
case *sqlparser.ColName:
if expr := findAlias(node, sel.SelectExprs); expr != nil {
matchedExpr = expr
} else {
matchedExpr = node
}
case *sqlparser.Literal:
if node.Type != sqlparser.IntVal {
continue
}
num, err := strconv.ParseInt(string(node.Val), 0, 64)
if err != nil {
continue
}
if num < 1 || num > int64(len(sel.SelectExprs)) {
continue
}
expr, ok := sel.SelectExprs[num-1].(*sqlparser.AliasedExpr)
if !ok {
continue
}
matchedExpr = expr.Expr
default:
continue
}
vindex := pb.st.Vindex(matchedExpr, rb)
if vindex != nil && vindex.IsUnique() {
return true
}
}
return false
}
func findAlias(colname *sqlparser.ColName, selects sqlparser.SelectExprs) sqlparser.Expr {
// Qualified column names cannot match an (unqualified) alias.
if !colname.Qualifier.IsEmpty() {
return nil
}
// See if this references an alias.
for _, selectExpr := range selects {
selectExpr, ok := selectExpr.(*sqlparser.AliasedExpr)
if !ok {
continue
}
if colname.Name.Equal(selectExpr.As) {
return selectExpr.Expr
}
}
return nil
}
// Primitive implements the logicalPlan interface
func (oa *orderedAggregate) Primitive() engine.Primitive {
colls := map[int]collations.ID{}
for _, key := range oa.aggregates {
if key.CollationID != collations.Unknown {
colls[key.KeyCol] = key.CollationID
}
}
for _, key := range oa.groupByKeys {
if key.CollationID != collations.Unknown {
colls[key.KeyCol] = key.CollationID
}
}
input := oa.input.Primitive()
if len(oa.groupByKeys) == 0 {
return &engine.ScalarAggregate{
PreProcess: oa.preProcess,
AggrOnEngine: oa.aggrOnEngine,
Aggregates: oa.aggregates,
TruncateColumnCount: oa.truncateColumnCount,
Collations: colls,
Input: input,
}
}
return &engine.OrderedAggregate{
PreProcess: oa.preProcess,
AggrOnEngine: oa.aggrOnEngine,
Aggregates: oa.aggregates,
GroupByKeys: oa.groupByKeys,
TruncateColumnCount: oa.truncateColumnCount,
Collations: colls,
Input: input,
}
}
func (oa *orderedAggregate) pushAggr(pb *primitiveBuilder, expr *sqlparser.AliasedExpr, origin logicalPlan) (rc *resultColumn, colNumber int, err error) {
funcExpr := expr.Expr.(*sqlparser.FuncExpr)
origOpcode := engine.SupportedAggregates[funcExpr.Name.Lowered()]
opcode := origOpcode
if len(funcExpr.Exprs) != 1 {
return nil, 0, fmt.Errorf("unsupported: only one expression allowed inside aggregates: %s", sqlparser.String(funcExpr))
}
handleDistinct, innerAliased, err := oa.needDistinctHandling(pb, funcExpr, opcode)
if err != nil {
return nil, 0, err
}
if handleDistinct {
if oa.extraDistinct != nil {
return nil, 0, fmt.Errorf("unsupported: only one distinct aggregation allowed in a select: %s", sqlparser.String(funcExpr))
}
// Push the expression that's inside the aggregate.
// The column will eventually get added to the group by and order by clauses.
newBuilder, _, innerCol, err := planProjection(pb, oa.input, innerAliased, origin)
if err != nil {
return nil, 0, err
}
pb.plan = newBuilder
col, err := BuildColName(oa.input.ResultColumns(), innerCol)
if err != nil {
return nil, 0, err
}
oa.extraDistinct = col
oa.preProcess = true
switch opcode {
case engine.AggregateCount:
opcode = engine.AggregateCountDistinct
case engine.AggregateSum:
opcode = engine.AggregateSumDistinct
}
oa.aggregates = append(oa.aggregates, &engine.AggregateParams{
Opcode: opcode,
Col: innerCol,
Alias: expr.ColumnName(),
OrigOpcode: origOpcode,
})
} else {
newBuilder, _, innerCol, err := planProjection(pb, oa.input, expr, origin)
if err != nil {
return nil, 0, err
}
pb.plan = newBuilder
oa.aggregates = append(oa.aggregates, &engine.AggregateParams{
Opcode: opcode,
Col: innerCol,
OrigOpcode: origOpcode,
})
}
// Build a new rc with oa as origin because it's semantically different
// from the expression we pushed down.
rc = newResultColumn(expr, oa)
oa.resultColumns = append(oa.resultColumns, rc)
return rc, len(oa.resultColumns) - 1, nil
}
// needDistinctHandling returns true if oa needs to handle the distinct clause.
// If true, it will also return the aliased expression that needs to be pushed
// down into the underlying route.
func (oa *orderedAggregate) needDistinctHandling(pb *primitiveBuilder, funcExpr *sqlparser.FuncExpr, opcode engine.AggregateOpcode) (bool, *sqlparser.AliasedExpr, error) {
if !funcExpr.Distinct {
return false, nil, nil
}
if opcode != engine.AggregateCount && opcode != engine.AggregateSum && opcode != engine.AggregateCountStar {
return false, nil, nil
}
innerAliased, ok := funcExpr.Exprs[0].(*sqlparser.AliasedExpr)
if !ok {
return false, nil, fmt.Errorf("syntax error: %s", sqlparser.String(funcExpr))
}
rb, ok := oa.input.(*route)
if !ok {
// Unreachable
return true, innerAliased, nil
}
vindex := pb.st.Vindex(innerAliased.Expr, rb)
if vindex != nil && vindex.IsUnique() {
return false, nil, nil
}
return true, innerAliased, nil
}
// Wireup implements the logicalPlan interface
// If text columns are detected in the keys, then the function modifies
// the primitive to pull a corresponding weight_string from mysql and
// compare those instead. This is because we currently don't have the
// ability to mimic mysql's collation behavior.
func (oa *orderedAggregate) Wireup(plan logicalPlan, jt *jointab) error {
for i, gbk := range oa.groupByKeys {
rc := oa.resultColumns[gbk.KeyCol]
if sqltypes.IsText(rc.column.typ) {
weightcolNumber, err := oa.input.SupplyWeightString(gbk.KeyCol, gbk.FromGroupBy)
if err != nil {
_, isUnsupportedErr := err.(UnsupportedSupplyWeightString)
if isUnsupportedErr {
continue
}
return err
}
oa.weightStrings[rc] = weightcolNumber
oa.groupByKeys[i].WeightStringCol = weightcolNumber
oa.groupByKeys[i].KeyCol = weightcolNumber
oa.truncateColumnCount = len(oa.resultColumns)
}
}
for _, key := range oa.aggregates {
switch key.Opcode {
case engine.AggregateCount:
if key.Alias == "" {
key.Alias = key.Opcode.String()
}
key.Opcode = engine.AggregateSum
}
}
return oa.input.Wireup(plan, jt)
}
func (oa *orderedAggregate) WireupGen4(semTable *semantics.SemTable) error {
return oa.input.WireupGen4(semTable)
}
// OutputColumns implements the logicalPlan interface
func (oa *orderedAggregate) OutputColumns() []sqlparser.SelectExpr {
outputCols := sqlparser.CloneSelectExprs(oa.input.OutputColumns())
for _, aggr := range oa.aggregates {
outputCols[aggr.Col] = &sqlparser.AliasedExpr{Expr: aggr.Expr, As: sqlparser.NewColIdent(aggr.Alias)}
}
if oa.truncateColumnCount > 0 {
return outputCols[:oa.truncateColumnCount]
}
return outputCols
}
// SetTruncateColumnCount sets the truncate column count.
func (oa *orderedAggregate) SetTruncateColumnCount(count int) {
oa.truncateColumnCount = count
}