-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
value.go
665 lines (585 loc) · 17.5 KB
/
value.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
/*
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 sqltypes implements interfaces and types that represent SQL values.
package sqltypes
import (
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"math/big"
"strconv"
"strings"
"vitess.io/vitess/go/bytes2"
"vitess.io/vitess/go/hack"
querypb "vitess.io/vitess/go/vt/proto/query"
"vitess.io/vitess/go/vt/proto/vtrpc"
vtrpcpb "vitess.io/vitess/go/vt/proto/vtrpc"
"vitess.io/vitess/go/vt/vterrors"
)
var (
// NULL represents the NULL value.
NULL = Value{}
// DontEscape tells you if a character should not be escaped.
DontEscape = byte(255)
nullstr = []byte("null")
// ErrIncompatibleTypeCast indicates a casting problem
ErrIncompatibleTypeCast = errors.New("Cannot convert value to desired type")
)
type (
// BinWriter interface is used for encoding values.
// Types like bytes.Buffer conform to this interface.
// We expect the writer objects to be in-memory buffers.
// So, we don't expect the write operations to fail.
BinWriter interface {
Write([]byte) (int, error)
}
// Value can store any SQL value. If the value represents
// an integral type, the bytes are always stored as a canonical
// representation that matches how MySQL returns such values.
Value struct {
typ querypb.Type
val []byte
}
Row = []Value
)
// NewValue builds a Value using typ and val. If the value and typ
// don't match, it returns an error.
func NewValue(typ querypb.Type, val []byte) (v Value, err error) {
switch {
case IsSigned(typ):
if _, err := strconv.ParseInt(string(val), 10, 64); err != nil {
return NULL, err
}
return MakeTrusted(typ, val), nil
case IsUnsigned(typ):
if _, err := strconv.ParseUint(string(val), 10, 64); err != nil {
return NULL, err
}
return MakeTrusted(typ, val), nil
case IsFloat(typ) || typ == Decimal:
if _, err := strconv.ParseFloat(string(val), 64); err != nil {
return NULL, err
}
return MakeTrusted(typ, val), nil
case IsQuoted(typ) || typ == Bit || typ == HexNum || typ == HexVal || typ == Null || typ == BitNum:
return MakeTrusted(typ, val), nil
}
// All other types are unsafe or invalid.
return NULL, fmt.Errorf("invalid type specified for MakeValue: %v", typ)
}
// MakeTrusted makes a new Value based on the type.
// This function should only be used if you know the value
// and type conform to the rules. Every place this function is
// called, a comment is needed that explains why it's justified.
// Exceptions: The current package and mysql package do not need
// comments. Other packages can also use the function to create
// VarBinary or VarChar values.
func MakeTrusted(typ querypb.Type, val []byte) Value {
if typ == Null {
return NULL
}
return Value{typ: typ, val: val}
}
// NewHexNum builds an Hex Value.
func NewHexNum(v []byte) Value {
return MakeTrusted(HexNum, v)
}
// NewHexVal builds a HexVal Value.
func NewHexVal(v []byte) Value {
return MakeTrusted(HexVal, v)
}
// NewBitNum builds a BitNum Value.
func NewBitNum(v []byte) Value {
return MakeTrusted(BitNum, v)
}
// NewInt64 builds an Int64 Value.
func NewInt64(v int64) Value {
return MakeTrusted(Int64, strconv.AppendInt(nil, v, 10))
}
// NewInt8 builds an Int8 Value.
func NewInt8(v int8) Value {
return MakeTrusted(Int8, strconv.AppendInt(nil, int64(v), 10))
}
// NewInt32 builds an Int64 Value.
func NewInt32(v int32) Value {
return MakeTrusted(Int32, strconv.AppendInt(nil, int64(v), 10))
}
// NewUint64 builds an Uint64 Value.
func NewUint64(v uint64) Value {
return MakeTrusted(Uint64, strconv.AppendUint(nil, v, 10))
}
// NewUint32 builds an Uint32 Value.
func NewUint32(v uint32) Value {
return MakeTrusted(Uint32, strconv.AppendUint(nil, uint64(v), 10))
}
// NewFloat64 builds an Float64 Value.
func NewFloat64(v float64) Value {
return MakeTrusted(Float64, strconv.AppendFloat(nil, v, 'g', -1, 64))
}
// NewVarChar builds a VarChar Value.
func NewVarChar(v string) Value {
return MakeTrusted(VarChar, []byte(v))
}
// NewVarBinary builds a VarBinary Value.
// The input is a string because it's the most common use case.
func NewVarBinary(v string) Value {
return MakeTrusted(VarBinary, []byte(v))
}
// NewDate builds a Date value.
func NewDate(v string) Value {
return MakeTrusted(Date, []byte(v))
}
// NewTime builds a Time value.
func NewTime(v string) Value {
return MakeTrusted(Time, []byte(v))
}
// NewTimestamp builds a Timestamp value.
func NewTimestamp(v string) Value {
return MakeTrusted(Timestamp, []byte(v))
}
// NewDatetime builds a Datetime value.
func NewDatetime(v string) Value {
return MakeTrusted(Datetime, []byte(v))
}
// NewDecimal builds a Decimal value.
func NewDecimal(v string) Value {
return MakeTrusted(Decimal, []byte(v))
}
// NewIntegral builds an integral type from a string representation.
// The type will be Int64 or Uint64. Int64 will be preferred where possible.
func NewIntegral(val string) (n Value, err error) {
signed, err := strconv.ParseInt(val, 0, 64)
if err == nil {
return MakeTrusted(Int64, strconv.AppendInt(nil, signed, 10)), nil
}
unsigned, err := strconv.ParseUint(val, 0, 64)
if err != nil {
return Value{}, err
}
return MakeTrusted(Uint64, strconv.AppendUint(nil, unsigned, 10)), nil
}
// InterfaceToValue builds a value from a go type.
// Supported types are nil, int64, uint64, float64,
// string and []byte.
// This function is deprecated. Use the type-specific
// functions instead.
func InterfaceToValue(goval any) (Value, error) {
switch goval := goval.(type) {
case nil:
return NULL, nil
case []byte:
return MakeTrusted(VarBinary, goval), nil
case int64:
return NewInt64(goval), nil
case uint64:
return NewUint64(goval), nil
case float64:
return NewFloat64(goval), nil
case string:
return NewVarChar(goval), nil
default:
return NULL, fmt.Errorf("unexpected type %T: %v", goval, goval)
}
}
// Type returns the type of Value.
func (v Value) Type() querypb.Type {
return v.typ
}
// Raw returns the internal representation of the value. For newer types,
// this may not match MySQL's representation.
func (v Value) Raw() []byte {
return v.val
}
// RawStr returns the internal representation of the value as a string instead
// of a byte slice. This is equivalent to calling `string(v.Raw())` but does
// not allocate.
func (v Value) RawStr() string {
return hack.String(v.val)
}
// ToBytes returns the value as MySQL would return it as []byte.
// In contrast, Raw returns the internal representation of the Value, which may not
// match MySQL's representation for hex encoded binary data or newer types.
// If the value is not convertible like in the case of Expression, it returns an error.
func (v Value) ToBytes() ([]byte, error) {
switch v.typ {
case Expression:
return nil, vterrors.New(vtrpcpb.Code_INVALID_ARGUMENT, "expression cannot be converted to bytes")
case HexVal: // TODO: all the decode below have problem when decoding odd number of bytes. This needs to be fixed.
return v.decodeHexVal()
case HexNum:
return v.decodeHexNum()
case BitNum:
return v.decodeBitNum()
default:
return v.val, nil
}
}
// Len returns the length.
func (v Value) Len() int {
return len(v.val)
}
// ToInt64 returns the value as MySQL would return it as a int64.
func (v Value) ToInt64() (int64, error) {
if !v.IsIntegral() {
return 0, ErrIncompatibleTypeCast
}
return strconv.ParseInt(v.RawStr(), 10, 64)
}
// ToFloat64 returns the value as MySQL would return it as a float64.
func (v Value) ToFloat64() (float64, error) {
if !IsNumber(v.typ) {
return 0, ErrIncompatibleTypeCast
}
return strconv.ParseFloat(v.RawStr(), 64)
}
// ToUint64 returns the value as MySQL would return it as a uint64.
func (v Value) ToUint64() (uint64, error) {
if !v.IsIntegral() {
return 0, ErrIncompatibleTypeCast
}
return strconv.ParseUint(v.RawStr(), 10, 64)
}
// ToBool returns the value as a bool value
func (v Value) ToBool() (bool, error) {
i, err := v.ToInt64()
if err != nil {
return false, err
}
switch i {
case 0:
return false, nil
case 1:
return true, nil
}
return false, ErrIncompatibleTypeCast
}
// ToString returns the value as MySQL would return it as string.
// If the value is not convertible like in the case of Expression, it returns nil.
func (v Value) ToString() string {
if v.typ == Expression {
return ""
}
return hack.String(v.val)
}
// String returns a printable version of the value.
func (v Value) String() string {
if v.typ == Null {
return "NULL"
}
if v.IsQuoted() || v.typ == Bit {
return fmt.Sprintf("%v(%q)", v.typ, v.val)
}
return fmt.Sprintf("%v(%s)", v.typ, v.val)
}
// EncodeSQL encodes the value into an SQL statement. Can be binary.
func (v Value) EncodeSQL(b BinWriter) {
switch {
case v.typ == Null:
b.Write(nullstr)
case v.IsQuoted():
encodeBytesSQL(v.val, b)
case v.typ == Bit:
encodeBytesSQLBits(v.val, b)
default:
b.Write(v.val)
}
}
// EncodeSQLStringBuilder is identical to EncodeSQL but it takes a strings.Builder
// as its writer, so it can be inlined for performance.
func (v Value) EncodeSQLStringBuilder(b *strings.Builder) {
switch {
case v.typ == Null:
b.Write(nullstr)
case v.IsQuoted():
encodeBytesSQLStringBuilder(v.val, b)
case v.typ == Bit:
encodeBytesSQLBits(v.val, b)
default:
b.Write(v.val)
}
}
// EncodeSQLBytes2 is identical to EncodeSQL but it takes a bytes2.Buffer
// as its writer, so it can be inlined for performance.
func (v Value) EncodeSQLBytes2(b *bytes2.Buffer) {
switch {
case v.typ == Null:
b.Write(nullstr)
case v.IsQuoted():
encodeBytesSQLBytes2(v.val, b)
case v.typ == Bit:
encodeBytesSQLBits(v.val, b)
default:
b.Write(v.val)
}
}
// EncodeASCII encodes the value using 7-bit clean ascii bytes.
func (v Value) EncodeASCII(b BinWriter) {
switch {
case v.typ == Null:
b.Write(nullstr)
case v.IsQuoted() || v.typ == Bit:
encodeBytesASCII(v.val, b)
default:
b.Write(v.val)
}
}
// IsNull returns true if Value is null.
func (v Value) IsNull() bool {
return v.typ == Null
}
// IsIntegral returns true if Value is an integral.
func (v Value) IsIntegral() bool {
return IsIntegral(v.typ)
}
// IsSigned returns true if Value is a signed integral.
func (v Value) IsSigned() bool {
return IsSigned(v.typ)
}
// IsUnsigned returns true if Value is an unsigned integral.
func (v Value) IsUnsigned() bool {
return IsUnsigned(v.typ)
}
// IsFloat returns true if Value is a float.
func (v Value) IsFloat() bool {
return IsFloat(v.typ)
}
// IsQuoted returns true if Value must be SQL-quoted.
func (v Value) IsQuoted() bool {
return IsQuoted(v.typ)
}
// IsText returns true if Value is a collatable text.
func (v Value) IsText() bool {
return IsText(v.typ)
}
// IsBinary returns true if Value is binary.
func (v Value) IsBinary() bool {
return IsBinary(v.typ)
}
// IsDateTime returns true if Value is datetime.
func (v Value) IsDateTime() bool {
dt := int(querypb.Type_DATETIME)
return int(v.typ)&dt == dt
}
// IsComparable returns true if the Value is null safe comparable without collation information.
func (v *Value) IsComparable() bool {
if v.typ == Null || IsNumber(v.typ) || IsBinary(v.typ) {
return true
}
switch v.typ {
case Timestamp, Date, Time, Datetime, Enum, Set, TypeJSON, Bit:
return true
}
return false
}
// MarshalJSON should only be used for testing.
// It's not a complete implementation.
func (v Value) MarshalJSON() ([]byte, error) {
switch {
case v.IsQuoted() || v.typ == Bit:
return json.Marshal(v.ToString())
case v.typ == Null:
return nullstr, nil
}
return v.val, nil
}
// UnmarshalJSON should only be used for testing.
// It's not a complete implementation.
func (v *Value) UnmarshalJSON(b []byte) error {
if len(b) == 0 {
return fmt.Errorf("error unmarshaling empty bytes")
}
var val any
var err error
switch b[0] {
case '-':
var ival int64
err = json.Unmarshal(b, &ival)
val = ival
case '"':
var bval []byte
err = json.Unmarshal(b, &bval)
val = bval
case 'n': // null
err = json.Unmarshal(b, &val)
default:
var uval uint64
err = json.Unmarshal(b, &uval)
val = uval
}
if err != nil {
return err
}
*v, err = InterfaceToValue(val)
return err
}
// decodeHexVal decodes the SQL hex value of the form x'A1' into a byte
// array matching what MySQL would return when querying the column where
// an INSERT was performed with x'A1' having been specified as a value
func (v *Value) decodeHexVal() ([]byte, error) {
if len(v.val) < 3 || (v.val[0] != 'x' && v.val[0] != 'X') || v.val[1] != '\'' || v.val[len(v.val)-1] != '\'' {
return nil, vterrors.Errorf(vtrpc.Code_INVALID_ARGUMENT, "invalid hex value: %v", v.val)
}
hexBytes := v.val[2 : len(v.val)-1]
decodedHexBytes, err := hex.DecodeString(string(hexBytes))
if err != nil {
return nil, err
}
return decodedHexBytes, nil
}
// decodeHexNum decodes the SQL hex value of the form 0xA1 into a byte
// array matching what MySQL would return when querying the column where
// an INSERT was performed with 0xA1 having been specified as a value
func (v *Value) decodeHexNum() ([]byte, error) {
if len(v.val) < 3 || v.val[0] != '0' || v.val[1] != 'x' {
return nil, vterrors.Errorf(vtrpc.Code_INVALID_ARGUMENT, "invalid hex number: %v", v.val)
}
hexBytes := v.val[2:]
decodedHexBytes, err := hex.DecodeString(string(hexBytes))
if err != nil {
return nil, err
}
return decodedHexBytes, nil
}
// decodeBitNum decodes the SQL bit value of the form 0b101 into a byte
// array matching what MySQL would return when querying the column where
// an INSERT was performed with 0x5 having been specified as a value
func (v *Value) decodeBitNum() ([]byte, error) {
if len(v.val) < 3 || v.val[0] != '0' || v.val[1] != 'b' {
return nil, vterrors.Errorf(vtrpc.Code_INVALID_ARGUMENT, "invalid bit number: %v", v.val)
}
var i big.Int
_, ok := i.SetString(string(v.val), 0)
if !ok {
return nil, vterrors.Errorf(vtrpc.Code_INVALID_ARGUMENT, "invalid bit number: %v", v.val)
}
return i.Bytes(), nil
}
func encodeBytesSQL(val []byte, b BinWriter) {
buf := &bytes2.Buffer{}
encodeBytesSQLBytes2(val, buf)
b.Write(buf.Bytes())
}
func encodeBytesSQLBytes2(val []byte, buf *bytes2.Buffer) {
buf.WriteByte('\'')
for idx, ch := range val {
// If \% or \_ is present, we want to keep them as is, and don't want to escape \ again
if ch == '\\' && idx+1 < len(val) && (val[idx+1] == '%' || val[idx+1] == '_') {
buf.WriteByte(ch)
continue
}
if encodedChar := SQLEncodeMap[ch]; encodedChar == DontEscape {
buf.WriteByte(ch)
} else {
buf.WriteByte('\\')
buf.WriteByte(encodedChar)
}
}
buf.WriteByte('\'')
}
func encodeBytesSQLStringBuilder(val []byte, buf *strings.Builder) {
buf.WriteByte('\'')
for idx, ch := range val {
// If \% or \_ is present, we want to keep them as is, and don't want to escape \ again
if ch == '\\' && idx+1 < len(val) && (val[idx+1] == '%' || val[idx+1] == '_') {
buf.WriteByte(ch)
continue
}
if encodedChar := SQLEncodeMap[ch]; encodedChar == DontEscape {
buf.WriteByte(ch)
} else {
buf.WriteByte('\\')
buf.WriteByte(encodedChar)
}
}
buf.WriteByte('\'')
}
// BufEncodeStringSQL encodes the string into a strings.Builder
func BufEncodeStringSQL(buf *strings.Builder, val string) {
buf.WriteByte('\'')
for idx, ch := range val {
if ch > 255 {
buf.WriteRune(ch)
continue
}
// If \% or \_ is present, we want to keep them as is, and don't want to escape \ again
if ch == '\\' && idx+1 < len(val) && (val[idx+1] == '%' || val[idx+1] == '_') {
buf.WriteRune(ch)
continue
}
if encodedChar := SQLEncodeMap[ch]; encodedChar == DontEscape {
buf.WriteRune(ch)
} else {
buf.WriteByte('\\')
buf.WriteByte(encodedChar)
}
}
buf.WriteByte('\'')
}
// EncodeStringSQL encodes the string as a SQL string.
func EncodeStringSQL(val string) string {
var buf strings.Builder
BufEncodeStringSQL(&buf, val)
return buf.String()
}
func encodeBytesSQLBits(val []byte, b BinWriter) {
fmt.Fprint(b, "b'")
for _, ch := range val {
fmt.Fprintf(b, "%08b", ch)
}
fmt.Fprint(b, "'")
}
func encodeBytesASCII(val []byte, b BinWriter) {
buf := &bytes2.Buffer{}
buf.WriteByte('\'')
encoder := base64.NewEncoder(base64.StdEncoding, buf)
encoder.Write(val)
encoder.Close()
buf.WriteByte('\'')
b.Write(buf.Bytes())
}
// SQLEncodeMap specifies how to escape binary data with '\'.
// Complies to https://dev.mysql.com/doc/refman/5.7/en/string-literals.html
// Handling escaping of % and _ is different than other characters.
// When escaped in a like clause, they are supposed to be treated as literals
// Everywhere else, they evaluate to strings '\%' and '\_' respectively.
// In Vitess, the way we are choosing to handle this behaviour is to always
// preserve the escaping of % and _ as is in all the places and handle it like MySQL
// in our evaluation engine for Like.
var SQLEncodeMap [256]byte
// SQLDecodeMap is the reverse of SQLEncodeMap
var SQLDecodeMap [256]byte
var encodeRef = map[byte]byte{
'\x00': '0',
'\'': '\'',
'"': '"',
'\b': 'b',
'\n': 'n',
'\r': 'r',
'\t': 't',
26: 'Z', // ctl-Z
'\\': '\\',
}
func init() {
for i := range SQLEncodeMap {
SQLEncodeMap[i] = DontEscape
SQLDecodeMap[i] = DontEscape
}
for i := range SQLEncodeMap {
if to, ok := encodeRef[byte(i)]; ok {
SQLEncodeMap[byte(i)] = to
SQLDecodeMap[to] = byte(i)
}
}
}