forked from talent-plan/tinysql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
merge_join.go
373 lines (322 loc) · 9.83 KB
/
merge_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
// Copyright 2017 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
package executor
import (
"context"
"github.com/pingcap/errors"
"github.com/pingcap/tidb/expression"
"github.com/pingcap/tidb/sessionctx/stmtctx"
"github.com/pingcap/tidb/util/chunk"
)
// MergeJoinExec implements the merge join algorithm.
// This operator assumes that two iterators of both sides
// will provide required order on join condition:
// 1. For equal-join, one of the join key from each side
// matches the order given.
// 2. For other cases its preferred not to use SMJ and operator
// will throw error.
type MergeJoinExec struct {
baseExecutor
stmtCtx *stmtctx.StatementContext
compareFuncs []expression.CompareFunc
joiner joiner
isOuterJoin bool
prepared bool
outerIdx int
innerTable *mergeJoinInnerTable
outerTable *mergeJoinOuterTable
innerRows []chunk.Row
innerIter4Row chunk.Iterator
childrenResults []*chunk.Chunk
}
type mergeJoinOuterTable struct {
reader Executor
filter []expression.Expression
keys []*expression.Column
chk *chunk.Chunk
selected []bool
iter *chunk.Iterator4Chunk
row chunk.Row
hasMatch bool
}
// mergeJoinInnerTable represents the inner table of merge join.
// All the inner rows which have the same join key are returned when function
// "rowsWithSameKey()" being called.
type mergeJoinInnerTable struct {
reader Executor
joinKeys []*expression.Column
ctx context.Context
// for chunk executions
sameKeyRows []chunk.Row
keyCmpFuncs []chunk.CompareFunc
firstRow4Key chunk.Row
curRow chunk.Row
curResult *chunk.Chunk
curIter *chunk.Iterator4Chunk
curResultInUse bool
resultQueue []*chunk.Chunk
resourceQueue []*chunk.Chunk
}
func (t *mergeJoinInnerTable) init(ctx context.Context, chk4Reader *chunk.Chunk) (err error) {
if t.reader == nil || ctx == nil {
return errors.Errorf("Invalid arguments: Empty arguments detected.")
}
t.ctx = ctx
t.curResult = chk4Reader
t.curIter = chunk.NewIterator4Chunk(t.curResult)
t.curRow = t.curIter.End()
t.curResultInUse = false
t.resultQueue = append(t.resultQueue, chk4Reader)
t.firstRow4Key, err = t.nextRow()
t.keyCmpFuncs = make([]chunk.CompareFunc, 0, len(t.joinKeys))
for i := range t.joinKeys {
t.keyCmpFuncs = append(t.keyCmpFuncs, chunk.GetCompareFunc(t.joinKeys[i].RetType))
}
return err
}
func (t *mergeJoinInnerTable) rowsWithSameKey() ([]chunk.Row, error) {
lastResultIdx := len(t.resultQueue) - 1
t.resourceQueue = append(t.resourceQueue, t.resultQueue[0:lastResultIdx]...)
t.resultQueue = t.resultQueue[lastResultIdx:]
// no more data.
if t.firstRow4Key == t.curIter.End() {
return nil, nil
}
t.sameKeyRows = t.sameKeyRows[:0]
t.sameKeyRows = append(t.sameKeyRows, t.firstRow4Key)
for {
selectedRow, err := t.nextRow()
// error happens or no more data.
if err != nil || selectedRow == t.curIter.End() {
t.firstRow4Key = t.curIter.End()
return t.sameKeyRows, err
}
compareResult := compareChunkRow(t.keyCmpFuncs, selectedRow, t.firstRow4Key, t.joinKeys, t.joinKeys)
if compareResult == 0 {
t.sameKeyRows = append(t.sameKeyRows, selectedRow)
} else {
t.firstRow4Key = selectedRow
return t.sameKeyRows, nil
}
}
}
func (t *mergeJoinInnerTable) nextRow() (chunk.Row, error) {
for {
if t.curRow == t.curIter.End() {
t.reallocReaderResult()
err := Next(t.ctx, t.reader, t.curResult)
// error happens or no more data.
if err != nil || t.curResult.NumRows() == 0 {
t.curRow = t.curIter.End()
return t.curRow, err
}
t.curRow = t.curIter.Begin()
}
result := t.curRow
t.curResultInUse = true
t.curRow = t.curIter.Next()
if !t.hasNullInJoinKey(result) {
return result, nil
}
}
}
func (t *mergeJoinInnerTable) hasNullInJoinKey(row chunk.Row) bool {
for _, col := range t.joinKeys {
ordinal := col.Index
if row.IsNull(ordinal) {
return true
}
}
return false
}
// reallocReaderResult resets "t.curResult" to an empty Chunk to buffer the result of "t.reader".
// It pops a Chunk from "t.resourceQueue" and push it into "t.resultQueue" immediately.
func (t *mergeJoinInnerTable) reallocReaderResult() {
if !t.curResultInUse {
// If "t.curResult" is not in use, we can just reuse it.
t.curResult.Reset()
return
}
// Create a new Chunk and append it to "resourceQueue" if there is no more
// available chunk in "resourceQueue".
if len(t.resourceQueue) == 0 {
newChunk := newFirstChunk(t.reader)
t.resourceQueue = append(t.resourceQueue, newChunk)
}
// NOTE: "t.curResult" is always the last element of "resultQueue".
t.curResult = t.resourceQueue[0]
t.curIter = chunk.NewIterator4Chunk(t.curResult)
t.resourceQueue = t.resourceQueue[1:]
t.resultQueue = append(t.resultQueue, t.curResult)
t.curResult.Reset()
t.curResultInUse = false
}
// Close implements the Executor Close interface.
func (e *MergeJoinExec) Close() error {
e.childrenResults = nil
return e.baseExecutor.Close()
}
// Open implements the Executor Open interface.
func (e *MergeJoinExec) Open(ctx context.Context) error {
if err := e.baseExecutor.Open(ctx); err != nil {
return err
}
e.prepared = false
e.childrenResults = make([]*chunk.Chunk, 0, len(e.children))
for _, child := range e.children {
e.childrenResults = append(e.childrenResults, newFirstChunk(child))
}
return nil
}
func compareChunkRow(cmpFuncs []chunk.CompareFunc, lhsRow, rhsRow chunk.Row, lhsKey, rhsKey []*expression.Column) int {
for i := range lhsKey {
cmp := cmpFuncs[i](lhsRow, lhsKey[i].Index, rhsRow, rhsKey[i].Index)
if cmp != 0 {
return cmp
}
}
return 0
}
func (e *MergeJoinExec) prepare(ctx context.Context, requiredRows int) error {
err := e.innerTable.init(ctx, e.childrenResults[e.outerIdx^1])
if err != nil {
return err
}
err = e.fetchNextInnerRows()
if err != nil {
return err
}
// init outer table.
e.outerTable.chk = e.childrenResults[e.outerIdx]
e.outerTable.iter = chunk.NewIterator4Chunk(e.outerTable.chk)
e.outerTable.selected = make([]bool, 0, e.maxChunkSize)
err = e.fetchNextOuterRows(ctx, requiredRows)
if err != nil {
return err
}
e.prepared = true
return nil
}
// Next implements the Executor Next interface.
func (e *MergeJoinExec) Next(ctx context.Context, req *chunk.Chunk) error {
req.Reset()
if !e.prepared {
if err := e.prepare(ctx, req.RequiredRows()); err != nil {
return err
}
}
for !req.IsFull() {
hasMore, err := e.joinToChunk(ctx, req)
if err != nil || !hasMore {
return err
}
}
return nil
}
func (e *MergeJoinExec) joinToChunk(ctx context.Context, chk *chunk.Chunk) (hasMore bool, err error) {
for {
if e.outerTable.row == e.outerTable.iter.End() {
err = e.fetchNextOuterRows(ctx, chk.RequiredRows()-chk.NumRows())
if err != nil || e.outerTable.chk.NumRows() == 0 {
return false, err
}
}
cmpResult := -1
if e.outerTable.selected[e.outerTable.row.Idx()] && len(e.innerRows) > 0 {
cmpResult, err = e.compare(e.outerTable.row, e.innerIter4Row.Current())
if err != nil {
return false, err
}
}
if cmpResult > 0 {
if err = e.fetchNextInnerRows(); err != nil {
return false, err
}
continue
}
if cmpResult < 0 {
e.joiner.onMissMatch(e.outerTable.row, chk)
if err != nil {
return false, err
}
e.outerTable.row = e.outerTable.iter.Next()
e.outerTable.hasMatch = false
if chk.IsFull() {
return true, nil
}
continue
}
matched, _, err := e.joiner.tryToMatchInners(e.outerTable.row, e.innerIter4Row, chk)
if err != nil {
return false, err
}
e.outerTable.hasMatch = e.outerTable.hasMatch || matched
if e.innerIter4Row.Current() == e.innerIter4Row.End() {
if !e.outerTable.hasMatch {
e.joiner.onMissMatch(e.outerTable.row, chk)
}
e.outerTable.row = e.outerTable.iter.Next()
e.outerTable.hasMatch = false
e.innerIter4Row.Begin()
}
if chk.IsFull() {
return true, err
}
}
}
func (e *MergeJoinExec) compare(outerRow, innerRow chunk.Row) (int, error) {
outerJoinKeys := e.outerTable.keys
innerJoinKeys := e.innerTable.joinKeys
for i := range outerJoinKeys {
cmp, _, err := e.compareFuncs[i](e.ctx, outerJoinKeys[i], innerJoinKeys[i], outerRow, innerRow)
if err != nil {
return 0, err
}
if cmp != 0 {
return int(cmp), nil
}
}
return 0, nil
}
// fetchNextInnerRows fetches the next join group, within which all the rows
// have the same join key, from the inner table.
func (e *MergeJoinExec) fetchNextInnerRows() (err error) {
e.innerRows, err = e.innerTable.rowsWithSameKey()
if err != nil {
return err
}
e.innerIter4Row = chunk.NewIterator4Slice(e.innerRows)
e.innerIter4Row.Begin()
return nil
}
// fetchNextOuterRows fetches the next Chunk of outer table. Rows in a Chunk
// may not all belong to the same join key, but are guaranteed to be sorted
// according to the join key.
func (e *MergeJoinExec) fetchNextOuterRows(ctx context.Context, requiredRows int) (err error) {
// It's hard to calculate selectivity if there is any filter or it's inner join,
// so we just push the requiredRows down when it's outer join and has no filter.
if e.isOuterJoin && len(e.outerTable.filter) == 0 {
e.outerTable.chk.SetRequiredRows(requiredRows, e.maxChunkSize)
}
err = Next(ctx, e.outerTable.reader, e.outerTable.chk)
if err != nil {
return err
}
e.outerTable.iter.Begin()
e.outerTable.selected, err = expression.VectorizedFilter(e.ctx, e.outerTable.filter, e.outerTable.iter, e.outerTable.selected)
if err != nil {
return err
}
e.outerTable.row = e.outerTable.iter.Begin()
return nil
}