-
Notifications
You must be signed in to change notification settings - Fork 90
/
dataparser.go
760 lines (654 loc) · 16.8 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
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
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
package clickhouse
import (
"bytes"
"database/sql/driver"
"fmt"
"io"
"reflect"
"strconv"
"strings"
"time"
)
var (
reflectTypeString = reflect.TypeOf("")
reflectTypeTime = reflect.TypeOf(time.Time{})
reflectTypeEmptyStruct = reflect.TypeOf(struct{}{})
reflectTypeBool = reflect.TypeOf(bool(false))
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))
)
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
}
// DataParser implements parsing of a driver value and reporting its type.
type DataParser interface {
Parse(io.RuneScanner) (driver.Value, error)
Type() reflect.Type
}
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)
var dB *bytes.Buffer
dType := p.DataParser.Type()
switch dType {
case reflectTypeInt8, reflectTypeInt16, reflectTypeInt32, reflectTypeInt64,
reflectTypeUInt8, reflectTypeUInt16, reflectTypeUInt32, reflectTypeUInt64,
reflectTypeFloat32, reflectTypeFloat64:
d, err := readNumber(s)
if err != nil {
return nil, fmt.Errorf("error: %v", err)
}
dB = bytes.NewBufferString(d)
case reflectTypeString:
runes := ""
iter := 0
isNotString := false
for {
r, size, err := s.ReadRune()
if err == io.EOF && size == 0 {
break
}
if err != nil {
return nil, fmt.Errorf("error: %v", err)
}
if r != '\'' && iter == 0 {
err = s.UnreadRune()
if err != nil {
return nil, fmt.Errorf("error: %v", err)
}
d := readRaw(s)
dB = d
isNotString = true
break
}
isEscaped := false
if r == '\\' {
escaped, err := readEscaped(s)
if err != nil {
return "", fmt.Errorf("incorrect escaping in string: %v", err)
}
isEscaped = true
r = escaped
if r == '\'' {
runes += string('\\')
}
}
runes += string(r)
if r == '\'' && iter != 0 && !isEscaped {
break
}
iter++
}
if bytes.Equal([]byte(runes), []byte(`'N'`)) {
return nil, nil
}
if !isNotString {
dB = bytes.NewBufferString(runes)
}
case reflectTypeTime:
runes := ""
iter := 0
for {
r, _, err := s.ReadRune()
if err != nil {
if err != io.EOF {
return nil, fmt.Errorf("unexpected error on ReadRune: %v", err)
}
break
}
runes += string(r)
if r == '\'' && iter != 0 {
break
}
iter++
}
if runes == "0000-00-00" || runes == "0000-00-00 00:00:00" {
return time.Time{}, nil
}
if bytes.Equal([]byte(runes), []byte(`'\N'`)) {
return nil, nil
}
dB = bytes.NewBufferString(runes)
case reflectTypeEmptyStruct:
d := readRaw(s)
dB = d
default:
d := readRaw(s)
dB = d
}
if bytes.Equal(dB.Bytes(), []byte(`\N`)) {
return nil, nil
}
return p.DataParser.Parse(dB)
}
type stringParser struct {
unquote bool
length int
}
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
}
type dateTimeParser struct {
unquote bool
format string
location *time.Location
precision int
}
func (p *dateTimeParser) Parse(s io.RuneScanner) (driver.Value, error) {
l := len(p.format)
if p.precision > 0 {
if i := strings.Index(p.format, "."); i >= 0 {
l = i + p.precision + 1
}
}
str, err := readString(s, l, p.unquote)
if err != nil {
return nil, fmt.Errorf("failed to read the string representation of date or datetime: %v", err)
}
test := str
if i := strings.Index(str, " "); i >= 0 {
test = str[:i]
}
if test == "0000-00-00" {
return time.Time{}, nil
}
return time.ParseInLocation(p.format, str, p.location)
}
func (p *dateTimeParser) Type() reflect.Type {
return reflectTypeTime
}
type tupleParser struct {
args []DataParser
}
func (p *tupleParser) Type() reflect.Type {
fields := make([]reflect.StructField, 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
}
type arrayParser struct {
arg DataParser
}
func (p *arrayParser) Type() reflect.Type {
return reflect.SliceOf(p.arg.Type())
}
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)
}
if v == nil {
if reflect.TypeOf(p.arg) != reflect.TypeOf(&nullableParser{}) {
//need check if v is nil: panic otherwise
return nil, fmt.Errorf("unexpected nil element")
}
} else {
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 mapParser struct {
key DataParser
value DataParser
}
func (p *mapParser) Type() reflect.Type {
return reflect.MapOf(p.key.Type(), p.value.Type())
}
func (p *mapParser) Parse(s io.RuneScanner) (driver.Value, error) {
r := read(s)
if r != '{' {
return nil, fmt.Errorf("unexpected character '%c', expected '{' at the beginning of map", r)
}
m := reflect.MakeMap(p.Type())
for i := 0; ; i++ {
r := read(s)
_ = s.UnreadRune()
if r == '}' {
break
}
k, err := p.key.Parse(s)
if err != nil {
return nil, fmt.Errorf("failed to parse map key: %v", err)
}
r = read(s)
if r != ':' {
return nil, fmt.Errorf("unexpected character '%c', expected ':' at the middle of map", r)
}
v, err := p.value.Parse(s)
if err != nil {
return nil, fmt.Errorf("failed to parse map value: %v", err)
}
m.SetMapIndex(reflect.ValueOf(k), 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 map", r)
}
return m.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)
}
type simpleAggregateFunctionParser struct {
arg DataParser
}
func (p *simpleAggregateFunctionParser) Type() reflect.Type {
return p.arg.Type()
}
func (p *simpleAggregateFunctionParser) Parse(s io.RuneScanner) (driver.Value, error) {
return p.arg.Parse(s)
}
func newDateTimeParser(format string, loc *time.Location, precision int, unquote bool) (DataParser, error) {
return &dateTimeParser{
unquote: unquote,
format: format,
location: loc,
precision: precision,
}, nil
}
type boolParser struct{}
func (p *boolParser) Parse(s io.RuneScanner) (driver.Value, error) {
repr := readRaw(s).String()
switch repr {
case "true":
return true, nil
case "false":
return false, nil
default:
return nil, fmt.Errorf("incorrect bool value: %v", repr)
}
}
func (p *boolParser) Type() reflect.Type {
return reflectTypeBool
}
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, 0, 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, 0, unquote)
case "DateTime64":
if len(t.Args) < 1 {
return nil, fmt.Errorf("tick size not specified for DateTime64")
}
loc := time.UTC
if (opt == nil || opt.Location == nil || opt.UseDBLocation) && len(t.Args) > 1 {
var err error
loc, err = time.LoadLocation(t.Args[1].Name)
if err != nil {
return nil, err
}
} else if opt != nil && opt.Location != nil {
loc = opt.Location
}
precision, err := strconv.Atoi(t.Args[0].Name)
if err != nil {
return nil, err
}
if precision < 0 {
return nil, fmt.Errorf("malformed tick size specified for DateTime64")
}
return newDateTimeParser(dateTime64Format, loc, precision, unquote)
case "Bool":
return &boolParser{}, nil
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", "IPv4", "IPv6":
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))
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
case "SimpleAggregateFunction":
if len(t.Args) != 2 {
return nil, fmt.Errorf("incorrect number of arguments for SimpleAggregateFunction")
}
subParser, err := newDataParser(t.Args[1], unquote, opt)
if err != nil {
return nil, fmt.Errorf("failed to create parser for SimpleAggregateFunction element: %v", err)
}
return &simpleAggregateFunctionParser{subParser}, nil
case "Map":
if len(t.Args) != 2 {
return nil, fmt.Errorf("incorrect number of arguments for Map")
}
keyParser, err := newDataParser(t.Args[0], true, opt)
if err != nil {
return nil, fmt.Errorf("failed to create parser for map keys: %v", err)
}
valueParser, err := newDataParser(t.Args[1], true, opt)
if err != nil {
return nil, fmt.Errorf("failed to create parser for map values: %v", err)
}
return &mapParser{
key: keyParser,
value: valueParser,
}, nil
default:
return nil, fmt.Errorf("type %s is not supported", t.Name)
}
}