Debian Codegraph @

dependency/sqltypes/value.go

raw symbols SCIP
1 /*
2 Copyright 2017 Google Inc.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 // Package sqltypes implements interfaces and types that represent SQL values.
18 package sqltypes
19
20 import (
21 "encoding/base64"
22 "encoding/json"
23 "fmt"
24 "strconv"
25
26 "github.com/xwb1989/sqlparser/dependency/bytes2"
27 "github.com/xwb1989/sqlparser/dependency/hack"
28
29 "github.com/xwb1989/sqlparser/dependency/querypb"
30 )
31
32 var (
33 // NULL represents the NULL value.
34 NULL = Value{}
35
36 // DontEscape tells you if a character should not be escaped.
37 DontEscape = byte(255)
38
39 nullstr = []byte("null")
40 )
41
42 // BinWriter interface is used for encoding values.
43 // Types like bytes.Buffer conform to this interface.
44 // We expect the writer objects to be in-memory buffers.
45 // So, we don't expect the write operations to fail.
46 type BinWriter interface {
47 Write([]byte) (int, error)
48 }
49
50 // Value can store any SQL value. If the value represents
51 // an integral type, the bytes are always stored as a cannonical
52 // representation that matches how MySQL returns such values.
53 type Value struct {
54 typ querypb.Type
55 val []byte
56 }
57
58 // NewValue builds a Value using typ and val. If the value and typ
59 // don't match, it returns an error.
60 func NewValue(typ querypb.Type, val []byte) (v Value, err error) {
61 switch {
62 case IsSigned(typ):
63 if _, err := strconv.ParseInt(string(val), 0, 64); err != nil {
64 return NULL, err
65 }
66 return MakeTrusted(typ, val), nil
67 case IsUnsigned(typ):
68 if _, err := strconv.ParseUint(string(val), 0, 64); err != nil {
69 return NULL, err
70 }
71 return MakeTrusted(typ, val), nil
72 case IsFloat(typ) || typ == Decimal:
73 if _, err := strconv.ParseFloat(string(val), 64); err != nil {
74 return NULL, err
75 }
76 return MakeTrusted(typ, val), nil
77 case IsQuoted(typ) || typ == Null:
78 return MakeTrusted(typ, val), nil
79 }
80 // All other types are unsafe or invalid.
81 return NULL, fmt.Errorf("invalid type specified for MakeValue: %v", typ)
82 }
83
84 // MakeTrusted makes a new Value based on the type.
85 // This function should only be used if you know the value
86 // and type conform to the rules. Every place this function is
87 // called, a comment is needed that explains why it's justified.
88 // Exceptions: The current package and mysql package do not need
89 // comments. Other packages can also use the function to create
90 // VarBinary or VarChar values.
91 func MakeTrusted(typ querypb.Type, val []byte) Value {
92 if typ == Null {
93 return NULL
94 }
95 return Value{typ: typ, val: val}
96 }
97
98 // NewInt64 builds an Int64 Value.
99 func NewInt64(v int64) Value {
100 return MakeTrusted(Int64, strconv.AppendInt(nil, v, 10))
101 }
102
103 // NewInt32 builds an Int64 Value.
104 func NewInt32(v int32) Value {
105 return MakeTrusted(Int32, strconv.AppendInt(nil, int64(v), 10))
106 }
107
108 // NewUint64 builds an Uint64 Value.
109 func NewUint64(v uint64) Value {
110 return MakeTrusted(Uint64, strconv.AppendUint(nil, v, 10))
111 }
112
113 // NewFloat64 builds an Float64 Value.
114 func NewFloat64(v float64) Value {
115 return MakeTrusted(Float64, strconv.AppendFloat(nil, v, 'g', -1, 64))
116 }
117
118 // NewVarChar builds a VarChar Value.
119 func NewVarChar(v string) Value {
120 return MakeTrusted(VarChar, []byte(v))
121 }
122
123 // NewVarBinary builds a VarBinary Value.
124 // The input is a string because it's the most common use case.
125 func NewVarBinary(v string) Value {
126 return MakeTrusted(VarBinary, []byte(v))
127 }
128
129 // NewIntegral builds an integral type from a string representaion.
130 // The type will be Int64 or Uint64. Int64 will be preferred where possible.
131 func NewIntegral(val string) (n Value, err error) {
132 signed, err := strconv.ParseInt(val, 0, 64)
133 if err == nil {
134 return MakeTrusted(Int64, strconv.AppendInt(nil, signed, 10)), nil
135 }
136 unsigned, err := strconv.ParseUint(val, 0, 64)
137 if err != nil {
138 return Value{}, err
139 }
140 return MakeTrusted(Uint64, strconv.AppendUint(nil, unsigned, 10)), nil
141 }
142
143 // InterfaceToValue builds a value from a go type.
144 // Supported types are nil, int64, uint64, float64,
145 // string and []byte.
146 // This function is deprecated. Use the type-specific
147 // functions instead.
148 func InterfaceToValue(goval interface{}) (Value, error) {
149 switch goval := goval.(type) {
150 case nil:
151 return NULL, nil
152 case []byte:
153 return MakeTrusted(VarBinary, goval), nil
154 case int64:
155 return NewInt64(goval), nil
156 case uint64:
157 return NewUint64(goval), nil
158 case float64:
159 return NewFloat64(goval), nil
160 case string:
161 return NewVarChar(goval), nil
162 default:
163 return NULL, fmt.Errorf("unexpected type %T: %v", goval, goval)
164 }
165 }
166
167 // Type returns the type of Value.
168 func (v Value) Type() querypb.Type {
169 return v.typ
170 }
171
172 // Raw returns the internal represenation of the value. For newer types,
173 // this may not match MySQL's representation.
174 func (v Value) Raw() []byte {
175 return v.val
176 }
177
178 // ToBytes returns the value as MySQL would return it as []byte.
179 // In contrast, Raw returns the internal representation of the Value, which may not
180 // match MySQL's representation for newer types.
181 // If the value is not convertible like in the case of Expression, it returns nil.
182 func (v Value) ToBytes() []byte {
183 if v.typ == Expression {
184 return nil
185 }
186 return v.val
187 }
188
189 // Len returns the length.
190 func (v Value) Len() int {
191 return len(v.val)
192 }
193
194 // ToString returns the value as MySQL would return it as string.
195 // If the value is not convertible like in the case of Expression, it returns nil.
196 func (v Value) ToString() string {
197 if v.typ == Expression {
198 return ""
199 }
200 return hack.String(v.val)
201 }
202
203 // String returns a printable version of the value.
204 func (v Value) String() string {
205 if v.typ == Null {
206 return "NULL"
207 }
208 if v.IsQuoted() {
209 return fmt.Sprintf("%v(%q)", v.typ, v.val)
210 }
211 return fmt.Sprintf("%v(%s)", v.typ, v.val)
212 }
213
214 // EncodeSQL encodes the value into an SQL statement. Can be binary.
215 func (v Value) EncodeSQL(b BinWriter) {
216 switch {
217 case v.typ == Null:
218 b.Write(nullstr)
219 case v.IsQuoted():
220 encodeBytesSQL(v.val, b)
221 default:
222 b.Write(v.val)
223 }
224 }
225
226 // EncodeASCII encodes the value using 7-bit clean ascii bytes.
227 func (v Value) EncodeASCII(b BinWriter) {
228 switch {
229 case v.typ == Null:
230 b.Write(nullstr)
231 case v.IsQuoted():
232 encodeBytesASCII(v.val, b)
233 default:
234 b.Write(v.val)
235 }
236 }
237
238 // IsNull returns true if Value is null.
239 func (v Value) IsNull() bool {
240 return v.typ == Null
241 }
242
243 // IsIntegral returns true if Value is an integral.
244 func (v Value) IsIntegral() bool {
245 return IsIntegral(v.typ)
246 }
247
248 // IsSigned returns true if Value is a signed integral.
249 func (v Value) IsSigned() bool {
250 return IsSigned(v.typ)
251 }
252
253 // IsUnsigned returns true if Value is an unsigned integral.
254 func (v Value) IsUnsigned() bool {
255 return IsUnsigned(v.typ)
256 }
257
258 // IsFloat returns true if Value is a float.
259 func (v Value) IsFloat() bool {
260 return IsFloat(v.typ)
261 }
262
263 // IsQuoted returns true if Value must be SQL-quoted.
264 func (v Value) IsQuoted() bool {
265 return IsQuoted(v.typ)
266 }
267
268 // IsText returns true if Value is a collatable text.
269 func (v Value) IsText() bool {
270 return IsText(v.typ)
271 }
272
273 // IsBinary returns true if Value is binary.
274 func (v Value) IsBinary() bool {
275 return IsBinary(v.typ)
276 }
277
278 // MarshalJSON should only be used for testing.
279 // It's not a complete implementation.
280 func (v Value) MarshalJSON() ([]byte, error) {
281 switch {
282 case v.IsQuoted():
283 return json.Marshal(v.ToString())
284 case v.typ == Null:
285 return nullstr, nil
286 }
287 return v.val, nil
288 }
289
290 // UnmarshalJSON should only be used for testing.
291 // It's not a complete implementation.
292 func (v *Value) UnmarshalJSON(b []byte) error {
293 if len(b) == 0 {
294 return fmt.Errorf("error unmarshaling empty bytes")
295 }
296 var val interface{}
297 var err error
298 switch b[0] {
299 case '-':
300 var ival int64
301 err = json.Unmarshal(b, &ival)
302 val = ival
303 case '"':
304 var bval []byte
305 err = json.Unmarshal(b, &bval)
306 val = bval
307 case 'n': // null
308 err = json.Unmarshal(b, &val)
309 default:
310 var uval uint64
311 err = json.Unmarshal(b, &uval)
312 val = uval
313 }
314 if err != nil {
315 return err
316 }
317 *v, err = InterfaceToValue(val)
318 return err
319 }
320
321 func encodeBytesSQL(val []byte, b BinWriter) {
322 buf := &bytes2.Buffer{}
323 buf.WriteByte('\'')
324 for _, ch := range val {
325 if encodedChar := SQLEncodeMap[ch]; encodedChar == DontEscape {
326 buf.WriteByte(ch)
327 } else {
328 buf.WriteByte('\\')
329 buf.WriteByte(encodedChar)
330 }
331 }
332 buf.WriteByte('\'')
333 b.Write(buf.Bytes())
334 }
335
336 func encodeBytesASCII(val []byte, b BinWriter) {
337 buf := &bytes2.Buffer{}
338 buf.WriteByte('\'')
339 encoder := base64.NewEncoder(base64.StdEncoding, buf)
340 encoder.Write(val)
341 encoder.Close()
342 buf.WriteByte('\'')
343 b.Write(buf.Bytes())
344 }
345
346 // SQLEncodeMap specifies how to escape binary data with '\'.
347 // Complies to http://dev.mysql.com/doc/refman/5.1/en/string-syntax.html
348 var SQLEncodeMap [256]byte
349
350 // SQLDecodeMap is the reverse of SQLEncodeMap
351 var SQLDecodeMap [256]byte
352
353 var encodeRef = map[byte]byte{
354 '\x00': '0',
355 '\'': '\'',
356 '"': '"',
357 '\b': 'b',
358 '\n': 'n',
359 '\r': 'r',
360 '\t': 't',
361 26: 'Z', // ctl-Z
362 '\\': '\\',
363 }
364
365 func init() {
366 for i := range SQLEncodeMap {
367 SQLEncodeMap[i] = DontEscape
368 SQLDecodeMap[i] = DontEscape
369 }
370 for i := range SQLEncodeMap {
371 if to, ok := encodeRef[byte(i)]; ok {
372 SQLEncodeMap[byte(i)] = to
373 SQLDecodeMap[to] = byte(i)
374 }
375 }
376 }