/
join.go
549 lines (461 loc) · 12.1 KB
/
join.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
package plan
import (
"io"
"os"
"reflect"
"strings"
opentracing "github.com/opentracing/opentracing-go"
"github.com/mushiyu/go-mysql-server/sql"
)
const (
inMemoryJoinKey = "INMEMORY_JOINS"
inMemoryJoinSessionVar = "inmemory_joins"
)
var useInMemoryJoins = shouldUseMemoryJoinsByEnv()
func shouldUseMemoryJoinsByEnv() bool {
v := strings.TrimSpace(strings.ToLower(os.Getenv(inMemoryJoinKey)))
return v == "on" || v == "1"
}
// InnerJoin is an inner join between two tables.
type InnerJoin struct {
BinaryNode
Cond sql.Expression
}
// NewInnerJoin creates a new inner join node from two tables.
func NewInnerJoin(left, right sql.Node, cond sql.Expression) *InnerJoin {
return &InnerJoin{
BinaryNode: BinaryNode{
Left: left,
Right: right,
},
Cond: cond,
}
}
// Schema implements the Node interface.
func (j *InnerJoin) Schema() sql.Schema {
return append(j.Left.Schema(), j.Right.Schema()...)
}
// Resolved implements the Resolvable interface.
func (j *InnerJoin) Resolved() bool {
return j.Left.Resolved() && j.Right.Resolved() && j.Cond.Resolved()
}
// RowIter implements the Node interface.
func (j *InnerJoin) RowIter(ctx *sql.Context) (sql.RowIter, error) {
return joinRowIter(ctx, innerJoin, j.Left, j.Right, j.Cond)
}
// WithChildren implements the Node interface.
func (j *InnerJoin) WithChildren(children ...sql.Node) (sql.Node, error) {
if len(children) != 2 {
return nil, sql.ErrInvalidChildrenNumber.New(j, len(children), 2)
}
return NewInnerJoin(children[0], children[1], j.Cond), nil
}
// WithExpressions implements the Expressioner interface.
func (j *InnerJoin) WithExpressions(exprs ...sql.Expression) (sql.Node, error) {
if len(exprs) != 1 {
return nil, sql.ErrInvalidChildrenNumber.New(j, len(exprs), 1)
}
return NewInnerJoin(j.Left, j.Right, exprs[0]), nil
}
func (j *InnerJoin) String() string {
pr := sql.NewTreePrinter()
_ = pr.WriteNode("InnerJoin(%s)", j.Cond)
_ = pr.WriteChildren(j.Left.String(), j.Right.String())
return pr.String()
}
// Expressions implements the Expressioner interface.
func (j *InnerJoin) Expressions() []sql.Expression {
return []sql.Expression{j.Cond}
}
// LeftJoin is a left join between two tables.
type LeftJoin struct {
BinaryNode
Cond sql.Expression
}
// NewLeftJoin creates a new left join node from two tables.
func NewLeftJoin(left, right sql.Node, cond sql.Expression) *LeftJoin {
return &LeftJoin{
BinaryNode: BinaryNode{
Left: left,
Right: right,
},
Cond: cond,
}
}
// Schema implements the Node interface.
func (j *LeftJoin) Schema() sql.Schema {
return append(j.Left.Schema(), makeNullable(j.Right.Schema())...)
}
// Resolved implements the Resolvable interface.
func (j *LeftJoin) Resolved() bool {
return j.Left.Resolved() && j.Right.Resolved() && j.Cond.Resolved()
}
// RowIter implements the Node interface.
func (j *LeftJoin) RowIter(ctx *sql.Context) (sql.RowIter, error) {
return joinRowIter(ctx, leftJoin, j.Left, j.Right, j.Cond)
}
// WithChildren implements the Node interface.
func (j *LeftJoin) WithChildren(children ...sql.Node) (sql.Node, error) {
if len(children) != 2 {
return nil, sql.ErrInvalidChildrenNumber.New(j, len(children), 1)
}
return NewLeftJoin(children[0], children[1], j.Cond), nil
}
// WithExpressions implements the Expressioner interface.
func (j *LeftJoin) WithExpressions(exprs ...sql.Expression) (sql.Node, error) {
if len(exprs) != 1 {
return nil, sql.ErrInvalidChildrenNumber.New(j, len(exprs), 1)
}
return NewLeftJoin(j.Left, j.Right, exprs[0]), nil
}
func (j *LeftJoin) String() string {
pr := sql.NewTreePrinter()
_ = pr.WriteNode("LeftJoin(%s)", j.Cond)
_ = pr.WriteChildren(j.Left.String(), j.Right.String())
return pr.String()
}
// Expressions implements the Expressioner interface.
func (j *LeftJoin) Expressions() []sql.Expression {
return []sql.Expression{j.Cond}
}
// RightJoin is a left join between two tables.
type RightJoin struct {
BinaryNode
Cond sql.Expression
}
// NewRightJoin creates a new right join node from two tables.
func NewRightJoin(left, right sql.Node, cond sql.Expression) *RightJoin {
return &RightJoin{
BinaryNode: BinaryNode{
Left: left,
Right: right,
},
Cond: cond,
}
}
// Schema implements the Node interface.
func (j *RightJoin) Schema() sql.Schema {
return append(makeNullable(j.Left.Schema()), j.Right.Schema()...)
}
// Resolved implements the Resolvable interface.
func (j *RightJoin) Resolved() bool {
return j.Left.Resolved() && j.Right.Resolved() && j.Cond.Resolved()
}
// RowIter implements the Node interface.
func (j *RightJoin) RowIter(ctx *sql.Context) (sql.RowIter, error) {
return joinRowIter(ctx, rightJoin, j.Left, j.Right, j.Cond)
}
// WithChildren implements the Node interface.
func (j *RightJoin) WithChildren(children ...sql.Node) (sql.Node, error) {
if len(children) != 2 {
return nil, sql.ErrInvalidChildrenNumber.New(j, len(children), 2)
}
return NewRightJoin(children[0], children[1], j.Cond), nil
}
// WithExpressions implements the Expressioner interface.
func (j *RightJoin) WithExpressions(exprs ...sql.Expression) (sql.Node, error) {
if len(exprs) != 1 {
return nil, sql.ErrInvalidChildrenNumber.New(j, len(exprs), 1)
}
return NewRightJoin(j.Left, j.Right, exprs[0]), nil
}
func (j *RightJoin) String() string {
pr := sql.NewTreePrinter()
_ = pr.WriteNode("RightJoin(%s)", j.Cond)
_ = pr.WriteChildren(j.Left.String(), j.Right.String())
return pr.String()
}
// Expressions implements the Expressioner interface.
func (j *RightJoin) Expressions() []sql.Expression {
return []sql.Expression{j.Cond}
}
type joinType byte
const (
innerJoin joinType = iota
leftJoin
rightJoin
)
func (t joinType) String() string {
switch t {
case innerJoin:
return "InnerJoin"
case leftJoin:
return "LeftJoin"
case rightJoin:
return "RightJoin"
default:
return "INVALID"
}
}
func joinRowIter(
ctx *sql.Context,
typ joinType,
left, right sql.Node,
cond sql.Expression,
) (sql.RowIter, error) {
var leftName, rightName string
if leftTable, ok := left.(sql.Nameable); ok {
leftName = leftTable.Name()
} else {
leftName = reflect.TypeOf(left).String()
}
if rightTable, ok := right.(sql.Nameable); ok {
rightName = rightTable.Name()
} else {
rightName = reflect.TypeOf(right).String()
}
span, ctx := ctx.Span("plan."+typ.String(), opentracing.Tags{
"left": leftName,
"right": rightName,
})
var inMemorySession bool
_, val := ctx.Get(inMemoryJoinSessionVar)
if val != nil {
inMemorySession = true
}
var mode = unknownMode
if useInMemoryJoins || inMemorySession {
mode = memoryMode
}
cache, dispose := ctx.Memory.NewRowsCache()
if typ == rightJoin {
r, err := right.RowIter(ctx)
if err != nil {
span.Finish()
return nil, err
}
return sql.NewSpanIter(span, &joinIter{
typ: typ,
primary: r,
secondaryProvider: left,
ctx: ctx,
cond: cond,
mode: mode,
secondaryRows: cache,
dispose: dispose,
}), nil
}
l, err := left.RowIter(ctx)
if err != nil {
span.Finish()
return nil, err
}
return sql.NewSpanIter(span, &joinIter{
typ: typ,
primary: l,
secondaryProvider: right,
ctx: ctx,
cond: cond,
mode: mode,
secondaryRows: cache,
dispose: dispose,
}), nil
}
// joinMode defines the mode in which a join will be performed.
type joinMode byte
const (
// unknownMode is the default mode. It will start iterating without really
// knowing in which mode it will end up computing the join. If it
// iterates the right side fully one time and so far it fits in memory,
// then it will switch to memory mode. Otherwise, if at some point during
// this first iteration it finds that it does not fit in memory, will
// switch to multipass mode.
unknownMode joinMode = iota
// memoryMode computes all the join directly in memory iterating each
// side of the join exactly once.
memoryMode
// multipassMode computes the join by iterating the left side once,
// and the right side one time for each row in the left side.
multipassMode
)
// joinIter is a generic iterator for all join types.
type joinIter struct {
typ joinType
primary sql.RowIter
secondaryProvider rowIterProvider
secondary sql.RowIter
ctx *sql.Context
cond sql.Expression
primaryRow sql.Row
foundMatch bool
rowSize int
// used to compute in-memory
mode joinMode
secondaryRows sql.RowsCache
pos int
dispose sql.DisposeFunc
}
func (i *joinIter) Dispose() {
if i.dispose != nil {
i.dispose()
i.dispose = nil
}
}
func (i *joinIter) loadPrimary() error {
if i.primaryRow == nil {
r, err := i.primary.Next()
if err != nil {
if err == io.EOF {
i.Dispose()
}
return err
}
i.primaryRow = r
i.foundMatch = false
}
return nil
}
func (i *joinIter) loadSecondaryInMemory() error {
iter, err := i.secondaryProvider.RowIter(i.ctx)
if err != nil {
return err
}
for {
row, err := iter.Next()
if err == io.EOF {
break
}
if err != nil {
return err
}
if err := i.secondaryRows.Add(row); err != nil {
return err
}
}
if len(i.secondaryRows.Get()) == 0 {
return io.EOF
}
return nil
}
func (i *joinIter) loadSecondary() (row sql.Row, err error) {
if i.mode == memoryMode {
if len(i.secondaryRows.Get()) == 0 {
if err = i.loadSecondaryInMemory(); err != nil {
return nil, err
}
}
if i.pos >= len(i.secondaryRows.Get()) {
i.primaryRow = nil
i.pos = 0
return nil, io.EOF
}
row := i.secondaryRows.Get()[i.pos]
i.pos++
return row, nil
}
if i.secondary == nil {
var iter sql.RowIter
iter, err = i.secondaryProvider.RowIter(i.ctx)
if err != nil {
return nil, err
}
i.secondary = iter
}
rightRow, err := i.secondary.Next()
if err != nil {
if err == io.EOF {
i.secondary = nil
i.primaryRow = nil
// If we got to this point and the mode is still unknown it means
// the right side fits in memory, so the mode changes to memory
// join.
if i.mode == unknownMode {
i.mode = memoryMode
}
return nil, io.EOF
}
return nil, err
}
if i.mode == unknownMode {
var switchToMultipass bool
if !i.ctx.Memory.HasAvailable() {
switchToMultipass = true
} else {
err := i.secondaryRows.Add(rightRow)
if err != nil && !sql.ErrNoMemoryAvailable.Is(err) {
return nil, err
}
}
if switchToMultipass {
i.Dispose()
i.secondaryRows = nil
i.mode = multipassMode
}
}
return rightRow, nil
}
func (i *joinIter) Next() (sql.Row, error) {
for {
if err := i.loadPrimary(); err != nil {
return nil, err
}
primary := i.primaryRow
secondary, err := i.loadSecondary()
if err != nil {
if err == io.EOF {
if !i.foundMatch && (i.typ == leftJoin || i.typ == rightJoin) {
return i.buildRow(primary, nil), nil
}
continue
}
return nil, err
}
row := i.buildRow(primary, secondary)
v, err := i.cond.Eval(i.ctx, row)
if err != nil {
return nil, err
}
if v == false {
continue
}
i.foundMatch = true
return row, nil
}
}
// buildRow builds the resulting row using the rows from the primary and
// secondary branches depending on the join type.
func (i *joinIter) buildRow(primary, secondary sql.Row) sql.Row {
var row sql.Row
if i.rowSize > 0 {
row = make(sql.Row, i.rowSize)
} else {
row = make(sql.Row, len(primary)+len(secondary))
i.rowSize = len(row)
}
switch i.typ {
case rightJoin:
copy(row, secondary)
copy(row[i.rowSize-len(primary):], primary)
default:
copy(row, primary)
copy(row[len(primary):], secondary)
}
return row
}
func (i *joinIter) Close() (err error) {
i.Dispose()
i.secondary = nil
if i.primary != nil {
if err = i.primary.Close(); err != nil {
if i.secondary != nil {
_ = i.secondary.Close()
}
return err
}
}
if i.secondary != nil {
err = i.secondary.Close()
}
return err
}
// makeNullable will return a copy of the received columns, but all of them
// will be turned into nullable columns.
func makeNullable(cols []*sql.Column) []*sql.Column {
var result = make([]*sql.Column, len(cols))
for i := 0; i < len(cols); i++ {
col := *cols[i]
col.Nullable = true
result[i] = &col
}
return result
}