-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
exportcsv.go
314 lines (282 loc) · 7.71 KB
/
exportcsv.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
// Copyright 2018 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package importer
import (
"bytes"
"compress/gzip"
"context"
"fmt"
"io"
"strings"
"github.com/cockroachdb/cockroach/pkg/cloud"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/colinfo"
"github.com/cockroachdb/cockroach/pkg/sql/execinfra"
"github.com/cockroachdb/cockroach/pkg/sql/execinfrapb"
"github.com/cockroachdb/cockroach/pkg/sql/rowenc"
"github.com/cockroachdb/cockroach/pkg/sql/rowexec"
"github.com/cockroachdb/cockroach/pkg/sql/sem/builtins"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util/encoding/csv"
"github.com/cockroachdb/cockroach/pkg/util/tracing"
"github.com/cockroachdb/errors"
)
const (
exportFilePatternPart = "%part%"
exportFilePatternDefault = exportFilePatternPart + ".csv"
)
// csvExporter data structure to augment the compression
// and csv writer, encapsulating the internals to make
// exporting oblivious for the consumers.
type csvExporter struct {
compressor *gzip.Writer
buf *bytes.Buffer
csvWriter *csv.Writer
}
// Write append record to csv file.
func (c *csvExporter) Write(record []string) error {
return c.csvWriter.Write(record)
}
// Close closes the compressor writer which
// appends archive footers.
func (c *csvExporter) Close() error {
if c.compressor != nil {
return c.compressor.Close()
}
return nil
}
// Flush flushes both csv and compressor writer if
// initialized.
func (c *csvExporter) Flush() error {
c.csvWriter.Flush()
if c.compressor != nil {
return c.compressor.Flush()
}
return nil
}
// ResetBuffer resets the buffer and compressor state.
func (c *csvExporter) ResetBuffer() {
c.buf.Reset()
if c.compressor != nil {
// Brings compressor to its initial state.
c.compressor.Reset(c.buf)
}
}
// Bytes results in the slice of bytes with compressed content.
func (c *csvExporter) Bytes() []byte {
return c.buf.Bytes()
}
// Len returns length of the buffer with content.
func (c *csvExporter) Len() int {
return c.buf.Len()
}
func (c *csvExporter) FileName(spec execinfrapb.ExportSpec, part string) string {
pattern := exportFilePatternDefault
if spec.NamePattern != "" {
pattern = spec.NamePattern
}
fileName := strings.Replace(pattern, exportFilePatternPart, part, -1)
// TODO: add suffix based on compressor type
if c.compressor != nil {
fileName += ".gz"
}
return fileName
}
func newCSVExporter(sp execinfrapb.ExportSpec) *csvExporter {
buf := bytes.NewBuffer([]byte{})
var exporter *csvExporter
switch sp.Format.Compression {
case roachpb.IOFileFormat_Gzip:
{
writer := gzip.NewWriter(buf)
exporter = &csvExporter{
compressor: writer,
buf: buf,
csvWriter: csv.NewWriter(writer),
}
}
default:
{
exporter = &csvExporter{
buf: buf,
csvWriter: csv.NewWriter(buf),
}
}
}
if sp.Format.Csv.Comma != 0 {
exporter.csvWriter.Comma = sp.Format.Csv.Comma
}
return exporter
}
func newCSVWriterProcessor(
flowCtx *execinfra.FlowCtx,
processorID int32,
spec execinfrapb.ExportSpec,
input execinfra.RowSource,
output execinfra.RowReceiver,
) (execinfra.Processor, error) {
c := &csvWriter{
flowCtx: flowCtx,
processorID: processorID,
spec: spec,
input: input,
output: output,
}
semaCtx := tree.MakeSemaContext()
if err := c.out.Init(&execinfrapb.PostProcessSpec{}, c.OutputTypes(), &semaCtx, flowCtx.NewEvalCtx()); err != nil {
return nil, err
}
return c, nil
}
type csvWriter struct {
flowCtx *execinfra.FlowCtx
processorID int32
spec execinfrapb.ExportSpec
input execinfra.RowSource
out execinfra.ProcOutputHelper
output execinfra.RowReceiver
}
var _ execinfra.Processor = &csvWriter{}
func (sp *csvWriter) OutputTypes() []*types.T {
res := make([]*types.T, len(colinfo.ExportColumns))
for i := range res {
res[i] = colinfo.ExportColumns[i].Typ
}
return res
}
func (sp *csvWriter) MustBeStreaming() bool {
return false
}
func (sp *csvWriter) Run(ctx context.Context) {
ctx, span := tracing.ChildSpan(ctx, "csvWriter")
defer span.Finish()
instanceID := sp.flowCtx.EvalCtx.NodeID.SQLInstanceID()
uniqueID := builtins.GenerateUniqueInt(instanceID)
// TODO(dt): pick up tracing info in trailing meta
pushTrailingMeta := func(context.Context) {}
err := func() error {
typs := sp.input.OutputTypes()
sp.input.Start(ctx)
alloc := &tree.DatumAlloc{}
writer := newCSVExporter(sp.spec)
var nullsAs string
if sp.spec.Format.Csv.NullEncoding != nil {
nullsAs = *sp.spec.Format.Csv.NullEncoding
}
f := tree.NewFmtCtx(tree.FmtExport)
defer f.Close()
csvRow := make([]string, len(typs))
chunk := 0
done := false
for {
var rows int64
writer.ResetBuffer()
for {
// If the bytes.Buffer sink exceeds the target size of a CSV file, we
// flush before exporting any additional rows.
if int64(writer.buf.Len()) >= sp.spec.ChunkSize {
break
}
if sp.spec.ChunkRows > 0 && rows >= sp.spec.ChunkRows {
break
}
row, meta := sp.input.Next()
if meta != nil {
if !rowexec.EmitHelper(ctx, sp.output, &sp.out, nil /* row */, meta, pushTrailingMeta, sp.input) {
return nil
}
continue
}
if row == nil {
done = true
break
}
rows++
for i, ed := range row {
if ed.IsNull() {
if sp.spec.Format.Csv.NullEncoding != nil {
csvRow[i] = nullsAs
continue
} else {
return errors.New("NULL value encountered during EXPORT, " +
"use `WITH nullas` to specify the string representation of NULL")
}
}
if err := ed.EnsureDecoded(typs[i], alloc); err != nil {
return err
}
ed.Datum.Format(f)
csvRow[i] = f.String()
f.Reset()
}
if err := writer.Write(csvRow); err != nil {
return err
}
}
if rows < 1 {
break
}
if err := writer.Flush(); err != nil {
return errors.Wrap(err, "failed to flush csv writer")
}
// Close writer to ensure buffer and any compression footer is flushed.
if err := writer.Close(); err != nil {
return errors.Wrapf(err, "failed to close exporting writer")
}
part := fmt.Sprintf("n%d.%d", uniqueID, chunk)
chunk++
filename := writer.FileName(sp.spec, part)
size := writer.Len()
if err := sp.writeToExternalStorage(ctx, filename, bytes.NewReader(writer.Bytes())); err != nil {
return err
}
res := rowenc.EncDatumRow{
rowenc.DatumToEncDatum(
types.String,
tree.NewDString(filename),
),
rowenc.DatumToEncDatum(
types.Int,
tree.NewDInt(tree.DInt(rows)),
),
rowenc.DatumToEncDatum(
types.Int,
tree.NewDInt(tree.DInt(size)),
),
}
if !rowexec.EmitHelper(ctx, sp.output, &sp.out, res, nil /* meta */, pushTrailingMeta, sp.input) {
return nil
}
if done {
break
}
}
return nil
}()
execinfra.DrainAndClose(ctx, sp.output, err, pushTrailingMeta /* pushTrailingMeta */, sp.input)
}
func (sp *csvWriter) writeToExternalStorage(
ctx context.Context, filename string, reader io.Reader,
) error {
conf, err := cloud.ExternalStorageConfFromURI(sp.spec.Destination, sp.spec.User())
if err != nil {
return err
}
es, err := sp.flowCtx.Cfg.ExternalStorage(ctx, conf)
if err != nil {
return err
}
defer es.Close()
return cloud.WriteFile(ctx, es, filename, reader)
}
func init() {
rowexec.NewCSVWriterProcessor = newCSVWriterProcessor
}