/
table_writer.go
68 lines (58 loc) · 1.67 KB
/
table_writer.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
package helper
import (
"github.com/bytehouse-cloud/driver-go/driver/lib/data"
"github.com/bytehouse-cloud/driver-go/driver/lib/data/column"
)
type TableWriter interface {
// WriteFirstFrame writes the first frame generated from the first block with data from server.
// meant for writing Headers if any (eg. JSON)
// return number of rows written and error if any.
WriteFirstFrame(frame [][]string, cols []*column.CHColumn) (int, error)
// WriteFrameCont is same as WriteFirstFrame but not for first row
WriteFrameCont(frame [][]string, cols []*column.CHColumn) (int, error)
// Flush indicates all blocks are read and caller should write any last data and do clean up
Flush() error
}
type tableEndWriter interface {
WriteEnd() error
}
func WriteTableFromBlockStream(blockStream <-chan *data.Block, tWriter TableWriter) (int, error) {
frameStream, cols, recycleFrame, ok := BlockToFrame(blockStream)
if !ok {
return 0, nil
}
defer func() {
for range frameStream {
}
}()
var (
totalRowsWrite int
currentRead int
err error
)
// Read first block
for frame := range frameStream {
currentRead, err = tWriter.WriteFirstFrame(frame, cols)
totalRowsWrite += currentRead
if err != nil {
return totalRowsWrite, err
}
recycleFrame(frame)
break
}
// Read subsequent block
for frame := range frameStream {
currentRead, err = tWriter.WriteFrameCont(frame, cols)
totalRowsWrite += currentRead
if err != nil {
return totalRowsWrite, err
}
recycleFrame(frame)
}
if endWriter, ok := tWriter.(tableEndWriter); ok {
if err := endWriter.WriteEnd(); err != nil {
return totalRowsWrite, err
}
}
return totalRowsWrite, tWriter.Flush()
}