forked from pingcap/tidb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunctions.go
549 lines (507 loc) · 13.8 KB
/
functions.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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
// Copyright 2015 PingCAP, 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package ast
import (
"bytes"
"fmt"
"strings"
"github.com/juju/errors"
"github.com/pingcap/tidb/model"
"github.com/pingcap/tidb/sessionctx/variable"
"github.com/pingcap/tidb/util/distinct"
"github.com/pingcap/tidb/util/types"
)
var (
_ FuncNode = &AggregateFuncExpr{}
_ FuncNode = &FuncCallExpr{}
_ FuncNode = &FuncCastExpr{}
)
// List scalar function names.
const (
AndAnd = "and"
Cast = "cast"
LeftShift = "leftshift"
RightShift = "rightshift"
OrOr = "or"
GE = "ge"
LE = "le"
EQ = "eq"
NE = "ne"
LT = "lt"
GT = "gt"
Plus = "plus"
Minus = "minus"
And = "bitand"
Or = "bitor"
Mod = "mod"
Xor = "bitxor"
Div = "div"
Mul = "mul"
UnaryNot = "not" // Avoid name conflict with Not in github/pingcap/check.
BitNeg = "bitneg"
IntDiv = "intdiv"
LogicXor = "xor"
NullEQ = "nulleq"
UnaryPlus = "unaryplus"
UnaryMinus = "unaryminus"
In = "in"
Like = "like"
Case = "case"
Regexp = "regexp"
IsNull = "isnull"
IsTruth = "istrue" // Avoid name conflict with IsTrue in github/pingcap/check.
IsFalsity = "isfalse" // Avoid name conflict with IsFalse in github/pingcap/check.
RowFunc = "row"
SetVar = "setvar"
GetVar = "getvar"
Values = "values"
// common functions
Coalesce = "coalesce"
Greatest = "greatest"
// math functions
Abs = "abs"
Ceil = "ceil"
Ceiling = "ceiling"
Ln = "ln"
Log = "log"
Log2 = "log2"
Log10 = "log10"
Pow = "pow"
Power = "power"
Rand = "rand"
Round = "round"
// time functions
Curdate = "curdate"
CurrentDate = "current_date"
CurrentTime = "current_time"
CurrentTimestamp = "current_timestamp"
Curtime = "curtime"
Date = "date"
DateArith = "date_arith"
DateFormat = "date_format"
Day = "day"
DayName = "dayname"
DayOfMonth = "dayofmonth"
DayOfWeek = "dayofweek"
DayOfYear = "dayofyear"
Extract = "extract"
Hour = "hour"
MicroSecond = "microsecond"
Minute = "minute"
Month = "month"
MonthName = "monthname"
Now = "now"
Second = "second"
StrToDate = "str_to_date"
Sysdate = "sysdate"
Time = "time"
TimeDiff = "timediff"
UTCDate = "utc_date"
Week = "week"
Weekday = "weekday"
WeekOfYear = "weekofyear"
Year = "year"
YearWeek = "yearweek"
FromUnixTime = "from_unixtime"
// string functions
ASCII = "ascii"
Concat = "concat"
ConcatWS = "concat_ws"
Convert = "convert"
Lcase = "lcase"
Left = "left"
Length = "length"
Locate = "locate"
Lower = "lower"
Ltrim = "ltrim"
Repeat = "repeat"
Replace = "replace"
Reverse = "reverse"
Rtrim = "rtrim"
Space = "space"
Strcmp = "strcmp"
Substring = "substring"
SubstringIndex = "substring_index"
Trim = "trim"
Upper = "upper"
Ucase = "ucase"
Hex = "hex"
Unhex = "unhex"
Rpad = "rpad"
BitLength = "bit_length"
CharFunc = "char_func"
CharLength = "char_length"
// information functions
ConnectionID = "connection_id"
CurrentUser = "current_user"
Database = "database"
Schema = "schema"
FoundRows = "found_rows"
LastInsertId = "last_insert_id"
User = "user"
Version = "version"
// control functions
If = "if"
Ifnull = "ifnull"
Nullif = "nullif"
// miscellaneous functions
Sleep = "sleep"
// get_lock() and release_lock() is parsed but do nothing.
// It is used for preventing error in Ruby's activerecord migrations.
GetLock = "get_lock"
ReleaseLock = "release_lock"
)
// FuncCallExpr is for function expression.
type FuncCallExpr struct {
funcNode
// FnName is the function name.
FnName model.CIStr
// Args is the function args.
Args []ExprNode
}
// Accept implements Node interface.
func (n *FuncCallExpr) Accept(v Visitor) (Node, bool) {
newNode, skipChildren := v.Enter(n)
if skipChildren {
return v.Leave(newNode)
}
n = newNode.(*FuncCallExpr)
for i, val := range n.Args {
node, ok := val.Accept(v)
if !ok {
return n, false
}
n.Args[i] = node.(ExprNode)
}
return v.Leave(n)
}
// CastFunctionType is the type for cast function.
type CastFunctionType int
// CastFunction types
const (
CastFunction CastFunctionType = iota + 1
CastConvertFunction
CastBinaryOperator
)
// FuncCastExpr is the cast function converting value to another type, e.g, cast(expr AS signed).
// See https://dev.mysql.com/doc/refman/5.7/en/cast-functions.html
type FuncCastExpr struct {
funcNode
// Expr is the expression to be converted.
Expr ExprNode
// Tp is the conversion type.
Tp *types.FieldType
// Cast, Convert and Binary share this struct.
FunctionType CastFunctionType
}
// Accept implements Node Accept interface.
func (n *FuncCastExpr) Accept(v Visitor) (Node, bool) {
newNode, skipChildren := v.Enter(n)
if skipChildren {
return v.Leave(newNode)
}
n = newNode.(*FuncCastExpr)
node, ok := n.Expr.Accept(v)
if !ok {
return n, false
}
n.Expr = node.(ExprNode)
return v.Leave(n)
}
// TrimDirectionType is the type for trim direction.
type TrimDirectionType int
const (
// TrimBothDefault trims from both direction by default.
TrimBothDefault TrimDirectionType = iota
// TrimBoth trims from both direction with explicit notation.
TrimBoth
// TrimLeading trims from left.
TrimLeading
// TrimTrailing trims from right.
TrimTrailing
)
// DateArithType is type for DateArith type.
type DateArithType byte
const (
// DateAdd is to run adddate or date_add function option.
// See https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_adddate
// See https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_date-add
DateAdd DateArithType = iota + 1
// DateSub is to run subdate or date_sub function option.
// See https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_subdate
// See https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_date-sub
DateSub
)
// DateArithInterval is the struct of DateArith interval part.
type DateArithInterval struct {
Unit string
Interval ExprNode
}
const (
// AggFuncCount is the name of Count function.
AggFuncCount = "count"
// AggFuncSum is the name of Sum function.
AggFuncSum = "sum"
// AggFuncAvg is the name of Avg function.
AggFuncAvg = "avg"
// AggFuncFirstRow is the name of FirstRowColumn function.
AggFuncFirstRow = "firstrow"
// AggFuncMax is the name of max function.
AggFuncMax = "max"
// AggFuncMin is the name of min function.
AggFuncMin = "min"
// AggFuncGroupConcat is the name of group_concat function.
AggFuncGroupConcat = "group_concat"
)
// AggregateFuncExpr represents aggregate function expression.
type AggregateFuncExpr struct {
funcNode
// F is the function name.
F string
// Args is the function args.
Args []ExprNode
// If distinct is true, the function only aggregate distinct values.
// For example, column c1 values are "1", "2", "2", "sum(c1)" is "5",
// but "sum(distinct c1)" is "3".
Distinct bool
CurrentGroup []byte
// contextPerGroupMap is used to store aggregate evaluation context.
// Each entry for a group.
contextPerGroupMap map[string](*AggEvaluateContext)
}
// Accept implements Node Accept interface.
func (n *AggregateFuncExpr) Accept(v Visitor) (Node, bool) {
newNode, skipChildren := v.Enter(n)
if skipChildren {
return v.Leave(newNode)
}
n = newNode.(*AggregateFuncExpr)
for i, val := range n.Args {
node, ok := val.Accept(v)
if !ok {
return n, false
}
n.Args[i] = node.(ExprNode)
}
return v.Leave(n)
}
// Clear clears aggregate computing context.
func (n *AggregateFuncExpr) Clear() {
n.CurrentGroup = []byte{}
n.contextPerGroupMap = nil
}
// Update is used for update aggregate context.
func (n *AggregateFuncExpr) Update(sc *variable.StatementContext) error {
name := strings.ToLower(n.F)
switch name {
case AggFuncCount:
return n.updateCount(sc)
case AggFuncFirstRow:
return n.updateFirstRow(sc)
case AggFuncGroupConcat:
return n.updateGroupConcat(sc)
case AggFuncMax:
return n.updateMaxMin(sc, true)
case AggFuncMin:
return n.updateMaxMin(sc, false)
case AggFuncSum, AggFuncAvg:
return n.updateSum(sc)
}
return nil
}
// GetContext gets aggregate evaluation context for the current group.
// If it is nil, add a new context into contextPerGroupMap.
func (n *AggregateFuncExpr) GetContext() *AggEvaluateContext {
if n.contextPerGroupMap == nil {
n.contextPerGroupMap = make(map[string](*AggEvaluateContext))
}
if _, ok := n.contextPerGroupMap[string(n.CurrentGroup)]; !ok {
c := &AggEvaluateContext{}
if n.Distinct {
c.DistinctChecker = distinct.CreateDistinctChecker()
}
n.contextPerGroupMap[string(n.CurrentGroup)] = c
}
return n.contextPerGroupMap[string(n.CurrentGroup)]
}
// SetContext sets the aggregate expr evaluation context.
func (n *AggregateFuncExpr) SetContext(ctx map[string](*AggEvaluateContext)) {
n.contextPerGroupMap = ctx
}
func (n *AggregateFuncExpr) updateCount(sc *variable.StatementContext) error {
ctx := n.GetContext()
vals := make([]interface{}, 0, len(n.Args))
for _, a := range n.Args {
value := a.GetValue()
if value == nil {
return nil
}
vals = append(vals, value)
}
if n.Distinct {
d, err := ctx.DistinctChecker.Check(vals)
if err != nil {
return errors.Trace(err)
}
if !d {
return nil
}
}
ctx.Count++
return nil
}
func (n *AggregateFuncExpr) updateFirstRow(sc *variable.StatementContext) error {
ctx := n.GetContext()
if !ctx.Value.IsNull() {
return nil
}
if len(n.Args) != 1 {
return errors.New("Wrong number of args for AggFuncFirstRow")
}
ctx.Value = *n.Args[0].GetDatum()
return nil
}
func (n *AggregateFuncExpr) updateMaxMin(sc *variable.StatementContext, max bool) error {
ctx := n.GetContext()
if len(n.Args) != 1 {
return errors.New("Wrong number of args for AggFuncFirstRow")
}
v := *n.Args[0].GetDatum()
if ctx.Value.IsNull() {
ctx.Value = v
return nil
}
c, err := ctx.Value.CompareDatum(sc, v)
if err != nil {
return errors.Trace(err)
}
if max {
if c == -1 {
ctx.Value = v
}
} else {
if c == 1 {
ctx.Value = v
}
}
return nil
}
func (n *AggregateFuncExpr) updateSum(sc *variable.StatementContext) error {
ctx := n.GetContext()
value := *n.Args[0].GetDatum()
if value.IsNull() {
return nil
}
if n.Distinct {
d, err := ctx.DistinctChecker.Check([]interface{}{value.GetValue()})
if err != nil {
return errors.Trace(err)
}
if !d {
return nil
}
}
var err error
ctx.Value, err = types.CalculateSum(sc, ctx.Value, value)
if err != nil {
return errors.Trace(err)
}
ctx.Count++
return nil
}
func (n *AggregateFuncExpr) updateGroupConcat(sc *variable.StatementContext) error {
ctx := n.GetContext()
vals := make([]interface{}, 0, len(n.Args))
for _, a := range n.Args {
value := a.GetValue()
if value == nil {
return nil
}
vals = append(vals, value)
}
if n.Distinct {
d, err := ctx.DistinctChecker.Check(vals)
if err != nil {
return errors.Trace(err)
}
if !d {
return nil
}
}
if ctx.Buffer == nil {
ctx.Buffer = &bytes.Buffer{}
} else {
// now use comma separator
ctx.Buffer.WriteString(",")
}
for _, val := range vals {
ctx.Buffer.WriteString(fmt.Sprintf("%v", val))
}
// TODO: if total length is greater than global var group_concat_max_len, truncate it.
return nil
}
// AggregateFuncExtractor visits Expr tree.
// It converts ColunmNameExpr to AggregateFuncExpr and collects AggregateFuncExpr.
type AggregateFuncExtractor struct {
inAggregateFuncExpr bool
// AggFuncs is the collected AggregateFuncExprs.
AggFuncs []*AggregateFuncExpr
extracting bool
}
// Enter implements Visitor interface.
func (a *AggregateFuncExtractor) Enter(n Node) (node Node, skipChildren bool) {
switch n.(type) {
case *AggregateFuncExpr:
a.inAggregateFuncExpr = true
case *SelectStmt, *InsertStmt, *DeleteStmt, *UpdateStmt:
// Enter a new context, skip it.
// For example: select sum(c) + c + exists(select c from t) from t;
if a.extracting {
return n, true
}
}
a.extracting = true
return n, false
}
// Leave implements Visitor interface.
func (a *AggregateFuncExtractor) Leave(n Node) (node Node, ok bool) {
switch v := n.(type) {
case *AggregateFuncExpr:
a.inAggregateFuncExpr = false
a.AggFuncs = append(a.AggFuncs, v)
case *ColumnNameExpr:
// compose new AggregateFuncExpr
if !a.inAggregateFuncExpr {
// For example: select sum(c) + c from t;
// The c in sum() should be evaluated for each row.
// The c after plus should be evaluated only once.
agg := &AggregateFuncExpr{
F: AggFuncFirstRow,
Args: []ExprNode{v},
}
agg.SetFlag((v.GetFlag() | FlagHasAggregateFunc))
agg.SetType(v.GetType())
a.AggFuncs = append(a.AggFuncs, agg)
return agg, true
}
}
return n, true
}
// AggEvaluateContext is used to store intermediate result when calculating aggregate functions.
type AggEvaluateContext struct {
DistinctChecker *distinct.Checker
Count int64
Value types.Datum
Buffer *bytes.Buffer // Buffer is used for group_concat.
GotFirstRow bool // It will check if the agg has met the first row key.
}