-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
crossjoiner.go
486 lines (454 loc) · 15.9 KB
/
crossjoiner.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
// Copyright 2020 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 colexecjoin
import (
"context"
"github.com/cockroachdb/cockroach/pkg/col/coldata"
"github.com/cockroachdb/cockroach/pkg/col/typeconv"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/colcontainer"
"github.com/cockroachdb/cockroach/pkg/sql/colexec/colexecutils"
"github.com/cockroachdb/cockroach/pkg/sql/colexecerror"
"github.com/cockroachdb/cockroach/pkg/sql/colexecop"
"github.com/cockroachdb/cockroach/pkg/sql/colmem"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util/mon"
"github.com/cockroachdb/errors"
"github.com/marusama/semaphore"
)
// NewCrossJoiner returns a vectorized cross join operator.
func NewCrossJoiner(
unlimitedAllocator *colmem.Allocator,
memoryLimit int64,
diskQueueCfg colcontainer.DiskQueueCfg,
fdSemaphore semaphore.Semaphore,
joinType descpb.JoinType,
left colexecop.Operator,
right colexecop.Operator,
leftTypes []*types.T,
rightTypes []*types.T,
diskAcc *mon.BoundAccount,
) colexecop.Operator {
if joinType.IsSetOpJoin() {
colexecerror.InternalError(errors.AssertionFailedf("set-op cross joins are invalid"))
}
return &crossJoiner{
crossJoinerBase: newCrossJoinerBase(
unlimitedAllocator,
joinType,
leftTypes,
rightTypes,
memoryLimit,
diskQueueCfg,
fdSemaphore,
diskAcc,
),
joinHelper: newJoinHelper(left, right),
unlimitedAllocator: unlimitedAllocator,
outputTypes: joinType.MakeOutputTypes(leftTypes, rightTypes),
maxOutputBatchMemSize: memoryLimit,
}
}
type crossJoiner struct {
*crossJoinerBase
*joinHelper
unlimitedAllocator *colmem.Allocator
rightInputConsumed bool
outputTypes []*types.T
maxOutputBatchMemSize int64
// isLeftAllNulls and isRightAllNulls indicate whether the output vectors
// corresponding to the left and right inputs, respectively, should consist
// only of NULL values. This is the case when we have right or left,
// respectively, unmatched tuples.
isLeftAllNulls, isRightAllNulls bool
// done indicates that the cross joiner has fully built its output and
// closed the spilling queue. Once set to true, only zero-length batches are
// emitted.
done bool
}
var _ colexecop.ClosableOperator = &crossJoiner{}
var _ colexecop.ResettableOperator = &crossJoiner{}
func (c *crossJoiner) Init(ctx context.Context) {
if !c.joinHelper.init(ctx) {
return
}
// Note that c.joinHelper.Ctx might contain an updated context, so we use
// that rather than ctx.
c.crossJoinerBase.init(c.joinHelper.Ctx)
}
func (c *crossJoiner) Next() coldata.Batch {
if c.done {
return coldata.ZeroBatch
}
if !c.rightInputConsumed {
c.consumeRightInput(c.Ctx)
c.setupForBuilding()
}
var willEmit int
if c.needLeftTuples {
if c.isLeftAllNulls {
if c.isRightAllNulls {
// This can happen only in FULL OUTER join when both inputs are
// empty.
return c.emitFirstZeroBatch()
}
// All tuples from the right are unmatched and will be emitted once.
c.builderState.setup.rightNumRepeats = 1
willEmit = c.numRightTuples - c.builderState.numAlreadyEmitted
} else {
if c.builderState.left.currentBatch == nil || c.canEmit() == 0 {
// Get the next left batch if we haven't fetched one yet or we
// have fully built the output using the current left batch.
leftBatch := c.inputOne.Next()
n := leftBatch.Length()
if n == 0 {
return c.emitFirstZeroBatch()
}
c.prepareForNextLeftBatch(leftBatch, 0 /* startIdx */, n)
}
willEmit = c.canEmit()
}
} else {
switch c.joinType {
case descpb.LeftSemiJoin, descpb.LeftAntiJoin:
// We don't need the left tuples, and in case of LEFT SEMI/ANTI this
// means that the right input was empty/non-empty, so the cross join
// is empty.
return c.emitFirstZeroBatch()
case descpb.RightSemiJoin, descpb.RightAntiJoin:
if c.numRightTuples == 0 {
// For RIGHT SEMI, we didn't fetch any right tuples if the left
// input was empty; for RIGHT ANTI - if the left input wasn't
// empty. In both such cases the cross join is empty.
return c.emitFirstZeroBatch()
}
willEmit = c.canEmit()
}
}
c.output, _ = c.unlimitedAllocator.ResetMaybeReallocate(
c.outputTypes, c.output, willEmit, c.maxOutputBatchMemSize,
)
if willEmit > c.output.Capacity() {
willEmit = c.output.Capacity()
}
if c.joinType.ShouldIncludeLeftColsInOutput() {
if c.isLeftAllNulls {
setAllNulls(c.output.ColVecs()[:len(c.left.types)], willEmit)
} else {
c.buildFromLeftInput(c.Ctx, 0 /* destStartIdx */)
}
}
if c.joinType.ShouldIncludeRightColsInOutput() {
if c.isRightAllNulls {
setAllNulls(c.output.ColVecs()[c.builderState.rightColOffset:], willEmit)
} else {
c.buildFromRightInput(c.Ctx, 0 /* destStartIdx */)
}
}
c.output.SetLength(willEmit)
c.builderState.numAlreadyEmitted += willEmit
c.builderState.numEmittedSinceReset += willEmit
return c.output
}
// emitFirstZeroBatch closes the cross joiner and returns a zero-length batch.
func (c *crossJoiner) emitFirstZeroBatch() coldata.Batch {
if err := c.Close(); err != nil {
colexecerror.InternalError(err)
}
c.done = true
return coldata.ZeroBatch
}
// consumeRightInput determines the kind of information the cross joiner needs
// from its right input (in some cases, we don't need to buffer all tuples from
// the right) and consumes the right input accordingly. It also checks whether
// we need any tuples from the left and possibly reads a single batch, depending
// on the join type.
func (c *crossJoiner) consumeRightInput(ctx context.Context) {
c.rightInputConsumed = true
var needRightTuples bool
switch c.joinType {
case descpb.InnerJoin, descpb.LeftOuterJoin, descpb.RightOuterJoin, descpb.FullOuterJoin:
c.needLeftTuples = true
needRightTuples = true
case descpb.LeftSemiJoin:
// With LEFT SEMI join we only need to know whether the right input is
// empty or not.
c.numRightTuples = c.inputTwo.Next().Length()
c.needLeftTuples = c.numRightTuples != 0
case descpb.RightSemiJoin:
// With RIGHT SEMI join we only need to know whether the left input is
// empty or not.
leftBatch := c.inputOne.Next()
c.prepareForNextLeftBatch(leftBatch, 0 /* startIdx */, leftBatch.Length())
needRightTuples = leftBatch.Length() != 0
case descpb.LeftAntiJoin:
// With LEFT ANTI join we only need to know whether the right input is
// empty or not.
c.numRightTuples = c.inputTwo.Next().Length()
c.needLeftTuples = c.numRightTuples == 0
case descpb.RightAntiJoin:
// With RIGHT ANTI join we only need to know whether the left input is
// empty or not.
leftBatch := c.inputOne.Next()
c.prepareForNextLeftBatch(leftBatch, 0 /* startIdx */, leftBatch.Length())
needRightTuples = leftBatch.Length() == 0
default:
colexecerror.InternalError(errors.AssertionFailedf("unexpected join type %s", c.joinType.String()))
}
if needRightTuples {
for {
batch := c.inputTwo.Next()
c.rightTuples.Enqueue(ctx, batch)
if batch.Length() == 0 {
break
}
c.numRightTuples += batch.Length()
}
}
}
// setupForBuilding prepares the cross joiner to build the output. This method
// must be called after the right input has been fully "processed" (which might
// mean it wasn't fully read, depending on the join type).
func (c *crossJoiner) setupForBuilding() {
switch c.joinType {
case descpb.LeftOuterJoin:
c.isRightAllNulls = c.numRightTuples == 0
case descpb.RightOuterJoin:
leftBatch := c.inputOne.Next()
c.builderState.left.currentBatch = leftBatch
c.isLeftAllNulls = leftBatch.Length() == 0
c.prepareForNextLeftBatch(leftBatch, 0 /* startIdx */, leftBatch.Length())
case descpb.FullOuterJoin:
leftBatch := c.inputOne.Next()
c.builderState.left.currentBatch = leftBatch
c.isLeftAllNulls = leftBatch.Length() == 0
c.isRightAllNulls = c.numRightTuples == 0
c.prepareForNextLeftBatch(leftBatch, 0 /* startIdx */, leftBatch.Length())
}
// In order for canEmit method to work in the unmatched cases, we "lie"
// that there is a single tuple on the right side which results in the
// builder method repeating the tuples only once, and that's exactly what we
// want.
if c.isRightAllNulls {
c.numRightTuples = 1
}
c.setupLeftBuilder()
}
// setAllNulls sets all tuples in vecs with indices in [0, length) range to
// null.
func setAllNulls(vecs []coldata.Vec, length int) {
for i := range vecs {
vecs[i].Nulls().SetNullRange(0 /* startIdx */, length)
}
}
func (c *crossJoiner) Reset(ctx context.Context) {
if r, ok := c.inputOne.(colexecop.Resetter); ok {
r.Reset(ctx)
}
if r, ok := c.inputTwo.(colexecop.Resetter); ok {
r.Reset(ctx)
}
c.crossJoinerBase.Reset(ctx)
c.rightInputConsumed = false
c.isLeftAllNulls = false
c.isRightAllNulls = false
c.done = false
}
func newCrossJoinerBase(
unlimitedAllocator *colmem.Allocator,
joinType descpb.JoinType,
leftTypes, rightTypes []*types.T,
memoryLimit int64,
cfg colcontainer.DiskQueueCfg,
fdSemaphore semaphore.Semaphore,
diskAcc *mon.BoundAccount,
) *crossJoinerBase {
base := &crossJoinerBase{
joinType: joinType,
left: cjState{
unlimitedAllocator: unlimitedAllocator,
types: leftTypes,
canonicalTypeFamilies: typeconv.ToCanonicalTypeFamilies(leftTypes),
},
right: cjState{
unlimitedAllocator: unlimitedAllocator,
types: rightTypes,
canonicalTypeFamilies: typeconv.ToCanonicalTypeFamilies(rightTypes),
},
rightTuples: colexecutils.NewRewindableSpillingQueue(
&colexecutils.NewSpillingQueueArgs{
UnlimitedAllocator: unlimitedAllocator,
Types: rightTypes,
MemoryLimit: memoryLimit,
DiskQueueCfg: cfg,
FDSemaphore: fdSemaphore,
DiskAcc: diskAcc,
},
),
}
if joinType.ShouldIncludeLeftColsInOutput() {
base.builderState.rightColOffset = len(leftTypes)
}
return base
}
type crossJoinerBase struct {
initHelper colexecop.InitHelper
// Note that unlike crossJoiner operator, crossJoinerBase needs to support
// all join types (including set-op joins) because it is used by the merge
// joiner.
joinType descpb.JoinType
left, right cjState
numRightTuples int
rightTuples *colexecutils.SpillingQueue
needLeftTuples bool
builderState struct {
setup cjBuilderSetupState
left, right cjMutableBuilderState
// numAlreadyEmitted tracks the number of joined rows returned based on
// the current left batch. It is reset on every call to
// prepareForNextLeftBatch.
numAlreadyEmitted int
// numEmittedSinceReset tracks the number of rows that have been emitted
// since the crossJoinerBase has been reset. It is only used in RIGHT
// SEMI, RIGHT ANTI, and INTERSECT ALL joins.
numEmittedSinceReset int
// rightColOffset indicates the number of vectors in the output batch
// that should be "skipped" when building from the right input.
rightColOffset int
}
output coldata.Batch
}
func (b *crossJoinerBase) init(ctx context.Context) {
b.initHelper.Init(ctx)
}
func (b *crossJoinerBase) setupLeftBuilder() {
switch b.joinType {
case descpb.LeftSemiJoin, descpb.IntersectAllJoin, descpb.ExceptAllJoin:
b.builderState.setup.leftNumRepeats = 1
case descpb.LeftAntiJoin:
// LEFT ANTI cross join emits all left tuples repeated once only if the
// right input is empty.
if b.numRightTuples == 0 {
b.builderState.setup.leftNumRepeats = 1
}
default:
b.builderState.setup.leftNumRepeats = b.numRightTuples
}
}
// prepareForNextLeftBatch sets up the crossJoinerBase to build based on a new
// batch coming from the left input. Only rows with ordinals in
// [startIdx, endIdx) range will be used for the cross join.
func (b *crossJoinerBase) prepareForNextLeftBatch(batch coldata.Batch, startIdx, endIdx int) {
b.builderState.numAlreadyEmitted = 0
b.builderState.left.currentBatch = batch
b.builderState.left.curSrcStartIdx = startIdx
b.builderState.left.numRepeatsIdx = 0
b.builderState.right.numRepeatsIdx = 0
if b.joinType == descpb.IntersectAllJoin {
// Intersect all is special because we need to count how many tuples
// from the right we have already used up.
if b.builderState.numEmittedSinceReset+endIdx-startIdx >= b.numRightTuples {
// The current left batch is the last one that contains tuples with
// a "match".
b.builderState.setup.leftSrcEndIdx = b.numRightTuples - b.builderState.numEmittedSinceReset + startIdx
} else {
// The current left batch is still emitted fully.
b.builderState.setup.leftSrcEndIdx = endIdx
}
} else {
b.builderState.setup.leftSrcEndIdx = endIdx
}
switch b.joinType {
case descpb.InnerJoin, descpb.LeftOuterJoin, descpb.RightOuterJoin, descpb.FullOuterJoin:
b.builderState.setup.rightNumRepeats = endIdx - startIdx
case descpb.RightSemiJoin, descpb.RightAntiJoin:
b.builderState.setup.rightNumRepeats = 1
}
}
// canEmit returns the number of output rows that can still be emitted based on
// the current left batch. It supports only the case when both left and right
// inputs are not empty.
func (b *crossJoinerBase) canEmit() int {
switch b.joinType {
case descpb.LeftSemiJoin, descpb.IntersectAllJoin, descpb.ExceptAllJoin:
return b.builderState.setup.leftSrcEndIdx - b.builderState.left.curSrcStartIdx
case descpb.LeftAntiJoin:
if b.numRightTuples != 0 {
return 0
}
return b.builderState.setup.leftSrcEndIdx - b.builderState.left.curSrcStartIdx
case descpb.RightSemiJoin:
// RIGHT SEMI cross join emits all right tuples repeated once iff the
// left input is not empty.
if b.builderState.setup.leftSrcEndIdx == b.builderState.left.curSrcStartIdx {
return 0
}
return b.numRightTuples - b.builderState.numEmittedSinceReset
case descpb.RightAntiJoin:
// RIGHT ANTI cross join emits all right tuples repeated once iff the
// left input is empty.
if b.builderState.setup.leftSrcEndIdx != b.builderState.left.curSrcStartIdx {
return 0
}
return b.numRightTuples - b.builderState.numEmittedSinceReset
default:
return b.builderState.setup.rightNumRepeats*b.numRightTuples - b.builderState.numAlreadyEmitted
}
}
func (b *crossJoinerBase) Reset(ctx context.Context) {
if b.rightTuples != nil {
b.rightTuples.Reset(ctx)
}
b.numRightTuples = 0
b.builderState.left.reset()
b.builderState.right.reset()
b.builderState.numAlreadyEmitted = 0
b.builderState.numEmittedSinceReset = 0
}
func (b *crossJoinerBase) Close() error {
ctx := b.initHelper.EnsureCtx()
if b.rightTuples != nil {
return b.rightTuples.Close(ctx)
}
return nil
}
type cjState struct {
unlimitedAllocator *colmem.Allocator
types []*types.T
canonicalTypeFamilies []types.Family
}
type cjBuilderSetupState struct {
// leftSrcEndIdx indicates the index of the tuple at which the building from
// the left input should stop. For some join types this number is less than
// the total number of left tuples (whereas for all join types if building
// from the right input is necessary, all right tuples are used).
leftSrcEndIdx int
// leftNumRepeats and rightNumRepeats indicate the number of times a "group"
// needs to be repeated (where "group" means a single tuple on the left side
// and all tuples on the right side).
leftNumRepeats, rightNumRepeats int
}
// cjMutableBuilderState contains the modifiable state of the builder from one
// side.
type cjMutableBuilderState struct {
// currentBatch is the batch that we're building from at the moment.
currentBatch coldata.Batch
// curSrcStartIdx is the index of the tuple in currentBatch that we're
// building from at the moment.
curSrcStartIdx int
// numRepeatsIdx tracks the number of times a "group" has already been
// repeated.
numRepeatsIdx int
}
func (s *cjMutableBuilderState) reset() {
s.currentBatch = nil
s.curSrcStartIdx = 0
s.numRepeatsIdx = 0
}