Skip to content

Commit 6d5ce09

Browse files
qw4990ti-chi-bot
authored andcommitted
planner: stop pushing TopN down through Projection if it has undeterministic functions (pingcap#53362)
close pingcap#37986
1 parent a0089c6 commit 6d5ce09

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

pkg/planner/core/integration_test.go

+25
Original file line numberDiff line numberDiff line change
@@ -1075,6 +1075,31 @@ func TestTiFlashFineGrainedShuffleWithMaxTiFlashThreads(t *testing.T) {
10751075
require.Equal(t, uint64(16), streamCount[0])
10761076
}
10771077

1078+
func TestIssue37986(t *testing.T) {
1079+
store := testkit.CreateMockStore(t)
1080+
tk := testkit.NewTestKit(t, store)
1081+
tk.MustExec("use test")
1082+
1083+
tk.MustExec(`drop table if exists t3`)
1084+
tk.MustExec(`CREATE TABLE t3(c0 INT, primary key(c0))`)
1085+
tk.MustExec(`insert into t3 values(1), (2), (3), (4), (5), (6), (7), (8), (9), (10)`)
1086+
rs := tk.MustQuery(`SELECT v2.c0 FROM (select rand() as c0 from t3) v2 order by v2.c0 limit 10`).Rows()
1087+
lastVal := -1.0
1088+
for _, r := range rs {
1089+
v := r[0].(string)
1090+
val, err := strconv.ParseFloat(v, 64)
1091+
require.NoError(t, err)
1092+
require.True(t, val >= lastVal)
1093+
lastVal = val
1094+
}
1095+
1096+
tk.MustQuery(`explain format='brief' SELECT v2.c0 FROM (select rand() as c0 from t3) v2 order by v2.c0 limit 10`).
1097+
Check(testkit.Rows(`TopN 10.00 root Column#2, offset:0, count:10`,
1098+
`└─Projection 10000.00 root rand()->Column#2`,
1099+
` └─TableReader 10000.00 root data:TableFullScan`,
1100+
` └─TableFullScan 10000.00 cop[tikv] table:t3 keep order:false, stats:pseudo`))
1101+
}
1102+
10781103
func TestIssue33175(t *testing.T) {
10791104
store := testkit.CreateMockStore(t)
10801105
tk := testkit.NewTestKit(t, store)

pkg/planner/core/rule_topn_push_down.go

+10-1
Original file line numberDiff line numberDiff line change
@@ -134,8 +134,17 @@ func (p *LogicalProjection) pushDownTopN(topN *LogicalTopN, opt *util.LogicalOpt
134134
}
135135
if topN != nil {
136136
exprCtx := p.SCtx().GetExprCtx()
137+
substitutedExprs := make([]expression.Expression, 0, len(topN.ByItems))
137138
for _, by := range topN.ByItems {
138-
by.Expr = expression.FoldConstant(exprCtx, expression.ColumnSubstitute(exprCtx, by.Expr, p.schema, p.Exprs))
139+
substituted := expression.FoldConstant(exprCtx, expression.ColumnSubstitute(exprCtx, by.Expr, p.schema, p.Exprs))
140+
if !expression.IsImmutableFunc(substituted) {
141+
// after substituting, if the order-by expression is un-deterministic like 'order by rand()', stop pushing down.
142+
return p.baseLogicalPlan.PushDownTopN(topN, opt)
143+
}
144+
substitutedExprs = append(substitutedExprs, substituted)
145+
}
146+
for i, by := range topN.ByItems {
147+
by.Expr = substitutedExprs[i]
139148
}
140149

141150
// remove meaningless constant sort items.

0 commit comments

Comments
 (0)