Skip to content

Commit 2f940f9

Browse files
authored
executor: fix index out of range panic of cte when max_chunk_size is samll (#48839) (#49002)
close #48808
1 parent de6e2ba commit 2f940f9

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

executor/cte.go

+10
Original file line numberDiff line numberDiff line change
@@ -539,6 +539,16 @@ func (p *cteProducer) computeChunkHash(chk *chunk.Chunk) (sel []int, err error)
539539
hashBitMap[val] = true
540540
}
541541
} else {
542+
// Length of p.sel is init as MaxChunkSize, but the row num of chunk may still exceeds MaxChunkSize.
543+
// So needs to handle here to make sure len(p.sel) == chk.NumRows().
544+
if len(p.sel) < numRows {
545+
tmpSel := make([]int, numRows-len(p.sel))
546+
for i := 0; i < len(tmpSel); i++ {
547+
tmpSel[i] = i + len(p.sel)
548+
}
549+
p.sel = append(p.sel, tmpSel...)
550+
}
551+
542552
// All rows is selected, sel will be [0....numRows).
543553
// e.sel is setup when building executor.
544554
sel = p.sel

executor/cte_test.go

+17
Original file line numberDiff line numberDiff line change
@@ -519,3 +519,20 @@ func TestCTEShareCorColumn(t *testing.T) {
519519
tk.MustExec("insert into t1 values(1), (2);")
520520
tk.MustQuery("SELECT * FROM t1 dt WHERE EXISTS( WITH RECURSIVE qn AS (SELECT a AS b UNION ALL SELECT b+1 FROM qn WHERE b=0 or b = 1) SELECT * FROM qn dtqn1 where exists (select /*+ NO_DECORRELATE() */ b from qn where dtqn1.b+1));").Check(testkit.Rows("1", "2"))
521521
}
522+
523+
func TestCTESmallChunkSize(t *testing.T) {
524+
store, clean := testkit.CreateMockStore(t)
525+
defer clean()
526+
tk := testkit.NewTestKit(t, store)
527+
tk.MustExec("use test;")
528+
tk.MustExec("drop table if exists t1")
529+
tk.MustExec("create table t1(c1 int);")
530+
insertStr := "insert into t1 values (0)"
531+
for i := 1; i < 300; i++ {
532+
insertStr += fmt.Sprintf(", (%d)", i)
533+
}
534+
tk.MustExec(insertStr)
535+
tk.MustExec("set @@tidb_max_chunk_size = 32;")
536+
tk.MustQuery("with recursive cte1(c1) as (select c1 from t1 union select c1 + 1 c1 from cte1 limit 1 offset 100) select * from cte1;").Check(testkit.Rows("100"))
537+
tk.MustExec("set @@tidb_max_chunk_size = default;")
538+
}

0 commit comments

Comments
 (0)