Skip to content

Commit

Permalink
planner: stop pushing TopN down through Projection if it has undeterm…
Browse files Browse the repository at this point in the history
…inistic functions (#53362)

close #37986
  • Loading branch information
qw4990 authored May 20, 2024
1 parent 2c76b1a commit b3d740f
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
25 changes: 25 additions & 0 deletions pkg/planner/core/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1075,6 +1075,31 @@ func TestTiFlashFineGrainedShuffleWithMaxTiFlashThreads(t *testing.T) {
require.Equal(t, uint64(16), streamCount[0])
}

func TestIssue37986(t *testing.T) {
store := testkit.CreateMockStore(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec("use test")

tk.MustExec(`drop table if exists t3`)
tk.MustExec(`CREATE TABLE t3(c0 INT, primary key(c0))`)
tk.MustExec(`insert into t3 values(1), (2), (3), (4), (5), (6), (7), (8), (9), (10)`)
rs := tk.MustQuery(`SELECT v2.c0 FROM (select rand() as c0 from t3) v2 order by v2.c0 limit 10`).Rows()
lastVal := -1.0
for _, r := range rs {
v := r[0].(string)
val, err := strconv.ParseFloat(v, 64)
require.NoError(t, err)
require.True(t, val >= lastVal)
lastVal = val
}

tk.MustQuery(`explain format='brief' SELECT v2.c0 FROM (select rand() as c0 from t3) v2 order by v2.c0 limit 10`).
Check(testkit.Rows(`TopN 10.00 root Column#2, offset:0, count:10`,
`└─Projection 10000.00 root rand()->Column#2`,
` └─TableReader 10000.00 root data:TableFullScan`,
` └─TableFullScan 10000.00 cop[tikv] table:t3 keep order:false, stats:pseudo`))
}

func TestIssue33175(t *testing.T) {
store := testkit.CreateMockStore(t)
tk := testkit.NewTestKit(t, store)
Expand Down
11 changes: 10 additions & 1 deletion pkg/planner/core/rule_topn_push_down.go
Original file line number Diff line number Diff line change
Expand Up @@ -172,8 +172,17 @@ func (p *LogicalProjection) PushDownTopN(topNLogicalPlan base.LogicalPlan, opt *
}
if topN != nil {
exprCtx := p.SCtx().GetExprCtx()
substitutedExprs := make([]expression.Expression, 0, len(topN.ByItems))
for _, by := range topN.ByItems {
by.Expr = expression.FoldConstant(exprCtx, expression.ColumnSubstitute(exprCtx, by.Expr, p.schema, p.Exprs))
substituted := expression.FoldConstant(exprCtx, expression.ColumnSubstitute(exprCtx, by.Expr, p.schema, p.Exprs))
if !expression.IsImmutableFunc(substituted) {
// after substituting, if the order-by expression is un-deterministic like 'order by rand()', stop pushing down.
return p.baseLogicalPlan.PushDownTopN(topN, opt)
}
substitutedExprs = append(substitutedExprs, substituted)
}
for i, by := range topN.ByItems {
by.Expr = substitutedExprs[i]
}

// remove meaningless constant sort items.
Expand Down

0 comments on commit b3d740f

Please sign in to comment.