-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
arithmetic.go
585 lines (506 loc) · 16.5 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
/*
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 evalengine
import (
"bytes"
"fmt"
"math"
"vitess.io/vitess/go/sqltypes"
"strconv"
querypb "vitess.io/vitess/go/vt/proto/query"
vtrpcpb "vitess.io/vitess/go/vt/proto/vtrpc"
"vitess.io/vitess/go/vt/vterrors"
)
// evalengine represents a numeric value extracted from
// a Value, used for arithmetic operations.
var zeroBytes = []byte("0")
// UnsupportedComparisonError represents the error where the comparison between the two types is unsupported on vitess
type UnsupportedComparisonError struct {
Type1 querypb.Type
Type2 querypb.Type
}
// Error function implements the error interface
func (err UnsupportedComparisonError) Error() string {
return fmt.Sprintf("types are not comparable: %v vs %v", err.Type1, err.Type2)
}
// Add adds two values together
// if v1 or v2 is null, then it returns null
func Add(v1, v2 sqltypes.Value) (sqltypes.Value, error) {
if v1.IsNull() || v2.IsNull() {
return sqltypes.NULL, nil
}
lv1, err := newEvalResult(v1)
if err != nil {
return sqltypes.NULL, err
}
lv2, err := newEvalResult(v2)
if err != nil {
return sqltypes.NULL, err
}
lresult, err := addNumericWithError(lv1, lv2)
if err != nil {
return sqltypes.NULL, err
}
return lresult.toSQLValue(lresult.typ), nil
}
// Subtract takes two values and subtracts them
func Subtract(v1, v2 sqltypes.Value) (sqltypes.Value, error) {
if v1.IsNull() || v2.IsNull() {
return sqltypes.NULL, nil
}
lv1, err := newEvalResult(v1)
if err != nil {
return sqltypes.NULL, err
}
lv2, err := newEvalResult(v2)
if err != nil {
return sqltypes.NULL, err
}
lresult, err := subtractNumericWithError(lv1, lv2)
if err != nil {
return sqltypes.NULL, err
}
return lresult.toSQLValue(lresult.typ), nil
}
// Multiply takes two values and multiplies it together
func Multiply(v1, v2 sqltypes.Value) (sqltypes.Value, error) {
if v1.IsNull() || v2.IsNull() {
return sqltypes.NULL, nil
}
lv1, err := newEvalResult(v1)
if err != nil {
return sqltypes.NULL, err
}
lv2, err := newEvalResult(v2)
if err != nil {
return sqltypes.NULL, err
}
lresult, err := multiplyNumericWithError(lv1, lv2)
if err != nil {
return sqltypes.NULL, err
}
return lresult.toSQLValue(lresult.typ), nil
}
// Divide (Float) for MySQL. Replicates behavior of "/" operator
func Divide(v1, v2 sqltypes.Value) (sqltypes.Value, error) {
if v1.IsNull() || v2.IsNull() {
return sqltypes.NULL, nil
}
lv2AsFloat, err := ToFloat64(v2)
divisorIsZero := lv2AsFloat == 0
if divisorIsZero || err != nil {
return sqltypes.NULL, err
}
lv1, err := newEvalResult(v1)
if err != nil {
return sqltypes.NULL, err
}
lv2, err := newEvalResult(v2)
if err != nil {
return sqltypes.NULL, err
}
lresult, err := divideNumericWithError(lv1, lv2)
if err != nil {
return sqltypes.NULL, err
}
return lresult.toSQLValue(lresult.typ), nil
}
// NullsafeAdd adds two Values in a null-safe manner. A null value
// is treated as 0. If both values are null, then a null is returned.
// If both values are not null, a numeric value is built
// from each input: Signed->int64, Unsigned->uint64, Float->float64.
// Otherwise the 'best type fit' is chosen for the number: int64 or float64.
// Addition is performed by upgrading types as needed, or in case
// of overflow: int64->uint64, int64->float64, uint64->float64.
// Unsigned ints can only be added to positive ints. After the
// addition, if one of the input types was Decimal, then
// a Decimal is built. Otherwise, the final type of the
// result is preserved.
func NullsafeAdd(v1, v2 sqltypes.Value, resultType querypb.Type) sqltypes.Value {
if v1.IsNull() {
v1 = sqltypes.MakeTrusted(resultType, zeroBytes)
}
if v2.IsNull() {
v2 = sqltypes.MakeTrusted(resultType, zeroBytes)
}
lv1, err := newEvalResult(v1)
if err != nil {
return sqltypes.NULL
}
lv2, err := newEvalResult(v2)
if err != nil {
return sqltypes.NULL
}
lresult := addNumeric(lv1, lv2)
return lresult.toSQLValue(resultType)
}
// NullsafeCompare returns 0 if v1==v2, -1 if v1<v2, and 1 if v1>v2.
// NULL is the lowest value. If any value is
// numeric, then a numeric comparison is performed after
// necessary conversions. If none are numeric, then it's
// a simple binary comparison. Uncomparable values return an error.
func NullsafeCompare(v1, v2 sqltypes.Value) (int, error) {
// Based on the categorization defined for the types,
// we're going to allow comparison of the following:
// Null, isNumber, IsBinary. This will exclude IsQuoted
// types that are not Binary, and Expression.
if v1.IsNull() {
if v2.IsNull() {
return 0, nil
}
return -1, nil
}
if v2.IsNull() {
return 1, nil
}
if sqltypes.IsNumber(v1.Type()) || sqltypes.IsNumber(v2.Type()) {
lv1, err := newEvalResult(v1)
if err != nil {
return 0, err
}
lv2, err := newEvalResult(v2)
if err != nil {
return 0, err
}
return compareNumeric(lv1, lv2)
}
if isByteComparable(v1) && isByteComparable(v2) {
return bytes.Compare(v1.ToBytes(), v2.ToBytes()), nil
}
return 0, UnsupportedComparisonError{
Type1: v1.Type(),
Type2: v2.Type(),
}
}
// NullsafeHashcode returns an int64 hashcode that is guaranteed to be the same
// for two values that are considered equal by `NullsafeCompare`.
// TODO: should be extended to support all possible types
func NullsafeHashcode(v sqltypes.Value) (int64, error) {
if v.IsNull() {
return math.MaxInt64, nil
}
if sqltypes.IsNumber(v.Type()) {
result, err := newEvalResult(v)
if err != nil {
return 0, err
}
return hashCode(result), nil
}
return 0, vterrors.Errorf(vtrpcpb.Code_UNIMPLEMENTED, "types does not support hashcode yet: %v", v.Type())
}
// isByteComparable returns true if the type is binary or date/time.
func isByteComparable(v sqltypes.Value) bool {
if v.IsBinary() {
return true
}
switch v.Type() {
case sqltypes.Timestamp, sqltypes.Date, sqltypes.Time, sqltypes.Datetime, sqltypes.Enum, sqltypes.Set, sqltypes.TypeJSON:
return true
}
return false
}
// Min returns the minimum of v1 and v2. If one of the
// values is NULL, it returns the other value. If both
// are NULL, it returns NULL.
func Min(v1, v2 sqltypes.Value) (sqltypes.Value, error) {
return minmax(v1, v2, true)
}
// Max returns the maximum of v1 and v2. If one of the
// values is NULL, it returns the other value. If both
// are NULL, it returns NULL.
func Max(v1, v2 sqltypes.Value) (sqltypes.Value, error) {
return minmax(v1, v2, false)
}
func minmax(v1, v2 sqltypes.Value, min bool) (sqltypes.Value, error) {
if v1.IsNull() {
return v2, nil
}
if v2.IsNull() {
return v1, nil
}
n, err := NullsafeCompare(v1, v2)
if err != nil {
return sqltypes.NULL, err
}
// XNOR construct. See tests.
v1isSmaller := n < 0
if min == v1isSmaller {
return v1, nil
}
return v2, nil
}
func addNumeric(v1, v2 EvalResult) EvalResult {
v1, v2 = makeNumericAndprioritize(v1, v2)
switch v1.typ {
case sqltypes.Int64:
return intPlusInt(v1.ival, v2.ival)
case sqltypes.Uint64:
switch v2.typ {
case sqltypes.Int64:
return uintPlusInt(v1.uval, v2.ival)
case sqltypes.Uint64:
return uintPlusUint(v1.uval, v2.uval)
}
case sqltypes.Float64:
return floatPlusAny(v1.fval, v2)
}
panic("unreachable")
}
func addNumericWithError(v1, v2 EvalResult) (EvalResult, error) {
v1, v2 = makeNumericAndprioritize(v1, v2)
switch v1.typ {
case sqltypes.Int64:
return intPlusIntWithError(v1.ival, v2.ival)
case sqltypes.Uint64:
switch v2.typ {
case sqltypes.Int64:
return uintPlusIntWithError(v1.uval, v2.ival)
case sqltypes.Uint64:
return uintPlusUintWithError(v1.uval, v2.uval)
}
case sqltypes.Float64:
return floatPlusAny(v1.fval, v2), nil
}
return EvalResult{}, vterrors.Errorf(vtrpcpb.Code_INTERNAL, "invalid arithmetic between: %s %s", v1.Value().String(), v2.Value().String())
}
func subtractNumericWithError(i1, i2 EvalResult) (EvalResult, error) {
v1 := makeNumeric(i1)
v2 := makeNumeric(i2)
switch v1.typ {
case sqltypes.Int64:
switch v2.typ {
case sqltypes.Int64:
return intMinusIntWithError(v1.ival, v2.ival)
case sqltypes.Uint64:
return intMinusUintWithError(v1.ival, v2.uval)
case sqltypes.Float64:
return anyMinusFloat(v1, v2.fval), nil
}
case sqltypes.Uint64:
switch v2.typ {
case sqltypes.Int64:
return uintMinusIntWithError(v1.uval, v2.ival)
case sqltypes.Uint64:
return uintMinusUintWithError(v1.uval, v2.uval)
case sqltypes.Float64:
return anyMinusFloat(v1, v2.fval), nil
}
case sqltypes.Float64:
return floatMinusAny(v1.fval, v2), nil
}
return EvalResult{}, vterrors.Errorf(vtrpcpb.Code_INTERNAL, "invalid arithmetic between: %s %s", v1.Value().String(), v2.Value().String())
}
func multiplyNumericWithError(v1, v2 EvalResult) (EvalResult, error) {
v1, v2 = makeNumericAndprioritize(v1, v2)
switch v1.typ {
case sqltypes.Int64:
return intTimesIntWithError(v1.ival, v2.ival)
case sqltypes.Uint64:
switch v2.typ {
case sqltypes.Int64:
return uintTimesIntWithError(v1.uval, v2.ival)
case sqltypes.Uint64:
return uintTimesUintWithError(v1.uval, v2.uval)
}
case sqltypes.Float64:
return floatTimesAny(v1.fval, v2), nil
}
return EvalResult{}, vterrors.Errorf(vtrpcpb.Code_INTERNAL, "invalid arithmetic between: %s %s", v1.Value().String(), v2.Value().String())
}
func divideNumericWithError(i1, i2 EvalResult) (EvalResult, error) {
v1 := makeNumeric(i1)
v2 := makeNumeric(i2)
switch v1.typ {
case sqltypes.Int64:
return floatDivideAnyWithError(float64(v1.ival), v2)
case sqltypes.Uint64:
return floatDivideAnyWithError(float64(v1.uval), v2)
case sqltypes.Float64:
return floatDivideAnyWithError(v1.fval, v2)
}
return EvalResult{}, vterrors.Errorf(vtrpcpb.Code_INTERNAL, "invalid arithmetic between: %s %s", v1.Value().String(), v2.Value().String())
}
// makeNumericAndprioritize reorders the input parameters
// to be Float64, Uint64, Int64.
func makeNumericAndprioritize(i1, i2 EvalResult) (EvalResult, EvalResult) {
v1 := makeNumeric(i1)
v2 := makeNumeric(i2)
switch v1.typ {
case sqltypes.Int64:
if v2.typ == sqltypes.Uint64 || v2.typ == sqltypes.Float64 {
return v2, v1
}
case sqltypes.Uint64:
if v2.typ == sqltypes.Float64 {
return v2, v1
}
}
return v1, v2
}
func makeNumeric(v EvalResult) EvalResult {
if sqltypes.IsNumber(v.typ) {
return v
}
if ival, err := strconv.ParseInt(string(v.bytes), 10, 64); err == nil {
return EvalResult{ival: ival, typ: sqltypes.Int64}
}
if fval, err := strconv.ParseFloat(string(v.bytes), 64); err == nil {
return EvalResult{fval: fval, typ: sqltypes.Float64}
}
return EvalResult{ival: 0, typ: sqltypes.Int64}
}
func intPlusInt(v1, v2 int64) EvalResult {
result := v1 + v2
if v1 > 0 && v2 > 0 && result < 0 {
goto overflow
}
if v1 < 0 && v2 < 0 && result > 0 {
goto overflow
}
return EvalResult{typ: sqltypes.Int64, ival: result}
overflow:
return EvalResult{typ: sqltypes.Float64, fval: float64(v1) + float64(v2)}
}
func intPlusIntWithError(v1, v2 int64) (EvalResult, error) {
result := v1 + v2
if (result > v1) != (v2 > 0) {
return EvalResult{}, vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.DataOutOfRange, "%s value is out of range in %v + %v", "BIGINT", v1, v2)
}
return EvalResult{typ: sqltypes.Int64, ival: result}, nil
}
func intMinusIntWithError(v1, v2 int64) (EvalResult, error) {
result := v1 - v2
if (result < v1) != (v2 > 0) {
return EvalResult{}, vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.DataOutOfRange, "%s value is out of range in %v - %v", "BIGINT", v1, v2)
}
return EvalResult{typ: sqltypes.Int64, ival: result}, nil
}
func intTimesIntWithError(v1, v2 int64) (EvalResult, error) {
result := v1 * v2
if v1 != 0 && result/v1 != v2 {
return EvalResult{}, vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.DataOutOfRange, "%s value is out of range in %v * %v", "BIGINT", v1, v2)
}
return EvalResult{typ: sqltypes.Int64, ival: result}, nil
}
func intMinusUintWithError(v1 int64, v2 uint64) (EvalResult, error) {
if v1 < 0 || v1 < int64(v2) {
return EvalResult{}, vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.DataOutOfRange, "%s value is out of range in %v - %v", "BIGINT UNSIGNED", v1, v2)
}
return uintMinusUintWithError(uint64(v1), v2)
}
func uintPlusInt(v1 uint64, v2 int64) EvalResult {
return uintPlusUint(v1, uint64(v2))
}
func uintPlusIntWithError(v1 uint64, v2 int64) (EvalResult, error) {
if v2 < 0 && v1 < uint64(v2) {
return EvalResult{}, vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.DataOutOfRange, "%s value is out of range in %v + %v", "BIGINT UNSIGNED", v1, v2)
}
// convert to int -> uint is because for numeric operators (such as + or -)
// where one of the operands is an unsigned integer, the result is unsigned by default.
return uintPlusUintWithError(v1, uint64(v2))
}
func uintMinusIntWithError(v1 uint64, v2 int64) (EvalResult, error) {
if int64(v1) < v2 && v2 > 0 {
return EvalResult{}, vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.DataOutOfRange, "%s value is out of range in %v - %v", "BIGINT UNSIGNED", v1, v2)
}
// uint - (- int) = uint + int
if v2 < 0 {
return uintPlusIntWithError(v1, -v2)
}
return uintMinusUintWithError(v1, uint64(v2))
}
func uintTimesIntWithError(v1 uint64, v2 int64) (EvalResult, error) {
if v2 < 0 || int64(v1) < 0 {
return EvalResult{}, vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.DataOutOfRange, "%s value is out of range in %v * %v", "BIGINT UNSIGNED", v1, v2)
}
return uintTimesUintWithError(v1, uint64(v2))
}
func uintPlusUint(v1, v2 uint64) EvalResult {
result := v1 + v2
if result < v2 {
return EvalResult{typ: sqltypes.Float64, fval: float64(v1) + float64(v2)}
}
return EvalResult{typ: sqltypes.Uint64, uval: result}
}
func uintPlusUintWithError(v1, v2 uint64) (EvalResult, error) {
result := v1 + v2
if result < v2 {
return EvalResult{}, vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.DataOutOfRange, "%s value is out of range in %v + %v", "BIGINT UNSIGNED", v1, v2)
}
return EvalResult{typ: sqltypes.Uint64, uval: result}, nil
}
func uintMinusUintWithError(v1, v2 uint64) (EvalResult, error) {
result := v1 - v2
if v2 > v1 {
return EvalResult{}, vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.DataOutOfRange, "%s value is out of range in %v - %v", "BIGINT UNSIGNED", v1, v2)
}
return EvalResult{typ: sqltypes.Uint64, uval: result}, nil
}
func uintTimesUintWithError(v1, v2 uint64) (EvalResult, error) {
result := v1 * v2
if result < v2 || result < v1 {
return EvalResult{}, vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.DataOutOfRange, "%s value is out of range in %v * %v", "BIGINT UNSIGNED", v1, v2)
}
return EvalResult{typ: sqltypes.Uint64, uval: result}, nil
}
func floatPlusAny(v1 float64, v2 EvalResult) EvalResult {
switch v2.typ {
case sqltypes.Int64:
v2.fval = float64(v2.ival)
case sqltypes.Uint64:
v2.fval = float64(v2.uval)
}
return EvalResult{typ: sqltypes.Float64, fval: v1 + v2.fval}
}
func floatMinusAny(v1 float64, v2 EvalResult) EvalResult {
switch v2.typ {
case sqltypes.Int64:
v2.fval = float64(v2.ival)
case sqltypes.Uint64:
v2.fval = float64(v2.uval)
}
return EvalResult{typ: sqltypes.Float64, fval: v1 - v2.fval}
}
func floatTimesAny(v1 float64, v2 EvalResult) EvalResult {
switch v2.typ {
case sqltypes.Int64:
v2.fval = float64(v2.ival)
case sqltypes.Uint64:
v2.fval = float64(v2.uval)
}
return EvalResult{typ: sqltypes.Float64, fval: v1 * v2.fval}
}
func floatDivideAnyWithError(v1 float64, v2 EvalResult) (EvalResult, error) {
switch v2.typ {
case sqltypes.Int64:
v2.fval = float64(v2.ival)
case sqltypes.Uint64:
v2.fval = float64(v2.uval)
}
result := v1 / v2.fval
divisorLessThanOne := v2.fval < 1
resultMismatch := v2.fval*result != v1
if divisorLessThanOne && resultMismatch {
return EvalResult{}, vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.DataOutOfRange, "%s value is out of range in %v / %v", "BIGINT", v1, v2.fval)
}
return EvalResult{typ: sqltypes.Float64, fval: v1 / v2.fval}, nil
}
func anyMinusFloat(v1 EvalResult, v2 float64) EvalResult {
switch v1.typ {
case sqltypes.Int64:
v1.fval = float64(v1.ival)
case sqltypes.Uint64:
v1.fval = float64(v1.uval)
}
return EvalResult{typ: sqltypes.Float64, fval: v1.fval - v2}
}