forked from mailru/go-clickhouse
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdataparser.go
495 lines (430 loc) · 11.2 KB
/
dataparser.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
package clickhouse
import (
"bytes"
"database/sql/driver"
"fmt"
"io"
"reflect"
"strconv"
"time"
)
var (
reflectTypeString = reflect.TypeOf("")
reflectTypeTime = reflect.TypeOf(time.Time{})
reflectTypeEmptyStruct = reflect.TypeOf(struct{}{})
reflectTypeInt8 = reflect.TypeOf(int8(0))
reflectTypeInt16 = reflect.TypeOf(int16(0))
reflectTypeInt32 = reflect.TypeOf(int32(0))
reflectTypeInt64 = reflect.TypeOf(int64(0))
reflectTypeUInt8 = reflect.TypeOf(uint8(0))
reflectTypeUInt16 = reflect.TypeOf(uint16(0))
reflectTypeUInt32 = reflect.TypeOf(uint32(0))
reflectTypeUInt64 = reflect.TypeOf(uint64(0))
reflectTypeFloat32 = reflect.TypeOf(float32(0))
reflectTypeFloat64 = reflect.TypeOf(float64(0))
)
// DataParser implements parsing of a driver value and reporting its type.
type DataParser interface {
Parse(io.RuneScanner) (driver.Value, error)
Type() reflect.Type
}
type stringParser struct {
unquote bool
length int
}
type dateTimeParser struct {
unquote bool
format string
location *time.Location
}
type nullableParser struct {
DataParser
}
func (p *nullableParser) Parse(s io.RuneScanner) (driver.Value, error) {
// Clickhouse returns `\N` string for `null` in tsv format.
// For checking this value we need to check first two runes in `io.RuneScanner`, but we can't reset `io.RuneScanner` after it.
// Copy io.RuneScanner to `bytes.Buffer` and use it twice (1st for casting to string and checking to null, 2nd for passing to original parser)
d := readRaw(s)
if bytes.Equal(d.Bytes(), []byte(`\N`)) {
return nil, nil
}
return p.DataParser.Parse(d)
}
func readNumber(s io.RuneScanner) (string, error) {
var builder bytes.Buffer
loop:
for {
r := read(s)
switch r {
case eof:
break loop
case ',', ']', ')':
s.UnreadRune()
break loop
}
builder.WriteRune(r)
}
return builder.String(), nil
}
func readUnquoted(s io.RuneScanner, length int) (string, error) {
var builder bytes.Buffer
runesRead := 0
loop:
for length == 0 || runesRead < length {
r := read(s)
switch r {
case eof:
break loop
case '\\':
escaped, err := readEscaped(s)
if err != nil {
return "", fmt.Errorf("incorrect escaping in string: %v", err)
}
r = escaped
case '\'':
s.UnreadRune()
break loop
}
builder.WriteRune(r)
runesRead++
}
if length != 0 && runesRead != length {
return "", fmt.Errorf("unexpected string length %d, expected %d", runesRead, length)
}
return builder.String(), nil
}
func readString(s io.RuneScanner, length int, unquote bool) (string, error) {
if unquote {
if r := read(s); r != '\'' {
return "", fmt.Errorf("unexpected character instead of a quote")
}
}
str, err := readUnquoted(s, length)
if err != nil {
return "", fmt.Errorf("failed to read string")
}
if unquote {
if r := read(s); r != '\'' {
return "", fmt.Errorf("unexpected character instead of a quote")
}
}
return str, nil
}
func (p *stringParser) Parse(s io.RuneScanner) (driver.Value, error) {
return readString(s, p.length, p.unquote)
}
func (p *stringParser) Type() reflect.Type {
return reflectTypeString
}
func (p *dateTimeParser) Parse(s io.RuneScanner) (driver.Value, error) {
str, err := readString(s, len(p.format), p.unquote)
if err != nil {
return nil, fmt.Errorf("failed to read the string representation of date or datetime: %v", err)
}
if str == "0000-00-00" || str == "0000-00-00 00:00:00" {
return time.Time{}, nil
}
return time.ParseInLocation(p.format, str, p.location)
}
func (p *dateTimeParser) Type() reflect.Type {
return reflectTypeTime
}
type arrayParser struct {
arg DataParser
}
func (p *arrayParser) Type() reflect.Type {
return reflect.SliceOf(p.arg.Type())
}
type tupleParser struct {
args []DataParser
}
func (p *tupleParser) Type() reflect.Type {
fields := make([]reflect.StructField, len(p.args), len(p.args))
for i, arg := range p.args {
fields[i].Name = "Field" + strconv.Itoa(i)
fields[i].Type = arg.Type()
}
return reflect.StructOf(fields)
}
func (p *tupleParser) Parse(s io.RuneScanner) (driver.Value, error) {
r := read(s)
if r != '(' {
return nil, fmt.Errorf("unexpected character '%c', expected '(' at the beginning of tuple", r)
}
struc := reflect.New(p.Type()).Elem()
for i, arg := range p.args {
if i > 0 {
r := read(s)
if r != ',' {
return nil, fmt.Errorf("unexpected character '%c', expected ',' between tuple elements", r)
}
}
v, err := arg.Parse(s)
if err != nil {
return nil, fmt.Errorf("failed to parse tuple element: %v", err)
}
struc.Field(i).Set(reflect.ValueOf(v))
}
r = read(s)
if r != ')' {
return nil, fmt.Errorf("unexpected character '%c', expected ')' at the end of tuple", r)
}
return struc.Interface(), nil
}
func (p *arrayParser) Parse(s io.RuneScanner) (driver.Value, error) {
r := read(s)
if r != '[' {
return nil, fmt.Errorf("unexpected character '%c', expected '[' at the beginning of array", r)
}
slice := reflect.MakeSlice(p.Type(), 0, 0)
for i := 0; ; i++ {
r := read(s)
s.UnreadRune()
if r == ']' {
break
}
v, err := p.arg.Parse(s)
if err != nil {
return nil, fmt.Errorf("failed to parse array element: %v", err)
}
slice = reflect.Append(slice, reflect.ValueOf(v))
r = read(s)
if r != ',' {
s.UnreadRune()
}
}
r = read(s)
if r != ']' {
return nil, fmt.Errorf("unexpected character '%c', expected ']' at the end of array", r)
}
return slice.Interface(), nil
}
type lowCardinalityParser struct {
arg DataParser
}
func (p *lowCardinalityParser) Type() reflect.Type {
return p.arg.Type()
}
func (p *lowCardinalityParser) Parse(s io.RuneScanner) (driver.Value, error) {
return p.arg.Parse(s)
}
func newDateTimeParser(format string, loc *time.Location, unquote bool) (DataParser, error) {
return &dateTimeParser{
unquote: unquote,
format: format,
location: loc,
}, nil
}
type intParser struct {
signed bool
bitSize int
}
type floatParser struct {
bitSize int
}
func (p *intParser) Parse(s io.RuneScanner) (driver.Value, error) {
repr, err := readNumber(s)
if err != nil {
return nil, err
}
if p.signed {
v, err := strconv.ParseInt(repr, 10, p.bitSize)
switch p.bitSize {
case 8:
return int8(v), err
case 16:
return int16(v), err
case 32:
return int32(v), err
case 64:
return int64(v), err
default:
panic("unsupported bit size")
}
} else {
v, err := strconv.ParseUint(repr, 10, p.bitSize)
switch p.bitSize {
case 8:
return uint8(v), err
case 16:
return uint16(v), err
case 32:
return uint32(v), err
case 64:
return uint64(v), err
default:
panic("unsupported bit size")
}
}
}
func (p *intParser) Type() reflect.Type {
if p.signed {
switch p.bitSize {
case 8:
return reflectTypeInt8
case 16:
return reflectTypeInt16
case 32:
return reflectTypeInt32
case 64:
return reflectTypeInt64
default:
panic("unsupported bit size")
}
} else {
switch p.bitSize {
case 8:
return reflectTypeUInt8
case 16:
return reflectTypeUInt16
case 32:
return reflectTypeUInt32
case 64:
return reflectTypeUInt64
default:
panic("unsupported bit size")
}
}
}
func (p *floatParser) Parse(s io.RuneScanner) (driver.Value, error) {
repr, err := readNumber(s)
if err != nil {
return nil, err
}
v, err := strconv.ParseFloat(repr, p.bitSize)
switch p.bitSize {
case 32:
return float32(v), err
case 64:
return float64(v), err
default:
panic("unsupported bit size")
}
}
func (p *floatParser) Type() reflect.Type {
switch p.bitSize {
case 32:
return reflectTypeFloat32
case 64:
return reflectTypeFloat64
default:
panic("unsupported bit size")
}
}
type nothingParser struct{}
func (p *nothingParser) Parse(s io.RuneScanner) (driver.Value, error) {
return nil, nil
}
func (p *nothingParser) Type() reflect.Type {
return reflectTypeEmptyStruct
}
// DataParserOptions describes DataParser options.
// Ex.: Fields Location and UseDBLocation specify timezone options.
type DataParserOptions struct {
// Location describes default location for DateTime and Date field without Timezone argument.
Location *time.Location
// UseDBLocation if false: always use Location, ignore DateTime argument.
UseDBLocation bool
}
// NewDataParser creates a new DataParser based on the
// given TypeDesc.
func NewDataParser(t *TypeDesc, opt *DataParserOptions) (DataParser, error) {
return newDataParser(t, false, opt)
}
func newDataParser(t *TypeDesc, unquote bool, opt *DataParserOptions) (DataParser, error) {
switch t.Name {
case "Nothing":
return ¬hingParser{}, nil
case "Nullable":
if len(t.Args) == 0 {
return nil, fmt.Errorf("Nullable should pass original type")
}
p, err := newDataParser(t.Args[0], unquote, opt)
if err != nil {
return nil, err
}
return &nullableParser{p}, nil
case "Date":
loc := time.UTC
if opt != nil && opt.Location != nil {
loc = opt.Location
}
return newDateTimeParser(dateFormat, loc, unquote)
case "DateTime":
loc := time.UTC
if (opt == nil || opt.Location == nil || opt.UseDBLocation) && len(t.Args) > 0 {
var err error
loc, err = time.LoadLocation(t.Args[0].Name)
if err != nil {
return nil, err
}
} else if opt != nil && opt.Location != nil {
loc = opt.Location
}
return newDateTimeParser(timeFormat, loc, unquote)
case "UInt8":
return &intParser{false, 8}, nil
case "UInt16":
return &intParser{false, 16}, nil
case "UInt32":
return &intParser{false, 32}, nil
case "UInt64":
return &intParser{false, 64}, nil
case "Int8":
return &intParser{true, 8}, nil
case "Int16":
return &intParser{true, 16}, nil
case "Int32":
return &intParser{true, 32}, nil
case "Int64":
return &intParser{true, 64}, nil
case "Float32":
return &floatParser{32}, nil
case "Float64":
return &floatParser{64}, nil
case "Decimal", "String", "Enum8", "Enum16", "UUID":
return &stringParser{unquote: unquote}, nil
case "FixedString":
if len(t.Args) != 1 {
return nil, fmt.Errorf("length not specified for FixedString")
}
length, err := strconv.Atoi(t.Args[0].Name)
if err != nil {
return nil, fmt.Errorf("malformed length specified for FixedString: %v", err)
}
return &stringParser{unquote: unquote, length: length}, nil
case "Array":
if len(t.Args) != 1 {
return nil, fmt.Errorf("element type not specified for Array")
}
subParser, err := newDataParser(t.Args[0], true, opt)
if err != nil {
return nil, fmt.Errorf("failed to create parser for array elements: %v", err)
}
return &arrayParser{subParser}, nil
case "Tuple":
if len(t.Args) < 1 {
return nil, fmt.Errorf("element types not specified for Tuple")
}
subParsers := make([]DataParser, len(t.Args), len(t.Args))
for i, arg := range t.Args {
subParser, err := newDataParser(arg, true, opt)
if err != nil {
return nil, fmt.Errorf("failed to create parser for tuple element: %v", err)
}
subParsers[i] = subParser
}
return &tupleParser{subParsers}, nil
case "LowCardinality":
if len(t.Args) != 1 {
return nil, fmt.Errorf("element type not specified for LowCardinality")
}
subParser, err := newDataParser(t.Args[0], unquote, opt)
if err != nil {
return nil, fmt.Errorf("failed to create parser for LowCardinality elements: %v", err)
}
return &lowCardinalityParser{subParser}, nil
default:
return nil, fmt.Errorf("type %s is not supported", t.Name)
}
}