diff --git a/DEPS.bzl b/DEPS.bzl index 7044fa1d6f003..1e3d644cbb35a 100644 --- a/DEPS.bzl +++ b/DEPS.bzl @@ -1508,8 +1508,8 @@ def go_deps(): name = "com_github_google_go_cmp", build_file_proto_mode = "disable_global", importpath = "github.com/google/go-cmp", - sum = "h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=", - version = "v0.5.9", + sum = "h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=", + version = "v0.6.0", ) go_repository( name = "com_github_google_go_querystring", @@ -5263,15 +5263,15 @@ def go_deps(): name = "org_golang_x_crypto", build_file_proto_mode = "disable_global", importpath = "golang.org/x/crypto", - sum = "h1:frVn1TEaCEaZcn3Tmd7Y2b5KKPaZ+I32Q2OA3kYp5TA=", - version = "v0.15.0", + sum = "h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI=", + version = "v0.23.0", ) go_repository( name = "org_golang_x_exp", build_file_proto_mode = "disable_global", importpath = "golang.org/x/exp", - sum = "h1:SkwG94eNiiYJhbeDE018Grw09HIN/KB9NlRmZsrzfWs=", - version = "v0.0.0-20221023144134-a1e5550cf13e", + sum = "h1:O9NuF4s+E/PvMIy+9IUZB9znFwUIXEWSstNjek6VpVg=", + version = "v0.0.0-20240531132922-fd00a4e0eefc", ) go_repository( name = "org_golang_x_exp_typeparams", @@ -5305,15 +5305,15 @@ def go_deps(): name = "org_golang_x_mod", build_file_proto_mode = "disable_global", importpath = "golang.org/x/mod", - sum = "h1:dGoOF9QVLYng8IHTm7BAyWqCqSheQ5pYWGhzW00YJr0=", - version = "v0.14.0", + sum = "h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA=", + version = "v0.17.0", ) go_repository( name = "org_golang_x_net", build_file_proto_mode = "disable_global", importpath = "golang.org/x/net", - sum = "h1:mIYleuAkSbHh0tCv7RvjL3F6ZVbLjq4+R7zbOn3Kokg=", - version = "v0.18.0", + sum = "h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac=", + version = "v0.25.0", ) go_repository( name = "org_golang_x_oauth2", @@ -5326,29 +5326,36 @@ def go_deps(): name = "org_golang_x_sync", build_file_proto_mode = "disable_global", importpath = "golang.org/x/sync", - sum = "h1:60k92dhOjHxJkrqnwsfl8KuaHbn/5dl0lUPUklKo3qE=", - version = "v0.5.0", + sum = "h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M=", + version = "v0.7.0", ) go_repository( name = "org_golang_x_sys", build_file_proto_mode = "disable_global", importpath = "golang.org/x/sys", - sum = "h1:Vz7Qs629MkJkGyHxUlRHizWJRG2j8fbQKjELVSNhy7Q=", - version = "v0.14.0", + sum = "h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=", + version = "v0.20.0", + ) + go_repository( + name = "org_golang_x_telemetry", + build_file_proto_mode = "disable", + importpath = "golang.org/x/telemetry", + sum = "h1:IRJeR9r1pYWsHKTRe/IInb7lYvbBVIqOgsX/u0mbOWY=", + version = "v0.0.0-20240228155512-f48c80bd79b2", ) go_repository( name = "org_golang_x_term", build_file_proto_mode = "disable_global", importpath = "golang.org/x/term", - sum = "h1:LGK9IlZ8T9jvdy6cTdfKUCltatMFOehAQo9SRC46UQ8=", - version = "v0.14.0", + sum = "h1:VnkxpohqXaOBYJtBmEppKUG6mXpi+4O6purfc2+sMhw=", + version = "v0.20.0", ) go_repository( name = "org_golang_x_text", build_file_proto_mode = "disable_global", importpath = "golang.org/x/text", - sum = "h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=", - version = "v0.14.0", + sum = "h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk=", + version = "v0.15.0", ) go_repository( name = "org_golang_x_time", @@ -5361,8 +5368,8 @@ def go_deps(): name = "org_golang_x_tools", build_file_proto_mode = "disable_global", importpath = "golang.org/x/tools", - sum = "h1:zdAyfUGbYmuVokhzVmghFl2ZJh5QhcfebBgmVPFYA+8=", - version = "v0.15.0", + sum = "h1:qc0xYgIbsSDt9EyWz05J5wfa7LOVW0YTLOXrqdLAWIw=", + version = "v0.21.0", ) go_repository( name = "org_golang_x_xerrors", diff --git a/br/pkg/lightning/BUILD.bazel b/br/pkg/lightning/BUILD.bazel index 95aca448f786a..c455fd97930b4 100644 --- a/br/pkg/lightning/BUILD.bazel +++ b/br/pkg/lightning/BUILD.bazel @@ -28,6 +28,7 @@ go_library( "//br/pkg/version/build", "//expression", "//planner/core", + "//util/cmp", "//util/promutil", "@com_github_pingcap_errors//:errors", "@com_github_pingcap_failpoint//:failpoint", diff --git a/br/pkg/lightning/backend/BUILD.bazel b/br/pkg/lightning/backend/BUILD.bazel index d2dd56338bf99..0d01026113a81 100644 --- a/br/pkg/lightning/backend/BUILD.bazel +++ b/br/pkg/lightning/backend/BUILD.bazel @@ -15,6 +15,7 @@ go_library( "//br/pkg/lightning/mydump", "//parser/model", "//table", + "//util/cmp", "@com_github_google_uuid//:uuid", "@com_github_pingcap_errors//:errors", "@com_github_pingcap_failpoint//:failpoint", diff --git a/br/pkg/lightning/backend/backend.go b/br/pkg/lightning/backend/backend.go index 4569b1beeded8..d64156abe9f22 100644 --- a/br/pkg/lightning/backend/backend.go +++ b/br/pkg/lightning/backend/backend.go @@ -31,6 +31,7 @@ import ( "github.com/pingcap/tidb/br/pkg/lightning/mydump" "github.com/pingcap/tidb/parser/model" "github.com/pingcap/tidb/table" + "github.com/pingcap/tidb/util/cmp" "go.uber.org/zap" "golang.org/x/exp/slices" ) @@ -311,11 +312,14 @@ func (be Backend) CheckDiskQuota(quota int64) ( totalMemSize int64, ) { sizes := be.abstract.EngineFileSizes() - slices.SortFunc(sizes, func(i, j EngineFileSize) bool { + slices.SortFunc(sizes, func(i, j EngineFileSize) int { if i.IsImporting != j.IsImporting { - return i.IsImporting + if i.IsImporting { + return -1 + } + return 1 } - return i.DiskSize+i.MemSize < j.DiskSize+j.MemSize + return cmp.Compare(i.DiskSize+i.MemSize, j.DiskSize+j.MemSize) }) for _, size := range sizes { totalDiskSize += size.DiskSize diff --git a/br/pkg/lightning/backend/kv/BUILD.bazel b/br/pkg/lightning/backend/kv/BUILD.bazel index d4fe5a0e2217c..c9d060798eded 100644 --- a/br/pkg/lightning/backend/kv/BUILD.bazel +++ b/br/pkg/lightning/backend/kv/BUILD.bazel @@ -32,6 +32,7 @@ go_library( "//tablecodec", "//types", "//util/chunk", + "//util/cmp", "//util/mathutil", "//util/topsql/stmtstats", "@com_github_docker_go_units//:go-units", diff --git a/br/pkg/lightning/backend/kv/sql2kv.go b/br/pkg/lightning/backend/kv/sql2kv.go index 1ff8390f6c564..0e95f09c361df 100644 --- a/br/pkg/lightning/backend/kv/sql2kv.go +++ b/br/pkg/lightning/backend/kv/sql2kv.go @@ -40,6 +40,7 @@ import ( "github.com/pingcap/tidb/tablecodec" "github.com/pingcap/tidb/types" "github.com/pingcap/tidb/util/chunk" + "github.com/pingcap/tidb/util/cmp" "go.uber.org/zap" "go.uber.org/zap/zapcore" "golang.org/x/exp/slices" @@ -186,8 +187,8 @@ func collectGeneratedColumns(se *session, meta *model.TableInfo, cols []*table.C } // order the result by column offset so they match the evaluation order. - slices.SortFunc(genCols, func(i, j genCol) bool { - return cols[i.index].Offset < cols[j.index].Offset + slices.SortFunc(genCols, func(i, j genCol) int { + return cmp.Compare(cols[i.index].Offset, cols[j.index].Offset) }) return genCols, nil } diff --git a/br/pkg/lightning/backend/local/engine.go b/br/pkg/lightning/backend/local/engine.go index 79ef97ddce45e..625fc1b9bc380 100644 --- a/br/pkg/lightning/backend/local/engine.go +++ b/br/pkg/lightning/backend/local/engine.go @@ -752,8 +752,8 @@ func (e *Engine) batchIngestSSTs(metas []*sstMeta) error { if len(metas) == 0 { return nil } - slices.SortFunc(metas, func(i, j *sstMeta) bool { - return bytes.Compare(i.minKey, j.minKey) < 0 + slices.SortFunc(metas, func(i, j *sstMeta) int { + return bytes.Compare(i.minKey, j.minKey) }) metaLevels := make([][]*sstMeta, 0) @@ -914,8 +914,8 @@ func sortAndMergeRanges(ranges []Range) []Range { return ranges } - slices.SortFunc(ranges, func(i, j Range) bool { - return bytes.Compare(i.start, j.start) < 0 + slices.SortFunc(ranges, func(i, j Range) int { + return bytes.Compare(i.start, j.start) }) curEnd := ranges[0].end @@ -1181,8 +1181,8 @@ func (w *Writer) flushKVs(ctx context.Context) error { return errors.Trace(err) } if !w.isWriteBatchSorted { - slices.SortFunc(w.writeBatch[:w.batchCount], func(i, j common.KvPair) bool { - return bytes.Compare(i.Key, j.Key) < 0 + slices.SortFunc(w.writeBatch[:w.batchCount], func(i, j common.KvPair) int { + return bytes.Compare(i.Key, j.Key) }) w.isWriteBatchSorted = true } diff --git a/br/pkg/lightning/backend/local/localhelper.go b/br/pkg/lightning/backend/local/localhelper.go index 5c423f8c26cb6..d7a80c2c534c4 100644 --- a/br/pkg/lightning/backend/local/localhelper.go +++ b/br/pkg/lightning/backend/local/localhelper.go @@ -203,8 +203,8 @@ func (local *local) SplitAndScatterRegionByRanges( var err1 error region := sp.region keys := sp.keys - slices.SortFunc(keys, func(i, j []byte) bool { - return bytes.Compare(i, j) < 0 + slices.SortFunc(keys, func(i, j []byte) int { + return bytes.Compare(i, j) }) splitRegion := region startIdx := 0 @@ -247,8 +247,8 @@ func (local *local) SplitAndScatterRegionByRanges( log.FromContext(ctx).Info("batch split region", zap.Uint64("region_id", splitRegion.Region.Id), zap.Int("keys", endIdx-startIdx), zap.Binary("firstKey", keys[startIdx]), zap.Binary("end", keys[endIdx-1])) - slices.SortFunc(newRegions, func(i, j *split.RegionInfo) bool { - return bytes.Compare(i.Region.StartKey, j.Region.StartKey) < 0 + slices.SortFunc(newRegions, func(i, j *split.RegionInfo) int { + return bytes.Compare(i.Region.StartKey, j.Region.StartKey) }) syncLock.Lock() scatterRegions = append(scatterRegions, newRegions...) @@ -293,8 +293,8 @@ func (local *local) SplitAndScatterRegionByRanges( if len(retryKeys) == 0 { break } - slices.SortFunc(retryKeys, func(i, j []byte) bool { - return bytes.Compare(i, j) < 0 + slices.SortFunc(retryKeys, func(i, j []byte) int { + return bytes.Compare(i, j) }) minKey = codec.EncodeBytes([]byte{}, retryKeys[0]) maxKey = codec.EncodeBytes([]byte{}, nextKey(retryKeys[len(retryKeys)-1])) diff --git a/br/pkg/lightning/checkpoints/BUILD.bazel b/br/pkg/lightning/checkpoints/BUILD.bazel index 35312b44a4998..a97589d19fd04 100644 --- a/br/pkg/lightning/checkpoints/BUILD.bazel +++ b/br/pkg/lightning/checkpoints/BUILD.bazel @@ -22,6 +22,7 @@ go_library( "//parser/model", "//types", "//util/chunk", + "//util/cmp", "//util/mathutil", "//util/sqlexec", "@com_github_joho_sqltocsv//:sqltocsv", diff --git a/br/pkg/lightning/checkpoints/checkpoints.go b/br/pkg/lightning/checkpoints/checkpoints.go index d20134660de9c..0e44186fabfb1 100644 --- a/br/pkg/lightning/checkpoints/checkpoints.go +++ b/br/pkg/lightning/checkpoints/checkpoints.go @@ -36,6 +36,7 @@ import ( verify "github.com/pingcap/tidb/br/pkg/lightning/verification" "github.com/pingcap/tidb/br/pkg/storage" "github.com/pingcap/tidb/br/pkg/version/build" + "github.com/pingcap/tidb/util/cmp" "github.com/pingcap/tidb/util/mathutil" "go.uber.org/zap" "golang.org/x/exp/slices" @@ -229,6 +230,13 @@ func (key *ChunkCheckpointKey) String() string { return fmt.Sprintf("%s:%d", key.Path, key.Offset) } +func (key *ChunkCheckpointKey) compare(other *ChunkCheckpointKey) int { + if c := cmp.Compare(key.Path, other.Path); c != 0 { + return c + } + return cmp.Compare(key.Offset, other.Offset) +} + func (key *ChunkCheckpointKey) less(other *ChunkCheckpointKey) bool { switch { case key.Path < other.Path: @@ -1257,8 +1265,8 @@ func (cpdb *FileCheckpointsDB) Get(_ context.Context, tableName string) (*TableC }) } - slices.SortFunc(engine.Chunks, func(i, j *ChunkCheckpoint) bool { - return i.Key.less(&j.Key) + slices.SortFunc(engine.Chunks, func(i, j *ChunkCheckpoint) int { + return i.Key.compare(&j.Key) }) cp.Engines[engineID] = engine diff --git a/br/pkg/lightning/lightning.go b/br/pkg/lightning/lightning.go index 2db76b1001078..79419f79736c0 100644 --- a/br/pkg/lightning/lightning.go +++ b/br/pkg/lightning/lightning.go @@ -53,6 +53,7 @@ import ( "github.com/pingcap/tidb/br/pkg/version/build" _ "github.com/pingcap/tidb/expression" // get rid of `import cycle`: just init expression.RewriteAstExpr,and called at package `backend.kv`. _ "github.com/pingcap/tidb/planner/core" + "github.com/pingcap/tidb/util/cmp" "github.com/pingcap/tidb/util/promutil" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/collectors" @@ -900,8 +901,8 @@ func checkSystemRequirement(cfg *config.Config, dbsMeta []*mydump.MDDatabaseMeta tableTotalSizes = append(tableTotalSizes, tb.TotalSize) } } - slices.SortFunc(tableTotalSizes, func(i, j int64) bool { - return i > j + slices.SortFunc(tableTotalSizes, func(i, j int64) int { + return cmp.Compare(j, i) }) topNTotalSize := int64(0) for i := 0; i < len(tableTotalSizes) && i < cfg.App.TableConcurrency; i++ { diff --git a/br/pkg/lightning/restore/BUILD.bazel b/br/pkg/lightning/restore/BUILD.bazel index 88358ae66f213..d18e3d4c496f2 100644 --- a/br/pkg/lightning/restore/BUILD.bazel +++ b/br/pkg/lightning/restore/BUILD.bazel @@ -59,6 +59,7 @@ go_library( "//table", "//table/tables", "//types", + "//util/cmp", "//util/collate", "//util/dbterror", "//util/engine", diff --git a/br/pkg/lightning/restore/precheck_impl.go b/br/pkg/lightning/restore/precheck_impl.go index 77d833e8ae54c..2edb01c1779ec 100644 --- a/br/pkg/lightning/restore/precheck_impl.go +++ b/br/pkg/lightning/restore/precheck_impl.go @@ -41,6 +41,7 @@ import ( "github.com/pingcap/tidb/store/pdtypes" "github.com/pingcap/tidb/table" "github.com/pingcap/tidb/types" + "github.com/pingcap/tidb/util/cmp" "github.com/pingcap/tidb/util/engine" "github.com/pingcap/tidb/util/mathutil" "github.com/pingcap/tidb/util/set" @@ -332,8 +333,8 @@ func (ci *regionDistributionCheckItem) Check(ctx context.Context) (*CheckResult, if len(stores) <= 1 { return theResult, nil } - slices.SortFunc(stores, func(i, j *pdtypes.StoreInfo) bool { - return i.Status.RegionCount < j.Status.RegionCount + slices.SortFunc(stores, func(i, j *pdtypes.StoreInfo) int { + return cmp.Compare(i.Status.RegionCount, j.Status.RegionCount) }) minStore := stores[0] maxStore := stores[len(stores)-1] diff --git a/br/pkg/lightning/restore/table_restore.go b/br/pkg/lightning/restore/table_restore.go index 5045f55131b31..c5eabdc076fcb 100644 --- a/br/pkg/lightning/restore/table_restore.go +++ b/br/pkg/lightning/restore/table_restore.go @@ -40,6 +40,7 @@ import ( "github.com/pingcap/tidb/parser/mysql" "github.com/pingcap/tidb/table" "github.com/pingcap/tidb/table/tables" + "github.com/pingcap/tidb/util/cmp" "github.com/pingcap/tidb/util/mathutil" clientv3 "go.etcd.io/etcd/client/v3" "go.uber.org/multierr" @@ -309,7 +310,7 @@ func (tr *TableRestore) restoreEngines(pCtx context.Context, rc *Controller, cp for engineID, engine := range cp.Engines { allEngines = append(allEngines, engineCheckpoint{engineID: engineID, checkpoint: engine}) } - slices.SortFunc(allEngines, func(i, j engineCheckpoint) bool { return i.engineID < j.engineID }) + slices.SortFunc(allEngines, func(i, j engineCheckpoint) int { return cmp.Compare(i.engineID, j.engineID) }) for _, ecp := range allEngines { engineID := ecp.engineID diff --git a/br/pkg/restore/BUILD.bazel b/br/pkg/restore/BUILD.bazel index 89558ea341e1a..9981e5497db59 100644 --- a/br/pkg/restore/BUILD.bazel +++ b/br/pkg/restore/BUILD.bazel @@ -61,6 +61,7 @@ go_library( "//store/pdtypes", "//tablecodec", "//util", + "//util/cmp", "//util/codec", "//util/collate", "//util/hack", diff --git a/br/pkg/restore/client.go b/br/pkg/restore/client.go index cadd5ad40d226..58542f1793803 100644 --- a/br/pkg/restore/client.go +++ b/br/pkg/restore/client.go @@ -52,6 +52,7 @@ import ( "github.com/pingcap/tidb/store/helper" "github.com/pingcap/tidb/store/pdtypes" "github.com/pingcap/tidb/tablecodec" + "github.com/pingcap/tidb/util/cmp" "github.com/pingcap/tidb/util/codec" "github.com/pingcap/tidb/util/collate" "github.com/pingcap/tidb/util/mathutil" @@ -654,8 +655,8 @@ func (rc *Client) CreateTables( newTables = append(newTables, et.Table) } // Let's ensure that it won't break the original order. - slices.SortFunc(newTables, func(i, j *model.TableInfo) bool { - return tbMapping[i.Name.String()] < tbMapping[j.Name.String()] + slices.SortFunc(newTables, func(i, j *model.TableInfo) int { + return cmp.Compare(tbMapping[i.Name.String()], tbMapping[j.Name.String()]) }) select { @@ -1027,8 +1028,8 @@ func (rc *Client) CheckSysTableCompatibility(dom *domain.Domain, tables []*metau // ExecDDLs executes the queries of the ddl jobs. func (rc *Client) ExecDDLs(ctx context.Context, ddlJobs []*model.Job) error { // Sort the ddl jobs by schema version in ascending order. - slices.SortFunc(ddlJobs, func(i, j *model.Job) bool { - return i.BinlogInfo.SchemaVersion < j.BinlogInfo.SchemaVersion + slices.SortFunc(ddlJobs, func(i, j *model.Job) int { + return cmp.Compare(i.BinlogInfo.SchemaVersion, j.BinlogInfo.SchemaVersion) }) for _, job := range ddlJobs { @@ -2278,26 +2279,14 @@ func (rc *Client) InitSchemasReplaceForDDL( } func SortMetaKVFiles(files []*backuppb.DataFileInfo) []*backuppb.DataFileInfo { - slices.SortFunc(files, func(i, j *backuppb.DataFileInfo) bool { - if i.GetMinTs() < j.GetMinTs() { - return true - } else if i.GetMinTs() > j.GetMinTs() { - return false - } - - if i.GetMaxTs() < j.GetMaxTs() { - return true - } else if i.GetMaxTs() > j.GetMaxTs() { - return false + slices.SortFunc(files, func(i, j *backuppb.DataFileInfo) int { + if c := cmp.Compare(i.GetMinTs(), j.GetMinTs()); c != 0 { + return c } - - if i.GetResolvedTs() < j.GetResolvedTs() { - return true - } else if i.GetResolvedTs() > j.GetResolvedTs() { - return false + if c := cmp.Compare(i.GetMaxTs(), j.GetMaxTs()); c != 0 { + return c } - - return true + return cmp.Compare(i.GetResolvedTs(), j.GetResolvedTs()) }) return files } @@ -2487,8 +2476,8 @@ func (rc *Client) RestoreBatchMetaKVFiles( } // sort these entries. - slices.SortFunc(curKvEntries, func(i, j *KvEntryWithTS) bool { - return i.ts < j.ts + slices.SortFunc(curKvEntries, func(i, j *KvEntryWithTS) int { + return cmp.Compare(i.ts, j.ts) }) // restore these entries with rawPut() method. diff --git a/br/pkg/restore/db.go b/br/pkg/restore/db.go index 3bf0557886a33..5a4e9327aae08 100644 --- a/br/pkg/restore/db.go +++ b/br/pkg/restore/db.go @@ -20,6 +20,7 @@ import ( "github.com/pingcap/tidb/parser/mysql" "github.com/pingcap/tidb/sessionctx/variable" tidbutil "github.com/pingcap/tidb/util" + "github.com/pingcap/tidb/util/cmp" "go.uber.org/zap" "golang.org/x/exp/slices" ) @@ -396,8 +397,8 @@ func (db *DB) ensureTablePlacementPolicies(ctx context.Context, tableInfo *model // FilterDDLJobs filters ddl jobs. func FilterDDLJobs(allDDLJobs []*model.Job, tables []*metautil.Table) (ddlJobs []*model.Job) { // Sort the ddl jobs by schema version in descending order. - slices.SortFunc(allDDLJobs, func(i, j *model.Job) bool { - return i.BinlogInfo.SchemaVersion > j.BinlogInfo.SchemaVersion + slices.SortFunc(allDDLJobs, func(i, j *model.Job) int { + return cmp.Compare(j.BinlogInfo.SchemaVersion, i.BinlogInfo.SchemaVersion) }) dbs := getDatabases(tables) for _, db := range dbs { diff --git a/br/pkg/streamhelper/advancer_test.go b/br/pkg/streamhelper/advancer_test.go index 216d97522d788..55abd5baa2c80 100644 --- a/br/pkg/streamhelper/advancer_test.go +++ b/br/pkg/streamhelper/advancer_test.go @@ -283,6 +283,7 @@ func TestBlocked(t *testing.T) { s.onGetRegionCheckpoint = func(glftrr *logbackup.GetLastFlushTSOfRegionRequest) error { // blocking the thread. // this may happen when TiKV goes down or too busy. + //nolint:nilness <-(chan struct{})(nil) return nil } diff --git a/br/pkg/task/stream.go b/br/pkg/task/stream.go index e78647328380d..f5b2a395a71c4 100644 --- a/br/pkg/task/stream.go +++ b/br/pkg/task/stream.go @@ -402,8 +402,8 @@ func (s *streamMgr) buildObserveRanges(ctx context.Context) ([]kv.KeyRange, erro mRange := stream.BuildObserveMetaRange() rs := append([]kv.KeyRange{*mRange}, dRanges...) - slices.SortFunc(rs, func(i, j kv.KeyRange) bool { - return bytes.Compare(i.StartKey, j.StartKey) < 0 + slices.SortFunc(rs, func(i, j kv.KeyRange) int { + return bytes.Compare(i.StartKey, j.StartKey) }) return rs, nil diff --git a/br/pkg/trace/BUILD.bazel b/br/pkg/trace/BUILD.bazel index f59c79a5d17f4..ec9e322255883 100644 --- a/br/pkg/trace/BUILD.bazel +++ b/br/pkg/trace/BUILD.bazel @@ -6,6 +6,7 @@ go_library( importpath = "github.com/pingcap/tidb/br/pkg/trace", visibility = ["//visibility:public"], deps = [ + "//util/cmp", "@com_github_cheynewallace_tabby//:tabby", "@com_github_opentracing_opentracing_go//:opentracing-go", "@com_github_pingcap_log//:log", diff --git a/br/pkg/trace/tracing.go b/br/pkg/trace/tracing.go index ff961367ff282..4678c3698acbf 100644 --- a/br/pkg/trace/tracing.go +++ b/br/pkg/trace/tracing.go @@ -13,6 +13,7 @@ import ( "github.com/cheynewallace/tabby" "github.com/opentracing/opentracing-go" "github.com/pingcap/log" + "github.com/pingcap/tidb/util/cmp" "go.uber.org/zap" "golang.org/x/exp/slices" "sourcegraph.com/sourcegraph/appdash" @@ -88,7 +89,7 @@ func dfsTree(t *appdash.Trace, prefix string, isLast bool, tub *tabby.Tabby) { tub.AddLine(prefix+suffix+t.Span.Name(), start.Format("15:04:05.000000"), duration.String()) // Sort events by their start time - slices.SortFunc(t.Sub, func(i, j *appdash.Trace) bool { + slices.SortFunc(t.Sub, func(i, j *appdash.Trace) int { var istart, jstart time.Time if ievent, err := i.TimespanEvent(); err == nil { istart = ievent.Start() @@ -96,7 +97,7 @@ func dfsTree(t *appdash.Trace, prefix string, isLast bool, tub *tabby.Tabby) { if jevent, err := j.TimespanEvent(); err == nil { jstart = jevent.Start() } - return istart.Before(jstart) + return cmp.Compare(istart.UnixNano(), jstart.UnixNano()) }) for i, sp := range t.Sub { diff --git a/ddl/BUILD.bazel b/ddl/BUILD.bazel index 7072c6cb93558..a12e4024cefee 100644 --- a/ddl/BUILD.bazel +++ b/ddl/BUILD.bazel @@ -97,6 +97,7 @@ go_library( "//types/parser_driver", "//util", "//util/chunk", + "//util/cmp", "//util/codec", "//util/collate", "//util/dbterror", @@ -250,6 +251,7 @@ go_test( "//types", "//util", "//util/chunk", + "//util/cmp", "//util/codec", "//util/collate", "//util/dbterror", diff --git a/ddl/cluster.go b/ddl/cluster.go index e05964c8826fa..598f1cda7de51 100644 --- a/ddl/cluster.go +++ b/ddl/cluster.go @@ -35,6 +35,7 @@ import ( "github.com/pingcap/tidb/sessionctx" "github.com/pingcap/tidb/sessionctx/variable" "github.com/pingcap/tidb/tablecodec" + "github.com/pingcap/tidb/util/cmp" "github.com/pingcap/tidb/util/filter" "github.com/pingcap/tidb/util/gcutil" "github.com/pingcap/tidb/util/logutil" @@ -274,8 +275,8 @@ func GetFlashbackKeyRanges(sess sessionctx.Context) ([]kv.KeyRange, error) { } } - slices.SortFunc(flashbackIDs, func(a, b flashbackID) bool { - return a.id < b.id + slices.SortFunc(flashbackIDs, func(a, b flashbackID) int { + return cmp.Compare(a.id, b.id) }) lastExcludeIdx := -1 diff --git a/ddl/ddl.go b/ddl/ddl.go index ed774c202b14a..6ba3b0cd736aa 100644 --- a/ddl/ddl.go +++ b/ddl/ddl.go @@ -59,6 +59,7 @@ import ( pumpcli "github.com/pingcap/tidb/tidb-binlog/pump_client" tidbutil "github.com/pingcap/tidb/util" "github.com/pingcap/tidb/util/chunk" + "github.com/pingcap/tidb/util/cmp" "github.com/pingcap/tidb/util/dbterror" "github.com/pingcap/tidb/util/gcutil" "github.com/pingcap/tidb/util/logutil" @@ -1699,8 +1700,8 @@ func getDDLJobs(t *meta.Meta) ([]*model.Job, error) { return nil, errors.Trace(err) } jobs := append(generalJobs, addIdxJobs...) - slices.SortFunc(jobs, func(i, j *model.Job) bool { - return i.ID < j.ID + slices.SortFunc(jobs, func(i, j *model.Job) int { + return cmp.Compare(i.ID, j.ID) }) return jobs, nil } @@ -1860,8 +1861,8 @@ func GetAllHistoryDDLJobs(m *meta.Meta) ([]*model.Job, error) { } } // sort job. - slices.SortFunc(allJobs, func(i, j *model.Job) bool { - return i.ID < j.ID + slices.SortFunc(allJobs, func(i, j *model.Job) int { + return cmp.Compare(i.ID, j.ID) }) return allJobs, nil } diff --git a/ddl/ddl_api_test.go b/ddl/ddl_api_test.go index 9283389047ecf..a6a5a3187eb3a 100644 --- a/ddl/ddl_api_test.go +++ b/ddl/ddl_api_test.go @@ -28,6 +28,7 @@ import ( "github.com/pingcap/tidb/session" "github.com/pingcap/tidb/testkit" "github.com/pingcap/tidb/util/chunk" + "github.com/pingcap/tidb/util/cmp" "github.com/stretchr/testify/require" "golang.org/x/exp/slices" ) @@ -110,8 +111,8 @@ func TestGetDDLJobsIsSort(t *testing.T) { require.NoError(t, err) require.Len(t, currJobs, 15) - isSort := slices.IsSortedFunc(currJobs, func(i, j *model.Job) bool { - return i.ID <= j.ID + isSort := slices.IsSortedFunc(currJobs, func(i, j *model.Job) int { + return cmp.Compare(i.ID, j.ID) }) require.True(t, isSort) diff --git a/ddl/index.go b/ddl/index.go index be5ce0df8d495..d085a658fd4a8 100644 --- a/ddl/index.go +++ b/ddl/index.go @@ -47,6 +47,7 @@ import ( "github.com/pingcap/tidb/types" "github.com/pingcap/tidb/util" "github.com/pingcap/tidb/util/chunk" + "github.com/pingcap/tidb/util/cmp" "github.com/pingcap/tidb/util/dbterror" "github.com/pingcap/tidb/util/logutil" decoder "github.com/pingcap/tidb/util/rowDecoder" @@ -1055,7 +1056,7 @@ func RemoveDependentHiddenColumns(tblInfo *model.TableInfo, idxInfo *model.Index } } // Sort the offset in descending order. - slices.SortFunc(hiddenColOffs, func(a, b int) bool { return a > b }) + slices.SortFunc(hiddenColOffs, func(a, b int) int { return cmp.Compare(b, a) }) // Move all the dependent hidden columns to the end. endOffset := len(tblInfo.Columns) - 1 for _, offset := range hiddenColOffs { diff --git a/executor/BUILD.bazel b/executor/BUILD.bazel index dbe42439f4162..7cbaa6eef5da6 100644 --- a/executor/BUILD.bazel +++ b/executor/BUILD.bazel @@ -161,6 +161,7 @@ go_library( "//util/breakpoint", "//util/channel", "//util/chunk", + "//util/cmp", "//util/codec", "//util/collate", "//util/cteutil", diff --git a/executor/aggregate.go b/executor/aggregate.go index d34d7be17731c..40314c65497c3 100644 --- a/executor/aggregate.go +++ b/executor/aggregate.go @@ -34,6 +34,7 @@ import ( "github.com/pingcap/tidb/types" "github.com/pingcap/tidb/util/channel" "github.com/pingcap/tidb/util/chunk" + "github.com/pingcap/tidb/util/cmp" "github.com/pingcap/tidb/util/codec" "github.com/pingcap/tidb/util/disk" "github.com/pingcap/tidb/util/execdetails" @@ -1188,7 +1189,7 @@ func (*HashAggRuntimeStats) workerString(buf *bytes.Buffer, prefix string, concu time.Duration(wallTime), concurrency, totalTaskNum, time.Duration(totalWait), time.Duration(totalExec), time.Duration(totalTime))) n := len(workerStats) if n > 0 { - slices.SortFunc(workerStats, func(i, j *AggWorkerStat) bool { return i.WorkerTime < j.WorkerTime }) + slices.SortFunc(workerStats, func(i, j *AggWorkerStat) int { return cmp.Compare(i.WorkerTime, j.WorkerTime) }) buf.WriteString(fmt.Sprintf(", max:%v, p95:%v", time.Duration(workerStats[n-1].WorkerTime), time.Duration(workerStats[n*19/20].WorkerTime))) } diff --git a/executor/batch_point_get.go b/executor/batch_point_get.go index 965708073a097..3134d37c0366e 100644 --- a/executor/batch_point_get.go +++ b/executor/batch_point_get.go @@ -250,11 +250,11 @@ func (e *BatchPointGetExec) initialize(ctx context.Context) error { toFetchIndexKeys = append(toFetchIndexKeys, idxKey) } if e.keepOrder { - slices.SortFunc(toFetchIndexKeys, func(i, j kv.Key) bool { + slices.SortFunc(toFetchIndexKeys, func(i, j kv.Key) int { if e.desc { - return i.Cmp(j) > 0 + return j.Cmp(i) } - return i.Cmp(j) < 0 + return i.Cmp(j) }) } @@ -318,11 +318,11 @@ func (e *BatchPointGetExec) initialize(ctx context.Context) error { failpoint.InjectContext(ctx, "batchPointGetRepeatableReadTest-step2", nil) }) } else if e.keepOrder { - less := func(i, j kv.Handle) bool { + less := func(i, j kv.Handle) int { if e.desc { - return i.Compare(j) > 0 + return j.Compare(i) } - return i.Compare(j) < 0 + return i.Compare(j) } if e.tblInfo.PKIsHandle && mysql.HasUnsignedFlag(e.tblInfo.GetPkColInfo().GetFlag()) { uintComparator := func(i, h kv.Handle) int { @@ -339,11 +339,11 @@ func (e *BatchPointGetExec) initialize(ctx context.Context) error { } return 0 } - less = func(i, j kv.Handle) bool { + less = func(i, j kv.Handle) int { if e.desc { - return uintComparator(i, j) > 0 + return uintComparator(j, i) } - return uintComparator(i, j) < 0 + return uintComparator(i, j) } } slices.SortFunc(e.handles, less) diff --git a/executor/builder.go b/executor/builder.go index 5b6a40be2bc4b..5fb31f642bd94 100644 --- a/executor/builder.go +++ b/executor/builder.go @@ -58,6 +58,7 @@ import ( "github.com/pingcap/tidb/types" "github.com/pingcap/tidb/util" "github.com/pingcap/tidb/util/chunk" + "github.com/pingcap/tidb/util/cmp" "github.com/pingcap/tidb/util/collate" "github.com/pingcap/tidb/util/cteutil" "github.com/pingcap/tidb/util/execdetails" @@ -3533,8 +3534,8 @@ func (b *executorBuilder) buildTableReader(v *plannercore.PhysicalTableReader) E } // Sort the partition is necessary to make the final multiple partition key ranges ordered. - slices.SortFunc(partitions, func(i, j table.PhysicalTable) bool { - return i.GetPhysicalID() < j.GetPhysicalID() + slices.SortFunc(partitions, func(i, j table.PhysicalTable) int { + return cmp.Compare(i.GetPhysicalID(), j.GetPhysicalID()) }) ret.kvRangeBuilder = kvRangeBuilderFromRangeAndPartition{ sctx: b.ctx, @@ -3653,8 +3654,8 @@ func (builder *dataReaderBuilder) prunePartitionForInnerExecutor(tbl table.Table } // To make the final key ranges involving multiple partitions ordered. - slices.SortFunc(usedPartition, func(i, j table.PhysicalTable) bool { - return i.GetPhysicalID() < j.GetPhysicalID() + slices.SortFunc(usedPartition, func(i, j table.PhysicalTable) int { + return cmp.Compare(i.GetPhysicalID(), j.GetPhysicalID()) }) return usedPartition, true, contentPos, nil } @@ -4256,8 +4257,8 @@ func (builder *dataReaderBuilder) buildTableReaderForIndexJoin(ctx context.Conte } } // The key ranges should be ordered. - slices.SortFunc(kvRanges, func(i, j kv.KeyRange) bool { - return bytes.Compare(i.StartKey, j.StartKey) < 0 + slices.SortFunc(kvRanges, func(i, j kv.KeyRange) int { + return bytes.Compare(i.StartKey, j.StartKey) }) return builder.buildTableReaderFromKvRanges(ctx, e, kvRanges) } @@ -4294,8 +4295,8 @@ func (builder *dataReaderBuilder) buildTableReaderForIndexJoin(ctx context.Conte } // The key ranges should be ordered. - slices.SortFunc(kvRanges, func(i, j kv.KeyRange) bool { - return bytes.Compare(i.StartKey, j.StartKey) < 0 + slices.SortFunc(kvRanges, func(i, j kv.KeyRange) int { + return bytes.Compare(i.StartKey, j.StartKey) }) return builder.buildTableReaderFromKvRanges(ctx, e, kvRanges) } @@ -4415,8 +4416,8 @@ func (builder *dataReaderBuilder) buildTableReaderBase(ctx context.Context, e *T func (builder *dataReaderBuilder) buildTableReaderFromHandles(ctx context.Context, e *TableReaderExecutor, handles []kv.Handle, canReorderHandles bool) (*TableReaderExecutor, error) { if canReorderHandles { - slices.SortFunc(handles, func(i, j kv.Handle) bool { - return i.Compare(j) < 0 + slices.SortFunc(handles, func(i, j kv.Handle) int { + return i.Compare(j) }) } var b distsql.RequestBuilder @@ -4670,8 +4671,8 @@ func buildKvRangesForIndexJoin(ctx sessionctx.Context, tableID, indexID int64, l memTracker.Consume(2 * types.EstimatedMemUsage(tmpDatumRanges[0].LowVal, len(tmpDatumRanges))) } if cwc == nil { - slices.SortFunc(kvRanges, func(i, j kv.KeyRange) bool { - return bytes.Compare(i.StartKey, j.StartKey) < 0 + slices.SortFunc(kvRanges, func(i, j kv.KeyRange) int { + return bytes.Compare(i.StartKey, j.StartKey) }) return kvRanges, nil } diff --git a/executor/distsql.go b/executor/distsql.go index ac531a452fb8f..7188b234d48f0 100644 --- a/executor/distsql.go +++ b/executor/distsql.go @@ -325,8 +325,8 @@ func (e *IndexReaderExecutor) open(ctx context.Context, kvRanges *kv.KeyRanges) e.memTracker = memory.NewTracker(e.id, -1) } e.memTracker.AttachTo(e.ctx.GetSessionVars().StmtCtx.MemTracker) - kvRanges.SortByFunc(func(i, j kv.KeyRange) bool { - return bytes.Compare(i.StartKey, j.StartKey) < 0 + kvRanges.SortByFunc(func(i, j kv.KeyRange) int { + return bytes.Compare(i.StartKey, j.StartKey) }) var builder distsql.RequestBuilder builder.SetWrappedKeyRanges(kvRanges). @@ -636,8 +636,8 @@ func (e *IndexLookUpExecutor) startIndexWorker(ctx context.Context, workCh chan< // init kvReq, result and worker for this partition // The key ranges should be ordered. - slices.SortFunc(kvRange, func(i, j kv.KeyRange) bool { - return bytes.Compare(i.StartKey, j.StartKey) < 0 + slices.SortFunc(kvRange, func(i, j kv.KeyRange) int { + return bytes.Compare(i.StartKey, j.StartKey) }) kvReq, err := builder.SetKeyRanges(kvRange).Build() if err != nil { diff --git a/executor/index_lookup_join.go b/executor/index_lookup_join.go index ee654b282cfe4..1c6a9cab4aa09 100644 --- a/executor/index_lookup_join.go +++ b/executor/index_lookup_join.go @@ -655,12 +655,12 @@ func (iw *innerWorker) sortAndDedupLookUpContents(lookUpContents []*indexJoinLoo return lookUpContents } sc := iw.ctx.GetSessionVars().StmtCtx - slices.SortFunc(lookUpContents, func(i, j *indexJoinLookUpContent) bool { + slices.SortFunc(lookUpContents, func(i, j *indexJoinLookUpContent) int { cmp := compareRow(sc, i.keys, j.keys, iw.keyCollators) if cmp != 0 || iw.nextColCompareFilters == nil { - return cmp < 0 + return cmp } - return iw.nextColCompareFilters.CompareRow(i.row, j.row) < 0 + return iw.nextColCompareFilters.CompareRow(i.row, j.row) }) deDupedLookupKeys := lookUpContents[:1] for i := 1; i < len(lookUpContents); i++ { diff --git a/executor/index_lookup_merge_join.go b/executor/index_lookup_merge_join.go index e0fb176fff589..60b9eacd4e73f 100644 --- a/executor/index_lookup_merge_join.go +++ b/executor/index_lookup_merge_join.go @@ -449,23 +449,29 @@ func (imw *innerMergeWorker) handleTask(ctx context.Context, task *lookUpMergeJo // Because the necessary condition of merge join is both outer and inner keep order of join keys. // In this case, we need sort the outer side. if imw.outerMergeCtx.needOuterSort { - slices.SortFunc(task.outerOrderIdx, func(idxI, idxJ chunk.RowPtr) bool { + slices.SortFunc(task.outerOrderIdx, func(idxI, idxJ chunk.RowPtr) int { rowI, rowJ := task.outerResult.GetRow(idxI), task.outerResult.GetRow(idxJ) - var cmp int64 + var c int64 var err error for _, keyOff := range imw.keyOff2KeyOffOrderByIdx { joinKey := imw.outerMergeCtx.joinKeys[keyOff] - cmp, _, err = imw.outerMergeCtx.compareFuncs[keyOff](imw.ctx, joinKey, joinKey, rowI, rowJ) + c, _, err = imw.outerMergeCtx.compareFuncs[keyOff](imw.ctx, joinKey, joinKey, rowI, rowJ) terror.Log(err) - if cmp != 0 { + if c != 0 { break } } - if cmp != 0 || imw.nextColCompareFilters == nil { - return (cmp < 0 && !imw.desc) || (cmp > 0 && imw.desc) + if c != 0 || imw.nextColCompareFilters == nil { + if imw.desc { + return int(-c) + } + return int(c) + } + c = int64(imw.nextColCompareFilters.CompareRow(rowI, rowJ)) + if imw.desc { + return int(-c) } - cmp = int64(imw.nextColCompareFilters.CompareRow(rowI, rowJ)) - return (cmp < 0 && !imw.desc) || (cmp > 0 && imw.desc) + return int(c) }) } dLookUpKeys, err := imw.constructDatumLookupKeys(task) diff --git a/executor/index_merge_reader.go b/executor/index_merge_reader.go index 46b6db3ecf678..20e78ee80f951 100644 --- a/executor/index_merge_reader.go +++ b/executor/index_merge_reader.go @@ -384,8 +384,8 @@ func (e *IndexMergeReaderExecutor) startPartialIndexWorker(ctx context.Context, // init kvReq and worker for this partition // The key ranges should be ordered. - slices.SortFunc(keyRange, func(i, j kv.KeyRange) bool { - return bytes.Compare(i.StartKey, j.StartKey) < 0 + slices.SortFunc(keyRange, func(i, j kv.KeyRange) int { + return bytes.Compare(i.StartKey, j.StartKey) }) kvReq, err := builder.SetKeyRanges(keyRange).Build() if err != nil { diff --git a/executor/infoschema_reader.go b/executor/infoschema_reader.go index 42615a2dd5d49..208d0be40cacd 100644 --- a/executor/infoschema_reader.go +++ b/executor/infoschema_reader.go @@ -3013,8 +3013,8 @@ func (e *hugeMemTableRetriever) retrieve(ctx context.Context, sctx sessionctx.Co if !e.initialized { is := sctx.GetInfoSchema().(infoschema.InfoSchema) dbs := is.AllSchemas() - slices.SortFunc(dbs, func(i, j *model.DBInfo) bool { - return i.Name.L < j.Name.L + slices.SortFunc(dbs, func(i, j *model.DBInfo) int { + return strings.Compare(i.Name.L, j.Name.L) }) e.dbs = dbs e.initialized = true diff --git a/executor/inspection_result.go b/executor/inspection_result.go index 55793a7729274..27741e2823e79 100644 --- a/executor/inspection_result.go +++ b/executor/inspection_result.go @@ -31,6 +31,7 @@ import ( "github.com/pingcap/tidb/types" "github.com/pingcap/tidb/util" "github.com/pingcap/tidb/util/chunk" + "github.com/pingcap/tidb/util/cmp" "github.com/pingcap/tidb/util/set" "github.com/pingcap/tidb/util/size" "github.com/pingcap/tidb/util/sqlexec" @@ -169,20 +170,22 @@ func (e *inspectionResultRetriever) retrieve(ctx context.Context, sctx sessionct continue } // make result stable - slices.SortFunc(results, func(i, j inspectionResult) bool { - if i.degree != j.degree { - return i.degree > j.degree + slices.SortFunc(results, func(i, j inspectionResult) int { + if c := cmp.Compare(i.degree, j.degree); c != 0 { + return -c } - if lhs, rhs := i.item, j.item; lhs != rhs { - return lhs < rhs + // lhs and rhs + if c := cmp.Compare(i.item, j.item); c != 0 { + return c } - if i.actual != j.actual { - return i.actual < j.actual + if c := cmp.Compare(i.actual, j.actual); c != 0 { + return c } - if lhs, rhs := i.tp, j.tp; lhs != rhs { - return lhs < rhs + // lhs and rhs + if c := cmp.Compare(i.tp, j.tp); c != 0 { + return c } - return i.instance < j.instance + return cmp.Compare(i.instance, j.instance) }) for _, result := range results { if len(result.instance) == 0 { diff --git a/executor/memtable_reader.go b/executor/memtable_reader.go index dc215e71fe3bb..b98388e01dba4 100644 --- a/executor/memtable_reader.go +++ b/executor/memtable_reader.go @@ -44,6 +44,7 @@ import ( "github.com/pingcap/tidb/types" "github.com/pingcap/tidb/util" "github.com/pingcap/tidb/util/chunk" + "github.com/pingcap/tidb/util/cmp" "github.com/pingcap/tidb/util/execdetails" "github.com/pingcap/tidb/util/pdapi" "github.com/pingcap/tidb/util/set" @@ -252,7 +253,7 @@ func fetchClusterConfig(sctx sessionctx.Context, nodeTypes, nodeAddrs set.String } items = append(items, item{key: key, val: str}) } - slices.SortFunc(items, func(i, j item) bool { return i.key < j.key }) + slices.SortFunc(items, func(i, j item) int { return strings.Compare(i.key, j.key) }) var rows [][]types.Datum for _, item := range items { rows = append(rows, types.MakeDatums( @@ -279,7 +280,7 @@ func fetchClusterConfig(sctx sessionctx.Context, nodeTypes, nodeAddrs set.String } results = append(results, result) } - slices.SortFunc(results, func(i, j result) bool { return i.idx < j.idx }) + slices.SortFunc(results, func(i, j result) int { return cmp.Compare(i.idx, j.idx) }) for _, result := range results { finalRows = append(finalRows, result.rows...) } @@ -357,7 +358,7 @@ func (e *clusterServerInfoRetriever) retrieve(ctx context.Context, sctx sessionc } results = append(results, result) } - slices.SortFunc(results, func(i, j result) bool { return i.idx < j.idx }) + slices.SortFunc(results, func(i, j result) int { return cmp.Compare(i.idx, j.idx) }) for _, result := range results { finalRows = append(finalRows, result.rows...) } diff --git a/executor/sample.go b/executor/sample.go index e7eb9bd223639..0b6c31bfc5403 100644 --- a/executor/sample.go +++ b/executor/sample.go @@ -228,12 +228,12 @@ func splitIntoMultiRanges(store kv.Storage, startKey, endKey kv.Key) ([]kv.KeyRa } func sortRanges(ranges []kv.KeyRange, isDesc bool) { - slices.SortFunc(ranges, func(i, j kv.KeyRange) bool { + slices.SortFunc(ranges, func(i, j kv.KeyRange) int { ir, jr := i.StartKey, j.StartKey if !isDesc { - return ir.Cmp(jr) < 0 + return ir.Cmp(jr) } - return ir.Cmp(jr) > 0 + return -ir.Cmp(jr) }) } diff --git a/executor/show_placement.go b/executor/show_placement.go index ae562105476be..8a0642e4f4ce9 100644 --- a/executor/show_placement.go +++ b/executor/show_placement.go @@ -18,6 +18,7 @@ import ( "context" gjson "encoding/json" "fmt" + "strings" "github.com/pingcap/errors" "github.com/pingcap/tidb/domain/infosync" @@ -251,7 +252,7 @@ func (e *ShowExec) fetchShowPlacement(ctx context.Context) error { func (e *ShowExec) fetchAllPlacementPolicies() error { policies := e.is.AllPlacementPolicies() - slices.SortFunc(policies, func(i, j *model.PolicyInfo) bool { return i.Name.O < j.Name.O }) + slices.SortFunc(policies, func(i, j *model.PolicyInfo) int { return strings.Compare(i.Name.O, j.Name.O) }) for _, policy := range policies { name := policy.Name settings := policy.PlacementSettings @@ -266,7 +267,7 @@ func (e *ShowExec) fetchAllDBPlacements(ctx context.Context, scheduleState map[i activeRoles := e.ctx.GetSessionVars().ActiveRoles dbs := e.is.AllSchemas() - slices.SortFunc(dbs, func(i, j *model.DBInfo) bool { return i.Name.O < j.Name.O }) + slices.SortFunc(dbs, func(i, j *model.DBInfo) int { return strings.Compare(i.Name.O, j.Name.O) }) for _, dbInfo := range dbs { if e.ctx.GetSessionVars().User != nil && checker != nil && !checker.DBIsVisible(activeRoles, dbInfo.Name.O) { @@ -300,7 +301,7 @@ func (e *ShowExec) fetchAllTablePlacements(ctx context.Context, scheduleState ma activeRoles := e.ctx.GetSessionVars().ActiveRoles dbs := e.is.AllSchemas() - slices.SortFunc(dbs, func(i, j *model.DBInfo) bool { return i.Name.O < j.Name.O }) + slices.SortFunc(dbs, func(i, j *model.DBInfo) int { return strings.Compare(i.Name.O, j.Name.O) }) for _, dbInfo := range dbs { tableRowSets := make([]tableRowSet, 0) @@ -359,7 +360,7 @@ func (e *ShowExec) fetchAllTablePlacements(ctx context.Context, scheduleState ma } } - slices.SortFunc(tableRowSets, func(i, j tableRowSet) bool { return i.name < j.name }) + slices.SortFunc(tableRowSets, func(i, j tableRowSet) int { return strings.Compare(i.name, j.name) }) for _, rowSet := range tableRowSets { for _, row := range rowSet.rows { e.appendRow(row) diff --git a/executor/show_stats.go b/executor/show_stats.go index 6161a173e8fe4..14fc14e1a575a 100644 --- a/executor/show_stats.go +++ b/executor/show_stats.go @@ -25,6 +25,7 @@ import ( "github.com/pingcap/tidb/parser/mysql" "github.com/pingcap/tidb/statistics" "github.com/pingcap/tidb/types" + "github.com/pingcap/tidb/util/cmp" "github.com/tikv/client-go/v2/oracle" "golang.org/x/exp/slices" ) @@ -382,7 +383,7 @@ func stableColsStats(colStats map[int64]*statistics.Column) (cols []*statistics. for _, col := range colStats { cols = append(cols, col) } - slices.SortFunc(cols, func(i, j *statistics.Column) bool { return i.ID < j.ID }) + slices.SortFunc(cols, func(i, j *statistics.Column) int { return cmp.Compare(i.ID, j.ID) }) return } @@ -390,7 +391,7 @@ func stableIdxsStats(idxStats map[int64]*statistics.Index) (idxs []*statistics.I for _, idx := range idxStats { idxs = append(idxs, idx) } - slices.SortFunc(idxs, func(i, j *statistics.Index) bool { return i.ID < j.ID }) + slices.SortFunc(idxs, func(i, j *statistics.Index) int { return cmp.Compare(i.ID, j.ID) }) return } diff --git a/executor/slow_query.go b/executor/slow_query.go index 395d8f4eba8ac..f1f7d1a5f6448 100644 --- a/executor/slow_query.go +++ b/executor/slow_query.go @@ -43,6 +43,7 @@ import ( "github.com/pingcap/tidb/table" "github.com/pingcap/tidb/types" "github.com/pingcap/tidb/util" + "github.com/pingcap/tidb/util/cmp" "github.com/pingcap/tidb/util/execdetails" "github.com/pingcap/tidb/util/hack" "github.com/pingcap/tidb/util/logutil" @@ -962,8 +963,8 @@ func (e *slowQueryRetriever) getAllFiles(ctx context.Context, sctx sessionctx.Co } } // Sort by start time - slices.SortFunc(logFiles, func(i, j logFile) bool { - return i.start.Before(j.start) + slices.SortFunc(logFiles, func(i, j logFile) int { + return cmp.Compare(i.start.UnixNano(), j.start.UnixNano()) }) return logFiles, err } diff --git a/executor/sort.go b/executor/sort.go index cb2c97e68a8e4..126269924b525 100644 --- a/executor/sort.go +++ b/executor/sort.go @@ -259,20 +259,18 @@ func (e *SortExec) buildKeyColumns() { } } -func (e *SortExec) lessRow(rowI, rowJ chunk.Row) bool { +func (e *SortExec) lessRow(rowI, rowJ chunk.Row) int { for i, colIdx := range e.keyColumns { cmpFunc := e.keyCmpFuncs[i] cmp := cmpFunc(rowI, colIdx, rowJ, colIdx) if e.ByItems[i].Desc { cmp = -cmp } - if cmp < 0 { - return true - } else if cmp > 0 { - return false + if cmp != 0 { + return cmp } } - return false + return 0 } type partitionPointer struct { @@ -282,14 +280,14 @@ type partitionPointer struct { } type multiWayMerge struct { - lessRowFunction func(rowI chunk.Row, rowJ chunk.Row) bool + lessRowFunction func(rowI chunk.Row, rowJ chunk.Row) int elements []partitionPointer } func (h *multiWayMerge) Less(i, j int) bool { rowI := h.elements[i].row rowJ := h.elements[j].row - return h.lessRowFunction(rowI, rowJ) + return h.lessRowFunction(rowI, rowJ) < 0 } func (h *multiWayMerge) Len() int { @@ -372,7 +370,7 @@ func (h *topNChunkHeap) Swap(i, j int) { } // keyColumnsLess is the less function for key columns. -func (e *TopNExec) keyColumnsLess(i, j chunk.RowPtr) bool { +func (e *TopNExec) keyColumnsLess(i, j chunk.RowPtr) int { rowI := e.rowChunks.GetRow(i) rowJ := e.rowChunks.GetRow(j) return e.lessRow(rowI, rowJ) diff --git a/executor/table_reader.go b/executor/table_reader.go index aa8fcf910be1b..9a3a54870105d 100644 --- a/executor/table_reader.go +++ b/executor/table_reader.go @@ -35,6 +35,7 @@ import ( "github.com/pingcap/tidb/table" "github.com/pingcap/tidb/types" "github.com/pingcap/tidb/util/chunk" + "github.com/pingcap/tidb/util/cmp" "github.com/pingcap/tidb/util/logutil" "github.com/pingcap/tidb/util/memory" "github.com/pingcap/tidb/util/ranger" @@ -318,8 +319,8 @@ func (e *TableReaderExecutor) buildResp(ctx context.Context, ranges []*ranger.Ra if err != nil { return nil, err } - kvReq.KeyRanges.SortByFunc(func(i, j kv.KeyRange) bool { - return bytes.Compare(i.StartKey, j.StartKey) < 0 + kvReq.KeyRanges.SortByFunc(func(i, j kv.KeyRange) int { + return bytes.Compare(i.StartKey, j.StartKey) }) e.kvRanges = kvReq.KeyRanges.AppendSelfTo(e.kvRanges) @@ -457,9 +458,9 @@ func buildVirtualColumnIndex(schema *expression.Schema, columns []*model.ColumnI virtualColumnIndex = append(virtualColumnIndex, i) } } - slices.SortFunc(virtualColumnIndex, func(i, j int) bool { - return plannercore.FindColumnInfoByID(columns, schema.Columns[i].ID).Offset < - plannercore.FindColumnInfoByID(columns, schema.Columns[j].ID).Offset + slices.SortFunc(virtualColumnIndex, func(i, j int) int { + return cmp.Compare(plannercore.FindColumnInfoByID(columns, schema.Columns[i].ID).Offset, + plannercore.FindColumnInfoByID(columns, schema.Columns[j].ID).Offset) }) return virtualColumnIndex } diff --git a/executor/trace.go b/executor/trace.go index d0ffd92677c10..343a2dfee03c3 100644 --- a/executor/trace.go +++ b/executor/trace.go @@ -39,6 +39,7 @@ import ( "github.com/pingcap/tidb/sessionctx" "github.com/pingcap/tidb/types" "github.com/pingcap/tidb/util/chunk" + "github.com/pingcap/tidb/util/cmp" "github.com/pingcap/tidb/util/logutil" "github.com/pingcap/tidb/util/sqlexec" "github.com/tikv/client-go/v2/util" @@ -312,7 +313,7 @@ func dfsTree(t *appdash.Trace, prefix string, isLast bool, chk *chunk.Chunk) { chk.AppendString(2, duration.String()) // Sort events by their start time - slices.SortFunc(t.Sub, func(i, j *appdash.Trace) bool { + slices.SortFunc(t.Sub, func(i, j *appdash.Trace) int { var istart, jstart time.Time if ievent, err := i.TimespanEvent(); err == nil { istart = ievent.Start() @@ -320,7 +321,7 @@ func dfsTree(t *appdash.Trace, prefix string, isLast bool, chk *chunk.Chunk) { if jevent, err := j.TimespanEvent(); err == nil { jstart = jevent.Start() } - return istart.Before(jstart) + return cmp.Compare(istart.UnixNano(), jstart.UnixNano()) }) for i, sp := range t.Sub { diff --git a/expression/BUILD.bazel b/expression/BUILD.bazel index c7304642c544a..e53cc125755ac 100644 --- a/expression/BUILD.bazel +++ b/expression/BUILD.bazel @@ -86,6 +86,7 @@ go_library( "//types/parser_driver", "//util", "//util/chunk", + "//util/cmp", "//util/codec", "//util/collate", "//util/dbterror", diff --git a/expression/column.go b/expression/column.go index abeca17409ce9..d5a3464667219 100644 --- a/expression/column.go +++ b/expression/column.go @@ -28,6 +28,7 @@ import ( "github.com/pingcap/tidb/sessionctx/stmtctx" "github.com/pingcap/tidb/types" "github.com/pingcap/tidb/util/chunk" + "github.com/pingcap/tidb/util/cmp" "github.com/pingcap/tidb/util/codec" "github.com/pingcap/tidb/util/size" "golang.org/x/exp/slices" @@ -725,8 +726,8 @@ func (col *Column) Repertoire() Repertoire { func SortColumns(cols []*Column) []*Column { sorted := make([]*Column, len(cols)) copy(sorted, cols) - slices.SortFunc(sorted, func(i, j *Column) bool { - return i.UniqueID < j.UniqueID + slices.SortFunc(sorted, func(i, j *Column) int { + return cmp.Compare(i.UniqueID, j.UniqueID) }) return sorted } diff --git a/go.mod b/go.mod index a0e8fa52a0271..242ae256c5bbe 100644 --- a/go.mod +++ b/go.mod @@ -111,15 +111,15 @@ require ( go.uber.org/mock v0.4.0 go.uber.org/multierr v1.8.0 go.uber.org/zap v1.23.0 - golang.org/x/exp v0.0.0-20221023144134-a1e5550cf13e - golang.org/x/net v0.18.0 + golang.org/x/exp v0.0.0-20240531132922-fd00a4e0eefc + golang.org/x/net v0.25.0 golang.org/x/oauth2 v0.2.0 - golang.org/x/sync v0.5.0 - golang.org/x/sys v0.14.0 - golang.org/x/term v0.14.0 - golang.org/x/text v0.14.0 + golang.org/x/sync v0.7.0 + golang.org/x/sys v0.20.0 + golang.org/x/term v0.20.0 + golang.org/x/text v0.15.0 golang.org/x/time v0.2.0 - golang.org/x/tools v0.15.0 + golang.org/x/tools v0.21.0 google.golang.org/api v0.103.0 google.golang.org/grpc v1.51.0 gopkg.in/yaml.v2 v2.4.0 @@ -168,7 +168,7 @@ require ( github.com/goccy/go-json v0.10.2 // indirect github.com/golang/glog v1.0.0 // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect - github.com/google/go-cmp v0.5.9 // indirect + github.com/google/go-cmp v0.6.0 // indirect github.com/google/gofuzz v1.1.0 // indirect github.com/googleapis/enterprise-certificate-proxy v0.2.0 // indirect github.com/googleapis/gax-go/v2 v2.7.0 // indirect @@ -247,9 +247,9 @@ require ( go.opentelemetry.io/otel/sdk/metric v0.20.0 // indirect go.opentelemetry.io/otel/trace v0.20.0 // indirect go.opentelemetry.io/proto/otlp v0.7.0 // indirect - golang.org/x/crypto v0.15.0 // indirect + golang.org/x/crypto v0.23.0 // indirect golang.org/x/exp/typeparams v0.0.0-20220827204233-334a2380cb91 // indirect - golang.org/x/mod v0.14.0 // indirect + golang.org/x/mod v0.17.0 // indirect golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect gonum.org/v1/gonum v0.8.2 // indirect google.golang.org/appengine v1.6.7 // indirect diff --git a/go.sum b/go.sum index 9f9a0600c10cf..c887fbfe052ae 100644 --- a/go.sum +++ b/go.sum @@ -422,8 +422,9 @@ github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= github.com/google/gofuzz v0.0.0-20170612174753-24818f796faf/go.mod h1:HP5RmnzzSNb993RKQDq4+1A4ia9nllfqcQFTQJedwGI= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= @@ -1099,8 +1100,9 @@ golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897/go.mod h1:LzIPMQfyMNhhGPh golang.org/x/crypto v0.0.0-20201112155050-0c6587e931a9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.15.0 h1:frVn1TEaCEaZcn3Tmd7Y2b5KKPaZ+I32Q2OA3kYp5TA= golang.org/x/crypto v0.15.0/go.mod h1:4ChreQoLWfG3xLDer1WdlH5NdlQ3+mwnQq1YTKY+72g= +golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI= +golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= golang.org/x/exp v0.0.0-20180321215751-8460e604b9de/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20180807140117-3d87b88a115f/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= @@ -1115,8 +1117,8 @@ golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u0 golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= golang.org/x/exp v0.0.0-20200513190911-00229845015e/go.mod h1:4M0jN8W1tt0AVLNr8HDosyJCDCDuyL9N9+3m7wDWgKw= -golang.org/x/exp v0.0.0-20221023144134-a1e5550cf13e h1:SkwG94eNiiYJhbeDE018Grw09HIN/KB9NlRmZsrzfWs= -golang.org/x/exp v0.0.0-20221023144134-a1e5550cf13e/go.mod h1:cyybsKvd6eL0RnXn6p/Grxp8F5bW7iYuBgsNCOHpMYE= +golang.org/x/exp v0.0.0-20240531132922-fd00a4e0eefc h1:O9NuF4s+E/PvMIy+9IUZB9znFwUIXEWSstNjek6VpVg= +golang.org/x/exp v0.0.0-20240531132922-fd00a4e0eefc/go.mod h1:XtvwrStGgqGPLc4cjQfWqZHG1YFdYs6swckp8vpsjnc= golang.org/x/exp/typeparams v0.0.0-20220827204233-334a2380cb91 h1:Ic/qN6TEifvObMGQy72k0n1LlJr7DjWWEi+MOsDOiSk= golang.org/x/exp/typeparams v0.0.0-20220827204233-334a2380cb91/go.mod h1:AbB0pIl9nAr9wVwH+Z2ZpaocVmF5I4GyWCDIsVjR0bk= golang.org/x/image v0.0.0-20180708004352-c73c2afc3b81/go.mod h1:ux5Hcp/YLpHSI86hEcLt0YII63i6oz57MZXIpbrjZUs= @@ -1148,8 +1150,8 @@ golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3/go.mod h1:3p9vT2HGsQu2K1YbXdKPJLVgG5VJdoTa1poYQBtP1AY= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.14.0 h1:dGoOF9QVLYng8IHTm7BAyWqCqSheQ5pYWGhzW00YJr0= -golang.org/x/mod v0.14.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/mod v0.17.0 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA= +golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -1204,8 +1206,8 @@ golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug golang.org/x/net v0.1.0/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= -golang.org/x/net v0.18.0 h1:mIYleuAkSbHh0tCv7RvjL3F6ZVbLjq4+R7zbOn3Kokg= -golang.org/x/net v0.18.0/go.mod h1:/czyP5RqHAH4odGYxBJ1qz0+CE5WZ+2j1YgoEo8F2jQ= +golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac= +golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -1228,8 +1230,8 @@ golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.5.0 h1:60k92dhOjHxJkrqnwsfl8KuaHbn/5dl0lUPUklKo3qE= -golang.org/x/sync v0.5.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M= +golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sys v0.0.0-20180816055513-1c9583448a9c/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -1309,15 +1311,17 @@ golang.org/x/sys v0.0.0-20221010170243-090e33056c14/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.14.0 h1:Vz7Qs629MkJkGyHxUlRHizWJRG2j8fbQKjELVSNhy7Q= golang.org/x/sys v0.14.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y= +golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= -golang.org/x/term v0.14.0 h1:LGK9IlZ8T9jvdy6cTdfKUCltatMFOehAQo9SRC46UQ8= golang.org/x/term v0.14.0/go.mod h1:TySc+nGkYR6qt8km8wUhuFRTVSMIX3XPR58y2lC8vww= +golang.org/x/term v0.20.0 h1:VnkxpohqXaOBYJtBmEppKUG6mXpi+4O6purfc2+sMhw= +golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -1330,8 +1334,9 @@ golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= -golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk= +golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -1410,8 +1415,8 @@ golang.org/x/tools v0.1.9/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= golang.org/x/tools v0.1.10/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= -golang.org/x/tools v0.15.0 h1:zdAyfUGbYmuVokhzVmghFl2ZJh5QhcfebBgmVPFYA+8= -golang.org/x/tools v0.15.0/go.mod h1:hpksKq4dtpQWS1uQ61JkdqWM3LscIS6Slf+VVkm+wQk= +golang.org/x/tools v0.21.0 h1:qc0xYgIbsSDt9EyWz05J5wfa7LOVW0YTLOXrqdLAWIw= +golang.org/x/tools v0.21.0/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/infoschema/BUILD.bazel b/infoschema/BUILD.bazel index f5d1563552cdc..f42e45f5050e6 100644 --- a/infoschema/BUILD.bazel +++ b/infoschema/BUILD.bazel @@ -35,6 +35,7 @@ go_library( "//table/tables", "//types", "//util", + "//util/cmp", "//util/dbterror", "//util/deadlockhistory", "//util/domainutil", diff --git a/infoschema/builder.go b/infoschema/builder.go index 30f1a0da8c37e..30e1ee43152cd 100644 --- a/infoschema/builder.go +++ b/infoschema/builder.go @@ -31,6 +31,7 @@ import ( "github.com/pingcap/tidb/parser/model" "github.com/pingcap/tidb/table" "github.com/pingcap/tidb/table/tables" + "github.com/pingcap/tidb/util/cmp" "github.com/pingcap/tidb/util/domainutil" "github.com/pingcap/tidb/util/logutil" "github.com/pingcap/tidb/util/mathutil" @@ -786,8 +787,8 @@ func (b *Builder) applyCreateTable(m *meta.Meta, dbInfo *model.DBInfo, tableID i bucketIdx := tableBucketIdx(tableID) sortedTbls := b.is.sortedTablesBuckets[bucketIdx] sortedTbls = append(sortedTbls, tbl) - slices.SortFunc(sortedTbls, func(i, j table.Table) bool { - return i.Meta().ID < j.Meta().ID + slices.SortFunc(sortedTbls, func(i, j table.Table) int { + return cmp.Compare(i.Meta().ID, j.Meta().ID) }) b.is.sortedTablesBuckets[bucketIdx] = sortedTbls @@ -981,8 +982,8 @@ func (b *Builder) InitWithDBInfos(dbInfos []*model.DBInfo, policies []*model.Pol // Sort all tables by `ID` for _, v := range info.sortedTablesBuckets { - slices.SortFunc(v, func(a, b table.Table) bool { - return a.Meta().ID < b.Meta().ID + slices.SortFunc(v, func(a, b table.Table) int { + return cmp.Compare(a.Meta().ID, b.Meta().ID) }) } return b, nil diff --git a/infoschema/infoschema.go b/infoschema/infoschema.go index 7a7393ca93c14..7f78a11fe420b 100644 --- a/infoschema/infoschema.go +++ b/infoschema/infoschema.go @@ -26,6 +26,7 @@ import ( "github.com/pingcap/tidb/sessionctx" "github.com/pingcap/tidb/table" "github.com/pingcap/tidb/util" + "github.com/pingcap/tidb/util/cmp" "github.com/pingcap/tidb/util/mock" "golang.org/x/exp/slices" ) @@ -135,8 +136,8 @@ func MockInfoSchema(tbList []*model.TableInfo) InfoSchema { result.sortedTablesBuckets[bucketIdx] = append(result.sortedTablesBuckets[bucketIdx], tbl) } for i := range result.sortedTablesBuckets { - slices.SortFunc(result.sortedTablesBuckets[i], func(i, j table.Table) bool { - return i.Meta().ID < j.Meta().ID + slices.SortFunc(result.sortedTablesBuckets[i], func(i, j table.Table) int { + return cmp.Compare(i.Meta().ID, j.Meta().ID) }) } return result @@ -162,8 +163,8 @@ func MockInfoSchemaWithSchemaVer(tbList []*model.TableInfo, schemaVer int64) Inf result.sortedTablesBuckets[bucketIdx] = append(result.sortedTablesBuckets[bucketIdx], tbl) } for i := range result.sortedTablesBuckets { - slices.SortFunc(result.sortedTablesBuckets[i], func(i, j table.Table) bool { - return i.Meta().ID < j.Meta().ID + slices.SortFunc(result.sortedTablesBuckets[i], func(i, j table.Table) int { + return cmp.Compare(i.Meta().ID, j.Meta().ID) }) } result.schemaMetaVersion = schemaVer diff --git a/infoschema/perfschema/tables.go b/infoschema/perfschema/tables.go index 9a5a36235cfa4..075bbcdca9c90 100644 --- a/infoschema/perfschema/tables.go +++ b/infoschema/perfschema/tables.go @@ -394,7 +394,7 @@ func dataForRemoteProfile(ctx sessionctx.Context, nodeType, uri string, isGorout } results = append(results, result) } - slices.SortFunc(results, func(i, j result) bool { return i.addr < j.addr }) + slices.SortFunc(results, func(i, j result) int { return strings.Compare(i.addr, j.addr) }) var finalRows [][]types.Datum for _, result := range results { addr := types.NewStringDatum(result.addr) diff --git a/kv/kv.go b/kv/kv.go index d84c34d1b89c4..0001d93459053 100644 --- a/kv/kv.go +++ b/kv/kv.go @@ -394,20 +394,20 @@ func (rr *KeyRanges) AppendSelfTo(ranges []KeyRange) []KeyRange { // SortByFunc sorts each partition's ranges. // Since the ranges are sorted in most cases, we check it first. -func (rr *KeyRanges) SortByFunc(sortFunc func(i, j KeyRange) bool) { - if !slices.IsSortedFunc(rr.ranges, func(i, j []KeyRange) bool { +func (rr *KeyRanges) SortByFunc(sortFunc func(i, j KeyRange) int) { + if !slices.IsSortedFunc(rr.ranges, func(i, j []KeyRange) int { // A simple short-circuit since the empty range actually won't make anything wrong. if len(i) == 0 || len(j) == 0 { - return true + return -1 } return sortFunc(i[0], j[0]) }) { - slices.SortFunc(rr.ranges, func(i, j []KeyRange) bool { + slices.SortFunc(rr.ranges, func(i, j []KeyRange) int { if len(i) == 0 { - return true + return -1 } if len(j) == 0 { - return false + return 1 } return sortFunc(i[0], j[0]) }) @@ -444,19 +444,19 @@ func (rr *KeyRanges) PartitionNum() int { // IsFullySorted checks whether the ranges are sorted inside partition and each partition is also sorated. func (rr *KeyRanges) IsFullySorted() bool { - sortedByPartition := slices.IsSortedFunc(rr.ranges, func(i, j []KeyRange) bool { + sortedByPartition := slices.IsSortedFunc(rr.ranges, func(i, j []KeyRange) int { // A simple short-circuit since the empty range actually won't make anything wrong. if len(i) == 0 || len(j) == 0 { - return true + return -1 } - return bytes.Compare(i[0].StartKey, j[0].StartKey) < 0 + return bytes.Compare(i[0].StartKey, j[0].StartKey) }) if !sortedByPartition { return false } for _, ranges := range rr.ranges { - if !slices.IsSortedFunc(ranges, func(i, j KeyRange) bool { - return bytes.Compare(i.StartKey, j.StartKey) < 0 + if !slices.IsSortedFunc(ranges, func(i, j KeyRange) int { + return bytes.Compare(i.StartKey, j.StartKey) }) { return false } diff --git a/parser/charset/charset.go b/parser/charset/charset.go index 6067e4f623424..7f970f75b4662 100644 --- a/parser/charset/charset.go +++ b/parser/charset/charset.go @@ -91,8 +91,8 @@ func GetSupportedCharsets() []*Charset { } // sort charset by name. - slices.SortFunc(charsets, func(i, j *Charset) bool { - return i.Name < j.Name + slices.SortFunc(charsets, func(i, j *Charset) int { + return strings.Compare(i.Name, j.Name) }) return charsets } diff --git a/parser/go.mod b/parser/go.mod index 1f49f53d36814..1bda0ab8d8804 100644 --- a/parser/go.mod +++ b/parser/go.mod @@ -10,7 +10,7 @@ require ( github.com/stretchr/testify v1.7.0 go.uber.org/goleak v1.1.10 go.uber.org/zap v1.18.1 - golang.org/x/exp v0.0.0-20220428152302-39d4317da171 + golang.org/x/exp v0.0.0-20231006140011-7918f672742d golang.org/x/text v0.3.7 modernc.org/parser v1.0.2 modernc.org/y v1.0.1 @@ -23,7 +23,7 @@ require ( go.uber.org/atomic v1.7.0 // indirect go.uber.org/multierr v1.6.0 // indirect golang.org/x/lint v0.0.0-20190930215403-16217165b5de // indirect - golang.org/x/tools v0.1.8-0.20211029000441-d6a9af8af023 // indirect + golang.org/x/tools v0.21.0 // indirect gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect modernc.org/golex v1.0.1 // indirect diff --git a/parser/go.sum b/parser/go.sum index 267fe82580882..266ecba17f5d8 100644 --- a/parser/go.sum +++ b/parser/go.sum @@ -48,23 +48,24 @@ go.uber.org/zap v1.18.1 h1:CSUJ2mjFszzEWt4CdKISEuChVIXGBn3lAPwkRGyVrc4= go.uber.org/zap v1.18.1/go.mod h1:xg/QME4nWcxGxrpdeYfq7UvYrLh66cuVKdrbD1XF/NI= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/exp v0.0.0-20181106170214-d68db9428509/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/exp v0.0.0-20220428152302-39d4317da171 h1:TfdoLivD44QwvssI9Sv1xwa5DcL5XQr4au4sZ2F2NV4= -golang.org/x/exp v0.0.0-20220428152302-39d4317da171/go.mod h1:lgLbSvA5ygNOMpwM/9anMpWVlVJ7Z+cHWq/eFuinpGE= +golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI= +golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo= golang.org/x/lint v0.0.0-20190930215403-16217165b5de h1:5hukYrvBGR8/eNkX5mdUezrA6JiaEZDtJb9Ei+1LlBs= golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/mod v0.17.0 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20211019181941-9d821ace8654 h1:id054HUawV2/6IGm2IV8KZQjqtwAOo2CYlOToYqa0d0= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191108193012-7d206e10da11/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.1.8-0.20211029000441-d6a9af8af023 h1:0c3L82FDQ5rt1bjTBlchS8t6RQ6299/+5bWMnRLh+uI= -golang.org/x/tools v0.1.8-0.20211029000441-d6a9af8af023/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= +golang.org/x/tools v0.21.0 h1:qc0xYgIbsSDt9EyWz05J5wfa7LOVW0YTLOXrqdLAWIw= +golang.org/x/tools v0.21.0/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= diff --git a/parser/model/model.go b/parser/model/model.go index 89db1169ebc9e..c0c0db87e7edc 100644 --- a/parser/model/model.go +++ b/parser/model/model.go @@ -1675,8 +1675,8 @@ func (db *DBInfo) Copy() *DBInfo { } // LessDBInfo is used for sorting DBInfo by DBInfo.Name. -func LessDBInfo(a *DBInfo, b *DBInfo) bool { - return a.Name.L < b.Name.L +func LessDBInfo(a *DBInfo, b *DBInfo) int { + return strings.Compare(a.Name.L, b.Name.L) } // CIStr is case insensitive string. diff --git a/planner/core/BUILD.bazel b/planner/core/BUILD.bazel index 747f35d70cbd7..8ccc4a2aa40e5 100644 --- a/planner/core/BUILD.bazel +++ b/planner/core/BUILD.bazel @@ -116,6 +116,7 @@ go_library( "//types/parser_driver", "//util", "//util/chunk", + "//util/cmp", "//util/codec", "//util/collate", "//util/dbterror", diff --git a/planner/core/fragment.go b/planner/core/fragment.go index 917f4392d9f9e..4c51026d10bf9 100644 --- a/planner/core/fragment.go +++ b/planner/core/fragment.go @@ -28,6 +28,7 @@ import ( "github.com/pingcap/tidb/sessionctx" "github.com/pingcap/tidb/table" "github.com/pingcap/tidb/types" + "github.com/pingcap/tidb/util/cmp" "github.com/pingcap/tidb/util/logutil" "github.com/pingcap/tidb/util/ranger" "github.com/pingcap/tidb/util/size" @@ -392,8 +393,8 @@ func (e *mppTaskGenerator) constructMPPTasksImpl(ctx context.Context, ts *Physic } func (e *mppTaskGenerator) constructMPPBuildTaskReqForPartitionedTable(ts *PhysicalTableScan, splitedRanges []*ranger.Range, partitions []table.PhysicalTable) (*kv.MPPBuildTasksRequest, []int64, error) { - slices.SortFunc(partitions, func(i, j table.PhysicalTable) bool { - return i.GetPhysicalID() < j.GetPhysicalID() + slices.SortFunc(partitions, func(i, j table.PhysicalTable) int { + return cmp.Compare(i.GetPhysicalID(), j.GetPhysicalID()) }) partitionIDAndRanges := make([]kv.PartitionIDAndRanges, len(partitions)) allPartitionsIDs := make([]int64, len(partitions)) diff --git a/planner/core/hashcode.go b/planner/core/hashcode.go index 41b00de127390..9509483dc5dc1 100644 --- a/planner/core/hashcode.go +++ b/planner/core/hashcode.go @@ -79,7 +79,7 @@ func (p *LogicalSelection) HashCode() []byte { condHashCodes[i] = expr.HashCode(p.ctx.GetSessionVars().StmtCtx) } // Sort the conditions, so `a > 1 and a < 100` can equal to `a < 100 and a > 1`. - slices.SortFunc(condHashCodes, func(i, j []byte) bool { return bytes.Compare(i, j) < 0 }) + slices.SortFunc(condHashCodes, func(i, j []byte) int { return bytes.Compare(i, j) }) for _, condHashCode := range condHashCodes { result = encodeIntAsUint32(result, len(condHashCode)) diff --git a/planner/core/optimizer.go b/planner/core/optimizer.go index 36a49d79f4e85..bbb419679f8bb 100644 --- a/planner/core/optimizer.go +++ b/planner/core/optimizer.go @@ -35,6 +35,7 @@ import ( "github.com/pingcap/tidb/sessionctx" "github.com/pingcap/tidb/sessionctx/variable" "github.com/pingcap/tidb/types" + "github.com/pingcap/tidb/util/cmp" utilhint "github.com/pingcap/tidb/util/hint" "github.com/pingcap/tidb/util/logutil" "github.com/pingcap/tidb/util/set" @@ -322,24 +323,24 @@ func DoOptimize(ctx context.Context, sctx sessionctx.Context, flag uint64, logic func refineCETrace(sctx sessionctx.Context) { stmtCtx := sctx.GetSessionVars().StmtCtx stmtCtx.OptimizerCETrace = tracing.DedupCETrace(stmtCtx.OptimizerCETrace) - slices.SortFunc(stmtCtx.OptimizerCETrace, func(i, j *tracing.CETraceRecord) bool { + slices.SortFunc(stmtCtx.OptimizerCETrace, func(i, j *tracing.CETraceRecord) int { if i == nil && j != nil { - return true + return -1 } if i == nil || j == nil { - return false + return 1 } - if i.TableID != j.TableID { - return i.TableID < j.TableID + if c := cmp.Compare(i.TableID, j.TableID); c != 0 { + return c } - if i.Type != j.Type { - return i.Type < j.Type + if c := cmp.Compare(i.Type, j.Type); c != 0 { + return c } - if i.Expr != j.Expr { - return i.Expr < j.Expr + if c := cmp.Compare(i.Expr, j.Expr); c != 0 { + return c } - return i.RowCount < j.RowCount + return cmp.Compare(i.RowCount, j.RowCount) }) traceRecords := stmtCtx.OptimizerCETrace is := sctx.GetDomainInfoSchema().(infoschema.InfoSchema) diff --git a/planner/core/plan_cache_utils.go b/planner/core/plan_cache_utils.go index f41f5a1c84659..cb526a4257b79 100644 --- a/planner/core/plan_cache_utils.go +++ b/planner/core/plan_cache_utils.go @@ -34,6 +34,7 @@ import ( "github.com/pingcap/tidb/sessionctx/variable" "github.com/pingcap/tidb/types" driver "github.com/pingcap/tidb/types/parser_driver" + "github.com/pingcap/tidb/util/cmp" "github.com/pingcap/tidb/util/codec" "github.com/pingcap/tidb/util/hack" "github.com/pingcap/tidb/util/hint" @@ -101,8 +102,8 @@ func GeneratePlanCacheStmtWithAST(ctx context.Context, sctx sessionctx.Context, // The parameter markers are appended in visiting order, which may not // be the same as the position order in the query string. We need to // sort it by position. - slices.SortFunc(extractor.markers, func(i, j ast.ParamMarkerExpr) bool { - return i.(*driver.ParamMarkerExpr).Offset < j.(*driver.ParamMarkerExpr).Offset + slices.SortFunc(extractor.markers, func(i, j ast.ParamMarkerExpr) int { + return cmp.Compare(i.(*driver.ParamMarkerExpr).Offset, j.(*driver.ParamMarkerExpr).Offset) }) ParamCount := len(extractor.markers) for i := 0; i < ParamCount; i++ { diff --git a/planner/core/rule_partition_processor.go b/planner/core/rule_partition_processor.go index cc5162cfe2233..6c26d05ba033e 100644 --- a/planner/core/rule_partition_processor.go +++ b/planner/core/rule_partition_processor.go @@ -32,6 +32,7 @@ import ( "github.com/pingcap/tidb/table/tables" "github.com/pingcap/tidb/types" "github.com/pingcap/tidb/util/chunk" + "github.com/pingcap/tidb/util/cmp" "github.com/pingcap/tidb/util/collate" "github.com/pingcap/tidb/util/mathutil" "github.com/pingcap/tidb/util/plancodec" @@ -1812,8 +1813,8 @@ func appendMakeUnionAllChildrenTranceStep(origin *DataSource, usedMap map[int64] for _, def := range usedMap { used = append(used, def) } - slices.SortFunc(used, func(i, j model.PartitionDefinition) bool { - return i.ID < j.ID + slices.SortFunc(used, func(i, j model.PartitionDefinition) int { + return cmp.Compare(i.ID, j.ID) }) if len(children) == 1 { newDS := plan.(*DataSource) diff --git a/privilege/privileges/BUILD.bazel b/privilege/privileges/BUILD.bazel index 563ea25ee90ed..954728a681cd3 100644 --- a/privilege/privileges/BUILD.bazel +++ b/privilege/privileges/BUILD.bazel @@ -25,6 +25,7 @@ go_library( "//types", "//util", "//util/chunk", + "//util/cmp", "//util/dbterror", "//util/hack", "//util/logutil", diff --git a/privilege/privileges/cache.go b/privilege/privileges/cache.go index 301f95ef9a1e3..10b3ec86ae89e 100644 --- a/privilege/privileges/cache.go +++ b/privilege/privileges/cache.go @@ -35,6 +35,7 @@ import ( "github.com/pingcap/tidb/types" "github.com/pingcap/tidb/util" "github.com/pingcap/tidb/util/chunk" + "github.com/pingcap/tidb/util/cmp" "github.com/pingcap/tidb/util/hack" "github.com/pingcap/tidb/util/logutil" "github.com/pingcap/tidb/util/sem" @@ -444,21 +445,17 @@ func (p *MySQLPrivilege) buildUserMap() { p.UserMap = userMap } -func compareBaseRecord(x, y *baseRecord) bool { +func compareBaseRecord(x, y *baseRecord) int { // Compare two item by user's host first. c1 := compareHost(x.Host, y.Host) - if c1 < 0 { - return true - } - if c1 > 0 { - return false + if c1 != 0 { + return c1 } - // Then, compare item by user's name value. - return x.User < y.User + return cmp.Compare(x.User, y.User) } -func compareUserRecord(x, y UserRecord) bool { +func compareUserRecord(x, y UserRecord) int { return compareBaseRecord(&x.baseRecord, &y.baseRecord) } @@ -536,7 +533,7 @@ func (p *MySQLPrivilege) LoadDBTable(ctx sessionctx.Context) error { return nil } -func compareDBRecord(x, y dbRecord) bool { +func compareDBRecord(x, y dbRecord) int { return compareBaseRecord(&x.baseRecord, &y.baseRecord) } diff --git a/statistics/BUILD.bazel b/statistics/BUILD.bazel index f2bfac72a1605..ab8d75bf24c1a 100644 --- a/statistics/BUILD.bazel +++ b/statistics/BUILD.bazel @@ -41,6 +41,7 @@ go_library( "//types", "//types/parser_driver", "//util/chunk", + "//util/cmp", "//util/codec", "//util/collate", "//util/dbterror", diff --git a/statistics/cmsketch.go b/statistics/cmsketch.go index 9d6a9a9cd3fa9..dd0381f42153b 100644 --- a/statistics/cmsketch.go +++ b/statistics/cmsketch.go @@ -32,6 +32,7 @@ import ( "github.com/pingcap/tidb/tablecodec" "github.com/pingcap/tidb/types" "github.com/pingcap/tidb/util/chunk" + "github.com/pingcap/tidb/util/cmp" "github.com/pingcap/tidb/util/codec" "github.com/pingcap/tidb/util/dbterror" "github.com/pingcap/tidb/util/hack" @@ -650,8 +651,8 @@ func (c *TopN) Sort() { if c == nil { return } - slices.SortFunc(c.TopN, func(i, j TopNMeta) bool { - return bytes.Compare(i.Encoded, j.Encoded) < 0 + slices.SortFunc(c.TopN, func(i, j TopNMeta) int { + return bytes.Compare(i.Encoded, j.Encoded) }) } @@ -871,11 +872,11 @@ func CheckEmptyTopNs(topNs []*TopN) bool { // SortTopnMeta sort topnMeta func SortTopnMeta(topnMetas []TopNMeta) []TopNMeta { - slices.SortFunc(topnMetas, func(i, j TopNMeta) bool { + slices.SortFunc(topnMetas, func(i, j TopNMeta) int { if i.Count != j.Count { - return i.Count > j.Count + return cmp.Compare(j.Count, i.Count) } - return bytes.Compare(i.Encoded, j.Encoded) < 0 + return bytes.Compare(i.Encoded, j.Encoded) }) return topnMetas } @@ -886,11 +887,11 @@ func GetMergedTopNFromSortedSlice(sorted []TopNMeta, n uint32) (*TopN, []TopNMet } func getMergedTopNFromSortedSlice(sorted []TopNMeta, n uint32) (*TopN, []TopNMeta) { - slices.SortFunc(sorted, func(i, j TopNMeta) bool { + slices.SortFunc(sorted, func(i, j TopNMeta) int { if i.Count != j.Count { - return i.Count > j.Count + return cmp.Compare(j.Count, i.Count) } - return bytes.Compare(i.Encoded, j.Encoded) < 0 + return bytes.Compare(i.Encoded, j.Encoded) }) n = mathutil.Min(uint32(len(sorted)), n) diff --git a/statistics/feedback.go b/statistics/feedback.go index 910d44167a1b0..ddbd688b913bf 100644 --- a/statistics/feedback.go +++ b/statistics/feedback.go @@ -353,19 +353,19 @@ func NonOverlappedFeedbacks(sc *stmtctx.StatementContext, fbs []Feedback) ([]Fee // Sort feedbacks by end point and start point incrementally, then pick every feedback that is not overlapped // with the previous chosen feedbacks. var existsErr bool - slices.SortFunc(fbs, func(i, j Feedback) bool { + slices.SortFunc(fbs, func(i, j Feedback) int { res, err := i.Upper.Compare(sc, j.Upper, collate.GetBinaryCollator()) if err != nil { existsErr = true } if existsErr || res != 0 { - return res < 0 + return res } res, err = i.Lower.Compare(sc, j.Lower, collate.GetBinaryCollator()) if err != nil { existsErr = true } - return res < 0 + return res }) if existsErr { return fbs, false diff --git a/statistics/handle/BUILD.bazel b/statistics/handle/BUILD.bazel index 5747364d0c766..bc682007042cb 100644 --- a/statistics/handle/BUILD.bazel +++ b/statistics/handle/BUILD.bazel @@ -34,6 +34,7 @@ go_library( "//types", "//util", "//util/chunk", + "//util/cmp", "//util/codec", "//util/collate", "//util/hack", diff --git a/statistics/handle/update.go b/statistics/handle/update.go index ef88791631f4d..2dc48e60c82a2 100644 --- a/statistics/handle/update.go +++ b/statistics/handle/update.go @@ -39,6 +39,7 @@ import ( "github.com/pingcap/tidb/types" "github.com/pingcap/tidb/util" "github.com/pingcap/tidb/util/chunk" + "github.com/pingcap/tidb/util/cmp" "github.com/pingcap/tidb/util/codec" "github.com/pingcap/tidb/util/collate" "github.com/pingcap/tidb/util/logutil" @@ -950,11 +951,11 @@ func (h *Handle) DumpColStatsUsageToKV() error { for id, t := range colMap { pairs = append(pairs, pair{tblColID: id, lastUsedAt: t.UTC().Format(types.TimeFormat)}) } - slices.SortFunc(pairs, func(i, j pair) bool { + slices.SortFunc(pairs, func(i, j pair) int { if i.tblColID.TableID == j.tblColID.TableID { - return i.tblColID.ID < j.tblColID.ID + return cmp.Compare(i.tblColID.ID, j.tblColID.ID) } - return i.tblColID.TableID < j.tblColID.TableID + return cmp.Compare(i.tblColID.TableID, j.tblColID.TableID) }) // Use batch insert to reduce cost. for i := 0; i < len(pairs); i += batchInsertSize { diff --git a/statistics/histogram.go b/statistics/histogram.go index a9aedf8a1d247..f1c50774ae578 100644 --- a/statistics/histogram.go +++ b/statistics/histogram.go @@ -347,8 +347,8 @@ func (hg *Histogram) RemoveVals(valCntPairs []TopNMeta) { // AddIdxVals adds the given values to the histogram. func (hg *Histogram) AddIdxVals(idxValCntPairs []TopNMeta) { totalAddCnt := int64(0) - slices.SortFunc(idxValCntPairs, func(i, j TopNMeta) bool { - return bytes.Compare(i.Encoded, j.Encoded) < 0 + slices.SortFunc(idxValCntPairs, func(i, j TopNMeta) int { + return bytes.Compare(i.Encoded, j.Encoded) }) for bktIdx, pairIdx := 0, 0; bktIdx < hg.Len(); bktIdx++ { for pairIdx < len(idxValCntPairs) { @@ -1475,19 +1475,19 @@ func MergePartitionHist2GlobalHist(sc *stmtctx.StatementContext, hists []*Histog buckets = buckets[:tail] var sortError error - slices.SortFunc(buckets, func(i, j *bucket4Merging) bool { + slices.SortFunc(buckets, func(i, j *bucket4Merging) int { res, err := i.upper.Compare(sc, j.upper, collate.GetBinaryCollator()) if err != nil { sortError = err } if res != 0 { - return res < 0 + return res } res, err = i.lower.Compare(sc, j.lower, collate.GetBinaryCollator()) if err != nil { sortError = err } - return res < 0 + return res }) if sortError != nil { return nil, sortError diff --git a/statistics/selectivity.go b/statistics/selectivity.go index 99458cc04bea6..61729debad741 100644 --- a/statistics/selectivity.go +++ b/statistics/selectivity.go @@ -29,6 +29,7 @@ import ( "github.com/pingcap/tidb/types" driver "github.com/pingcap/tidb/types/parser_driver" "github.com/pingcap/tidb/util/chunk" + "github.com/pingcap/tidb/util/cmp" "github.com/pingcap/tidb/util/logutil" "github.com/pingcap/tidb/util/ranger" "github.com/pingcap/tidb/util/tracing" @@ -534,11 +535,11 @@ func getMaskAndRanges(ctx sessionctx.Context, exprs []expression.Expression, ran // GetUsableSetsByGreedy will select the indices and pk used for calculate selectivity by greedy algorithm. func GetUsableSetsByGreedy(nodes []*StatsNode) (newBlocks []*StatsNode) { - slices.SortFunc(nodes, func(i, j *StatsNode) bool { + slices.SortFunc(nodes, func(i, j *StatsNode) int { if r := compareType(i.Tp, j.Tp); r != 0 { - return r < 0 + return r } - return i.ID < j.ID + return cmp.Compare(i.ID, j.ID) }) marked := make([]bool, len(nodes)) mask := int64(math.MaxInt64) diff --git a/statistics/table.go b/statistics/table.go index b9c0bcb5be777..6345f4e9a9bba 100644 --- a/statistics/table.go +++ b/statistics/table.go @@ -30,6 +30,7 @@ import ( "github.com/pingcap/tidb/tablecodec" "github.com/pingcap/tidb/types" "github.com/pingcap/tidb/util/chunk" + "github.com/pingcap/tidb/util/cmp" "github.com/pingcap/tidb/util/codec" "github.com/pingcap/tidb/util/collate" "github.com/pingcap/tidb/util/logutil" @@ -341,7 +342,7 @@ func (t *Table) String() string { for _, col := range t.Columns { cols = append(cols, col) } - slices.SortFunc(cols, func(i, j *Column) bool { return i.ID < j.ID }) + slices.SortFunc(cols, func(i, j *Column) int { return cmp.Compare(i.ID, j.ID) }) for _, col := range cols { strs = append(strs, col.String()) } @@ -349,7 +350,7 @@ func (t *Table) String() string { for _, idx := range t.Indices { idxs = append(idxs, idx) } - slices.SortFunc(idxs, func(i, j *Index) bool { return i.ID < j.ID }) + slices.SortFunc(idxs, func(i, j *Index) int { return cmp.Compare(i.ID, j.ID) }) for _, idx := range idxs { strs = append(strs, idx.String()) } diff --git a/store/copr/BUILD.bazel b/store/copr/BUILD.bazel index 1de1a6ba66af6..1d3238f13e93a 100644 --- a/store/copr/BUILD.bazel +++ b/store/copr/BUILD.bazel @@ -26,6 +26,7 @@ go_library( "//store/driver/error", "//store/driver/options", "//util", + "//util/cmp", "//util/execdetails", "//util/logutil", "//util/mathutil", diff --git a/store/copr/batch_coprocessor.go b/store/copr/batch_coprocessor.go index 85f2e983851f0..6f8923344fe9c 100644 --- a/store/copr/batch_coprocessor.go +++ b/store/copr/batch_coprocessor.go @@ -33,6 +33,7 @@ import ( "github.com/pingcap/tidb/kv" "github.com/pingcap/tidb/store/driver/backoff" derr "github.com/pingcap/tidb/store/driver/error" + "github.com/pingcap/tidb/util/cmp" "github.com/pingcap/tidb/util/logutil" "github.com/tikv/client-go/v2/metrics" "github.com/tikv/client-go/v2/tikv" @@ -207,13 +208,13 @@ func balanceBatchCopTaskWithContinuity(storeTaskMap map[uint64]*batchCopTask, ca storeTasks := deepCopyStoreTaskMap(storeTaskMap) // Sort regions by their key ranges. - slices.SortFunc(candidateRegionInfos, func(i, j RegionInfo) bool { + slices.SortFunc(candidateRegionInfos, func(i, j RegionInfo) int { // Special case: Sort empty ranges to the end. if i.Ranges.Len() < 1 || j.Ranges.Len() < 1 { - return i.Ranges.Len() > j.Ranges.Len() + return cmp.Compare(j.Ranges.Len(), i.Ranges.Len()) } // StartKey0 < StartKey1 - return bytes.Compare(i.Ranges.At(0).StartKey, j.Ranges.At(0).StartKey) == -1 + return bytes.Compare(i.Ranges.At(0).StartKey, j.Ranges.At(0).StartKey) }) balanceStart := time.Now() @@ -835,8 +836,8 @@ func (b *batchCopIterator) retryBatchCopTask(ctx context.Context, bo *backoff.Ba }) } // need to make sure the key ranges is sorted - slices.SortFunc(ranges, func(i, j kv.KeyRange) bool { - return bytes.Compare(i.StartKey, j.StartKey) < 0 + slices.SortFunc(ranges, func(i, j kv.KeyRange) int { + return bytes.Compare(i.StartKey, j.StartKey) }) ret, err := buildBatchCopTasksForNonPartitionedTable(bo, b.store, NewKeyRanges(ranges), b.req.StoreType, false, 0, false, 0) return ret, err @@ -856,8 +857,8 @@ func (b *batchCopIterator) retryBatchCopTask(ctx context.Context, bo *backoff.Ba } } // need to make sure the key ranges is sorted - slices.SortFunc(ranges, func(i, j kv.KeyRange) bool { - return bytes.Compare(i.StartKey, j.StartKey) < 0 + slices.SortFunc(ranges, func(i, j kv.KeyRange) int { + return bytes.Compare(i.StartKey, j.StartKey) }) keyRanges = append(keyRanges, NewKeyRanges(ranges)) } diff --git a/store/gcworker/gc_worker.go b/store/gcworker/gc_worker.go index e9365d727777a..15f759d42ca9a 100644 --- a/store/gcworker/gc_worker.go +++ b/store/gcworker/gc_worker.go @@ -1234,8 +1234,8 @@ func (w *GCWorker) checkLockObservers(ctx context.Context, safePoint uint64, sto for i, lockInfo := range respInner.Locks { locks[i] = txnlock.NewLock(lockInfo) } - slices.SortFunc(locks, func(i, j *txnlock.Lock) bool { - return bytes.Compare(i.Key, j.Key) < 0 + slices.SortFunc(locks, func(i, j *txnlock.Lock) int { + return bytes.Compare(i.Key, j.Key) }) err = w.resolveLocksAcrossRegions(ctx, locks) diff --git a/store/helper/helper.go b/store/helper/helper.go index 5ff582f75e928..99299f6c71c60 100644 --- a/store/helper/helper.go +++ b/store/helper/helper.go @@ -824,8 +824,8 @@ func (*Helper) GetTablesInfoWithKeyRange(schemas []*model.DBInfo) []TableInfoWit } } } - slices.SortFunc(tables, func(i, j TableInfoWithKeyRange) bool { - return i.getStartKey() < j.getStartKey() + slices.SortFunc(tables, func(i, j TableInfoWithKeyRange) int { + return strings.Compare(i.getStartKey(), j.getStartKey()) }) return tables } @@ -838,8 +838,8 @@ func (*Helper) ParseRegionsTableInfos(regionsInfo []*RegionInfo, tables []TableI return tableInfos } // tables is sorted in GetTablesInfoWithKeyRange func - slices.SortFunc(regionsInfo, func(i, j *RegionInfo) bool { - return i.getStartKey() < j.getStartKey() + slices.SortFunc(regionsInfo, func(i, j *RegionInfo) int { + return strings.Compare(i.getStartKey(), j.getStartKey()) }) idx := 0 diff --git a/store/mockstore/unistore/cophandler/BUILD.bazel b/store/mockstore/unistore/cophandler/BUILD.bazel index 91dc48a88798c..2f9a81953035f 100644 --- a/store/mockstore/unistore/cophandler/BUILD.bazel +++ b/store/mockstore/unistore/cophandler/BUILD.bazel @@ -33,6 +33,7 @@ go_library( "//types", "//util", "//util/chunk", + "//util/cmp", "//util/codec", "//util/collate", "//util/mock", diff --git a/store/mockstore/unistore/cophandler/analyze.go b/store/mockstore/unistore/cophandler/analyze.go index a04b158e4b4a6..3f179d18d8f97 100644 --- a/store/mockstore/unistore/cophandler/analyze.go +++ b/store/mockstore/unistore/cophandler/analyze.go @@ -36,6 +36,7 @@ import ( "github.com/pingcap/tidb/tablecodec" "github.com/pingcap/tidb/types" "github.com/pingcap/tidb/util/chunk" + "github.com/pingcap/tidb/util/cmp" "github.com/pingcap/tidb/util/collate" "github.com/pingcap/tidb/util/rowcodec" "github.com/pingcap/tipb/go-tipb" @@ -112,13 +113,12 @@ func handleAnalyzeIndexReq(dbReader *dbreader.DBReader, rans []kv.KeyRange, anal if processor.topNCurValuePair.Count != 0 { processor.topNValuePairs = append(processor.topNValuePairs, processor.topNCurValuePair) } - slices.SortFunc(processor.topNValuePairs, func(i, j statistics.TopNMeta) bool { - if i.Count > j.Count { - return true - } else if i.Count < j.Count { - return false + slices.SortFunc(processor.topNValuePairs, func(i, j statistics.TopNMeta) int { + c := cmp.Compare(j.Count, i.Count) + if c != 0 { + return c } - return bytes.Compare(i.Encoded, j.Encoded) < 0 + return bytes.Compare(i.Encoded, j.Encoded) }) if len(processor.topNValuePairs) > int(processor.topNCount) { processor.topNValuePairs = processor.topNValuePairs[:processor.topNCount] @@ -564,13 +564,12 @@ func handleAnalyzeMixedReq(dbReader *dbreader.DBReader, rans []kv.KeyRange, anal if e.topNCurValuePair.Count != 0 { e.topNValuePairs = append(e.topNValuePairs, e.topNCurValuePair) } - slices.SortFunc(e.topNValuePairs, func(i, j statistics.TopNMeta) bool { - if i.Count > j.Count { - return true - } else if i.Count < j.Count { - return false + slices.SortFunc(e.topNValuePairs, func(i, j statistics.TopNMeta) int { + c := cmp.Compare(j.Count, i.Count) + if c != 0 { + return c } - return bytes.Compare(i.Encoded, j.Encoded) < 0 + return bytes.Compare(i.Encoded, j.Encoded) }) if len(e.topNValuePairs) > int(e.topNCount) { e.topNValuePairs = e.topNValuePairs[:e.topNCount] diff --git a/store/mockstore/unistore/tikv/BUILD.bazel b/store/mockstore/unistore/tikv/BUILD.bazel index 91db06dd09dfa..665b86b761816 100644 --- a/store/mockstore/unistore/tikv/BUILD.bazel +++ b/store/mockstore/unistore/tikv/BUILD.bazel @@ -32,6 +32,7 @@ go_library( "//store/mockstore/unistore/util/lockwaiter", "//tablecodec", "//types", + "//util/cmp", "//util/codec", "//util/mathutil", "//util/rowcodec", diff --git a/store/mockstore/unistore/tikv/mock_region.go b/store/mockstore/unistore/tikv/mock_region.go index f2bdbe9e71c3e..1fe60b10af94d 100644 --- a/store/mockstore/unistore/tikv/mock_region.go +++ b/store/mockstore/unistore/tikv/mock_region.go @@ -414,8 +414,8 @@ func (rm *MockRegionManager) SplitRegion(req *kvrpcpb.SplitRegionRequest) *kvrpc for _, rawKey := range req.SplitKeys { splitKeys = append(splitKeys, codec.EncodeBytes(nil, rawKey)) } - slices.SortFunc(splitKeys, func(i, j []byte) bool { - return bytes.Compare(i, j) < 0 + slices.SortFunc(splitKeys, func(i, j []byte) int { + return bytes.Compare(i, j) }) newRegions, err := rm.splitKeys(splitKeys) diff --git a/store/mockstore/unistore/tikv/mvcc.go b/store/mockstore/unistore/tikv/mvcc.go index 8efd8f26ee75c..ceeeb7095d101 100644 --- a/store/mockstore/unistore/tikv/mvcc.go +++ b/store/mockstore/unistore/tikv/mvcc.go @@ -40,6 +40,7 @@ import ( "github.com/pingcap/tidb/store/mockstore/unistore/tikv/mvcc" "github.com/pingcap/tidb/store/mockstore/unistore/util/lockwaiter" "github.com/pingcap/tidb/types" + "github.com/pingcap/tidb/util/cmp" "github.com/pingcap/tidb/util/codec" "github.com/pingcap/tidb/util/rowcodec" "github.com/tikv/client-go/v2/oracle" @@ -175,8 +176,8 @@ func (store *MVCCStore) getDBItems(reqCtx *requestCtx, mutations []*kvrpcpb.Muta } func sortMutations(mutations []*kvrpcpb.Mutation) []*kvrpcpb.Mutation { - fn := func(i, j *kvrpcpb.Mutation) bool { - return bytes.Compare(i.Key, j.Key) < 0 + fn := func(i, j *kvrpcpb.Mutation) int { + return bytes.Compare(i.Key, j.Key) } if slices.IsSortedFunc(mutations, fn) { return mutations @@ -215,8 +216,8 @@ func (sorter pessimisticPrewriteSorter) Swap(i, j int) { } func sortKeys(keys [][]byte) [][]byte { - less := func(i, j []byte) bool { - return bytes.Compare(i, j) < 0 + less := func(i, j []byte) int { + return bytes.Compare(i, j) } if slices.IsSortedFunc(keys, less) { return keys @@ -1447,8 +1448,8 @@ func (store *MVCCStore) MvccGetByKey(reqCtx *requestCtx, key []byte) (*kvrpcpb.M if err != nil { return nil, err } - slices.SortFunc(mvccInfo.Writes, func(i, j *kvrpcpb.MvccWrite) bool { - return i.CommitTs > j.CommitTs + slices.SortFunc(mvccInfo.Writes, func(i, j *kvrpcpb.MvccWrite) int { + return cmp.Compare(j.CommitTs, i.CommitTs) }) mvccInfo.Values = make([]*kvrpcpb.MvccValue, len(mvccInfo.Writes)) for i := 0; i < len(mvccInfo.Writes); i++ { diff --git a/store/mockstore/unistore/util/lockwaiter/BUILD.bazel b/store/mockstore/unistore/util/lockwaiter/BUILD.bazel index 757f51ef806f0..81bafb702303d 100644 --- a/store/mockstore/unistore/util/lockwaiter/BUILD.bazel +++ b/store/mockstore/unistore/util/lockwaiter/BUILD.bazel @@ -7,6 +7,7 @@ go_library( visibility = ["//visibility:public"], deps = [ "//store/mockstore/unistore/config", + "//util/cmp", "@com_github_pingcap_kvproto//pkg/deadlock", "@com_github_pingcap_log//:log", "@org_golang_x_exp//slices", diff --git a/store/mockstore/unistore/util/lockwaiter/lockwaiter.go b/store/mockstore/unistore/util/lockwaiter/lockwaiter.go index 979eed53652c2..32c4b99e8ae46 100644 --- a/store/mockstore/unistore/util/lockwaiter/lockwaiter.go +++ b/store/mockstore/unistore/util/lockwaiter/lockwaiter.go @@ -21,6 +21,7 @@ import ( "github.com/pingcap/kvproto/pkg/deadlock" "github.com/pingcap/log" "github.com/pingcap/tidb/store/mockstore/unistore/config" + "github.com/pingcap/tidb/util/cmp" "go.uber.org/zap" "golang.org/x/exp/slices" ) @@ -51,8 +52,8 @@ type queue struct { func (q *queue) getOldestWaiter() (*Waiter, []*Waiter) { // make the waiters in start ts order - slices.SortFunc(q.waiters, func(i, j *Waiter) bool { - return i.startTS < j.startTS + slices.SortFunc(q.waiters, func(i, j *Waiter) int { + return cmp.Compare(i.startTS, j.startTS) }) oldestWaiter := q.waiters[0] remainWaiter := q.waiters[1:] diff --git a/store/pdtypes/region_tree.go b/store/pdtypes/region_tree.go index cc99e981e0097..7971424dcd953 100644 --- a/store/pdtypes/region_tree.go +++ b/store/pdtypes/region_tree.go @@ -52,8 +52,8 @@ func (t *RegionTree) SetRegion(region *Region) { // ScanRange scans regions intersecting [start key, end key), returns at most // `limit` regions. limit <= 0 means no limit. func (t *RegionTree) ScanRange(startKey, endKey []byte, limit int) []*Region { - slices.SortFunc(t.Regions, func(i, j *Region) bool { - return bytes.Compare(i.Meta.StartKey, j.Meta.StartKey) < 0 + slices.SortFunc(t.Regions, func(i, j *Region) int { + return bytes.Compare(i.Meta.StartKey, j.Meta.StartKey) }) pivot := NewRegionInfo(&metapb.Region{StartKey: startKey, EndKey: endKey}, nil) var res []*Region diff --git a/table/temptable/main_test.go b/table/temptable/main_test.go index 8c5c4f557e1ae..c3a8ba15386eb 100644 --- a/table/temptable/main_test.go +++ b/table/temptable/main_test.go @@ -126,7 +126,7 @@ func newMockedRetriever(t *testing.T) *mockedRetriever { } func (r *mockedRetriever) SetData(data []*kv.Entry) *mockedRetriever { - lessFunc := func(i, j *kv.Entry) bool { return bytes.Compare(i.Key, j.Key) < 0 } + lessFunc := func(i, j *kv.Entry) int { return bytes.Compare(i.Key, j.Key) } if !slices.IsSortedFunc(data, lessFunc) { data = append([]*kv.Entry{}, data...) slices.SortFunc(data, lessFunc) diff --git a/testkit/result.go b/testkit/result.go index 5debc9b1ee242..44950b5faf039 100644 --- a/testkit/result.go +++ b/testkit/result.go @@ -71,15 +71,8 @@ func Rows(args ...string) [][]interface{} { // Sort sorts and return the result. func (res *Result) Sort() *Result { - slices.SortFunc(res.rows, func(a, b []string) bool { - for i := range a { - if a[i] < b[i] { - return true - } else if a[i] > b[i] { - return false - } - } - return false + slices.SortFunc(res.rows, func(a, b []string) int { + return slices.Compare(a, b) }) return res } diff --git a/types/json_binary.go b/types/json_binary.go index eb9a818b6a7f5..b394089d1500d 100644 --- a/types/json_binary.go +++ b/types/json_binary.go @@ -812,8 +812,8 @@ func appendBinaryObject(buf []byte, x map[string]interface{}) ([]byte, error) { for key, val := range x { fields = append(fields, field{key: key, val: val}) } - slices.SortFunc(fields, func(i, j field) bool { - return i.key < j.key + slices.SortFunc(fields, func(i, j field) int { + return strings.Compare(i.key, j.key) }) for i, field := range fields { keyEntryOff := keyEntryBegin + i*keyEntrySize diff --git a/types/json_binary_functions.go b/types/json_binary_functions.go index 2b02d5a0f65e7..56842fa82945e 100644 --- a/types/json_binary_functions.go +++ b/types/json_binary_functions.go @@ -933,8 +933,8 @@ func mergePatchBinaryJSON(target, patch *BinaryJSON) (result *BinaryJSON, err er for key := range keyValMap { keys = append(keys, []byte(key)) } - slices.SortFunc(keys, func(i, j []byte) bool { - return bytes.Compare(i, j) < 0 + slices.SortFunc(keys, func(i, j []byte) int { + return bytes.Compare(i, j) }) length = len(keys) values := make([]BinaryJSON, 0, len(keys)) @@ -1016,8 +1016,8 @@ func mergeBinaryObject(objects []BinaryJSON) BinaryJSON { } } } - slices.SortFunc(keys, func(i, j []byte) bool { - return bytes.Compare(i, j) < 0 + slices.SortFunc(keys, func(i, j []byte) int { + return bytes.Compare(i, j) }) values := make([]BinaryJSON, len(keys)) for i, key := range keys { diff --git a/util/cmp/BUILD.bazel b/util/cmp/BUILD.bazel new file mode 100644 index 0000000000000..500497d39126c --- /dev/null +++ b/util/cmp/BUILD.bazel @@ -0,0 +1,16 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") + +go_library( + name = "cmp", + srcs = ["compare.go"], + importpath = "github.com/pingcap/tidb/util/cmp", + visibility = ["//visibility:public"], + deps = ["@org_golang_x_exp//constraints"], +) + +go_test( + name = "cmp_test", + srcs = ["compare_test.go"], + embed = [":cmp"], + deps = ["@com_github_stretchr_testify//require"], +) diff --git a/util/cmp/compare.go b/util/cmp/compare.go new file mode 100644 index 0000000000000..1e220e32417e5 --- /dev/null +++ b/util/cmp/compare.go @@ -0,0 +1,28 @@ +// Copyright 2024 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, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package cmp + +import "golang.org/x/exp/constraints" + +// Compare returns -1 if x is less than y, 0 if x equals y, and +1 if x is greater than y. +func Compare[T constraints.Ordered](x, y T) int { + if x < y { + return -1 + } + if x > y { + return +1 + } + return 0 +} diff --git a/util/cmp/compare_test.go b/util/cmp/compare_test.go new file mode 100644 index 0000000000000..63f81008060d5 --- /dev/null +++ b/util/cmp/compare_test.go @@ -0,0 +1,31 @@ +// Copyright 2024 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, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package cmp + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestCompare(t *testing.T) { + require.Equal(t, -1, Compare(1, 2)) + require.Equal(t, 1, Compare(2, 1)) + require.Zero(t, Compare(1, 1)) + + require.Equal(t, -1, Compare("a", "b")) + require.Equal(t, 1, Compare("b", "a")) + require.Zero(t, Compare("a", "a")) +} diff --git a/util/collate/collate.go b/util/collate/collate.go index d212fa49e8f18..c96d863bd492d 100644 --- a/util/collate/collate.go +++ b/util/collate/collate.go @@ -16,6 +16,7 @@ package collate import ( "fmt" + "strings" "sync/atomic" "github.com/pingcap/errors" @@ -255,8 +256,8 @@ func GetSupportedCollations() []*charset.Collation { newSupportedCollations = append(newSupportedCollations, coll) } } - slices.SortFunc(newSupportedCollations, func(i, j *charset.Collation) bool { - return i.Name < j.Name + slices.SortFunc(newSupportedCollations, func(i, j *charset.Collation) int { + return strings.Compare(i.Name, j.Name) }) return newSupportedCollations } diff --git a/util/memoryusagealarm/BUILD.bazel b/util/memoryusagealarm/BUILD.bazel index 80d092d6e4723..b9cab29827874 100644 --- a/util/memoryusagealarm/BUILD.bazel +++ b/util/memoryusagealarm/BUILD.bazel @@ -9,6 +9,7 @@ go_library( "//config", "//sessionctx/variable", "//util", + "//util/cmp", "//util/disk", "//util/logutil", "//util/memory", diff --git a/util/memoryusagealarm/memoryusagealarm.go b/util/memoryusagealarm/memoryusagealarm.go index c8a6fd0eaecda..9308f9854a45f 100644 --- a/util/memoryusagealarm/memoryusagealarm.go +++ b/util/memoryusagealarm/memoryusagealarm.go @@ -26,6 +26,7 @@ import ( "github.com/pingcap/tidb/config" "github.com/pingcap/tidb/sessionctx/variable" "github.com/pingcap/tidb/util" + "github.com/pingcap/tidb/util/cmp" "github.com/pingcap/tidb/util/disk" "github.com/pingcap/tidb/util/logutil" "github.com/pingcap/tidb/util/memory" @@ -263,7 +264,7 @@ func (record *memoryUsageAlarm) printTop10SqlInfo(pinfo []*util.ProcessInfo, f * } } -func (record *memoryUsageAlarm) getTop10SqlInfo(cmp func(i, j *util.ProcessInfo) bool, pinfo []*util.ProcessInfo) strings.Builder { +func (record *memoryUsageAlarm) getTop10SqlInfo(cmp func(i, j *util.ProcessInfo) int, pinfo []*util.ProcessInfo) strings.Builder { slices.SortFunc(pinfo, cmp) list := pinfo var buf strings.Builder @@ -302,14 +303,14 @@ func (record *memoryUsageAlarm) getTop10SqlInfo(cmp func(i, j *util.ProcessInfo) } func (record *memoryUsageAlarm) getTop10SqlInfoByMemoryUsage(pinfo []*util.ProcessInfo) strings.Builder { - return record.getTop10SqlInfo(func(i, j *util.ProcessInfo) bool { - return i.MemTracker.MaxConsumed() > j.MemTracker.MaxConsumed() + return record.getTop10SqlInfo(func(i, j *util.ProcessInfo) int { + return cmp.Compare(j.MemTracker.MaxConsumed(), i.MemTracker.MaxConsumed()) }, pinfo) } func (record *memoryUsageAlarm) getTop10SqlInfoByCostTime(pinfo []*util.ProcessInfo) strings.Builder { - return record.getTop10SqlInfo(func(i, j *util.ProcessInfo) bool { - return i.Time.Before(j.Time) + return record.getTop10SqlInfo(func(i, j *util.ProcessInfo) int { + return cmp.Compare(i.Time.UnixNano(), j.Time.UnixNano()) }, pinfo) } diff --git a/util/profile/BUILD.bazel b/util/profile/BUILD.bazel index 4710fda796d29..5e19af7883659 100644 --- a/util/profile/BUILD.bazel +++ b/util/profile/BUILD.bazel @@ -10,6 +10,7 @@ go_library( visibility = ["//visibility:public"], deps = [ "//types", + "//util/cmp", "//util/cpuprofile", "//util/texttree", "@com_github_google_pprof//profile", diff --git a/util/profile/flamegraph.go b/util/profile/flamegraph.go index 5bb2a9cd3fb92..3e3f64daac65c 100644 --- a/util/profile/flamegraph.go +++ b/util/profile/flamegraph.go @@ -20,6 +20,7 @@ import ( "github.com/google/pprof/profile" "github.com/pingcap/tidb/types" + "github.com/pingcap/tidb/util/cmp" "github.com/pingcap/tidb/util/texttree" "golang.org/x/exp/slices" ) @@ -93,11 +94,11 @@ func (n *flamegraphNode) sortedChildren() []flamegraphNodeWithLocation { locID: locID, }) } - slices.SortFunc(children, func(i, j flamegraphNodeWithLocation) bool { + slices.SortFunc(children, func(i, j flamegraphNodeWithLocation) int { if i.cumValue != j.cumValue { - return i.cumValue > j.cumValue + return cmp.Compare(j.cumValue, i.cumValue) } - return i.locID < j.locID + return cmp.Compare(i.locID, j.locID) }) return children diff --git a/util/ranger/ranger.go b/util/ranger/ranger.go index ad83f68ebd258..bf43491544a07 100644 --- a/util/ranger/ranger.go +++ b/util/ranger/ranger.go @@ -587,8 +587,8 @@ func UnionRanges(sctx sessionctx.Context, ranges Ranges, mergeConsecutive bool) } objects = append(objects, &sortRange{originalValue: ran, encodedStart: left, encodedEnd: right}) } - slices.SortFunc(objects, func(i, j *sortRange) bool { - return bytes.Compare(i.encodedStart, j.encodedStart) < 0 + slices.SortFunc(objects, func(i, j *sortRange) int { + return bytes.Compare(i.encodedStart, j.encodedStart) }) ranges = ranges[:0] lastRange := objects[0] diff --git a/util/schemacmp/table.go b/util/schemacmp/table.go index cf56db3559576..ad076342dd1ec 100644 --- a/util/schemacmp/table.go +++ b/util/schemacmp/table.go @@ -294,8 +294,8 @@ func sortedMap(input map[string]interface{}) []kvPair { res = append(res, kvPair{key: key, value: value}) } - slices.SortFunc(res, func(a, b kvPair) bool { - return a.key < b.key + slices.SortFunc(res, func(a, b kvPair) int { + return strings.Compare(a.key, b.key) }) return res } diff --git a/util/stmtsummary/BUILD.bazel b/util/stmtsummary/BUILD.bazel index 7c85e57d52aee..18bddb4158f5e 100644 --- a/util/stmtsummary/BUILD.bazel +++ b/util/stmtsummary/BUILD.bazel @@ -15,6 +15,7 @@ go_library( "//parser/mysql", "//sessionctx/stmtctx", "//types", + "//util/cmp", "//util/execdetails", "//util/hack", "//util/kvcache", diff --git a/util/stmtsummary/statement_summary.go b/util/stmtsummary/statement_summary.go index b7710ec6745b1..0da8387ed18f4 100644 --- a/util/stmtsummary/statement_summary.go +++ b/util/stmtsummary/statement_summary.go @@ -27,6 +27,7 @@ import ( "github.com/pingcap/failpoint" "github.com/pingcap/tidb/sessionctx/stmtctx" + "github.com/pingcap/tidb/util/cmp" "github.com/pingcap/tidb/util/execdetails" "github.com/pingcap/tidb/util/hack" "github.com/pingcap/tidb/util/kvcache" @@ -934,8 +935,8 @@ func formatBackoffTypes(backoffMap map[string]int) interface{} { for backoffType, count := range backoffMap { backoffArray = append(backoffArray, backoffStat{backoffType, count}) } - slices.SortFunc(backoffArray, func(i, j backoffStat) bool { - return i.count > j.count + slices.SortFunc(backoffArray, func(i, j backoffStat) int { + return cmp.Compare(j.count, i.count) }) var buffer bytes.Buffer