-
-
Notifications
You must be signed in to change notification settings - Fork 197
/
arithmetic.go
771 lines (680 loc) · 18 KB
/
arithmetic.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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
// Copyright 2020-2021 Dolthub, 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 expression
import (
"fmt"
"reflect"
"regexp"
"strconv"
"strings"
"time"
"github.com/dolthub/vitess/go/mysql"
"github.com/dolthub/vitess/go/vt/sqlparser"
"github.com/shopspring/decimal"
errors "gopkg.in/src-d/go-errors.v1"
"github.com/dolthub/go-mysql-server/sql"
"github.com/dolthub/go-mysql-server/sql/types"
)
var (
// errUnableToCast means that we could not find common type for two arithemtic objects
errUnableToCast = errors.NewKind("Unable to cast between types: %T, %T")
// errUnableToEval means that we could not evaluate an expression
errUnableToEval = errors.NewKind("Unable to evaluate an expression: %v %s %v")
timeTypeRegex = regexp.MustCompile("[0-9]+")
)
func arithmeticWarning(ctx *sql.Context, errCode int, errMsg string) {
if ctx != nil && ctx.Session != nil {
ctx.Session.Warn(&sql.Warning{
Level: "Warning",
Code: errCode,
Message: errMsg,
})
}
}
// ArithmeticOp implements an arithmetic expression. Since we had separate expressions
// for division and mod operation, we need to group all arithmetic together. Use this
// expression to define any arithmetic operation that is separately implemented from
// Arithmetic expression in the future.
type ArithmeticOp interface {
sql.Expression
BinaryExpression
SetOpCount(int32)
Operator() string
}
var _ ArithmeticOp = (*Arithmetic)(nil)
var _ sql.CollationCoercible = (*Arithmetic)(nil)
// Arithmetic expressions include plus, minus and multiplication (+, -, *) operations.
type Arithmetic struct {
BinaryExpressionStub
Op string
ops int32
}
// NewArithmetic creates a new Arithmetic sql.Expression.
func NewArithmetic(left, right sql.Expression, op string) *Arithmetic {
a := &Arithmetic{BinaryExpressionStub{LeftChild: left, RightChild: right}, op, 0}
ops := countArithmeticOps(a)
setArithmeticOps(a, ops)
return a
}
// NewPlus creates a new Arithmetic + sql.Expression.
func NewPlus(left, right sql.Expression) *Arithmetic {
return NewArithmetic(left, right, sqlparser.PlusStr)
}
// NewMinus creates a new Arithmetic - sql.Expression.
func NewMinus(left, right sql.Expression) *Arithmetic {
return NewArithmetic(left, right, sqlparser.MinusStr)
}
// NewMult creates a new Arithmetic * sql.Expression.
func NewMult(left, right sql.Expression) *Arithmetic {
return NewArithmetic(left, right, sqlparser.MultStr)
}
func (a *Arithmetic) Operator() string {
return a.Op
}
func (a *Arithmetic) SetOpCount(i int32) {
a.ops = i
}
func (a *Arithmetic) String() string {
return fmt.Sprintf("(%s %s %s)", a.LeftChild.String(), a.Op, a.RightChild.String())
}
func (a *Arithmetic) DebugString() string {
return fmt.Sprintf("(%s %s %s)", sql.DebugString(a.LeftChild), a.Op, sql.DebugString(a.RightChild))
}
// IsNullable implements the sql.Expression interface.
func (a *Arithmetic) IsNullable() bool {
if types.IsDatetimeType(a.Type()) || types.IsTimestampType(a.Type()) {
return true
}
return a.BinaryExpressionStub.IsNullable()
}
// Type returns the greatest type for given operation.
func (a *Arithmetic) Type() sql.Type {
//TODO: what if both BindVars? should be constant folded
rTyp := a.RightChild.Type()
if types.IsDeferredType(rTyp) {
return rTyp
}
lTyp := a.LeftChild.Type()
if types.IsDeferredType(lTyp) {
return lTyp
}
// applies for + and - ops
if isInterval(a.LeftChild) || isInterval(a.RightChild) {
// TODO: need to use the precision stored in datetimeType; something like
// return types.MustCreateDatetimeType(sqltypes.Datetime, 0)
return types.Datetime
}
if types.IsText(lTyp) || types.IsText(rTyp) {
return types.Float64
}
if types.IsJSON(lTyp) || types.IsJSON(rTyp) {
return types.Float64
}
if types.IsFloat(lTyp) || types.IsFloat(rTyp) {
return types.Float64
}
if types.IsYear(lTyp) && types.IsYear(rTyp) {
// MySQL just returns the largest int that fits
return types.Uint64
}
// Bit types are integers
if types.IsBit(lTyp) {
lTyp = types.Int64
}
if types.IsBit(rTyp) {
rTyp = types.Int64
}
// Dates are Integers
if types.IsDateType(lTyp) {
lTyp = types.Int64
}
if types.IsDateType(rTyp) {
rTyp = types.Int64
}
// Datetime(0) is treated as Int64, otherwise as Decimal
if types.IsDatetimeType(lTyp) {
if dtType, ok := lTyp.(sql.DatetimeType); ok {
scale := uint8(dtType.Precision())
if scale == 0 {
lTyp = types.Int64
} else {
lTyp = types.MustCreateDecimalType(types.DecimalTypeMaxPrecision, scale)
}
}
}
if types.IsDatetimeType(rTyp) {
if dtType, ok := rTyp.(sql.DatetimeType); ok {
scale := uint8(dtType.Precision())
if scale == 0 {
rTyp = types.Int64
} else {
rTyp = types.MustCreateDecimalType(types.DecimalTypeMaxPrecision, scale)
}
}
}
if types.IsUnsigned(lTyp) && types.IsUnsigned(rTyp) {
return types.Uint64
}
if types.IsInteger(lTyp) && types.IsInteger(rTyp) {
return types.Int64
}
if types.IsDecimal(lTyp) && !types.IsDecimal(rTyp) {
return lTyp
}
if types.IsDecimal(rTyp) && !types.IsDecimal(lTyp) {
return rTyp
}
if types.IsDecimal(lTyp) && types.IsDecimal(rTyp) {
lPrec := lTyp.(sql.DecimalType).Precision()
lScale := lTyp.(sql.DecimalType).Scale()
rPrec := rTyp.(sql.DecimalType).Precision()
rScale := rTyp.(sql.DecimalType).Scale()
var prec, scale uint8
if lPrec > rPrec {
prec = lPrec
} else {
prec = rPrec
}
switch a.Op {
case sqlparser.PlusStr, sqlparser.MinusStr:
if lScale > rScale {
scale = lScale
} else {
scale = rScale
}
prec = prec + scale
case sqlparser.MultStr:
scale = lScale + rScale
prec = prec + scale
}
if prec > types.DecimalTypeMaxPrecision {
prec = types.DecimalTypeMaxPrecision
}
if scale > types.DecimalTypeMaxScale {
scale = types.DecimalTypeMaxScale
}
return types.MustCreateDecimalType(prec, scale)
}
// When in doubt return float64
return types.Float64
}
// CollationCoercibility implements the interface sql.CollationCoercible.
func (*Arithmetic) CollationCoercibility(ctx *sql.Context) (collation sql.CollationID, coercibility byte) {
return sql.Collation_binary, 5
}
// WithChildren implements the Expression interface.
func (a *Arithmetic) WithChildren(children ...sql.Expression) (sql.Expression, error) {
if len(children) != 2 {
return nil, sql.ErrInvalidChildrenNumber.New(a, len(children), 2)
}
// sanity check
switch strings.ToLower(a.Op) {
case sqlparser.DivStr:
return NewDiv(children[0], children[1]), nil
case sqlparser.ModStr:
return NewMod(children[0], children[1]), nil
}
return NewArithmetic(children[0], children[1], a.Op), nil
}
// Eval implements the Expression interface.
func (a *Arithmetic) Eval(ctx *sql.Context, row sql.Row) (interface{}, error) {
lval, rval, err := a.evalLeftRight(ctx, row)
if err != nil {
return nil, err
}
if lval == nil || rval == nil {
return nil, nil
}
lval, rval, err = a.convertLeftRight(ctx, lval, rval)
if err != nil {
return nil, err
}
var result interface{}
switch strings.ToLower(a.Op) {
case sqlparser.PlusStr:
result, err = plus(lval, rval)
case sqlparser.MinusStr:
result, err = minus(lval, rval)
case sqlparser.MultStr:
result, err = mult(lval, rval)
}
if err != nil {
return nil, err
}
// Decimals must be rounded
if res, ok := result.(decimal.Decimal); ok {
if isOutermostArithmeticOp(a, a.ops) {
finalScale, hasDiv := getFinalScale(ctx, row, a, 0)
if hasDiv {
// TODO: should always round regardless; we have bad Decimal defaults
return res.Round(finalScale), nil
}
}
}
return result, nil
}
func (a *Arithmetic) evalLeftRight(ctx *sql.Context, row sql.Row) (interface{}, interface{}, error) {
var lval, rval interface{}
var err error
if i, ok := a.LeftChild.(*Interval); ok {
lval, err = i.EvalDelta(ctx, row)
if err != nil {
return nil, nil, err
}
} else {
lval, err = a.LeftChild.Eval(ctx, row)
if err != nil {
return nil, nil, err
}
}
if i, ok := a.RightChild.(*Interval); ok {
rval, err = i.EvalDelta(ctx, row)
if err != nil {
return nil, nil, err
}
} else {
rval, err = a.RightChild.Eval(ctx, row)
if err != nil {
return nil, nil, err
}
}
return lval, rval, nil
}
func (a *Arithmetic) convertLeftRight(ctx *sql.Context, left interface{}, right interface{}) (interface{}, interface{}, error) {
typ := a.Type()
lIsTimeType := types.IsTime(a.LeftChild.Type())
rIsTimeType := types.IsTime(a.RightChild.Type())
if i, ok := left.(*TimeDelta); ok {
left = i
} else {
// these are the types we specifically want to capture from we get from Type()
if types.IsInteger(typ) || types.IsFloat(typ) || types.IsTime(typ) {
left = convertValueToType(ctx, typ, left, lIsTimeType)
} else {
left = convertToDecimalValue(left, lIsTimeType)
}
}
if i, ok := right.(*TimeDelta); ok {
right = i
} else {
// these are the types we specifically want to capture from we get from Type()
if types.IsInteger(typ) || types.IsFloat(typ) || types.IsTime(typ) {
right = convertValueToType(ctx, typ, right, rIsTimeType)
} else {
right = convertToDecimalValue(right, rIsTimeType)
}
}
return left, right, nil
}
func isInterval(expr sql.Expression) bool {
_, ok := expr.(*Interval)
return ok
}
// countArithmeticOps returns the number of arithmetic operators under the current node.
// This lets us count how many arithmetic operators used one after the other
func countArithmeticOps(e sql.Expression) int32 {
if e == nil {
return 0
}
if a, ok := e.(ArithmeticOp); ok {
return countArithmeticOps(a.Left()) + countArithmeticOps(a.Right()) + 1
}
return 0
}
// setArithmeticOps will set ops number with number counted by countArithmeticOps. This allows
// us to keep track of whether the expression is the last arithmetic operation.
func setArithmeticOps(e sql.Expression, ops int32) {
if e == nil {
return
}
if a, ok := e.(ArithmeticOp); ok {
a.SetOpCount(ops)
setArithmeticOps(a.Left(), ops)
setArithmeticOps(a.Right(), ops)
}
if tup, ok := e.(Tuple); ok {
for _, expr := range tup {
setArithmeticOps(expr, ops)
}
}
return
}
// isOutermostArithmeticOp return whether the expression we're currently on is
// the last arithmetic operation of all continuous arithmetic operations.
func isOutermostArithmeticOp(e sql.Expression, opScale int32) bool {
return opScale == countArithmeticOps(e)
}
// convertValueToType returns |val| converted into type |typ|. If the value is
// invalid and cannot be converted to the given type, it returns nil, and it should be
// interpreted as value of 0. For time types, all the numbers are parsed up to seconds only.
// E.g: `2022-11-10 12:14:36` is parsed into `20221110121436` and `2022-03-24` is parsed into `20220324`.
func convertValueToType(ctx *sql.Context, typ sql.Type, val interface{}, isTimeType bool) interface{} {
var cval interface{}
if isTimeType {
val = convertTimeTypeToString(val)
}
cval, _, err := typ.Convert(val)
if err != nil {
arithmeticWarning(ctx, mysql.ERTruncatedWrongValue, fmt.Sprintf("Truncated incorrect %s value: '%v'", typ.String(), val))
// the value is interpreted as 0, but we need to match the type of the other valid value
// to avoid additional conversion, the nil value is handled in each operation
}
return cval
}
// convertTimeTypeToString returns string value parsed from either time.Time or string
// representation. all the numbers are parsed up to seconds only. The location can be
// different between two time.Time values, so we set it to default UTC location before
// parsing. E.g:
// `2022-11-10 12:14:36` is parsed into `20221110121436`
// `2022-03-24` is parsed into `20220324`.
func convertTimeTypeToString(val interface{}) interface{} {
if t, ok := val.(time.Time); ok {
val = t.In(time.UTC).Format("2006-01-02 15:04:05")
}
if t, ok := val.(string); ok {
nums := timeTypeRegex.FindAllString(t, -1)
val = strings.Join(nums, "")
}
return val
}
func plus(lval, rval interface{}) (interface{}, error) {
switch l := lval.(type) {
case uint8:
switch r := rval.(type) {
case uint8:
return l + r, nil
}
case int8:
switch r := rval.(type) {
case int8:
return l + r, nil
}
case uint16:
switch r := rval.(type) {
case uint16:
return l + r, nil
}
case int16:
switch r := rval.(type) {
case int16:
return l + r, nil
}
case uint32:
switch r := rval.(type) {
case uint32:
return l + r, nil
}
case int32:
switch r := rval.(type) {
case int32:
return l + r, nil
}
case uint64:
switch r := rval.(type) {
case uint64:
return l + r, nil
}
case int64:
switch r := rval.(type) {
case int64:
return l + r, nil
}
case float32:
switch r := rval.(type) {
case float32:
return l + r, nil
}
case float64:
switch r := rval.(type) {
case float64:
return l + r, nil
}
case decimal.Decimal:
switch r := rval.(type) {
case decimal.Decimal:
return l.Add(r), nil
}
case time.Time:
switch r := rval.(type) {
case *TimeDelta:
return types.ValidateTime(r.Add(l)), nil
case time.Time:
return l.Unix() + r.Unix(), nil
}
case *TimeDelta:
switch r := rval.(type) {
case time.Time:
return types.ValidateTime(l.Add(r)), nil
}
}
return nil, errUnableToCast.New(lval, rval)
}
func minus(lval, rval interface{}) (interface{}, error) {
switch l := lval.(type) {
case uint8:
switch r := rval.(type) {
case uint8:
return l - r, nil
}
case int8:
switch r := rval.(type) {
case int8:
return l - r, nil
}
case uint16:
switch r := rval.(type) {
case uint16:
return l - r, nil
}
case int16:
switch r := rval.(type) {
case int16:
return l - r, nil
}
case uint32:
switch r := rval.(type) {
case uint32:
return l - r, nil
}
case int32:
switch r := rval.(type) {
case int32:
return l - r, nil
}
case uint64:
switch r := rval.(type) {
case uint64:
return l - r, nil
}
case int64:
switch r := rval.(type) {
case int64:
return l - r, nil
}
case float32:
switch r := rval.(type) {
case float32:
return l - r, nil
}
case float64:
switch r := rval.(type) {
case float64:
return l - r, nil
}
case decimal.Decimal:
switch r := rval.(type) {
case decimal.Decimal:
return l.Sub(r), nil
}
case time.Time:
switch r := rval.(type) {
case *TimeDelta:
return types.ValidateTime(r.Sub(l)), nil
case time.Time:
return l.Unix() - r.Unix(), nil
}
}
return nil, errUnableToCast.New(lval, rval)
}
func mult(lval, rval interface{}) (interface{}, error) {
switch l := lval.(type) {
case uint8:
switch r := rval.(type) {
case uint8:
return l * r, nil
}
case int8:
switch r := rval.(type) {
case int8:
return l * r, nil
}
case uint16:
switch r := rval.(type) {
case uint16:
return l * r, nil
}
case int16:
switch r := rval.(type) {
case int16:
return l * r, nil
}
case uint32:
switch r := rval.(type) {
case uint32:
return l * r, nil
}
case int32:
switch r := rval.(type) {
case int32:
return l * r, nil
}
case uint64:
switch r := rval.(type) {
case uint64:
return l * r, nil
}
case int64:
switch r := rval.(type) {
case int64:
return l * r, nil
}
case float32:
switch r := rval.(type) {
case float32:
return l * r, nil
}
case float64:
switch r := rval.(type) {
case float64:
return l * r, nil
}
case decimal.Decimal:
switch r := rval.(type) {
case decimal.Decimal:
return l.Mul(r), nil
}
}
return nil, errUnableToCast.New(lval, rval)
}
// UnaryMinus is an unary minus operator.
type UnaryMinus struct {
UnaryExpression
}
var _ sql.Expression = (*UnaryMinus)(nil)
var _ sql.CollationCoercible = (*UnaryMinus)(nil)
// NewUnaryMinus creates a new UnaryMinus expression node.
func NewUnaryMinus(child sql.Expression) *UnaryMinus {
return &UnaryMinus{UnaryExpression{Child: child}}
}
// Eval implements the sql.Expression interface.
func (e *UnaryMinus) Eval(ctx *sql.Context, row sql.Row) (interface{}, error) {
child, err := e.Child.Eval(ctx, row)
if err != nil {
return nil, err
}
if child == nil {
return nil, nil
}
if !types.IsNumber(e.Child.Type()) {
child, err = decimal.NewFromString(fmt.Sprintf("%v", child))
if err != nil {
child = 0.0
}
}
switch n := child.(type) {
case float64:
return -n, nil
case float32:
return -n, nil
case int:
return -n, nil
case int8:
return -n, nil
case int16:
return -n, nil
case int32:
return -n, nil
case int64:
return -n, nil
case uint:
return -int(n), nil
case uint8:
return -int8(n), nil
case uint16:
return -int16(n), nil
case uint32:
return -int32(n), nil
case uint64:
return -int64(n), nil
case decimal.Decimal:
return n.Neg(), err
case string:
// try getting int out of string value
i, iErr := strconv.ParseInt(n, 10, 64)
if iErr != nil {
return nil, sql.ErrInvalidType.New(reflect.TypeOf(n))
}
return -i, nil
default:
return nil, sql.ErrInvalidType.New(reflect.TypeOf(n))
}
}
// Type implements the sql.Expression interface.
func (e *UnaryMinus) Type() sql.Type {
typ := e.Child.Type()
if !types.IsNumber(typ) {
return types.Float64
}
if typ == types.Uint32 {
return types.Int32
}
if typ == types.Uint64 {
return types.Int64
}
return e.Child.Type()
}
// CollationCoercibility implements the interface sql.CollationCoercible.
func (*UnaryMinus) CollationCoercibility(ctx *sql.Context) (collation sql.CollationID, coercibility byte) {
return sql.Collation_binary, 5
}
func (e *UnaryMinus) String() string {
return fmt.Sprintf("-%s", e.Child)
}
// WithChildren implements the Expression interface.
func (e *UnaryMinus) WithChildren(children ...sql.Expression) (sql.Expression, error) {
if len(children) != 1 {
return nil, sql.ErrInvalidChildrenNumber.New(e, len(children), 1)
}
return NewUnaryMinus(children[0]), nil
}