forked from dinedal/textql
/
sqltypes.go
378 lines (334 loc) · 8.46 KB
/
sqltypes.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
// Copyright 2012, Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package sqltypes implements interfaces and types that represent SQL values.
package sqltypes
import (
"encoding/base64"
"encoding/gob"
"encoding/json"
"fmt"
"reflect"
"strconv"
"time"
"unsafe"
)
var (
NULL = Value{}
DONTESCAPE = byte(255)
nullstr = []byte("null")
)
// 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.
type BinWriter interface {
Write([]byte) (int, error)
WriteByte(byte) error
}
// Value can store any SQL value. NULL is stored as nil.
type Value struct {
Inner InnerValue
}
// Numeric represents non-fractional SQL number.
type Numeric []byte
// Fractional represents fractional types like float and decimal
// It's functionally equivalent to Numeric other than how it's constructed
type Fractional []byte
// String represents any SQL type that needs to be represented using quotes.
type String []byte
// MakeNumeric makes a Numeric from a []byte without validation.
func MakeNumeric(b []byte) Value {
return Value{Numeric(b)}
}
// MakeFractional makes a Fractional value from a []byte without validation.
func MakeFractional(b []byte) Value {
return Value{Fractional(b)}
}
// MakeString makes a String value from a []byte.
func MakeString(b []byte) Value {
return Value{String(b)}
}
// Raw returns the raw bytes. All types are currently implemented as []byte.
func (v Value) Raw() []byte {
if v.Inner == nil {
return nil
}
return v.Inner.raw()
}
// String returns the raw value as a string
func (v Value) String() string {
if v.Inner == nil {
return ""
}
return toString(v.Inner.raw())
}
// String force casts a []byte to a string.
// USE AT YOUR OWN RISK
func toString(b []byte) (s string) {
if len(b) == 0 {
return ""
}
pbytes := (*reflect.SliceHeader)(unsafe.Pointer(&b))
pstring := (*reflect.StringHeader)(unsafe.Pointer(&s))
pstring.Data = pbytes.Data
pstring.Len = pbytes.Len
return
}
// ParseInt64 will parse a Numeric value into an int64
func (v Value) ParseInt64() (val int64, err error) {
if v.Inner == nil {
return 0, fmt.Errorf("value is null")
}
n, ok := v.Inner.(Numeric)
if !ok {
return 0, fmt.Errorf("value is not Numeric")
}
return strconv.ParseInt(string(n.raw()), 10, 64)
}
// ParseUint64 will parse a Numeric value into a uint64
func (v Value) ParseUint64() (val uint64, err error) {
if v.Inner == nil {
return 0, fmt.Errorf("value is null")
}
n, ok := v.Inner.(Numeric)
if !ok {
return 0, fmt.Errorf("value is not Numeric")
}
return strconv.ParseUint(string(n.raw()), 10, 64)
}
// ParseFloat64 will parse a Fractional value into an float64
func (v Value) ParseFloat64() (val float64, err error) {
if v.Inner == nil {
return 0, fmt.Errorf("value is null")
}
n, ok := v.Inner.(Fractional)
if !ok {
return 0, fmt.Errorf("value is not Fractional")
}
return strconv.ParseFloat(string(n.raw()), 64)
}
// EncodeSql encodes the value into an SQL statement. Can be binary.
func (v Value) EncodeSql(b BinWriter) {
if v.Inner == nil {
if _, err := b.Write(nullstr); err != nil {
panic(err)
}
} else {
v.Inner.encodeSql(b)
}
}
// EncodeAscii encodes the value using 7-bit clean ascii bytes.
func (v Value) EncodeAscii(b BinWriter) {
if v.Inner == nil {
if _, err := b.Write(nullstr); err != nil {
panic(err)
}
} else {
v.Inner.encodeAscii(b)
}
}
func (v Value) IsNull() bool {
return v.Inner == nil
}
func (v Value) IsNumeric() (ok bool) {
if v.Inner != nil {
_, ok = v.Inner.(Numeric)
}
return ok
}
func (v Value) IsFractional() (ok bool) {
if v.Inner != nil {
_, ok = v.Inner.(Fractional)
}
return ok
}
func (v Value) IsString() (ok bool) {
if v.Inner != nil {
_, ok = v.Inner.(String)
}
return ok
}
// MarshalJSON should only be used for testing.
// It's not a complete implementation.
func (v Value) MarshalJSON() ([]byte, error) {
return json.Marshal(v.Inner)
}
// 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 interface{}
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 = BuildValue(val)
return err
}
// InnerValue defines methods that need to be supported by all non-null value types.
type InnerValue interface {
raw() []byte
encodeSql(BinWriter)
encodeAscii(BinWriter)
}
func BuildValue(goval interface{}) (v Value, err error) {
switch bindVal := goval.(type) {
case nil:
// no op
case int:
v = Value{Numeric(strconv.AppendInt(nil, int64(bindVal), 10))}
case int32:
v = Value{Numeric(strconv.AppendInt(nil, int64(bindVal), 10))}
case int64:
v = Value{Numeric(strconv.AppendInt(nil, int64(bindVal), 10))}
case uint:
v = Value{Numeric(strconv.AppendUint(nil, uint64(bindVal), 10))}
case uint32:
v = Value{Numeric(strconv.AppendUint(nil, uint64(bindVal), 10))}
case uint64:
v = Value{Numeric(strconv.AppendUint(nil, uint64(bindVal), 10))}
case float64:
v = Value{Fractional(strconv.AppendFloat(nil, bindVal, 'f', -1, 64))}
case string:
v = Value{String([]byte(bindVal))}
case []byte:
v = Value{String(bindVal)}
case time.Time:
v = Value{String([]byte(bindVal.Format("2006-01-02 15:04:05")))}
case Numeric, Fractional, String:
v = Value{bindVal.(InnerValue)}
case Value:
v = bindVal
default:
return Value{}, fmt.Errorf("unsupported bind variable type %T: %v", goval, goval)
}
return v, nil
}
// BuildNumeric builds a Numeric type that represents any whole number.
// It normalizes the representation to ensure 1:1 mapping between the
// number and its representation.
func BuildNumeric(val string) (n Value, err error) {
if val[0] == '-' || val[0] == '+' {
signed, err := strconv.ParseInt(val, 0, 64)
if err != nil {
return Value{}, err
}
n = Value{Numeric(strconv.AppendInt(nil, signed, 10))}
} else {
unsigned, err := strconv.ParseUint(val, 0, 64)
if err != nil {
return Value{}, err
}
n = Value{Numeric(strconv.AppendUint(nil, unsigned, 10))}
}
return n, nil
}
func (n Numeric) raw() []byte {
return []byte(n)
}
func (n Numeric) encodeSql(b BinWriter) {
if _, err := b.Write(n.raw()); err != nil {
panic(err)
}
}
func (n Numeric) encodeAscii(b BinWriter) {
if _, err := b.Write(n.raw()); err != nil {
panic(err)
}
}
func (n Numeric) MarshalJSON() ([]byte, error) {
return n.raw(), nil
}
func (f Fractional) raw() []byte {
return []byte(f)
}
func (f Fractional) encodeSql(b BinWriter) {
if _, err := b.Write(f.raw()); err != nil {
panic(err)
}
}
func (f Fractional) encodeAscii(b BinWriter) {
if _, err := b.Write(f.raw()); err != nil {
panic(err)
}
}
func (s String) MarshalJSON() ([]byte, error) {
return json.Marshal(string(s.raw()))
}
func (s String) raw() []byte {
return []byte(s)
}
func (s String) encodeSql(b BinWriter) {
writebyte(b, '\'')
for _, ch := range s.raw() {
if encodedChar := SqlEncodeMap[ch]; encodedChar == DONTESCAPE {
writebyte(b, ch)
} else {
writebyte(b, '\\')
writebyte(b, encodedChar)
}
}
writebyte(b, '\'')
}
func (s String) encodeAscii(b BinWriter) {
writebyte(b, '\'')
encoder := base64.NewEncoder(base64.StdEncoding, b)
encoder.Write(s.raw())
encoder.Close()
writebyte(b, '\'')
}
func writebyte(b BinWriter, c byte) {
if err := b.WriteByte(c); err != nil {
panic(err)
}
}
// SqlEncodeMap specifies how to escape binary data with '\'.
// Complies to http://dev.mysql.com/doc/refman/5.1/en/string-syntax.html
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)
}
}
gob.Register(Numeric(nil))
gob.Register(Fractional(nil))
gob.Register(String(nil))
}