Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions DEPS.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -5971,13 +5971,13 @@ def go_deps():
name = "com_github_pingcap_tipb",
build_file_proto_mode = "disable_global",
importpath = "github.com/pingcap/tipb",
sha256 = "af0d5b3d3d28d8c7e43b446873541c0f53a1c552e78fd2eda33931302c9f62e3",
strip_prefix = "github.com/pingcap/tipb@v0.0.0-20260507102040-d3d6e146648f",
sha256 = "8fc936a7308e69dd6a95e5594576ccf3f6229bcb9ef90804c52fb065bb09b403",
strip_prefix = "github.com/pingcap/tipb@v0.0.0-20260605083900-f9f651ef5fbc",
urls = [
"http://bazel-cache.pingcap.net:8080/gomod/github.com/pingcap/tipb/com_github_pingcap_tipb-v0.0.0-20260507102040-d3d6e146648f.zip",
"http://ats.apps.svc/gomod/github.com/pingcap/tipb/com_github_pingcap_tipb-v0.0.0-20260507102040-d3d6e146648f.zip",
"https://cache.hawkingrei.com/gomod/github.com/pingcap/tipb/com_github_pingcap_tipb-v0.0.0-20260507102040-d3d6e146648f.zip",
"https://storage.googleapis.com/pingcapmirror/gomod/github.com/pingcap/tipb/com_github_pingcap_tipb-v0.0.0-20260507102040-d3d6e146648f.zip",
"http://bazel-cache.pingcap.net:8080/gomod/github.com/pingcap/tipb/com_github_pingcap_tipb-v0.0.0-20260605083900-f9f651ef5fbc.zip",
"http://ats.apps.svc/gomod/github.com/pingcap/tipb/com_github_pingcap_tipb-v0.0.0-20260605083900-f9f651ef5fbc.zip",
"https://cache.hawkingrei.com/gomod/github.com/pingcap/tipb/com_github_pingcap_tipb-v0.0.0-20260605083900-f9f651ef5fbc.zip",
"https://storage.googleapis.com/pingcapmirror/gomod/github.com/pingcap/tipb/com_github_pingcap_tipb-v0.0.0-20260605083900-f9f651ef5fbc.zip",
],
)
go_repository(
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ require (
github.com/pingcap/log v1.1.1-0.20250917021125-19901e015dc9
github.com/pingcap/sysutil v1.0.1-0.20240311050922-ae81ee01f3a5
github.com/pingcap/tidb/pkg/parser v0.0.0-20211011031125-9b13dc409c5e
github.com/pingcap/tipb v0.0.0-20260507102040-d3d6e146648f
github.com/pingcap/tipb v0.0.0-20260605083900-f9f651ef5fbc
github.com/prometheus/client_golang v1.23.0
github.com/prometheus/client_model v0.6.2
github.com/prometheus/common v0.65.0
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -663,8 +663,8 @@ github.com/pingcap/log v1.1.1-0.20250917021125-19901e015dc9 h1:qG9BSvlWFEE5otQGa
github.com/pingcap/log v1.1.1-0.20250917021125-19901e015dc9/go.mod h1:ORfBOFp1eteu2odzsyaxI+b8TzJwgjwyQcGhI+9SfEA=
github.com/pingcap/sysutil v1.0.1-0.20240311050922-ae81ee01f3a5 h1:T4pXRhBflzDeAhmOQHNPRRogMYxP13V7BkYw3ZsoSfE=
github.com/pingcap/sysutil v1.0.1-0.20240311050922-ae81ee01f3a5/go.mod h1:rlimy0GcTvjiJqvD5mXTRr8O2eNZPBrcUgiWVYp9530=
github.com/pingcap/tipb v0.0.0-20260507102040-d3d6e146648f h1:ld8bQ5d0zh1B0HRbJHiaf2seZvcVV5Ug2rih70uNJMM=
github.com/pingcap/tipb v0.0.0-20260507102040-d3d6e146648f/go.mod h1:A7mrd7WHBl1o63LE2bIBGEJMTNWXqhgmYiOvMLxozfs=
github.com/pingcap/tipb v0.0.0-20260605083900-f9f651ef5fbc h1:wxolKysltFSu8gxWJBdUdWuTBoSuY3MjNIIZI5S9JLY=
github.com/pingcap/tipb v0.0.0-20260605083900-f9f651ef5fbc/go.mod h1:A7mrd7WHBl1o63LE2bIBGEJMTNWXqhgmYiOvMLxozfs=
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ=
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU=
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
Expand Down
2 changes: 1 addition & 1 deletion pkg/planner/core/casetest/rule/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ go_test(
],
data = glob(["testdata/**"]),
flaky = True,
shard_count = 12,
shard_count = 13,
deps = [
"//pkg/config",
"//pkg/domain",
Expand Down
55 changes: 54 additions & 1 deletion pkg/planner/core/exhaust_physical_plans.go
Original file line number Diff line number Diff line change
Expand Up @@ -2266,7 +2266,10 @@ func getPhysTopN(lt *logicalop.LogicalTopN, prop *property.PhysicalProperty) []b
if mppAllowed {
allTaskTypes = append(allTaskTypes, property.MppTaskType)
}
ret := make([]base.PhysicalPlan, 0, len(allTaskTypes))
ret := make([]base.PhysicalPlan, 0, len(allTaskTypes)+1)
if canUsePartialOrder4TopN(lt) {
ret = append(ret, getPhysTopNWithPartialOrderProperty(lt, prop)...)
}
for _, tp := range allTaskTypes {
resultProp := &property.PhysicalProperty{TaskTp: tp, ExpectedCnt: math.MaxFloat64, CTEProducerStatus: prop.CTEProducerStatus}
topN := PhysicalTopN{
Expand Down Expand Up @@ -2318,6 +2321,56 @@ func getPhysTopN(lt *logicalop.LogicalTopN, prop *property.PhysicalProperty) []b
return ret
}

// canUsePartialOrder4TopN checks if the TopN's child tree satisfies the supported partial-order pattern.
func canUsePartialOrder4TopN(lt *logicalop.LogicalTopN) bool {
if !lt.SCtx().GetSessionVars().IsPartialOrderedIndexForTopNEnabled() {
return false
}
if len(lt.ByItems) == 0 {
return false
}
return checkPartialOrderPattern(lt.Children()[0])
}

func checkPartialOrderPattern(plan base.LogicalPlan) bool {
switch p := plan.(type) {
case *logicalop.DataSource:
return true
case *logicalop.LogicalSelection:
return len(p.Children()) == 1 && checkPartialOrderPattern(p.Children()[0])
case *logicalop.LogicalProjection:
return len(p.Children()) == 1 && checkPartialOrderPattern(p.Children()[0])
default:
return false
}
}

func getPhysTopNWithPartialOrderProperty(lt *logicalop.LogicalTopN, prop *property.PhysicalProperty) []base.PhysicalPlan {
sortItems := make([]*property.SortItem, 0, len(lt.ByItems))
for _, byItem := range lt.ByItems {
col, ok := byItem.Expr.(*expression.Column)
if !ok {
return nil
}
sortItems = append(sortItems, &property.SortItem{Col: col, Desc: byItem.Desc})
}
partialOrderProp := &property.PhysicalProperty{
TaskTp: property.CopMultiReadTaskType,
ExpectedCnt: math.MaxFloat64,
PartialOrderInfo: &property.PartialOrderInfo{
SortItems: sortItems,
},
CTEProducerStatus: prop.CTEProducerStatus,
}
topN := PhysicalTopN{
ByItems: lt.ByItems,
PartitionBy: lt.PartitionBy,
Count: lt.Count,
Offset: lt.Offset,
}.Init(lt.SCtx(), lt.StatsInfo(), lt.QueryBlockOffset(), partialOrderProp)
return []base.PhysicalPlan{topN}
}

func getPhysLimits(lt *logicalop.LogicalTopN, prop *property.PhysicalProperty) []base.PhysicalPlan {
p, canPass := GetPropByOrderByItems(lt.ByItems)
if !canPass {
Expand Down
22 changes: 22 additions & 0 deletions pkg/planner/core/explain.go
Original file line number Diff line number Diff line change
Expand Up @@ -483,10 +483,21 @@ func (p *PhysicalLimit) ExplainInfo() string {
}
if redact == perrors.RedactLogDisable {
fmt.Fprintf(buffer, "offset:%v, count:%v", p.Offset, p.Count)
if p.PrefixCol != nil {
fmt.Fprintf(buffer, ", prefix_col:%v, prefix_len:%v",
p.PrefixCol.ColumnExplainInfo(ectx, false), p.PrefixLen)
}
} else if redact == perrors.RedactLogMarker {
fmt.Fprintf(buffer, "offset:‹%v›, count:‹%v›", p.Offset, p.Count)
if p.PrefixCol != nil {
fmt.Fprintf(buffer, ", prefix_col:‹%v›, prefix_len:‹%v›",
p.PrefixCol.ColumnExplainInfo(ectx, false), p.PrefixLen)
}
} else if redact == perrors.RedactLogEnable {
fmt.Fprintf(buffer, "offset:?, count:?")
if p.PrefixCol != nil {
fmt.Fprintf(buffer, ", prefix_col:?, prefix_len:?")
}
}
return buffer.String()
}
Expand Down Expand Up @@ -790,10 +801,21 @@ func (p *PhysicalTopN) ExplainInfo() string {
switch p.SCtx().GetSessionVars().EnableRedactLog {
case perrors.RedactLogDisable:
fmt.Fprintf(buffer, ", offset:%v, count:%v", p.Offset, p.Count)
if p.PrefixCol != nil {
fmt.Fprintf(buffer, ", prefix_col:%v, prefix_len:%v",
p.PrefixCol.ColumnExplainInfo(ectx, false), p.PrefixLen)
}
case perrors.RedactLogMarker:
fmt.Fprintf(buffer, ", offset:‹%v›, count:‹%v›", p.Offset, p.Count)
if p.PrefixCol != nil {
fmt.Fprintf(buffer, ", prefix_col:‹%v›, prefix_len:‹%v›",
p.PrefixCol.ColumnExplainInfo(ectx, false), p.PrefixLen)
}
case perrors.RedactLogEnable:
fmt.Fprintf(buffer, ", offset:?, count:?")
if p.PrefixCol != nil {
fmt.Fprintf(buffer, ", prefix_col:?, prefix_len:?")
}
}
return buffer.String()
}
Expand Down
107 changes: 96 additions & 11 deletions pkg/planner/core/find_best_task.go
Original file line number Diff line number Diff line change
Expand Up @@ -683,9 +683,11 @@ type candidatePath struct {
accessCondsColMap util.Col2Len // accessCondsColMap maps Column.UniqueID to column length for the columns in AccessConds.
indexCondsColMap util.Col2Len // indexCondsColMap maps Column.UniqueID to column length for the columns in AccessConds and indexFilters.
matchPropResult property.PhysicalPropMatchResult
indexJoinCols int // how many index columns are used in access conditions in this IndexJoin.
isFullRange bool // cached result of whether this path covers the full scan range.
eqOrInCount int // cached result of equalPredicateCount().
// partialOrderMatchResult records whether this path can provide partial order using prefix index.
partialOrderMatchResult property.PartialOrderMatchResult
indexJoinCols int // how many index columns are used in access conditions in this IndexJoin.
isFullRange bool // cached result of whether this path covers the full scan range.
eqOrInCount int // cached result of equalPredicateCount().
}

func compareBool(l, r bool) int {
Expand Down Expand Up @@ -1014,6 +1016,62 @@ func matchProperty(ds *logicalop.DataSource, path *util.AccessPath, prop *proper
return matchResult
}

// matchPartialOrderProperty checks if the index can provide partial order for TopN optimization.
// Unlike matchProperty, this function allows a prefix index to match ORDER BY columns.
func matchPartialOrderProperty(path *util.AccessPath, partialOrderInfo *property.PartialOrderInfo) property.PartialOrderMatchResult {
emptyResult := property.PartialOrderMatchResult{Matched: false}
if partialOrderInfo == nil || path.Index == nil || len(path.IdxCols) == 0 {
return emptyResult
}

sortItems := partialOrderInfo.SortItems
if len(sortItems) == 0 {
return emptyResult
}

allSameOrder, _ := partialOrderInfo.AllSameOrder()
if !allSameOrder {
return emptyResult
}

indexColCount := len(path.Index.Columns)
if len(path.FullIdxCols) < indexColCount || len(path.FullIdxColLens) < indexColCount {
return emptyResult
}
if indexColCount > len(sortItems) {
return emptyResult
}
if path.Index.Columns[indexColCount-1].Length == types.UnspecifiedLength {
return emptyResult
}

orderByCols := make([]*expression.Column, 0, len(sortItems))
for _, item := range sortItems {
orderByCols = append(orderByCols, item.Col)
}

for i := range indexColCount {
idxCol := path.FullIdxCols[i]
if idxCol == nil {
return emptyResult
}
if !orderByCols[i].EqualColumn(idxCol) {
return emptyResult
}
if path.FullIdxColLens[i] != types.UnspecifiedLength {
if i != indexColCount-1 {
return emptyResult
}
return property.PartialOrderMatchResult{
Matched: true,
PrefixCol: idxCol,
PrefixLen: path.FullIdxColLens[i],
}
}
}
return emptyResult
}

// GroupRangesByCols groups the ranges by the values of the columns specified by groupByColIdxs.
func GroupRangesByCols(ranges []*ranger.Range, groupByColIdxs []int) ([][]*ranger.Range, error) {
groups := make(map[string][]*ranger.Range)
Expand Down Expand Up @@ -1262,6 +1320,9 @@ func getTableCandidate(ds *logicalop.DataSource, path *util.AccessPath, prop *pr
func getIndexCandidate(ds *logicalop.DataSource, path *util.AccessPath, prop *property.PhysicalProperty) *candidatePath {
candidate := &candidatePath{path: path}
candidate.matchPropResult = matchProperty(ds, path, prop)
if ds.SCtx().GetSessionVars().IsPartialOrderedIndexForTopNEnabled() && prop.PartialOrderInfo != nil {
candidate.partialOrderMatchResult = matchPartialOrderProperty(path, prop.PartialOrderInfo)
}
candidate.accessCondsColMap = util.ExtractCol2Len(ds.SCtx().GetExprCtx().GetEvalCtx(), path.AccessConds, path.IdxCols, path.IdxColLens)
candidate.indexCondsColMap = util.ExtractCol2Len(ds.SCtx().GetExprCtx().GetEvalCtx(), append(path.AccessConds, path.IndexFilters...), path.FullIdxCols, path.FullIdxColLens)
candidate.isFullRange = path.IsFullScanRange(ds.TableInfo)
Expand Down Expand Up @@ -1337,16 +1398,32 @@ func skylinePruning(ds *logicalop.DataSource, prop *property.PhysicalProperty) [
}
var currentCandidate *candidatePath
if path.IsTablePath() {
if prop.PartialOrderInfo != nil {
continue
}
currentCandidate = getTableCandidate(ds, path, prop)
} else {
if !(len(path.AccessConds) > 0 || !prop.IsSortItemEmpty() || path.Forced || path.IsSingleScan) {
var matchPartialOrderIndex bool
if ds.SCtx().GetSessionVars().IsPartialOrderedIndexForTopNEnabled() &&
prop.PartialOrderInfo != nil {
if !matchPartialOrderProperty(path, prop.PartialOrderInfo).Matched {
continue
}
matchPartialOrderIndex = true
if path.Forced && !path.ForceNoKeepOrder {
path.ForcePartialOrder = true
}
Comment on lines +1401 to +1415
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Don't persist ForcePartialOrder on the shared AccessPath.

skylinePruning() sets path.ForcePartialOrder = true in-place, but ds.PossibleAccessPaths are reused across later property explorations. After one partial-order pass marks a forced path here, a later normal pass can hit the prop.PartialOrderInfo == nil rejection in convertToIndexScan() and incorrectly discard that hinted path. Keep this flag candidate-local, or at least clear it before each pruning pass.

Minimal safe reset
for _, path := range ds.PossibleAccessPaths {
+	path.ForcePartialOrder = false
 	// We should check whether the possible access path is valid first.
 	if path.StoreType != kv.TiFlash && prop.IsFlashProp() {
 		continue
 	}

Also applies to: 2401-2404

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/planner/core/find_best_task.go` around lines 1401 - 1415, The review
points out that skylinePruning()/the loop is mutating the shared AccessPath by
setting path.ForcePartialOrder = true which later causes convertToIndexScan() to
reject paths when prop.PartialOrderInfo == nil; to fix, avoid persisting
ForcePartialOrder on the shared ds.PossibleAccessPaths: either operate on a
shallow copy of the AccessPath or use a candidate-local boolean (e.g.,
localForcePartialOrder) when evaluating/constructing currentCandidate in
getTableCandidate/skylinePruning rather than writing to path.ForcePartialOrder,
and if you must modify path, ensure you clear/reset path.ForcePartialOrder
before finishing each pruning pass so convertToIndexScan() sees the original
state.

}
keepIndex := len(path.AccessConds) > 0 || !prop.IsSortItemEmpty() || path.Forced || path.IsSingleScan || matchPartialOrderIndex
if !keepIndex {
continue
}
// We will use index to generate physical plan if any of the following conditions is satisfied:
// 1. This path's access cond is not nil.
// 2. We have a non-empty prop to match.
// 3. This index is forced to choose.
// 4. The needed columns are all covered by index columns(and handleCol).
// 5. It matches PartialOrderInfo physical property for partial order optimization.
currentCandidate = getIndexCandidate(ds, path, prop)
}
pruned := false
Expand Down Expand Up @@ -2314,11 +2391,15 @@ func convertToIndexScan(ds *logicalop.DataSource, prop *property.PhysicalPropert
return base.InvalidTask, nil
}
// If we need to keep order for the index scan, we should forbid the non-keep-order index scan when we try to generate the path.
if prop.IsSortItemEmpty() && candidate.path.ForceKeepOrder {
if !prop.NeedKeepOrder() && candidate.path.ForceKeepOrder {
return base.InvalidTask, nil
}
// If we don't need to keep order for the index scan, we should forbid the non-keep-order index scan when we try to generate the path.
if !prop.IsSortItemEmpty() && candidate.path.ForceNoKeepOrder {
if prop.NeedKeepOrder() && candidate.path.ForceNoKeepOrder {
return base.InvalidTask, nil
}
// If partial order is forced, reject normal full-order or no-order candidates.
if candidate.path.ForcePartialOrder && prop.PartialOrderInfo == nil {
return base.InvalidTask, nil
}
path := candidate.path
Expand All @@ -2329,6 +2410,9 @@ func convertToIndexScan(ds *logicalop.DataSource, prop *property.PhysicalPropert
tblCols: ds.TblCols,
expectCnt: uint64(prop.ExpectedCnt),
}
if candidate.partialOrderMatchResult.Matched {
cop.partialOrderMatchResult = &candidate.partialOrderMatchResult
}
cop.physPlanPartInfo = &PhysPlanPartInfo{
PruningConds: pushDownNot(ds.SCtx().GetExprCtx(), ds.AllConds),
PartitionNames: ds.PartitionNames,
Expand Down Expand Up @@ -2372,7 +2456,7 @@ func convertToIndexScan(ds *logicalop.DataSource, prop *property.PhysicalPropert
}
}
}
if candidate.matchPropResult.Matched() {
if prop.NeedKeepOrder() {
cop.keepOrder = true
if cop.tablePlan != nil && !ds.TableInfo.IsCommonHandle {
col, isNew := cop.tablePlan.(*PhysicalTableScan).appendExtraHandleCol(ds)
Expand All @@ -2387,8 +2471,9 @@ func convertToIndexScan(ds *logicalop.DataSource, prop *property.PhysicalPropert
// Case 3: both
if (ds.TableInfo.GetPartitionInfo() != nil && !is.Index.Global) ||
candidate.matchPropResult == property.PropMatchedNeedMergeSort {
byItems := make([]*util.ByItems, 0, len(prop.SortItems))
for _, si := range prop.SortItems {
sortItems := prop.GetSortItemsForKeepOrder()
byItems := make([]*util.ByItems, 0, len(sortItems))
for _, si := range sortItems {
byItems = append(byItems, &util.ByItems{
Expr: si.Col,
Desc: si.Desc,
Expand Down Expand Up @@ -3265,8 +3350,8 @@ func getOriginalPhysicalIndexScan(ds *logicalop.DataSource, prop *property.Physi
if usedStats != nil && usedStats.GetUsedInfo(is.physicalTableID) != nil {
is.usedStatsInfo = usedStats.GetUsedInfo(is.physicalTableID)
}
if isMatchProp {
is.Desc = prop.SortItems[0].Desc
if prop.NeedKeepOrder() {
is.Desc = prop.GetSortDescForKeepOrder()
is.KeepOrder = true
}
return is
Expand Down
31 changes: 13 additions & 18 deletions pkg/planner/core/hint_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,35 +90,30 @@ func TestSetVarPartialOrderedIndexForTopN(t *testing.T) {
testKit.MustExec(`use test`)

// Test default value
testKit.MustQuery(`select @@tidb_opt_partial_ordered_index_for_topn`).Check(testkit.Rows("0"))
testKit.MustQuery(`select @@tidb_opt_partial_ordered_index_for_topn`).Check(testkit.Rows("DISABLE"))

// Test set_var hint changes the value during query execution
testKit.MustExec(`set @@tidb_opt_partial_ordered_index_for_topn = 0`)
testKit.MustQuery(`select /*+ set_var(tidb_opt_partial_ordered_index_for_topn=ON) */ @@tidb_opt_partial_ordered_index_for_topn`).Check(testkit.Rows("1"))
testKit.MustExec(`set @@tidb_opt_partial_ordered_index_for_topn = DISABLE`)
testKit.MustQuery(`select /*+ set_var(tidb_opt_partial_ordered_index_for_topn=COST) */ @@tidb_opt_partial_ordered_index_for_topn`).Check(testkit.Rows("COST"))
// Value should be restored after query
testKit.MustQuery(`select @@tidb_opt_partial_ordered_index_for_topn`).Check(testkit.Rows("0"))
testKit.MustQuery(`select @@tidb_opt_partial_ordered_index_for_topn`).Check(testkit.Rows("DISABLE"))

// Test set_var hint with OFF
testKit.MustExec(`set @@tidb_opt_partial_ordered_index_for_topn = 1`)
testKit.MustQuery(`select /*+ set_var(tidb_opt_partial_ordered_index_for_topn=OFF) */ @@tidb_opt_partial_ordered_index_for_topn`).Check(testkit.Rows("0"))
testKit.MustExec(`set @@tidb_opt_partial_ordered_index_for_topn = COST`)
testKit.MustQuery(`select /*+ set_var(tidb_opt_partial_ordered_index_for_topn=DISABLE) */ @@tidb_opt_partial_ordered_index_for_topn`).Check(testkit.Rows("DISABLE"))
// Value should be restored after query
testKit.MustQuery(`select @@tidb_opt_partial_ordered_index_for_topn`).Check(testkit.Rows("1"))

// Test set_var hint with numeric values
testKit.MustExec(`set @@tidb_opt_partial_ordered_index_for_topn = 0`)
testKit.MustQuery(`select /*+ set_var(tidb_opt_partial_ordered_index_for_topn=1) */ @@tidb_opt_partial_ordered_index_for_topn`).Check(testkit.Rows("1"))
testKit.MustQuery(`select @@tidb_opt_partial_ordered_index_for_topn`).Check(testkit.Rows("0"))
testKit.MustQuery(`select @@tidb_opt_partial_ordered_index_for_topn`).Check(testkit.Rows("COST"))

// Test set_var hint with multiple queries
testKit.MustExec(`create table t(a int, b varchar(10), index idx_b(b(5)));`)
testKit.MustExec(`set @@tidb_opt_partial_ordered_index_for_topn = 0`)
testKit.MustExec(`select /*+ set_var(tidb_opt_partial_ordered_index_for_topn=ON) */ * from t order by b limit 10;`)
testKit.MustQuery(`select @@tidb_opt_partial_ordered_index_for_topn`).Check(testkit.Rows("0"))
testKit.MustExec(`set @@tidb_opt_partial_ordered_index_for_topn = DISABLE`)
testKit.MustExec(`select /*+ set_var(tidb_opt_partial_ordered_index_for_topn=COST) */ * from t order by b limit 10;`)
testKit.MustQuery(`select @@tidb_opt_partial_ordered_index_for_topn`).Check(testkit.Rows("DISABLE"))

// Test with EXPLAIN (should not change the value)
testKit.MustExec(`set @@tidb_opt_partial_ordered_index_for_topn = 0`)
testKit.MustExec(`explain select /*+ set_var(tidb_opt_partial_ordered_index_for_topn=ON) */ * from t order by b limit 10;`)
testKit.MustQuery(`select @@tidb_opt_partial_ordered_index_for_topn`).Check(testkit.Rows("0"))
testKit.MustExec(`set @@tidb_opt_partial_ordered_index_for_topn = DISABLE`)
testKit.MustExec(`explain select /*+ set_var(tidb_opt_partial_ordered_index_for_topn=COST) */ * from t order by b limit 10;`)
testKit.MustQuery(`select @@tidb_opt_partial_ordered_index_for_topn`).Check(testkit.Rows("DISABLE"))
})
}

Expand Down
Loading