This repository has been archived by the owner on Feb 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdatastream.go
1692 lines (1423 loc) · 37.8 KB
/
datastream.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 iop
import (
"bytes"
"context"
"encoding/xml"
"io"
"io/ioutil"
"os"
"path"
"runtime"
"strings"
"sync"
"time"
"github.com/flarco/g"
"github.com/flarco/g/csv"
"github.com/flarco/g/json"
jit "github.com/json-iterator/go"
parquet "github.com/parquet-go/parquet-go"
"github.com/samber/lo"
"github.com/spf13/cast"
)
var (
jsoniter = jit.ConfigCompatibleWithStandardLibrary
)
// Datastream is a stream of rows
type Datastream struct {
Columns Columns
Buffer [][]any
BatchChan chan *Batch
Batches []*Batch
CurrentBatch *Batch
Count uint64
Context *g.Context
Ready bool
Bytes uint64
Sp *StreamProcessor
SafeInference bool
NoDebug bool
Inferred bool
deferFuncs []func()
closed bool
empty bool
it *Iterator
config *streamConfig
df *Dataflow
bwRows chan []any // for correct byte written
readyChn chan struct{}
schemaChgChan chan schemaChg
bwCsv *csv.Writer // for correct byte written
ID string
Metadata Metadata // map of column name to metadata type
paused bool
pauseChan chan struct{}
unpauseChan chan struct{}
}
type schemaChg struct {
I int
Type ColumnType
Added bool
Cols Columns
}
type KeyValue struct {
Key string `json:"key"`
Value any `json:"value"`
}
type Metadata struct {
StreamURL KeyValue `json:"stream_url"`
LoadedAt KeyValue `json:"loaded_at"`
}
// AsMap return as map
func (m *Metadata) AsMap() map[string]any {
m0 := g.M()
g.JSONConvert(m, &m0)
return m0
}
// Iterator is the row provider for a datastream
type Iterator struct {
Row []any
Reprocess chan []any
IsCasted bool
Counter uint64
Context *g.Context
Closed bool
ds *Datastream
dsBufferI int // -1 means ds is not buffered
nextFunc func(it *Iterator) bool
limitCnt uint64 // to not check for df limit each cycle
}
// NewDatastream return a new datastream
func NewDatastream(columns Columns) (ds *Datastream) {
return NewDatastreamContext(context.Background(), columns)
}
// NewDatastreamIt with it
func NewDatastreamIt(ctx context.Context, columns Columns, nextFunc func(it *Iterator) bool) (ds *Datastream) {
ds = NewDatastreamContext(ctx, columns)
ds.it = ds.NewIterator(columns, nextFunc)
return
}
func (ds *Datastream) NewIterator(columns Columns, nextFunc func(it *Iterator) bool) *Iterator {
return &Iterator{
Row: make([]any, len(columns)),
Reprocess: make(chan []any, 1), // for reprocessing row
nextFunc: nextFunc,
Context: ds.Context,
ds: ds,
dsBufferI: -1,
}
}
// NewDatastreamContext return a new datastream
func NewDatastreamContext(ctx context.Context, columns Columns) (ds *Datastream) {
context := g.NewContext(ctx)
ds = &Datastream{
ID: g.NewTsID("ds"),
BatchChan: make(chan *Batch, 1000),
Batches: []*Batch{},
Columns: columns,
Context: &context,
Sp: NewStreamProcessor(),
config: &streamConfig{EmptyAsNull: true, Header: true},
deferFuncs: []func(){},
bwCsv: csv.NewWriter(io.Discard),
bwRows: make(chan []any, 100),
readyChn: make(chan struct{}),
schemaChgChan: make(chan schemaChg, 1000),
pauseChan: make(chan struct{}),
unpauseChan: make(chan struct{}),
}
ds.Sp.ds = ds
ds.it = ds.NewIterator(columns, func(it *Iterator) bool { return false })
return
}
func (ds *Datastream) Df() *Dataflow {
return ds.df
}
func (ds *Datastream) processBwRows() {
// bwRows slows process speed by 10x, but this is needed for byte sizing
go func() {
if os.Getenv("DBIO_CSV_BYTES") == "TRUE" {
for row := range ds.bwRows {
ds.writeBwCsv(ds.CastRowToString(row))
ds.bwCsv.Flush()
}
} else {
for range ds.bwRows {
// drain channel
}
}
}()
}
// SetReady sets the ds.ready
func (ds *Datastream) SetReady() {
if !ds.Ready {
ds.Ready = true
go func() { ds.readyChn <- struct{}{} }()
}
}
// SetEmpty sets the ds.Rows channel as empty
func (ds *Datastream) SetEmpty() {
ds.empty = true
}
// SetConfig sets the ds.config values
func (ds *Datastream) SetConfig(configMap map[string]string) {
// lower the keys
for _, k := range lo.Keys(configMap) {
configMap[strings.ToLower(k)] = configMap[k]
}
ds.Sp.SetConfig(configMap)
ds.config = ds.Sp.config
// set metadata
if metadata, ok := configMap["metadata"]; ok {
ds.SetMetadata(metadata)
}
}
// GetConfig get config
func (ds *Datastream) GetConfig() (configMap map[string]string) {
// lower the keys
configMapI := g.M()
g.JSONConvert(ds.Sp.config, &configMapI)
return g.ToMapString(configMapI)
}
// CastRowToString returns the row as string casted
func (ds *Datastream) CastRowToString(row []any) []string {
rowStr := make([]string, len(row))
for i, val := range row {
rowStr[i] = ds.Sp.CastToString(i, val, ds.Columns[i].Type)
}
return rowStr
}
// writeBwCsv writes to the nullCsv
func (ds *Datastream) writeBwCsv(row []string) {
bw, _ := ds.bwCsv.Write(row)
ds.AddBytes(int64(bw))
}
// Push return the fields of the Data
func (ds *Datastream) Push(row []any) {
batch := ds.LatestBatch()
if batch == nil {
batch = ds.NewBatch(ds.Columns)
}
batch.Push(row)
}
// IsClosed is true is ds is closed
func (ds *Datastream) IsClosed() bool {
return ds.closed
}
// WaitReady waits until datastream is ready
func (ds *Datastream) WaitReady() error {
if ds.Ready {
return ds.Context.Err()
}
select {
case <-ds.readyChn:
return ds.Context.Err()
case <-ds.Context.Ctx.Done():
return ds.Context.Err()
}
}
// Defer runs a given function as close of Datastream
func (ds *Datastream) Defer(f func()) {
if !cast.ToBool(os.Getenv("KEEP_TEMP_FILES")) {
ds.deferFuncs = append(ds.deferFuncs, f)
}
if ds.closed { // mutex?
for _, f := range ds.deferFuncs {
f()
}
}
}
// Close closes the datastream
func (ds *Datastream) Close() {
if !ds.closed {
close(ds.bwRows)
close(ds.BatchChan)
if batch := ds.LatestBatch(); batch != nil {
batch.Close()
}
for _, batch := range ds.Batches {
select {
case <-batch.closeChan: // clean up
default:
}
}
loop:
for {
select {
case <-ds.pauseChan:
<-ds.unpauseChan // wait for unpause
case <-ds.readyChn:
case <-ds.schemaChgChan:
default:
break loop
}
}
for _, f := range ds.deferFuncs {
f()
}
if ds.Sp.unrecognizedDate != "" {
g.Warn("unrecognized date format (%s)", ds.Sp.unrecognizedDate)
}
ds.Buffer = nil // clear buffer
}
if ds.it != nil {
ds.it.close()
}
ds.closed = true
select {
case <-ds.readyChn:
default:
}
}
// SetColumns sets the columns
func (ds *Datastream) AddColumns(newCols Columns, overwrite bool) (added Columns) {
ds.Columns, added = ds.Columns.Add(newCols, overwrite)
ds.schemaChgChan <- schemaChg{Added: true, Cols: newCols}
return added
}
// ChangeColumn applies a column type change
func (ds *Datastream) ChangeColumn(i int, newType ColumnType) {
switch {
case ds == nil || ds.Columns[i].Type == newType:
return
case ds.Columns[i].Type == TextType && newType == StringType:
return
}
g.Debug("column type change for %s (%s to %s)", ds.Columns[i].Name, ds.Columns[i].Type, newType)
ds.Columns[i].Type = newType
ds.schemaChgChan <- schemaChg{I: i, Type: newType}
}
// GetFields return the fields of the Data
func (ds *Datastream) GetFields(args ...bool) []string {
lower := false
cleanUp := false
if len(args) > 1 {
lower = args[0]
cleanUp = args[1]
} else if len(args) > 0 {
lower = args[0]
}
fields := make([]string, len(ds.Columns))
for j, column := range ds.Columns {
field := column.Name
if lower {
field = strings.ToLower(column.Name)
}
if cleanUp {
field = CleanName(field) // clean up
}
fields[j] = field
}
return fields
}
// SetFields sets the fields/columns of the Datastream
func (ds *Datastream) SetFields(fields []string) {
if ds.Columns == nil || len(ds.Columns) != len(fields) {
ds.Columns = make(Columns, len(fields))
}
for i, field := range fields {
ds.Columns[i].Name = field
ds.Columns[i].Position = i + 1
}
}
// Collect reads a stream and return a dataset
// limit of 0 is unlimited
func (ds *Datastream) Collect(limit int) (Dataset, error) {
data := NewDataset(ds.Columns)
// wait for first ds to start streaming.
// columns/buffer need to be populated
err := ds.WaitReady()
if err != nil {
return data, g.Error(err)
}
data.Result = nil
data.Columns = ds.Columns
data.Rows = [][]any{}
limited := false
for row := range ds.Rows() {
data.Rows = append(data.Rows, row)
if limit > 0 && len(data.Rows) == limit {
limited = true
break
}
}
if !limited {
ds.SetEmpty()
}
ds.Buffer = nil // clear buffer
if ds.Err() != nil {
return data, g.Error(ds.Err())
}
return data, nil
}
// Err return the error if any
func (ds *Datastream) Err() (err error) {
return ds.Context.Err()
}
// Start generates the stream
// Should cycle the Iter Func until done
func (ds *Datastream) Start() (err error) {
if ds.it == nil {
err = g.Error("iterator not defined")
return g.Error(err, "need to define iterator")
}
loop:
for ds.it.next() {
select {
case <-ds.Context.Ctx.Done():
if ds.Context.Err() != nil {
err = g.Error(ds.Context.Err())
return
}
break loop
case <-ds.it.Context.Ctx.Done():
if ds.it.Context.Err() != nil {
err = g.Error(ds.it.Context.Err())
ds.Context.CaptureErr(err, "Failed to scan")
return
}
break loop
default:
if ds.it.Counter == 1 && !ds.NoDebug {
g.Trace("%#v", ds.it.Row) // trace first row for debugging
}
row := ds.Sp.ProcessRow(ds.it.Row)
ds.Buffer = append(ds.Buffer, row)
if ds.it.Counter >= cast.ToUint64(SampleSize) {
break loop
}
}
}
// infer types
if !ds.Inferred {
sampleData := NewDataset(ds.Columns)
sampleData.Rows = ds.Buffer
sampleData.NoDebug = ds.NoDebug
sampleData.SafeInference = ds.SafeInference
sampleData.Sp.dateLayouts = ds.Sp.dateLayouts
sampleData.Sp.config = ds.Sp.config
sampleData.InferColumnTypes()
ds.Columns = sampleData.Columns
ds.Inferred = true
} else if len(ds.Sp.config.Columns) > 0 {
ds.Columns = ds.Columns.Coerce(ds.Sp.config.Columns, true)
}
// set to have it loop process
ds.it.dsBufferI = 0
if ds.it.Context.Err() != nil {
err = g.Error(ds.it.Context.Err(), "error in getting rows")
return
}
// add metadata
metaValuesMap := map[int]any{}
{
// ensure there are no duplicates
ensureName := func(name string) string {
colNames := lo.Keys(ds.Columns.FieldMap(true))
for lo.Contains(colNames, strings.ToLower(name)) {
name = name + "_"
}
return name
}
if ds.Metadata.LoadedAt.Key != "" && ds.Metadata.LoadedAt.Value != nil {
ds.Metadata.LoadedAt.Key = ensureName(ds.Metadata.LoadedAt.Key)
col := Column{
Name: ds.Metadata.LoadedAt.Key,
Type: IntegerType,
Position: len(ds.Columns) + 1,
}
ds.Columns = append(ds.Columns, col)
metaValuesMap[col.Position-1] = ds.Metadata.LoadedAt.Value
}
if ds.Metadata.StreamURL.Key != "" && ds.Metadata.StreamURL.Value != nil {
ds.Metadata.StreamURL.Key = ensureName(ds.Metadata.StreamURL.Key)
col := Column{
Name: ds.Metadata.StreamURL.Key,
Type: StringType,
Position: len(ds.Columns) + 1,
}
ds.Columns = append(ds.Columns, col)
metaValuesMap[col.Position-1] = ds.Metadata.StreamURL.Value
}
}
// setMetaValues sets mata column values
setMetaValues := func(row []any) []any { return row }
if len(metaValuesMap) > 0 {
setMetaValues = func(row []any) []any {
for len(row) < len(ds.Columns) {
row = append(row, nil)
}
for i, v := range metaValuesMap {
row[i] = v
}
return row
}
}
go ds.processBwRows()
if !ds.NoDebug {
g.Trace("new ds.Start %s [%s]", ds.ID, ds.Metadata.StreamURL.Value)
}
go func() {
var err error
defer ds.Close()
ds.SetReady()
if ds.CurrentBatch == nil {
ds.CurrentBatch = ds.NewBatch(ds.Columns)
}
row := make([]any, len(ds.Columns))
rowPtrs := make([]any, len(ds.Columns))
for i := range row {
// cast the interface place holders
row[i] = ds.Sp.CastType(row[i], ds.Columns[i].Type)
rowPtrs[i] = &row[i]
}
defer func() {
// if any error occurs during iteration
if ds.it.Context.Err() != nil {
ds.Context.CaptureErr(g.Error(ds.it.Context.Err(), "error during iteration"))
}
}()
loop:
for ds.it.next() {
// if !ds.NoDebug {
// g.Warn("ds.it.next() ROW %s > %d", ds.ID, ds.it.Counter)
// }
schemaChgLoop:
for {
// reprocess row if needed (to expand it as needed)
ds.it.Row = setMetaValues(ds.it.Row)
if ds.it.IsCasted {
row = ds.it.Row
} else {
row = ds.Sp.CastRow(ds.it.Row, ds.Columns)
}
if ds.config.SkipBlankLines && ds.Sp.rowBlankValCnt == len(row) {
goto loop
}
if df := ds.df; df != nil && df.OnColumnAdded != nil && df.OnColumnChanged != nil {
select {
case <-ds.pauseChan:
<-ds.unpauseChan // wait for unpause
goto schemaChgLoop
// only consume channel if df exists
case schemaChgVal := <-ds.schemaChgChan:
ds.CurrentBatch.Close()
if schemaChgVal.Added {
g.DebugLow("%s, adding columns %s", ds.ID, g.Marshal(schemaChgVal.Cols.Types()))
if _, ok := df.AddColumns(schemaChgVal.Cols, false, ds.ID); !ok {
ds.schemaChgChan <- schemaChgVal // requeue to try adding again
}
} else {
g.DebugLow("%s, changing column %s to %s", ds.ID, df.Columns[schemaChgVal.I].Name, schemaChgVal.Type)
if !df.ChangeColumn(schemaChgVal.I, schemaChgVal.Type, ds.ID) {
ds.schemaChgChan <- schemaChgVal // requeue to try changing again
}
}
goto schemaChgLoop
default:
}
}
select {
case <-ds.pauseChan:
<-ds.unpauseChan // wait for unpause
goto schemaChgLoop
default:
if ds.CurrentBatch.closed {
ds.CurrentBatch = ds.NewBatch(ds.Columns)
}
break schemaChgLoop
}
}
select {
case <-ds.Context.Ctx.Done():
if ds.df != nil {
ds.df.Context.CaptureErr(ds.Err())
}
break loop
case <-ds.it.Context.Ctx.Done():
if ds.it.Context.Err() != nil {
err = g.Error(ds.it.Context.Err())
ds.Context.CaptureErr(err, "Failed to scan")
if ds.df != nil {
ds.df.Context.CaptureErr(ds.Err())
}
}
break loop
default:
ds.CurrentBatch.Push(row)
}
}
// close batch
ds.CurrentBatch.Close()
ds.SetEmpty()
if !ds.NoDebug {
g.Trace("Pushed %d rows for %s", ds.it.Counter, ds.ID)
}
}()
return
}
func (ds *Datastream) Rows() chan []any {
rows := MakeRowsChan()
go func() {
defer close(rows)
for batch := range ds.BatchChan {
for row := range batch.Rows {
rows <- row
}
}
}()
return rows
}
func (ds *Datastream) SetMetadata(jsonStr string) {
if jsonStr != "" {
streamValue := ds.Metadata.StreamURL.Value
g.Unmarshal(jsonStr, &ds.Metadata)
ds.Metadata.LoadedAt.Value = cast.ToInt64(ds.Metadata.LoadedAt.Value)
if ds.Metadata.StreamURL.Value == nil {
ds.Metadata.StreamURL.Value = streamValue
}
}
}
// ConsumeJsonReader uses the provided reader to stream JSON
// This will put each JSON rec as one string value
// so payload can be processed downstream
func (ds *Datastream) ConsumeJsonReader(reader io.Reader) (err error) {
reader2, err := AutoDecompress(reader)
if err != nil {
return g.Error(err, "Could not decompress reader")
}
decoder := json.NewDecoder(reader2)
js := NewJSONStream(ds, decoder, ds.Sp.config.Flatten, ds.Sp.config.Jmespath)
ds.it = ds.NewIterator(ds.Columns, js.nextFunc)
err = ds.Start()
if err != nil {
return g.Error(err, "could start datastream")
}
return
}
// ConsumeXmlReader uses the provided reader to stream XML
// This will put each XML rec as one string value
// so payload can be processed downstream
func (ds *Datastream) ConsumeXmlReader(reader io.Reader) (err error) {
reader2, err := AutoDecompress(reader)
if err != nil {
return g.Error(err, "Could not decompress reader")
}
decoder := xml.NewDecoder(reader2)
js := NewJSONStream(ds, decoder, ds.Sp.config.Flatten, ds.Sp.config.Jmespath)
ds.it = ds.NewIterator(ds.Columns, js.nextFunc)
err = ds.Start()
if err != nil {
return g.Error(err, "could start datastream")
}
return
}
// ConsumeCsvReader uses the provided reader to stream rows
func (ds *Datastream) ConsumeCsvReader(reader io.Reader) (err error) {
c := CSV{Reader: reader, NoHeader: !ds.config.Header, FieldsPerRecord: ds.config.FieldsPerRec}
r, err := c.getReader(ds.config.Delimiter)
if err != nil {
err = g.Error(err, "could not get reader")
ds.Context.CaptureErr(err)
return err
}
// set delimiter
ds.config.Delimiter = string(c.Delimiter)
row0, err := r.Read()
if err == io.EOF {
g.Debug("%s, csv stream provided is empty", ds.ID)
ds.SetReady()
ds.Close()
return nil
} else if err != nil {
err = g.Error(err, "could not parse header line")
ds.Context.CaptureErr(err)
return err
}
if c.FieldsPerRecord == 0 || len(ds.Columns) == 0 {
ds.SetFields(CleanHeaderRow(row0))
}
nextFunc := func(it *Iterator) bool {
row, err := r.Read()
if err == io.EOF {
c.File.Close()
return false
} else if err != nil {
it.Context.CaptureErr(g.Error(err, "Error reading file"))
return false
}
it.Row = make([]any, len(row))
var val any
for i, val0 := range row {
if !it.ds.Columns[i].IsString() {
val0 = strings.TrimSpace(val0)
if val0 == "" {
val = nil
} else {
val = val0
}
} else {
val = val0
}
it.Row[i] = val
}
return true
}
ds.it = ds.NewIterator(ds.Columns, nextFunc)
err = ds.Start()
if err != nil {
return g.Error(err, "could start datastream")
}
return
}
// ConsumeParquetReader uses the provided reader to stream rows
func (ds *Datastream) ConsumeParquetReaderSeeker(reader io.ReaderAt) (err error) {
p, err := NewParquetStream(reader, Columns{})
if err != nil {
return g.Error(err, "could create parquet stream")
}
ds.Columns = p.Columns()
ds.Inferred = true
ds.it = ds.NewIterator(ds.Columns, p.nextFunc)
err = ds.Start()
if err != nil {
return g.Error(err, "could start datastream")
}
return
}
// ConsumeParquetReader uses the provided reader to stream rows
func (ds *Datastream) ConsumeParquetReader(reader io.Reader) (err error) {
// need to write to temp file prior
tempDir := strings.TrimRight(strings.TrimRight(os.TempDir(), "/"), "\\")
parquetPath := path.Join(tempDir, g.NewTsID("parquet.temp")+".parquet")
ds.Defer(func() { os.Remove(parquetPath) })
file, err := os.Create(parquetPath)
if err != nil {
return g.Error(err, "Unable to create temp file: "+parquetPath)
}
g.Debug("downloading to temp file on disk: %s", parquetPath)
bw, err := io.Copy(file, reader)
if err != nil {
return g.Error(err, "Unable to write to temp file: "+parquetPath)
}
g.Debug("wrote %d bytes to %s", bw, parquetPath)
_, err = file.Seek(0, 0) // reset to beginning
if err != nil {
return g.Error(err, "Unable to seek to beginning of temp file: "+parquetPath)
}
return ds.ConsumeParquetReaderSeeker(file)
}
// ConsumeAvroReaderSeeker uses the provided reader to stream rows
func (ds *Datastream) ConsumeAvroReaderSeeker(reader io.ReadSeeker) (err error) {
a, err := NewAvroStream(reader, Columns{})
if err != nil {
return g.Error(err, "could create avro stream")
}
ds.Columns = a.Columns()
ds.Inferred = true
ds.it = ds.NewIterator(ds.Columns, a.nextFunc)
err = ds.Start()
if err != nil {
return g.Error(err, "could start datastream")
}
return
}
// ConsumeAvroReader uses the provided reader to stream rows
func (ds *Datastream) ConsumeAvroReader(reader io.Reader) (err error) {
// need to write to temp file prior
tempDir := strings.TrimRight(strings.TrimRight(os.TempDir(), "/"), "\\")
avroPath := path.Join(tempDir, g.NewTsID("avro.temp")+".avro")
ds.Defer(func() { os.Remove(avroPath) })
file, err := os.Create(avroPath)
if err != nil {
return g.Error(err, "Unable to create temp file: "+avroPath)
}
g.Debug("downloading to temp file on disk: %s", avroPath)
bw, err := io.Copy(file, reader)
if err != nil {
return g.Error(err, "Unable to write to temp file: "+avroPath)
}
g.Debug("wrote %d bytes to %s", bw, avroPath)
_, err = file.Seek(0, 0) // reset to beginning
if err != nil {
return g.Error(err, "Unable to seek to beginning of temp file: "+avroPath)
}
return ds.ConsumeAvroReaderSeeker(file)
}
// ConsumeSASReaderSeeker uses the provided reader to stream rows
func (ds *Datastream) ConsumeSASReaderSeeker(reader io.ReadSeeker) (err error) {
s, err := NewSASStream(reader, Columns{})
if err != nil {
return g.Error(err, "could create SAS stream")
}
ds.Columns = s.Columns()
ds.Inferred = false
ds.it = ds.NewIterator(ds.Columns, s.nextFunc)
err = ds.Start()
if err != nil {
return g.Error(err, "could start datastream")
}
return
}
// ConsumeSASReader uses the provided reader to stream rows
func (ds *Datastream) ConsumeSASReader(reader io.Reader) (err error) {
// need to write to temp file prior
tempDir := strings.TrimRight(strings.TrimRight(os.TempDir(), "/"), "\\")
sasPath := path.Join(tempDir, g.NewTsID("sas.temp")+".sas7bdat")
ds.Defer(func() { os.Remove(sasPath) })
file, err := os.Create(sasPath)
if err != nil {
return g.Error(err, "Unable to create temp file: "+sasPath)
}
g.Debug("downloading to temp file on disk: %s", sasPath)
bw, err := io.Copy(file, reader)
if err != nil {
return g.Error(err, "Unable to write to temp file: "+sasPath)
}
g.Debug("wrote %d bytes to %s", bw, sasPath)
_, err = file.Seek(0, 0) // reset to beginning
if err != nil {
return g.Error(err, "Unable to seek to beginning of temp file: "+sasPath)
}
return ds.ConsumeSASReaderSeeker(file)
}
// AddBytes add bytes as processed
func (ds *Datastream) AddBytes(b int64) {
ds.Bytes = ds.Bytes + cast.ToUint64(b)
}
// Records return rows of maps
func (ds *Datastream) Records() <-chan map[string]any {
chnl := make(chan map[string]any, 1000)
ds.WaitReady()
fields := ds.GetFields(true)
go func() {
defer close(chnl)
for row := range ds.Rows() {
// get records
rec := map[string]any{}
for i, field := range fields {
rec[field] = row[i]
}
chnl <- rec
}
}()
return chnl
}
// Chunk splits the datastream into chunk datastreams (in sequence)
func (ds *Datastream) Chunk(limit uint64) (chDs chan *Datastream) {
chDs = make(chan *Datastream)
if limit == 0 {
limit = 200000
}
go func() {
defer close(chDs)
nDs := NewDatastreamContext(ds.Context.Ctx, ds.Columns)
chDs <- nDs
defer func() { nDs.Close() }()
loop:
for row := range ds.Rows() {
select {
case <-nDs.Context.Ctx.Done():
break loop
default:
nDs.Push(row)
if nDs.Count == limit {
nDs.Close()
nDs = NewDatastreamContext(ds.Context.Ctx, ds.Columns)
chDs <- nDs
}
}
}
ds.SetEmpty()
}()
return
}
// Split splits the datastream into parallel datastreams
func (ds *Datastream) Split(numStreams ...int) (dss []*Datastream) {
// TODO: Split freezes the flow in some situation, such as S3 -> PG.
return []*Datastream{ds}
conncurrency := lo.Ternary(
os.Getenv("CONCURRENCY") != "",
cast.ToInt(os.Getenv("CONCURRENCY")),
runtime.NumCPU(),
)
if len(numStreams) > 0 {
conncurrency = numStreams[0]
}
for i := 0; i < conncurrency; i++ {
nDs := NewDatastreamContext(ds.Context.Ctx, ds.Columns)
nDs.SetReady()
dss = append(dss, nDs)
}
var nDs *Datastream
go func() {