/
ordering.go
353 lines (332 loc) · 10.8 KB
/
ordering.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
/*
Copyright 2020 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"
"vitess.io/vitess/go/mysql/collations"
vtrpcpb "vitess.io/vitess/go/vt/proto/vtrpc"
"vitess.io/vitess/go/vt/sqlparser"
"vitess.io/vitess/go/vt/vterrors"
"vitess.io/vitess/go/vt/vtgate/engine"
)
type v3Order struct {
*sqlparser.Order
fromGroupBy bool
}
type v3OrderBy []*v3Order
func planOrdering(pb *primitiveBuilder, input logicalPlan, orderBy v3OrderBy) (logicalPlan, error) {
switch node := input.(type) {
case *simpleProjection, *vindexFunc:
if len(orderBy) == 0 {
return node, nil
}
return newMemorySort(node, orderBy)
case *distinct:
// TODO: this is weird, but needed
newInput, err := planOrdering(pb, node.input, orderBy)
node.input = newInput
return node, err
case *pulloutSubquery:
plan, err := planOrdering(pb, node.underlying, orderBy)
if err != nil {
return nil, err
}
node.underlying = plan
return node, nil
case *route:
return planRouteOrdering(orderBy, node)
case *join:
return planJoinOrdering(pb, orderBy, node)
case *orderedAggregate:
return planOAOrdering(pb, orderBy, node)
case *mergeSort:
return nil, vterrors.Errorf(vtrpcpb.Code_UNIMPLEMENTED, "can't do ORDER BY on top of ORDER BY")
case *concatenate:
if len(orderBy) == 0 {
return input, nil
}
return nil, vterrors.Errorf(vtrpcpb.Code_UNIMPLEMENTED, "can't do ORDER BY on top of UNION")
}
return nil, vterrors.Errorf(vtrpcpb.Code_INTERNAL, "[BUG] unreachable %T.ordering", input)
}
func planOAOrdering(pb *primitiveBuilder, orderBy v3OrderBy, oa *orderedAggregate) (logicalPlan, error) {
// The requested order must be such that the ordering can be done
// before the group by, which will allow us to push it down to the
// route. This is actually true in most use cases, except for situations
// where ordering is requested on values of an aggregate result.
// Such constructs will need to be handled by a separate 'Sorter'
// primitive, after aggregation is done. For example, the following
// constructs are allowed:
// 'select a, b, count(*) from t group by a, b order by a desc, b asc'
// 'select a, b, count(*) from t group by a, b order by b'
// The following construct is not allowed:
// 'select a, count(*) from t group by a order by count(*)'
// Treat order by null as nil order by.
if len(orderBy) == 1 {
if _, ok := orderBy[0].Expr.(*sqlparser.NullVal); ok {
orderBy = nil
}
}
// referenced tracks the keys referenced by the order by clause.
referenced := make([]bool, len(oa.groupByKeys))
postSort := false
selOrderBy := make(v3OrderBy, 0, len(orderBy))
for _, order := range orderBy {
// Identify the order by column.
var orderByCol *column
switch expr := order.Expr.(type) {
case *sqlparser.Literal:
num, err := ResultFromNumber(oa.resultColumns, expr, "order clause")
if err != nil {
return nil, err
}
orderByCol = oa.resultColumns[num].column
case *sqlparser.ColName:
orderByCol = expr.Metadata.(*column)
case *sqlparser.CastExpr:
col, ok := expr.Expr.(*sqlparser.ColName)
if !ok {
return nil, fmt.Errorf("unsupported: in scatter query: complex order by expression: %s", sqlparser.String(expr))
}
orderByCol = col.Metadata.(*column)
case *sqlparser.ConvertExpr:
col, ok := expr.Expr.(*sqlparser.ColName)
if !ok {
return nil, fmt.Errorf("unsupported: in scatter query: complex order by expression: %s", sqlparser.String(expr))
}
orderByCol = col.Metadata.(*column)
default:
return nil, fmt.Errorf("unsupported: in scatter query: complex order by expression: %v", sqlparser.String(expr))
}
// Match orderByCol against the group by columns.
found := false
for j, groupBy := range oa.groupByKeys {
if oa.resultColumns[groupBy.KeyCol].column != orderByCol {
continue
}
found = true
referenced[j] = true
order.fromGroupBy = groupBy.FromGroupBy
selOrderBy = append(selOrderBy, order)
break
}
if !found {
postSort = true
}
}
// Append any unreferenced keys at the end of the order by.
for i, groupByKey := range oa.groupByKeys {
if referenced[i] {
continue
}
// Build a brand new reference for the key.
col, err := BuildColName(oa.input.ResultColumns(), groupByKey.KeyCol)
if err != nil {
return nil, vterrors.Wrapf(err, "generating order by clause")
}
selOrderBy = append(selOrderBy, &v3Order{
Order: &sqlparser.Order{Expr: col, Direction: sqlparser.AscOrder},
fromGroupBy: groupByKey.FromGroupBy,
})
}
// Append the distinct aggregate if any.
if oa.extraDistinct != nil {
selOrderBy = append(selOrderBy, &v3Order{
Order: &sqlparser.Order{Expr: oa.extraDistinct, Direction: sqlparser.AscOrder},
fromGroupBy: true,
})
}
// Push down the order by.
// It's ok to push the original AST down because all references
// should point to the route. Only aggregate functions are originated
// by node, and we currently don't allow the ORDER BY to reference them.
plan, err := planOrdering(pb, oa.input, selOrderBy)
if err != nil {
return nil, err
}
oa.input = plan
if postSort {
return newMemorySort(oa, orderBy)
}
return oa, nil
}
func planJoinOrdering(pb *primitiveBuilder, orderBy v3OrderBy, node *join) (logicalPlan, error) {
isSpecial := false
switch len(orderBy) {
case 0:
isSpecial = true
case 1:
if _, ok := orderBy[0].Expr.(*sqlparser.NullVal); ok {
isSpecial = true
} else if f, ok := orderBy[0].Expr.(*sqlparser.FuncExpr); ok {
if f.Name.Lowered() == "rand" {
isSpecial = true
}
}
}
if isSpecial {
l, err := planOrdering(pb, node.Left, orderBy)
if err != nil {
return nil, err
}
node.Left = l
r, err := planOrdering(pb, node.Right, orderBy)
if err != nil {
return nil, err
}
node.Right = r
return node, nil
}
for _, order := range orderBy {
if e, ok := order.Expr.(*sqlparser.Literal); ok {
// This block handles constructs that use ordinals for 'ORDER BY'. For example:
// SELECT a, b, c FROM t1, t2 ORDER BY 1, 2, 3.
num, err := ResultFromNumber(node.ResultColumns(), e, "order clause")
if err != nil {
return nil, err
}
if node.ResultColumns()[num].column.Origin().Order() > node.Left.Order() {
return newMemorySort(node, orderBy)
}
} else {
// Analyze column references within the expression to make sure they all
// go to the left.
err := sqlparser.Walk(func(in sqlparser.SQLNode) (kontinue bool, err error) {
switch e := in.(type) {
case *sqlparser.ColName:
if e.Metadata.(*column).Origin().Order() > node.Left.Order() {
return false, vterrors.New(vtrpcpb.Code_UNIMPLEMENTED, "unsupported: order by spans across shards")
}
case *sqlparser.Subquery:
// Unreachable because ResolveSymbols perfoms this check up above.
return false, vterrors.New(vtrpcpb.Code_UNIMPLEMENTED, "unsupported: order by has subquery")
}
return true, nil
}, order.Expr)
if err != nil {
return newMemorySort(node, orderBy)
}
}
}
// There were no errors. We can push the order by to the left-most route.
l, err := planOrdering(pb, node.Left, orderBy)
if err != nil {
return nil, err
}
node.Left = l
// Still need to push an empty order by to the right.
r, err := planOrdering(pb, node.Right, nil)
if err != nil {
return nil, err
}
node.Right = r
return node, nil
}
func planRouteOrdering(orderBy v3OrderBy, node *route) (logicalPlan, error) {
switch len(orderBy) {
case 0:
return node, nil
case 1:
isSpecial := false
if _, ok := orderBy[0].Expr.(*sqlparser.NullVal); ok {
isSpecial = true
} else if f, ok := orderBy[0].Expr.(*sqlparser.FuncExpr); ok {
if f.Name.Lowered() == "rand" {
isSpecial = true
}
}
if isSpecial {
node.Select.AddOrder(orderBy[0].Order)
return node, nil
}
}
if node.isSingleShard() {
for _, order := range orderBy {
node.Select.AddOrder(order.Order)
}
return node, nil
}
// If it's a scatter, we have to populate the OrderBy field.
for _, order := range orderBy {
colNumber := -1
switch expr := order.Expr.(type) {
case *sqlparser.Literal:
var err error
if colNumber, err = ResultFromNumber(node.resultColumns, expr, "order clause"); err != nil {
return nil, err
}
case *sqlparser.ColName:
c := expr.Metadata.(*column)
for i, rc := range node.resultColumns {
if rc.column == c {
colNumber = i
break
}
}
case *sqlparser.UnaryExpr:
col, ok := expr.Expr.(*sqlparser.ColName)
if !ok {
return nil, fmt.Errorf("unsupported: in scatter query: complex order by expression: %s", sqlparser.String(expr))
}
c := col.Metadata.(*column)
for i, rc := range node.resultColumns {
if rc.column == c {
colNumber = i
break
}
}
default:
return nil, fmt.Errorf("unsupported: in scatter query: complex order by expression: %s", sqlparser.String(expr))
}
// If column is not found, then the order by is referencing
// a column that's not on the select list.
if colNumber == -1 {
return nil, fmt.Errorf("unsupported: in scatter query: order by must reference a column in the select list: %s", sqlparser.String(order))
}
starColFixedIndex := colNumber
if selectStatement, ok := node.Select.(*sqlparser.Select); ok {
for i, selectExpr := range selectStatement.SelectExprs {
if starExpr, ok := selectExpr.(*sqlparser.StarExpr); ok {
if i < colNumber {
tableName := starExpr.TableName
tableMap := node.resultColumns[i].column.st.tables
var tableMeta *table
if tableName.IsEmpty() && len(tableMap) == 1 {
for j := range tableMap {
tableMeta = tableMap[j]
}
} else {
tableMeta = tableMap[tableName]
}
if tableMeta == nil || !tableMeta.isAuthoritative {
return nil, vterrors.Errorf(vtrpcpb.Code_UNIMPLEMENTED, "unsupported: in scatter query, can't order by a column that comes after `*` expressions in the SELECT list")
}
starColFixedIndex += len(tableMeta.columnNames) - 1
}
}
}
}
// TODO(king-11) pass in collation here
ob := engine.OrderByParams{
Col: colNumber,
WeightStringCol: -1,
Desc: order.Direction == sqlparser.DescOrder,
StarColFixedIndex: starColFixedIndex,
FromGroupBy: order.fromGroupBy,
CollationID: collations.Unknown,
}
node.eroute.OrderBy = append(node.eroute.OrderBy, ob)
node.Select.AddOrder(order.Order)
}
return newMergeSort(node), nil
}