-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
bulk_row_writer.go
240 lines (214 loc) · 6.5 KB
/
bulk_row_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
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
// Copyright 2019 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 rowexec
import (
"context"
"sync/atomic"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/kvserverbase"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/execinfra"
"github.com/cockroachdb/cockroach/pkg/sql/execinfrapb"
"github.com/cockroachdb/cockroach/pkg/sql/row"
"github.com/cockroachdb/cockroach/pkg/sql/rowenc"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util/ctxgroup"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
"github.com/cockroachdb/errors"
)
// CTASPlanResultTypes is the result types for EXPORT plans.
var CTASPlanResultTypes = []*types.T{
types.Bytes, // rows
}
type bulkRowWriter struct {
execinfra.ProcessorBase
flowCtx *execinfra.FlowCtx
processorID int32
batchIdxAtomic int64
tableDesc catalog.TableDescriptor
spec execinfrapb.BulkRowWriterSpec
input execinfra.RowSource
output execinfra.RowReceiver
summary roachpb.BulkOpSummary
}
var _ execinfra.Processor = &bulkRowWriter{}
var _ execinfra.RowSource = &bulkRowWriter{}
func newBulkRowWriterProcessor(
flowCtx *execinfra.FlowCtx,
processorID int32,
spec execinfrapb.BulkRowWriterSpec,
input execinfra.RowSource,
output execinfra.RowReceiver,
) (execinfra.Processor, error) {
c := &bulkRowWriter{
flowCtx: flowCtx,
processorID: processorID,
batchIdxAtomic: 0,
tableDesc: spec.BuildTableDescriptor(),
spec: spec,
input: input,
output: output,
}
if err := c.Init(
c, &execinfrapb.PostProcessSpec{}, CTASPlanResultTypes, flowCtx, processorID, output,
nil /* memMonitor */, execinfra.ProcStateOpts{InputsToDrain: []execinfra.RowSource{input}},
); err != nil {
return nil, err
}
return c, nil
}
// Start is part of the RowSource interface.
func (sp *bulkRowWriter) Start(ctx context.Context) {
ctx = sp.StartInternal(ctx, "bulkRowWriter")
sp.input.Start(ctx)
err := sp.work(ctx)
sp.MoveToDraining(err)
}
// Next is part of the RowSource interface.
func (sp *bulkRowWriter) Next() (rowenc.EncDatumRow, *execinfrapb.ProducerMetadata) {
// If there wasn't an error while processing, output the summary.
if sp.ProcessorBase.State == execinfra.StateRunning {
countsBytes, marshalErr := protoutil.Marshal(&sp.summary)
sp.MoveToDraining(marshalErr)
if marshalErr == nil {
// Output the summary.
return rowenc.EncDatumRow{
rowenc.DatumToEncDatum(types.Bytes, tree.NewDBytes(tree.DBytes(countsBytes))),
}, nil
}
}
return nil, sp.DrainHelper()
}
func (sp *bulkRowWriter) work(ctx context.Context) error {
kvCh := make(chan row.KVBatch, 10)
var g ctxgroup.Group
semaCtx := tree.MakeSemaContext()
conv, err := row.NewDatumRowConverter(
ctx, &semaCtx, sp.tableDesc, nil /* targetColNames */, sp.EvalCtx, kvCh, nil,
/* seqChunkProvider */ sp.flowCtx.GetRowMetrics(),
)
if err != nil {
return err
}
if conv.EvalCtx.SessionData() == nil {
panic("uninitialized session data")
}
g = ctxgroup.WithContext(ctx)
g.GoCtx(func(ctx context.Context) error {
return sp.ingestLoop(ctx, kvCh)
})
g.GoCtx(func(ctx context.Context) error {
return sp.convertLoop(ctx, kvCh, conv)
})
return g.Wait()
}
func (sp *bulkRowWriter) wrapDupError(ctx context.Context, orig error) error {
var typed *kvserverbase.DuplicateKeyError
if !errors.As(orig, &typed) {
return orig
}
v := &roachpb.Value{RawBytes: typed.Value}
return row.NewUniquenessConstraintViolationError(ctx, sp.tableDesc, typed.Key, v)
}
func (sp *bulkRowWriter) ingestLoop(ctx context.Context, kvCh chan row.KVBatch) error {
writeTS := sp.spec.Table.CreateAsOfTime
const bufferSize = 64 << 20
adder, err := sp.flowCtx.Cfg.BulkAdder(
ctx, sp.flowCtx.Cfg.DB, writeTS, kvserverbase.BulkAdderOptions{
MinBufferSize: bufferSize,
// We disallow shadowing here to ensure that we report errors when builds
// of unique indexes fail when there are duplicate values.
DisallowShadowing: true,
},
)
if err != nil {
return err
}
defer adder.Close(ctx)
// ingestKvs drains kvs from the channel until it closes, ingesting them using
// the BulkAdder. It handles the required buffering/sorting/etc.
ingestKvs := func() error {
for kvBatch := range kvCh {
for _, kv := range kvBatch.KVs {
if err := adder.Add(ctx, kv.Key, kv.Value.RawBytes); err != nil {
return sp.wrapDupError(ctx, err)
}
}
}
if err := adder.Flush(ctx); err != nil {
return sp.wrapDupError(ctx, err)
}
return nil
}
// Drain the kvCh using the BulkAdder until it closes.
if err := ingestKvs(); err != nil {
return err
}
sp.summary = adder.GetSummary()
return nil
}
func (sp *bulkRowWriter) convertLoop(
ctx context.Context, kvCh chan row.KVBatch, conv *row.DatumRowConverter,
) error {
defer close(kvCh)
done := false
alloc := &rowenc.DatumAlloc{}
typs := sp.input.OutputTypes()
for {
var rows int64
for {
row, meta := sp.input.Next()
if meta != nil {
if meta.Err != nil {
return meta.Err
}
sp.AppendTrailingMeta(*meta)
continue
}
if row == nil {
done = true
break
}
rows++
for i, ed := range row {
if ed.IsNull() {
conv.Datums[i] = tree.DNull
continue
}
if err := ed.EnsureDecoded(typs[i], alloc); err != nil {
return err
}
conv.Datums[i] = ed.Datum
}
// `conv.Row` uses these as arguments to GenerateUniqueID to generate
// hidden primary keys, when necessary. We want them to be ascending per
// to reduce overlap in the resulting kvs and non-conflicting (because
// of primary key uniqueness). The ids that come out of GenerateUniqueID
// are sorted by (fileIndex, rowIndex) and unique as long as the two
// inputs are a unique combo, so using the processor ID and a
// monotonically increasing batch index should do what we want.
if err := conv.Row(ctx, sp.processorID, sp.batchIdxAtomic); err != nil {
return err
}
atomic.AddInt64(&sp.batchIdxAtomic, 1)
}
if rows < 1 {
break
}
if err := conv.SendBatch(ctx); err != nil {
return err
}
if done {
break
}
}
return nil
}