-
Notifications
You must be signed in to change notification settings - Fork 153
/
result.go
1369 lines (1233 loc) · 32.3 KB
/
result.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
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package csv contains the csv result encoders and decoders.
package csv
import (
"context"
"encoding/csv"
"encoding/json"
"fmt"
"io"
"strconv"
"strings"
"sync/atomic"
"time"
"unicode/utf8"
"github.com/apache/arrow/go/v7/arrow/memory"
"github.com/influxdata/flux"
"github.com/influxdata/flux/array"
"github.com/influxdata/flux/arrow"
"github.com/influxdata/flux/codes"
"github.com/influxdata/flux/execute"
"github.com/influxdata/flux/internal/errors"
"github.com/influxdata/flux/iocounter"
"github.com/influxdata/flux/values"
)
const (
defaultMaxBufferCount = 1000
annotationIdx = 0
resultIdx = 1
tableIdx = 2
defaultRecordStartIdx = 3
datatypeAnnotation = "datatype"
groupAnnotation = "group"
defaultAnnotation = "default"
resultLabel = "result"
tableLabel = "table"
commentPrefix = "#"
stringDatatype = "string"
timeDatatype = "dateTime"
floatDatatype = "double"
boolDatatype = "boolean"
intDatatype = "long"
uintDatatype = "unsignedLong"
timeDataTypeWithFmt = "dateTime:RFC3339"
nullValue = ""
)
// ResultDecoder decodes a csv representation of a result.
type ResultDecoder struct {
c ResultDecoderConfig
}
// NewResultDecoder creates a new ResultDecoder.
func NewResultDecoder(c ResultDecoderConfig) *ResultDecoder {
if c.MaxBufferCount == 0 {
c.MaxBufferCount = defaultMaxBufferCount
}
return &ResultDecoder{
c: c,
}
}
// ResultDecoderConfig are options that can be specified on the ResultDecoder.
type ResultDecoderConfig struct {
// NoAnnotations indicates that the CSV data will not have annotations rows.
// Without annotations the decoder will assume every column is of type string and
// that all data is in a single table in a single result.
NoAnnotations bool
// NoHeader indicates that the CSV data will not have a header row.
NoHeader bool
// MaxBufferCount is the maximum number of rows that will be buffered when decoding.
// If 0, then a value of 1000 will be used.
MaxBufferCount int
// Allocator is the memory allocator that will be used during decoding.
// The default is to use an unlimited allocator when this is not set.
Allocator memory.Allocator
// Context is the context for this ResultDecoder.
// When the context is canceled, the decoder will also be canceled.
// This defaults to context.Background.
Context context.Context
}
func (d *ResultDecoder) Decode(r io.Reader) (flux.Result, error) {
return newResultDecoder(newCSVReader(r), d.c, nil)
}
// MultiResultDecoder reads multiple results from a single csv file.
// Results are delimited by an empty line.
type MultiResultDecoder struct {
c ResultDecoderConfig
}
// NewMultiResultDecoder creates a new MultiResultDecoder.
func NewMultiResultDecoder(c ResultDecoderConfig) *MultiResultDecoder {
if c.MaxBufferCount == 0 {
c.MaxBufferCount = defaultMaxBufferCount
}
return &MultiResultDecoder{
c: c,
}
}
func (d *MultiResultDecoder) Decode(r io.ReadCloser) (flux.ResultIterator, error) {
return &resultIterator{
c: d.c,
r: r,
cr: newCSVReader(r),
}, nil
}
// resultIterator iterates through the results encoded in r.
type resultIterator struct {
c ResultDecoderConfig
r io.ReadCloser
cr *bufferedCSVReader
next *resultDecoder
err error
canceled bool
}
func (r *resultIterator) More() bool {
if r.next == nil || !r.next.eof {
var extraMeta *tableMetadata
if r.next != nil {
extraMeta = r.next.extraMeta
}
r.next, r.err = newResultDecoder(r.cr, r.c, extraMeta)
if r.err == nil {
return true
}
if r.err == io.EOF {
// Do not report EOF errors
r.err = nil
}
}
// Release the resources for this query.
r.Release()
return false
}
func (r *resultIterator) Next() flux.Result {
return r.next
}
func (r *resultIterator) Release() {
if r.canceled {
return
}
if err := r.r.Close(); err != nil && r.err == nil {
r.err = err
}
r.canceled = true
}
func (r *resultIterator) Err() error {
return r.err
}
func (r *resultIterator) Statistics() flux.Statistics {
return flux.Statistics{}
}
type resultDecoder struct {
id string
c ResultDecoderConfig
cr *bufferedCSVReader
extraMeta *tableMetadata
eof bool
}
func newResultDecoder(cr *bufferedCSVReader, c ResultDecoderConfig, extraMeta *tableMetadata) (*resultDecoder, error) {
d := &resultDecoder{
c: c,
cr: cr,
extraMeta: extraMeta,
}
// We need to know the result ID before we return
if extraMeta == nil {
tm, err := readMetadata(d.cr, c)
if err != nil {
if err == io.EOF {
return nil, err
} else if sfe, ok := err.(*serializedFluxError); ok {
return nil, sfe.err
}
return nil, errors.Wrap(err, codes.Inherit, "failed to read metadata")
}
d.extraMeta = &tm
}
d.id = d.extraMeta.ResultID
return d, nil
}
func newCSVReader(r io.Reader) *bufferedCSVReader {
csvr := csv.NewReader(r)
csvr.ReuseRecord = true
// Do not check record size
csvr.FieldsPerRecord = -1
csvr.LazyQuotes = true
return &bufferedCSVReader{
r: csvr,
line: nil,
}
}
func (r *resultDecoder) Name() string {
return r.id
}
func (r *resultDecoder) Tables() flux.TableIterator {
return r
}
func (r *resultDecoder) Abort(error) {
panic("not implemented")
}
func (r *resultDecoder) Do(f func(flux.Table) error) error {
ctx := r.c.Context
if ctx == nil {
ctx = context.Background()
}
var meta tableMetadata
newMeta := true
for !r.eof {
if newMeta {
if r.extraMeta != nil {
meta = *r.extraMeta
r.extraMeta = nil
} else {
tm, err := readMetadata(r.cr, r.c)
if err != nil {
if err == io.EOF {
goto EOF
}
if sfe, ok := err.(*serializedFluxError); ok {
return sfe.err
}
return errors.Wrap(err, codes.Inherit, "failed to read metadata")
}
meta = tm
}
if meta.ResultID != r.id {
r.extraMeta = &meta
return nil
}
}
// Create a new table
tbl, err := newTable(r.cr, r.c, meta)
if err != nil {
return err
}
// Call f on the table, f can return before the table has been fully consumed.
if err := f(tbl); err != nil {
return err
}
// Block until the table has been fully consumed or the context is canceled
select {
case <-tbl.done:
case <-ctx.Done():
return ctx.Err()
}
// Now that the table has been consumed we can check for more tables
// Check next line to see if we have a new meta block
line, err := r.cr.Read()
if err != nil {
if err == io.EOF {
goto EOF
}
return err
}
// cannot be a new meta block if there are no annotations
newMeta = !r.c.NoAnnotations && len(line) > annotationIdx && line[annotationIdx] != ""
err = r.cr.Unread(line)
if err != nil {
return err
}
// track whether we hit the EOF
r.eof = tbl.eof
}
EOF:
r.eof = true
return nil
}
type tableMetadata struct {
ResultID string
TableID string
Cols []colMeta
Groups []bool
Defaults []values.Value
NumFields int
RecordStartIdx int
}
// serializedFluxError represents an error that occurred during
// Flux execution that has been serialized to CSV.
type serializedFluxError struct {
err error
}
func (sfe *serializedFluxError) Error() string {
return sfe.err.Error()
}
// readMetadata reads the table annotations and header.
// If there is no more data, returns (tableMetadata{}, io.EOF).
// In case of an actual error:
// - if it's error that was serialized to CSV, it will be wrapped in serializedFluxError.
// - otherwise, it's a serialization error, it will be returned as-is.
func readMetadata(r *bufferedCSVReader, c ResultDecoderConfig) (tableMetadata, error) {
n := -1
var recordStartIdx int
var resultID, tableID string
var datatypes, groups, defaults []string
if c.NoAnnotations {
// No annotations means that we are going to treat all rows as part of the same result with exactly one table
resultID = "_result"
tableID = "0"
recordStartIdx = 0
line, err := r.Read()
if err != nil {
return tableMetadata{}, err
}
n = len(line)
// We treat all columns as strings
datatypes = make([]string, n)
groups = make([]string, n)
defaults = make([]string, n)
for i := range datatypes {
datatypes[i] = "string"
groups[i] = "false"
defaults[i] = ""
}
// put this line back now that we know its length
err = r.Unread(line)
if err != nil {
return tableMetadata{}, err
}
} else {
recordStartIdx = defaultRecordStartIdx
for datatypes == nil || groups == nil || defaults == nil {
line, err := r.Read()
if err != nil {
if err == io.EOF {
if datatypes == nil && groups == nil && defaults == nil {
return tableMetadata{}, err
}
switch {
case datatypes == nil:
return tableMetadata{}, errors.New(codes.FailedPrecondition, "missing expected annotation datatype. "+
"Consider using the mode: \"raw\" for csv that is not expected to have annotations.")
case groups == nil:
return tableMetadata{}, fmt.Errorf("missing expected annotation group")
case defaults == nil:
return tableMetadata{}, fmt.Errorf("missing expected annotation default")
}
}
return tableMetadata{}, err
}
if n == -1 {
n = len(line)
}
if n != len(line) {
return tableMetadata{}, errors.Wrap(csv.ErrFieldCount, codes.Invalid, "failed to read annotations")
}
switch annotation := strings.TrimPrefix(line[annotationIdx], commentPrefix); annotation {
case datatypeAnnotation:
if defaultRecordStartIdx > len(line) {
return tableMetadata{}, errors.Wrap(csv.ErrFieldCount, codes.Invalid, "failed to read \"datatype\" annotation")
}
datatypes = copyLine(line[defaultRecordStartIdx:])
case groupAnnotation:
if defaultRecordStartIdx > len(line) {
return tableMetadata{}, errors.Wrap(csv.ErrFieldCount, codes.Invalid, "failed to read \"group\" annotation")
}
groups = copyLine(line[defaultRecordStartIdx:])
case defaultAnnotation:
if defaultRecordStartIdx > len(line) {
return tableMetadata{}, errors.Wrap(csv.ErrFieldCount, codes.Invalid, "failed to read \"default\" annotation")
}
resultID = line[resultIdx]
tableID = line[tableIdx]
if _, err := strconv.ParseInt(tableID, 10, 64); tableID != "" && err != nil {
return tableMetadata{}, fmt.Errorf("default Table ID is not an integer")
}
defaults = copyLine(line[defaultRecordStartIdx:])
default:
if !strings.HasPrefix(line[annotationIdx], commentPrefix) {
switch {
case datatypes == nil:
return tableMetadata{}, errors.New(codes.FailedPrecondition, "missing expected annotation datatype. "+
"consider using the mode: \"raw\" for csv that is not expected to have annotations.")
case groups == nil:
return tableMetadata{}, fmt.Errorf("missing expected annotation group")
case defaults == nil:
return tableMetadata{}, fmt.Errorf("missing expected annotation default")
}
}
// Ignore unsupported/unknown annotations.
}
}
}
// Determine column labels
var labels []string
if c.NoHeader {
labels = make([]string, len(datatypes))
for i := range labels {
labels[i] = fmt.Sprintf("col%d", i)
}
} else {
// Read header row
line, err := r.Read()
if err != nil {
if err == io.EOF {
return tableMetadata{}, errors.New(codes.Invalid, "missing expected header row")
}
return tableMetadata{}, err
}
if n != len(line) {
return tableMetadata{}, errors.Wrap(csv.ErrFieldCount, codes.Invalid, "failed to read header row")
}
if len(line) > 1 && line[1] == "error" {
// Read the first row and return the error.
line, err := r.Read()
if err != nil || n != len(line) {
if err == io.EOF {
return tableMetadata{}, errors.Wrap(io.ErrUnexpectedEOF, codes.Invalid)
} else if err == nil && n != len(line) {
return tableMetadata{}, errors.Wrap(csv.ErrFieldCount, codes.Invalid)
}
return tableMetadata{}, errors.Wrap(err, codes.Inherit, "failed to read error value")
}
// TODO: We should determine the correct error code here:
// https://github.com/influxdata/flux/issues/1916
return tableMetadata{}, &serializedFluxError{err: errors.New(codes.Internal, line[1])}
}
labels = line[recordStartIdx:]
}
cols := make([]colMeta, len(labels))
defaultValues := make([]values.Value, len(labels))
groupValues := make([]bool, len(labels))
for j, label := range labels {
t, desc, err := decodeType(datatypes[j])
if err != nil {
return tableMetadata{}, errors.Wrapf(err, codes.Invalid, "column %q has invalid datatype", label)
}
cols[j].ColMeta.Label = label
cols[j].ColMeta.Type = t
if t == flux.TTime {
switch desc {
case "RFC3339":
cols[j].fmt = time.RFC3339
case "RFC3339Nano":
cols[j].fmt = time.RFC3339Nano
default:
cols[j].fmt = desc
}
}
if defaults[j] == nullValue {
defaultValues[j] = values.NewNull(flux.SemanticType(cols[j].ColMeta.Type))
} else if defaults[j] == "" {
// for now, the null value is always represented with "", so this is
// unreachable.
// When we support the #null annotation we'll want to distinguish
// between "" (for strings) and null here.
panic("unreachable")
} else {
v, err := decodeValue(defaults[j], cols[j])
if err != nil {
return tableMetadata{}, errors.Wrapf(err, codes.Invalid, "column %q has invalid default value", label)
}
defaultValues[j] = v
}
groupValues[j] = groups[j] == "true"
}
return tableMetadata{
ResultID: resultID,
TableID: tableID,
Cols: cols,
Groups: groupValues,
Defaults: defaultValues,
NumFields: n,
RecordStartIdx: recordStartIdx,
}, nil
}
type tableDecoder struct {
r *bufferedCSVReader
c ResultDecoderConfig
meta tableMetadata
used int32
empty bool
initialized bool
id string
key flux.GroupKey
colMeta []flux.ColMeta
cols []array.Builder
nrows int
done chan struct{}
eof bool
}
func newTable(
r *bufferedCSVReader,
c ResultDecoderConfig,
meta tableMetadata,
) (*tableDecoder, error) {
b := &tableDecoder{
r: r,
c: c,
meta: meta,
// assume its empty until we append a record
empty: true,
done: make(chan struct{}),
}
more, err := b.advance()
if !more {
close(b.done)
}
if err != nil {
return nil, err
}
if !b.initialized {
return b, b.init(nil)
}
return b, nil
}
func (d *tableDecoder) Do(f func(flux.ColReader) error) error {
if !atomic.CompareAndSwapInt32(&d.used, 0, 1) {
return errors.New(codes.Internal, "table already read")
}
// Ensure that all internal memory is released when we exit.
defer d.release()
// Send off first batch from first advance call.
if err := d.Emit(f); err != nil {
return err
}
select {
case <-d.done:
return nil
default:
}
more := true
defer close(d.done)
for more {
var err error
more, err = d.advance()
if err != nil {
return err
}
if err := d.Emit(f); err != nil {
return err
}
}
return nil
}
func (d *tableDecoder) Done() {
_ = d.Do(func(flux.ColReader) error { return nil })
}
// advance reads the csv data until the end of the table or bufSize rows have been read.
// Advance returns whether there is more data and any error.
func (d *tableDecoder) advance() (bool, error) {
var line, record []string
var err error
for !d.initialized || d.nrows < d.c.MaxBufferCount {
line, err = d.r.Read()
if err != nil {
if err == io.EOF {
d.eof = true
return false, nil
}
return false, err
}
// whatever this line is, it's not part of this table so goto DONE
if len(line) != d.meta.NumFields {
// If this line is another annotation then the current table has no more data.
// Otherwise if this line is not another annotation or if we are not expecting annotations
// we have an ErrFieldCount, meaning that a row we expected to be a data row has the wrong number of fields.
if d.c.NoAnnotations || (len(line) > annotationIdx && line[annotationIdx] == "") {
return false, csv.ErrFieldCount
}
goto DONE
}
// Check for new annotation
if !d.c.NoAnnotations && line[annotationIdx] != "" {
goto DONE
}
if !d.initialized {
if err := d.init(line); err != nil {
return false, err
}
d.initialized = true
}
// check if we have tableID that is now different
if !d.c.NoAnnotations && line[tableIdx] != "" && line[tableIdx] != d.id {
goto DONE
}
record = line[d.meta.RecordStartIdx:]
err = d.appendRecord(record)
if err != nil {
return false, err
}
}
return true, nil
DONE:
// table is done
// unread the last line
err = d.r.Unread(line)
if err != nil {
return false, err
}
if !d.initialized {
// if we found a new annotation without any data rows, then the table is empty and we
// init using the meta.Default column values.
if d.empty {
if err := d.init(nil); err != nil {
return false, err
}
} else {
return false, errors.New(codes.Internal, "table was not initialized, missing group key data")
}
}
return false, nil
}
func (d *tableDecoder) init(line []string) error {
if d.c.NoAnnotations {
d.id = "0"
} else {
if len(line) != 0 {
d.id = line[tableIdx]
} else if d.meta.TableID != "" {
d.id = d.meta.TableID
} else {
return errors.New(codes.Invalid, "missing table ID")
}
}
var record []string
if len(line) != 0 {
record = line[d.meta.RecordStartIdx:]
}
keyCols := make([]flux.ColMeta, 0, len(d.meta.Cols))
keyValues := make([]values.Value, 0, len(d.meta.Cols))
for j, c := range d.meta.Cols {
if d.meta.Groups[j] {
var value values.Value
if record != nil && record[j] != "" {
// TODO: consider treatment of nullValue here
v, err := decodeValue(record[j], c)
if err != nil {
return err
}
value = v
} else {
value = d.meta.Defaults[j]
}
keyCols = append(keyCols, c.ColMeta)
keyValues = append(keyValues, value)
}
}
d.key = execute.NewGroupKey(keyCols, keyValues)
alloc := memory.DefaultAllocator
if d.c.Allocator != nil {
alloc = d.c.Allocator
}
if len(d.meta.Cols) > 0 {
d.colMeta = make([]flux.ColMeta, len(d.meta.Cols))
d.cols = make([]array.Builder, len(d.meta.Cols))
for i, c := range d.meta.Cols {
d.colMeta[i] = c.ColMeta
d.cols[i] = arrow.NewBuilder(c.Type, alloc)
}
}
return nil
}
func (d *tableDecoder) appendRecord(record []string) error {
d.empty = false
for j, c := range d.meta.Cols {
if record[j] == "" {
v := d.meta.Defaults[j]
if err := arrow.AppendValue(d.cols[j], v); err != nil {
return err
}
continue
}
if err := decodeValueInto(c, record[j], d.cols[j]); err != nil {
return err
}
}
d.nrows++
return nil
}
func (d *tableDecoder) Empty() bool {
return d.empty
}
func (d *tableDecoder) Key() flux.GroupKey {
return d.key
}
func (d *tableDecoder) Cols() []flux.ColMeta {
return d.colMeta
}
func (d *tableDecoder) Emit(f func(flux.ColReader) error) error {
cr := arrow.TableBuffer{
GroupKey: d.key,
Columns: d.colMeta,
Values: make([]array.Array, len(d.cols)),
}
for i, c := range d.cols {
// Creating a new array resets the builder so
// we do not have to release the memory or
// reinitialize the builder.
cr.Values[i] = c.NewArray()
}
d.nrows = 0
defer cr.Release()
return f(&cr)
}
func (d *tableDecoder) release() {
for _, c := range d.cols {
c.Release()
}
d.cols = nil
}
type colMeta struct {
flux.ColMeta
fmt string
}
type ResultEncoder struct {
c ResultEncoderConfig
written bool
}
// ResultEncoderConfig are options that can be specified on the ResultEncoder.
type ResultEncoderConfig struct {
// Annotations is a list of annotations to include.
Annotations []string
// NoHeader indicates whether a header row should be added.
NoHeader bool
// Delimiter is the character to delimite columns.
// It must not be \r, \n, or the Unicode replacement character (0xFFFD).
Delimiter rune
}
func (c ResultEncoderConfig) MarshalJSON() ([]byte, error) {
request := struct {
Header bool `json:"header,omitempty"`
Delimiter string `json:"delimiter"`
Annotations []string `json:"annotations,omitempty"`
}{
Delimiter: string(c.Delimiter),
Annotations: c.Annotations,
Header: !c.NoHeader,
}
return json.Marshal(request)
}
func (c *ResultEncoderConfig) UnmarshalJSON(b []byte) error {
request := &struct {
Header *bool `json:"header,omitempty"`
Delimiter string `json:"delimiter"`
Annotations []string `json:"annotations,omitempty"`
}{}
if err := json.Unmarshal(b, request); err != nil {
return err
}
if request.Delimiter == "" {
request.Delimiter = ","
}
c.Delimiter, _ = utf8.DecodeRuneInString(request.Delimiter)
c.NoHeader = false
if request.Header != nil {
c.NoHeader = !*request.Header
}
c.Annotations = request.Annotations
return nil
}
func DefaultEncoderConfig() ResultEncoderConfig {
return ResultEncoderConfig{
Annotations: []string{datatypeAnnotation, groupAnnotation, defaultAnnotation},
}
}
// NewResultEncoder creates a new encoder with the provided configuration.
func NewResultEncoder(c ResultEncoderConfig) *ResultEncoder {
return &ResultEncoder{
c: c,
}
}
func (e *ResultEncoder) csvWriter(w io.Writer) *csv.Writer {
writer := csv.NewWriter(w)
if e.c.Delimiter != 0 {
writer.Comma = e.c.Delimiter
}
writer.UseCRLF = true
return writer
}
type csvEncoderError struct {
err error
}
func (e *csvEncoderError) Error() string {
return fmt.Sprintf("csv encoder error: %s", e.err.Error())
}
func (e *csvEncoderError) IsEncoderError() bool {
return true
}
func (e *csvEncoderError) Unwrap() error {
return e.err
}
func wrapEncodingError(err error) error {
if err == nil {
return err
}
return &csvEncoderError{err: err}
}
func (e *ResultEncoder) Encode(w io.Writer, result flux.Result) (int64, error) {
tableID := 0
tableIDStr := "0"
metaCols := []colMeta{
{ColMeta: flux.ColMeta{Label: "", Type: flux.TInvalid}},
{ColMeta: flux.ColMeta{Label: resultLabel, Type: flux.TString}},
{ColMeta: flux.ColMeta{Label: tableLabel, Type: flux.TInt}},
}
writeCounter := &iocounter.Writer{Writer: w}
writer := e.csvWriter(writeCounter)
var lastCols []colMeta
var lastGroupCols []flux.ColMeta
var lastEmpty bool
resultName := result.Name()
err := result.Tables().Do(func(tbl flux.Table) error {
e.written = true
// Update cols with table cols
cols := metaCols
for _, c := range tbl.Cols() {
cm := colMeta{ColMeta: c}
if c.Type == flux.TTime {
cm.fmt = time.RFC3339Nano
}
cols = append(cols, cm)
}
// pre-allocate row slice
row := make([]string, len(cols))
if lastEmpty || tbl.Empty() || schemaChanged(cols, lastCols, tbl.Key().Cols(), lastGroupCols) {
if len(lastCols) > 0 {
// Write out empty line if not first table
writer.Write(nil)
}
if err := writeSchema(writer, &e.c, row, cols, tbl.Empty(), tbl.Key(), resultName, tableIDStr); err != nil {
return wrapEncodingError(err)
}
}
if execute.ContainsStr(e.c.Annotations, defaultAnnotation) {
for j := range cols {
switch j {
case annotationIdx:
row[j] = ""
case resultIdx:
row[j] = ""
case tableIdx:
row[j] = tableIDStr
default:
row[j] = ""
}
}
} else {
for j := range cols {
switch j {
case annotationIdx:
row[j] = ""
case resultIdx:
row[j] = resultName
case tableIdx:
row[j] = tableIDStr
default:
row[j] = ""
}
}
}
if err := tbl.Do(func(cr flux.ColReader) error {
record := row[defaultRecordStartIdx:]
l := cr.Len()
for i := 0; i < l; i++ {
for j, c := range cols[defaultRecordStartIdx:] {
v, err := encodeValueFrom(i, j, c, cr)
if err != nil {
return wrapEncodingError(err)
}
record[j] = v
}
writer.Write(row)
}
writer.Flush()
return wrapEncodingError(writer.Error())
}); err != nil {
return err
}
tableID++
tableIDStr = strconv.Itoa(tableID)
lastCols = cols
lastGroupCols = tbl.Key().Cols()
lastEmpty = tbl.Empty()
writer.Flush()
return wrapEncodingError(writer.Error())
})
return writeCounter.Count(), err
}
func (e *ResultEncoder) EncodeError(w io.Writer, err error) error {
writer := e.csvWriter(w)
if e.written {
// Write out empty line
writer.Write(nil)
}
for _, anno := range e.c.Annotations {
switch anno {
case datatypeAnnotation:
writer.Write([]string{commentPrefix + datatypeAnnotation, "string", "string"})
case groupAnnotation:
writer.Write([]string{commentPrefix + groupAnnotation, "true", "true"})
case defaultAnnotation:
writer.Write([]string{commentPrefix + defaultAnnotation, "", ""})