-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
eval.go
465 lines (433 loc) · 13.3 KB
/
eval.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
/*
Copyright 2023 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 (
"strconv"
"time"
"unicode/utf8"
"vitess.io/vitess/go/mysql/collations"
"vitess.io/vitess/go/mysql/decimal"
"vitess.io/vitess/go/mysql/fastparse"
"vitess.io/vitess/go/mysql/format"
"vitess.io/vitess/go/mysql/json"
"vitess.io/vitess/go/sqltypes"
vtrpcpb "vitess.io/vitess/go/vt/proto/vtrpc"
"vitess.io/vitess/go/vt/vterrors"
"vitess.io/vitess/go/vt/vthash"
)
type typeFlag uint16
const (
// flagNull marks that this value is null; implies flagNullable
flagNull typeFlag = 1 << 0
// flagNullable marks that this value CAN be null
flagNullable typeFlag = 1 << 1
// flagIsBoolean marks that this value should be interpreted as boolean
flagIsBoolean typeFlag = 1 << 2
// flagIntegerUdf marks that this value is math.MinInt64, and will underflow if negated
flagIntegerUdf typeFlag = 1 << 5
// flagIntegerCap marks that this value is (-math.MinInt64),
// and should be promoted to flagIntegerUdf if negated
flagIntegerCap typeFlag = 1 << 6
// flagIntegerOvf marks that this value will overflow if negated
flagIntegerOvf typeFlag = 1 << 7
// flagHex marks that this value originated from a hex literal
flagHex typeFlag = 1 << 8
// flagBit marks that this value originated from a bit literal
flagBit typeFlag = 1 << 9
// flagExplicitCollation marks that this value has an explicit collation
flagExplicitCollation typeFlag = 1 << 10
// flagAmbiguousType marks that the type of this value depends on the value at runtime
// and cannot be computed accurately
flagAmbiguousType typeFlag = 1 << 11
// flagIntegerRange are the flags that mark overflow/underflow in integers
flagIntegerRange = flagIntegerOvf | flagIntegerCap | flagIntegerUdf
)
func (f typeFlag) Nullable() bool {
return f&flagNullable != 0 || f&flagNull != 0
}
type eval interface {
ToRawBytes() []byte
SQLType() sqltypes.Type
Size() int32
Scale() int32
}
type hashable interface {
eval
Hash(h *vthash.Hasher)
}
func evalToSQLValue(e eval) sqltypes.Value {
if e == nil {
return sqltypes.NULL
}
return sqltypes.MakeTrusted(e.SQLType(), e.ToRawBytes())
}
func evalToSQLValueWithType(e eval, resultType Type) sqltypes.Value {
tt := resultType.Type()
switch {
case sqltypes.IsSigned(tt):
switch e := e.(type) {
case *evalInt64:
return sqltypes.MakeTrusted(tt, strconv.AppendInt(nil, e.i, 10))
case *evalUint64:
return sqltypes.MakeTrusted(tt, strconv.AppendUint(nil, e.u, 10))
case *evalFloat:
return sqltypes.MakeTrusted(tt, strconv.AppendInt(nil, int64(e.f), 10))
}
case sqltypes.IsUnsigned(tt):
switch e := e.(type) {
case *evalInt64:
return sqltypes.MakeTrusted(tt, strconv.AppendUint(nil, uint64(e.i), 10))
case *evalUint64:
return sqltypes.MakeTrusted(tt, strconv.AppendUint(nil, e.u, 10))
case *evalFloat:
return sqltypes.MakeTrusted(tt, strconv.AppendUint(nil, uint64(e.f), 10))
}
case sqltypes.IsFloat(tt):
switch e := e.(type) {
case *evalInt64:
return sqltypes.MakeTrusted(tt, strconv.AppendInt(nil, e.i, 10))
case *evalUint64:
return sqltypes.MakeTrusted(tt, strconv.AppendUint(nil, e.u, 10))
case *evalFloat:
return sqltypes.MakeTrusted(tt, format.FormatFloat(e.f))
case *evalDecimal:
return sqltypes.MakeTrusted(tt, e.dec.FormatMySQL(e.length))
}
case sqltypes.IsDecimal(tt):
if numeric, ok := e.(evalNumeric); ok {
dec := numeric.toDecimal(resultType.size, resultType.scale)
return sqltypes.MakeTrusted(tt, dec.dec.FormatMySQL(dec.length))
}
case e != nil:
return sqltypes.MakeTrusted(tt, e.ToRawBytes())
}
return sqltypes.NULL
}
func evalIsTruthy(e eval) boolean {
if e == nil {
return boolNULL
}
switch e := e.(type) {
case *evalInt64:
return makeboolean(e.i != 0)
case *evalUint64:
return makeboolean(e.u != 0)
case *evalFloat:
return makeboolean(e.f != 0.0)
case *evalDecimal:
return makeboolean(!e.dec.IsZero())
case *evalBytes:
if e.isHexLiteral() {
hex, ok := e.toNumericHex()
if !ok {
// overflow
return makeboolean(true)
}
return makeboolean(hex.u != 0)
}
if e.isBitLiteral() {
bit, ok := e.toNumericBit()
if !ok {
// overflow
return makeboolean(true)
}
return makeboolean(bit.i != 0)
}
f, _ := fastparse.ParseFloat64(e.string())
return makeboolean(f != 0.0)
case *evalJSON:
return makeboolean(e.ToBoolean())
case *evalTemporal:
return makeboolean(!e.isZero())
default:
panic("unhandled case: evalIsTruthy")
}
}
func evalCoerce(e eval, typ sqltypes.Type, size, scale int32, col collations.ID, now time.Time, allowZero bool) (eval, error) {
if e == nil {
return nil, nil
}
if col == collations.Unknown {
panic("EvalResult.coerce with no collation")
}
if typ == sqltypes.VarChar || typ == sqltypes.Char {
// if we have an explicit VARCHAR coercion, always force it so the collation is replaced in the target
return evalToVarchar(e, col, false)
}
if e.SQLType() == typ && e.Size() == size && e.Scale() == scale {
// nothing to be done here
return e, nil
}
switch typ {
case sqltypes.Null:
return nil, nil
case sqltypes.Binary, sqltypes.VarBinary:
return evalToBinary(e), nil
case sqltypes.Char, sqltypes.VarChar:
panic("unreacheable")
case sqltypes.Decimal:
return evalToDecimal(e, 0, 0), nil
case sqltypes.Float32, sqltypes.Float64:
f, _ := evalToFloat(e)
return f, nil
case sqltypes.Int8, sqltypes.Int16, sqltypes.Int32, sqltypes.Int64:
return evalToInt64(e), nil
case sqltypes.Uint8, sqltypes.Uint16, sqltypes.Uint32, sqltypes.Uint64:
return evalToInt64(e).toUint64(), nil
case sqltypes.Date:
return evalToDate(e, now, allowZero), nil
case sqltypes.Datetime, sqltypes.Timestamp:
return evalToDateTime(e, int(size), now, allowZero), nil
case sqltypes.Time:
return evalToTime(e, int(size)), nil
default:
return nil, vterrors.Errorf(vtrpcpb.Code_UNIMPLEMENTED, "Unsupported type conversion: %s", typ.String())
}
}
func valueToEvalCast(v sqltypes.Value, typ sqltypes.Type, collation collations.ID, values *EnumSetValues, sqlmode SQLMode) (eval, error) {
switch {
case typ == sqltypes.Null:
return nil, nil
case sqltypes.IsFloat(typ):
switch {
case v.IsSigned():
ival, err := v.ToInt64()
return newEvalFloat(float64(ival)), err
case v.IsUnsigned():
uval, err := v.ToUint64()
return newEvalFloat(float64(uval)), err
case v.IsFloat() || v.IsDecimal():
fval, err := v.ToFloat64()
return newEvalFloat(fval), err
case v.IsText() || v.IsBinary():
fval, _ := fastparse.ParseFloat64(v.RawStr())
return newEvalFloat(fval), nil
default:
e, err := valueToEval(v, typedCoercionCollation(v.Type(), collation), values)
if err != nil {
return nil, err
}
f, _ := evalToFloat(e)
return f, nil
}
case sqltypes.IsDecimal(typ):
var dec decimal.Decimal
switch {
case v.IsIntegral() || v.IsDecimal():
var err error
dec, err = decimal.NewFromMySQL(v.Raw())
if err != nil {
return nil, err
}
case v.IsFloat():
fval, err := v.ToFloat64()
if err != nil {
return nil, err
}
dec = decimal.NewFromFloat(fval)
case v.IsText() || v.IsBinary():
fval, _ := fastparse.ParseFloat64(v.RawStr())
dec = decimal.NewFromFloat(fval)
default:
e, err := valueToEval(v, typedCoercionCollation(v.Type(), collation), values)
if err != nil {
return nil, err
}
return evalToDecimal(e, 0, 0), nil
}
return &evalDecimal{dec: dec, length: -dec.Exponent()}, nil
case sqltypes.IsSigned(typ):
switch {
case v.IsSigned():
ival, err := v.ToInt64()
return newEvalInt64(ival), err
case v.IsUnsigned():
uval, err := v.ToUint64()
return newEvalInt64(int64(uval)), err
case v.IsText() || v.IsBinary():
i, err := fastparse.ParseInt64(v.RawStr(), 10)
return newEvalInt64(i), err
default:
e, err := valueToEval(v, typedCoercionCollation(v.Type(), collation), values)
if err != nil {
return nil, err
}
return evalToInt64(e), nil
}
case sqltypes.IsUnsigned(typ):
switch {
case v.IsSigned():
ival, err := v.ToInt64()
return newEvalUint64(uint64(ival)), err
case v.IsUnsigned():
uval, err := v.ToUint64()
return newEvalUint64(uval), err
case v.IsText() || v.IsBinary():
u, err := fastparse.ParseUint64(v.RawStr(), 10)
return newEvalUint64(u), err
default:
e, err := valueToEval(v, typedCoercionCollation(v.Type(), collation), values)
if err != nil {
return nil, err
}
i := evalToInt64(e)
return newEvalUint64(uint64(i.i)), nil
}
case sqltypes.IsTextOrBinary(typ):
switch {
case v.IsText() || v.IsBinary():
return newEvalRaw(v.Type(), v.Raw(), typedCoercionCollation(v.Type(), collation)), nil
case sqltypes.IsText(typ):
e, err := valueToEval(v, typedCoercionCollation(v.Type(), collation), values)
if err != nil {
return nil, err
}
return evalToVarchar(e, collation, true)
default:
e, err := valueToEval(v, typedCoercionCollation(v.Type(), collation), values)
if err != nil {
return nil, err
}
return evalToBinary(e), nil
}
case typ == sqltypes.TypeJSON:
return json.NewFromSQL(v)
case typ == sqltypes.Date:
e, err := valueToEval(v, typedCoercionCollation(v.Type(), collation), values)
if err != nil {
return nil, err
}
// Separate return here to avoid nil wrapped in interface type
d := evalToDate(e, time.Now(), sqlmode.AllowZeroDate())
if d == nil {
return nil, nil
}
return d, nil
case typ == sqltypes.Datetime || typ == sqltypes.Timestamp:
e, err := valueToEval(v, typedCoercionCollation(v.Type(), collation), values)
if err != nil {
return nil, err
}
// Separate return here to avoid nil wrapped in interface type
dt := evalToDateTime(e, -1, time.Now(), sqlmode.AllowZeroDate())
if dt == nil {
return nil, nil
}
return dt, nil
case typ == sqltypes.Time:
e, err := valueToEval(v, typedCoercionCollation(v.Type(), collation), values)
if err != nil {
return nil, err
}
// Separate return here to avoid nil wrapped in interface type
t := evalToTime(e, -1)
if t == nil {
return nil, nil
}
return t, nil
case typ == sqltypes.Enum:
return newEvalEnum(v.Raw(), values), nil
case typ == sqltypes.Set:
return newEvalSet(v.Raw(), values), nil
}
return nil, vterrors.Errorf(vtrpcpb.Code_INTERNAL, "coercion should not try to coerce this value: %v", v)
}
func valueToEval(value sqltypes.Value, collation collations.TypedCollation, values *EnumSetValues) (eval, error) {
wrap := func(err error) error {
if err == nil {
return nil
}
return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", err)
}
switch tt := value.Type(); {
case sqltypes.IsSigned(tt):
ival, err := value.ToInt64()
return newEvalInt64(ival), wrap(err)
case sqltypes.IsUnsigned(tt):
uval, err := value.ToUint64()
return newEvalUint64(uval), wrap(err)
case sqltypes.IsFloat(tt):
fval, err := value.ToFloat64()
return newEvalFloat(fval), wrap(err)
case tt == sqltypes.Decimal:
dec, err := decimal.NewFromMySQL(value.Raw())
return newEvalDecimal(dec, 0, 0), wrap(err)
case tt == sqltypes.Enum:
return newEvalEnum(value.Raw(), values), nil
case tt == sqltypes.Set:
return newEvalSet(value.Raw(), values), nil
case sqltypes.IsText(tt):
if tt == sqltypes.HexNum {
raw, err := parseHexNumber(value.Raw())
return newEvalBytesHex(raw), wrap(err)
} else if tt == sqltypes.HexVal {
hex := value.Raw()
raw, err := parseHexLiteral(hex[2 : len(hex)-1])
return newEvalBytesHex(raw), wrap(err)
} else if tt == sqltypes.BitNum {
raw, err := parseBitNum(value.Raw())
return newEvalBytesBit(raw), wrap(err)
} else {
return newEvalText(value.Raw(), collation), nil
}
case sqltypes.IsBinary(tt):
return newEvalBinary(value.Raw()), nil
case tt == sqltypes.Date:
return parseDate(value.Raw())
case tt == sqltypes.Datetime || tt == sqltypes.Timestamp:
return parseDateTime(value.Raw())
case tt == sqltypes.Time:
return parseTime(value.Raw())
case sqltypes.IsNull(tt):
return nil, nil
case tt == sqltypes.TypeJSON:
var p json.Parser
j, err := p.ParseBytes(value.Raw())
return j, wrap(err)
case fallbackBinary(tt):
return newEvalRaw(tt, value.Raw(), collation), nil
default:
return nil, vterrors.Errorf(vtrpcpb.Code_INTERNAL, "Type is not supported: %q %s", value, value.Type())
}
}
const hexchars = "0123456789ABCDEF"
func sanitizeErrorValue(s []byte) []byte {
var buf []byte
for width := 0; len(s) > 0; s = s[width:] {
r := rune(s[0])
width = 1
if r >= utf8.RuneSelf {
r, width = utf8.DecodeLastRune(s)
}
if width == 1 && r == utf8.RuneError {
buf = append(buf, `\x`...)
buf = append(buf, hexchars[s[0]>>4])
buf = append(buf, hexchars[s[0]&0xF])
continue
}
if strconv.IsPrint(r) {
if r < utf8.RuneSelf {
buf = append(buf, byte(r))
} else {
b := [utf8.UTFMax]byte{}
n := utf8.EncodeRune(b[:], r)
buf = append(buf, b[:n]...)
}
continue
}
buf = append(buf, `\x`...)
buf = append(buf, hexchars[s[0]>>4])
buf = append(buf, hexchars[s[0]&0xF])
}
return buf
}