From 63c3fe6d991d087a4db66ed5f06e1b85e473049a Mon Sep 17 00:00:00 2001 From: Sourcegraph Date: Thu, 6 Oct 2022 23:55:09 +0000 Subject: [PATCH] Rewrites `interface{}` to `any` using `gofmt` --- cmd/benchdb/main.go | 4 +- cmd/benchfilesort/main.go | 4 +- cmd/ddltest/column_test.go | 6 +- cmd/ddltest/ddl_test.go | 24 +- cmd/explaintest/main.go | 2 +- cmd/pluginpkg/pluginpkg.go | 2 +- config/config.go | 2 +- config/config_util.go | 10 +- config/config_util_test.go | 6 +- ddl/column.go | 14 +- ddl/column_change_test.go | 8 +- ddl/column_test.go | 30 +- ddl/db_change_test.go | 6 +- ddl/db_integration_test.go | 2 +- ddl/db_test.go | 22 +- ddl/ddl.go | 8 +- ddl/ddl_api.go | 72 +- ddl/ddl_test.go | 14 +- ddl/ddl_worker.go | 2 +- ddl/ddl_worker_test.go | 100 +-- ddl/delete_range.go | 2 +- ddl/foreign_key_test.go | 4 +- ddl/index_change_test.go | 2 +- ddl/partition.go | 8 +- ddl/reorg_test.go | 2 +- ddl/rollingback.go | 8 +- ddl/schema_test.go | 6 +- ddl/serial_test.go | 2 +- ddl/stat.go | 4 +- ddl/stat_test.go | 2 +- ddl/table.go | 2 +- ddl/table_lock.go | 6 +- ddl/table_test.go | 14 +- domain/global_vars_cache.go | 2 +- domain/topn_slow_query.go | 4 +- executor/aggfuncs/aggfunc_test.go | 8 +- executor/aggfuncs/func_json_objectagg.go | 6 +- executor/aggfuncs/func_json_objectagg_test.go | 6 +- executor/aggfuncs/window_func_test.go | 4 +- executor/aggregate.go | 74 +- executor/benchmark_test.go | 22 +- executor/brie.go | 2 +- executor/chunk_size_control_test.go | 2 +- executor/delete.go | 2 +- executor/distsql.go | 2 +- executor/executor.go | 34 +- executor/executor_required_rows_test.go | 20 +- executor/executor_test.go | 4 +- executor/index_lookup_hash_join.go | 33 +- executor/index_merge_reader.go | 26 +- executor/infoschema_reader.go | 10 +- executor/infoschema_reader_test.go | 28 +- executor/insert_test.go | 2 +- executor/inspection_summary.go | 2 +- executor/join.go | 8 +- executor/join_pkg_test.go | 2 +- executor/join_test.go | 18 +- executor/memtable_reader.go | 6 +- executor/memtable_reader_test.go | 4 +- executor/metrics_reader.go | 4 +- executor/pkg_test.go | 4 +- executor/projection.go | 100 +-- executor/seqtest/seq_executor_test.go | 32 +- executor/show.go | 126 ++-- executor/show_stats.go | 8 +- executor/shuffle.go | 80 +- executor/sort.go | 20 +- executor/table_readers_required_rows_test.go | 2 +- executor/trace_test.go | 2 +- executor/update_test.go | 2 +- executor/write_concurrent_test.go | 8 +- expression/aggregation/util_test.go | 14 +- expression/bench_test.go | 78 +- expression/builtin_arithmetic_test.go | 208 +++--- expression/builtin_cast_vec_test.go | 6 +- expression/builtin_compare_test.go | 56 +- expression/builtin_control_test.go | 42 +- .../builtin_control_vec_generated_test.go | 2 +- expression/builtin_encryption_test.go | 94 +-- expression/builtin_encryption_vec.go | 2 +- expression/builtin_info_test.go | 18 +- expression/builtin_info_vec_test.go | 2 +- expression/builtin_json.go | 6 +- expression/builtin_json_test.go | 644 ++++++++-------- expression/builtin_json_vec.go | 8 +- expression/builtin_math_test.go | 292 ++++---- expression/builtin_miscellaneous_test.go | 26 +- expression/builtin_op_test.go | 264 +++---- expression/builtin_op_vec_test.go | 14 +- expression/builtin_other_test.go | 80 +- .../builtin_other_vec_generated_test.go | 2 +- expression/builtin_string_test.go | 704 +++++++++--------- expression/builtin_string_vec_test.go | 2 +- expression/builtin_test.go | 6 +- expression/builtin_time_test.go | 272 +++---- expression/builtin_time_vec_generated_test.go | 2 +- expression/builtin_time_vec_test.go | 8 +- expression/evaluator_test.go | 40 +- expression/expression.go | 9 +- expression/generator/compare_vec.go | 3 +- expression/generator/control_vec.go | 1 + expression/generator/other_vec.go | 1 + expression/generator/time_vec.go | 1 + expression/helper.go | 2 +- expression/helper_test.go | 6 +- expression/scalar_function.go | 2 +- expression/util_test.go | 2 +- infoschema/tables.go | 13 +- infoschema/tables_test.go | 12 +- kv/interface_mock_test.go | 14 +- kv/key.go | 20 +- kv/key_test.go | 4 +- kv/kv.go | 6 +- kv/union_store.go | 16 +- planner/core/cache.go | 4 +- planner/core/encode.go | 4 +- planner/core/logical_plan_builder.go | 17 +- planner/core/preprocess.go | 8 +- planner/core/util.go | 2 +- planner/memo/group_expr.go | 4 +- plugin/spi.go | 2 +- server/conn_stmt.go | 2 +- server/conn_stmt_test.go | 2 +- server/driver.go | 4 +- server/driver_tidb.go | 4 +- server/http_handler.go | 18 +- server/http_handler_test.go | 6 +- server/server_test.go | 16 +- server/statistics_handler_test.go | 2 +- session/bootstrap_test.go | 2 +- session/session.go | 14 +- session/tidb_test.go | 6 +- sessionctx/context.go | 6 +- sessionctx/variable/session.go | 16 +- sessionctx/variable/session_test.go | 2 +- sessionctx/variable/statusvar.go | 8 +- sessionctx/variable/statusvar_test.go | 4 +- statistics/handle/update.go | 12 +- store/helper/helper.go | 2 +- store/mockstore/mocktikv/cop_handler_dag.go | 4 +- store/mockstore/mocktikv/mvcc.go | 4 +- store/mockstore/mocktikv/topn.go | 4 +- store/tikv/backoff.go | 2 +- store/tikv/client_batch.go | 2 +- store/tikv/client_collapse.go | 2 +- store/tikv/gcworker/gc_worker.go | 14 +- store/tikv/gcworker/gc_worker_test.go | 6 +- store/tikv/kv.go | 2 +- store/tikv/region_cache.go | 2 +- store/tikv/snapshot.go | 2 +- store/tikv/split_region.go | 2 +- store/tikv/tikvrpc/tikvrpc.go | 10 +- store/tikv/txn.go | 2 +- table/column.go | 10 +- table/tables/tables.go | 4 +- tidb-server/main.go | 2 +- types/compare_test.go | 6 +- types/convert.go | 2 +- types/convert_test.go | 24 +- types/datum.go | 49 +- types/datum_test.go | 38 +- types/etc.go | 5 +- types/field_type.go | 4 +- types/field_type_test.go | 2 +- types/json/binary.go | 18 +- types/json/binary_functions.go | 11 +- types/parser_driver/value_expr.go | 10 +- util/chunk/disk.go | 4 +- util/chunk/mutrow.go | 10 +- util/chunk/mutrow_test.go | 2 +- util/chunk/pool.go | 10 +- util/codec/codec_test.go | 8 +- util/expensivequery/expensivequerey_test.go | 2 +- util/filesort/filesort.go | 4 +- util/format/format.go | 40 +- util/localpool/localpool.go | 10 +- util/localpool/localpool_norace.go | 7 +- util/localpool/localpool_race.go | 5 +- util/localpool/localpool_test.go | 5 +- util/logutil/log.go | 4 +- util/misc.go | 11 +- util/misc_test.go | 4 +- util/mock/context.go | 10 +- util/mock/store.go | 2 +- util/plancodec/codec.go | 2 +- util/prefix_helper_test.go | 8 +- util/processinfo.go | 14 +- util/stmtsummary/statement_summary.go | 4 +- util/stmtsummary/statement_summary_test.go | 4 +- util/testkit/ctestkit.go | 19 +- util/testkit/testkit.go | 33 +- util/testutil/testutil.go | 20 +- 192 files changed, 2413 insertions(+), 2362 deletions(-) diff --git a/cmd/benchdb/main.go b/cmd/benchdb/main.go index 4d9e40daa..8e0bf1da6 100644 --- a/cmd/benchdb/main.go +++ b/cmd/benchdb/main.go @@ -281,12 +281,12 @@ func (ut *benchDB) query(spec string) { }) } -func cLogf(format string, args ...interface{}) { +func cLogf(format string, args ...any) { str := fmt.Sprintf(format, args...) fmt.Println("\033[0;32m" + str + "\033[0m\n") } -func cLog(args ...interface{}) { +func cLog(args ...any) { str := fmt.Sprint(args...) fmt.Println("\033[0;32m" + str + "\033[0m\n") } diff --git a/cmd/benchfilesort/main.go b/cmd/benchfilesort/main.go index 1a580f5ca..3016ccd6c 100644 --- a/cmd/benchfilesort/main.go +++ b/cmd/benchfilesort/main.go @@ -426,12 +426,12 @@ func main() { } } -func cLogf(format string, args ...interface{}) { +func cLogf(format string, args ...any) { str := fmt.Sprintf(format, args...) fmt.Println("\033[0;32m" + str + "\033[0m") } -func cLog(args ...interface{}) { +func cLog(args ...any) { str := fmt.Sprint(args...) fmt.Println("\033[0;32m" + str + "\033[0m") } diff --git a/cmd/ddltest/column_test.go b/cmd/ddltest/column_test.go index bd4eba824..6a1ee7753 100644 --- a/cmd/ddltest/column_test.go +++ b/cmd/ddltest/column_test.go @@ -31,7 +31,7 @@ import ( ) // After add column finished, check the records in the table. -func (s *TestDDLSuite) checkAddColumn(c *C, rowID int64, defaultVal interface{}, updatedVal interface{}) { +func (s *TestDDLSuite) checkAddColumn(c *C, rowID int64, defaultVal any, updatedVal any) { ctx := s.ctx err := ctx.NewTxn(goctx.Background()) c.Assert(err, IsNil) @@ -81,7 +81,7 @@ func (s *TestDDLSuite) checkAddColumn(c *C, rowID int64, defaultVal interface{}, c.Assert(deleteCount, Greater, int64(0)) } -func (s *TestDDLSuite) checkDropColumn(c *C, rowID int64, alterColumn *table.Column, updateDefault interface{}) { +func (s *TestDDLSuite) checkDropColumn(c *C, rowID int64, alterColumn *table.Column, updateDefault any) { ctx := s.ctx err := ctx.NewTxn(goctx.Background()) c.Assert(err, IsNil) @@ -134,7 +134,7 @@ func (s *TestDDLSuite) TestColumn(c *C) { Query string ColumnName string Add bool - Default interface{} + Default any }{ {"alter table test_column add column c3 int default -1", "c3", true, int64(-1)}, {"alter table test_column drop column c3", "c3", false, nil}, diff --git a/cmd/ddltest/ddl_test.go b/cmd/ddltest/ddl_test.go index f78112b7e..90ea76d85 100644 --- a/cmd/ddltest/ddl_test.go +++ b/cmd/ddltest/ddl_test.go @@ -372,7 +372,7 @@ func isRetryError(err error) bool { return false } -func (s *TestDDLSuite) exec(query string, args ...interface{}) (sql.Result, error) { +func (s *TestDDLSuite) exec(query string, args ...any) (sql.Result, error) { for { server := s.getServer() r, err := server.db.Exec(query, args...) @@ -385,7 +385,7 @@ func (s *TestDDLSuite) exec(query string, args ...interface{}) (sql.Result, erro } } -func (s *TestDDLSuite) mustExec(c *C, query string, args ...interface{}) sql.Result { +func (s *TestDDLSuite) mustExec(c *C, query string, args ...any) sql.Result { r, err := s.exec(query, args...) if err != nil { log.Fatalf("[mustExec fail]query - %v %v, error - %v", query, args, err) @@ -394,7 +394,7 @@ func (s *TestDDLSuite) mustExec(c *C, query string, args ...interface{}) sql.Res return r } -func (s *TestDDLSuite) execInsert(c *C, query string, args ...interface{}) sql.Result { +func (s *TestDDLSuite) execInsert(c *C, query string, args ...any) sql.Result { for { r, err := s.exec(query, args...) if err == nil { @@ -413,7 +413,7 @@ func (s *TestDDLSuite) execInsert(c *C, query string, args ...interface{}) sql.R } } -func (s *TestDDLSuite) query(query string, args ...interface{}) (*sql.Rows, error) { +func (s *TestDDLSuite) query(query string, args ...any) (*sql.Rows, error) { for { server := s.getServer() r, err := server.db.Query(query, args...) @@ -464,20 +464,20 @@ func (s *TestDDLSuite) getTable(c *C, name string) table.Table { return tbl } -func dumpRows(c *C, rows *sql.Rows) [][]interface{} { +func dumpRows(c *C, rows *sql.Rows) [][]any { cols, err := rows.Columns() c.Assert(err, IsNil) - var ay [][]interface{} + var ay [][]any for rows.Next() { - v := make([]interface{}, len(cols)) + v := make([]any, len(cols)) for i := range v { - v[i] = new(interface{}) + v[i] = new(any) } err = rows.Scan(v...) c.Assert(err, IsNil) for i := range v { - v[i] = *(v[i].(*interface{})) + v[i] = *(v[i].(*any)) } ay = append(ay, v) } @@ -487,7 +487,7 @@ func dumpRows(c *C, rows *sql.Rows) [][]interface{} { return ay } -func matchRows(c *C, rows *sql.Rows, expected [][]interface{}) { +func matchRows(c *C, rows *sql.Rows, expected [][]any) { ay := dumpRows(c, rows) c.Assert(len(ay), Equals, len(expected), Commentf("%v", expected)) for i := range ay { @@ -495,7 +495,7 @@ func matchRows(c *C, rows *sql.Rows, expected [][]interface{}) { } } -func match(c *C, row []interface{}, expected ...interface{}) { +func match(c *C, row []any, expected ...any) { c.Assert(len(row), Equals, len(expected)) for i := range row { if row[i] == nil { @@ -563,7 +563,7 @@ func (s *TestDDLSuite) TestSimple(c *C) { rows, err := s.query("select c1 from test_simple limit 1") c.Assert(err, IsNil) - matchRows(c, rows, [][]interface{}{{1}}) + matchRows(c, rows, [][]any{{1}}) done = s.runDDL("drop table if exists test_simple") err = <-done diff --git a/cmd/explaintest/main.go b/cmd/explaintest/main.go index be897ec59..0068afb1c 100644 --- a/cmd/explaintest/main.go +++ b/cmd/explaintest/main.go @@ -474,7 +474,7 @@ func (t *tester) executeStmt(query string) error { t.buf.WriteString("\n") values := make([][]byte, len(cols)) - scanArgs := make([]interface{}, len(values)) + scanArgs := make([]any, len(values)) for i := range values { scanArgs[i] = &values[i] } diff --git a/cmd/pluginpkg/pluginpkg.go b/cmd/pluginpkg/pluginpkg.go index a2bfa356c..1f5f792f1 100644 --- a/cmd/pluginpkg/pluginpkg.go +++ b/cmd/pluginpkg/pluginpkg.go @@ -109,7 +109,7 @@ func main() { flag.Usage() } - var manifest map[string]interface{} + var manifest map[string]any _, err = toml.DecodeFile(filepath.Join(pkgDir, "manifest.toml"), &manifest) if err != nil { log.Printf("read pkg %s's manifest failure, %+v\n", pkgDir, err) diff --git a/config/config.go b/config/config.go index 59a2d047f..bf095c499 100644 --- a/config/config.go +++ b/config/config.go @@ -205,7 +205,7 @@ func (b nullableBool) MarshalText() ([]byte, error) { func (b *nullableBool) UnmarshalJSON(data []byte) error { var err error - var v interface{} + var v any if err = json.Unmarshal(data, &v); err != nil { return err } diff --git a/config/config_util.go b/config/config_util.go index 6922437cf..4e8fbcd0c 100644 --- a/config/config_util.go +++ b/config/config_util.go @@ -134,16 +134,16 @@ func decodeConfig(content string) (*Config, error) { } // FlattenConfigItems flatten this config, see more cases in the test. -func FlattenConfigItems(nestedConfig map[string]interface{}) map[string]interface{} { - flatMap := make(map[string]interface{}) +func FlattenConfigItems(nestedConfig map[string]any) map[string]any { + flatMap := make(map[string]any) flatten(flatMap, nestedConfig, "") return flatMap } -func flatten(flatMap map[string]interface{}, nested interface{}, prefix string) { +func flatten(flatMap map[string]any, nested any, prefix string) { switch nested.(type) { - case map[string]interface{}: - for k, v := range nested.(map[string]interface{}) { + case map[string]any: + for k, v := range nested.(map[string]any) { path := k if prefix != "" { path = prefix + "." + k diff --git a/config/config_util_test.go b/config/config_util_test.go index 7972fcf70..f86b86788 100644 --- a/config/config_util_test.go +++ b/config/config_util_test.go @@ -123,7 +123,7 @@ func (s *testConfigSuite) TestAtomicWriteConfig(c *C) { } func (s *testConfigSuite) TestFlattenConfig(c *C) { - toJSONStr := func(v interface{}) string { + toJSONStr := func(v any) string { str, err := json.Marshal(v) c.Assert(err, IsNil) return string(str) @@ -139,7 +139,7 @@ func (s *testConfigSuite) TestFlattenConfig(c *C) { "k4-2": [5, 6, 7, 8], "k4-3": [666] }}` - nested := make(map[string]interface{}) + nested := make(map[string]any) c.Assert(json.Unmarshal([]byte(jsonConf), &nested), IsNil) flatMap := FlattenConfigItems(nested) c.Assert(len(flatMap), Equals, 7) @@ -159,7 +159,7 @@ format='text' [isolation-read] engines = ["tikv", "tiflash", "tidb"] ` - nested = make(map[string]interface{}) + nested = make(map[string]any) c.Assert(toml.Unmarshal([]byte(tomlConf), &nested), IsNil) flatMap = FlattenConfigItems(nested) c.Assert(len(flatMap), Equals, 4) diff --git a/ddl/column.go b/ddl/column.go index c97e3fa1a..468082838 100644 --- a/ddl/column.go +++ b/ddl/column.go @@ -36,9 +36,9 @@ import ( ) // adjustColumnInfoInAddColumn is used to set the correct position of column info when adding column. -// 1. The added column was append at the end of tblInfo.Columns, due to ddl state was not public then. -// It should be moved to the correct position when the ddl state to be changed to public. -// 2. The offset of column should also to be set to the right value. +// 1. The added column was append at the end of tblInfo.Columns, due to ddl state was not public then. +// It should be moved to the correct position when the ddl state to be changed to public. +// 2. The offset of column should also to be set to the right value. func adjustColumnInfoInAddColumn(tblInfo *model.TableInfo, offset int) { oldCols := tblInfo.Columns newCols := make([]*model.ColumnInfo, 0, len(oldCols)) @@ -188,7 +188,7 @@ func onAddColumn(d *ddlCtx, t *meta.Meta, job *model.Job) (ver int64, err error) logutil.BgLogger().Info("[ddl] run add column job", zap.String("job", job.String()), zap.Reflect("columnInfo", *columnInfo), zap.Int("offset", offset)) // Set offset arg to job. if offset != 0 { - job.Args = []interface{}{columnInfo, pos, offset} + job.Args = []any{columnInfo, pos, offset} } if err = checkAddColumnTooManyColumns(len(tblInfo.Columns)); err != nil { job.State = model.JobStateCancelled @@ -324,7 +324,7 @@ func onAddColumns(d *ddlCtx, t *meta.Meta, job *model.Job) (ver int64, err error columnInfos = append(columnInfos, columnInfo) } // Set arg to job. - job.Args = []interface{}{columnInfos, positions, offsets, ifNotExists} + job.Args = []any{columnInfos, positions, offsets, ifNotExists} } originalState := columnInfos[0].State @@ -473,7 +473,7 @@ func checkDropColumns(t *meta.Meta, job *model.Job) (*model.TableInfo, []*model. newIfExists = append(newIfExists, ifExists[i]) colInfos = append(colInfos, colInfo) } - job.Args = []interface{}{newColNames, newIfExists} + job.Args = []any{newColNames, newIfExists} return tblInfo, colInfos, len(colInfos), nil } @@ -857,7 +857,7 @@ func modifyColsFromNull2NotNull(w *worker, dbInfo *model.DBInfo, tblInfo *model. return nil } -func generateOriginDefaultValue(col *model.ColumnInfo) (interface{}, error) { +func generateOriginDefaultValue(col *model.ColumnInfo) (any, error) { var err error odValue := col.GetDefaultValue() if odValue == nil && mysql.HasNotNullFlag(col.Flag) { diff --git a/ddl/column_change_test.go b/ddl/column_change_test.go index bd4c240cb..0eb6cb2c9 100644 --- a/ddl/column_change_test.go +++ b/ddl/column_change_test.go @@ -360,8 +360,8 @@ func getCurrentTable(d *ddl, schemaID, tableID int64) (table.Table, error) { return tbl, err } -func checkResult(ctx sessionctx.Context, t table.Table, cols []*table.Column, rows [][]interface{}) error { - var gotRows [][]interface{} +func checkResult(ctx sessionctx.Context, t table.Table, cols []*table.Column, rows [][]any) error { + var gotRows [][]any err := t.IterRecords(ctx, t.FirstKey(), cols, func(h int64, data []types.Datum, cols []*table.Column) (bool, error) { gotRows = append(gotRows, datumsToInterfaces(data)) return true, nil @@ -377,8 +377,8 @@ func checkResult(ctx sessionctx.Context, t table.Table, cols []*table.Column, ro return nil } -func datumsToInterfaces(datums []types.Datum) []interface{} { - ifs := make([]interface{}, 0, len(datums)) +func datumsToInterfaces(datums []types.Datum) []any { + ifs := make([]any, 0, len(datums)) for _, d := range datums { ifs = append(ifs, d.GetValue()) } diff --git a/ddl/column_test.go b/ddl/column_test.go index dad5eca4b..a5046b11b 100644 --- a/ddl/column_test.go +++ b/ddl/column_test.go @@ -61,7 +61,7 @@ func (s *testColumnSuite) TearDownSuite(c *C) { } func buildCreateColumnJob(dbInfo *model.DBInfo, tblInfo *model.TableInfo, colName string, - pos *ast.ColumnPosition, defaultValue interface{}) *model.Job { + pos *ast.ColumnPosition, defaultValue any) *model.Job { col := &model.ColumnInfo{ Name: model.NewCIStr(colName), Offset: len(tblInfo.Columns), @@ -76,13 +76,13 @@ func buildCreateColumnJob(dbInfo *model.DBInfo, tblInfo *model.TableInfo, colNam TableID: tblInfo.ID, Type: model.ActionAddColumn, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{col, pos, 0}, + Args: []any{col, pos, 0}, } return job } func testCreateColumn(c *C, ctx sessionctx.Context, d *ddl, dbInfo *model.DBInfo, tblInfo *model.TableInfo, - colName string, pos *ast.ColumnPosition, defaultValue interface{}) *model.Job { + colName string, pos *ast.ColumnPosition, defaultValue any) *model.Job { job := buildCreateColumnJob(dbInfo, tblInfo, colName, pos, defaultValue) err := d.doDDLJob(ctx, job) c.Assert(err, IsNil) @@ -92,7 +92,7 @@ func testCreateColumn(c *C, ctx sessionctx.Context, d *ddl, dbInfo *model.DBInfo } func buildCreateColumnsJob(dbInfo *model.DBInfo, tblInfo *model.TableInfo, colNames []string, - positions []*ast.ColumnPosition, defaultValue interface{}) *model.Job { + positions []*ast.ColumnPosition, defaultValue any) *model.Job { colInfos := make([]*model.ColumnInfo, len(colNames)) offsets := make([]int, len(colNames)) ifNotExists := make([]bool, len(colNames)) @@ -113,13 +113,13 @@ func buildCreateColumnsJob(dbInfo *model.DBInfo, tblInfo *model.TableInfo, colNa TableID: tblInfo.ID, Type: model.ActionAddColumns, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{colInfos, positions, offsets, ifNotExists}, + Args: []any{colInfos, positions, offsets, ifNotExists}, } return job } func testCreateColumns(c *C, ctx sessionctx.Context, d *ddl, dbInfo *model.DBInfo, tblInfo *model.TableInfo, - colNames []string, positions []*ast.ColumnPosition, defaultValue interface{}) *model.Job { + colNames []string, positions []*ast.ColumnPosition, defaultValue any) *model.Job { job := buildCreateColumnsJob(dbInfo, tblInfo, colNames, positions, defaultValue) err := d.doDDLJob(ctx, job) c.Assert(err, IsNil) @@ -134,7 +134,7 @@ func buildDropColumnJob(dbInfo *model.DBInfo, tblInfo *model.TableInfo, colName TableID: tblInfo.ID, Type: model.ActionDropColumn, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{model.NewCIStr(colName)}, + Args: []any{model.NewCIStr(colName)}, } } @@ -162,7 +162,7 @@ func buildDropColumnsJob(dbInfo *model.DBInfo, tblInfo *model.TableInfo, colName TableID: tblInfo.ID, Type: model.ActionDropColumns, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{columnNames, ifExists}, + Args: []any{columnNames, ifExists}, } return job } @@ -339,7 +339,7 @@ func (s *testColumnSuite) TestColumn(c *C) { testDropTable(c, ctx, d, s.dbInfo, tblInfo) } -func (s *testColumnSuite) checkColumnKVExist(ctx sessionctx.Context, t table.Table, handle kv.Handle, col *table.Column, columnValue interface{}, isExist bool) error { +func (s *testColumnSuite) checkColumnKVExist(ctx sessionctx.Context, t table.Table, handle kv.Handle, col *table.Column, columnValue any, isExist bool) error { err := ctx.NewTxn(context.Background()) if err != nil { return errors.Trace(err) @@ -382,7 +382,7 @@ func (s *testColumnSuite) checkColumnKVExist(ctx sessionctx.Context, t table.Tab return nil } -func (s *testColumnSuite) checkNoneColumn(ctx sessionctx.Context, d *ddl, tblInfo *model.TableInfo, handle kv.Handle, col *table.Column, columnValue interface{}) error { +func (s *testColumnSuite) checkNoneColumn(ctx sessionctx.Context, d *ddl, tblInfo *model.TableInfo, handle kv.Handle, col *table.Column, columnValue any) error { t, err := testGetTableWithError(d, s.dbInfo.ID, tblInfo.ID) if err != nil { return errors.Trace(err) @@ -398,7 +398,7 @@ func (s *testColumnSuite) checkNoneColumn(ctx sessionctx.Context, d *ddl, tblInf return nil } -func (s *testColumnSuite) checkDeleteOnlyColumn(ctx sessionctx.Context, d *ddl, tblInfo *model.TableInfo, handle kv.Handle, col *table.Column, row []types.Datum, columnValue interface{}) error { +func (s *testColumnSuite) checkDeleteOnlyColumn(ctx sessionctx.Context, d *ddl, tblInfo *model.TableInfo, handle kv.Handle, col *table.Column, row []types.Datum, columnValue any) error { t, err := testGetTableWithError(d, s.dbInfo.ID, tblInfo.ID) if err != nil { return errors.Trace(err) @@ -499,7 +499,7 @@ func (s *testColumnSuite) checkDeleteOnlyColumn(ctx sessionctx.Context, d *ddl, return nil } -func (s *testColumnSuite) checkWriteOnlyColumn(ctx sessionctx.Context, d *ddl, tblInfo *model.TableInfo, handle kv.Handle, col *table.Column, row []types.Datum, columnValue interface{}) error { +func (s *testColumnSuite) checkWriteOnlyColumn(ctx sessionctx.Context, d *ddl, tblInfo *model.TableInfo, handle kv.Handle, col *table.Column, row []types.Datum, columnValue any) error { t, err := testGetTableWithError(d, s.dbInfo.ID, tblInfo.ID) if err != nil { return errors.Trace(err) @@ -604,7 +604,7 @@ func (s *testColumnSuite) checkWriteOnlyColumn(ctx sessionctx.Context, d *ddl, t return nil } -func (s *testColumnSuite) checkReorganizationColumn(ctx sessionctx.Context, d *ddl, tblInfo *model.TableInfo, col *table.Column, row []types.Datum, columnValue interface{}) error { +func (s *testColumnSuite) checkReorganizationColumn(ctx sessionctx.Context, d *ddl, tblInfo *model.TableInfo, col *table.Column, row []types.Datum, columnValue any) error { t, err := testGetTableWithError(d, s.dbInfo.ID, tblInfo.ID) if err != nil { return errors.Trace(err) @@ -700,7 +700,7 @@ func (s *testColumnSuite) checkReorganizationColumn(ctx sessionctx.Context, d *d return nil } -func (s *testColumnSuite) checkPublicColumn(ctx sessionctx.Context, d *ddl, tblInfo *model.TableInfo, newCol *table.Column, oldRow []types.Datum, columnValue interface{}) error { +func (s *testColumnSuite) checkPublicColumn(ctx sessionctx.Context, d *ddl, tblInfo *model.TableInfo, newCol *table.Column, oldRow []types.Datum, columnValue any) error { t, err := testGetTableWithError(d, s.dbInfo.ID, tblInfo.ID) if err != nil { return errors.Trace(err) @@ -794,7 +794,7 @@ func (s *testColumnSuite) checkPublicColumn(ctx sessionctx.Context, d *ddl, tblI return nil } -func (s *testColumnSuite) checkAddColumn(state model.SchemaState, d *ddl, tblInfo *model.TableInfo, handle kv.Handle, newCol *table.Column, oldRow []types.Datum, columnValue interface{}) error { +func (s *testColumnSuite) checkAddColumn(state model.SchemaState, d *ddl, tblInfo *model.TableInfo, handle kv.Handle, newCol *table.Column, oldRow []types.Datum, columnValue any) error { ctx := testNewContext(d) var err error switch state { diff --git a/ddl/db_change_test.go b/ddl/db_change_test.go index 0928bf75a..5468e924f 100644 --- a/ddl/db_change_test.go +++ b/ddl/db_change_test.go @@ -683,7 +683,7 @@ func (s *testStateChangeSuiteBase) runTestInSchemaState(c *C, state model.Schema } } -func (s *testStateChangeSuiteBase) execQuery(tk *testkit.TestKit, sql string, args ...interface{}) (*testkit.Result, error) { +func (s *testStateChangeSuiteBase) execQuery(tk *testkit.TestKit, sql string, args ...any) (*testkit.Result, error) { comment := Commentf("sql:%s, args:%v", sql, args) rs, err := tk.Exec(sql, args...) if err != nil { @@ -693,7 +693,7 @@ func (s *testStateChangeSuiteBase) execQuery(tk *testkit.TestKit, sql string, ar return result, nil } -func checkResult(result *testkit.Result, expected [][]interface{}) error { +func checkResult(result *testkit.Result, expected [][]any) error { got := fmt.Sprintf("%s", result.Rows()) need := fmt.Sprintf("%s", expected) if got != need { @@ -702,7 +702,7 @@ func checkResult(result *testkit.Result, expected [][]interface{}) error { return nil } -func (s *testStateChangeSuiteBase) CheckResult(tk *testkit.TestKit, sql string, args ...interface{}) (*testkit.Result, error) { +func (s *testStateChangeSuiteBase) CheckResult(tk *testkit.TestKit, sql string, args ...any) (*testkit.Result, error) { comment := Commentf("sql:%s, args:%v", sql, args) rs, err := tk.Exec(sql, args...) if err != nil { diff --git a/ddl/db_integration_test.go b/ddl/db_integration_test.go index c1ad1b9a6..2d921517f 100644 --- a/ddl/db_integration_test.go +++ b/ddl/db_integration_test.go @@ -1176,7 +1176,7 @@ func (s *testIntegrationSuite5) TestBackwardCompatibility(c *C) { TableID: tbl.Meta().ID, Type: model.ActionAddIndex, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{unique, indexName, indexPartSpecifications, indexOption}, + Args: []any{unique, indexName, indexPartSpecifications, indexOption}, } txn, err := s.store.Begin() c.Assert(err, IsNil) diff --git a/ddl/db_test.go b/ddl/db_test.go index 97d2f5f2e..79ceea8e4 100644 --- a/ddl/db_test.go +++ b/ddl/db_test.go @@ -1062,9 +1062,9 @@ LOOP: keys = append(keys, otherKeys...) // test index key - expectedRows := make([][]interface{}, 0, len(keys)) + expectedRows := make([][]any, 0, len(keys)) for _, key := range keys { - expectedRows = append(expectedRows, []interface{}{key}) + expectedRows = append(expectedRows, []any{key}) } rows := tk.MustQuery(fmt.Sprintf("select c1 from test_add_index where c3 >= %d order by c1", start)).Rows() matchRows(c, rows, expectedRows) @@ -1626,7 +1626,7 @@ func (s *testDBSuite4) TestAddIndexWithDupCols(c *C) { s.tk.MustExec("drop table test_add_index_with_dup") } -func (s *testDBSuite) showColumns(c *C, tableName string) [][]interface{} { +func (s *testDBSuite) showColumns(c *C, tableName string) [][]any { return s.mustQuery(c, fmt.Sprintf("show columns from %s", tableName)) } @@ -1721,11 +1721,11 @@ LOOP: c.Assert(count, Greater, int64(0)) rows = s.mustQuery(c, "select count(c4) from t2 where c4 = -1") - matchRows(c, rows, [][]interface{}{{count - int64(step)}}) + matchRows(c, rows, [][]any{{count - int64(step)}}) for i := num; i < num+step; i++ { rows = s.mustQuery(c, "select c4 from t2 where c4 = ?", i) - matchRows(c, rows, [][]interface{}{{i}}) + matchRows(c, rows, [][]any{{i}}) } ctx := s.s.(sessionctx.Context) @@ -1762,7 +1762,7 @@ LOOP: s.mustExec(c, "insert into t2 values (?, ?, ?, ?)", i, i, i, i) } rows = s.mustQuery(c, "select count(c4) from t2 where c4 = -1") - matchRows(c, rows, [][]interface{}{{count - int64(step)}}) + matchRows(c, rows, [][]any{{count - int64(step)}}) // add timestamp type column s.mustExec(c, "create table test_on_update_c (c1 int, c2 timestamp);") @@ -2030,23 +2030,23 @@ func (s *testDBSuite7) TestSelectInViewFromAnotherDB(c *C) { s.tk.MustExec("select test_db2.v.a from test_db2.v") } -func (s *testDBSuite) mustExec(c *C, query string, args ...interface{}) { +func (s *testDBSuite) mustExec(c *C, query string, args ...any) { s.tk.MustExec(query, args...) } -func (s *testDBSuite) mustQuery(c *C, query string, args ...interface{}) [][]interface{} { +func (s *testDBSuite) mustQuery(c *C, query string, args ...any) [][]any { r := s.tk.MustQuery(query, args...) return r.Rows() } -func matchRows(c *C, rows [][]interface{}, expected [][]interface{}) { +func matchRows(c *C, rows [][]any, expected [][]any) { c.Assert(len(rows), Equals, len(expected), Commentf("got %v, expected %v", rows, expected)) for i := range rows { match(c, rows[i], expected[i]...) } } -func match(c *C, row []interface{}, expected ...interface{}) { +func match(c *C, row []any, expected ...any) { c.Assert(len(row), Equals, len(expected)) for i := range row { got := fmt.Sprintf("%v", row[i]) @@ -4611,7 +4611,7 @@ func (s *testSerialDBSuite) TestDDLJobErrorCount(c *C) { SchemaName: schema.Name.L, Type: model.ActionRenameTable, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{schema.ID, newTableName}, + Args: []any{schema.ID, newTableName}, } c.Assert(failpoint.Enable("github.com/pingcap/tidb/ddl/mockErrEntrySizeTooLarge", `return(true)`), IsNil) diff --git a/ddl/ddl.go b/ddl/ddl.go index 4d6fcbe47..27b6928de 100644 --- a/ddl/ddl.go +++ b/ddl/ddl.go @@ -144,7 +144,7 @@ type DDL interface { // GetLease returns current schema lease time. GetLease() time.Duration // Stats returns the DDL statistics. - Stats(vars *variable.SessionVars) (map[string]interface{}, error) + Stats(vars *variable.SessionVars) (map[string]any, error) // GetScope gets the status variables scope. GetScope(status string) variable.ScopeFlag // Stop stops DDL worker. @@ -326,7 +326,7 @@ func (d *ddl) start(ctx context.Context, ctxPool *pools.ResourcePool) { defer d.wg.Done() tidbutil.WithRecovery( func() { d.limitDDLJobs() }, - func(r interface{}) { + func(r any) { if r != nil { logutil.BgLogger().Error("[ddl] limit DDL jobs meet panic", zap.String("ID", d.uuid), zap.Reflect("r", r), zap.Stack("stack trace")) @@ -351,7 +351,7 @@ func (d *ddl) start(ctx context.Context, ctxPool *pools.ResourcePool) { w := worker go tidbutil.WithRecovery( func() { w.start(d.ddlCtx) }, - func(r interface{}) { + func(r any) { if r != nil { logutil.Logger(w.logCtx).Error("[ddl] DDL worker meet panic", zap.String("ID", d.uuid)) metrics.PanicCounter.WithLabelValues(metrics.LabelDDLWorker).Inc() @@ -366,7 +366,7 @@ func (d *ddl) start(ctx context.Context, ctxPool *pools.ResourcePool) { go tidbutil.WithRecovery( func() { d.schemaSyncer.StartCleanWork() }, - func(r interface{}) { + func(r any) { if r != nil { logutil.BgLogger().Error("[ddl] DDL syncer clean worker meet panic", zap.String("ID", d.uuid), zap.Reflect("r", r), zap.Stack("stack trace")) diff --git a/ddl/ddl_api.go b/ddl/ddl_api.go index f77d70ff2..c6df3d195 100644 --- a/ddl/ddl_api.go +++ b/ddl/ddl_api.go @@ -113,7 +113,7 @@ func (d *ddl) CreateSchemaWithInfo( SchemaName: dbInfo.Name.L, Type: model.ActionCreateSchema, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{dbInfo}, + Args: []any{dbInfo}, } err = d.doDDLJob(ctx, job) @@ -168,7 +168,7 @@ func (d *ddl) AlterSchema(ctx sessionctx.Context, stmt *ast.AlterDatabaseStmt) ( SchemaName: dbInfo.Name.L, Type: model.ActionModifySchemaCharsetAndCollate, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{toCharset, toCollate}, + Args: []any{toCharset, toCollate}, } err = d.doDDLJob(ctx, job) err = d.callHookOnChanged(err) @@ -407,7 +407,7 @@ func buildColumnAndConstraint( // In non-strict SQL mode, if the default value of the column is an empty string, the default value can be ignored. // In strict SQL mode, TEXT/BLOB/JSON can't have not null default values. // In NO_ZERO_DATE SQL mode, TIMESTAMP/DATE/DATETIME type can't have zero date like '0000-00-00' or '0000-00-00 00:00:00'. -func checkColumnDefaultValue(ctx sessionctx.Context, col *table.Column, value interface{}) (bool, interface{}, error) { +func checkColumnDefaultValue(ctx sessionctx.Context, col *table.Column, value any) (bool, any, error) { hasDefaultValue := true if value != nil && (col.Tp == mysql.TypeJSON || col.Tp == mysql.TypeTinyBlob || col.Tp == mysql.TypeMediumBlob || @@ -451,7 +451,7 @@ func checkSequenceDefaultValue(col *table.Column) error { return ErrColumnTypeUnsupportedNextValue.GenWithStackByArgs(col.ColumnInfo.Name.O) } -func convertTimestampDefaultValToUTC(ctx sessionctx.Context, defaultVal interface{}, col *table.Column) (interface{}, error) { +func convertTimestampDefaultValToUTC(ctx sessionctx.Context, defaultVal any, col *table.Column) (any, error) { if defaultVal == nil || col.Tp != mysql.TypeTimestamp { return defaultVal, nil } @@ -631,7 +631,7 @@ func columnDefToCol(ctx sessionctx.Context, offset int, colDef *ast.ColumnDef, o // getDefault value will get the default value for column. // 1: get the expr restored string for the column which uses sequence next value as default value. // 2: get specific default value for the other column. -func getDefaultValue(ctx sessionctx.Context, col *table.Column, c *ast.ColumnOption) (interface{}, bool, error) { +func getDefaultValue(ctx sessionctx.Context, col *table.Column, c *ast.ColumnOption) (any, bool, error) { tp, fsp := col.FieldType.Tp, col.FieldType.Decimal if tp == mysql.TypeTimestamp || tp == mysql.TypeDatetime { switch x := c.Expr.(type) { @@ -1547,7 +1547,7 @@ func (d *ddl) CreateTableWithInfo( } var actionType model.ActionType - args := []interface{}{tbInfo} + args := []any{tbInfo} switch { case tbInfo.View != nil: actionType = model.ActionCreateView @@ -1645,7 +1645,7 @@ func (d *ddl) RecoverTable(ctx sessionctx.Context, recoverInfo *RecoverInfo) (er SchemaName: schema.Name.L, Type: model.ActionRecoverTable, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{tbInfo, recoverInfo.CurAutoIncID, recoverInfo.DropJobID, + Args: []any{tbInfo, recoverInfo.CurAutoIncID, recoverInfo.DropJobID, recoverInfo.SnapshotTS, recoverTableCheckFlagNone, recoverInfo.CurAutoRandID}, } err = d.doDDLJob(ctx, job) @@ -2240,7 +2240,7 @@ func (d *ddl) RebaseAutoID(ctx sessionctx.Context, ident ast.Ident, newBase int6 SchemaName: schema.Name.L, Type: actionType, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{newBase}, + Args: []any{newBase}, } err = d.doDDLJob(ctx, job) err = d.callHookOnChanged(err) @@ -2270,7 +2270,7 @@ func (d *ddl) ShardRowID(ctx sessionctx.Context, tableIdent ast.Ident, uVal uint TableID: t.Meta().ID, SchemaName: schema.Name.L, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{uVal}, + Args: []any{uVal}, } err = d.doDDLJob(ctx, job) err = d.callHookOnChanged(err) @@ -2415,7 +2415,7 @@ func (d *ddl) AddColumn(ctx sessionctx.Context, ti ast.Ident, spec *ast.AlterTab SchemaName: schema.Name.L, Type: model.ActionAddColumn, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{col, spec.Position, 0}, + Args: []any{col, spec.Position, 0}, } err = d.doDDLJob(ctx, job) @@ -2491,7 +2491,7 @@ func (d *ddl) AddColumns(ctx sessionctx.Context, ti ast.Ident, specs []*ast.Alte SchemaName: schema.Name.L, Type: model.ActionAddColumns, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{columns, positions, offsets, ifNotExists}, + Args: []any{columns, positions, offsets, ifNotExists}, } err = d.doDDLJob(ctx, job) @@ -2546,7 +2546,7 @@ func (d *ddl) AddTablePartitions(ctx sessionctx.Context, ident ast.Ident, spec * SchemaName: schema.Name.L, Type: model.ActionAddTablePartition, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{partInfo}, + Args: []any{partInfo}, } err = d.doDDLJob(ctx, job) @@ -2626,7 +2626,7 @@ func (d *ddl) TruncateTablePartition(ctx sessionctx.Context, ident ast.Ident, sp SchemaName: schema.Name.L, Type: model.ActionTruncateTablePartition, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{pid}, + Args: []any{pid}, } err = d.doDDLJob(ctx, job) @@ -2673,7 +2673,7 @@ func (d *ddl) DropTablePartition(ctx sessionctx.Context, ident ast.Ident, spec * SchemaName: schema.Name.L, Type: model.ActionDropTablePartition, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{partName}, + Args: []any{partName}, } err = d.doDDLJob(ctx, job) @@ -2710,7 +2710,7 @@ func (d *ddl) DropColumn(ctx sessionctx.Context, ti ast.Ident, spec *ast.AlterTa SchemaName: schema.Name.L, Type: model.ActionDropColumn, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{colName}, + Args: []any{colName}, } err = d.doDDLJob(ctx, job) @@ -2778,7 +2778,7 @@ func (d *ddl) DropColumns(ctx sessionctx.Context, ti ast.Ident, specs []*ast.Alt SchemaName: schema.Name.L, Type: model.ActionDropColumns, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{colNames, ifExists}, + Args: []any{colNames, ifExists}, } err = d.doDDLJob(ctx, job) @@ -3173,7 +3173,7 @@ func (d *ddl) getModifiableColumnJob(ctx sessionctx.Context, ident ast.Ident, or SchemaName: schema.Name.L, Type: model.ActionModifyColumn, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{&newCol, originalColName, spec.Position, modifyColumnTp}, + Args: []any{&newCol, originalColName, spec.Position, modifyColumnTp}, } return job, nil } @@ -3331,7 +3331,7 @@ func (d *ddl) RenameColumn(ctx sessionctx.Context, ident ast.Ident, spec *ast.Al SchemaName: schema.Name.L, Type: model.ActionModifyColumn, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{&newCol, oldColName, spec.Position, 0}, + Args: []any{&newCol, oldColName, spec.Position, 0}, } err = d.doDDLJob(ctx, job) err = d.callHookOnChanged(err) @@ -3412,7 +3412,7 @@ func (d *ddl) AlterColumn(ctx sessionctx.Context, ident ast.Ident, spec *ast.Alt SchemaName: schema.Name.L, Type: model.ActionSetDefaultValue, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{col}, + Args: []any{col}, } err = d.doDDLJob(ctx, job) @@ -3439,7 +3439,7 @@ func (d *ddl) AlterTableComment(ctx sessionctx.Context, ident ast.Ident, spec *a SchemaName: schema.Name.L, Type: model.ActionModifyTableComment, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{spec.Comment}, + Args: []any{spec.Comment}, } err = d.doDDLJob(ctx, job) @@ -3460,7 +3460,7 @@ func (d *ddl) AlterTableAutoIDCache(ctx sessionctx.Context, ident ast.Ident, new SchemaName: schema.Name.L, Type: model.ActionModifyTableAutoIdCache, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{newCache}, + Args: []any{newCache}, } err = d.doDDLJob(ctx, job) @@ -3512,7 +3512,7 @@ func (d *ddl) AlterTableCharsetAndCollate(ctx sessionctx.Context, ident ast.Iden SchemaName: schema.Name.L, Type: model.ActionModifyTableCharsetAndCollate, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{toCharset, toCollate, needsOverwriteCols}, + Args: []any{toCharset, toCollate, needsOverwriteCols}, } err = d.doDDLJob(ctx, job) err = d.callHookOnChanged(err) @@ -3547,7 +3547,7 @@ func (d *ddl) AlterTableSetTiFlashReplica(ctx sessionctx.Context, ident ast.Iden SchemaName: schema.Name.L, Type: model.ActionSetTiFlashReplica, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{*replicaInfo}, + Args: []any{*replicaInfo}, } err = d.doDDLJob(ctx, job) err = d.callHookOnChanged(err) @@ -3581,7 +3581,7 @@ func (d *ddl) UpdateTableReplicaInfo(ctx sessionctx.Context, physicalID int64, a SchemaName: db.Name.L, Type: model.ActionUpdateTiFlashReplicaStatus, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{available, physicalID}, + Args: []any{available, physicalID}, } err := d.doDDLJob(ctx, job) err = d.callHookOnChanged(err) @@ -3680,7 +3680,7 @@ func (d *ddl) RenameIndex(ctx sessionctx.Context, ident ast.Ident, spec *ast.Alt SchemaName: schema.Name.L, Type: model.ActionRenameIndex, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{spec.FromKey, spec.ToKey}, + Args: []any{spec.FromKey, spec.ToKey}, } err = d.doDDLJob(ctx, job) @@ -3764,7 +3764,7 @@ func (d *ddl) TruncateTable(ctx sessionctx.Context, ti ast.Ident) error { SchemaName: schema.Name.L, Type: model.ActionTruncateTable, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{newTableID}, + Args: []any{newTableID}, } if ok, _ := ctx.CheckTableLocked(tb.Meta().ID); ok && config.TableLockEnabled() { // AddTableLock here to avoid this ddl job was executed successfully but the session was been kill before return. @@ -3844,7 +3844,7 @@ func (d *ddl) RenameTable(ctx sessionctx.Context, oldIdent, newIdent ast.Ident, SchemaName: newSchema.Name.L, Type: model.ActionRenameTable, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{oldSchema.ID, newIdent.Name}, + Args: []any{oldSchema.ID, newIdent.Name}, } err = d.doDDLJob(ctx, job) @@ -3931,7 +3931,7 @@ func (d *ddl) CreatePrimaryKey(ctx sessionctx.Context, ti ast.Ident, indexName m SchemaName: schema.Name.L, Type: model.ActionAddPrimaryKey, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{unique, indexName, indexPartSpecifications, indexOption, sqlMode}, + Args: []any{unique, indexName, indexPartSpecifications, indexOption, sqlMode}, Priority: ctx.GetSessionVars().DDLReorgPriority, } @@ -4081,7 +4081,7 @@ func (d *ddl) CreateIndex(ctx sessionctx.Context, ti ast.Ident, keyType ast.Inde SchemaName: schema.Name.L, Type: model.ActionAddIndex, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{unique, indexName, indexPartSpecifications, indexOption, hiddenCols}, + Args: []any{unique, indexName, indexPartSpecifications, indexOption, hiddenCols}, Priority: ctx.GetSessionVars().DDLReorgPriority, } @@ -4192,7 +4192,7 @@ func (d *ddl) CreateForeignKey(ctx sessionctx.Context, ti ast.Ident, fkName mode SchemaName: schema.Name.L, Type: model.ActionAddForeignKey, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{fkInfo}, + Args: []any{fkInfo}, } err = d.doDDLJob(ctx, job) @@ -4219,7 +4219,7 @@ func (d *ddl) DropForeignKey(ctx sessionctx.Context, ti ast.Ident, fkName model. SchemaName: schema.Name.L, Type: model.ActionDropForeignKey, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{fkName}, + Args: []any{fkName}, } err = d.doDDLJob(ctx, job) @@ -4284,7 +4284,7 @@ func (d *ddl) DropIndex(ctx sessionctx.Context, ti ast.Ident, indexName model.CI SchemaName: schema.Name.L, Type: jobTp, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{indexName}, + Args: []any{indexName}, } err = d.doDDLJob(ctx, job) @@ -4473,7 +4473,7 @@ func (d *ddl) LockTables(ctx sessionctx.Context, stmt *ast.LockTablesStmt) error TableID: lockTables[0].TableID, Type: model.ActionLockTable, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{arg}, + Args: []any{arg}, } // AddTableLock here is avoiding this job was executed successfully but the session was killed before return. ctx.AddTableLock(lockTables) @@ -4503,7 +4503,7 @@ func (d *ddl) UnlockTables(ctx sessionctx.Context, unlockTables []model.TableLoc TableID: unlockTables[0].TableID, Type: model.ActionUnlockTable, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{arg}, + Args: []any{arg}, } err := d.doDDLJob(ctx, job) @@ -4568,7 +4568,7 @@ func (d *ddl) CleanupTableLock(ctx sessionctx.Context, tables []*ast.TableName) TableID: cleanupTables[0].TableID, Type: model.ActionUnlockTable, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{arg}, + Args: []any{arg}, } err := d.doDDLJob(ctx, job) if err == nil { @@ -4653,7 +4653,7 @@ func (d *ddl) RepairTable(ctx sessionctx.Context, table *ast.TableName, createSt SchemaName: oldDBInfo.Name.L, Type: model.ActionRepairTable, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{newTableInfo}, + Args: []any{newTableInfo}, } err = d.doDDLJob(ctx, job) if err == nil { diff --git a/ddl/ddl_test.go b/ddl/ddl_test.go index 1e519aa50..d7d27b320 100644 --- a/ddl/ddl_test.go +++ b/ddl/ddl_test.go @@ -77,7 +77,7 @@ func (d *ddl) restartWorkers(ctx context.Context) { defer d.wg.Done() util.WithRecovery( func() { d.limitDDLJobs() }, - func(r interface{}) { + func(r any) { logutil.BgLogger().Error("[ddl] DDL add batch DDL jobs meet panic", zap.String("ID", d.uuid), zap.Reflect("r", r), zap.Stack("stack trace")) metrics.PanicCounter.WithLabelValues(metrics.LabelDDL).Inc() @@ -94,7 +94,7 @@ func (d *ddl) restartWorkers(ctx context.Context) { worker.quitCh = make(chan struct{}) w := worker go util.WithRecovery(func() { w.start(d.ddlCtx) }, - func(r interface{}) { + func(r any) { if r != nil { log.Error("[ddl] restart DDL worker meet panic", zap.String("worker", w.String()), zap.String("ID", d.uuid)) } @@ -198,7 +198,7 @@ func buildCreateIdxJob(dbInfo *model.DBInfo, tblInfo *model.TableInfo, unique bo TableID: tblInfo.ID, Type: model.ActionAddIndex, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{unique, model.NewCIStr(indexName), + Args: []any{unique, model.NewCIStr(indexName), []*ast.IndexPartSpecification{{ Column: &ast.ColumnName{Name: model.NewCIStr(colName)}, Length: types.UnspecifiedLength}}}, @@ -224,7 +224,7 @@ func testCreateIndex(c *C, ctx sessionctx.Context, d *ddl, dbInfo *model.DBInfo, return job } -func testAddColumn(c *C, ctx sessionctx.Context, d *ddl, dbInfo *model.DBInfo, tblInfo *model.TableInfo, args []interface{}) *model.Job { +func testAddColumn(c *C, ctx sessionctx.Context, d *ddl, dbInfo *model.DBInfo, tblInfo *model.TableInfo, args []any) *model.Job { job := &model.Job{ SchemaID: dbInfo.ID, TableID: tblInfo.ID, @@ -239,7 +239,7 @@ func testAddColumn(c *C, ctx sessionctx.Context, d *ddl, dbInfo *model.DBInfo, t return job } -func testAddColumns(c *C, ctx sessionctx.Context, d *ddl, dbInfo *model.DBInfo, tblInfo *model.TableInfo, args []interface{}) *model.Job { +func testAddColumns(c *C, ctx sessionctx.Context, d *ddl, dbInfo *model.DBInfo, tblInfo *model.TableInfo, args []any) *model.Job { job := &model.Job{ SchemaID: dbInfo.ID, TableID: tblInfo.ID, @@ -264,7 +264,7 @@ func buildDropIdxJob(dbInfo *model.DBInfo, tblInfo *model.TableInfo, indexName s TableID: tblInfo.ID, Type: tp, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{model.NewCIStr(indexName)}, + Args: []any{model.NewCIStr(indexName)}, } } @@ -283,6 +283,6 @@ func buildRebaseAutoIDJobJob(dbInfo *model.DBInfo, tblInfo *model.TableInfo, new TableID: tblInfo.ID, Type: model.ActionRebaseAutoID, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{newBaseID}, + Args: []any{newBaseID}, } } diff --git a/ddl/ddl_worker.go b/ddl/ddl_worker.go index 2eb17fb6a..c174fdf5a 100644 --- a/ddl/ddl_worker.go +++ b/ddl/ddl_worker.go @@ -462,7 +462,7 @@ func (w *worker) handleDDLJobQueue(d *ddlCtx) error { // and retry later if the job is not cancelled. tidbutil.WithRecovery(func() { schemaVer, runJobErr = w.runDDLJob(d, t, job) - }, func(r interface{}) { + }, func(r any) { if r != nil { // If run ddl job panic, just cancel the ddl jobs. job.State = model.JobStateCancelling diff --git a/ddl/ddl_worker_test.go b/ddl/ddl_worker_test.go index 5a3630173..841c9bfcc 100644 --- a/ddl/ddl_worker_test.go +++ b/ddl/ddl_worker_test.go @@ -111,7 +111,7 @@ func (s *testDDLSuite) TestSchemaError(c *C) { defer d.Stop() ctx := testNewContext(d) - doDDLJobErr(c, 1, 0, model.ActionCreateSchema, []interface{}{1}, ctx, d) + doDDLJobErr(c, 1, 0, model.ActionCreateSchema, []any{1}, ctx, d) } func (s *testDDLSuite) TestTableError(c *C) { @@ -150,12 +150,12 @@ func (s *testDDLSuite) TestTableError(c *C) { c.Assert(err, IsNil) // Args is wrong, so creating table is failed. - doDDLJobErr(c, 1, 1, model.ActionCreateTable, []interface{}{1}, ctx, d) + doDDLJobErr(c, 1, 1, model.ActionCreateTable, []any{1}, ctx, d) // Schema ID is wrong, so creating table is failed. - doDDLJobErr(c, -1, tblInfo.ID, model.ActionCreateTable, []interface{}{tblInfo}, ctx, d) + doDDLJobErr(c, -1, tblInfo.ID, model.ActionCreateTable, []any{tblInfo}, ctx, d) // Table exists, so creating table is failed. tblInfo.ID = tblInfo.ID + 1 - doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionCreateTable, []interface{}{tblInfo}, ctx, d) + doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionCreateTable, []any{tblInfo}, ctx, d) } @@ -178,12 +178,12 @@ func (s *testDDLSuite) TestViewError(c *C) { testCreateView(c, ctx, d, dbInfo, tblInfo) // Args is wrong, so creating view is failed. - doDDLJobErr(c, 1, 1, model.ActionCreateView, []interface{}{1}, ctx, d) + doDDLJobErr(c, 1, 1, model.ActionCreateView, []any{1}, ctx, d) // Schema ID is wrong and orReplace is false, so creating view is failed. - doDDLJobErr(c, -1, tblInfo.ID, model.ActionCreateView, []interface{}{tblInfo, false}, ctx, d) + doDDLJobErr(c, -1, tblInfo.ID, model.ActionCreateView, []any{tblInfo, false}, ctx, d) // View exists and orReplace is false, so creating view is failed. tblInfo.ID = tblInfo.ID + 1 - doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionCreateView, []interface{}{tblInfo, false}, ctx, d) + doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionCreateView, []any{tblInfo, false}, ctx, d) } @@ -203,7 +203,7 @@ func (s *testDDLSuite) TestInvalidDDLJob(c *C) { TableID: 0, Type: model.ActionNone, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{}, + Args: []any{}, } err := d.doDDLJob(ctx, job) c.Assert(err.Error(), Equals, "[ddl:8204]invalid ddl job type: none") @@ -228,7 +228,7 @@ func (s *testDDLSuite) TestForeignKeyError(c *C) { tblInfo := testTableInfo(c, d, "t", 3) testCreateSchema(c, ctx, d, dbInfo) testCreateTable(c, ctx, d, dbInfo, tblInfo) - doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionDropForeignKey, []interface{}{model.NewCIStr("c1_foreign_key")}, ctx, d) + doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionDropForeignKey, []any{model.NewCIStr("c1_foreign_key")}, ctx, d) } func (s *testDDLSuite) TestIndexError(c *C) { @@ -253,22 +253,22 @@ func (s *testDDLSuite) TestIndexError(c *C) { testCreateTable(c, ctx, d, dbInfo, tblInfo) // for adding index - doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionAddIndex, []interface{}{1}, ctx, d) + doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionAddIndex, []any{1}, ctx, d) doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionAddIndex, - []interface{}{false, model.NewCIStr("t"), 1, + []any{false, model.NewCIStr("t"), 1, []*ast.IndexPartSpecification{{Column: &ast.ColumnName{Name: model.NewCIStr("c")}, Length: 256}}}, ctx, d) doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionAddIndex, - []interface{}{false, model.NewCIStr("c1_index"), 1, + []any{false, model.NewCIStr("c1_index"), 1, []*ast.IndexPartSpecification{{Column: &ast.ColumnName{Name: model.NewCIStr("c")}, Length: 256}}}, ctx, d) testCreateIndex(c, ctx, d, dbInfo, tblInfo, false, "c1_index", "c1") doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionAddIndex, - []interface{}{false, model.NewCIStr("c1_index"), 1, + []any{false, model.NewCIStr("c1_index"), 1, []*ast.IndexPartSpecification{{Column: &ast.ColumnName{Name: model.NewCIStr("c1")}, Length: 256}}}, ctx, d) // for dropping index - doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionDropIndex, []interface{}{1}, ctx, d) + doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionDropIndex, []any{1}, ctx, d) testDropIndex(c, ctx, d, dbInfo, tblInfo, "c1_index") - doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionDropIndex, []interface{}{model.NewCIStr("c1_index")}, ctx, d) + doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionDropIndex, []any{model.NewCIStr("c1_index")}, ctx, d) } func (s *testDDLSuite) TestColumnError(c *C) { @@ -299,28 +299,28 @@ func (s *testDDLSuite) TestColumnError(c *C) { positions := &[]*ast.ColumnPosition{pos} // for adding column - doDDLJobErr(c, -1, tblInfo.ID, model.ActionAddColumn, []interface{}{col, pos, 0}, ctx, d) - doDDLJobErr(c, dbInfo.ID, -1, model.ActionAddColumn, []interface{}{col, pos, 0}, ctx, d) - doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionAddColumn, []interface{}{0}, ctx, d) - doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionAddColumn, []interface{}{col, pos, 0}, ctx, d) + doDDLJobErr(c, -1, tblInfo.ID, model.ActionAddColumn, []any{col, pos, 0}, ctx, d) + doDDLJobErr(c, dbInfo.ID, -1, model.ActionAddColumn, []any{col, pos, 0}, ctx, d) + doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionAddColumn, []any{0}, ctx, d) + doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionAddColumn, []any{col, pos, 0}, ctx, d) // for dropping column - doDDLJobErr(c, -1, tblInfo.ID, model.ActionDropColumn, []interface{}{col, pos, 0}, ctx, d) - doDDLJobErr(c, dbInfo.ID, -1, model.ActionDropColumn, []interface{}{col, pos, 0}, ctx, d) - doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionDropColumn, []interface{}{0}, ctx, d) - doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionDropColumn, []interface{}{model.NewCIStr("c5")}, ctx, d) + doDDLJobErr(c, -1, tblInfo.ID, model.ActionDropColumn, []any{col, pos, 0}, ctx, d) + doDDLJobErr(c, dbInfo.ID, -1, model.ActionDropColumn, []any{col, pos, 0}, ctx, d) + doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionDropColumn, []any{0}, ctx, d) + doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionDropColumn, []any{model.NewCIStr("c5")}, ctx, d) // for adding columns - doDDLJobErr(c, -1, tblInfo.ID, model.ActionAddColumns, []interface{}{cols, positions, 0}, ctx, d) - doDDLJobErr(c, dbInfo.ID, -1, model.ActionAddColumns, []interface{}{cols, positions, 0}, ctx, d) - doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionAddColumns, []interface{}{0}, ctx, d) - doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionAddColumns, []interface{}{cols, positions, 0}, ctx, d) + doDDLJobErr(c, -1, tblInfo.ID, model.ActionAddColumns, []any{cols, positions, 0}, ctx, d) + doDDLJobErr(c, dbInfo.ID, -1, model.ActionAddColumns, []any{cols, positions, 0}, ctx, d) + doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionAddColumns, []any{0}, ctx, d) + doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionAddColumns, []any{cols, positions, 0}, ctx, d) // for dropping columns - doDDLJobErr(c, -1, tblInfo.ID, model.ActionDropColumns, []interface{}{col, pos, 0}, ctx, d) - doDDLJobErr(c, dbInfo.ID, -1, model.ActionDropColumns, []interface{}{col, pos, 0}, ctx, d) - doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionDropColumns, []interface{}{0}, ctx, d) - doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionDropColumns, []interface{}{[]model.CIStr{model.NewCIStr("c5"), model.NewCIStr("c6")}, make([]bool, 2)}, ctx, d) + doDDLJobErr(c, -1, tblInfo.ID, model.ActionDropColumns, []any{col, pos, 0}, ctx, d) + doDDLJobErr(c, dbInfo.ID, -1, model.ActionDropColumns, []any{col, pos, 0}, ctx, d) + doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionDropColumns, []any{0}, ctx, d) + doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionDropColumns, []any{[]model.CIStr{model.NewCIStr("c5"), model.NewCIStr("c6")}, make([]bool, 2)}, ctx, d) } func testCheckOwner(c *C, d *ddl, expectedVal bool) { @@ -357,7 +357,7 @@ func testCheckJobCancelled(c *C, d *ddl, job *model.Job, state *model.SchemaStat } func doDDLJobErrWithSchemaState(ctx sessionctx.Context, d *ddl, c *C, schemaID, tableID int64, tp model.ActionType, - args []interface{}, state *model.SchemaState) *model.Job { + args []any, state *model.SchemaState) *model.Job { job := &model.Job{ SchemaID: schemaID, TableID: tableID, @@ -374,7 +374,7 @@ func doDDLJobErrWithSchemaState(ctx sessionctx.Context, d *ddl, c *C, schemaID, } func doDDLJobSuccess(ctx sessionctx.Context, d *ddl, c *C, schemaID, tableID int64, tp model.ActionType, - args []interface{}) { + args []any) { job := &model.Job{ SchemaID: schemaID, TableID: tableID, @@ -386,7 +386,7 @@ func doDDLJobSuccess(ctx sessionctx.Context, d *ddl, c *C, schemaID, tableID int c.Assert(err, IsNil) } -func doDDLJobErr(c *C, schemaID, tableID int64, tp model.ActionType, args []interface{}, +func doDDLJobErr(c *C, schemaID, tableID int64, tp model.ActionType, args []any, ctx sessionctx.Context, d *ddl) *model.Job { return doDDLJobErrWithSchemaState(ctx, d, c, schemaID, tableID, tp, args, nil) } @@ -619,7 +619,7 @@ func (s *testDDLSuite) TestCancelJob(c *C) { // for adding index updateTest(&tests[0]) idxOrigName := "idx" - validArgs := []interface{}{false, model.NewCIStr(idxOrigName), + validArgs := []any{false, model.NewCIStr(idxOrigName), []*ast.IndexPartSpecification{{ Column: &ast.ColumnName{Name: model.NewCIStr("c1")}, Length: -1, @@ -658,7 +658,7 @@ func (s *testDDLSuite) TestCancelJob(c *C) { col, _, err := buildColumnAndConstraint(ctx, 2, newColumnDef, nil, chs, coll) c.Assert(err, IsNil) - addColumnArgs := []interface{}{col, &ast.ColumnPosition{Tp: ast.ColumnPositionNone}, 0} + addColumnArgs := []any{col, &ast.ColumnPosition{Tp: ast.ColumnPositionNone}, 0} doDDLJobErrWithSchemaState(ctx, d, c, dbInfo.ID, tblInfo.ID, model.ActionAddColumn, addColumnArgs, &cancelState) c.Check(errors.ErrorStack(checkErr), Equals, "") s.checkAddColumns(c, d, dbInfo.ID, tblInfo.ID, []string{addingColName}, false) @@ -681,14 +681,14 @@ func (s *testDDLSuite) TestCancelJob(c *C) { // for create table tblInfo1 := testTableInfo(c, d, "t1", 2) updateTest(&tests[8]) - doDDLJobErrWithSchemaState(ctx, d, c, dbInfo.ID, tblInfo1.ID, model.ActionCreateTable, []interface{}{tblInfo1}, &cancelState) + doDDLJobErrWithSchemaState(ctx, d, c, dbInfo.ID, tblInfo1.ID, model.ActionCreateTable, []any{tblInfo1}, &cancelState) c.Check(checkErr, IsNil) testCheckTableState(c, d, dbInfo, tblInfo1, model.StateNone) // for create database dbInfo1 := testSchemaInfo(c, d, "test_cancel_job1") updateTest(&tests[9]) - doDDLJobErrWithSchemaState(ctx, d, c, dbInfo1.ID, 0, model.ActionCreateSchema, []interface{}{dbInfo1}, &cancelState) + doDDLJobErrWithSchemaState(ctx, d, c, dbInfo1.ID, 0, model.ActionCreateSchema, []any{dbInfo1}, &cancelState) c.Check(checkErr, IsNil) testCheckSchemaState(c, d, dbInfo1, model.StateNone) @@ -716,7 +716,7 @@ func (s *testDDLSuite) TestCancelJob(c *C) { // cancel rebase auto id updateTest(&tests[13]) - rebaseIDArgs := []interface{}{int64(200)} + rebaseIDArgs := []any{int64(200)} doDDLJobErrWithSchemaState(ctx, d, c, dbInfo.ID, tblInfo.ID, model.ActionRebaseAutoID, rebaseIDArgs, &cancelState) c.Check(errors.ErrorStack(checkErr), Equals, "") changedTable := testGetTable(c, d, dbInfo.ID, tblInfo.ID) @@ -724,7 +724,7 @@ func (s *testDDLSuite) TestCancelJob(c *C) { // cancel shard bits updateTest(&tests[14]) - shardRowIDArgs := []interface{}{uint64(7)} + shardRowIDArgs := []any{uint64(7)} doDDLJobErrWithSchemaState(ctx, d, c, dbInfo.ID, tblInfo.ID, model.ActionShardRowID, shardRowIDArgs, &cancelState) c.Check(checkErr, IsNil) changedTable = testGetTable(c, d, dbInfo.ID, tblInfo.ID) @@ -733,7 +733,7 @@ func (s *testDDLSuite) TestCancelJob(c *C) { // modify column col.DefaultValue = "1" updateTest(&tests[15]) - modifyColumnArgs := []interface{}{col, col.Name, &ast.ColumnPosition{}, byte(0)} + modifyColumnArgs := []any{col, col.Name, &ast.ColumnPosition{}, byte(0)} doDDLJobErrWithSchemaState(ctx, d, c, dbInfo.ID, tblInfo.ID, test.act, modifyColumnArgs, &test.cancelState) c.Check(checkErr, IsNil) changedTable = testGetTable(c, d, dbInfo.ID, tblInfo.ID) @@ -742,7 +742,7 @@ func (s *testDDLSuite) TestCancelJob(c *C) { // Test add foreign key failed cause by canceled. updateTest(&tests[16]) - addForeignKeyArgs := []interface{}{model.FKInfo{Name: model.NewCIStr("fk1")}} + addForeignKeyArgs := []any{model.FKInfo{Name: model.NewCIStr("fk1")}} doDDLJobErrWithSchemaState(ctx, d, c, dbInfo.ID, tblInfo.ID, test.act, addForeignKeyArgs, &test.cancelState) c.Check(checkErr, IsNil) changedTable = testGetTable(c, d, dbInfo.ID, tblInfo.ID) @@ -758,7 +758,7 @@ func (s *testDDLSuite) TestCancelJob(c *C) { // Test drop foreign key failed cause by canceled. updateTest(&tests[18]) - dropForeignKeyArgs := []interface{}{addForeignKeyArgs[0].(model.FKInfo).Name} + dropForeignKeyArgs := []any{addForeignKeyArgs[0].(model.FKInfo).Name} doDDLJobErrWithSchemaState(ctx, d, c, dbInfo.ID, tblInfo.ID, test.act, dropForeignKeyArgs, &test.cancelState) c.Check(checkErr, IsNil) changedTable = testGetTable(c, d, dbInfo.ID, tblInfo.ID) @@ -774,7 +774,7 @@ func (s *testDDLSuite) TestCancelJob(c *C) { // test rename table failed caused by canceled. test = &tests[20] - renameTableArgs := []interface{}{dbInfo.ID, model.NewCIStr("t2")} + renameTableArgs := []any{dbInfo.ID, model.NewCIStr("t2")} doDDLJobErrWithSchemaState(ctx, d, c, dbInfo.ID, tblInfo.ID, test.act, renameTableArgs, &test.cancelState) c.Check(checkErr, IsNil) changedTable = testGetTable(c, d, dbInfo.ID, tblInfo.ID) @@ -789,7 +789,7 @@ func (s *testDDLSuite) TestCancelJob(c *C) { // test modify table charset failed caused by canceled. test = &tests[22] - modifyTableCharsetArgs := []interface{}{"utf8mb4", "utf8mb4_bin"} + modifyTableCharsetArgs := []any{"utf8mb4", "utf8mb4_bin"} doDDLJobErrWithSchemaState(ctx, d, c, dbInfo.ID, tblInfo.ID, test.act, modifyTableCharsetArgs, &test.cancelState) c.Check(checkErr, IsNil) changedTable = testGetTable(c, d, dbInfo.ID, tblInfo.ID) @@ -806,7 +806,7 @@ func (s *testDDLSuite) TestCancelJob(c *C) { // test truncate table partition failed caused by canceled. test = &tests[24] - truncateTblPartitionArgs := []interface{}{partitionTblInfo.Partition.Definitions[0].ID} + truncateTblPartitionArgs := []any{partitionTblInfo.Partition.Definitions[0].ID} doDDLJobErrWithSchemaState(ctx, d, c, dbInfo.ID, partitionTblInfo.ID, test.act, truncateTblPartitionArgs, &test.cancelState) c.Check(checkErr, IsNil) changedTable = testGetTable(c, d, dbInfo.ID, partitionTblInfo.ID) @@ -821,7 +821,7 @@ func (s *testDDLSuite) TestCancelJob(c *C) { // test modify schema charset failed caused by canceled. test = &tests[26] - charsetAndCollate := []interface{}{"utf8mb4", "utf8mb4_bin"} + charsetAndCollate := []any{"utf8mb4", "utf8mb4_bin"} doDDLJobErrWithSchemaState(ctx, d, c, dbInfo.ID, tblInfo.ID, test.act, charsetAndCollate, &test.cancelState) c.Check(checkErr, IsNil) dbInfo, err = testGetSchemaInfoWithError(d, dbInfo.ID) @@ -842,7 +842,7 @@ func (s *testDDLSuite) TestCancelJob(c *C) { tblInfo = changedTable.Meta() updateTest(&tests[28]) idxOrigName = "primary" - validArgs = []interface{}{false, model.NewCIStr(idxOrigName), + validArgs = []any{false, model.NewCIStr(idxOrigName), []*ast.IndexPartSpecification{{ Column: &ast.ColumnName{Name: model.NewCIStr("c1")}, Length: -1, @@ -898,7 +898,7 @@ func (s *testDDLSuite) TestCancelJob(c *C) { } ifNotExists := make([]bool, len(cols)) - addColumnArgs = []interface{}{cols, positions, offsets, ifNotExists} + addColumnArgs = []any{cols, positions, offsets, ifNotExists} doDDLJobErrWithSchemaState(ctx, d, c, dbInfo.ID, tblInfo.ID, model.ActionAddColumns, addColumnArgs, &cancelState) c.Check(errors.ErrorStack(checkErr), Equals, "") s.checkAddColumns(c, d, dbInfo.ID, tblInfo.ID, addingColNames, false) @@ -979,7 +979,7 @@ func (s *testDDLSuite) TestBuildJobDependence(c *C) { job6 := &model.Job{ID: 6, TableID: 1, Type: model.ActionDropTable} job7 := &model.Job{ID: 7, TableID: 2, Type: model.ActionModifyColumn} job9 := &model.Job{ID: 9, SchemaID: 111, Type: model.ActionDropSchema} - job11 := &model.Job{ID: 11, TableID: 2, Type: model.ActionRenameTable, Args: []interface{}{int64(111), "old db name"}} + job11 := &model.Job{ID: 11, TableID: 2, Type: model.ActionRenameTable, Args: []any{int64(111), "old db name"}} kv.RunInNewTxn(store, false, func(txn kv.Transaction) error { t := meta.NewMeta(txn) err := t.EnQueueDDLJob(job1) diff --git a/ddl/delete_range.go b/ddl/delete_range.go index 81179a7c2..0f7486bfc 100644 --- a/ddl/delete_range.go +++ b/ddl/delete_range.go @@ -310,7 +310,7 @@ func insertJobIntoDeleteRangeTable(ctx sessionctx.Context, job *model.Job) error } case model.ActionDropIndex, model.ActionDropPrimaryKey: tableID := job.TableID - var indexName interface{} + var indexName any var indexID int64 var partitionIDs []int64 if err := job.DecodeArgs(&indexName, &indexID, &partitionIDs); err != nil { diff --git a/ddl/foreign_key_test.go b/ddl/foreign_key_test.go index 137330b16..7ed812b88 100644 --- a/ddl/foreign_key_test.go +++ b/ddl/foreign_key_test.go @@ -73,7 +73,7 @@ func (s *testForeighKeySuite) testCreateForeignKey(c *C, tblInfo *model.TableInf TableID: tblInfo.ID, Type: model.ActionAddForeignKey, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{fkInfo}, + Args: []any{fkInfo}, } err := s.ctx.NewTxn(context.Background()) c.Assert(err, IsNil) @@ -88,7 +88,7 @@ func testDropForeignKey(c *C, ctx sessionctx.Context, d *ddl, dbInfo *model.DBIn TableID: tblInfo.ID, Type: model.ActionDropForeignKey, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{model.NewCIStr(foreignKeyName)}, + Args: []any{model.NewCIStr(foreignKeyName)}, } err := d.doDDLJob(ctx, job) c.Assert(err, IsNil) diff --git a/ddl/index_change_test.go b/ddl/index_change_test.go index a9d84301c..bbba18887 100644 --- a/ddl/index_change_test.go +++ b/ddl/index_change_test.go @@ -173,7 +173,7 @@ func (s *testIndexChangeSuite) TestIndexChange(c *C) { c.Check(errors.ErrorStack(checkErr), Equals, "") } -func checkIndexExists(ctx sessionctx.Context, tbl table.Table, indexValue interface{}, handle int64, exists bool) error { +func checkIndexExists(ctx sessionctx.Context, tbl table.Table, indexValue any, handle int64, exists bool) error { idx := tbl.Indices()[0] txn, err := ctx.Txn(true) if err != nil { diff --git a/ddl/partition.go b/ddl/partition.go index 8292c3ccb..6712e695d 100644 --- a/ddl/partition.go +++ b/ddl/partition.go @@ -478,7 +478,7 @@ func checkCreatePartitionValue(ctx sessionctx.Context, tblInfo *model.TableInfo) defs = defs[:len(defs)-1] } isUnsignedBigint := isRangePartitionColUnsignedBigint(cols, pi) - var prevRangeValue interface{} + var prevRangeValue any for i := 0; i < len(defs); i++ { if strings.EqualFold(defs[i].LessThan[0], partitionMaxValue) { return errors.Trace(ErrPartitionMaxvalue) @@ -514,7 +514,7 @@ func checkCreatePartitionValue(ctx sessionctx.Context, tblInfo *model.TableInfo) // getRangeValue gets an integer from the range value string. // The returned boolean value indicates whether the input string is a constant expression. -func getRangeValue(ctx sessionctx.Context, tblInfo *model.TableInfo, str string, unsignedBigint bool) (interface{}, bool, error) { +func getRangeValue(ctx sessionctx.Context, tblInfo *model.TableInfo, str string, unsignedBigint bool) (any, bool, error) { // Unsigned bigint was converted to uint64 handle. if unsignedBigint { if value, err := strconv.ParseUint(str, 10, 64); err == nil { @@ -616,7 +616,7 @@ func onDropTablePartition(t *meta.Meta, job *model.Job) (ver int64, _ error) { // Finish this job. job.FinishTableJob(model.JobStateDone, model.StateNone, ver, tblInfo) // A background job will be created to delete old partition data. - job.Args = []interface{}{physicalTableID} + job.Args = []any{physicalTableID} return ver, nil } @@ -677,7 +677,7 @@ func onTruncateTablePartition(d *ddlCtx, t *meta.Meta, job *model.Job) (int64, e job.FinishTableJob(model.JobStateDone, model.StateNone, ver, tblInfo) asyncNotifyEvent(d, &util.Event{Tp: model.ActionTruncateTablePartition, TableInfo: tblInfo, PartInfo: &model.PartitionInfo{Definitions: []model.PartitionDefinition{*newPartition}}}) // A background job will be created to delete old partition data. - job.Args = []interface{}{oldID} + job.Args = []any{oldID} return ver, nil } diff --git a/ddl/reorg_test.go b/ddl/reorg_test.go index 9f84b5e53..f8d4a1a64 100644 --- a/ddl/reorg_test.go +++ b/ddl/reorg_test.go @@ -120,7 +120,7 @@ func (s *testDDLSuite) TestReorg(c *C) { ID: 2, SchemaID: 1, Type: model.ActionCreateSchema, - Args: []interface{}{model.NewCIStr("test")}, + Args: []any{model.NewCIStr("test")}, SnapshotVer: 1, // Make sure it is not zero. So the reorgInfo's first is false. } diff --git a/ddl/rollingback.go b/ddl/rollingback.go index f48449f53..512520669 100644 --- a/ddl/rollingback.go +++ b/ddl/rollingback.go @@ -54,7 +54,7 @@ func convertAddIdxJob2RollbackJob(t *meta.Meta, job *model.Job, tblInfo *model.T } // the second args will be used in onDropIndex. - job.Args = []interface{}{indexInfo.Name, getPartitionIDs(tblInfo)} + job.Args = []any{indexInfo.Name, getPartitionIDs(tblInfo)} // If add index job rollbacks in write reorganization state, its need to delete all keys which has been added. // Its work is the same as drop index job do. // The write reorganization state in add index job that likes write only state in drop index job. @@ -120,7 +120,7 @@ func rollingbackAddColumn(t *meta.Meta, job *model.Job) (ver int64, err error) { columnInfo.State = model.StateDeleteOnly job.SchemaState = model.StateDeleteOnly - job.Args = []interface{}{col.Name} + job.Args = []any{col.Name} ver, err = updateVersionAndTableInfo(t, job, tblInfo, originalState != columnInfo.State) if err != nil { return ver, errors.Trace(err) @@ -148,7 +148,7 @@ func rollingbackAddColumns(t *meta.Meta, job *model.Job) (ver int64, err error) ifExists := make([]bool, len(columnInfos)) job.SchemaState = model.StateDeleteOnly - job.Args = []interface{}{colNames, ifExists} + job.Args = []any{colNames, ifExists} ver, err = updateVersionAndTableInfo(t, job, tblInfo, originalState != columnInfos[0].State) if err != nil { return ver, errors.Trace(err) @@ -213,7 +213,7 @@ func rollingbackDropIndex(t *meta.Meta, job *model.Job) (ver int64, err error) { } job.SchemaState = indexInfo.State - job.Args = []interface{}{indexInfo.Name} + job.Args = []any{indexInfo.Name} ver, err = updateVersionAndTableInfo(t, job, tblInfo, originalState != indexInfo.State) if err != nil { return ver, errors.Trace(err) diff --git a/ddl/schema_test.go b/ddl/schema_test.go index 9cea3ec0b..789dc045e 100644 --- a/ddl/schema_test.go +++ b/ddl/schema_test.go @@ -54,7 +54,7 @@ func testCreateSchema(c *C, ctx sessionctx.Context, d *ddl, dbInfo *model.DBInfo SchemaID: dbInfo.ID, Type: model.ActionCreateSchema, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{dbInfo}, + Args: []any{dbInfo}, } err := d.doDDLJob(ctx, job) c.Assert(err, IsNil) @@ -220,7 +220,7 @@ func (s *testSchemaSuite) TestSchemaWaitJob(c *C) { genIDs, err := d2.genGlobalIDs(1) c.Assert(err, IsNil) schemaID := genIDs[0] - doDDLJobErr(c, schemaID, 0, model.ActionCreateSchema, []interface{}{dbInfo}, ctx, d2) + doDDLJobErr(c, schemaID, 0, model.ActionCreateSchema, []any{dbInfo}, ctx, d2) } func testRunInterruptedJob(c *C, d *ddl, job *model.Job) { @@ -266,7 +266,7 @@ func (s *testSchemaSuite) TestSchemaResume(c *C) { SchemaID: dbInfo.ID, Type: model.ActionCreateSchema, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{dbInfo}, + Args: []any{dbInfo}, } testRunInterruptedJob(c, d1, job) testCheckSchemaState(c, d1, dbInfo, model.StatePublic) diff --git a/ddl/serial_test.go b/ddl/serial_test.go index 03f44135e..ab52e42d4 100644 --- a/ddl/serial_test.go +++ b/ddl/serial_test.go @@ -809,7 +809,7 @@ func (s *testSerialSuite) TestAutoRandom(c *C) { tk.MustExec("use auto_random_db") tk.MustExec("drop table if exists t") - assertInvalidAutoRandomErr := func(sql string, errMsg string, args ...interface{}) { + assertInvalidAutoRandomErr := func(sql string, errMsg string, args ...any) { _, err := tk.Exec(sql) c.Assert(err, NotNil) c.Assert(err.Error(), Equals, ddl.ErrInvalidAutoRandom.GenWithStackByArgs(fmt.Sprintf(errMsg, args...)).Error()) diff --git a/ddl/stat.go b/ddl/stat.go index 7a3bd67f1..c06d58105 100644 --- a/ddl/stat.go +++ b/ddl/stat.go @@ -44,8 +44,8 @@ func (d *ddl) GetScope(status string) variable.ScopeFlag { } // Stats returns the DDL statistics. -func (d *ddl) Stats(vars *variable.SessionVars) (map[string]interface{}, error) { - m := make(map[string]interface{}) +func (d *ddl) Stats(vars *variable.SessionVars) (map[string]any, error) { + m := make(map[string]any) m[serverID] = d.uuid var ddlInfo *admin.DDLInfo diff --git a/ddl/stat_test.go b/ddl/stat_test.go index 0bb6b18b6..11fecf8f3 100644 --- a/ddl/stat_test.go +++ b/ddl/stat_test.go @@ -63,7 +63,7 @@ func (s *testStatSuite) TestStat(c *C) { SchemaID: dbInfo.ID, Type: model.ActionDropSchema, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{dbInfo.Name}, + Args: []any{dbInfo.Name}, } ctx := mock.NewContext() diff --git a/ddl/table.go b/ddl/table.go index 2802aeffa..7a780f20b 100644 --- a/ddl/table.go +++ b/ddl/table.go @@ -485,7 +485,7 @@ func onTruncateTable(d *ddlCtx, t *meta.Meta, job *model.Job) (ver int64, _ erro job.FinishTableJob(model.JobStateDone, model.StatePublic, ver, tblInfo) asyncNotifyEvent(d, &util.Event{Tp: model.ActionTruncateTable, TableInfo: tblInfo}) startKey := tablecodec.EncodeTablePrefix(tableID) - job.Args = []interface{}{startKey, oldPartitionIDs} + job.Args = []any{startKey, oldPartitionIDs} return ver, nil } diff --git a/ddl/table_lock.go b/ddl/table_lock.go index 1b24c9511..9e7aed7db 100644 --- a/ddl/table_lock.go +++ b/ddl/table_lock.go @@ -84,7 +84,7 @@ func onLockTables(t *meta.Meta, job *model.Job) (ver int64, err error) { return ver, errors.Trace(err) } arg.IndexOfLock++ - job.Args = []interface{}{arg} + job.Args = []any{arg} if arg.IndexOfLock == len(arg.LockTables) { // Finish this job. job.FinishTableJob(model.JobStateDone, model.StatePublic, ver, nil) @@ -174,7 +174,7 @@ func unlockTables(t *meta.Meta, job *model.Job, arg *lockTablesArg) (ver int64, if infoschema.ErrDatabaseNotExists.Equal(err) || infoschema.ErrTableNotExists.Equal(err) { // The table maybe has been dropped. just ignore this err and go on. arg.IndexOfUnlock++ - job.Args = []interface{}{arg} + job.Args = []any{arg} return ver, nil } return ver, err @@ -189,7 +189,7 @@ func unlockTables(t *meta.Meta, job *model.Job, arg *lockTablesArg) (ver int64, } arg.IndexOfUnlock++ - job.Args = []interface{}{arg} + job.Args = []any{arg} return ver, nil } diff --git a/ddl/table_test.go b/ddl/table_test.go index fc47a11bf..e4f5fb89b 100644 --- a/ddl/table_test.go +++ b/ddl/table_test.go @@ -131,7 +131,7 @@ func testCreateTable(c *C, ctx sessionctx.Context, d *ddl, dbInfo *model.DBInfo, TableID: tblInfo.ID, Type: model.ActionCreateTable, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{tblInfo}, + Args: []any{tblInfo}, } err := d.doDDLJob(ctx, job) c.Assert(err, IsNil) @@ -149,7 +149,7 @@ func testCreateView(c *C, ctx sessionctx.Context, d *ddl, dbInfo *model.DBInfo, TableID: tblInfo.ID, Type: model.ActionCreateView, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{tblInfo, false, 0}, + Args: []any{tblInfo, false, 0}, } c.Assert(tblInfo.IsView(), IsTrue) @@ -169,7 +169,7 @@ func testRenameTable(c *C, ctx sessionctx.Context, d *ddl, newSchemaID, oldSchem TableID: tblInfo.ID, Type: model.ActionRenameTable, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{oldSchemaID, tblInfo.Name}, + Args: []any{oldSchemaID, tblInfo.Name}, } err := d.doDDLJob(ctx, job) c.Assert(err, IsNil) @@ -194,7 +194,7 @@ func testLockTable(c *C, ctx sessionctx.Context, d *ddl, newSchemaID int64, tblI TableID: tblInfo.ID, Type: model.ActionLockTable, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{arg}, + Args: []any{arg}, } err := d.doDDLJob(ctx, job) c.Assert(err, IsNil) @@ -246,7 +246,7 @@ func testTruncateTable(c *C, ctx sessionctx.Context, d *ddl, dbInfo *model.DBInf TableID: tblInfo.ID, Type: model.ActionTruncateTable, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{newTableID}, + Args: []any{newTableID}, } err = d.doDDLJob(ctx, job) c.Assert(err, IsNil) @@ -336,7 +336,7 @@ func (s *testTableSuite) TestTable(c *C) { // Create an existing table. newTblInfo := testTableInfo(c, d, "t", 3) - doDDLJobErr(c, s.dbInfo.ID, newTblInfo.ID, model.ActionCreateTable, []interface{}{newTblInfo}, ctx, d) + doDDLJobErr(c, s.dbInfo.ID, newTblInfo.ID, model.ActionCreateTable, []any{newTblInfo}, ctx, d) count := 2000 tbl := testGetTable(c, d, s.dbInfo.ID, tblInfo.ID) @@ -381,7 +381,7 @@ func (s *testTableSuite) TestTableResume(c *C) { TableID: tblInfo.ID, Type: model.ActionCreateTable, BinlogInfo: &model.HistoryInfo{}, - Args: []interface{}{tblInfo}, + Args: []any{tblInfo}, } testRunInterruptedJob(c, d, job) testCheckTableState(c, d, s.dbInfo, tblInfo, model.StatePublic) diff --git a/domain/global_vars_cache.go b/domain/global_vars_cache.go index fb9223177..01321c45b 100644 --- a/domain/global_vars_cache.go +++ b/domain/global_vars_cache.go @@ -75,7 +75,7 @@ func (gvc *GlobalVariableCache) LoadGlobalVariables(loadFn func() ([]chunk.Row, if succ { return rows, fields, nil } - fn := func() (interface{}, error) { + fn := func() (any, error) { resRows, resFields, loadErr := loadFn() if loadErr != nil { return nil, loadErr diff --git a/domain/topn_slow_query.go b/domain/topn_slow_query.go index 10f441e44..a02b680bc 100644 --- a/domain/topn_slow_query.go +++ b/domain/topn_slow_query.go @@ -31,11 +31,11 @@ func (h *slowQueryHeap) Len() int { return len(h.data) } func (h *slowQueryHeap) Less(i, j int) bool { return h.data[i].Duration < h.data[j].Duration } func (h *slowQueryHeap) Swap(i, j int) { h.data[i], h.data[j] = h.data[j], h.data[i] } -func (h *slowQueryHeap) Push(x interface{}) { +func (h *slowQueryHeap) Push(x any) { h.data = append(h.data, x.(*SlowQueryInfo)) } -func (h *slowQueryHeap) Pop() interface{} { +func (h *slowQueryHeap) Pop() any { old := h.data n := len(old) x := old[n-1] diff --git a/executor/aggfuncs/aggfunc_test.go b/executor/aggfuncs/aggfunc_test.go index 3a995be8f..1231dc99f 100644 --- a/executor/aggfuncs/aggfunc_test.go +++ b/executor/aggfuncs/aggfunc_test.go @@ -142,11 +142,11 @@ func (s *testSuite) testMergePartialResult(c *C, p aggTest) { c.Assert(result, Equals, 0) } -func buildAggTester(funcName string, tp byte, numRows int, results ...interface{}) aggTest { +func buildAggTester(funcName string, tp byte, numRows int, results ...any) aggTest { return buildAggTesterWithFieldType(funcName, types.NewFieldType(tp), numRows, results...) } -func buildAggTesterWithFieldType(funcName string, ft *types.FieldType, numRows int, results ...interface{}) aggTest { +func buildAggTesterWithFieldType(funcName string, ft *types.FieldType, numRows int, results ...any) aggTest { pt := aggTest{ dataType: ft, numRows: numRows, @@ -226,7 +226,7 @@ func (s *testSuite) testMultiArgsMergePartialResult(c *C, p multiArgsAggTest) { } // for multiple args in aggfuncs such as json_objectagg(c1, c2) -func buildMultiArgsAggTester(funcName string, tps []byte, rt byte, numRows int, results ...interface{}) multiArgsAggTest { +func buildMultiArgsAggTester(funcName string, tps []byte, rt byte, numRows int, results ...any) multiArgsAggTest { fts := make([]*types.FieldType, len(tps)) for i := 0; i < len(tps); i++ { fts[i] = types.NewFieldType(tps[i]) @@ -234,7 +234,7 @@ func buildMultiArgsAggTester(funcName string, tps []byte, rt byte, numRows int, return buildMultiArgsAggTesterWithFieldType(funcName, fts, types.NewFieldType(rt), numRows, results...) } -func buildMultiArgsAggTesterWithFieldType(funcName string, fts []*types.FieldType, rt *types.FieldType, numRows int, results ...interface{}) multiArgsAggTest { +func buildMultiArgsAggTesterWithFieldType(funcName string, fts []*types.FieldType, rt *types.FieldType, numRows int, results ...any) multiArgsAggTest { dataGens := make([]func(i int) types.Datum, len(fts)) for i := 0; i < len(fts); i++ { dataGens[i] = getDataGenFunc(fts[i]) diff --git a/executor/aggfuncs/func_json_objectagg.go b/executor/aggfuncs/func_json_objectagg.go index 48bd1d8e8..724b710f6 100644 --- a/executor/aggfuncs/func_json_objectagg.go +++ b/executor/aggfuncs/func_json_objectagg.go @@ -26,18 +26,18 @@ type jsonObjectAgg struct { } type partialResult4JsonObjectAgg struct { - entries map[string]interface{} + entries map[string]any } func (e *jsonObjectAgg) AllocPartialResult() PartialResult { p := partialResult4JsonObjectAgg{} - p.entries = make(map[string]interface{}) + p.entries = make(map[string]any) return PartialResult(&p) } func (e *jsonObjectAgg) ResetPartialResult(pr PartialResult) { p := (*partialResult4JsonObjectAgg)(pr) - p.entries = make(map[string]interface{}) + p.entries = make(map[string]any) } func (e *jsonObjectAgg) AppendFinalResult2Chunk(sctx sessionctx.Context, pr PartialResult, chk *chunk.Chunk) error { diff --git a/executor/aggfuncs/func_json_objectagg_test.go b/executor/aggfuncs/func_json_objectagg_test.go index 82354a858..3fd1ab8e1 100644 --- a/executor/aggfuncs/func_json_objectagg_test.go +++ b/executor/aggfuncs/func_json_objectagg_test.go @@ -35,8 +35,8 @@ func (s *testSuite) TestMergePartialResult4JsonObjectagg(c *C) { numRows := 5 for k := 0; k < len(argCombines); k++ { - entries1 := make(map[string]interface{}) - entries2 := make(map[string]interface{}) + entries1 := make(map[string]any) + entries2 := make(map[string]any) argTypes := argCombines[k] fGenFunc := getDataGenFunc(types.NewFieldType(argTypes[0])) @@ -80,7 +80,7 @@ func (s *testSuite) TestJsonObjectagg(c *C) { numRows := 5 for k := 0; k < len(argCombines); k++ { - entries := make(map[string]interface{}) + entries := make(map[string]any) argTypes := argCombines[k] fGenFunc := getDataGenFunc(types.NewFieldType(argTypes[0])) diff --git a/executor/aggfuncs/window_func_test.go b/executor/aggfuncs/window_func_test.go index f6d879596..30273e3d9 100644 --- a/executor/aggfuncs/window_func_test.go +++ b/executor/aggfuncs/window_func_test.go @@ -69,7 +69,7 @@ func (s *testSuite) testWindowFunc(c *C, p windowTest) { finalFunc.ResetPartialResult(finalPr) } -func buildWindowTesterWithArgs(funcName string, tp byte, args []expression.Expression, orderByCols int, numRows int, results ...interface{}) windowTest { +func buildWindowTesterWithArgs(funcName string, tp byte, args []expression.Expression, orderByCols int, numRows int, results ...any) windowTest { pt := windowTest{ dataType: types.NewFieldType(tp), numRows: numRows, @@ -89,7 +89,7 @@ func buildWindowTesterWithArgs(funcName string, tp byte, args []expression.Expre return pt } -func buildWindowTester(funcName string, tp byte, constantArg uint64, orderByCols int, numRows int, results ...interface{}) windowTest { +func buildWindowTester(funcName string, tp byte, constantArg uint64, orderByCols int, numRows int, results ...any) windowTest { pt := windowTest{ dataType: types.NewFieldType(tp), numRows: numRows, diff --git a/executor/aggregate.go b/executor/aggregate.go index a5b67eb77..cf3059de1 100644 --- a/executor/aggregate.go +++ b/executor/aggregate.go @@ -102,42 +102,44 @@ type AfFinalResult struct { // and updates all the items in PartialAggFuncs. // The parallel execution flow is as the following graph shows: // -// +-------------+ -// | Main Thread | -// +------+------+ -// ^ -// | -// + -// +-+- +-+ -// | | ...... | | finalOutputCh -// +++- +-+ -// ^ -// | -// +---------------+ -// | | -// +--------------+ +--------------+ -// | final worker | ...... | final worker | -// +------------+-+ +-+------------+ -// ^ ^ -// | | -// +-+ +-+ ...... +-+ -// | | | | | | -// ... ... ... partialOutputChs -// | | | | | | -// +++ +++ +++ -// ^ ^ ^ -// +-+ | | | -// | | +--------o----+ | +// +-------------+ +// | Main Thread | +// +------+------+ +// ^ +// | +// + +// +-+- +-+ +// | | ...... | | finalOutputCh +// +++- +-+ +// ^ +// | +// +---------------+ +// | | +// +--------------+ +--------------+ +// | final worker | ...... | final worker | +// +------------+-+ +-+------------+ +// ^ ^ +// | | +// +-+ +-+ ...... +-+ +// | | | | | | +// ... ... ... partialOutputChs +// | | | | | | +// +++ +++ +++ +// ^ ^ ^ +// +-+ | | | +// | | +--------o----+ | +// // inputCh +-+ | +-----------------+---+ -// | | | | -// ... +---+------------+ +----+-----------+ -// | | | partial worker | ...... | partial worker | -// +++ +--------------+-+ +-+--------------+ -// | ^ ^ -// | | | -// +----v---------+ +++ +-+ +++ -// | data fetcher | +------> | | | | ...... | | partialInputChs -// +--------------+ +-+ +-+ +-+ +// +// | | | | +// ... +---+------------+ +----+-----------+ +// | | | partial worker | ...... | partial worker | +// +++ +--------------+-+ +-+--------------+ +// | ^ ^ +// | | | +// +----v---------+ +++ +-+ +++ +// | data fetcher | +------> | | | | ...... | | partialInputChs +// +--------------+ +-+ +-+ +-+ type HashAggExec struct { baseExecutor @@ -355,7 +357,7 @@ func (w *HashAggPartialWorker) getChildInput() bool { return true } -func recoveryHashAgg(output chan *AfFinalResult, r interface{}) { +func recoveryHashAgg(output chan *AfFinalResult, r any) { err := errors.Errorf("%v", r) output <- &AfFinalResult{err: errors.Errorf("%v", r)} logutil.BgLogger().Error("parallel hash aggregation panicked", zap.Error(err), zap.Stack("stack")) diff --git a/executor/benchmark_test.go b/executor/benchmark_test.go index 433203125..4c3ec8c8d 100644 --- a/executor/benchmark_test.go +++ b/executor/benchmark_test.go @@ -49,7 +49,7 @@ var ( type mockDataSourceParameters struct { schema *expression.Schema - genDataFunc func(row int, typ *types.FieldType) interface{} + genDataFunc func(row int, typ *types.FieldType) any ndvs []int // number of distinct values on columns[i] and zero represents no limit orders []bool // columns[i] should be ordered if orders[i] is true rows int // number of rows the DataSource should output @@ -92,7 +92,7 @@ func (mp *mockDataPhysicalPlan) SelectBlockOffset() int { return 0 } -func (mds *mockDataSource) genColDatums(col int) (results []interface{}) { +func (mds *mockDataSource) genColDatums(col int) (results []any) { typ := mds.retFieldTypes[col] order := false if col < len(mds.p.orders) { @@ -103,7 +103,7 @@ func (mds *mockDataSource) genColDatums(col int) (results []interface{}) { if col < len(mds.p.ndvs) { NDV = mds.p.ndvs[col] } - results = make([]interface{}, 0, rows) + results = make([]any, 0, rows) if NDV == 0 { if mds.p.genDataFunc == nil { for i := 0; i < rows; i++ { @@ -116,7 +116,7 @@ func (mds *mockDataSource) genColDatums(col int) (results []interface{}) { } } else { datumSet := make(map[string]bool, NDV) - datums := make([]interface{}, 0, NDV) + datums := make([]any, 0, NDV) for len(datums) < NDV { d := mds.randDatum(typ) str := fmt.Sprintf("%v", d) @@ -150,7 +150,7 @@ func (mds *mockDataSource) genColDatums(col int) (results []interface{}) { return } -func (mds *mockDataSource) randDatum(typ *types.FieldType) interface{} { +func (mds *mockDataSource) randDatum(typ *types.FieldType) any { switch typ.Tp { case mysql.TypeLong, mysql.TypeLonglong: return int64(rand.Int()) @@ -191,7 +191,7 @@ func buildMockDataSource(opt mockDataSourceParameters) *mockDataSource { baseExec := newBaseExecutor(opt.ctx, opt.schema, nil) m := &mockDataSource{baseExec, opt, nil, nil, 0} rTypes := retTypes(m) - colData := make([][]interface{}, len(rTypes)) + colData := make([][]any, len(rTypes)) for i := 0; i < len(rTypes); i++ { colData[i] = m.genColDatums(i) } @@ -819,7 +819,7 @@ func benchmarkHashJoinExecWithCase(b *testing.B, casTest *hashJoinTestCase) { opt1 := mockDataSourceParameters{ rows: casTest.rows, ctx: casTest.ctx, - genDataFunc: func(row int, typ *types.FieldType) interface{} { + genDataFunc: func(row int, typ *types.FieldType) any { switch typ.Tp { case mysql.TypeLong, mysql.TypeLonglong: return int64(row) @@ -1011,7 +1011,7 @@ func benchmarkBuildHashTableForList(b *testing.B, casTest *hashJoinTestCase) { schema: expression.NewSchema(casTest.columns()...), rows: casTest.rows, ctx: casTest.ctx, - genDataFunc: func(row int, typ *types.FieldType) interface{} { + genDataFunc: func(row int, typ *types.FieldType) any { switch typ.Tp { case mysql.TypeLong, mysql.TypeLonglong: return int64(row) @@ -1135,7 +1135,7 @@ func (tc indexJoinTestCase) getMockDataSourceOptByRows(rows int) mockDataSourceP schema: expression.NewSchema(tc.columns()...), rows: rows, ctx: tc.ctx, - genDataFunc: func(row int, typ *types.FieldType) interface{} { + genDataFunc: func(row int, typ *types.FieldType) any { switch typ.Tp { case mysql.TypeLong, mysql.TypeLonglong: return int64(row) @@ -1444,7 +1444,7 @@ func newMergeJoinBenchmark(numOuterRows, numInnerDup, numInnerRedundant int) (tc schema: expression.NewSchema(tc.columns()...), rows: numOuterRows, ctx: tc.ctx, - genDataFunc: func(row int, typ *types.FieldType) interface{} { + genDataFunc: func(row int, typ *types.FieldType) any { switch typ.Tp { case mysql.TypeLong, mysql.TypeLonglong: return int64(row) @@ -1462,7 +1462,7 @@ func newMergeJoinBenchmark(numOuterRows, numInnerDup, numInnerRedundant int) (tc schema: expression.NewSchema(tc.columns()...), rows: numInnerRows, ctx: tc.ctx, - genDataFunc: func(row int, typ *types.FieldType) interface{} { + genDataFunc: func(row int, typ *types.FieldType) any { row = row / numInnerDup switch typ.Tp { case mysql.TypeLong, mysql.TypeLonglong: diff --git a/executor/brie.go b/executor/brie.go index c23b018e1..12a44e6bb 100644 --- a/executor/brie.go +++ b/executor/brie.go @@ -369,7 +369,7 @@ func handleBRIEError(err error, terror *terror.Error) error { } func (e *ShowExec) fetchShowBRIE(kind ast.BRIEKind) error { - globalBRIEQueue.tasks.Range(func(key, value interface{}) bool { + globalBRIEQueue.tasks.Range(func(key, value any) bool { item := value.(*brieQueueItem) if item.info.kind == kind { item.progress.lock.Lock() diff --git a/executor/chunk_size_control_test.go b/executor/chunk_size_control_test.go index 2fbfeea07..44cc386a6 100644 --- a/executor/chunk_size_control_test.go +++ b/executor/chunk_size_control_test.go @@ -226,7 +226,7 @@ func (s *testChunkSizeControlSuite) TestLimitAndIndexScan(c *C) { c.Assert(cost, Not(Less), delayThreshold) // have to wait } -func (s *testChunkSizeControlSuite) parseTimeCost(c *C, line []interface{}) time.Duration { +func (s *testChunkSizeControlSuite) parseTimeCost(c *C, line []any) time.Duration { lineStr := fmt.Sprintf("%v", line) idx := strings.Index(lineStr, "time:") c.Assert(idx, Not(Equals), -1) diff --git a/executor/delete.go b/executor/delete.go index e1b736a65..a6f06b9f4 100644 --- a/executor/delete.go +++ b/executor/delete.go @@ -163,7 +163,7 @@ func (e *DeleteExec) deleteMultiTablesByChunk(ctx context.Context) error { func (e *DeleteExec) removeRowsInTblRowMap(tblRowMap tableRowMapType) error { for id, rowMap := range tblRowMap { var err error - rowMap.Range(func(h kv.Handle, val interface{}) bool { + rowMap.Range(func(h kv.Handle, val any) bool { err = e.removeRow(e.ctx, e.tblID2Table[id], h, val.([]types.Datum)) if err != nil { return false diff --git a/executor/distsql.go b/executor/distsql.go index faff88d0e..b380f2134 100644 --- a/executor/distsql.go +++ b/executor/distsql.go @@ -837,7 +837,7 @@ func (w *tableWorker) compareData(ctx context.Context, task *lookupTableTask, ta return errors.Trace(err) } if chk.NumRows() == 0 { - task.indexOrder.Range(func(h kv.Handle, val interface{}) bool { + task.indexOrder.Range(func(h kv.Handle, val any) bool { idxRow := task.idxRows.GetRow(val.(int)) err = errors.Errorf("handle %#v, index:%#v != record:%#v", h, idxRow.GetDatum(0, w.idxColTps[0]), nil) return false diff --git a/executor/executor.go b/executor/executor.go index b196f55a6..7fc1e76d2 100644 --- a/executor/executor.go +++ b/executor/executor.go @@ -686,7 +686,7 @@ func (e *CheckTableExec) checkIndexHandle(ctx context.Context, src *IndexLookUpE return errors.Trace(err) } -func (e *CheckTableExec) handlePanic(r interface{}) { +func (e *CheckTableExec) handlePanic(r any) { if r != nil { e.retCh <- errors.Errorf("%v", r) } @@ -828,6 +828,7 @@ func (e *CheckIndexExec) Next(ctx context.Context, req *chunk.Chunk) error { // ShowSlowExec represents the executor of showing the slow queries. // It is build from the "admin show slow" statement: +// // admin show slow top [internal | all] N // admin show slow recent N type ShowSlowExec struct { @@ -1423,21 +1424,22 @@ func (e *MaxOneRowExec) Next(ctx context.Context, req *chunk.Chunk) error { // UnionExec pulls all it's children's result and returns to its parent directly. // A "resultPuller" is started for every child to pull result from that child and push it to the "resultPool", the used // "Chunk" is obtained from the corresponding "resourcePool". All resultPullers are running concurrently. -// +----------------+ -// +---> resourcePool 1 ---> | resultPuller 1 |-----+ -// | +----------------+ | -// | | -// | +----------------+ v -// +---> resourcePool 2 ---> | resultPuller 2 |-----> resultPool ---+ -// | +----------------+ ^ | -// | ...... | | -// | +----------------+ | | -// +---> resourcePool n ---> | resultPuller n |-----+ | -// | +----------------+ | -// | | -// | +-------------+ | -// |--------------------------| main thread | <---------------------+ -// +-------------+ +// +// +----------------+ +// +---> resourcePool 1 ---> | resultPuller 1 |-----+ +// | +----------------+ | +// | | +// | +----------------+ v +// +---> resourcePool 2 ---> | resultPuller 2 |-----> resultPool ---+ +// | +----------------+ ^ | +// | ...... | | +// | +----------------+ | | +// +---> resourcePool n ---> | resultPuller n |-----+ | +// | +----------------+ | +// | | +// | +-------------+ | +// |--------------------------| main thread | <---------------------+ +// +-------------+ type UnionExec struct { baseExecutor diff --git a/executor/executor_required_rows_test.go b/executor/executor_required_rows_test.go index 470919229..ad95c6ab0 100644 --- a/executor/executor_required_rows_test.go +++ b/executor/executor_required_rows_test.go @@ -46,11 +46,11 @@ type requiredRowsDataSource struct { expectedRowsRet []int numNextCalled int - generator func(valType *types.FieldType) interface{} + generator func(valType *types.FieldType) any } func newRequiredRowsDataSourceWithGenerator(ctx sessionctx.Context, totalRows int, expectedRowsRet []int, - gen func(valType *types.FieldType) interface{}) *requiredRowsDataSource { + gen func(valType *types.FieldType) any) *requiredRowsDataSource { ds := newRequiredRowsDataSource(ctx, totalRows, expectedRowsRet) ds.generator = gen return ds @@ -102,7 +102,7 @@ func (r *requiredRowsDataSource) genOneRow() chunk.Row { return row.ToRow() } -func defaultGenerator(valType *types.FieldType) interface{} { +func defaultGenerator(valType *types.FieldType) any { switch valType.Tp { case mysql.TypeLong, mysql.TypeLonglong: return int64(rand.Int()) @@ -393,9 +393,9 @@ func buildTopNExec(ctx sessionctx.Context, offset, count int, byItems []*planner } func (s *testExecSuite) TestSelectionRequiredRows(c *C) { - gen01 := func() func(valType *types.FieldType) interface{} { + gen01 := func() func(valType *types.FieldType) any { closureCount := 0 - return func(valType *types.FieldType) interface{} { + return func(valType *types.FieldType) any { switch valType.Tp { case mysql.TypeLong, mysql.TypeLonglong: ret := int64(closureCount % 2) @@ -416,7 +416,7 @@ func (s *testExecSuite) TestSelectionRequiredRows(c *C) { requiredRows []int expectedRows []int expectedRowsDS []int - gen func(valType *types.FieldType) interface{} + gen func(valType *types.FieldType) any }{ { totalRows: 20, @@ -599,10 +599,10 @@ func buildProjectionExec(ctx sessionctx.Context, exprs []expression.Expression, } } -func divGenerator(factor int) func(valType *types.FieldType) interface{} { +func divGenerator(factor int) func(valType *types.FieldType) any { closureCountInt := 0 closureCountDouble := 0 - return func(valType *types.FieldType) interface{} { + return func(valType *types.FieldType) any { switch valType.Tp { case mysql.TypeLong, mysql.TypeLonglong: ret := int64(closureCountInt / factor) @@ -626,7 +626,7 @@ func (s *testExecSuite) TestStreamAggRequiredRows(c *C) { requiredRows []int expectedRows []int expectedRowsDS []int - gen func(valType *types.FieldType) interface{} + gen func(valType *types.FieldType) any }{ { totalRows: 1000000, @@ -678,7 +678,7 @@ func (s *testExecSuite) TestStreamAggRequiredRows(c *C) { } func (s *testExecSuite) TestMergeJoinRequiredRows(c *C) { - justReturn1 := func(valType *types.FieldType) interface{} { + justReturn1 := func(valType *types.FieldType) any { switch valType.Tp { case mysql.TypeLong, mysql.TypeLonglong: return int64(1) diff --git a/executor/executor_test.go b/executor/executor_test.go index 017ec4bd8..0d5a0958a 100644 --- a/executor/executor_test.go +++ b/executor/executor_test.go @@ -1386,7 +1386,7 @@ func (s *testSuiteP1) TestTablePKisHandleScan(c *C) { tests := []struct { sql string - result [][]interface{} + result [][]any }{ { "select * from t", @@ -3548,7 +3548,7 @@ func (s *testSuite3) TestForSelectScopeInUnion(c *C) { func (s *testSuite3) TestUnsignedDecimalOverflow(c *C) { tests := []struct { - input interface{} + input any hasErr bool err string }{{ diff --git a/executor/index_lookup_hash_join.go b/executor/index_lookup_hash_join.go index f3dbf8560..cf69f9174 100644 --- a/executor/index_lookup_hash_join.go +++ b/executor/index_lookup_hash_join.go @@ -34,11 +34,11 @@ import ( // numResChkHold indicates the number of resource chunks that an inner worker // holds at the same time. // It's used in 2 cases individually: -// 1. IndexMergeJoin -// 2. IndexNestedLoopHashJoin: -// It's used when IndexNestedLoopHashJoin.keepOuterOrder is true. -// Otherwise, there will be at most `concurrency` resource chunks throughout -// the execution of IndexNestedLoopHashJoin. +// 1. IndexMergeJoin +// 2. IndexNestedLoopHashJoin: +// It's used when IndexNestedLoopHashJoin.keepOuterOrder is true. +// Otherwise, there will be at most `concurrency` resource chunks throughout +// the execution of IndexNestedLoopHashJoin. const numResChkHold = 4 // IndexNestedLoopHashJoin employs one outer worker and N inner workers to @@ -48,10 +48,11 @@ const numResChkHold = 4 // 1. The outer worker reads N outer rows, builds a task and sends it to the // inner worker channel. // 2. The inner worker receives the tasks and does 3 things for every task: -// 1. builds hash table from the outer rows -// 2. builds key ranges from outer rows and fetches inner rows -// 3. probes the hash table and sends the join result to the main thread channel. -// Note: step 1 and step 2 runs concurrently. +// 1. builds hash table from the outer rows +// 2. builds key ranges from outer rows and fetches inner rows +// 3. probes the hash table and sends the join result to the main thread channel. +// Note: step 1 and step 2 runs concurrently. +// // 3. The main thread receives the join results. type IndexNestedLoopHashJoin struct { IndexLookUpJoin @@ -186,7 +187,7 @@ func (e *IndexNestedLoopHashJoin) startWorkers(ctx context.Context) { go e.wait4JoinWorkers() } -func (e *IndexNestedLoopHashJoin) finishJoinWorkers(r interface{}) { +func (e *IndexNestedLoopHashJoin) finishJoinWorkers(r any) { if r != nil { logutil.BgLogger().Error("IndexNestedLoopHashJoin failed", zap.Error(errors.Errorf("%v", r))) if e.cancelFunc != nil { @@ -531,7 +532,7 @@ func (iw *indexHashJoinInnerWorker) fetchInnerResults(ctx context.Context, task return iw.innerWorker.fetchInnerResults(ctx, task, lookUpContents) } -func (iw *indexHashJoinInnerWorker) handleHashJoinInnerWorkerPanic(r interface{}) { +func (iw *indexHashJoinInnerWorker) handleHashJoinInnerWorkerPanic(r any) { if r != nil { iw.resultCh <- &indexHashJoinResult{err: errors.Errorf("%v", r)} } @@ -670,11 +671,11 @@ func (iw *indexHashJoinInnerWorker) collectMatchedInnerPtrs4OuterRows(ctx contex } // doJoinInOrder follows the following steps: -// 1. collect all the matched inner row ptrs for every outer row -// 2. do the join work -// 2.1 collect all the matched inner rows using the collected ptrs for every outer row -// 2.2 call tryToMatchInners for every outer row -// 2.3 call onMissMatch when no inner rows are matched +// 1. collect all the matched inner row ptrs for every outer row +// 2. do the join work +// 2.1 collect all the matched inner rows using the collected ptrs for every outer row +// 2.2 call tryToMatchInners for every outer row +// 2.3 call onMissMatch when no inner rows are matched func (iw *indexHashJoinInnerWorker) doJoinInOrder(ctx context.Context, task *indexHashJoinTask, joinResult *indexHashJoinResult, h hash.Hash64, resultCh chan *indexHashJoinResult) (err error) { defer func() { if err == nil && joinResult.chk != nil { diff --git a/executor/index_merge_reader.go b/executor/index_merge_reader.go index 9a019b6e5..d6a2c10f4 100644 --- a/executor/index_merge_reader.go +++ b/executor/index_merge_reader.go @@ -54,13 +54,13 @@ var ( // // The execution flow is really like IndexLookUpReader. However, it uses multiple index scans // or table scans to get the handles: -// 1. use the partialTableWorkers and partialIndexWorkers to fetch the handles (a batch per time) -// and send them to the indexMergeProcessWorker. -// 2. indexMergeProcessWorker do the `Union` operation for a batch of handles it have got. -// For every handle in the batch: -// 1. check whether it has been accessed. -// 2. if not, record it and send it to the indexMergeTableScanWorker. -// 3. if accessed, just ignore it. +// 1. use the partialTableWorkers and partialIndexWorkers to fetch the handles (a batch per time) +// and send them to the indexMergeProcessWorker. +// 2. indexMergeProcessWorker do the `Union` operation for a batch of handles it have got. +// For every handle in the batch: +// 1. check whether it has been accessed. +// 2. if not, record it and send it to the indexMergeTableScanWorker. +// 3. if accessed, just ignore it. type IndexMergeReaderExecutor struct { baseExecutor @@ -471,8 +471,8 @@ func (e *IndexMergeReaderExecutor) getResultTask() (*lookupTableTask, error) { return e.resultCurr, nil } -func (e *IndexMergeReaderExecutor) handleHandlesFetcherPanic(ctx context.Context, resultCh chan<- *lookupTableTask, worker string) func(r interface{}) { - return func(r interface{}) { +func (e *IndexMergeReaderExecutor) handleHandlesFetcherPanic(ctx context.Context, resultCh chan<- *lookupTableTask, worker string) func(r any) { + return func(r any) { if r == nil { return } @@ -540,8 +540,8 @@ func (w *indexMergeProcessWorker) fetchLoop(ctx context.Context, fetchCh <-chan } } -func (w *indexMergeProcessWorker) handleLoopFetcherPanic(ctx context.Context, resultCh chan<- *lookupTableTask) func(r interface{}) { - return func(r interface{}) { +func (w *indexMergeProcessWorker) handleLoopFetcherPanic(ctx context.Context, resultCh chan<- *lookupTableTask) func(r any) { + return func(r any) { if r == nil { return } @@ -652,8 +652,8 @@ func (w *indexMergeTableScanWorker) pickAndExecTask(ctx context.Context) (task * } } -func (w *indexMergeTableScanWorker) handlePickAndExecTaskPanic(ctx context.Context, task *lookupTableTask) func(r interface{}) { - return func(r interface{}) { +func (w *indexMergeTableScanWorker) handlePickAndExecTaskPanic(ctx context.Context, task *lookupTableTask) func(r any) { + return func(r any) { if r == nil { return } diff --git a/executor/infoschema_reader.go b/executor/infoschema_reader.go index 04fe642f0..71d53cc32 100644 --- a/executor/infoschema_reader.go +++ b/executor/infoschema_reader.go @@ -445,7 +445,7 @@ func (e *memtableRetriever) setDataFromTables(ctx sessionctx.Context, schemas [] if table.GetPartitionInfo() != nil { createOptions = "partitioned" } - var autoIncID interface{} + var autoIncID any hasAutoIncID, _ := infoschema.HasAutoIncrementColumn(table) if hasAutoIncID { autoIncID, err = getAutoIncrementID(ctx, schema, table) @@ -561,7 +561,7 @@ func (e *memtableRetriever) dataForColumnsInTable(schema *model.DBInfo, tbl *mod if col.Hidden { continue } - var charMaxLen, charOctLen, numericPrecision, numericScale, datetimePrecision interface{} + var charMaxLen, charOctLen, numericPrecision, numericScale, datetimePrecision any colLen, decimal := col.Flen, col.Decimal defaultFlen, defaultDecimal := mysql.GetDefaultFieldLengthAndDecimal(col.Tp) if decimal == types.UnspecifiedLength { @@ -610,7 +610,7 @@ func (e *memtableRetriever) dataForColumnsInTable(schema *model.DBInfo, tbl *mod } columnType := col.FieldType.InfoSchemaStr() columnDesc := table.NewColDesc(table.ToColumn(col)) - var columnDefault interface{} + var columnDefault any if columnDesc.DefaultValue != nil { columnDefault = fmt.Sprintf("%v", columnDesc.DefaultValue) } @@ -784,7 +784,7 @@ func (e *memtableRetriever) setDataFromIndexes(ctx sessionctx.Context, schemas [ if idxInfo.Unique { nonUniq = 0 } - var subPart interface{} + var subPart any if col.Length != types.UnspecifiedLength { subPart = col.Length } @@ -1452,7 +1452,7 @@ func dataForAnalyzeStatusHelper(sctx sessionctx.Context) (rows [][]types.Datum) checker := privilege.GetPrivilegeManager(sctx) for _, job := range statistics.GetAllAnalyzeJobs() { job.Lock() - var startTime interface{} + var startTime any if job.StartTime.IsZero() { startTime = nil } else { diff --git a/executor/infoschema_reader_test.go b/executor/infoschema_reader_test.go index 51eb2e165..c2324e210 100644 --- a/executor/infoschema_reader_test.go +++ b/executor/infoschema_reader_test.go @@ -172,7 +172,7 @@ func (s *testInfoschemaTableSuite) TestSchemataTables(c *C) { }, nil, nil), IsTrue) schemataTester.MustQuery("select count(*) from information_schema.SCHEMATA;").Check(testkit.Rows("1")) schemataTester.MustQuery("select * from information_schema.SCHEMATA where schema_name='mysql';").Check( - [][]interface{}{}) + [][]any{}) schemataTester.MustQuery("select * from information_schema.SCHEMATA where schema_name='INFORMATION_SCHEMA';").Check( testkit.Rows("def INFORMATION_SCHEMA utf8mb4 utf8mb4_bin ")) @@ -261,7 +261,7 @@ func (s *testInfoschemaTableSuite) TestDDLJobs(c *C) { // Test the privilege of user for information_schema.ddl_jobs. DDLJobsTester.MustQuery("select DB_NAME, TABLE_NAME from information_schema.DDL_JOBS where DB_NAME = 'test_ddl_jobs' and TABLE_NAME = 't';").Check( - [][]interface{}{}) + [][]any{}) tk.MustExec("CREATE ROLE r_priv;") tk.MustExec("GRANT ALL PRIVILEGES ON test_ddl_jobs.* TO r_priv;") tk.MustExec("GRANT r_priv TO DDL_JOBS_tester;") @@ -284,7 +284,7 @@ func (s *testInfoschemaTableSuite) TestKeyColumnUsage(c *C) { Username: "key_column_tester", Hostname: "127.0.0.1", }, nil, nil), IsTrue) - keyColumnTester.MustQuery("select * from information_schema.KEY_COLUMN_USAGE;").Check([][]interface{}{}) + keyColumnTester.MustQuery("select * from information_schema.KEY_COLUMN_USAGE;").Check([][]any{}) //test the privilege of user with privilege of mysql.gc_delete_range for information_schema.table_constraints tk.MustExec("CREATE ROLE r_stats_meta ;") @@ -304,7 +304,7 @@ func (s *testInfoschemaTableSuite) TestUserPrivileges(c *C) { Username: "constraints_tester", Hostname: "127.0.0.1", }, nil, nil), IsTrue) - constraintsTester.MustQuery("select * from information_schema.TABLE_CONSTRAINTS;").Check([][]interface{}{}) + constraintsTester.MustQuery("select * from information_schema.TABLE_CONSTRAINTS;").Check([][]any{}) //test the privilege of user with privilege of mysql.gc_delete_range for information_schema.table_constraints tk.MustExec("CREATE ROLE r_gc_delete_range ;") @@ -312,7 +312,7 @@ func (s *testInfoschemaTableSuite) TestUserPrivileges(c *C) { tk.MustExec("GRANT r_gc_delete_range TO constraints_tester;") constraintsTester.MustExec("set role r_gc_delete_range") c.Assert(len(constraintsTester.MustQuery("select * from information_schema.TABLE_CONSTRAINTS where TABLE_NAME='gc_delete_range';").Rows()), Greater, 0) - constraintsTester.MustQuery("select * from information_schema.TABLE_CONSTRAINTS where TABLE_NAME='tables_priv';").Check([][]interface{}{}) + constraintsTester.MustQuery("select * from information_schema.TABLE_CONSTRAINTS where TABLE_NAME='tables_priv';").Check([][]any{}) //test the privilege of new user for information_schema tk.MustExec("create user tester1") @@ -322,7 +322,7 @@ func (s *testInfoschemaTableSuite) TestUserPrivileges(c *C) { Username: "tester1", Hostname: "127.0.0.1", }, nil, nil), IsTrue) - tk1.MustQuery("select * from information_schema.STATISTICS;").Check([][]interface{}{}) + tk1.MustQuery("select * from information_schema.STATISTICS;").Check([][]any{}) //test the privilege of user with some privilege for information_schema tk.MustExec("create user tester2") @@ -339,7 +339,7 @@ func (s *testInfoschemaTableSuite) TestUserPrivileges(c *C) { result := tk2.MustQuery("select * from information_schema.STATISTICS where TABLE_NAME='columns_priv' and COLUMN_NAME='Host';") c.Assert(len(result.Rows()), Greater, 0) tk2.MustQuery("select * from information_schema.STATISTICS where TABLE_NAME='tables_priv' and COLUMN_NAME='Host';").Check( - [][]interface{}{}) + [][]any{}) //test the privilege of user with all privilege for information_schema tk.MustExec("create user tester3") @@ -487,7 +487,7 @@ func (s *testInfoschemaTableSuite) TestForAnalyzeStatus(c *C) { tk.MustExec("create table analyze_test (a int, b int, index idx(a))") tk.MustExec("insert into analyze_test values (1,2),(3,4)") - tk.MustQuery("select distinct TABLE_NAME from information_schema.analyze_status where TABLE_NAME='analyze_test'").Check([][]interface{}{}) + tk.MustQuery("select distinct TABLE_NAME from information_schema.analyze_status where TABLE_NAME='analyze_test'").Check([][]any{}) tk.MustExec("analyze table analyze_test") tk.MustQuery("select distinct TABLE_NAME from information_schema.analyze_status where TABLE_NAME='analyze_test'").Check(testkit.Rows("analyze_test")) @@ -499,8 +499,8 @@ func (s *testInfoschemaTableSuite) TestForAnalyzeStatus(c *C) { Username: "analyze_tester", Hostname: "127.0.0.1", }, nil, nil), IsTrue) - analyzeTester.MustQuery("show analyze status").Check([][]interface{}{}) - analyzeTester.MustQuery("select * from information_schema.ANALYZE_STATUS;").Check([][]interface{}{}) + analyzeTester.MustQuery("show analyze status").Check([][]any{}) + analyzeTester.MustQuery("select * from information_schema.ANALYZE_STATUS;").Check([][]any{}) //test the privilege of user with privilege of test.t1 for information_schema.analyze_status tk.MustExec("create table t1 (a int, b int, index idx(a))") @@ -617,7 +617,7 @@ func (s *testInfoschemaClusterTableSuite) setUpMockPDHTTPServer() (*httptest.Ser })) // mock PD API router.Handle(pdapi.ClusterVersion, fn.Wrap(func() (string, error) { return "4.0.0-alpha", nil })) - router.Handle(pdapi.Status, fn.Wrap(func() (interface{}, error) { + router.Handle(pdapi.Status, fn.Wrap(func() (any, error) { return struct { GitHash string `json:"git_hash"` StartTimestamp int64 `json:"start_timestamp"` @@ -626,14 +626,14 @@ func (s *testInfoschemaClusterTableSuite) setUpMockPDHTTPServer() (*httptest.Ser StartTimestamp: s.startTime.Unix(), }, nil })) - var mockConfig = func() (map[string]interface{}, error) { - configuration := map[string]interface{}{ + var mockConfig = func() (map[string]any, error) { + configuration := map[string]any{ "key1": "value1", "key2": map[string]string{ "nest1": "n-value1", "nest2": "n-value2", }, - "key3": map[string]interface{}{ + "key3": map[string]any{ "nest1": "n-value1", "nest2": "n-value2", "key4": map[string]string{ diff --git a/executor/insert_test.go b/executor/insert_test.go index d6e912f95..983efe0af 100644 --- a/executor/insert_test.go +++ b/executor/insert_test.go @@ -368,7 +368,7 @@ func (s *testSuite3) TestInsertWithAutoidSchema(c *C) { tests := []struct { insert string query string - result [][]interface{} + result [][]any }{ { `insert into t1(id, n) values(1, 1)`, diff --git a/executor/inspection_summary.go b/executor/inspection_summary.go index 78742b73f..b651b3c24 100644 --- a/executor/inspection_summary.go +++ b/executor/inspection_summary.go @@ -481,7 +481,7 @@ func (e *inspectionSummaryRetriever) retrieve(ctx context.Context, sctx sessionc } labels = append(labels, val) } - var quantile interface{} + var quantile any if def.Quantile > 0 { quantile = row.GetFloat64(row.Len() - 1) // quantile will be the last column } diff --git a/executor/join.go b/executor/join.go index fb94c34b8..b20cc08d4 100644 --- a/executor/join.go +++ b/executor/join.go @@ -327,7 +327,7 @@ func (e *HashJoinExec) fetchAndProbeHashTable(ctx context.Context) { go util.WithRecovery(e.waitJoinWorkersAndCloseResultChan, nil) } -func (e *HashJoinExec) handleProbeSideFetcherPanic(r interface{}) { +func (e *HashJoinExec) handleProbeSideFetcherPanic(r any) { for i := range e.probeResultChs { close(e.probeResultChs[i]) } @@ -337,7 +337,7 @@ func (e *HashJoinExec) handleProbeSideFetcherPanic(r interface{}) { e.joinWorkerWaitGroup.Done() } -func (e *HashJoinExec) handleJoinWorkerPanic(r interface{}) { +func (e *HashJoinExec) handleJoinWorkerPanic(r any) { if r != nil { e.joinResultCh <- &hashjoinWorkerResult{err: errors.Errorf("%v", r)} } @@ -661,7 +661,7 @@ func (e *HashJoinExec) Next(ctx context.Context, req *chunk.Chunk) (err error) { return nil } -func (e *HashJoinExec) handleFetchAndBuildHashTablePanic(r interface{}) { +func (e *HashJoinExec) handleFetchAndBuildHashTablePanic(r any) { if r != nil { e.buildFinished <- errors.Errorf("%v", r) } @@ -675,7 +675,7 @@ func (e *HashJoinExec) fetchAndBuildHashTable(ctx context.Context) { fetchBuildSideRowsOk := make(chan error, 1) go util.WithRecovery( func() { e.fetchBuildSideRows(ctx, buildSideResultCh, doneCh) }, - func(r interface{}) { + func(r any) { if r != nil { fetchBuildSideRowsOk <- errors.Errorf("%v", r) } diff --git a/executor/join_pkg_test.go b/executor/join_pkg_test.go index 8086f6438..66412da9f 100644 --- a/executor/join_pkg_test.go +++ b/executor/join_pkg_test.go @@ -33,7 +33,7 @@ func (s *pkgTestSuite) TestJoinExec(c *C) { opt1 := mockDataSourceParameters{ rows: casTest.rows, ctx: casTest.ctx, - genDataFunc: func(row int, typ *types.FieldType) interface{} { + genDataFunc: func(row int, typ *types.FieldType) any { switch typ.Tp { case mysql.TypeLong, mysql.TypeLonglong: return int64(row) diff --git a/executor/join_test.go b/executor/join_test.go index 8a7a13cea..a4fe71b77 100644 --- a/executor/join_test.go +++ b/executor/join_test.go @@ -99,7 +99,7 @@ func (s *testSuiteJoin2) TestJoin(c *C) { tk.MustExec("insert t values (1)") tests := []struct { sql string - result [][]interface{} + result [][]any }{ { "select 1 from t as a left join t as b on 0", @@ -1533,7 +1533,7 @@ func (s *testSuiteJoin2) TestNullEmptyAwareSemiJoin(c *C) { }, } results := []struct { - result [][]interface{} + result [][]any }{ { testkit.Rows(), @@ -1584,7 +1584,7 @@ func (s *testSuiteJoin2) TestNullEmptyAwareSemiJoin(c *C) { tk.MustExec("truncate table t") tk.MustExec("insert into t values(1, null, 0), (2, 1, 0)") results = []struct { - result [][]interface{} + result [][]any }{ { testkit.Rows(), @@ -1628,7 +1628,7 @@ func (s *testSuiteJoin2) TestNullEmptyAwareSemiJoin(c *C) { tk.MustExec("truncate table t") tk.MustExec("insert into t values(1, null, 0), (2, 1, 0), (null, 2, 0)") results = []struct { - result [][]interface{} + result [][]any }{ { testkit.Rows(), @@ -1679,7 +1679,7 @@ func (s *testSuiteJoin2) TestNullEmptyAwareSemiJoin(c *C) { }, } results = []struct { - result [][]interface{} + result [][]any }{ { testkit.Rows(), @@ -1712,7 +1712,7 @@ func (s *testSuiteJoin2) TestNullEmptyAwareSemiJoin(c *C) { }, } results = []struct { - result [][]interface{} + result [][]any }{ { testkit.Rows( @@ -1771,7 +1771,7 @@ func (s *testSuiteJoin2) TestNullEmptyAwareSemiJoin(c *C) { }, } results = []struct { - result [][]interface{} + result [][]any }{ { testkit.Rows("0"), @@ -1803,7 +1803,7 @@ func (s *testSuiteJoin2) TestNullEmptyAwareSemiJoin(c *C) { }, } results = []struct { - result [][]interface{} + result [][]any }{ { testkit.Rows("0"), @@ -1844,7 +1844,7 @@ func (s *testSuiteJoin2) TestNullEmptyAwareSemiJoin(c *C) { }, } results = []struct { - result [][]interface{} + result [][]any }{ { testkit.Rows("0"), diff --git a/executor/memtable_reader.go b/executor/memtable_reader.go index 986c58409..404a5116c 100644 --- a/executor/memtable_reader.go +++ b/executor/memtable_reader.go @@ -207,7 +207,7 @@ func fetchClusterConfig(sctx sessionctx.Context, nodeTypes, nodeAddrs set.String ch <- result{err: errors.Errorf("request %s failed: %s", url, resp.Status)} return } - var nested map[string]interface{} + var nested map[string]any if err = json.NewDecoder(resp.Body).Decode(&nested); err != nil { ch <- result{err: errors.Trace(err)} return @@ -454,11 +454,11 @@ func (h logResponseHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } -func (h *logResponseHeap) Push(x interface{}) { +func (h *logResponseHeap) Push(x any) { *h = append(*h, x.(logStreamResult)) } -func (h *logResponseHeap) Pop() interface{} { +func (h *logResponseHeap) Pop() any { old := *h n := len(old) x := old[n-1] diff --git a/executor/memtable_reader_test.go b/executor/memtable_reader_test.go index a5d5192db..1d0290832 100644 --- a/executor/memtable_reader_test.go +++ b/executor/memtable_reader_test.go @@ -145,9 +145,9 @@ func (s *testMemTableReaderSuite) TestTiDBClusterConfig(c *C) { // We check the counter to valid how many times request has been sent var requestCounter int32 - var mockConfig = func() (map[string]interface{}, error) { + var mockConfig = func() (map[string]any, error) { atomic.AddInt32(&requestCounter, 1) - configuration := map[string]interface{}{ + configuration := map[string]any{ "key1": "value1", "key2": map[string]string{ "nest1": "n-value1", diff --git a/executor/metrics_reader.go b/executor/metrics_reader.go index 91cb8159b..68e1a6a1d 100644 --- a/executor/metrics_reader.go +++ b/executor/metrics_reader.go @@ -234,7 +234,7 @@ func (e *MetricsSummaryRetriever) retrieve(_ context.Context, sctx sessionctx.Co return nil, errors.Errorf("execute '%s' failed: %v", sql, err) } for _, row := range rows { - var quantile interface{} + var quantile any if def.Quantile > 0 { quantile = row.GetFloat64(row.Len() - 1) } @@ -330,7 +330,7 @@ func (e *MetricsSummaryByLabelRetriever) retrieve(ctx context.Context, sctx sess } labels = append(labels, val) } - var quantile interface{} + var quantile any if def.Quantile > 0 { quantile = row.GetFloat64(row.Len() - 1) // quantile will be the last column } diff --git a/executor/pkg_test.go b/executor/pkg_test.go index a4e1986d7..dbcf6a220 100644 --- a/executor/pkg_test.go +++ b/executor/pkg_test.go @@ -30,7 +30,7 @@ func (s *pkgTestSuite) TestNestedLoopApply(c *C) { schema: outerSchema, rows: 6, ctx: sctx, - genDataFunc: func(row int, typ *types.FieldType) interface{} { + genDataFunc: func(row int, typ *types.FieldType) any { return int64(row + 1) }, }) @@ -41,7 +41,7 @@ func (s *pkgTestSuite) TestNestedLoopApply(c *C) { schema: innerSchema, rows: 6, ctx: sctx, - genDataFunc: func(row int, typ *types.FieldType) interface{} { + genDataFunc: func(row int, typ *types.FieldType) any { return int64(row + 1) }, }) diff --git a/executor/projection.go b/executor/projection.go index ca5015904..41680e977 100644 --- a/executor/projection.go +++ b/executor/projection.go @@ -112,59 +112,65 @@ func (e *ProjectionExec) open(ctx context.Context) error { // // Here we explain the execution flow of the parallel projection implementation. // There are 3 main components: -// 1. "projectionInputFetcher": Fetch input "Chunk" from child. -// 2. "projectionWorker": Do the projection work. -// 3. "ProjectionExec.Next": Return result to parent. +// 1. "projectionInputFetcher": Fetch input "Chunk" from child. +// 2. "projectionWorker": Do the projection work. +// 3. "ProjectionExec.Next": Return result to parent. // // 1. "projectionInputFetcher" gets its input and output resources from its // "inputCh" and "outputCh" channel, once the input and output resources are // abtained, it fetches child's result into "input.chk" and: -// a. Dispatches this input to the worker specified in "input.targetWorker" -// b. Dispatches this output to the main thread: "ProjectionExec.Next" -// c. Dispatches this output to the worker specified in "input.targetWorker" +// +// a. Dispatches this input to the worker specified in "input.targetWorker" +// b. Dispatches this output to the main thread: "ProjectionExec.Next" +// c. Dispatches this output to the worker specified in "input.targetWorker" +// // It is finished and exited once: -// a. There is no more input from child. -// b. "ProjectionExec" close the "globalFinishCh" +// +// a. There is no more input from child. +// b. "ProjectionExec" close the "globalFinishCh" // // 2. "projectionWorker" gets its input and output resources from its // "inputCh" and "outputCh" channel, once the input and output resources are // abtained, it calculates the projection result use "input.chk" as the input // and "output.chk" as the output, once the calculation is done, it: -// a. Sends "nil" or error to "output.done" to mark this input is finished. -// b. Returns the "input" resource to "projectionInputFetcher.inputCh" +// +// a. Sends "nil" or error to "output.done" to mark this input is finished. +// b. Returns the "input" resource to "projectionInputFetcher.inputCh" +// // They are finished and exited once: -// a. "ProjectionExec" closes the "globalFinishCh" +// +// a. "ProjectionExec" closes the "globalFinishCh" // // 3. "ProjectionExec.Next" gets its output resources from its "outputCh" channel. // After receiving an output from "outputCh", it should wait to receive a "nil" // or error from "output.done" channel. Once a "nil" or error is received: -// a. Returns this output to its parent -// b. Returns the "output" resource to "projectionInputFetcher.outputCh" // -// +-----------+----------------------+--------------------------+ -// | | | | -// | +--------+---------+ +--------+---------+ +--------+---------+ -// | | projectionWorker | + projectionWorker | ... + projectionWorker | -// | +------------------+ +------------------+ +------------------+ -// | ^ ^ ^ ^ ^ ^ -// | | | | | | | -// | inputCh outputCh inputCh outputCh inputCh outputCh -// | ^ ^ ^ ^ ^ ^ -// | | | | | | | -// | | | -// | | +----------------->outputCh -// | | | | -// | | | v -// | +-------+-------+--------+ +---------------------+ -// | | projectionInputFetcher | | ProjectionExec.Next | -// | +------------------------+ +---------+-----------+ -// | ^ ^ | -// | | | | -// | inputCh outputCh | -// | ^ ^ | -// | | | | -// +------------------------------+ +----------------------+ +// a. Returns this output to its parent +// b. Returns the "output" resource to "projectionInputFetcher.outputCh" // +// +-----------+----------------------+--------------------------+ +// | | | | +// | +--------+---------+ +--------+---------+ +--------+---------+ +// | | projectionWorker | + projectionWorker | ... + projectionWorker | +// | +------------------+ +------------------+ +------------------+ +// | ^ ^ ^ ^ ^ ^ +// | | | | | | | +// | inputCh outputCh inputCh outputCh inputCh outputCh +// | ^ ^ ^ ^ ^ ^ +// | | | | | | | +// | | | +// | | +----------------->outputCh +// | | | | +// | | | v +// | +-------+-------+--------+ +---------------------+ +// | | projectionInputFetcher | | ProjectionExec.Next | +// | +------------------------+ +---------+-----------+ +// | ^ ^ | +// | | | | +// | inputCh outputCh | +// | ^ ^ | +// | | | | +// +------------------------------+ +----------------------+ func (e *ProjectionExec) Next(ctx context.Context, req *chunk.Chunk) error { req.GrowAndReset(e.maxChunkSize) if e.isUnparallelExec() { @@ -330,13 +336,15 @@ type projectionInputFetcher struct { // run gets projectionInputFetcher's input and output resources from its // "inputCh" and "outputCh" channel, once the input and output resources are // abtained, it fetches child's result into "input.chk" and: -// a. Dispatches this input to the worker specified in "input.targetWorker" -// b. Dispatches this output to the main thread: "ProjectionExec.Next" -// c. Dispatches this output to the worker specified in "input.targetWorker" +// +// a. Dispatches this input to the worker specified in "input.targetWorker" +// b. Dispatches this output to the main thread: "ProjectionExec.Next" +// c. Dispatches this output to the worker specified in "input.targetWorker" // // It is finished and exited once: -// a. There is no more input from child. -// b. "ProjectionExec" close the "globalFinishCh" +// +// a. There is no more input from child. +// b. "ProjectionExec" close the "globalFinishCh" func (f *projectionInputFetcher) run(ctx context.Context) { var output *projectionOutput defer func() { @@ -397,11 +405,13 @@ type projectionWorker struct { // "inputCh" and "outputCh" channel, once the input and output resources are // abtained, it calculate the projection result use "input.chk" as the input // and "output.chk" as the output, once the calculation is done, it: -// a. Sends "nil" or error to "output.done" to mark this input is finished. -// b. Returns the "input" resource to "projectionInputFetcher.inputCh". +// +// a. Sends "nil" or error to "output.done" to mark this input is finished. +// b. Returns the "input" resource to "projectionInputFetcher.inputCh". // // It is finished and exited once: -// a. "ProjectionExec" closes the "globalFinishCh". +// +// a. "ProjectionExec" closes the "globalFinishCh". func (w *projectionWorker) run(ctx context.Context) { var output *projectionOutput defer func() { @@ -435,7 +445,7 @@ func (w *projectionWorker) run(ctx context.Context) { } } -func recoveryProjection(output *projectionOutput, r interface{}) { +func recoveryProjection(output *projectionOutput, r any) { if output != nil { output.done <- errors.Errorf("%v", r) } diff --git a/executor/seqtest/seq_executor_test.go b/executor/seqtest/seq_executor_test.go index 8deb2966b..64c4c806e 100644 --- a/executor/seqtest/seq_executor_test.go +++ b/executor/seqtest/seq_executor_test.go @@ -167,13 +167,13 @@ type stats struct { func (s stats) GetScope(status string) variable.ScopeFlag { return variable.DefaultStatusVarScopeFlag } -func (s stats) Stats(vars *variable.SessionVars) (map[string]interface{}, error) { - m := make(map[string]interface{}) - var a, b interface{} +func (s stats) Stats(vars *variable.SessionVars) (map[string]any, error) { + m := make(map[string]any) + var a, b any b = "123" m["test_interface_nil"] = a m["test_interface"] = b - m["test_interface_slice"] = []interface{}{"a", "b", "c"} + m["test_interface_slice"] = []any{"a", "b", "c"} return m, nil } @@ -196,7 +196,7 @@ func (s *seqTestSuite) TestShow(c *C) { c.Check(result.Rows(), HasLen, 1) row := result.Rows()[0] // For issue https://github.com/pingcap/tidb/issues/1061 - expectedRow := []interface{}{ + expectedRow := []any{ "SHOW_test", "CREATE TABLE `SHOW_test` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `c1` int(11) DEFAULT NULL COMMENT 'c1_comment',\n `c2` int(11) DEFAULT NULL,\n `c3` int(11) DEFAULT 1,\n `c4` text DEFAULT NULL,\n `c5` tinyint(1) DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `idx_wide_c4` (`c3`,`c4`(10))\n) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=28934 COMMENT='table_comment'"} for i, r := range row { c.Check(r, Equals, expectedRow[i]) @@ -216,7 +216,7 @@ func (s *seqTestSuite) TestShow(c *C) { result = tk.MustQuery(testSQL) c.Check(result.Rows(), HasLen, 1) row = result.Rows()[0] - expectedRow = []interface{}{ + expectedRow = []any{ "ptest", "CREATE TABLE `ptest` (\n `a` int(11) NOT NULL,\n `b` double NOT NULL DEFAULT 2.0,\n `c` varchar(10) NOT NULL,\n `d` time DEFAULT NULL,\n `e` timestamp NULL DEFAULT NULL,\n `f` timestamp NULL DEFAULT NULL,\n PRIMARY KEY (`a`),\n UNIQUE KEY `d` (`d`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"} for i, r := range row { c.Check(r, Equals, expectedRow[i]) @@ -236,7 +236,7 @@ func (s *seqTestSuite) TestShow(c *C) { result = tk.MustQuery(testSQL) c.Check(result.Rows(), HasLen, 1) row = result.Rows()[0] - expectedRow = []interface{}{ + expectedRow = []any{ "t1", "CREATE TABLE `t1` (\n" + " `c1` tinyint(3) unsigned DEFAULT NULL,\n" + " `c2` smallint(5) unsigned DEFAULT NULL,\n" + @@ -256,7 +256,7 @@ func (s *seqTestSuite) TestShow(c *C) { result = tk.MustQuery(testSQL) c.Check(result.Rows(), HasLen, 1) row = result.Rows()[0] - expectedRow = []interface{}{ + expectedRow = []any{ "decimalschema", "CREATE TABLE `decimalschema` (\n" + " `c1` decimal(11,0) DEFAULT NULL\n" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"} @@ -271,7 +271,7 @@ func (s *seqTestSuite) TestShow(c *C) { result = tk.MustQuery(testSQL) c.Check(result.Rows(), HasLen, 1) row = result.Rows()[0] - expectedRow = []interface{}{ + expectedRow = []any{ "decimalschema", "CREATE TABLE `decimalschema` (\n" + " `c1` decimal(15,0) DEFAULT NULL\n" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"} @@ -338,7 +338,7 @@ func (s *seqTestSuite) TestShow(c *C) { result = tk.MustQuery(testSQL) rows := result.Rows() c.Check(rows, HasLen, 1) - c.Check(rows[0], DeepEquals, []interface{}{"SHOW_test"}) + c.Check(rows[0], DeepEquals, []any{"SHOW_test"}) var ss stats variable.RegisterStatistics(ss) @@ -453,7 +453,7 @@ func (s *seqTestSuite) TestShow(c *C) { result = tk.MustQuery(testSQL) c.Check(result.Rows(), HasLen, 1) row = result.Rows()[0] - expectedRow = []interface{}{ + expectedRow = []any{ "show_test", "CREATE TABLE `show_test` (\n `a` varchar(10) DEFAULT NULL COMMENT 'a\\nb\\rc d\\0e'\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='a\\nb\\rc d\\0e'"} for i, r := range row { c.Check(r, Equals, expectedRow[i]) @@ -469,7 +469,7 @@ func (s *seqTestSuite) TestShow(c *C) { result = tk.MustQuery(testSQL) c.Check(result.Rows(), HasLen, 1) row = result.Rows()[0] - expectedRow = []interface{}{ + expectedRow = []any{ "show_test", "CREATE TABLE `show_test` (\n `a` varchar(10) DEFAULT 'a\\nb\\rc d\\0e'\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"} for i, r := range row { c.Check(r, Equals, expectedRow[i]) @@ -488,7 +488,7 @@ func (s *seqTestSuite) TestShow(c *C) { result = tk.MustQuery(testSQL) c.Check(result.Rows(), HasLen, 1) row = result.Rows()[0] - expectedRow = []interface{}{ + expectedRow = []any{ "show_test", "CREATE TABLE `show_test` (\n `a` bit(1) DEFAULT NULL,\n `b` bit(32) DEFAULT b'0',\n `c` bit(1) DEFAULT b'1',\n `d` bit(10) DEFAULT b'1010'\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin"} for i, r := range row { c.Check(r, Equals, expectedRow[i]) @@ -509,7 +509,7 @@ func (s *seqTestSuite) TestShow(c *C) { result = tk.MustQuery(testSQL) c.Check(result.Rows(), HasLen, 1) row = result.Rows()[0] - expectedRow = []interface{}{ + expectedRow = []any{ "t", "CREATE TABLE `t` (\n" + " `a` tinyint(4) DEFAULT NULL,\n" + @@ -924,8 +924,8 @@ func (s *seqTestSuite) TestPrepareMaxParamCountCheck(c *C) { c.Assert(err.Error(), Equals, "[executor:1390]Prepared statement contains too many placeholders") } -func generateBatchSQL(paramCount int) (sql string, paramSlice []interface{}) { - params := make([]interface{}, 0, paramCount) +func generateBatchSQL(paramCount int) (sql string, paramSlice []any) { + params := make([]any, 0, paramCount) placeholders := make([]string, 0, paramCount) for i := 0; i < paramCount; i++ { params = append(params, i) diff --git a/executor/show.go b/executor/show.go index 9e05ce2b1..ea3459909 100644 --- a/executor/show.go +++ b/executor/show.go @@ -266,7 +266,7 @@ func (e *ShowExec) fetchShowBind() error { if !checker.ok { continue } - e.appendRow([]interface{}{ + e.appendRow([]any{ bindData.OriginalSQL, hint.BindSQL, bindData.Db, @@ -317,7 +317,7 @@ func (e *ShowExec) fetchShowDatabases() error { if checker != nil && !checker.DBIsVisible(e.ctx.GetSessionVars().ActiveRoles, d) { continue } - e.appendRow([]interface{}{ + e.appendRow([]any{ d, }) } @@ -389,9 +389,9 @@ func (e *ShowExec) fetchShowTables() error { sort.Strings(tableNames) for _, v := range tableNames { if e.Full { - e.appendRow([]interface{}{v, tableTypes[v]}) + e.appendRow([]any{v, tableTypes[v]}) } else { - e.appendRow([]interface{}{v}) + e.appendRow([]any{v}) } } return nil @@ -476,7 +476,7 @@ func (e *ShowExec) fetchShowColumns(ctx context.Context) error { } desc := table.NewColDesc(col) - var columnDefault interface{} + var columnDefault any if desc.DefaultValue != nil { // SHOW COLUMNS result expects string value defaultValStr := fmt.Sprintf("%v", desc.DefaultValue) @@ -499,7 +499,7 @@ func (e *ShowExec) fetchShowColumns(ctx context.Context) error { // The FULL keyword causes the output to include the column collation and comments, // as well as the privileges you have for each column. if e.Full { - e.appendRow([]interface{}{ + e.appendRow([]any{ desc.Field, desc.Type, desc.Collation, @@ -511,7 +511,7 @@ func (e *ShowExec) fetchShowColumns(ctx context.Context) error { desc.Comment, }) } else { - e.appendRow([]interface{}{ + e.appendRow([]any{ desc.Field, desc.Type, desc.Null, @@ -544,7 +544,7 @@ func (e *ShowExec) fetchShowIndex() error { break } } - e.appendRow([]interface{}{ + e.appendRow([]any{ tb.Meta().Name.O, // Table 0, // Non_unique "PRIMARY", // Key_name @@ -573,7 +573,7 @@ func (e *ShowExec) fetchShowIndex() error { nonUniq = 0 } - var subPart interface{} + var subPart any if col.Length != types.UnspecifiedLength { subPart = col.Length } @@ -596,7 +596,7 @@ func (e *ShowExec) fetchShowIndex() error { expression = fmt.Sprintf("(%s)", tblCol.GeneratedExprString) } - e.appendRow([]interface{}{ + e.appendRow([]any{ tb.Meta().Name.O, // Table nonUniq, // Non_unique idx.Meta().Name.O, // Key_name @@ -623,7 +623,7 @@ func (e *ShowExec) fetchShowIndex() error { func (e *ShowExec) fetchShowCharset() error { descs := charset.GetSupportedCharsets() for _, desc := range descs { - e.appendRow([]interface{}{ + e.appendRow([]any{ desc.Name, desc.Desc, desc.DefaultCollation, @@ -635,7 +635,7 @@ func (e *ShowExec) fetchShowCharset() error { func (e *ShowExec) fetchShowMainStatus() error { tso := e.ctx.GetSessionVars().TxnCtx.StartTS - e.appendRow([]interface{}{"tidb-binlog", tso, "", "", ""}) + e.appendRow([]any{"tidb-binlog", tso, "", "", ""}) return nil } @@ -666,7 +666,7 @@ func (e *ShowExec) fetchShowVariables() (err error) { unreachedVars = append(unreachedVars, v.Name) continue } - e.appendRow([]interface{}{v.Name, value}) + e.appendRow([]any{v.Name, value}) } if len(unreachedVars) != 0 { systemVars, err := sessionVars.GlobalVarsAccessor.GetAllSysVars() @@ -678,7 +678,7 @@ func (e *ShowExec) fetchShowVariables() (err error) { if !ok { varValue = variable.SysVars[varName].Value } - e.appendRow([]interface{}{varName, varValue}) + e.appendRow([]any{varName, varValue}) } } return nil @@ -695,14 +695,14 @@ func (e *ShowExec) fetchShowStatus() error { continue } switch v.Value.(type) { - case []interface{}, nil: + case []any, nil: v.Value = fmt.Sprintf("%v", v.Value) } value, err := types.ToString(v.Value) if err != nil { return errors.Trace(err) } - e.appendRow([]interface{}{status, value}) + e.appendRow([]any{status, value}) } return nil } @@ -972,7 +972,7 @@ func (e *ShowExec) fetchShowCreateSequence() error { } var buf bytes.Buffer ConstructResultOfShowCreateSequence(e.ctx, tableInfo, &buf) - e.appendRow([]interface{}{tableInfo.Name.O, buf.String()}) + e.appendRow([]any{tableInfo.Name.O, buf.String()}) return nil } @@ -995,7 +995,7 @@ func (e *ShowExec) fetchShowClusterConfigs(ctx context.Context) error { return err } for _, items := range confItems { - row := make([]interface{}, 0, 4) + row := make([]any, 0, 4) for _, item := range items { row = append(row, item.GetString()) } @@ -1018,11 +1018,11 @@ func (e *ShowExec) fetchShowCreateTable() error { return err } if tableInfo.IsView() { - e.appendRow([]interface{}{tableInfo.Name.O, buf.String(), tableInfo.Charset, tableInfo.Collate}) + e.appendRow([]any{tableInfo.Name.O, buf.String(), tableInfo.Charset, tableInfo.Collate}) return nil } - e.appendRow([]interface{}{tableInfo.Name.O, buf.String()}) + e.appendRow([]any{tableInfo.Name.O, buf.String()}) return nil } @@ -1043,7 +1043,7 @@ func (e *ShowExec) fetchShowCreateView() error { var buf bytes.Buffer fetchShowCreateTable4View(e.ctx, tb.Meta(), &buf) - e.appendRow([]interface{}{tb.Meta().Name.O, buf.String(), tb.Meta().Charset, tb.Meta().Collate}) + e.appendRow([]any{tb.Meta().Name.O, buf.String(), tb.Meta().Charset, tb.Meta().Collate}) return nil } @@ -1152,7 +1152,7 @@ func (e *ShowExec) fetchShowCreateDatabase() error { if err != nil { return err } - e.appendRow([]interface{}{dbInfo.Name.O, buf.String()}) + e.appendRow([]any{dbInfo.Name.O, buf.String()}) return nil } @@ -1163,7 +1163,7 @@ func (e *ShowExec) fetchShowCollation() error { if v.IsDefault { isDefault = "Yes" } - e.appendRow([]interface{}{ + e.appendRow([]any{ v.Name, v.CharsetName, v.ID, @@ -1224,7 +1224,7 @@ func (e *ShowExec) fetchShowCreateUser() error { } showStr := fmt.Sprintf("CREATE USER '%s'@'%s' IDENTIFIED WITH 'mysql_native_password' AS '%s' REQUIRE %s PASSWORD EXPIRE DEFAULT ACCOUNT UNLOCK", e.User.Username, e.User.Hostname, checker.GetEncodedPassword(e.User.Username, e.User.Hostname), require) - e.appendRow([]interface{}{showStr}) + e.appendRow([]any{showStr}) return nil } @@ -1260,44 +1260,44 @@ func (e *ShowExec) fetchShowGrants() error { return errors.Trace(err) } for _, g := range gs { - e.appendRow([]interface{}{g}) + e.appendRow([]any{g}) } return nil } func (e *ShowExec) fetchShowPrivileges() error { - e.appendRow([]interface{}{"Alter", "Tables", "To alter the table"}) - e.appendRow([]interface{}{"Alter", "Tables", "To alter the table"}) - e.appendRow([]interface{}{"Alter routine", "Functions,Procedures", "To alter or drop stored functions/procedures"}) - e.appendRow([]interface{}{"Create", "Databases,Tables,Indexes", "To create new databases and tables"}) - e.appendRow([]interface{}{"Create routine", "Databases", "To use CREATE FUNCTION/PROCEDURE"}) - e.appendRow([]interface{}{"Create temporary tables", "Databases", "To use CREATE TEMPORARY TABLE"}) - e.appendRow([]interface{}{"Create view", "Tables", "To create new views"}) - e.appendRow([]interface{}{"Create user", "Server Admin", "To create new users"}) - e.appendRow([]interface{}{"Delete", "Tables", "To delete existing rows"}) - e.appendRow([]interface{}{"Drop", "Databases,Tables", "To drop databases, tables, and views"}) - e.appendRow([]interface{}{"Event", "Server Admin", "To create, alter, drop and execute events"}) - e.appendRow([]interface{}{"Execute", "Functions,Procedures", "To execute stored routines"}) - e.appendRow([]interface{}{"File", "File access on server", "To read and write files on the server"}) - e.appendRow([]interface{}{"Grant option", "Databases,Tables,Functions,Procedures", "To give to other users those privileges you possess"}) - e.appendRow([]interface{}{"Index", "Tables", "To create or drop indexes"}) - e.appendRow([]interface{}{"Insert", "Tables", "To insert data into tables"}) - e.appendRow([]interface{}{"Lock tables", "Databases", "To use LOCK TABLES (together with SELECT privilege)"}) - e.appendRow([]interface{}{"Process", "Server Admin", "To view the plain text of currently executing queries"}) - e.appendRow([]interface{}{"Proxy", "Server Admin", "To make proxy user possible"}) - e.appendRow([]interface{}{"References", "Databases,Tables", "To have references on tables"}) - e.appendRow([]interface{}{"Reload", "Server Admin", "To reload or refresh tables, logs and privileges"}) - e.appendRow([]interface{}{"Replication client", "Server Admin", "To ask where the subordinate or main servers are"}) - e.appendRow([]interface{}{"Replication subordinate", "Server Admin", "To read binary log events from the main"}) - e.appendRow([]interface{}{"Select", "Tables", "To retrieve rows from table"}) - e.appendRow([]interface{}{"Show databases", "Server Admin", "To see all databases with SHOW DATABASES"}) - e.appendRow([]interface{}{"Show view", "Tables", "To see views with SHOW CREATE VIEW"}) - e.appendRow([]interface{}{"Shutdown", "Server Admin", "To shut down the server"}) - e.appendRow([]interface{}{"Super", "Server Admin", "To use KILL thread, SET GLOBAL, CHANGE MASTER, etc."}) - e.appendRow([]interface{}{"Trigger", "Tables", "To use triggers"}) - e.appendRow([]interface{}{"Create tablespace", "Server Admin", "To create/alter/drop tablespaces"}) - e.appendRow([]interface{}{"Update", "Tables", "To update existing rows"}) - e.appendRow([]interface{}{"Usage", "Server Admin", "No privileges - allow connect only"}) + e.appendRow([]any{"Alter", "Tables", "To alter the table"}) + e.appendRow([]any{"Alter", "Tables", "To alter the table"}) + e.appendRow([]any{"Alter routine", "Functions,Procedures", "To alter or drop stored functions/procedures"}) + e.appendRow([]any{"Create", "Databases,Tables,Indexes", "To create new databases and tables"}) + e.appendRow([]any{"Create routine", "Databases", "To use CREATE FUNCTION/PROCEDURE"}) + e.appendRow([]any{"Create temporary tables", "Databases", "To use CREATE TEMPORARY TABLE"}) + e.appendRow([]any{"Create view", "Tables", "To create new views"}) + e.appendRow([]any{"Create user", "Server Admin", "To create new users"}) + e.appendRow([]any{"Delete", "Tables", "To delete existing rows"}) + e.appendRow([]any{"Drop", "Databases,Tables", "To drop databases, tables, and views"}) + e.appendRow([]any{"Event", "Server Admin", "To create, alter, drop and execute events"}) + e.appendRow([]any{"Execute", "Functions,Procedures", "To execute stored routines"}) + e.appendRow([]any{"File", "File access on server", "To read and write files on the server"}) + e.appendRow([]any{"Grant option", "Databases,Tables,Functions,Procedures", "To give to other users those privileges you possess"}) + e.appendRow([]any{"Index", "Tables", "To create or drop indexes"}) + e.appendRow([]any{"Insert", "Tables", "To insert data into tables"}) + e.appendRow([]any{"Lock tables", "Databases", "To use LOCK TABLES (together with SELECT privilege)"}) + e.appendRow([]any{"Process", "Server Admin", "To view the plain text of currently executing queries"}) + e.appendRow([]any{"Proxy", "Server Admin", "To make proxy user possible"}) + e.appendRow([]any{"References", "Databases,Tables", "To have references on tables"}) + e.appendRow([]any{"Reload", "Server Admin", "To reload or refresh tables, logs and privileges"}) + e.appendRow([]any{"Replication client", "Server Admin", "To ask where the subordinate or main servers are"}) + e.appendRow([]any{"Replication subordinate", "Server Admin", "To read binary log events from the main"}) + e.appendRow([]any{"Select", "Tables", "To retrieve rows from table"}) + e.appendRow([]any{"Show databases", "Server Admin", "To see all databases with SHOW DATABASES"}) + e.appendRow([]any{"Show view", "Tables", "To see views with SHOW CREATE VIEW"}) + e.appendRow([]any{"Shutdown", "Server Admin", "To shut down the server"}) + e.appendRow([]any{"Super", "Server Admin", "To use KILL thread, SET GLOBAL, CHANGE MASTER, etc."}) + e.appendRow([]any{"Trigger", "Tables", "To use triggers"}) + e.appendRow([]any{"Create tablespace", "Server Admin", "To create/alter/drop tablespaces"}) + e.appendRow([]any{"Update", "Tables", "To update existing rows"}) + e.appendRow([]any{"Usage", "Server Admin", "No privileges - allow connect only"}) return nil } @@ -1313,7 +1313,7 @@ func (e *ShowExec) fetchShowPlugins() error { tiPlugins := plugin.GetAll() for _, ps := range tiPlugins { for _, p := range ps { - e.appendRow([]interface{}{p.Name, p.StateValue(), p.Kind.String(), p.Path, p.License, strconv.Itoa(int(p.Version))}) + e.appendRow([]any{p.Name, p.StateValue(), p.Kind.String(), p.Path, p.License, strconv.Itoa(int(p.Version))}) } } return nil @@ -1329,9 +1329,9 @@ func (e *ShowExec) fetchShowWarnings(errOnly bool) error { switch x := warn.(type) { case *terror.Error: sqlErr := x.ToSQLError() - e.appendRow([]interface{}{w.Level, int64(sqlErr.Code), sqlErr.Message}) + e.appendRow([]any{w.Level, int64(sqlErr.Code), sqlErr.Message}) default: - e.appendRow([]interface{}{w.Level, int64(mysql.ErrUnknown), warn.Error()}) + e.appendRow([]any{w.Level, int64(mysql.ErrUnknown), warn.Error()}) } } return nil @@ -1357,7 +1357,7 @@ func (e *ShowExec) fetchShowPumpOrDrainerStatus(kind string) error { if n.State == node.Offline { continue } - e.appendRow([]interface{}{n.NodeID, n.Addr, n.State, n.MaxCommitTS, utils.TSOToRoughTime(n.UpdateTS).Format(types.TimeFormat)}) + e.appendRow([]any{n.NodeID, n.Addr, n.State, n.MaxCommitTS, utils.TSOToRoughTime(n.UpdateTS).Format(types.TimeFormat)}) } return nil @@ -1410,7 +1410,7 @@ func (e *ShowExec) tableAccessDenied(access string, table string) error { return ErrTableaccessDenied.GenWithStackByArgs(access, u, h, table) } -func (e *ShowExec) appendRow(row []interface{}) { +func (e *ShowExec) appendRow(row []any) { for i, col := range row { if col == nil { e.result.AppendNull(i) @@ -1565,7 +1565,7 @@ func (e *ShowExec) fillRegionsToChunk(regions []regionMeta) { func (e *ShowExec) fetchShowBuiltins() error { for _, f := range expression.GetBuiltinList() { - e.appendRow([]interface{}{f}) + e.appendRow([]any{f}) } return nil } diff --git a/executor/show_stats.go b/executor/show_stats.go index 0c1461821..b94058cad 100644 --- a/executor/show_stats.go +++ b/executor/show_stats.go @@ -47,7 +47,7 @@ func (e *ShowExec) appendTableForStatsMeta(dbName, tblName, partitionName string if statsTbl.Pseudo { return } - e.appendRow([]interface{}{ + e.appendRow([]any{ dbName, tblName, partitionName, @@ -93,7 +93,7 @@ func (e *ShowExec) appendTableForStatsHistograms(dbName, tblName, partitionName } func (e *ShowExec) histogramToRow(dbName, tblName, partitionName, colName string, isIndex int, hist statistics.Histogram, avgColSize float64) { - e.appendRow([]interface{}{ + e.appendRow([]any{ dbName, tblName, partitionName, @@ -170,7 +170,7 @@ func (e *ShowExec) bucketsToRows(dbName, tblName, partitionName, colName string, if err != nil { return errors.Trace(err) } - e.appendRow([]interface{}{ + e.appendRow([]any{ dbName, tblName, partitionName, @@ -214,7 +214,7 @@ func (e *ShowExec) appendTableForStatsHealthy(dbName, tblName, partitionName str } else if statsTbl.ModifyCount == 0 { healthy = 100 } - e.appendRow([]interface{}{ + e.appendRow([]any{ dbName, tblName, partitionName, diff --git a/executor/shuffle.go b/executor/shuffle.go index 84ec40220..e15838791 100644 --- a/executor/shuffle.go +++ b/executor/shuffle.go @@ -28,49 +28,53 @@ import ( ) // ShuffleExec is the executor to run other executors in a parallel manner. +// // 1. It fetches chunks from `DataSource`. +// // 2. It splits tuples from `DataSource` into N partitions (Only "split by hash" is implemented so far). +// // 3. It invokes N workers in parallel, assign each partition as input to each worker and execute child executors. +// // 4. It collects outputs from each worker, then sends outputs to its parent. // -// +-------------+ -// +-------| Main Thread | -// | +------+------+ -// | ^ -// | | -// | + -// v +++ -// outputHolderCh | | outputCh (1 x Concurrency) -// v +++ -// | ^ -// | | -// | +-------+-------+ -// v | | -// +--------------+ +--------------+ -// +----- | worker | ....... | worker | worker (N Concurrency): child executor, eg. WindowExec (+SortExec) -// | +------------+-+ +-+------------+ -// | ^ ^ -// | | | -// | +-+ +-+ ...... +-+ -// | | | | | | | -// | ... ... ... inputCh (Concurrency x 1) -// v | | | | | | -// inputHolderCh +++ +++ +++ -// v ^ ^ ^ -// | | | | -// | +------o----+ | -// | | +-----------------+-----+ -// | | | -// | +---+------------+------------+----+-----------+ -// | | Partition Splitter | -// | +--------------+-+------------+-+--------------+ -// | ^ -// | | -// | +---------------v-----------------+ -// +----------> | fetch data from DataSource | -// +---------------------------------+ +// +-------------+ +// +-------| Main Thread | +// | +------+------+ +// | ^ +// | | +// | + +// v +++ +// outputHolderCh | | outputCh (1 x Concurrency) +// v +++ +// | ^ +// | | +// | +-------+-------+ +// v | | +// +--------------+ +--------------+ +// +----- | worker | ....... | worker | worker (N Concurrency): child executor, eg. WindowExec (+SortExec) +// | +------------+-+ +-+------------+ +// | ^ ^ +// | | | +// | +-+ +-+ ...... +-+ +// | | | | | | | +// | ... ... ... inputCh (Concurrency x 1) +// v | | | | | | +// inputHolderCh +++ +++ +++ +// v ^ ^ ^ +// | | | | +// | +------o----+ | +// | | +-----------------+-----+ +// | | | +// | +---+------------+------------+----+-----------+ +// | | Partition Splitter | +// | +--------------+-+------------+-+--------------+ +// | ^ +// | | +// | +---------------v-----------------+ +// +----------> | fetch data from DataSource | +// +---------------------------------+ // -//////////////////////////////////////////////////////////////////////////////////////// +// ////////////////////////////////////////////////////////////////////////////////////// type ShuffleExec struct { baseExecutor concurrency int @@ -204,7 +208,7 @@ func (e *ShuffleExec) Next(ctx context.Context, req *chunk.Chunk) error { return nil } -func recoveryShuffleExec(output chan *shuffleOutput, r interface{}) { +func recoveryShuffleExec(output chan *shuffleOutput, r any) { err := errors.Errorf("%v", r) output <- &shuffleOutput{err: errors.Errorf("%v", r)} logutil.BgLogger().Error("shuffle panicked", zap.Error(err), zap.Stack("stack")) diff --git a/executor/sort.go b/executor/sort.go index 8f5be2074..044c3639e 100644 --- a/executor/sort.go +++ b/executor/sort.go @@ -114,12 +114,12 @@ func (e *SortExec) Open(ctx context.Context) error { // Next implements the Executor Next interface. // Sort constructs the result following these step: -// 1. Read as mush as rows into memory. -// 2. If memory quota is triggered, sort these rows in memory and put them into disk as partition 1, then reset -// the memory quota trigger and return to step 1 -// 3. If memory quota is not triggered and child is consumed, sort these rows in memory as partition N. -// 4. Merge sort if the count of partitions is larger than 1. If there is only one partition in step 4, it works -// just like in-memory sort before. +// 1. Read as mush as rows into memory. +// 2. If memory quota is triggered, sort these rows in memory and put them into disk as partition 1, then reset +// the memory quota trigger and return to step 1 +// 3. If memory quota is not triggered and child is consumed, sort these rows in memory as partition N. +// 4. Merge sort if the count of partitions is larger than 1. If there is only one partition in step 4, it works +// just like in-memory sort before. func (e *SortExec) Next(ctx context.Context, req *chunk.Chunk) error { req.Reset() if !e.fetched { @@ -192,11 +192,11 @@ func (h *multiWayMerge) Len() int { return len(h.elements) } -func (h *multiWayMerge) Push(x interface{}) { +func (h *multiWayMerge) Push(x any) { // Should never be called. } -func (h *multiWayMerge) Pop() interface{} { +func (h *multiWayMerge) Pop() any { h.elements = h.elements[:len(h.elements)-1] return nil } @@ -374,11 +374,11 @@ func (h *topNChunkHeap) Len() int { return len(h.rowPtrs) } -func (h *topNChunkHeap) Push(x interface{}) { +func (h *topNChunkHeap) Push(x any) { // Should never be called. } -func (h *topNChunkHeap) Pop() interface{} { +func (h *topNChunkHeap) Pop() any { h.rowPtrs = h.rowPtrs[:len(h.rowPtrs)-1] // We don't need the popped value, return nil to avoid memory allocation. return nil diff --git a/executor/table_readers_required_rows_test.go b/executor/table_readers_required_rows_test.go index 9e5aab6b5..749bccf69 100644 --- a/executor/table_readers_required_rows_test.go +++ b/executor/table_readers_required_rows_test.go @@ -78,7 +78,7 @@ func (r *requiredRowsSelectResult) genOneRow() chunk.Row { return row.ToRow() } -func (r *requiredRowsSelectResult) genValue(valType *types.FieldType) interface{} { +func (r *requiredRowsSelectResult) genValue(valType *types.FieldType) any { switch valType.Tp { case mysql.TypeLong, mysql.TypeLonglong: return int64(rand.Int()) diff --git a/executor/trace_test.go b/executor/trace_test.go index 70bdcc35a..42283eebc 100644 --- a/executor/trace_test.go +++ b/executor/trace_test.go @@ -51,7 +51,7 @@ func (s *testSuite1) TestTraceExec(c *C) { c.Assert(len(rows), GreaterEqual, 1) } -func rowsOrdered(rows [][]interface{}) bool { +func rowsOrdered(rows [][]any) bool { for idx := range rows { if _, ok := rows[idx][1].(string); !ok { return false diff --git a/executor/update_test.go b/executor/update_test.go index 87ef2ffb1..34c5b01d6 100644 --- a/executor/update_test.go +++ b/executor/update_test.go @@ -101,7 +101,7 @@ func (s *testUpdateSuite) TestUpdateWithAutoidSchema(c *C) { tests := []struct { exec string query string - result [][]interface{} + result [][]any }{ { `insert into t1 set n = 1`, diff --git a/executor/write_concurrent_test.go b/executor/write_concurrent_test.go index dffb474dd..a021c9f49 100644 --- a/executor/write_concurrent_test.go +++ b/executor/write_concurrent_test.go @@ -40,15 +40,15 @@ func (s *testSuite) TestBatchInsertWithOnDuplicate(c *C) { tk.ConcurrentRun(c, 3, 2, // concurrent: 3, loops: 2, // prepare data for each loop. - func(ctx context.Context, tk *testkit.CTestKit, concurrent int, currentLoop int) [][][]interface{} { - var ii [][][]interface{} + func(ctx context.Context, tk *testkit.CTestKit, concurrent int, currentLoop int) [][][]any { + var ii [][][]any for i := 0; i < concurrent; i++ { - ii = append(ii, [][]interface{}{tk.PermInt(7)}) + ii = append(ii, [][]any{tk.PermInt(7)}) } return ii }, // concurrent execute logic. - func(ctx context.Context, tk *testkit.CTestKit, input [][]interface{}) { + func(ctx context.Context, tk *testkit.CTestKit, input [][]any) { tk.MustExec(ctx, "set @@session.tidb_batch_insert=1") tk.MustExec(ctx, "set @@session.tidb_dml_batch_size=1") _, err := tk.Exec(ctx, "insert ignore into duplicate_test(k1) values (?),(?),(?),(?),(?),(?),(?)", input[0]...) diff --git a/expression/aggregation/util_test.go b/expression/aggregation/util_test.go index 00a2f7769..7db7388da 100644 --- a/expression/aggregation/util_test.go +++ b/expression/aggregation/util_test.go @@ -17,15 +17,15 @@ func (s *testUtilSuite) TestDistinct(c *check.C) { sc := &stmtctx.StatementContext{TimeZone: time.Local} dc := createDistinctChecker(sc) tests := []struct { - vals []interface{} + vals []any expect bool }{ - {[]interface{}{1, 1}, true}, - {[]interface{}{1, 1}, false}, - {[]interface{}{1, 2}, true}, - {[]interface{}{1, 2}, false}, - {[]interface{}{1, nil}, true}, - {[]interface{}{1, nil}, false}, + {[]any{1, 1}, true}, + {[]any{1, 1}, false}, + {[]any{1, 2}, true}, + {[]any{1, 2}, false}, + {[]any{1, nil}, true}, + {[]any{1, nil}, false}, } for _, tt := range tests { d, err := dc.Check(types.MakeDatums(tt.vals...)) diff --git a/expression/bench_test.go b/expression/bench_test.go index 133639f54..022205340 100644 --- a/expression/bench_test.go +++ b/expression/bench_test.go @@ -209,7 +209,7 @@ func getRandomTime(r *rand.Rand) types.CoreTime { // dataGenerator is used to generate data for test. type dataGenerator interface { - gen() interface{} + gen() any } type defaultRandGen struct { @@ -234,7 +234,7 @@ func newDefaultGener(nullRation float64, eType types.EvalType) *defaultGener { } } -func (g *defaultGener) gen() interface{} { +func (g *defaultGener) gen() any { if g.randGen.Float64() < g.nullRation { return nil } @@ -286,7 +286,7 @@ func (g *defaultGener) gen() interface{} { // charInt64Gener is used to generate int which is equal to char's ascii type charInt64Gener struct{} -func (g *charInt64Gener) gen() interface{} { +func (g *charInt64Gener) gen() any { rand := time.Now().Nanosecond() rand = rand % 1024 return int64(rand) @@ -295,7 +295,7 @@ func (g *charInt64Gener) gen() interface{} { // charsetStringGener is used to generate "ascii" or "gbk" type charsetStringGener struct{} -func (g *charsetStringGener) gen() interface{} { +func (g *charsetStringGener) gen() any { rand := time.Now().Nanosecond() % 3 if rand == 0 { return "ascii" @@ -316,7 +316,7 @@ func newSelectStringGener(candidates []string) *selectStringGener { return &selectStringGener{candidates, newDefaultRandGen()} } -func (g *selectStringGener) gen() interface{} { +func (g *selectStringGener) gen() any { if len(g.candidates) == 0 { return nil } @@ -333,7 +333,7 @@ func newSelectRealGener(candidates []float64) *selectRealGener { return &selectRealGener{candidates, newDefaultRandGen()} } -func (g *selectRealGener) gen() interface{} { +func (g *selectRealGener) gen() any { if len(g.candidates) == 0 { return nil } @@ -344,7 +344,7 @@ type constJSONGener struct { jsonStr string } -func (g *constJSONGener) gen() interface{} { +func (g *constJSONGener) gen() any { j := new(json.BinaryJSON) if err := j.UnmarshalJSON([]byte(g.jsonStr)); err != nil { panic(err) @@ -361,7 +361,7 @@ func newDecimalJSONGener(nullRation float64) *decimalJSONGener { return &decimalJSONGener{nullRation, newDefaultRandGen()} } -func (g *decimalJSONGener) gen() interface{} { +func (g *decimalJSONGener) gen() any { if g.randGen.Float64() < g.nullRation { return nil } @@ -386,7 +386,7 @@ func newJSONStringGener() *jsonStringGener { return &jsonStringGener{newDefaultRandGen()} } -func (g *jsonStringGener) gen() interface{} { +func (g *jsonStringGener) gen() any { j := new(json.BinaryJSON) if err := j.UnmarshalJSON([]byte(fmt.Sprintf(`{"key":%v}`, g.randGen.Int()))); err != nil { panic(err) @@ -402,7 +402,7 @@ func newDecimalStringGener() *decimalStringGener { return &decimalStringGener{newDefaultRandGen()} } -func (g *decimalStringGener) gen() interface{} { +func (g *decimalStringGener) gen() any { tempDecimal := new(types.MyDecimal) if err := tempDecimal.FromFloat64(g.randGen.Float64()); err != nil { panic(err) @@ -418,7 +418,7 @@ func newRealStringGener() *realStringGener { return &realStringGener{newDefaultRandGen()} } -func (g *realStringGener) gen() interface{} { +func (g *realStringGener) gen() any { return fmt.Sprintf("%f", g.randGen.Float64()) } @@ -430,7 +430,7 @@ func newJSONTimeGener() *jsonTimeGener { return &jsonTimeGener{newDefaultRandGen()} } -func (g *jsonTimeGener) gen() interface{} { +func (g *jsonTimeGener) gen() any { tm := types.NewTime(getRandomTime(g.randGen.Rand), mysql.TypeDatetime, types.DefaultFsp) return json.CreateBinary(tm.String()) } @@ -444,7 +444,7 @@ func newRangeDurationGener(nullRation float64) *rangeDurationGener { return &rangeDurationGener{nullRation, newDefaultRandGen()} } -func (g *rangeDurationGener) gen() interface{} { +func (g *rangeDurationGener) gen() any { if g.randGen.Float64() < g.nullRation { return nil } @@ -463,7 +463,7 @@ func newTimeFormatGener(nullRation float64) *timeFormatGener { return &timeFormatGener{nullRation, newDefaultRandGen()} } -func (g *timeFormatGener) gen() interface{} { +func (g *timeFormatGener) gen() any { if g.randGen.Float64() < g.nullRation { return nil } @@ -496,7 +496,7 @@ func newRangeRealGener(begin, end, nullRation float64) *rangeRealGener { return &rangeRealGener{begin, end, nullRation, newDefaultRandGen()} } -func (g *rangeRealGener) gen() interface{} { +func (g *rangeRealGener) gen() any { if g.randGen.Float64() < g.nullRation { return nil } @@ -520,7 +520,7 @@ func newRangeDecimalGener(begin, end, nullRation float64) *rangeDecimalGener { return &rangeDecimalGener{begin, end, nullRation, newDefaultRandGen()} } -func (g *rangeDecimalGener) gen() interface{} { +func (g *rangeDecimalGener) gen() any { if g.randGen.Float64() < g.nullRation { return nil } @@ -547,7 +547,7 @@ func newRangeInt64Gener(begin, end int) *rangeInt64Gener { return &rangeInt64Gener{begin, end, newDefaultRandGen()} } -func (rig *rangeInt64Gener) gen() interface{} { +func (rig *rangeInt64Gener) gen() any { return int64(rig.randGen.Intn(rig.end-rig.begin) + rig.begin) } @@ -556,7 +556,7 @@ type numStrGener struct { rangeInt64Gener } -func (g *numStrGener) gen() interface{} { +func (g *numStrGener) gen() any { return fmt.Sprintf("%v", g.rangeInt64Gener.gen()) } @@ -565,7 +565,7 @@ type ipv6StrGener struct { randGen *defaultRandGen } -func (g *ipv6StrGener) gen() interface{} { +func (g *ipv6StrGener) gen() any { var ip net.IP = make([]byte, net.IPv6len) for i := range ip { ip[i] = uint8(g.randGen.Intn(256)) @@ -578,7 +578,7 @@ type ipv4StrGener struct { randGen *defaultRandGen } -func (g *ipv4StrGener) gen() interface{} { +func (g *ipv4StrGener) gen() any { var ip net.IP = make([]byte, net.IPv4len) for i := range ip { ip[i] = uint8(g.randGen.Intn(256)) @@ -591,7 +591,7 @@ type ipv6ByteGener struct { randGen *defaultRandGen } -func (g *ipv6ByteGener) gen() interface{} { +func (g *ipv6ByteGener) gen() any { var ip = make([]byte, net.IPv6len) for i := range ip { ip[i] = uint8(g.randGen.Intn(256)) @@ -604,7 +604,7 @@ type ipv4ByteGener struct { randGen *defaultRandGen } -func (g *ipv4ByteGener) gen() interface{} { +func (g *ipv4ByteGener) gen() any { var ip = make([]byte, net.IPv4len) for i := range ip { ip[i] = uint8(g.randGen.Intn(256)) @@ -617,7 +617,7 @@ type ipv4CompatByteGener struct { randGen *defaultRandGen } -func (g *ipv4CompatByteGener) gen() interface{} { +func (g *ipv4CompatByteGener) gen() any { var ip = make([]byte, net.IPv6len) for i := range ip { if i < 12 { @@ -634,7 +634,7 @@ type ipv4MappedByteGener struct { randGen *defaultRandGen } -func (g *ipv4MappedByteGener) gen() interface{} { +func (g *ipv4MappedByteGener) gen() any { var ip = []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0, 0, 0, 0} for i := 12; i < 16; i++ { ip[i] = uint8(g.randGen.Intn(256)) // reset the last 4 bytes @@ -653,7 +653,7 @@ func newRandLenStrGener(lenBegin, lenEnd int) *randLenStrGener { return &randLenStrGener{lenBegin, lenEnd, newDefaultRandGen()} } -func (g *randLenStrGener) gen() interface{} { +func (g *randLenStrGener) gen() any { n := g.randGen.Intn(g.lenEnd-g.lenBegin) + g.lenBegin buf := make([]byte, n) for i := range buf { @@ -679,7 +679,7 @@ func newRandHexStrGener(lenBegin, lenEnd int) *randHexStrGener { return &randHexStrGener{lenBegin, lenEnd, newDefaultRandGen()} } -func (g *randHexStrGener) gen() interface{} { +func (g *randHexStrGener) gen() any { n := g.randGen.Intn(g.lenEnd-g.lenBegin) + g.lenBegin buf := make([]byte, n) for i := range buf { @@ -710,7 +710,7 @@ func newDateTimeGener(fsp, year, month, day int) *dateTimeGener { return &dateTimeGener{fsp, year, month, day, newDefaultRandGen()} } -func (g *dateTimeGener) gen() interface{} { +func (g *dateTimeGener) gen() any { if g.Year == 0 { g.Year = 1970 + g.randGen.Intn(100) } @@ -739,7 +739,7 @@ type dateTimeStrGener struct { randGen *defaultRandGen } -func (g *dateTimeStrGener) gen() interface{} { +func (g *dateTimeStrGener) gen() any { if g.Year == 0 { g.Year = 1970 + g.randGen.Intn(100) } @@ -771,7 +771,7 @@ type dateStrGener struct { randGen *defaultRandGen } -func (g *dateStrGener) gen() interface{} { +func (g *dateStrGener) gen() any { if g.NullRation > 1e-6 && g.randGen.Float64() < g.NullRation { return nil } @@ -795,7 +795,7 @@ type timeStrGener struct { randGen *defaultRandGen } -func (g *timeStrGener) gen() interface{} { +func (g *timeStrGener) gen() any { if g.nullRation > 1e-6 && g.randGen.Float64() < g.nullRation { return nil } @@ -811,7 +811,7 @@ type dateTimeIntGener struct { nullRation float64 } -func (g *dateTimeIntGener) gen() interface{} { +func (g *dateTimeIntGener) gen() any { if g.randGen.Float64() < g.nullRation { return nil } @@ -829,7 +829,7 @@ type constStrGener struct { s string } -func (g *constStrGener) gen() interface{} { +func (g *constStrGener) gen() any { return g.s } @@ -841,7 +841,7 @@ func newRandDurInt() *randDurInt { return &randDurInt{newDefaultRandGen()} } -func (g *randDurInt) gen() interface{} { +func (g *randDurInt) gen() any { return int64(g.randGen.Intn(types.TimeMaxHour)*10000 + g.randGen.Intn(60)*100 + g.randGen.Intn(60)) } @@ -853,7 +853,7 @@ func newRandDurReal() *randDurReal { return &randDurReal{newDefaultRandGen()} } -func (g *randDurReal) gen() interface{} { +func (g *randDurReal) gen() any { return float64(g.randGen.Intn(types.TimeMaxHour)*10000 + g.randGen.Intn(60)*100 + g.randGen.Intn(60)) } @@ -865,14 +865,14 @@ func newRandDurDecimal() *randDurDecimal { return &randDurDecimal{newDefaultRandGen()} } -func (g *randDurDecimal) gen() interface{} { +func (g *randDurDecimal) gen() any { d := new(types.MyDecimal) return d.FromFloat64(float64(g.randGen.Intn(types.TimeMaxHour)*10000 + g.randGen.Intn(60)*100 + g.randGen.Intn(60))) } type randDurString struct{} -func (g *randDurString) gen() interface{} { +func (g *randDurString) gen() any { return strconv.Itoa(rand.Intn(types.TimeMaxHour)*10000 + rand.Intn(60)*100 + rand.Intn(60)) } @@ -886,7 +886,7 @@ func newLocationGener(nullRation float64) *locationGener { return &locationGener{nullRation, newDefaultRandGen()} } -func (g *locationGener) gen() interface{} { +func (g *locationGener) gen() any { if g.randGen.Float64() < g.nullRation { return nil } @@ -916,7 +916,7 @@ func newFormatGener(nullRation float64) *formatGener { return &formatGener{nullRation, newDefaultRandGen()} } -func (g *formatGener) gen() interface{} { +func (g *formatGener) gen() any { if g.randGen.Float64() < g.nullRation { return nil } @@ -944,7 +944,7 @@ func newNullWrappedGener(nullRation float64, inner dataGenerator) *nullWrappedGe return &nullWrappedGener{nullRation, inner, newDefaultRandGen()} } -func (g *nullWrappedGener) gen() interface{} { +func (g *nullWrappedGener) gen() any { if g.randGen.Float64() < g.nullRation { return nil } diff --git a/expression/builtin_arithmetic_test.go b/expression/builtin_arithmetic_test.go index df54f479b..be5ab7a92 100644 --- a/expression/builtin_arithmetic_test.go +++ b/expression/builtin_arithmetic_test.go @@ -116,7 +116,7 @@ func (s *testEvaluatorSuite) TestSetFlenDecimal4Int(c *C) { func (s *testEvaluatorSuite) TestArithmeticPlus(c *C) { // case: 1 - args := []interface{}{int64(12), int64(1)} + args := []any{int64(12), int64(1)} bf, err := funcs[ast.Plus].getFunction(s.ctx, s.datumsToConstants(types.MakeDatums(args...))) c.Assert(err, IsNil) @@ -131,7 +131,7 @@ func (s *testEvaluatorSuite) TestArithmeticPlus(c *C) { c.Assert(intResult, Equals, int64(13)) // case 2 - args = []interface{}{float64(1.01001), float64(-0.01)} + args = []any{float64(1.01001), float64(-0.01)} bf, err = funcs[ast.Plus].getFunction(s.ctx, s.datumsToConstants(types.MakeDatums(args...))) c.Assert(err, IsNil) @@ -146,7 +146,7 @@ func (s *testEvaluatorSuite) TestArithmeticPlus(c *C) { c.Assert(realResult, Equals, float64(1.00001)) // case 3 - args = []interface{}{nil, float64(-0.11101)} + args = []any{nil, float64(-0.11101)} bf, err = funcs[ast.Plus].getFunction(s.ctx, s.datumsToConstants(types.MakeDatums(args...))) c.Assert(err, IsNil) @@ -161,7 +161,7 @@ func (s *testEvaluatorSuite) TestArithmeticPlus(c *C) { c.Assert(realResult, Equals, float64(0)) // case 4 - args = []interface{}{nil, nil} + args = []any{nil, nil} bf, err = funcs[ast.Plus].getFunction(s.ctx, s.datumsToConstants(types.MakeDatums(args...))) c.Assert(err, IsNil) @@ -178,7 +178,7 @@ func (s *testEvaluatorSuite) TestArithmeticPlus(c *C) { // case 5 hexStr, err := types.ParseHexStr("0x20000000000000") c.Assert(err, IsNil) - args = []interface{}{hexStr, int64(1)} + args = []any{hexStr, int64(1)} bf, err = funcs[ast.Plus].getFunction(s.ctx, s.datumsToConstants(types.MakeDatums(args...))) c.Assert(err, IsNil) @@ -194,7 +194,7 @@ func (s *testEvaluatorSuite) TestArithmeticPlus(c *C) { func (s *testEvaluatorSuite) TestArithmeticMinus(c *C) { // case: 1 - args := []interface{}{int64(12), int64(1)} + args := []any{int64(12), int64(1)} bf, err := funcs[ast.Minus].getFunction(s.ctx, s.datumsToConstants(types.MakeDatums(args...))) c.Assert(err, IsNil) @@ -209,7 +209,7 @@ func (s *testEvaluatorSuite) TestArithmeticMinus(c *C) { c.Assert(intResult, Equals, int64(11)) // case 2 - args = []interface{}{float64(1.01001), float64(-0.01)} + args = []any{float64(1.01001), float64(-0.01)} bf, err = funcs[ast.Minus].getFunction(s.ctx, s.datumsToConstants(types.MakeDatums(args...))) c.Assert(err, IsNil) @@ -224,7 +224,7 @@ func (s *testEvaluatorSuite) TestArithmeticMinus(c *C) { c.Assert(realResult, Equals, float64(1.02001)) // case 3 - args = []interface{}{nil, float64(-0.11101)} + args = []any{nil, float64(-0.11101)} bf, err = funcs[ast.Minus].getFunction(s.ctx, s.datumsToConstants(types.MakeDatums(args...))) c.Assert(err, IsNil) @@ -239,7 +239,7 @@ func (s *testEvaluatorSuite) TestArithmeticMinus(c *C) { c.Assert(realResult, Equals, float64(0)) // case 4 - args = []interface{}{float64(1.01), nil} + args = []any{float64(1.01), nil} bf, err = funcs[ast.Minus].getFunction(s.ctx, s.datumsToConstants(types.MakeDatums(args...))) c.Assert(err, IsNil) @@ -254,7 +254,7 @@ func (s *testEvaluatorSuite) TestArithmeticMinus(c *C) { c.Assert(realResult, Equals, float64(0)) // case 5 - args = []interface{}{nil, nil} + args = []any{nil, nil} bf, err = funcs[ast.Minus].getFunction(s.ctx, s.datumsToConstants(types.MakeDatums(args...))) c.Assert(err, IsNil) @@ -271,32 +271,32 @@ func (s *testEvaluatorSuite) TestArithmeticMinus(c *C) { func (s *testEvaluatorSuite) TestArithmeticMultiply(c *C) { testCases := []struct { - args []interface{} - expect interface{} + args []any + expect any err error }{ { - args: []interface{}{int64(11), int64(11)}, + args: []any{int64(11), int64(11)}, expect: int64(121), }, { - args: []interface{}{uint64(11), uint64(11)}, + args: []any{uint64(11), uint64(11)}, expect: int64(121), }, { - args: []interface{}{float64(11), float64(11)}, + args: []any{float64(11), float64(11)}, expect: float64(121), }, { - args: []interface{}{nil, float64(-0.11101)}, + args: []any{nil, float64(-0.11101)}, expect: nil, }, { - args: []interface{}{float64(1.01), nil}, + args: []any{float64(1.01), nil}, expect: nil, }, { - args: []interface{}{nil, nil}, + args: []any{nil, nil}, expect: nil, }, } @@ -313,51 +313,51 @@ func (s *testEvaluatorSuite) TestArithmeticMultiply(c *C) { func (s *testEvaluatorSuite) TestArithmeticDivide(c *C) { testCases := []struct { - args []interface{} - expect interface{} + args []any + expect any }{ { - args: []interface{}{float64(11.1111111), float64(11.1)}, + args: []any{float64(11.1111111), float64(11.1)}, expect: float64(1.001001), }, { - args: []interface{}{float64(11.1111111), float64(0)}, + args: []any{float64(11.1111111), float64(0)}, expect: nil, }, { - args: []interface{}{int64(11), int64(11)}, + args: []any{int64(11), int64(11)}, expect: float64(1), }, { - args: []interface{}{int64(11), int64(2)}, + args: []any{int64(11), int64(2)}, expect: float64(5.5), }, { - args: []interface{}{int64(11), int64(0)}, + args: []any{int64(11), int64(0)}, expect: nil, }, { - args: []interface{}{uint64(11), uint64(11)}, + args: []any{uint64(11), uint64(11)}, expect: float64(1), }, { - args: []interface{}{uint64(11), uint64(2)}, + args: []any{uint64(11), uint64(2)}, expect: float64(5.5), }, { - args: []interface{}{uint64(11), uint64(0)}, + args: []any{uint64(11), uint64(0)}, expect: nil, }, { - args: []interface{}{nil, float64(-0.11101)}, + args: []any{nil, float64(-0.11101)}, expect: nil, }, { - args: []interface{}{float64(1.01), nil}, + args: []any{float64(1.01), nil}, expect: nil, }, { - args: []interface{}{nil, nil}, + args: []any{nil, nil}, expect: nil, }, } @@ -380,100 +380,100 @@ func (s *testEvaluatorSuite) TestArithmeticDivide(c *C) { func (s *testEvaluatorSuite) TestArithmeticIntDivide(c *C) { testCases := []struct { - args []interface{} - expect []interface{} + args []any + expect []any }{ { - args: []interface{}{int64(13), int64(11)}, - expect: []interface{}{int64(1), nil}, + args: []any{int64(13), int64(11)}, + expect: []any{int64(1), nil}, }, { - args: []interface{}{int64(-13), int64(11)}, - expect: []interface{}{int64(-1), nil}, + args: []any{int64(-13), int64(11)}, + expect: []any{int64(-1), nil}, }, { - args: []interface{}{int64(13), int64(-11)}, - expect: []interface{}{int64(-1), nil}, + args: []any{int64(13), int64(-11)}, + expect: []any{int64(-1), nil}, }, { - args: []interface{}{int64(-13), int64(-11)}, - expect: []interface{}{int64(1), nil}, + args: []any{int64(-13), int64(-11)}, + expect: []any{int64(1), nil}, }, { - args: []interface{}{int64(33), int64(11)}, - expect: []interface{}{int64(3), nil}, + args: []any{int64(33), int64(11)}, + expect: []any{int64(3), nil}, }, { - args: []interface{}{int64(-33), int64(11)}, - expect: []interface{}{int64(-3), nil}, + args: []any{int64(-33), int64(11)}, + expect: []any{int64(-3), nil}, }, { - args: []interface{}{int64(33), int64(-11)}, - expect: []interface{}{int64(-3), nil}, + args: []any{int64(33), int64(-11)}, + expect: []any{int64(-3), nil}, }, { - args: []interface{}{int64(-33), int64(-11)}, - expect: []interface{}{int64(3), nil}, + args: []any{int64(-33), int64(-11)}, + expect: []any{int64(3), nil}, }, { - args: []interface{}{int64(11), int64(0)}, - expect: []interface{}{nil, nil}, + args: []any{int64(11), int64(0)}, + expect: []any{nil, nil}, }, { - args: []interface{}{int64(-11), int64(0)}, - expect: []interface{}{nil, nil}, + args: []any{int64(-11), int64(0)}, + expect: []any{nil, nil}, }, { - args: []interface{}{float64(11.01), float64(1.1)}, - expect: []interface{}{int64(10), nil}, + args: []any{float64(11.01), float64(1.1)}, + expect: []any{int64(10), nil}, }, { - args: []interface{}{float64(-11.01), float64(1.1)}, - expect: []interface{}{int64(-10), nil}, + args: []any{float64(-11.01), float64(1.1)}, + expect: []any{int64(-10), nil}, }, { - args: []interface{}{float64(11.01), float64(-1.1)}, - expect: []interface{}{int64(-10), nil}, + args: []any{float64(11.01), float64(-1.1)}, + expect: []any{int64(-10), nil}, }, { - args: []interface{}{float64(-11.01), float64(-1.1)}, - expect: []interface{}{int64(10), nil}, + args: []any{float64(-11.01), float64(-1.1)}, + expect: []any{int64(10), nil}, }, { - args: []interface{}{nil, float64(-0.11101)}, - expect: []interface{}{nil, nil}, + args: []any{nil, float64(-0.11101)}, + expect: []any{nil, nil}, }, { - args: []interface{}{float64(1.01), nil}, - expect: []interface{}{nil, nil}, + args: []any{float64(1.01), nil}, + expect: []any{nil, nil}, }, { - args: []interface{}{nil, int64(-1001)}, - expect: []interface{}{nil, nil}, + args: []any{nil, int64(-1001)}, + expect: []any{nil, nil}, }, { - args: []interface{}{int64(101), nil}, - expect: []interface{}{nil, nil}, + args: []any{int64(101), nil}, + expect: []any{nil, nil}, }, { - args: []interface{}{nil, nil}, - expect: []interface{}{nil, nil}, + args: []any{nil, nil}, + expect: []any{nil, nil}, }, { - args: []interface{}{float64(123456789100000.0), float64(-0.00001)}, - expect: []interface{}{nil, "*BIGINT value is out of range in '\\(123456789100000 DIV -0.00001\\)'"}, + args: []any{float64(123456789100000.0), float64(-0.00001)}, + expect: []any{nil, "*BIGINT value is out of range in '\\(123456789100000 DIV -0.00001\\)'"}, }, { - args: []interface{}{int64(-9223372036854775808), float64(-1)}, - expect: []interface{}{nil, "*BIGINT value is out of range in '\\(-9223372036854775808 DIV -1\\)'"}, + args: []any{int64(-9223372036854775808), float64(-1)}, + expect: []any{nil, "*BIGINT value is out of range in '\\(-9223372036854775808 DIV -1\\)'"}, }, { - args: []interface{}{uint64(1), float64(-2)}, - expect: []interface{}{0, nil}, + args: []any{uint64(1), float64(-2)}, + expect: []any{0, nil}, }, { - args: []interface{}{uint64(1), float64(-1)}, - expect: []interface{}{nil, "*BIGINT UNSIGNED value is out of range in '\\(1 DIV -1\\)'"}, + args: []any{uint64(1), float64(-1)}, + expect: []any{nil, "*BIGINT UNSIGNED value is out of range in '\\(1 DIV -1\\)'"}, }, } @@ -493,99 +493,99 @@ func (s *testEvaluatorSuite) TestArithmeticIntDivide(c *C) { func (s *testEvaluatorSuite) TestArithmeticMod(c *C) { testCases := []struct { - args []interface{} - expect interface{} + args []any + expect any }{ { - args: []interface{}{int64(13), int64(11)}, + args: []any{int64(13), int64(11)}, expect: int64(2), }, { - args: []interface{}{int64(-13), int64(11)}, + args: []any{int64(-13), int64(11)}, expect: int64(-2), }, { - args: []interface{}{int64(13), int64(-11)}, + args: []any{int64(13), int64(-11)}, expect: int64(2), }, { - args: []interface{}{int64(-13), int64(-11)}, + args: []any{int64(-13), int64(-11)}, expect: int64(-2), }, { - args: []interface{}{int64(33), int64(11)}, + args: []any{int64(33), int64(11)}, expect: int64(0), }, { - args: []interface{}{int64(-33), int64(11)}, + args: []any{int64(-33), int64(11)}, expect: int64(0), }, { - args: []interface{}{int64(33), int64(-11)}, + args: []any{int64(33), int64(-11)}, expect: int64(0), }, { - args: []interface{}{int64(-33), int64(-11)}, + args: []any{int64(-33), int64(-11)}, expect: int64(0), }, { - args: []interface{}{int64(11), int64(0)}, + args: []any{int64(11), int64(0)}, expect: nil, }, { - args: []interface{}{int64(-11), int64(0)}, + args: []any{int64(-11), int64(0)}, expect: nil, }, { - args: []interface{}{int64(1), float64(1.1)}, + args: []any{int64(1), float64(1.1)}, expect: float64(1), }, { - args: []interface{}{int64(-1), float64(1.1)}, + args: []any{int64(-1), float64(1.1)}, expect: float64(-1), }, { - args: []interface{}{int64(1), float64(-1.1)}, + args: []any{int64(1), float64(-1.1)}, expect: float64(1), }, { - args: []interface{}{int64(-1), float64(-1.1)}, + args: []any{int64(-1), float64(-1.1)}, expect: float64(-1), }, { - args: []interface{}{nil, float64(-0.11101)}, + args: []any{nil, float64(-0.11101)}, expect: nil, }, { - args: []interface{}{float64(1.01), nil}, + args: []any{float64(1.01), nil}, expect: nil, }, { - args: []interface{}{nil, int64(-1001)}, + args: []any{nil, int64(-1001)}, expect: nil, }, { - args: []interface{}{int64(101), nil}, + args: []any{int64(101), nil}, expect: nil, }, { - args: []interface{}{nil, nil}, + args: []any{nil, nil}, expect: nil, }, { - args: []interface{}{"1231", 12}, + args: []any{"1231", 12}, expect: 7, }, { - args: []interface{}{"1231", "12"}, + args: []any{"1231", "12"}, expect: float64(7), }, { - args: []interface{}{types.Duration{Duration: 45296 * time.Second}, 122}, + args: []any{types.Duration{Duration: 45296 * time.Second}, 122}, expect: 114, }, { - args: []interface{}{types.Set{Value: 7, Name: "abc"}, "12"}, + args: []any{types.Set{Value: 7, Name: "abc"}, "12"}, expect: float64(7), }, } diff --git a/expression/builtin_cast_vec_test.go b/expression/builtin_cast_vec_test.go index 1fbf9380d..118874fb2 100644 --- a/expression/builtin_cast_vec_test.go +++ b/expression/builtin_cast_vec_test.go @@ -108,7 +108,7 @@ type dateTimeGenerWithFsp struct { fsp int8 } -func (g *dateTimeGenerWithFsp) gen() interface{} { +func (g *dateTimeGenerWithFsp) gen() any { result := g.defaultGener.gen() if t, ok := result.(types.Time); ok { t.SetFsp(g.fsp) @@ -119,7 +119,7 @@ func (g *dateTimeGenerWithFsp) gen() interface{} { type randJSONDuration struct{} -func (g *randJSONDuration) gen() interface{} { +func (g *randJSONDuration) gen() any { d := types.Duration{ Duration: time.Duration(rand.Intn(12))*time.Hour + time.Duration(rand.Intn(60))*time.Minute + time.Duration(rand.Intn(60))*time.Second + time.Duration(rand.Intn(1000))*time.Millisecond, Fsp: 3} @@ -128,7 +128,7 @@ func (g *randJSONDuration) gen() interface{} { type datetimeJSONGener struct{} -func (g *datetimeJSONGener) gen() interface{} { +func (g *datetimeJSONGener) gen() any { year := rand.Intn(2200) month := rand.Intn(10) + 1 day := rand.Intn(20) + 1 diff --git a/expression/builtin_compare_test.go b/expression/builtin_compare_test.go index 8f3516c65..49acb5f77 100644 --- a/expression/builtin_compare_test.go +++ b/expression/builtin_compare_test.go @@ -86,8 +86,8 @@ func (s *testEvaluatorSuite) TestCompare(c *C) { jsonVal := json.CreateBinary("123") // test cases for generating function signatures. tests := []struct { - arg0 interface{} - arg1 interface{} + arg0 any + arg1 any funcName string tp byte expected int64 @@ -134,7 +134,7 @@ func (s *testEvaluatorSuite) TestCompare(c *C) { } for _, t := range tests { - bf, err := funcs[t.funcName].getFunction(s.ctx, s.primitiveValsToConstants([]interface{}{t.arg0, t.arg1})) + bf, err := funcs[t.funcName].getFunction(s.ctx, s.primitiveValsToConstants([]any{t.arg0, t.arg1})) c.Assert(err, IsNil) args := bf.getArgs() c.Assert(args[0].GetType().Tp, Equals, t.tp) @@ -164,23 +164,23 @@ func (s *testEvaluatorSuite) TestCompare(c *C) { func (s *testEvaluatorSuite) TestCoalesce(c *C) { cases := []struct { - args []interface{} - expected interface{} + args []any + expected any isNil bool getErr bool }{ - {[]interface{}{nil}, nil, true, false}, - {[]interface{}{nil, nil}, nil, true, false}, - {[]interface{}{nil, nil, nil}, nil, true, false}, - {[]interface{}{nil, 1}, int64(1), false, false}, - {[]interface{}{nil, 1.1}, float64(1.1), false, false}, - {[]interface{}{1, 1.1}, float64(1), false, false}, - {[]interface{}{nil, types.NewDecFromFloatForTest(123.456)}, types.NewDecFromFloatForTest(123.456), false, false}, - {[]interface{}{1, types.NewDecFromFloatForTest(123.456)}, types.NewDecFromInt(1), false, false}, - {[]interface{}{nil, duration}, duration, false, false}, - {[]interface{}{nil, tm, nil}, tm, false, false}, - {[]interface{}{nil, dt, nil}, dt, false, false}, - {[]interface{}{tm, dt}, tm, false, false}, + {[]any{nil}, nil, true, false}, + {[]any{nil, nil}, nil, true, false}, + {[]any{nil, nil, nil}, nil, true, false}, + {[]any{nil, 1}, int64(1), false, false}, + {[]any{nil, 1.1}, float64(1.1), false, false}, + {[]any{1, 1.1}, float64(1), false, false}, + {[]any{nil, types.NewDecFromFloatForTest(123.456)}, types.NewDecFromFloatForTest(123.456), false, false}, + {[]any{1, types.NewDecFromFloatForTest(123.456)}, types.NewDecFromInt(1), false, false}, + {[]any{nil, duration}, duration, false, false}, + {[]any{nil, tm, nil}, tm, false, false}, + {[]any{nil, dt, nil}, dt, false, false}, + {[]any{tm, dt}, tm, false, false}, } for _, t := range cases { @@ -264,42 +264,42 @@ func (s *testEvaluatorSuite) TestGreatestLeastFuncs(c *C) { }() for _, t := range []struct { - args []interface{} - expectedGreatest interface{} - expectedLeast interface{} + args []any + expectedGreatest any + expectedLeast any isNil bool getErr bool }{ { - []interface{}{1, 2, 3, 4}, + []any{1, 2, 3, 4}, int64(4), int64(1), false, false, }, { - []interface{}{"a", "b", "c"}, + []any{"a", "b", "c"}, "c", "a", false, false, }, { - []interface{}{"123a", "b", "c", 12}, + []any{"123a", "b", "c", 12}, float64(123), float64(0), false, false, }, { - []interface{}{tm, "123"}, + []any{tm, "123"}, curTimeString, "123", false, false, }, { - []interface{}{tm, 123}, + []any{tm, 123}, curTimeInt, int64(123), false, false, }, { - []interface{}{duration, "123"}, + []any{duration, "123"}, "12:59:59", "123", false, false, }, { - []interface{}{"123", nil, "123"}, + []any{"123", nil, "123"}, nil, nil, true, false, }, { - []interface{}{errors.New("must error"), 123}, + []any{errors.New("must error"), 123}, nil, nil, false, true, }, } { diff --git a/expression/builtin_control_test.go b/expression/builtin_control_test.go index 6ea1655e1..9d7328b57 100644 --- a/expression/builtin_control_test.go +++ b/expression/builtin_control_test.go @@ -26,20 +26,20 @@ import ( func (s *testEvaluatorSuite) TestCaseWhen(c *C) { tbl := []struct { - Arg []interface{} - Ret interface{} + Arg []any + Ret any }{ - {[]interface{}{true, 1, true, 2, 3}, 1}, - {[]interface{}{false, 1, true, 2, 3}, 2}, - {[]interface{}{nil, 1, true, 2, 3}, 2}, - {[]interface{}{false, 1, false, 2, 3}, 3}, - {[]interface{}{nil, 1, nil, 2, 3}, 3}, - {[]interface{}{false, 1, nil, 2, 3}, 3}, - {[]interface{}{nil, 1, false, 2, 3}, 3}, - {[]interface{}{1, jsonInt.GetMysqlJSON(), nil}, 3}, - {[]interface{}{0, jsonInt.GetMysqlJSON(), nil}, nil}, - {[]interface{}{0.1, 1, 2}, 1}, - {[]interface{}{0.0, 1, 0.1, 2}, 2}, + {[]any{true, 1, true, 2, 3}, 1}, + {[]any{false, 1, true, 2, 3}, 2}, + {[]any{nil, 1, true, 2, 3}, 2}, + {[]any{false, 1, false, 2, 3}, 3}, + {[]any{nil, 1, nil, 2, 3}, 3}, + {[]any{false, 1, nil, 2, 3}, 3}, + {[]any{nil, 1, false, 2, 3}, 3}, + {[]any{1, jsonInt.GetMysqlJSON(), nil}, 3}, + {[]any{0, jsonInt.GetMysqlJSON(), nil}, nil}, + {[]any{0.1, 1, 2}, 1}, + {[]any{0.0, 1, 0.1, 2}, 2}, } fc := funcs[ast.Case] for _, t := range tbl { @@ -63,10 +63,10 @@ func (s *testEvaluatorSuite) TestIf(c *C) { stmtCtx.IgnoreTruncate = origin }() tbl := []struct { - Arg1 interface{} - Arg2 interface{} - Arg3 interface{} - Ret interface{} + Arg1 any + Arg2 any + Arg3 any + Ret any }{ {1, 1, 2, 1}, {nil, 1, 2, 2}, @@ -104,9 +104,9 @@ func (s *testEvaluatorSuite) TestIf(c *C) { func (s *testEvaluatorSuite) TestIfNull(c *C) { tbl := []struct { - arg1 interface{} - arg2 interface{} - expected interface{} + arg1 any + arg2 any + expected any isNil bool getErr bool }{ @@ -124,7 +124,7 @@ func (s *testEvaluatorSuite) TestIfNull(c *C) { } for _, t := range tbl { - f, err := newFunctionForTest(s.ctx, ast.Ifnull, s.primitiveValsToConstants([]interface{}{t.arg1, t.arg2})...) + f, err := newFunctionForTest(s.ctx, ast.Ifnull, s.primitiveValsToConstants([]any{t.arg1, t.arg2})...) c.Assert(err, IsNil) d, err := f.Eval(chunk.Row{}) if t.getErr { diff --git a/expression/builtin_control_vec_generated_test.go b/expression/builtin_control_vec_generated_test.go index 74b77b504..d26074d96 100644 --- a/expression/builtin_control_vec_generated_test.go +++ b/expression/builtin_control_vec_generated_test.go @@ -31,7 +31,7 @@ type controlIntGener struct { defaultGener } -func (g *controlIntGener) gen() interface{} { +func (g *controlIntGener) gen() any { if rand.Float64() < g.zeroRation { return int64(0) } diff --git a/expression/builtin_encryption_test.go b/expression/builtin_encryption_test.go index c3b7f3487..0223303a2 100644 --- a/expression/builtin_encryption_test.go +++ b/expression/builtin_encryption_test.go @@ -30,9 +30,9 @@ import ( ) var cryptTests = []struct { - origin interface{} - password interface{} - crypt interface{} + origin any + password any + crypt any }{ {"", "", ""}, {"pingcap", "1234567890123456", "2C35B5A4ADF391"}, @@ -81,40 +81,40 @@ func (s *testEvaluatorSuite) TestSQLEncode(c *C) { var aesTests = []struct { mode string - origin interface{} - params []interface{} - crypt interface{} + origin any + params []any + crypt any }{ // test for ecb - {"aes-128-ecb", "pingcap", []interface{}{"1234567890123456"}, "697BFE9B3F8C2F289DD82C88C7BC95C4"}, - {"aes-128-ecb", "pingcap123", []interface{}{"1234567890123456"}, "CEC348F4EF5F84D3AA6C4FA184C65766"}, - {"aes-128-ecb", "pingcap", []interface{}{"123456789012345678901234"}, "6F1589686860C8E8C7A40A78B25FF2C0"}, - {"aes-128-ecb", "pingcap", []interface{}{"123"}, "996E0CA8688D7AD20819B90B273E01C6"}, - {"aes-128-ecb", "pingcap", []interface{}{123}, "996E0CA8688D7AD20819B90B273E01C6"}, - {"aes-128-ecb", nil, []interface{}{123}, nil}, - {"aes-192-ecb", "pingcap", []interface{}{"1234567890123456"}, "9B139FD002E6496EA2D5C73A2265E661"}, - {"aes-256-ecb", "pingcap", []interface{}{"1234567890123456"}, "F80DCDEDDBE5663BDB68F74AEDDB8EE3"}, + {"aes-128-ecb", "pingcap", []any{"1234567890123456"}, "697BFE9B3F8C2F289DD82C88C7BC95C4"}, + {"aes-128-ecb", "pingcap123", []any{"1234567890123456"}, "CEC348F4EF5F84D3AA6C4FA184C65766"}, + {"aes-128-ecb", "pingcap", []any{"123456789012345678901234"}, "6F1589686860C8E8C7A40A78B25FF2C0"}, + {"aes-128-ecb", "pingcap", []any{"123"}, "996E0CA8688D7AD20819B90B273E01C6"}, + {"aes-128-ecb", "pingcap", []any{123}, "996E0CA8688D7AD20819B90B273E01C6"}, + {"aes-128-ecb", nil, []any{123}, nil}, + {"aes-192-ecb", "pingcap", []any{"1234567890123456"}, "9B139FD002E6496EA2D5C73A2265E661"}, + {"aes-256-ecb", "pingcap", []any{"1234567890123456"}, "F80DCDEDDBE5663BDB68F74AEDDB8EE3"}, // test for cbc - {"aes-128-cbc", "pingcap", []interface{}{"1234567890123456", "1234567890123456"}, "2ECA0077C5EA5768A0485AA522774792"}, - {"aes-128-cbc", "pingcap", []interface{}{"123456789012345678901234", "1234567890123456"}, "483788634DA8817423BA0934FD2C096E"}, - {"aes-192-cbc", "pingcap", []interface{}{"1234567890123456", "1234567890123456"}, "516391DB38E908ECA93AAB22870EC787"}, - {"aes-256-cbc", "pingcap", []interface{}{"1234567890123456", "1234567890123456"}, "5D0E22C1E77523AEF5C3E10B65653C8F"}, - {"aes-256-cbc", "pingcap", []interface{}{"12345678901234561234567890123456", "1234567890123456"}, "A26BA27CA4BE9D361D545AA84A17002D"}, - {"aes-256-cbc", "pingcap", []interface{}{"1234567890123456", "12345678901234561234567890123456"}, "5D0E22C1E77523AEF5C3E10B65653C8F"}, + {"aes-128-cbc", "pingcap", []any{"1234567890123456", "1234567890123456"}, "2ECA0077C5EA5768A0485AA522774792"}, + {"aes-128-cbc", "pingcap", []any{"123456789012345678901234", "1234567890123456"}, "483788634DA8817423BA0934FD2C096E"}, + {"aes-192-cbc", "pingcap", []any{"1234567890123456", "1234567890123456"}, "516391DB38E908ECA93AAB22870EC787"}, + {"aes-256-cbc", "pingcap", []any{"1234567890123456", "1234567890123456"}, "5D0E22C1E77523AEF5C3E10B65653C8F"}, + {"aes-256-cbc", "pingcap", []any{"12345678901234561234567890123456", "1234567890123456"}, "A26BA27CA4BE9D361D545AA84A17002D"}, + {"aes-256-cbc", "pingcap", []any{"1234567890123456", "12345678901234561234567890123456"}, "5D0E22C1E77523AEF5C3E10B65653C8F"}, // test for ofb - {"aes-128-ofb", "pingcap", []interface{}{"1234567890123456", "1234567890123456"}, "0515A36BBF3DE0"}, - {"aes-128-ofb", "pingcap", []interface{}{"123456789012345678901234", "1234567890123456"}, "C2A93A93818546"}, - {"aes-192-ofb", "pingcap", []interface{}{"1234567890123456", "1234567890123456"}, "FE09DCCF14D458"}, - {"aes-256-ofb", "pingcap", []interface{}{"1234567890123456", "1234567890123456"}, "2E70FCAC0C0834"}, - {"aes-256-ofb", "pingcap", []interface{}{"12345678901234561234567890123456", "1234567890123456"}, "83E2B30A71F011"}, - {"aes-256-ofb", "pingcap", []interface{}{"1234567890123456", "12345678901234561234567890123456"}, "2E70FCAC0C0834"}, + {"aes-128-ofb", "pingcap", []any{"1234567890123456", "1234567890123456"}, "0515A36BBF3DE0"}, + {"aes-128-ofb", "pingcap", []any{"123456789012345678901234", "1234567890123456"}, "C2A93A93818546"}, + {"aes-192-ofb", "pingcap", []any{"1234567890123456", "1234567890123456"}, "FE09DCCF14D458"}, + {"aes-256-ofb", "pingcap", []any{"1234567890123456", "1234567890123456"}, "2E70FCAC0C0834"}, + {"aes-256-ofb", "pingcap", []any{"12345678901234561234567890123456", "1234567890123456"}, "83E2B30A71F011"}, + {"aes-256-ofb", "pingcap", []any{"1234567890123456", "12345678901234561234567890123456"}, "2E70FCAC0C0834"}, // test for cfb - {"aes-128-cfb", "pingcap", []interface{}{"1234567890123456", "1234567890123456"}, "0515A36BBF3DE0"}, - {"aes-128-cfb", "pingcap", []interface{}{"123456789012345678901234", "1234567890123456"}, "C2A93A93818546"}, - {"aes-192-cfb", "pingcap", []interface{}{"1234567890123456", "1234567890123456"}, "FE09DCCF14D458"}, - {"aes-256-cfb", "pingcap", []interface{}{"1234567890123456", "1234567890123456"}, "2E70FCAC0C0834"}, - {"aes-256-cfb", "pingcap", []interface{}{"12345678901234561234567890123456", "1234567890123456"}, "83E2B30A71F011"}, - {"aes-256-cfb", "pingcap", []interface{}{"1234567890123456", "12345678901234561234567890123456"}, "2E70FCAC0C0834"}, + {"aes-128-cfb", "pingcap", []any{"1234567890123456", "1234567890123456"}, "0515A36BBF3DE0"}, + {"aes-128-cfb", "pingcap", []any{"123456789012345678901234", "1234567890123456"}, "C2A93A93818546"}, + {"aes-192-cfb", "pingcap", []any{"1234567890123456", "1234567890123456"}, "FE09DCCF14D458"}, + {"aes-256-cfb", "pingcap", []any{"1234567890123456", "1234567890123456"}, "2E70FCAC0C0834"}, + {"aes-256-cfb", "pingcap", []any{"12345678901234561234567890123456", "1234567890123456"}, "83E2B30A71F011"}, + {"aes-256-cfb", "pingcap", []any{"1234567890123456", "12345678901234561234567890123456"}, "2E70FCAC0C0834"}, } func (s *testEvaluatorSuite) TestAESEncrypt(c *C) { @@ -208,7 +208,7 @@ func toHex(d types.Datum) (h types.Datum) { return } -func fromHex(str interface{}) (d types.Datum) { +func fromHex(str any) (d types.Datum) { if str == nil { return } @@ -220,7 +220,7 @@ func fromHex(str interface{}) (d types.Datum) { } var sha1Tests = []struct { - origin interface{} + origin any crypt string }{ {"test", "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3"}, @@ -251,9 +251,9 @@ func (s *testEvaluatorSuite) TestSha1Hash(c *C) { } var sha2Tests = []struct { - origin interface{} - hashLength interface{} - crypt interface{} + origin any + hashLength any + crypt any validCase bool }{ {"pingcap", 0, "2871823be240f8ecd1d72f24c99eaa2e58af18b4b8ba99a4fc2823ba5c43930a", true}, @@ -292,7 +292,7 @@ func (s *testEvaluatorSuite) TestSha2Hash(c *C) { func (s *testEvaluatorSuite) TestMD5Hash(c *C) { cases := []struct { - args interface{} + args any expected string isNil bool getErr bool @@ -307,7 +307,7 @@ func (s *testEvaluatorSuite) TestMD5Hash(c *C) { {nil, "", true, false}, } for _, t := range cases { - f, err := newFunctionForTest(s.ctx, ast.MD5, s.primitiveValsToConstants([]interface{}{t.args})...) + f, err := newFunctionForTest(s.ctx, ast.MD5, s.primitiveValsToConstants([]any{t.args})...) c.Assert(err, IsNil) d, err := f.Eval(chunk.Row{}) if t.getErr { @@ -364,8 +364,8 @@ func decodeHex(str string) []byte { func (s *testEvaluatorSuite) TestCompress(c *C) { tests := []struct { - in interface{} - expect interface{} + in any + expect any }{ {"hello world", string(decodeHex("0B000000789CCA48CDC9C95728CF2FCA4901040000FFFF1A0B045D"))}, {"", ""}, @@ -389,8 +389,8 @@ func (s *testEvaluatorSuite) TestCompress(c *C) { func (s *testEvaluatorSuite) TestUncompress(c *C) { tests := []struct { - in interface{} - expect interface{} + in any + expect any }{ {decodeHex("0B000000789CCB48CDC9C95728CF2FCA4901001A0B045D"), "hello world"}, // zlib result from MySQL {decodeHex("0B000000789CCA48CDC9C95728CF2FCA4901040000FFFF1A0B045D"), "hello world"}, // zlib result from TiDB @@ -423,8 +423,8 @@ func (s *testEvaluatorSuite) TestUncompress(c *C) { func (s *testEvaluatorSuite) TestUncompressLength(c *C) { tests := []struct { - in interface{} - expect interface{} + in any + expect any }{ {decodeHex("0B000000789CCB48CDC9C95728CF2FCA4901001A0B045D"), int64(11)}, // zlib result from MySQL {decodeHex("0B000000789CCA48CDC9C95728CF2FCA4901040000FFFF1A0B045D"), int64(11)}, // zlib result from TiDB @@ -452,7 +452,7 @@ func (s *testEvaluatorSuite) TestUncompressLength(c *C) { func (s *testEvaluatorSuite) TestPassword(c *C) { cases := []struct { - args interface{} + args any expected string isNil bool getErr bool @@ -468,7 +468,7 @@ func (s *testEvaluatorSuite) TestPassword(c *C) { warnCount := len(s.ctx.GetSessionVars().StmtCtx.GetWarnings()) for _, t := range cases { - f, err := newFunctionForTest(s.ctx, ast.PasswordFunc, s.primitiveValsToConstants([]interface{}{t.args})...) + f, err := newFunctionForTest(s.ctx, ast.PasswordFunc, s.primitiveValsToConstants([]any{t.args})...) c.Assert(err, IsNil) d, err := f.Eval(chunk.Row{}) c.Assert(err, IsNil) diff --git a/expression/builtin_encryption_vec.go b/expression/builtin_encryption_vec.go index 61ae46444..b400d3add 100644 --- a/expression/builtin_encryption_vec.go +++ b/expression/builtin_encryption_vec.go @@ -522,7 +522,7 @@ func (b *builtinCompressSig) vectorized() bool { var ( defaultByteSliceSize = 1024 bytePool = sync.Pool{ - New: func() interface{} { + New: func() any { return make([]byte, defaultByteSliceSize) }, } diff --git a/expression/builtin_info_test.go b/expression/builtin_info_test.go index 54f5305a8..d0216ad61 100644 --- a/expression/builtin_info_test.go +++ b/expression/builtin_info_test.go @@ -138,7 +138,7 @@ func (s *testEvaluatorSuite) TestVersion(c *C) { func (s *testEvaluatorSuite) TestBenchMark(c *C) { cases := []struct { LoopCount int - Expression interface{} + Expression any Expected int64 IsNil bool }{ @@ -155,7 +155,7 @@ func (s *testEvaluatorSuite) TestBenchMark(c *C) { } for _, t := range cases { - f, err := newFunctionForTest(s.ctx, ast.Benchmark, s.primitiveValsToConstants([]interface{}{ + f, err := newFunctionForTest(s.ctx, ast.Benchmark, s.primitiveValsToConstants([]any{ t.LoopCount, t.Expression, })...) @@ -216,7 +216,7 @@ func (s *testEvaluatorSuite) TestRowCount(c *C) { // TestTiDBVersion for tidb_server(). func (s *testEvaluatorSuite) TestTiDBVersion(c *C) { - f, err := newFunctionForTest(s.ctx, ast.TiDBVersion, s.primitiveValsToConstants([]interface{}{})...) + f, err := newFunctionForTest(s.ctx, ast.TiDBVersion, s.primitiveValsToConstants([]any{})...) c.Assert(err, IsNil) v, err := f.Eval(chunk.Row{}) c.Assert(err, IsNil) @@ -227,7 +227,7 @@ func (s *testEvaluatorSuite) TestLastInsertID(c *C) { maxUint64 := uint64(math.MaxUint64) cases := []struct { insertID uint64 - args interface{} + args any expected uint64 isNil bool getErr bool @@ -250,7 +250,7 @@ func (s *testEvaluatorSuite) TestLastInsertID(c *C) { } if t.args != nil { - f, err = newFunctionForTest(s.ctx, ast.LastInsertId, s.primitiveValsToConstants([]interface{}{t.args})...) + f, err = newFunctionForTest(s.ctx, ast.LastInsertId, s.primitiveValsToConstants([]any{t.args})...) } else { f, err = newFunctionForTest(s.ctx, ast.LastInsertId) } @@ -280,8 +280,8 @@ func (s *testEvaluatorSuite) TestLastInsertID(c *C) { func (s *testEvaluatorSuite) TestFormatBytes(c *C) { tbl := []struct { - Arg interface{} - Ret interface{} + Arg any + Ret any }{ {nil, nil}, {float64(0), "0 bytes"}, @@ -308,8 +308,8 @@ func (s *testEvaluatorSuite) TestFormatBytes(c *C) { func (s *testEvaluatorSuite) TestFormatNanoTime(c *C) { tbl := []struct { - Arg interface{} - Ret interface{} + Arg any + Ret any }{ {nil, nil}, {float64(0), "0 ns"}, diff --git a/expression/builtin_info_vec_test.go b/expression/builtin_info_vec_test.go index 474d1c80d..bee95e674 100644 --- a/expression/builtin_info_vec_test.go +++ b/expression/builtin_info_vec_test.go @@ -30,7 +30,7 @@ type tidbKeyGener struct { inner *defaultGener } -func (g *tidbKeyGener) gen() interface{} { +func (g *tidbKeyGener) gen() any { tableID := g.inner.gen().(int64) var result []byte if rand.Intn(2) == 1 { diff --git a/expression/builtin_json.go b/expression/builtin_json.go index bb2eee747..1faac9cb2 100644 --- a/expression/builtin_json.go +++ b/expression/builtin_json.go @@ -506,7 +506,7 @@ func (b *builtinJSONObjectSig) evalJSON(row chunk.Row) (res json.BinaryJSON, isN err = ErrIncorrectParameterCount.GenWithStackByArgs(ast.JSONObject) return res, true, err } - jsons := make(map[string]interface{}, len(b.args)>>1) + jsons := make(map[string]any, len(b.args)>>1) var key string var value json.BinaryJSON for i, arg := range b.args { @@ -568,7 +568,7 @@ func (c *jsonArrayFunctionClass) getFunction(ctx sessionctx.Context, args []Expr } func (b *builtinJSONArraySig) evalJSON(row chunk.Row) (res json.BinaryJSON, isNull bool, err error) { - jsons := make([]interface{}, 0, len(b.args)) + jsons := make([]any, 0, len(b.args)) for _, arg := range b.args { j, isNull, err := arg.EvalJSON(b.ctx, row) if err != nil { @@ -954,7 +954,7 @@ func (b *builtinJSONArrayAppendSig) appendJSONArray(res json.BinaryJSON, p strin // res.Extract will return a json object instead of an array if there is an object at path pathExpr. // JSON_ARRAY_APPEND({"a": "b"}, "$", {"b": "c"}) => [{"a": "b"}, {"b", "c"}] // We should wrap them to a single array first. - obj = json.CreateBinary([]interface{}{obj}) + obj = json.CreateBinary([]any{obj}) } obj = json.MergeBinary([]json.BinaryJSON{obj, v}) diff --git a/expression/builtin_json_test.go b/expression/builtin_json_test.go index 0302e4f3c..342f6b0c8 100644 --- a/expression/builtin_json_test.go +++ b/expression/builtin_json_test.go @@ -26,8 +26,8 @@ import ( func (s *testEvaluatorSuite) TestJSONType(c *C) { fc := funcs[ast.JSONType] tbl := []struct { - Input interface{} - Expected interface{} + Input any + Expected any }{ {nil, nil}, {`3`, `INTEGER`}, @@ -50,8 +50,8 @@ func (s *testEvaluatorSuite) TestJSONType(c *C) { func (s *testEvaluatorSuite) TestJSONQuote(c *C) { fc := funcs[ast.JSONQuote] tbl := []struct { - Input interface{} - Expected interface{} + Input any + Expected any }{ {nil, nil}, {``, `""`}, @@ -78,8 +78,8 @@ func (s *testEvaluatorSuite) TestJSONQuote(c *C) { func (s *testEvaluatorSuite) TestJSONUnquote(c *C) { fc := funcs[ast.JSONUnquote] tbl := []struct { - Input interface{} - Expected interface{} + Input any + Expected any }{ {nil, nil}, {``, ``}, @@ -110,13 +110,13 @@ func (s *testEvaluatorSuite) TestJSONExtract(c *C) { fc := funcs[ast.JSONExtract] jstr := `{"a": [{"aa": [{"aaa": 1}]}], "aaa": 2}` tbl := []struct { - Input []interface{} - Expected interface{} + Input []any + Expected any Success bool }{ - {[]interface{}{nil, nil}, nil, true}, - {[]interface{}{jstr, `$.a[0].aa[0].aaa`, `$.aaa`}, `[1, 2]`, true}, - {[]interface{}{jstr, `$.a[0].aa[0].aaa`, `$InvalidPath`}, nil, false}, + {[]any{nil, nil}, nil, true}, + {[]any{jstr, `$.a[0].aa[0].aaa`, `$.aaa`}, `[1, 2]`, true}, + {[]any{jstr, `$.a[0].aa[0].aaa`, `$InvalidPath`}, nil, false}, } for _, t := range tbl { args := types.MakeDatums(t.Input...) @@ -146,19 +146,19 @@ func (s *testEvaluatorSuite) TestJSONExtract(c *C) { func (s *testEvaluatorSuite) TestJSONSetInsertReplace(c *C) { tbl := []struct { fc functionClass - Input []interface{} - Expected interface{} + Input []any + Expected any BuildSuccess bool Success bool }{ - {funcs[ast.JSONSet], []interface{}{nil, nil, nil}, nil, true, true}, - {funcs[ast.JSONSet], []interface{}{`{}`, `$.a`, 3}, `{"a": 3}`, true, true}, - {funcs[ast.JSONInsert], []interface{}{`{}`, `$.a`, 3}, `{"a": 3}`, true, true}, - {funcs[ast.JSONReplace], []interface{}{`{}`, `$.a`, 3}, `{}`, true, true}, - {funcs[ast.JSONSet], []interface{}{`{}`, `$.a`, 3, `$.b`, "3"}, `{"a": 3, "b": "3"}`, true, true}, - {funcs[ast.JSONSet], []interface{}{`{}`, `$.a`, nil, `$.b`, "nil"}, `{"a": null, "b": "nil"}`, true, true}, - {funcs[ast.JSONSet], []interface{}{`{}`, `$.a`, 3, `$.b`}, nil, false, false}, - {funcs[ast.JSONSet], []interface{}{`{}`, `$InvalidPath`, 3}, nil, true, false}, + {funcs[ast.JSONSet], []any{nil, nil, nil}, nil, true, true}, + {funcs[ast.JSONSet], []any{`{}`, `$.a`, 3}, `{"a": 3}`, true, true}, + {funcs[ast.JSONInsert], []any{`{}`, `$.a`, 3}, `{"a": 3}`, true, true}, + {funcs[ast.JSONReplace], []any{`{}`, `$.a`, 3}, `{}`, true, true}, + {funcs[ast.JSONSet], []any{`{}`, `$.a`, 3, `$.b`, "3"}, `{"a": 3, "b": "3"}`, true, true}, + {funcs[ast.JSONSet], []any{`{}`, `$.a`, nil, `$.b`, "nil"}, `{"a": null, "b": "nil"}`, true, true}, + {funcs[ast.JSONSet], []any{`{}`, `$.a`, 3, `$.b`}, nil, false, false}, + {funcs[ast.JSONSet], []any{`{}`, `$InvalidPath`, 3}, nil, true, false}, } var err error var f builtinFunc @@ -191,12 +191,12 @@ func (s *testEvaluatorSuite) TestJSONSetInsertReplace(c *C) { func (s *testEvaluatorSuite) TestJSONMerge(c *C) { fc := funcs[ast.JSONMerge] tbl := []struct { - Input []interface{} - Expected interface{} + Input []any + Expected any }{ - {[]interface{}{nil, nil}, nil}, - {[]interface{}{`{}`, `[]`}, `[{}]`}, - {[]interface{}{`{}`, `[]`, `3`, `"4"`}, `[{}, 3, "4"]`}, + {[]any{nil, nil}, nil}, + {[]any{`{}`, `[]`}, `[{}]`}, + {[]any{`{}`, `[]`, `3`, `"4"`}, `[{}, 3, "4"]`}, } for _, t := range tbl { args := types.MakeDatums(t.Input...) @@ -221,12 +221,12 @@ func (s *testEvaluatorSuite) TestJSONMerge(c *C) { func (s *testEvaluatorSuite) TestJSONMergePreserve(c *C) { fc := funcs[ast.JSONMergePreserve] tbl := []struct { - Input []interface{} - Expected interface{} + Input []any + Expected any }{ - {[]interface{}{nil, nil}, nil}, - {[]interface{}{`{}`, `[]`}, `[{}]`}, - {[]interface{}{`{}`, `[]`, `3`, `"4"`}, `[{}, 3, "4"]`}, + {[]any{nil, nil}, nil}, + {[]any{`{}`, `[]`}, `[{}]`}, + {[]any{`{}`, `[]`, `3`, `"4"`}, `[{}, 3, "4"]`}, } for _, t := range tbl { args := types.MakeDatums(t.Input...) @@ -251,11 +251,11 @@ func (s *testEvaluatorSuite) TestJSONMergePreserve(c *C) { func (s *testEvaluatorSuite) TestJSONArray(c *C) { fc := funcs[ast.JSONArray] tbl := []struct { - Input []interface{} + Input []any Expected string }{ - {[]interface{}{1}, `[1]`}, - {[]interface{}{nil, "a", 3, `{"a": "b"}`}, `[null, "a", 3, "{\"a\": \"b\"}"]`}, + {[]any{1}, `[1]`}, + {[]any{nil, "a", 3, `{"a": "b"}`}, `[null, "a", 3, "{\"a\": \"b\"}"]`}, } for _, t := range tbl { args := types.MakeDatums(t.Input...) @@ -275,17 +275,17 @@ func (s *testEvaluatorSuite) TestJSONArray(c *C) { func (s *testEvaluatorSuite) TestJSONObject(c *C) { fc := funcs[ast.JSONObject] tbl := []struct { - Input []interface{} - Expected interface{} + Input []any + Expected any BuildSuccess bool Success bool }{ - {[]interface{}{1, 2, 3}, nil, false, false}, - {[]interface{}{1, 2, "hello", nil}, `{"1": 2, "hello": null}`, true, true}, - {[]interface{}{nil, 2}, nil, true, false}, + {[]any{1, 2, 3}, nil, false, false}, + {[]any{1, 2, "hello", nil}, `{"1": 2, "hello": null}`, true, true}, + {[]any{nil, 2}, nil, true, false}, // TiDB can only tell booleans from parser. - {[]interface{}{1, true}, `{"1": 1}`, true, true}, + {[]any{1, true}, `{"1": 1}`, true, true}, } var err error var f builtinFunc @@ -318,27 +318,27 @@ func (s *testEvaluatorSuite) TestJSONObject(c *C) { func (s *testEvaluatorSuite) TestJSONRemove(c *C) { fc := funcs[ast.JSONRemove] tbl := []struct { - Input []interface{} - Expected interface{} + Input []any + Expected any Success bool }{ - {[]interface{}{`{"a": [1, 2, {"aa": "xx"}]}`, "$"}, nil, false}, - {[]interface{}{`{"a": [1, 2, {"aa": "xx"}]}`, "$.*"}, nil, false}, - {[]interface{}{`{"a": [1, 2, {"aa": "xx"}]}`, "$[*]"}, nil, false}, - {[]interface{}{`{"a": [1, 2, {"aa": "xx"}]}`, "$**.a"}, nil, false}, + {[]any{`{"a": [1, 2, {"aa": "xx"}]}`, "$"}, nil, false}, + {[]any{`{"a": [1, 2, {"aa": "xx"}]}`, "$.*"}, nil, false}, + {[]any{`{"a": [1, 2, {"aa": "xx"}]}`, "$[*]"}, nil, false}, + {[]any{`{"a": [1, 2, {"aa": "xx"}]}`, "$**.a"}, nil, false}, - {[]interface{}{nil, "$.a"}, nil, true}, - {[]interface{}{`{"a": [1, 2, {"aa": "xx"}]}`, "$.a[2].aa"}, `{"a": [1, 2, {}]}`, true}, - {[]interface{}{`{"a": [1, 2, {"aa": "xx"}]}`, "$.a[1]"}, `{"a": [1, {"aa": "xx"}]}`, true}, + {[]any{nil, "$.a"}, nil, true}, + {[]any{`{"a": [1, 2, {"aa": "xx"}]}`, "$.a[2].aa"}, `{"a": [1, 2, {}]}`, true}, + {[]any{`{"a": [1, 2, {"aa": "xx"}]}`, "$.a[1]"}, `{"a": [1, {"aa": "xx"}]}`, true}, // Tests multi path expressions. - {[]interface{}{`{"a": [1, 2, {"aa": "xx"}]}`, "$.a[2].aa", "$.a[1]"}, `{"a": [1, {}]}`, true}, - {[]interface{}{`{"a": [1, 2, {"aa": "xx"}]}`, "$.a[1]", "$.a[1].aa"}, `{"a": [1, {}]}`, true}, + {[]any{`{"a": [1, 2, {"aa": "xx"}]}`, "$.a[2].aa", "$.a[1]"}, `{"a": [1, {}]}`, true}, + {[]any{`{"a": [1, 2, {"aa": "xx"}]}`, "$.a[1]", "$.a[1].aa"}, `{"a": [1, {}]}`, true}, // Tests path expressions not exists. - {[]interface{}{`{"a": [1, 2, {"aa": "xx"}]}`, "$.a[3]"}, `{"a": [1, 2, {"aa": "xx"}]}`, true}, - {[]interface{}{`{"a": [1, 2, {"aa": "xx"}]}`, "$.b"}, `{"a": [1, 2, {"aa": "xx"}]}`, true}, - {[]interface{}{`{"a": [1, 2, {"aa": "xx"}]}`, "$.a[3]", "$.b"}, `{"a": [1, 2, {"aa": "xx"}]}`, true}, + {[]any{`{"a": [1, 2, {"aa": "xx"}]}`, "$.a[3]"}, `{"a": [1, 2, {"aa": "xx"}]}`, true}, + {[]any{`{"a": [1, 2, {"aa": "xx"}]}`, "$.b"}, `{"a": [1, 2, {"aa": "xx"}]}`, true}, + {[]any{`{"a": [1, 2, {"aa": "xx"}]}`, "$.a[3]", "$.b"}, `{"a": [1, 2, {"aa": "xx"}]}`, true}, } for _, t := range tbl { args := types.MakeDatums(t.Input...) @@ -367,49 +367,49 @@ func (s *testEvaluatorSuite) TestJSONRemove(c *C) { func (s *testEvaluatorSuite) TestJSONContains(c *C) { fc := funcs[ast.JSONContains] tbl := []struct { - input []interface{} - expected interface{} + input []any + expected any err error }{ // Tests nil arguments - {[]interface{}{nil, `1`, "$.c"}, nil, nil}, - {[]interface{}{`{"a": [1, 2, {"aa": "xx"}]}`, nil, "$.a[3]"}, nil, nil}, - {[]interface{}{`{"a": [1, 2, {"aa": "xx"}]}`, `1`, nil}, nil, nil}, + {[]any{nil, `1`, "$.c"}, nil, nil}, + {[]any{`{"a": [1, 2, {"aa": "xx"}]}`, nil, "$.a[3]"}, nil, nil}, + {[]any{`{"a": [1, 2, {"aa": "xx"}]}`, `1`, nil}, nil, nil}, // Tests with path expression - {[]interface{}{`[1,2,[1,[5,[3]]]]`, `[1,3]`, "$[2]"}, 1, nil}, - {[]interface{}{`[1,2,[1,[5,{"a":[2,3]}]]]`, `[1,{"a":[3]}]`, "$[2]"}, 1, nil}, - {[]interface{}{`[{"a":1}]`, `{"a":1}`, "$"}, 1, nil}, - {[]interface{}{`[{"a":1,"b":2}]`, `{"a":1,"b":2}`, "$"}, 1, nil}, - {[]interface{}{`[{"a":{"a":1},"b":2}]`, `{"a":1}`, "$.a"}, 0, nil}, + {[]any{`[1,2,[1,[5,[3]]]]`, `[1,3]`, "$[2]"}, 1, nil}, + {[]any{`[1,2,[1,[5,{"a":[2,3]}]]]`, `[1,{"a":[3]}]`, "$[2]"}, 1, nil}, + {[]any{`[{"a":1}]`, `{"a":1}`, "$"}, 1, nil}, + {[]any{`[{"a":1,"b":2}]`, `{"a":1,"b":2}`, "$"}, 1, nil}, + {[]any{`[{"a":{"a":1},"b":2}]`, `{"a":1}`, "$.a"}, 0, nil}, // Tests without path expression - {[]interface{}{`{}`, `{}`}, 1, nil}, - {[]interface{}{`{"a":1}`, `{}`}, 1, nil}, - {[]interface{}{`{"a":1}`, `1`}, 0, nil}, - {[]interface{}{`{"a":[1]}`, `[1]`}, 0, nil}, - {[]interface{}{`{"b":2, "c":3}`, `{"c":3}`}, 1, nil}, - {[]interface{}{`1`, `1`}, 1, nil}, - {[]interface{}{`[1]`, `1`}, 1, nil}, - {[]interface{}{`[1,2]`, `[1]`}, 1, nil}, - {[]interface{}{`[1,2]`, `[1,3]`}, 0, nil}, - {[]interface{}{`[1,2]`, `["1"]`}, 0, nil}, - {[]interface{}{`[1,2,[1,3]]`, `[1,3]`}, 1, nil}, - {[]interface{}{`[1,2,[1,3]]`, `[1, 3]`}, 1, nil}, - {[]interface{}{`[1,2,[1,[5,[3]]]]`, `[1,3]`}, 1, nil}, - {[]interface{}{`[1,2,[1,[5,{"a":[2,3]}]]]`, `[1,{"a":[3]}]`}, 1, nil}, - {[]interface{}{`[{"a":1}]`, `{"a":1}`}, 1, nil}, - {[]interface{}{`[{"a":1,"b":2}]`, `{"a":1}`}, 1, nil}, - {[]interface{}{`[{"a":{"a":1},"b":2}]`, `{"a":1}`}, 0, nil}, + {[]any{`{}`, `{}`}, 1, nil}, + {[]any{`{"a":1}`, `{}`}, 1, nil}, + {[]any{`{"a":1}`, `1`}, 0, nil}, + {[]any{`{"a":[1]}`, `[1]`}, 0, nil}, + {[]any{`{"b":2, "c":3}`, `{"c":3}`}, 1, nil}, + {[]any{`1`, `1`}, 1, nil}, + {[]any{`[1]`, `1`}, 1, nil}, + {[]any{`[1,2]`, `[1]`}, 1, nil}, + {[]any{`[1,2]`, `[1,3]`}, 0, nil}, + {[]any{`[1,2]`, `["1"]`}, 0, nil}, + {[]any{`[1,2,[1,3]]`, `[1,3]`}, 1, nil}, + {[]any{`[1,2,[1,3]]`, `[1, 3]`}, 1, nil}, + {[]any{`[1,2,[1,[5,[3]]]]`, `[1,3]`}, 1, nil}, + {[]any{`[1,2,[1,[5,{"a":[2,3]}]]]`, `[1,{"a":[3]}]`}, 1, nil}, + {[]any{`[{"a":1}]`, `{"a":1}`}, 1, nil}, + {[]any{`[{"a":1,"b":2}]`, `{"a":1}`}, 1, nil}, + {[]any{`[{"a":{"a":1},"b":2}]`, `{"a":1}`}, 0, nil}, // Tests path expression contains any asterisk - {[]interface{}{`{"a": [1, 2, {"aa": "xx"}]}`, `1`, "$.*"}, nil, json.ErrInvalidJSONPathWildcard}, - {[]interface{}{`{"a": [1, 2, {"aa": "xx"}]}`, `1`, "$[*]"}, nil, json.ErrInvalidJSONPathWildcard}, - {[]interface{}{`{"a": [1, 2, {"aa": "xx"}]}`, `1`, "$**.a"}, nil, json.ErrInvalidJSONPathWildcard}, + {[]any{`{"a": [1, 2, {"aa": "xx"}]}`, `1`, "$.*"}, nil, json.ErrInvalidJSONPathWildcard}, + {[]any{`{"a": [1, 2, {"aa": "xx"}]}`, `1`, "$[*]"}, nil, json.ErrInvalidJSONPathWildcard}, + {[]any{`{"a": [1, 2, {"aa": "xx"}]}`, `1`, "$**.a"}, nil, json.ErrInvalidJSONPathWildcard}, // Tests path expression does not identify a section of the target document - {[]interface{}{`{"a": [1, 2, {"aa": "xx"}]}`, `1`, "$.c"}, nil, nil}, - {[]interface{}{`{"a": [1, 2, {"aa": "xx"}]}`, `1`, "$.a[3]"}, nil, nil}, - {[]interface{}{`{"a": [1, 2, {"aa": "xx"}]}`, `1`, "$.a[2].b"}, nil, nil}, + {[]any{`{"a": [1, 2, {"aa": "xx"}]}`, `1`, "$.c"}, nil, nil}, + {[]any{`{"a": [1, 2, {"aa": "xx"}]}`, `1`, "$.a[3]"}, nil, nil}, + {[]any{`{"a": [1, 2, {"aa": "xx"}]}`, `1`, "$.a[2].b"}, nil, nil}, // For issue 9957: test 'argument 1 and 2 as valid json object' - {[]interface{}{`[1,2,[1,3]]`, `a:1`}, 1, json.ErrInvalidJSONText}, - {[]interface{}{`a:1`, `1`}, 1, json.ErrInvalidJSONText}, + {[]any{`[1,2,[1,3]]`, `a:1`}, 1, json.ErrInvalidJSONText}, + {[]any{`a:1`, `1`}, 1, json.ErrInvalidJSONText}, } for _, t := range tbl { args := types.MakeDatums(t.input...) @@ -429,8 +429,8 @@ func (s *testEvaluatorSuite) TestJSONContains(c *C) { } // For issue 9957: test 'argument 1 and 2 as valid json object' cases := []struct { - arg1 interface{} - arg2 interface{} + arg1 any + arg2 any }{ {1, ""}, {0.05, ""}, @@ -448,40 +448,40 @@ func (s *testEvaluatorSuite) TestJSONContainsPath(c *C) { jsonString := `{"a": 1, "b": 2, "c": {"d": 4}}` invalidJSON := `{"a": 1` tbl := []struct { - input []interface{} - expected interface{} + input []any + expected any success bool }{ // Tests nil arguments - {[]interface{}{nil, json.ContainsPathOne, "$.c"}, nil, true}, - {[]interface{}{nil, json.ContainsPathAll, "$.c"}, nil, true}, - {[]interface{}{jsonString, nil, "$.a[3]"}, nil, true}, - {[]interface{}{jsonString, json.ContainsPathOne, nil}, nil, true}, - {[]interface{}{jsonString, json.ContainsPathAll, nil}, nil, true}, + {[]any{nil, json.ContainsPathOne, "$.c"}, nil, true}, + {[]any{nil, json.ContainsPathAll, "$.c"}, nil, true}, + {[]any{jsonString, nil, "$.a[3]"}, nil, true}, + {[]any{jsonString, json.ContainsPathOne, nil}, nil, true}, + {[]any{jsonString, json.ContainsPathAll, nil}, nil, true}, // Tests with one path expression - {[]interface{}{jsonString, json.ContainsPathOne, "$.c.d"}, 1, true}, - {[]interface{}{jsonString, json.ContainsPathOne, "$.a.d"}, 0, true}, - {[]interface{}{jsonString, json.ContainsPathAll, "$.c.d"}, 1, true}, - {[]interface{}{jsonString, json.ContainsPathAll, "$.a.d"}, 0, true}, + {[]any{jsonString, json.ContainsPathOne, "$.c.d"}, 1, true}, + {[]any{jsonString, json.ContainsPathOne, "$.a.d"}, 0, true}, + {[]any{jsonString, json.ContainsPathAll, "$.c.d"}, 1, true}, + {[]any{jsonString, json.ContainsPathAll, "$.a.d"}, 0, true}, // Tests with multiple path expression - {[]interface{}{jsonString, json.ContainsPathOne, "$.a", "$.e"}, 1, true}, - {[]interface{}{jsonString, json.ContainsPathOne, "$.a", "$.c"}, 1, true}, - {[]interface{}{jsonString, json.ContainsPathAll, "$.a", "$.e"}, 0, true}, - {[]interface{}{jsonString, json.ContainsPathAll, "$.a", "$.c"}, 1, true}, + {[]any{jsonString, json.ContainsPathOne, "$.a", "$.e"}, 1, true}, + {[]any{jsonString, json.ContainsPathOne, "$.a", "$.c"}, 1, true}, + {[]any{jsonString, json.ContainsPathAll, "$.a", "$.e"}, 0, true}, + {[]any{jsonString, json.ContainsPathAll, "$.a", "$.c"}, 1, true}, // Tests path expression contains any asterisk - {[]interface{}{jsonString, json.ContainsPathOne, "$.*"}, 1, true}, - {[]interface{}{jsonString, json.ContainsPathOne, "$[*]"}, 0, true}, - {[]interface{}{jsonString, json.ContainsPathAll, "$.*"}, 1, true}, - {[]interface{}{jsonString, json.ContainsPathAll, "$[*]"}, 0, true}, + {[]any{jsonString, json.ContainsPathOne, "$.*"}, 1, true}, + {[]any{jsonString, json.ContainsPathOne, "$[*]"}, 0, true}, + {[]any{jsonString, json.ContainsPathAll, "$.*"}, 1, true}, + {[]any{jsonString, json.ContainsPathAll, "$[*]"}, 0, true}, // Tests invalid json document - {[]interface{}{invalidJSON, json.ContainsPathOne, "$.a"}, nil, false}, - {[]interface{}{invalidJSON, json.ContainsPathAll, "$.a"}, nil, false}, + {[]any{invalidJSON, json.ContainsPathOne, "$.a"}, nil, false}, + {[]any{invalidJSON, json.ContainsPathAll, "$.a"}, nil, false}, // Tests compatible contains path - {[]interface{}{jsonString, "ONE", "$.c.d"}, 1, true}, - {[]interface{}{jsonString, "ALL", "$.c.d"}, 1, true}, - {[]interface{}{jsonString, "One", "$.a", "$.e"}, 1, true}, - {[]interface{}{jsonString, "aLl", "$.a", "$.e"}, 0, true}, - {[]interface{}{jsonString, "test", "$.a"}, nil, false}, + {[]any{jsonString, "ONE", "$.c.d"}, 1, true}, + {[]any{jsonString, "ALL", "$.c.d"}, 1, true}, + {[]any{jsonString, "One", "$.a", "$.e"}, 1, true}, + {[]any{jsonString, "aLl", "$.a", "$.e"}, 0, true}, + {[]any{jsonString, "test", "$.a"}, nil, false}, } for _, t := range tbl { args := types.MakeDatums(t.input...) @@ -504,54 +504,54 @@ func (s *testEvaluatorSuite) TestJSONContainsPath(c *C) { func (s *testEvaluatorSuite) TestJSONLength(c *C) { fc := funcs[ast.JSONLength] tbl := []struct { - input []interface{} - expected interface{} + input []any + expected any success bool }{ // Tests scalar arguments - {[]interface{}{`null`}, 1, true}, - {[]interface{}{`true`}, 1, true}, - {[]interface{}{`false`}, 1, true}, - {[]interface{}{`1`}, 1, true}, - {[]interface{}{`-1`}, 1, true}, - {[]interface{}{`1.1`}, 1, true}, - {[]interface{}{`"1"`}, 1, true}, - {[]interface{}{`"1"`, "$.a"}, 1, true}, - {[]interface{}{`null`, "$.a"}, 1, true}, + {[]any{`null`}, 1, true}, + {[]any{`true`}, 1, true}, + {[]any{`false`}, 1, true}, + {[]any{`1`}, 1, true}, + {[]any{`-1`}, 1, true}, + {[]any{`1.1`}, 1, true}, + {[]any{`"1"`}, 1, true}, + {[]any{`"1"`, "$.a"}, 1, true}, + {[]any{`null`, "$.a"}, 1, true}, // Tests nil arguments - {[]interface{}{nil}, nil, true}, - {[]interface{}{nil, "a"}, nil, true}, - {[]interface{}{`{"a": 1}`, nil}, nil, true}, - {[]interface{}{nil, nil}, nil, true}, + {[]any{nil}, nil, true}, + {[]any{nil, "a"}, nil, true}, + {[]any{`{"a": 1}`, nil}, nil, true}, + {[]any{nil, nil}, nil, true}, // Tests with path expression - {[]interface{}{`[1,2,[1,[5,[3]]]]`, "$[2]"}, 2, true}, - {[]interface{}{`[{"a":1}]`, "$"}, 1, true}, - {[]interface{}{`[{"a":1,"b":2}]`, "$[0].a"}, 1, true}, - {[]interface{}{`{"a":{"a":1},"b":2}`, "$"}, 2, true}, - {[]interface{}{`{"a":{"a":1},"b":2}`, "$.a"}, 1, true}, - {[]interface{}{`{"a":{"a":1},"b":2}`, "$.a.a"}, 1, true}, - {[]interface{}{`{"a": [1, 2, {"aa": "xx"}]}`, "$.a[2].aa"}, 1, true}, + {[]any{`[1,2,[1,[5,[3]]]]`, "$[2]"}, 2, true}, + {[]any{`[{"a":1}]`, "$"}, 1, true}, + {[]any{`[{"a":1,"b":2}]`, "$[0].a"}, 1, true}, + {[]any{`{"a":{"a":1},"b":2}`, "$"}, 2, true}, + {[]any{`{"a":{"a":1},"b":2}`, "$.a"}, 1, true}, + {[]any{`{"a":{"a":1},"b":2}`, "$.a.a"}, 1, true}, + {[]any{`{"a": [1, 2, {"aa": "xx"}]}`, "$.a[2].aa"}, 1, true}, // Tests without path expression - {[]interface{}{`{}`}, 0, true}, - {[]interface{}{`{"a":1}`}, 1, true}, - {[]interface{}{`{"a":[1]}`}, 1, true}, - {[]interface{}{`{"b":2, "c":3}`}, 2, true}, - {[]interface{}{`[1]`}, 1, true}, - {[]interface{}{`[1,2]`}, 2, true}, - {[]interface{}{`[1,2,[1,3]]`}, 3, true}, - {[]interface{}{`[1,2,[1,[5,[3]]]]`}, 3, true}, - {[]interface{}{`[1,2,[1,[5,{"a":[2,3]}]]]`}, 3, true}, - {[]interface{}{`[{"a":1}]`}, 1, true}, - {[]interface{}{`[{"a":1,"b":2}]`}, 1, true}, - {[]interface{}{`[{"a":{"a":1},"b":2}]`}, 1, true}, + {[]any{`{}`}, 0, true}, + {[]any{`{"a":1}`}, 1, true}, + {[]any{`{"a":[1]}`}, 1, true}, + {[]any{`{"b":2, "c":3}`}, 2, true}, + {[]any{`[1]`}, 1, true}, + {[]any{`[1,2]`}, 2, true}, + {[]any{`[1,2,[1,3]]`}, 3, true}, + {[]any{`[1,2,[1,[5,[3]]]]`}, 3, true}, + {[]any{`[1,2,[1,[5,{"a":[2,3]}]]]`}, 3, true}, + {[]any{`[{"a":1}]`}, 1, true}, + {[]any{`[{"a":1,"b":2}]`}, 1, true}, + {[]any{`[{"a":{"a":1},"b":2}]`}, 1, true}, // Tests path expression contains any asterisk - {[]interface{}{`{"a": [1, 2, {"aa": "xx"}]}`, "$.*"}, nil, false}, - {[]interface{}{`{"a": [1, 2, {"aa": "xx"}]}`, "$[*]"}, nil, false}, - {[]interface{}{`{"a": [1, 2, {"aa": "xx"}]}`, "$**.a"}, nil, false}, + {[]any{`{"a": [1, 2, {"aa": "xx"}]}`, "$.*"}, nil, false}, + {[]any{`{"a": [1, 2, {"aa": "xx"}]}`, "$[*]"}, nil, false}, + {[]any{`{"a": [1, 2, {"aa": "xx"}]}`, "$**.a"}, nil, false}, // Tests path expression does not identify a section of the target document - {[]interface{}{`{"a": [1, 2, {"aa": "xx"}]}`, "$.c"}, nil, true}, - {[]interface{}{`{"a": [1, 2, {"aa": "xx"}]}`, "$.a[3]"}, nil, true}, - {[]interface{}{`{"a": [1, 2, {"aa": "xx"}]}`, "$.a[2].b"}, nil, true}, + {[]any{`{"a": [1, 2, {"aa": "xx"}]}`, "$.c"}, nil, true}, + {[]any{`{"a": [1, 2, {"aa": "xx"}]}`, "$.a[3]"}, nil, true}, + {[]any{`{"a": [1, 2, {"aa": "xx"}]}`, "$.a[2].b"}, nil, true}, } for _, t := range tbl { args := types.MakeDatums(t.input...) @@ -575,47 +575,47 @@ func (s *testEvaluatorSuite) TestJSONLength(c *C) { func (s *testEvaluatorSuite) TestJSONKeys(c *C) { fc := funcs[ast.JSONKeys] tbl := []struct { - input []interface{} - expected interface{} + input []any + expected any success bool }{ // Tests nil arguments - {[]interface{}{nil}, nil, true}, - {[]interface{}{nil, "$.c"}, nil, true}, - {[]interface{}{`{"a": 1}`, nil}, nil, true}, - {[]interface{}{nil, nil}, nil, true}, + {[]any{nil}, nil, true}, + {[]any{nil, "$.c"}, nil, true}, + {[]any{`{"a": 1}`, nil}, nil, true}, + {[]any{nil, nil}, nil, true}, // Tests with other type - {[]interface{}{`1`}, nil, true}, - {[]interface{}{`"str"`}, nil, true}, - {[]interface{}{`true`}, nil, true}, - {[]interface{}{`null`}, nil, true}, - {[]interface{}{`[1, 2]`}, nil, true}, - {[]interface{}{`["1", "2"]`}, nil, true}, + {[]any{`1`}, nil, true}, + {[]any{`"str"`}, nil, true}, + {[]any{`true`}, nil, true}, + {[]any{`null`}, nil, true}, + {[]any{`[1, 2]`}, nil, true}, + {[]any{`["1", "2"]`}, nil, true}, // Tests without path expression - {[]interface{}{`{}`}, `[]`, true}, - {[]interface{}{`{"a": 1}`}, `["a"]`, true}, - {[]interface{}{`{"a": 1, "b": 2}`}, `["a", "b"]`, true}, - {[]interface{}{`{"a": {"c": 3}, "b": 2}`}, `["a", "b"]`, true}, + {[]any{`{}`}, `[]`, true}, + {[]any{`{"a": 1}`}, `["a"]`, true}, + {[]any{`{"a": 1, "b": 2}`}, `["a", "b"]`, true}, + {[]any{`{"a": {"c": 3}, "b": 2}`}, `["a", "b"]`, true}, // Tests with path expression - {[]interface{}{`{"a": 1}`, "$.a"}, nil, true}, - {[]interface{}{`{"a": {"c": 3}, "b": 2}`, "$.a"}, `["c"]`, true}, - {[]interface{}{`{"a": {"c": 3}, "b": 2}`, "$.a.c"}, nil, true}, - {[]interface{}{`{"a": {"c": 3}, "b": 2}`, nil}, nil, true}, + {[]any{`{"a": 1}`, "$.a"}, nil, true}, + {[]any{`{"a": {"c": 3}, "b": 2}`, "$.a"}, `["c"]`, true}, + {[]any{`{"a": {"c": 3}, "b": 2}`, "$.a.c"}, nil, true}, + {[]any{`{"a": {"c": 3}, "b": 2}`, nil}, nil, true}, // Tests path expression contains any asterisk - {[]interface{}{`{}`, "$.*"}, nil, false}, - {[]interface{}{`{"a": 1}`, "$.*"}, nil, false}, - {[]interface{}{`{"a": {"c": 3}, "b": 2}`, "$.*"}, nil, false}, - {[]interface{}{`{"a": {"c": 3}, "b": 2}`, "$.a.*"}, nil, false}, + {[]any{`{}`, "$.*"}, nil, false}, + {[]any{`{"a": 1}`, "$.*"}, nil, false}, + {[]any{`{"a": {"c": 3}, "b": 2}`, "$.*"}, nil, false}, + {[]any{`{"a": {"c": 3}, "b": 2}`, "$.a.*"}, nil, false}, // Tests path expression does not identify a section of the target document - {[]interface{}{`{"a": 1}`, "$.b"}, nil, true}, - {[]interface{}{`{"a": {"c": 3}, "b": 2}`, "$.c"}, nil, true}, - {[]interface{}{`{"a": {"c": 3}, "b": 2}`, "$.a.d"}, nil, true}, + {[]any{`{"a": 1}`, "$.b"}, nil, true}, + {[]any{`{"a": {"c": 3}, "b": 2}`, "$.c"}, nil, true}, + {[]any{`{"a": {"c": 3}, "b": 2}`, "$.a.d"}, nil, true}, } for _, t := range tbl { args := types.MakeDatums(t.input...) @@ -645,41 +645,41 @@ func (s *testEvaluatorSuite) TestJSONKeys(c *C) { func (s *testEvaluatorSuite) TestJSONDepth(c *C) { fc := funcs[ast.JSONDepth] tbl := []struct { - input []interface{} - expected interface{} + input []any + expected any success bool }{ // Tests scalar arguments - {[]interface{}{`null`}, 1, true}, - {[]interface{}{`true`}, 1, true}, - {[]interface{}{`false`}, 1, true}, - {[]interface{}{`1`}, 1, true}, - {[]interface{}{`-1`}, 1, true}, - {[]interface{}{`1.1`}, 1, true}, - {[]interface{}{`"1"`}, 1, true}, + {[]any{`null`}, 1, true}, + {[]any{`true`}, 1, true}, + {[]any{`false`}, 1, true}, + {[]any{`1`}, 1, true}, + {[]any{`-1`}, 1, true}, + {[]any{`1.1`}, 1, true}, + {[]any{`"1"`}, 1, true}, // Tests nil arguments - {[]interface{}{nil}, nil, true}, + {[]any{nil}, nil, true}, // Tests depth - {[]interface{}{`{}`}, 1, true}, - {[]interface{}{`[]`}, 1, true}, - {[]interface{}{`[10, 20]`}, 2, true}, - {[]interface{}{`[[], {}]`}, 2, true}, - {[]interface{}{`{"Name": "Homer"}`}, 2, true}, - {[]interface{}{`[10, {"a": 20}]`}, 3, true}, - {[]interface{}{`{"Person": {"Name": "Homer", "Age": 39, "Hobbies": ["Eating", "Sleeping"]} }`}, 4, true}, - {[]interface{}{`{"a":1}`}, 2, true}, - {[]interface{}{`{"a":[1]}`}, 3, true}, - {[]interface{}{`{"b":2, "c":3}`}, 2, true}, - {[]interface{}{`[1]`}, 2, true}, - {[]interface{}{`[1,2]`}, 2, true}, - {[]interface{}{`[1,2,[1,3]]`}, 3, true}, - {[]interface{}{`[1,2,[1,[5,[3]]]]`}, 5, true}, - {[]interface{}{`[1,2,[1,[5,{"a":[2,3]}]]]`}, 6, true}, - {[]interface{}{`[{"a":1}]`}, 3, true}, - {[]interface{}{`[{"a":1,"b":2}]`}, 3, true}, - {[]interface{}{`[{"a":{"a":1},"b":2}]`}, 4, true}, + {[]any{`{}`}, 1, true}, + {[]any{`[]`}, 1, true}, + {[]any{`[10, 20]`}, 2, true}, + {[]any{`[[], {}]`}, 2, true}, + {[]any{`{"Name": "Homer"}`}, 2, true}, + {[]any{`[10, {"a": 20}]`}, 3, true}, + {[]any{`{"Person": {"Name": "Homer", "Age": 39, "Hobbies": ["Eating", "Sleeping"]} }`}, 4, true}, + {[]any{`{"a":1}`}, 2, true}, + {[]any{`{"a":[1]}`}, 3, true}, + {[]any{`{"b":2, "c":3}`}, 2, true}, + {[]any{`[1]`}, 2, true}, + {[]any{`[1,2]`}, 2, true}, + {[]any{`[1,2,[1,3]]`}, 3, true}, + {[]any{`[1,2,[1,[5,[3]]]]`}, 5, true}, + {[]any{`[1,2,[1,[5,{"a":[2,3]}]]]`}, 6, true}, + {[]any{`[{"a":1}]`}, 3, true}, + {[]any{`[{"a":1,"b":2}]`}, 3, true}, + {[]any{`[{"a":{"a":1},"b":2}]`}, 4, true}, // Tests non-json - {[]interface{}{`a`}, nil, false}, + {[]any{`a`}, nil, false}, } for _, t := range tbl { args := types.MakeDatums(t.input...) @@ -705,42 +705,42 @@ func (s *testEvaluatorSuite) TestJSONArrayAppend(c *C) { c.Assert(err, IsNil) fc := funcs[ast.JSONArrayAppend] tbl := []struct { - input []interface{} - expected interface{} + input []any + expected any err *terror.Error }{ - {[]interface{}{`{"a": 1, "b": [2, 3], "c": 4}`, `$.d`, `z`}, `{"a": 1, "b": [2, 3], "c": 4}`, nil}, - {[]interface{}{`{"a": 1, "b": [2, 3], "c": 4}`, `$`, `w`}, `[{"a": 1, "b": [2, 3], "c": 4}, "w"]`, nil}, - {[]interface{}{`{"a": 1, "b": [2, 3], "c": 4}`, `$`, nil}, `[{"a": 1, "b": [2, 3], "c": 4}, null]`, nil}, - {[]interface{}{`{"a": 1}`, `$`, `{"b": 2}`}, `[{"a": 1}, "{\"b\": 2}"]`, nil}, - {[]interface{}{`{"a": 1}`, `$`, sampleJSON}, `[{"a": 1}, {"b": 2}]`, nil}, - {[]interface{}{`{"a": 1}`, `$.a`, sampleJSON}, `{"a": [1, {"b": 2}]}`, nil}, - - {[]interface{}{`{"a": 1}`, `$.a`, sampleJSON, `$.a[1]`, sampleJSON}, `{"a": [1, [{"b": 2}, {"b": 2}]]}`, nil}, - {[]interface{}{nil, `$`, nil}, nil, nil}, - {[]interface{}{nil, `$`, `a`}, nil, nil}, - {[]interface{}{`null`, `$`, nil}, `[null, null]`, nil}, - {[]interface{}{`[]`, `$`, nil}, `[null]`, nil}, - {[]interface{}{`{}`, `$`, nil}, `[{}, null]`, nil}, + {[]any{`{"a": 1, "b": [2, 3], "c": 4}`, `$.d`, `z`}, `{"a": 1, "b": [2, 3], "c": 4}`, nil}, + {[]any{`{"a": 1, "b": [2, 3], "c": 4}`, `$`, `w`}, `[{"a": 1, "b": [2, 3], "c": 4}, "w"]`, nil}, + {[]any{`{"a": 1, "b": [2, 3], "c": 4}`, `$`, nil}, `[{"a": 1, "b": [2, 3], "c": 4}, null]`, nil}, + {[]any{`{"a": 1}`, `$`, `{"b": 2}`}, `[{"a": 1}, "{\"b\": 2}"]`, nil}, + {[]any{`{"a": 1}`, `$`, sampleJSON}, `[{"a": 1}, {"b": 2}]`, nil}, + {[]any{`{"a": 1}`, `$.a`, sampleJSON}, `{"a": [1, {"b": 2}]}`, nil}, + + {[]any{`{"a": 1}`, `$.a`, sampleJSON, `$.a[1]`, sampleJSON}, `{"a": [1, [{"b": 2}, {"b": 2}]]}`, nil}, + {[]any{nil, `$`, nil}, nil, nil}, + {[]any{nil, `$`, `a`}, nil, nil}, + {[]any{`null`, `$`, nil}, `[null, null]`, nil}, + {[]any{`[]`, `$`, nil}, `[null]`, nil}, + {[]any{`{}`, `$`, nil}, `[{}, null]`, nil}, // Bad arguments. - {[]interface{}{`asdf`, `$`, nil}, nil, json.ErrInvalidJSONText}, - {[]interface{}{``, `$`, nil}, nil, json.ErrInvalidJSONText}, - {[]interface{}{`{"a": 1, "b": [2, 3], "c": 4}`, `$.d`}, nil, ErrIncorrectParameterCount}, - {[]interface{}{`{"a": 1, "b": [2, 3], "c": 4}`, `$.c`, `y`, `$.b`}, nil, ErrIncorrectParameterCount}, - {[]interface{}{`{"a": 1, "b": [2, 3], "c": 4}`, nil, nil}, nil, nil}, - {[]interface{}{`{"a": 1, "b": [2, 3], "c": 4}`, `asdf`, nil}, nil, json.ErrInvalidJSONPath}, - {[]interface{}{`{"a": 1, "b": [2, 3], "c": 4}`, 42, nil}, nil, json.ErrInvalidJSONPath}, - {[]interface{}{`{"a": 1, "b": [2, 3], "c": 4}`, `$.*`, nil}, nil, json.ErrInvalidJSONPathWildcard}, + {[]any{`asdf`, `$`, nil}, nil, json.ErrInvalidJSONText}, + {[]any{``, `$`, nil}, nil, json.ErrInvalidJSONText}, + {[]any{`{"a": 1, "b": [2, 3], "c": 4}`, `$.d`}, nil, ErrIncorrectParameterCount}, + {[]any{`{"a": 1, "b": [2, 3], "c": 4}`, `$.c`, `y`, `$.b`}, nil, ErrIncorrectParameterCount}, + {[]any{`{"a": 1, "b": [2, 3], "c": 4}`, nil, nil}, nil, nil}, + {[]any{`{"a": 1, "b": [2, 3], "c": 4}`, `asdf`, nil}, nil, json.ErrInvalidJSONPath}, + {[]any{`{"a": 1, "b": [2, 3], "c": 4}`, 42, nil}, nil, json.ErrInvalidJSONPath}, + {[]any{`{"a": 1, "b": [2, 3], "c": 4}`, `$.*`, nil}, nil, json.ErrInvalidJSONPathWildcard}, // Following tests come from MySQL doc. - {[]interface{}{`["a", ["b", "c"], "d"]`, `$[1]`, 1}, `["a", ["b", "c", 1], "d"]`, nil}, - {[]interface{}{`["a", ["b", "c"], "d"]`, `$[0]`, 2}, `[["a", 2], ["b", "c"], "d"]`, nil}, - {[]interface{}{`["a", ["b", "c"], "d"]`, `$[1][0]`, 3}, `["a", [["b", 3], "c"], "d"]`, nil}, - {[]interface{}{`{"a": 1, "b": [2, 3], "c": 4}`, `$.b`, `x`}, `{"a": 1, "b": [2, 3, "x"], "c": 4}`, nil}, - {[]interface{}{`{"a": 1, "b": [2, 3], "c": 4}`, `$.c`, `y`}, `{"a": 1, "b": [2, 3], "c": [4, "y"]}`, nil}, + {[]any{`["a", ["b", "c"], "d"]`, `$[1]`, 1}, `["a", ["b", "c", 1], "d"]`, nil}, + {[]any{`["a", ["b", "c"], "d"]`, `$[0]`, 2}, `[["a", 2], ["b", "c"], "d"]`, nil}, + {[]any{`["a", ["b", "c"], "d"]`, `$[1][0]`, 3}, `["a", [["b", 3], "c"], "d"]`, nil}, + {[]any{`{"a": 1, "b": [2, 3], "c": 4}`, `$.b`, `x`}, `{"a": 1, "b": [2, 3, "x"], "c": 4}`, nil}, + {[]any{`{"a": 1, "b": [2, 3], "c": 4}`, `$.c`, `y`}, `{"a": 1, "b": [2, 3], "c": [4, "y"]}`, nil}, // Following tests come from MySQL test. - {[]interface{}{`[1,2,3, {"a":[4,5,6]}]`, `$`, 7}, `[1, 2, 3, {"a": [4, 5, 6]}, 7]`, nil}, - {[]interface{}{`[1,2,3, {"a":[4,5,6]}]`, `$`, 7, `$[3].a`, 3.14}, `[1, 2, 3, {"a": [4, 5, 6, 3.14]}, 7]`, nil}, - {[]interface{}{`[1,2,3, {"a":[4,5,6]}]`, `$`, 7, `$[3].b`, 8}, `[1, 2, 3, {"a": [4, 5, 6]}, 7]`, nil}, + {[]any{`[1,2,3, {"a":[4,5,6]}]`, `$`, 7}, `[1, 2, 3, {"a": [4, 5, 6]}, 7]`, nil}, + {[]any{`[1,2,3, {"a":[4,5,6]}]`, `$`, 7, `$[3].a`, 3.14}, `[1, 2, 3, {"a": [4, 5, 6, 3.14]}, 7]`, nil}, + {[]any{`[1,2,3, {"a":[4,5,6]}]`, `$`, 7, `$[3].b`, 8}, `[1, 2, 3, {"a": [4, 5, 6]}, 7]`, nil}, } for i, t := range tbl { @@ -783,50 +783,50 @@ func (s *testEvaluatorSuite) TestJSONSearch(c *C) { jsonString := `["abc", [{"k": "10"}, "def"], {"x":"abc"}, {"y":"bcd"}]` jsonString2 := `["abc", [{"k": "10"}, "def"], {"x":"ab%d"}, {"y":"abcd"}]` tbl := []struct { - input []interface{} - expected interface{} + input []any + expected any success bool }{ // simple case - {[]interface{}{jsonString, `one`, `abc`}, `"$[0]"`, true}, - {[]interface{}{jsonString, `all`, `abc`}, `["$[0]", "$[2].x"]`, true}, - {[]interface{}{jsonString, `all`, `ghi`}, nil, true}, - {[]interface{}{jsonString, `ALL`, `ghi`}, nil, true}, - {[]interface{}{jsonString, `all`, `10`}, `"$[1][0].k"`, true}, - {[]interface{}{jsonString, `all`, `10`, nil, `$`}, `"$[1][0].k"`, true}, - {[]interface{}{jsonString, `all`, `10`, nil, `$[*]`}, `"$[1][0].k"`, true}, - {[]interface{}{jsonString, `all`, `10`, nil, `$**.k`}, `"$[1][0].k"`, true}, - {[]interface{}{jsonString, `all`, `10`, nil, `$[*][0].k`}, `"$[1][0].k"`, true}, - {[]interface{}{jsonString, `all`, `10`, nil, `$[1]`}, `"$[1][0].k"`, true}, - {[]interface{}{jsonString, `all`, `10`, nil, `$[1][0]`}, `"$[1][0].k"`, true}, - {[]interface{}{jsonString, `all`, `abc`, nil, `$[2]`}, `"$[2].x"`, true}, - {[]interface{}{jsonString, `all`, `abc`, nil, `$[2]`, `$[0]`}, `["$[2].x", "$[0]"]`, true}, - {[]interface{}{jsonString, `all`, `abc`, nil, `$[2]`, `$[2]`}, `"$[2].x"`, true}, + {[]any{jsonString, `one`, `abc`}, `"$[0]"`, true}, + {[]any{jsonString, `all`, `abc`}, `["$[0]", "$[2].x"]`, true}, + {[]any{jsonString, `all`, `ghi`}, nil, true}, + {[]any{jsonString, `ALL`, `ghi`}, nil, true}, + {[]any{jsonString, `all`, `10`}, `"$[1][0].k"`, true}, + {[]any{jsonString, `all`, `10`, nil, `$`}, `"$[1][0].k"`, true}, + {[]any{jsonString, `all`, `10`, nil, `$[*]`}, `"$[1][0].k"`, true}, + {[]any{jsonString, `all`, `10`, nil, `$**.k`}, `"$[1][0].k"`, true}, + {[]any{jsonString, `all`, `10`, nil, `$[*][0].k`}, `"$[1][0].k"`, true}, + {[]any{jsonString, `all`, `10`, nil, `$[1]`}, `"$[1][0].k"`, true}, + {[]any{jsonString, `all`, `10`, nil, `$[1][0]`}, `"$[1][0].k"`, true}, + {[]any{jsonString, `all`, `abc`, nil, `$[2]`}, `"$[2].x"`, true}, + {[]any{jsonString, `all`, `abc`, nil, `$[2]`, `$[0]`}, `["$[2].x", "$[0]"]`, true}, + {[]any{jsonString, `all`, `abc`, nil, `$[2]`, `$[2]`}, `"$[2].x"`, true}, // search pattern - {[]interface{}{jsonString, `all`, `%a%`}, `["$[0]", "$[2].x"]`, true}, - {[]interface{}{jsonString, `all`, `%b%`}, `["$[0]", "$[2].x", "$[3].y"]`, true}, - {[]interface{}{jsonString, `all`, `%b%`, nil, `$[0]`}, `"$[0]"`, true}, - {[]interface{}{jsonString, `all`, `%b%`, nil, `$[2]`}, `"$[2].x"`, true}, - {[]interface{}{jsonString, `all`, `%b%`, nil, `$[1]`}, nil, true}, - {[]interface{}{jsonString, `all`, `%b%`, ``, `$[1]`}, nil, true}, - {[]interface{}{jsonString, `all`, `%b%`, nil, `$[3]`}, `"$[3].y"`, true}, - {[]interface{}{jsonString2, `all`, `ab_d`}, `["$[2].x", "$[3].y"]`, true}, + {[]any{jsonString, `all`, `%a%`}, `["$[0]", "$[2].x"]`, true}, + {[]any{jsonString, `all`, `%b%`}, `["$[0]", "$[2].x", "$[3].y"]`, true}, + {[]any{jsonString, `all`, `%b%`, nil, `$[0]`}, `"$[0]"`, true}, + {[]any{jsonString, `all`, `%b%`, nil, `$[2]`}, `"$[2].x"`, true}, + {[]any{jsonString, `all`, `%b%`, nil, `$[1]`}, nil, true}, + {[]any{jsonString, `all`, `%b%`, ``, `$[1]`}, nil, true}, + {[]any{jsonString, `all`, `%b%`, nil, `$[3]`}, `"$[3].y"`, true}, + {[]any{jsonString2, `all`, `ab_d`}, `["$[2].x", "$[3].y"]`, true}, // escape char - {[]interface{}{jsonString2, `all`, `ab%d`}, `["$[2].x", "$[3].y"]`, true}, - {[]interface{}{jsonString2, `all`, `ab\%d`}, `"$[2].x"`, true}, - {[]interface{}{jsonString2, `all`, `ab|%d`, `|`}, `"$[2].x"`, true}, + {[]any{jsonString2, `all`, `ab%d`}, `["$[2].x", "$[3].y"]`, true}, + {[]any{jsonString2, `all`, `ab\%d`}, `"$[2].x"`, true}, + {[]any{jsonString2, `all`, `ab|%d`, `|`}, `"$[2].x"`, true}, // error handle - {[]interface{}{nil, `all`, `abc`}, nil, true}, // NULL json - {[]interface{}{`a`, `all`, `abc`}, nil, false}, // non json - {[]interface{}{jsonString, `wrong`, `abc`}, nil, false}, // wrong one_or_all - {[]interface{}{jsonString, `all`, nil}, nil, true}, // NULL search_str - {[]interface{}{jsonString, `all`, `abc`, `??`}, nil, false}, // wrong escape_char - {[]interface{}{jsonString, `all`, `abc`, nil, nil}, nil, true}, // NULL path - {[]interface{}{jsonString, `all`, `abc`, nil, `$xx`}, nil, false}, // wrong path - {[]interface{}{jsonString, nil, `abc`}, nil, true}, + {[]any{nil, `all`, `abc`}, nil, true}, // NULL json + {[]any{`a`, `all`, `abc`}, nil, false}, // non json + {[]any{jsonString, `wrong`, `abc`}, nil, false}, // wrong one_or_all + {[]any{jsonString, `all`, nil}, nil, true}, // NULL search_str + {[]any{jsonString, `all`, `abc`, `??`}, nil, false}, // wrong escape_char + {[]any{jsonString, `all`, `abc`, nil, nil}, nil, true}, // NULL path + {[]any{jsonString, `all`, `abc`, nil, `$xx`}, nil, false}, // wrong path + {[]any{jsonString, nil, `abc`}, nil, true}, } for _, t := range tbl { args := types.MakeDatums(t.input...) @@ -855,42 +855,42 @@ func (s *testEvaluatorSuite) TestJSONSearch(c *C) { func (s *testEvaluatorSuite) TestJSONArrayInsert(c *C) { fc := funcs[ast.JSONArrayInsert] tbl := []struct { - input []interface{} - expected interface{} + input []any + expected any success bool err *terror.Error }{ // Success - {[]interface{}{`{"a": 1, "b": [2, 3], "c": 4}`, `$.b[1]`, `z`}, `{"a": 1, "b": [2, "z", 3], "c": 4}`, true, nil}, - {[]interface{}{`{"a": 1, "b": [2, 3], "c": 4}`, `$.a[1]`, `z`}, `{"a": 1, "b": [2, 3], "c": 4}`, true, nil}, - {[]interface{}{`{"a": 1, "b": [2, 3], "c": 4}`, `$.d[1]`, `z`}, `{"a": 1, "b": [2, 3], "c": 4}`, true, nil}, - {[]interface{}{`[{"a": 1, "b": [2, 3], "c": 4}]`, `$[1]`, `w`}, `[{"a": 1, "b": [2, 3], "c": 4}, "w"]`, true, nil}, - {[]interface{}{`[{"a": 1, "b": [2, 3], "c": 4}]`, `$[0]`, nil}, `[null, {"a": 1, "b": [2, 3], "c": 4}]`, true, nil}, - {[]interface{}{`[1, 2, 3]`, `$[100]`, `{"b": 2}`}, `[1, 2, 3, "{\"b\": 2}"]`, true, nil}, + {[]any{`{"a": 1, "b": [2, 3], "c": 4}`, `$.b[1]`, `z`}, `{"a": 1, "b": [2, "z", 3], "c": 4}`, true, nil}, + {[]any{`{"a": 1, "b": [2, 3], "c": 4}`, `$.a[1]`, `z`}, `{"a": 1, "b": [2, 3], "c": 4}`, true, nil}, + {[]any{`{"a": 1, "b": [2, 3], "c": 4}`, `$.d[1]`, `z`}, `{"a": 1, "b": [2, 3], "c": 4}`, true, nil}, + {[]any{`[{"a": 1, "b": [2, 3], "c": 4}]`, `$[1]`, `w`}, `[{"a": 1, "b": [2, 3], "c": 4}, "w"]`, true, nil}, + {[]any{`[{"a": 1, "b": [2, 3], "c": 4}]`, `$[0]`, nil}, `[null, {"a": 1, "b": [2, 3], "c": 4}]`, true, nil}, + {[]any{`[1, 2, 3]`, `$[100]`, `{"b": 2}`}, `[1, 2, 3, "{\"b\": 2}"]`, true, nil}, // About null - {[]interface{}{nil, `$`, nil}, nil, true, nil}, - {[]interface{}{nil, `$`, `a`}, nil, true, nil}, - {[]interface{}{`[]`, `$[0]`, nil}, `[null]`, true, nil}, - {[]interface{}{`{}`, `$[0]`, nil}, `{}`, true, nil}, + {[]any{nil, `$`, nil}, nil, true, nil}, + {[]any{nil, `$`, `a`}, nil, true, nil}, + {[]any{`[]`, `$[0]`, nil}, `[null]`, true, nil}, + {[]any{`{}`, `$[0]`, nil}, `{}`, true, nil}, // Bad arguments - {[]interface{}{`asdf`, `$`, nil}, nil, false, json.ErrInvalidJSONText}, - {[]interface{}{``, `$`, nil}, nil, false, json.ErrInvalidJSONText}, - {[]interface{}{`{"a": 1, "b": [2, 3], "c": 4}`, `$.d`}, nil, false, ErrIncorrectParameterCount}, - {[]interface{}{`{"a": 1, "b": [2, 3], "c": 4}`, `$.c`, `y`, `$.b`}, nil, false, ErrIncorrectParameterCount}, - {[]interface{}{`{"a": 1, "b": [2, 3], "c": 4}`, nil, nil}, nil, true, nil}, - {[]interface{}{`{"a": 1, "b": [2, 3], "c": 4}`, `asdf`, nil}, nil, false, json.ErrInvalidJSONPath}, - {[]interface{}{`{"a": 1, "b": [2, 3], "c": 4}`, 42, nil}, nil, false, json.ErrInvalidJSONPath}, - {[]interface{}{`{"a": 1, "b": [2, 3], "c": 4}`, `$.*`, nil}, nil, false, json.ErrInvalidJSONPathWildcard}, - {[]interface{}{`{"a": 1, "b": [2, 3], "c": 4}`, `$.b[0]`, nil, `$.a`, nil}, nil, false, json.ErrInvalidJSONPathArrayCell}, - {[]interface{}{`{"a": 1, "b": [2, 3], "c": 4}`, `$.a`, nil}, nil, false, json.ErrInvalidJSONPathArrayCell}, + {[]any{`asdf`, `$`, nil}, nil, false, json.ErrInvalidJSONText}, + {[]any{``, `$`, nil}, nil, false, json.ErrInvalidJSONText}, + {[]any{`{"a": 1, "b": [2, 3], "c": 4}`, `$.d`}, nil, false, ErrIncorrectParameterCount}, + {[]any{`{"a": 1, "b": [2, 3], "c": 4}`, `$.c`, `y`, `$.b`}, nil, false, ErrIncorrectParameterCount}, + {[]any{`{"a": 1, "b": [2, 3], "c": 4}`, nil, nil}, nil, true, nil}, + {[]any{`{"a": 1, "b": [2, 3], "c": 4}`, `asdf`, nil}, nil, false, json.ErrInvalidJSONPath}, + {[]any{`{"a": 1, "b": [2, 3], "c": 4}`, 42, nil}, nil, false, json.ErrInvalidJSONPath}, + {[]any{`{"a": 1, "b": [2, 3], "c": 4}`, `$.*`, nil}, nil, false, json.ErrInvalidJSONPathWildcard}, + {[]any{`{"a": 1, "b": [2, 3], "c": 4}`, `$.b[0]`, nil, `$.a`, nil}, nil, false, json.ErrInvalidJSONPathArrayCell}, + {[]any{`{"a": 1, "b": [2, 3], "c": 4}`, `$.a`, nil}, nil, false, json.ErrInvalidJSONPathArrayCell}, // Following tests come from MySQL doc. - {[]interface{}{`["a", {"b": [1, 2]}, [3, 4]]`, `$[1]`, `x`}, `["a", "x", {"b": [1, 2]}, [3, 4]]`, true, nil}, - {[]interface{}{`["a", {"b": [1, 2]}, [3, 4]]`, `$[100]`, `x`}, `["a", {"b": [1, 2]}, [3, 4], "x"]`, true, nil}, - {[]interface{}{`["a", {"b": [1, 2]}, [3, 4]]`, `$[1].b[0]`, `x`}, `["a", {"b": ["x", 1, 2]}, [3, 4]]`, true, nil}, - {[]interface{}{`["a", {"b": [1, 2]}, [3, 4]]`, `$[2][1]`, `y`}, `["a", {"b": [1, 2]}, [3, "y", 4]]`, true, nil}, - {[]interface{}{`["a", {"b": [1, 2]}, [3, 4]]`, `$[0]`, `x`, `$[2][1]`, `y`}, `["x", "a", {"b": [1, 2]}, [3, 4]]`, true, nil}, + {[]any{`["a", {"b": [1, 2]}, [3, 4]]`, `$[1]`, `x`}, `["a", "x", {"b": [1, 2]}, [3, 4]]`, true, nil}, + {[]any{`["a", {"b": [1, 2]}, [3, 4]]`, `$[100]`, `x`}, `["a", {"b": [1, 2]}, [3, 4], "x"]`, true, nil}, + {[]any{`["a", {"b": [1, 2]}, [3, 4]]`, `$[1].b[0]`, `x`}, `["a", {"b": ["x", 1, 2]}, [3, 4]]`, true, nil}, + {[]any{`["a", {"b": [1, 2]}, [3, 4]]`, `$[2][1]`, `y`}, `["a", {"b": [1, 2]}, [3, "y", 4]]`, true, nil}, + {[]any{`["a", {"b": [1, 2]}, [3, 4]]`, `$[0]`, `x`, `$[2][1]`, `y`}, `["x", "a", {"b": [1, 2]}, [3, 4]]`, true, nil}, // More test cases - {[]interface{}{`["a", {"b": [1, 2]}, [3, 4]]`, `$[0]`, `x`, `$[0]`, `y`}, `["y", "x", "a", {"b": [1, 2]}, [3, 4]]`, true, nil}, + {[]any{`["a", {"b": [1, 2]}, [3, 4]]`, `$[0]`, `x`, `$[0]`, `y`}, `["y", "x", "a", {"b": [1, 2]}, [3, 4]]`, true, nil}, } for _, t := range tbl { args := types.MakeDatums(t.input...) @@ -927,8 +927,8 @@ func (s *testEvaluatorSuite) TestJSONArrayInsert(c *C) { func (s *testEvaluatorSuite) TestJSONValid(c *C) { fc := funcs[ast.JSONValid] tbl := []struct { - Input interface{} - Expected interface{} + Input any + Expected any }{ {`{"a":1}`, 1}, {`hello`, 0}, @@ -957,25 +957,25 @@ func (s *testEvaluatorSuite) TestJSONValid(c *C) { func (s *testEvaluatorSuite) TestJSONStorageSize(c *C) { fc := funcs[ast.JSONStorageSize] tbl := []struct { - input []interface{} - expected interface{} + input []any + expected any success bool }{ // Tests scalar arguments - {[]interface{}{`null`}, 4, true}, - {[]interface{}{`true`}, 4, true}, - {[]interface{}{`1`}, 1, true}, - {[]interface{}{`"1"`}, 3, true}, + {[]any{`null`}, 4, true}, + {[]any{`true`}, 4, true}, + {[]any{`1`}, 1, true}, + {[]any{`"1"`}, 3, true}, // Tests nil arguments - {[]interface{}{nil}, nil, true}, + {[]any{nil}, nil, true}, // Tests valid json documents - {[]interface{}{`{}`}, 2, true}, - {[]interface{}{`{"a":1}`}, 8, true}, - {[]interface{}{`[{"a":{"a":1},"b":2}]`}, 25, true}, - {[]interface{}{`{"a": 1000, "b": "wxyz", "c": "[1, 3, 5, 7]"}`}, 45, true}, + {[]any{`{}`}, 2, true}, + {[]any{`{"a":1}`}, 8, true}, + {[]any{`[{"a":{"a":1},"b":2}]`}, 25, true}, + {[]any{`{"a": 1000, "b": "wxyz", "c": "[1, 3, 5, 7]"}`}, 45, true}, // Tests invalid json documents - {[]interface{}{`[{"a":1]`}, 0, false}, - {[]interface{}{`[{a":1]`}, 0, false}, + {[]any{`[{"a":1]`}, 0, false}, + {[]any{`[{a":1]`}, 0, false}, } for _, t := range tbl { args := types.MakeDatums(t.input...) diff --git a/expression/builtin_json_vec.go b/expression/builtin_json_vec.go index db512fc81..7b820854d 100644 --- a/expression/builtin_json_vec.go +++ b/expression/builtin_json_vec.go @@ -217,9 +217,9 @@ func (b *builtinJSONArraySig) vectorized() bool { func (b *builtinJSONArraySig) vecEvalJSON(input *chunk.Chunk, result *chunk.Column) error { nr := input.NumRows() - jsons := make([][]interface{}, nr) + jsons := make([][]any, nr) for i := 0; i < nr; i++ { - jsons[i] = make([]interface{}, 0, len(b.args)) + jsons[i] = make([]any, 0, len(b.args)) } for _, arg := range b.args { j, err := b.bufAllocator.get(types.ETJson, nr) @@ -477,9 +477,9 @@ func (b *builtinJSONObjectSig) vecEvalJSON(input *chunk.Chunk, result *chunk.Col return err } - jsons := make([]map[string]interface{}, nr) + jsons := make([]map[string]any, nr) for i := 0; i < nr; i++ { - jsons[i] = make(map[string]interface{}, len(b.args)>>1) + jsons[i] = make(map[string]any, len(b.args)>>1) } argBuffers := make([]*chunk.Column, len(b.args)) diff --git a/expression/builtin_math_test.go b/expression/builtin_math_test.go index 4d792bae3..0a2c65cdb 100644 --- a/expression/builtin_math_test.go +++ b/expression/builtin_math_test.go @@ -30,8 +30,8 @@ import ( func (s *testEvaluatorSuite) TestAbs(c *C) { tbl := []struct { - Arg interface{} - Ret interface{} + Arg any + Ret any }{ {nil, nil}, {int64(1), int64(1)}, @@ -62,8 +62,8 @@ func (s *testEvaluatorSuite) TestCeil(c *C) { }() type testCase struct { - arg interface{} - expect interface{} + arg any + expect any isNil bool getErr bool } @@ -91,7 +91,7 @@ func (s *testEvaluatorSuite) TestCeil(c *C) { runCasesOn := func(funcName string, cases []testCase, exps []Expression) { for _, test := range cases { - f, err := newFunctionForTest(s.ctx, funcName, s.primitiveValsToConstants([]interface{}{test.arg})...) + f, err := newFunctionForTest(s.ctx, funcName, s.primitiveValsToConstants([]any{test.arg})...) c.Assert(err, IsNil) result, err := f.Eval(chunk.Row{}) @@ -119,7 +119,7 @@ func (s *testEvaluatorSuite) TestCeil(c *C) { func (s *testEvaluatorSuite) TestExp(c *C) { tests := []struct { - args interface{} + args any expect float64 isNil bool getErr bool @@ -140,7 +140,7 @@ func (s *testEvaluatorSuite) TestExp(c *C) { } for _, test := range tests { - f, err := newFunctionForTest(s.ctx, ast.Exp, s.primitiveValsToConstants([]interface{}{test.args})...) + f, err := newFunctionForTest(s.ctx, ast.Exp, s.primitiveValsToConstants([]any{test.args})...) c.Assert(err, IsNil) result, err := f.Eval(chunk.Row{}) @@ -184,8 +184,8 @@ func (s *testEvaluatorSuite) TestFloor(c *C) { } for _, test := range []struct { - arg interface{} - expect interface{} + arg any + expect any isNil bool getErr bool }{ @@ -201,7 +201,7 @@ func (s *testEvaluatorSuite) TestFloor(c *C) { {genDuration(0, 12, 34), float64(1234), false, false}, {genTime(2017, 7, 19), float64(20170719000000), false, false}, } { - f, err := newFunctionForTest(s.ctx, ast.Floor, s.primitiveValsToConstants([]interface{}{test.arg})...) + f, err := newFunctionForTest(s.ctx, ast.Floor, s.primitiveValsToConstants([]any{test.arg})...) c.Assert(err, IsNil) result, err := f.Eval(chunk.Row{}) @@ -234,21 +234,21 @@ func (s *testEvaluatorSuite) TestFloor(c *C) { func (s *testEvaluatorSuite) TestLog(c *C) { tests := []struct { - args []interface{} + args []any expect float64 isNil bool getErr bool }{ - {[]interface{}{nil}, 0, true, false}, - {[]interface{}{nil, nil}, 0, true, false}, - {[]interface{}{int64(100)}, 4.605170185988092, false, false}, - {[]interface{}{float64(100)}, 4.605170185988092, false, false}, - {[]interface{}{int64(10), int64(100)}, 2, false, false}, - {[]interface{}{float64(10), float64(100)}, 2, false, false}, - {[]interface{}{float64(-1)}, 0, true, false}, - {[]interface{}{float64(1), float64(2)}, 0, true, false}, - {[]interface{}{float64(0.5), float64(0.25)}, 2, false, false}, - {[]interface{}{"abc"}, 0, false, true}, + {[]any{nil}, 0, true, false}, + {[]any{nil, nil}, 0, true, false}, + {[]any{int64(100)}, 4.605170185988092, false, false}, + {[]any{float64(100)}, 4.605170185988092, false, false}, + {[]any{int64(10), int64(100)}, 2, false, false}, + {[]any{float64(10), float64(100)}, 2, false, false}, + {[]any{float64(-1)}, 0, true, false}, + {[]any{float64(1), float64(2)}, 0, true, false}, + {[]any{float64(0.5), float64(0.25)}, 2, false, false}, + {[]any{"abc"}, 0, false, true}, } for _, test := range tests { @@ -274,7 +274,7 @@ func (s *testEvaluatorSuite) TestLog(c *C) { func (s *testEvaluatorSuite) TestLog2(c *C) { tests := []struct { - args interface{} + args any expect float64 isNil bool getErr bool @@ -288,7 +288,7 @@ func (s *testEvaluatorSuite) TestLog2(c *C) { } for _, test := range tests { - f, err := newFunctionForTest(s.ctx, ast.Log2, s.primitiveValsToConstants([]interface{}{test.args})...) + f, err := newFunctionForTest(s.ctx, ast.Log2, s.primitiveValsToConstants([]any{test.args})...) c.Assert(err, IsNil) result, err := f.Eval(chunk.Row{}) @@ -310,7 +310,7 @@ func (s *testEvaluatorSuite) TestLog2(c *C) { func (s *testEvaluatorSuite) TestLog10(c *C) { tests := []struct { - args interface{} + args any expect float64 isNil bool getErr bool @@ -324,7 +324,7 @@ func (s *testEvaluatorSuite) TestLog10(c *C) { } for _, test := range tests { - f, err := newFunctionForTest(s.ctx, ast.Log10, s.primitiveValsToConstants([]interface{}{test.args})...) + f, err := newFunctionForTest(s.ctx, ast.Log10, s.primitiveValsToConstants([]any{test.args})...) c.Assert(err, IsNil) result, err := f.Eval(chunk.Row{}) @@ -366,13 +366,13 @@ func (s *testEvaluatorSuite) TestRand(c *C) { func (s *testEvaluatorSuite) TestPow(c *C) { tbl := []struct { - Arg []interface{} + Arg []any Ret float64 }{ - {[]interface{}{1, 3}, 1}, - {[]interface{}{2, 2}, 4}, - {[]interface{}{4, 0.5}, 2}, - {[]interface{}{4, -2}, 0.0625}, + {[]any{1, 3}, 1}, + {[]any{2, 2}, 4}, + {[]any{4, 0.5}, 2}, + {[]any{4, -2}, 0.0625}, } Dtbl := tblToDtbl(tbl) @@ -387,11 +387,11 @@ func (s *testEvaluatorSuite) TestPow(c *C) { } errTbl := []struct { - Arg []interface{} + Arg []any }{ - {[]interface{}{"test", "test"}}, - {[]interface{}{1, "test"}}, - {[]interface{}{10, 700}}, // added overflow test + {[]any{"test", "test"}}, + {[]any{1, "test"}}, + {[]any{10, 700}}, // added overflow test } errDtbl := tblToDtbl(errTbl) @@ -407,26 +407,26 @@ func (s *testEvaluatorSuite) TestPow(c *C) { func (s *testEvaluatorSuite) TestRound(c *C) { newDec := types.NewDecFromStringForTest tbl := []struct { - Arg []interface{} - Ret interface{} + Arg []any + Ret any }{ - {[]interface{}{-1.23}, -1}, - {[]interface{}{-1.23, 0}, -1}, - {[]interface{}{-1.58}, -2}, - {[]interface{}{1.58}, 2}, - {[]interface{}{1.298, 1}, 1.3}, - {[]interface{}{1.298}, 1}, - {[]interface{}{1.298, 0}, 1}, - {[]interface{}{23.298, -1}, 20}, - {[]interface{}{newDec("-1.23")}, newDec("-1")}, - {[]interface{}{newDec("-1.23"), 1}, newDec("-1.2")}, - {[]interface{}{newDec("-1.58")}, newDec("-2")}, - {[]interface{}{newDec("1.58")}, newDec("2")}, - {[]interface{}{newDec("1.58"), 1}, newDec("1.6")}, - {[]interface{}{newDec("23.298"), -1}, newDec("20")}, - {[]interface{}{nil, 2}, nil}, - {[]interface{}{1, -2012}, 0}, - {[]interface{}{1, -201299999999999}, 0}, + {[]any{-1.23}, -1}, + {[]any{-1.23, 0}, -1}, + {[]any{-1.58}, -2}, + {[]any{1.58}, 2}, + {[]any{1.298, 1}, 1.3}, + {[]any{1.298}, 1}, + {[]any{1.298, 0}, 1}, + {[]any{23.298, -1}, 20}, + {[]any{newDec("-1.23")}, newDec("-1")}, + {[]any{newDec("-1.23"), 1}, newDec("-1.2")}, + {[]any{newDec("-1.58")}, newDec("-2")}, + {[]any{newDec("1.58")}, newDec("2")}, + {[]any{newDec("1.58"), 1}, newDec("1.6")}, + {[]any{newDec("23.298"), -1}, newDec("20")}, + {[]any{nil, 2}, nil}, + {[]any{1, -2012}, 0}, + {[]any{1, -201299999999999}, 0}, } Dtbl := tblToDtbl(tbl) @@ -458,31 +458,31 @@ func (s *testEvaluatorSuite) TestRound(c *C) { func (s *testEvaluatorSuite) TestTruncate(c *C) { newDec := types.NewDecFromStringForTest tbl := []struct { - Arg []interface{} - Ret interface{} + Arg []any + Ret any }{ - {[]interface{}{-1.23, 0}, -1}, - {[]interface{}{1.58, 0}, 1}, - {[]interface{}{1.298, 1}, 1.2}, - {[]interface{}{123.2, -1}, 120}, - {[]interface{}{123.2, 100}, 123.2}, - {[]interface{}{123.2, -100}, 0}, - {[]interface{}{123.2, -100}, 0}, - {[]interface{}{1.797693134862315708145274237317043567981e+308, 2}, + {[]any{-1.23, 0}, -1}, + {[]any{1.58, 0}, 1}, + {[]any{1.298, 1}, 1.2}, + {[]any{123.2, -1}, 120}, + {[]any{123.2, 100}, 123.2}, + {[]any{123.2, -100}, 0}, + {[]any{123.2, -100}, 0}, + {[]any{1.797693134862315708145274237317043567981e+308, 2}, 1.797693134862315708145274237317043567981e+308}, - {[]interface{}{newDec("-1.23"), 0}, newDec("-1")}, - {[]interface{}{newDec("-1.23"), 1}, newDec("-1.2")}, - {[]interface{}{newDec("-11.23"), -1}, newDec("-10")}, - {[]interface{}{newDec("1.58"), 0}, newDec("1")}, - {[]interface{}{newDec("1.58"), 1}, newDec("1.5")}, - {[]interface{}{newDec("11.58"), -1}, newDec("10")}, - {[]interface{}{newDec("23.298"), -1}, newDec("20")}, - {[]interface{}{newDec("23.298"), -100}, newDec("0")}, - {[]interface{}{newDec("23.298"), 100}, newDec("23.298")}, - {[]interface{}{nil, 2}, nil}, - {[]interface{}{uint64(9223372036854775808), -10}, 9223372030000000000}, - {[]interface{}{9223372036854775807, -7}, 9223372036850000000}, - {[]interface{}{uint64(18446744073709551615), -10}, uint64(18446744070000000000)}, + {[]any{newDec("-1.23"), 0}, newDec("-1")}, + {[]any{newDec("-1.23"), 1}, newDec("-1.2")}, + {[]any{newDec("-11.23"), -1}, newDec("-10")}, + {[]any{newDec("1.58"), 0}, newDec("1")}, + {[]any{newDec("1.58"), 1}, newDec("1.5")}, + {[]any{newDec("11.58"), -1}, newDec("10")}, + {[]any{newDec("23.298"), -1}, newDec("20")}, + {[]any{newDec("23.298"), -100}, newDec("0")}, + {[]any{newDec("23.298"), 100}, newDec("23.298")}, + {[]any{nil, 2}, nil}, + {[]any{uint64(9223372036854775808), -10}, 9223372030000000000}, + {[]any{9223372036854775807, -7}, 9223372036850000000}, + {[]any{uint64(18446744073709551615), -10}, uint64(18446744070000000000)}, } Dtbl := tblToDtbl(tbl) @@ -500,16 +500,16 @@ func (s *testEvaluatorSuite) TestTruncate(c *C) { func (s *testEvaluatorSuite) TestCRC32(c *C) { tbl := []struct { - Arg []interface{} - Ret interface{} + Arg []any + Ret any }{ - {[]interface{}{nil}, nil}, - {[]interface{}{""}, 0}, - {[]interface{}{-1}, 808273962}, - {[]interface{}{"-1"}, 808273962}, - {[]interface{}{"mysql"}, 2501908538}, - {[]interface{}{"MySQL"}, 3259397556}, - {[]interface{}{"hello"}, 907060870}, + {[]any{nil}, nil}, + {[]any{""}, 0}, + {[]any{-1}, 808273962}, + {[]any{"-1"}, 808273962}, + {[]any{"mysql"}, 2501908538}, + {[]any{"MySQL"}, 3259397556}, + {[]any{"hello"}, 907060870}, } Dtbl := tblToDtbl(tbl) @@ -526,25 +526,25 @@ func (s *testEvaluatorSuite) TestCRC32(c *C) { func (s *testEvaluatorSuite) TestConv(c *C) { cases := []struct { - args []interface{} - expected interface{} + args []any + expected any isNil bool getErr bool }{ - {[]interface{}{"a", 16, 2}, "1010", false, false}, - {[]interface{}{"6E", 18, 8}, "172", false, false}, - {[]interface{}{"-17", 10, -18}, "-H", false, false}, - {[]interface{}{"-17", 10, 18}, "2D3FGB0B9CG4BD1H", false, false}, - {[]interface{}{nil, 10, 10}, "0", true, false}, - {[]interface{}{"+18aZ", 7, 36}, "1", false, false}, - {[]interface{}{"18446744073709551615", -10, 16}, "7FFFFFFFFFFFFFFF", false, false}, - {[]interface{}{"12F", -10, 16}, "C", false, false}, - {[]interface{}{" FF ", 16, 10}, "255", false, false}, - {[]interface{}{"TIDB", 10, 8}, "0", false, false}, - {[]interface{}{"aa", 10, 2}, "0", false, false}, - {[]interface{}{" A", -10, 16}, "0", false, false}, - {[]interface{}{"a6a", 10, 8}, "0", false, false}, - {[]interface{}{"a6a", 1, 8}, "0", true, false}, + {[]any{"a", 16, 2}, "1010", false, false}, + {[]any{"6E", 18, 8}, "172", false, false}, + {[]any{"-17", 10, -18}, "-H", false, false}, + {[]any{"-17", 10, 18}, "2D3FGB0B9CG4BD1H", false, false}, + {[]any{nil, 10, 10}, "0", true, false}, + {[]any{"+18aZ", 7, 36}, "1", false, false}, + {[]any{"18446744073709551615", -10, 16}, "7FFFFFFFFFFFFFFF", false, false}, + {[]any{"12F", -10, 16}, "C", false, false}, + {[]any{" FF ", 16, 10}, "255", false, false}, + {[]any{"TIDB", 10, 8}, "0", false, false}, + {[]any{"aa", 10, 2}, "0", false, false}, + {[]any{" A", -10, 16}, "0", false, false}, + {[]any{"a6a", 10, 8}, "0", false, false}, + {[]any{"a6a", 1, 8}, "0", true, false}, } for _, t := range cases { @@ -596,21 +596,21 @@ func (s *testEvaluatorSuite) TestSign(c *C) { }() for _, t := range []struct { - num []interface{} - ret interface{} + num []any + ret any }{ - {[]interface{}{nil}, nil}, - {[]interface{}{1}, int64(1)}, - {[]interface{}{0}, int64(0)}, - {[]interface{}{-1}, int64(-1)}, - {[]interface{}{0.4}, int64(1)}, - {[]interface{}{-0.4}, int64(-1)}, - {[]interface{}{"1"}, int64(1)}, - {[]interface{}{"-1"}, int64(-1)}, - {[]interface{}{"1a"}, int64(1)}, - {[]interface{}{"-1a"}, int64(-1)}, - {[]interface{}{"a"}, int64(0)}, - {[]interface{}{uint64(9223372036854775808)}, int64(1)}, + {[]any{nil}, nil}, + {[]any{1}, int64(1)}, + {[]any{0}, int64(0)}, + {[]any{-1}, int64(-1)}, + {[]any{0.4}, int64(1)}, + {[]any{-0.4}, int64(-1)}, + {[]any{"1"}, int64(1)}, + {[]any{"-1"}, int64(-1)}, + {[]any{"1a"}, int64(1)}, + {[]any{"-1a"}, int64(-1)}, + {[]any{"a"}, int64(0)}, + {[]any{uint64(9223372036854775808)}, int64(1)}, } { fc := funcs[ast.Sign] f, err := fc.getFunction(s.ctx, s.primitiveValsToConstants(t.num)) @@ -625,7 +625,7 @@ func (s *testEvaluatorSuite) TestDegrees(c *C) { sc := s.ctx.GetSessionVars().StmtCtx sc.IgnoreTruncate = false cases := []struct { - args interface{} + args any expected float64 isNil bool getErr bool @@ -643,7 +643,7 @@ func (s *testEvaluatorSuite) TestDegrees(c *C) { } for _, t := range cases { - f, err := newFunctionForTest(s.ctx, ast.Degrees, s.primitiveValsToConstants([]interface{}{t.args})...) + f, err := newFunctionForTest(s.ctx, ast.Degrees, s.primitiveValsToConstants([]any{t.args})...) c.Assert(err, IsNil) d, err := f.Eval(chunk.Row{}) if t.getErr { @@ -663,15 +663,15 @@ func (s *testEvaluatorSuite) TestDegrees(c *C) { func (s *testEvaluatorSuite) TestSqrt(c *C) { tbl := []struct { - Arg []interface{} - Ret interface{} + Arg []any + Ret any }{ - {[]interface{}{nil}, nil}, - {[]interface{}{int64(1)}, float64(1)}, - {[]interface{}{float64(4)}, float64(2)}, - {[]interface{}{"4"}, float64(2)}, - {[]interface{}{"9"}, float64(3)}, - {[]interface{}{"-16"}, nil}, + {[]any{nil}, nil}, + {[]any{int64(1)}, float64(1)}, + {[]any{float64(4)}, float64(2)}, + {[]any{"4"}, float64(2)}, + {[]any{"9"}, float64(3)}, + {[]any{"-16"}, nil}, } for _, t := range tbl { @@ -695,8 +695,8 @@ func (s *testEvaluatorSuite) TestPi(c *C) { func (s *testEvaluatorSuite) TestRadians(c *C) { tbl := []struct { - Arg interface{} - Ret interface{} + Arg any + Ret any }{ {nil, nil}, {0, float64(0)}, @@ -726,7 +726,7 @@ func (s *testEvaluatorSuite) TestRadians(c *C) { func (s *testEvaluatorSuite) TestSin(c *C) { cases := []struct { - args interface{} + args any expected float64 isNil bool getErr bool @@ -745,7 +745,7 @@ func (s *testEvaluatorSuite) TestSin(c *C) { } for _, t := range cases { - f, err := newFunctionForTest(s.ctx, ast.Sin, s.primitiveValsToConstants([]interface{}{t.args})...) + f, err := newFunctionForTest(s.ctx, ast.Sin, s.primitiveValsToConstants([]any{t.args})...) c.Assert(err, IsNil) d, err := f.Eval(chunk.Row{}) @@ -767,7 +767,7 @@ func (s *testEvaluatorSuite) TestSin(c *C) { func (s *testEvaluatorSuite) TestCos(c *C) { cases := []struct { - args interface{} + args any expected float64 isNil bool getErr bool @@ -783,7 +783,7 @@ func (s *testEvaluatorSuite) TestCos(c *C) { } for _, t := range cases { - f, err := newFunctionForTest(s.ctx, ast.Cos, s.primitiveValsToConstants([]interface{}{t.args})...) + f, err := newFunctionForTest(s.ctx, ast.Cos, s.primitiveValsToConstants([]any{t.args})...) c.Assert(err, IsNil) d, err := f.Eval(chunk.Row{}) @@ -805,7 +805,7 @@ func (s *testEvaluatorSuite) TestCos(c *C) { func (s *testEvaluatorSuite) TestAcos(c *C) { tests := []struct { - args interface{} + args any expect float64 isNil bool getErr bool @@ -819,7 +819,7 @@ func (s *testEvaluatorSuite) TestAcos(c *C) { } for _, test := range tests { - f, err := newFunctionForTest(s.ctx, ast.Acos, s.primitiveValsToConstants([]interface{}{test.args})...) + f, err := newFunctionForTest(s.ctx, ast.Acos, s.primitiveValsToConstants([]any{test.args})...) c.Assert(err, IsNil) result, err := f.Eval(chunk.Row{}) @@ -841,7 +841,7 @@ func (s *testEvaluatorSuite) TestAcos(c *C) { func (s *testEvaluatorSuite) TestAsin(c *C) { tests := []struct { - args interface{} + args any expect float64 isNil bool getErr bool @@ -855,7 +855,7 @@ func (s *testEvaluatorSuite) TestAsin(c *C) { } for _, test := range tests { - f, err := newFunctionForTest(s.ctx, ast.Asin, s.primitiveValsToConstants([]interface{}{test.args})...) + f, err := newFunctionForTest(s.ctx, ast.Asin, s.primitiveValsToConstants([]any{test.args})...) c.Assert(err, IsNil) result, err := f.Eval(chunk.Row{}) @@ -877,17 +877,17 @@ func (s *testEvaluatorSuite) TestAsin(c *C) { func (s *testEvaluatorSuite) TestAtan(c *C) { tests := []struct { - args []interface{} + args []any expect float64 isNil bool getErr bool }{ - {[]interface{}{nil}, 0, true, false}, - {[]interface{}{nil, nil}, 0, true, false}, - {[]interface{}{float64(1)}, 0.7853981633974483, false, false}, - {[]interface{}{float64(-1)}, -0.7853981633974483, false, false}, - {[]interface{}{float64(0), float64(-2)}, float64(math.Pi), false, false}, - {[]interface{}{"tidb"}, 0, false, true}, + {[]any{nil}, 0, true, false}, + {[]any{nil, nil}, 0, true, false}, + {[]any{float64(1)}, 0.7853981633974483, false, false}, + {[]any{float64(-1)}, -0.7853981633974483, false, false}, + {[]any{float64(0), float64(-2)}, float64(math.Pi), false, false}, + {[]any{"tidb"}, 0, false, true}, } for _, test := range tests { @@ -913,7 +913,7 @@ func (s *testEvaluatorSuite) TestAtan(c *C) { func (s *testEvaluatorSuite) TestTan(c *C) { cases := []struct { - args interface{} + args any expected float64 isNil bool getErr bool @@ -928,7 +928,7 @@ func (s *testEvaluatorSuite) TestTan(c *C) { } for _, t := range cases { - f, err := newFunctionForTest(s.ctx, ast.Tan, s.primitiveValsToConstants([]interface{}{t.args})...) + f, err := newFunctionForTest(s.ctx, ast.Tan, s.primitiveValsToConstants([]any{t.args})...) c.Assert(err, IsNil) d, err := f.Eval(chunk.Row{}) @@ -950,7 +950,7 @@ func (s *testEvaluatorSuite) TestTan(c *C) { func (s *testEvaluatorSuite) TestCot(c *C) { tests := []struct { - args interface{} + args any expect float64 isNil bool getErr bool @@ -967,7 +967,7 @@ func (s *testEvaluatorSuite) TestCot(c *C) { } for _, test := range tests { - f, err := newFunctionForTest(s.ctx, ast.Cot, s.primitiveValsToConstants([]interface{}{test.args})...) + f, err := newFunctionForTest(s.ctx, ast.Cot, s.primitiveValsToConstants([]any{test.args})...) c.Assert(err, IsNil) result, err := f.Eval(chunk.Row{}) diff --git a/expression/builtin_miscellaneous_test.go b/expression/builtin_miscellaneous_test.go index 0a23283c1..1a5400012 100644 --- a/expression/builtin_miscellaneous_test.go +++ b/expression/builtin_miscellaneous_test.go @@ -27,8 +27,8 @@ import ( func (s *testEvaluatorSuite) TestInetAton(c *C) { tbl := []struct { - Input interface{} - Expected interface{} + Input any + Expected any }{ {"", nil}, {nil, nil}, @@ -59,7 +59,7 @@ func (s *testEvaluatorSuite) TestInetAton(c *C) { func (s *testEvaluatorSuite) TestIsIPv4(c *C) { tests := []struct { ip string - expect interface{} + expect any }{ {"192.168.1.1", 1}, {"255.255.255.255", 1}, @@ -117,8 +117,8 @@ func (s *testEvaluatorSuite) TestUUID(c *C) { func (s *testEvaluatorSuite) TestAnyValue(c *C) { tbl := []struct { - arg interface{} - ret interface{} + arg any + ret any }{ {nil, nil}, {1234, 1234}, @@ -139,7 +139,7 @@ func (s *testEvaluatorSuite) TestAnyValue(c *C) { func (s *testEvaluatorSuite) TestIsIPv6(c *C) { tests := []struct { ip string - expect interface{} + expect any }{ {"2001:250:207:0:0:eef2::1", 1}, {"2001:0250:0207:0001:0000:0000:0000:ff02", 1}, @@ -167,7 +167,7 @@ func (s *testEvaluatorSuite) TestIsIPv6(c *C) { func (s *testEvaluatorSuite) TestInetNtoa(c *C) { tests := []struct { ip int - expect interface{} + expect any }{ {167773449, "10.0.5.9"}, {2063728641, "123.2.0.1"}, @@ -196,7 +196,7 @@ func (s *testEvaluatorSuite) TestInetNtoa(c *C) { func (s *testEvaluatorSuite) TestInet6NtoA(c *C) { tests := []struct { ip []byte - expect interface{} + expect any }{ // Success cases {[]byte{0x00, 0x00, 0x00, 0x00}, "0.0.0.0"}, @@ -233,7 +233,7 @@ func (s *testEvaluatorSuite) TestInet6NtoA(c *C) { func (s *testEvaluatorSuite) TestInet6AtoN(c *C) { tests := []struct { ip string - expect interface{} + expect any }{ {"0.0.0.0", []byte{0x00, 0x00, 0x00, 0x00}}, {"10.0.5.9", []byte{0x0A, 0x00, 0x05, 0x09}}, @@ -263,7 +263,7 @@ func (s *testEvaluatorSuite) TestInet6AtoN(c *C) { func (s *testEvaluatorSuite) TestIsIPv4Mapped(c *C) { tests := []struct { ip []byte - expect interface{} + expect any }{ {[]byte{}, 0}, {[]byte{0x10, 0x10, 0x10, 0x10}, 0}, @@ -291,7 +291,7 @@ func (s *testEvaluatorSuite) TestIsIPv4Mapped(c *C) { func (s *testEvaluatorSuite) TestIsIPv4Compat(c *C) { tests := []struct { ip []byte - expect interface{} + expect any }{ {[]byte{}, 0}, {[]byte{0x10, 0x10, 0x10, 0x10}, 0}, @@ -323,7 +323,7 @@ func (s *testEvaluatorSuite) TestNameConst(c *C) { du := types.Duration{Duration: 12*time.Hour + 1*time.Minute + 1*time.Second, Fsp: types.DefaultFsp} cases := []struct { colName string - arg interface{} + arg any isNil bool asserts func(d types.Datum) }{ @@ -351,7 +351,7 @@ func (s *testEvaluatorSuite) TestNameConst(c *C) { } for _, t := range cases { - f, err := newFunctionForTest(s.ctx, ast.NameConst, s.primitiveValsToConstants([]interface{}{t.colName, t.arg})...) + f, err := newFunctionForTest(s.ctx, ast.NameConst, s.primitiveValsToConstants([]any{t.colName, t.arg})...) c.Assert(err, IsNil) d, err := f.Eval(chunk.Row{}) c.Assert(err, IsNil) diff --git a/expression/builtin_op_test.go b/expression/builtin_op_test.go index 5ad0c8707..3ebf646e1 100644 --- a/expression/builtin_op_test.go +++ b/expression/builtin_op_test.go @@ -26,8 +26,8 @@ import ( func (s *testEvaluatorSuite) TestUnary(c *C) { cases := []struct { - args interface{} - expected interface{} + args any + expected any overflow bool getErr bool }{ @@ -44,7 +44,7 @@ func (s *testEvaluatorSuite) TestUnary(c *C) { }() for _, t := range cases { - f, err := newFunctionForTest(s.ctx, ast.UnaryMinus, s.primitiveValsToConstants([]interface{}{t.args})...) + f, err := newFunctionForTest(s.ctx, ast.UnaryMinus, s.primitiveValsToConstants([]any{t.args})...) c.Assert(err, IsNil) d, err := f.Eval(chunk.Row{}) if !t.getErr { @@ -72,33 +72,33 @@ func (s *testEvaluatorSuite) TestLogicAnd(c *C) { sc.IgnoreTruncate = true cases := []struct { - args []interface{} + args []any expected int64 isNil bool getErr bool }{ - {[]interface{}{1, 1}, 1, false, false}, - {[]interface{}{1, 0}, 0, false, false}, - {[]interface{}{0, 1}, 0, false, false}, - {[]interface{}{0, 0}, 0, false, false}, - {[]interface{}{2, -1}, 1, false, false}, - {[]interface{}{"a", "0"}, 0, false, false}, - {[]interface{}{"a", "1"}, 0, false, false}, - {[]interface{}{"1a", "0"}, 0, false, false}, - {[]interface{}{"1a", "1"}, 1, false, false}, - {[]interface{}{0, nil}, 0, false, false}, - {[]interface{}{nil, 0}, 0, false, false}, - {[]interface{}{nil, 1}, 0, true, false}, - {[]interface{}{0.001, 0}, 0, false, false}, - {[]interface{}{0.001, 1}, 1, false, false}, - {[]interface{}{nil, 0.000}, 0, false, false}, - {[]interface{}{nil, 0.001}, 0, true, false}, - {[]interface{}{types.NewDecFromStringForTest("0.000001"), 0}, 0, false, false}, - {[]interface{}{types.NewDecFromStringForTest("0.000001"), 1}, 1, false, false}, - {[]interface{}{types.NewDecFromStringForTest("0.000000"), nil}, 0, false, false}, - {[]interface{}{types.NewDecFromStringForTest("0.000001"), nil}, 0, true, false}, - - {[]interface{}{errors.New("must error"), 1}, 0, false, true}, + {[]any{1, 1}, 1, false, false}, + {[]any{1, 0}, 0, false, false}, + {[]any{0, 1}, 0, false, false}, + {[]any{0, 0}, 0, false, false}, + {[]any{2, -1}, 1, false, false}, + {[]any{"a", "0"}, 0, false, false}, + {[]any{"a", "1"}, 0, false, false}, + {[]any{"1a", "0"}, 0, false, false}, + {[]any{"1a", "1"}, 1, false, false}, + {[]any{0, nil}, 0, false, false}, + {[]any{nil, 0}, 0, false, false}, + {[]any{nil, 1}, 0, true, false}, + {[]any{0.001, 0}, 0, false, false}, + {[]any{0.001, 1}, 1, false, false}, + {[]any{nil, 0.000}, 0, false, false}, + {[]any{nil, 0.001}, 0, true, false}, + {[]any{types.NewDecFromStringForTest("0.000001"), 0}, 0, false, false}, + {[]any{types.NewDecFromStringForTest("0.000001"), 1}, 1, false, false}, + {[]any{types.NewDecFromStringForTest("0.000000"), nil}, 0, false, false}, + {[]any{types.NewDecFromStringForTest("0.000001"), nil}, 0, true, false}, + + {[]any{errors.New("must error"), 1}, 0, false, true}, } for _, t := range cases { @@ -127,16 +127,16 @@ func (s *testEvaluatorSuite) TestLogicAnd(c *C) { func (s *testEvaluatorSuite) TestLeftShift(c *C) { cases := []struct { - args []interface{} + args []any expected uint64 isNil bool getErr bool }{ - {[]interface{}{123, 2}, uint64(492), false, false}, - {[]interface{}{-123, 2}, uint64(18446744073709551124), false, false}, - {[]interface{}{nil, 1}, 0, true, false}, + {[]any{123, 2}, uint64(492), false, false}, + {[]any{-123, 2}, uint64(18446744073709551124), false, false}, + {[]any{nil, 1}, 0, true, false}, - {[]interface{}{errors.New("must error"), 1}, 0, false, true}, + {[]any{errors.New("must error"), 1}, 0, false, true}, } for _, t := range cases { @@ -158,16 +158,16 @@ func (s *testEvaluatorSuite) TestLeftShift(c *C) { func (s *testEvaluatorSuite) TestRightShift(c *C) { cases := []struct { - args []interface{} + args []any expected uint64 isNil bool getErr bool }{ - {[]interface{}{123, 2}, uint64(30), false, false}, - {[]interface{}{-123, 2}, uint64(4611686018427387873), false, false}, - {[]interface{}{nil, 1}, 0, true, false}, + {[]any{123, 2}, uint64(30), false, false}, + {[]any{-123, 2}, uint64(4611686018427387873), false, false}, + {[]any{nil, 1}, 0, true, false}, - {[]interface{}{errors.New("must error"), 1}, 0, false, true}, + {[]any{errors.New("must error"), 1}, 0, false, true}, } for _, t := range cases { @@ -196,16 +196,16 @@ func (s *testEvaluatorSuite) TestRightShift(c *C) { func (s *testEvaluatorSuite) TestBitXor(c *C) { cases := []struct { - args []interface{} + args []any expected uint64 isNil bool getErr bool }{ - {[]interface{}{123, 321}, uint64(314), false, false}, - {[]interface{}{-123, 321}, uint64(18446744073709551300), false, false}, - {[]interface{}{nil, 1}, 0, true, false}, + {[]any{123, 321}, uint64(314), false, false}, + {[]any{-123, 321}, uint64(18446744073709551300), false, false}, + {[]any{nil, 1}, 0, true, false}, - {[]interface{}{errors.New("must error"), 1}, 0, false, true}, + {[]any{errors.New("must error"), 1}, 0, false, true}, } for _, t := range cases { @@ -241,16 +241,16 @@ func (s *testEvaluatorSuite) TestBitOr(c *C) { sc.IgnoreTruncate = true cases := []struct { - args []interface{} + args []any expected uint64 isNil bool getErr bool }{ - {[]interface{}{123, 321}, uint64(379), false, false}, - {[]interface{}{-123, 321}, uint64(18446744073709551557), false, false}, - {[]interface{}{nil, 1}, 0, true, false}, + {[]any{123, 321}, uint64(379), false, false}, + {[]any{-123, 321}, uint64(18446744073709551557), false, false}, + {[]any{nil, 1}, 0, true, false}, - {[]interface{}{errors.New("must error"), 1}, 0, false, true}, + {[]any{errors.New("must error"), 1}, 0, false, true}, } for _, t := range cases { @@ -286,37 +286,37 @@ func (s *testEvaluatorSuite) TestLogicOr(c *C) { sc.IgnoreTruncate = true cases := []struct { - args []interface{} + args []any expected int64 isNil bool getErr bool }{ - {[]interface{}{1, 1}, 1, false, false}, - {[]interface{}{1, 0}, 1, false, false}, - {[]interface{}{0, 1}, 1, false, false}, - {[]interface{}{0, 0}, 0, false, false}, - {[]interface{}{2, -1}, 1, false, false}, - {[]interface{}{"a", "0"}, 0, false, false}, - {[]interface{}{"a", "1"}, 1, false, false}, - {[]interface{}{"1a", "0"}, 1, false, false}, - {[]interface{}{"1a", "1"}, 1, false, false}, - {[]interface{}{"0.0a", 0}, 0, false, false}, - {[]interface{}{"0.0001a", 0}, 1, false, false}, - {[]interface{}{1, nil}, 1, false, false}, - {[]interface{}{nil, 1}, 1, false, false}, - {[]interface{}{nil, 0}, 0, true, false}, - {[]interface{}{0.000, 0}, 0, false, false}, - {[]interface{}{0.001, 0}, 1, false, false}, - {[]interface{}{nil, 0.000}, 0, true, false}, - {[]interface{}{nil, 0.001}, 1, false, false}, - {[]interface{}{types.NewDecFromStringForTest("0.000000"), 0}, 0, false, false}, - {[]interface{}{types.NewDecFromStringForTest("0.000000"), 1}, 1, false, false}, - {[]interface{}{types.NewDecFromStringForTest("0.000000"), nil}, 0, true, false}, - {[]interface{}{types.NewDecFromStringForTest("0.000001"), 0}, 1, false, false}, - {[]interface{}{types.NewDecFromStringForTest("0.000001"), 1}, 1, false, false}, - {[]interface{}{types.NewDecFromStringForTest("0.000001"), nil}, 1, false, false}, - - {[]interface{}{errors.New("must error"), 1}, 0, false, true}, + {[]any{1, 1}, 1, false, false}, + {[]any{1, 0}, 1, false, false}, + {[]any{0, 1}, 1, false, false}, + {[]any{0, 0}, 0, false, false}, + {[]any{2, -1}, 1, false, false}, + {[]any{"a", "0"}, 0, false, false}, + {[]any{"a", "1"}, 1, false, false}, + {[]any{"1a", "0"}, 1, false, false}, + {[]any{"1a", "1"}, 1, false, false}, + {[]any{"0.0a", 0}, 0, false, false}, + {[]any{"0.0001a", 0}, 1, false, false}, + {[]any{1, nil}, 1, false, false}, + {[]any{nil, 1}, 1, false, false}, + {[]any{nil, 0}, 0, true, false}, + {[]any{0.000, 0}, 0, false, false}, + {[]any{0.001, 0}, 1, false, false}, + {[]any{nil, 0.000}, 0, true, false}, + {[]any{nil, 0.001}, 1, false, false}, + {[]any{types.NewDecFromStringForTest("0.000000"), 0}, 0, false, false}, + {[]any{types.NewDecFromStringForTest("0.000000"), 1}, 1, false, false}, + {[]any{types.NewDecFromStringForTest("0.000000"), nil}, 0, true, false}, + {[]any{types.NewDecFromStringForTest("0.000001"), 0}, 1, false, false}, + {[]any{types.NewDecFromStringForTest("0.000001"), 1}, 1, false, false}, + {[]any{types.NewDecFromStringForTest("0.000001"), nil}, 1, false, false}, + + {[]any{errors.New("must error"), 1}, 0, false, true}, } for _, t := range cases { @@ -345,16 +345,16 @@ func (s *testEvaluatorSuite) TestLogicOr(c *C) { func (s *testEvaluatorSuite) TestBitAnd(c *C) { cases := []struct { - args []interface{} + args []any expected int64 isNil bool getErr bool }{ - {[]interface{}{123, 321}, 65, false, false}, - {[]interface{}{-123, 321}, 257, false, false}, - {[]interface{}{nil, 1}, 0, true, false}, + {[]any{123, 321}, 65, false, false}, + {[]any{-123, 321}, 257, false, false}, + {[]any{nil, 1}, 0, true, false}, - {[]interface{}{errors.New("must error"), 1}, 0, false, true}, + {[]any{errors.New("must error"), 1}, 0, false, true}, } for _, t := range cases { @@ -390,16 +390,16 @@ func (s *testEvaluatorSuite) TestBitNeg(c *C) { sc.IgnoreTruncate = true cases := []struct { - args []interface{} + args []any expected uint64 isNil bool getErr bool }{ - {[]interface{}{123}, uint64(18446744073709551492), false, false}, - {[]interface{}{-123}, uint64(122), false, false}, - {[]interface{}{nil}, 0, true, false}, + {[]any{123}, uint64(18446744073709551492), false, false}, + {[]any{-123}, uint64(122), false, false}, + {[]any{nil}, 0, true, false}, - {[]interface{}{errors.New("must error")}, 0, false, true}, + {[]any{errors.New("must error")}, 0, false, true}, } for _, t := range cases { @@ -435,22 +435,22 @@ func (s *testEvaluatorSuite) TestUnaryNot(c *C) { sc.IgnoreTruncate = true cases := []struct { - args []interface{} + args []any expected int64 isNil bool getErr bool }{ - {[]interface{}{1}, 0, false, false}, - {[]interface{}{0}, 1, false, false}, - {[]interface{}{123}, 0, false, false}, - {[]interface{}{-123}, 0, false, false}, - {[]interface{}{"123"}, 0, false, false}, - {[]interface{}{float64(0.3)}, 0, false, false}, - {[]interface{}{"0.3"}, 0, false, false}, - {[]interface{}{types.NewDecFromFloatForTest(0.3)}, 0, false, false}, - {[]interface{}{nil}, 0, true, false}, - - {[]interface{}{errors.New("must error")}, 0, false, true}, + {[]any{1}, 0, false, false}, + {[]any{0}, 1, false, false}, + {[]any{123}, 0, false, false}, + {[]any{-123}, 0, false, false}, + {[]any{"123"}, 0, false, false}, + {[]any{float64(0.3)}, 0, false, false}, + {[]any{"0.3"}, 0, false, false}, + {[]any{types.NewDecFromFloatForTest(0.3)}, 0, false, false}, + {[]any{nil}, 0, true, false}, + + {[]any{errors.New("must error")}, 0, false, true}, } for _, t := range cases { @@ -486,57 +486,57 @@ func (s *testEvaluatorSuite) TestIsTrueOrFalse(c *C) { sc.IgnoreTruncate = true testCases := []struct { - args []interface{} - isTrue interface{} - isFalse interface{} + args []any + isTrue any + isFalse any }{ { - args: []interface{}{-12}, + args: []any{-12}, isTrue: 1, isFalse: 0, }, { - args: []interface{}{12}, + args: []any{12}, isTrue: 1, isFalse: 0, }, { - args: []interface{}{0}, + args: []any{0}, isTrue: 0, isFalse: 1, }, { - args: []interface{}{float64(0)}, + args: []any{float64(0)}, isTrue: 0, isFalse: 1, }, { - args: []interface{}{"aaa"}, + args: []any{"aaa"}, isTrue: 0, isFalse: 1, }, { - args: []interface{}{""}, + args: []any{""}, isTrue: 0, isFalse: 1, }, { - args: []interface{}{"0.3"}, + args: []any{"0.3"}, isTrue: 1, isFalse: 0, }, { - args: []interface{}{float64(0.3)}, + args: []any{float64(0.3)}, isTrue: 1, isFalse: 0, }, { - args: []interface{}{types.NewDecFromFloatForTest(0.3)}, + args: []any{types.NewDecFromFloatForTest(0.3)}, isTrue: 1, isFalse: 0, }, { - args: []interface{}{nil}, + args: []any{nil}, isTrue: 0, isFalse: 0, }, @@ -572,34 +572,34 @@ func (s *testEvaluatorSuite) TestLogicXor(c *C) { sc.IgnoreTruncate = true cases := []struct { - args []interface{} + args []any expected int64 isNil bool getErr bool }{ - {[]interface{}{1, 1}, 0, false, false}, - {[]interface{}{1, 0}, 1, false, false}, - {[]interface{}{0, 1}, 1, false, false}, - {[]interface{}{0, 0}, 0, false, false}, - {[]interface{}{2, -1}, 0, false, false}, - {[]interface{}{"a", "0"}, 0, false, false}, - {[]interface{}{"a", "1"}, 1, false, false}, - {[]interface{}{"1a", "0"}, 1, false, false}, - {[]interface{}{"1a", "1"}, 0, false, false}, - {[]interface{}{0, nil}, 0, true, false}, - {[]interface{}{nil, 0}, 0, true, false}, - {[]interface{}{nil, 1}, 0, true, false}, - {[]interface{}{0.5000, 0.4999}, 1, false, false}, - {[]interface{}{0.5000, 1.0}, 0, false, false}, - {[]interface{}{0.4999, 1.0}, 1, false, false}, - {[]interface{}{nil, 0.000}, 0, true, false}, - {[]interface{}{nil, 0.001}, 0, true, false}, - {[]interface{}{types.NewDecFromStringForTest("0.000001"), 0.00001}, 0, false, false}, - {[]interface{}{types.NewDecFromStringForTest("0.000001"), 1}, 1, false, false}, - {[]interface{}{types.NewDecFromStringForTest("0.000000"), nil}, 0, true, false}, - {[]interface{}{types.NewDecFromStringForTest("0.000001"), nil}, 0, true, false}, - - {[]interface{}{errors.New("must error"), 1}, 0, false, true}, + {[]any{1, 1}, 0, false, false}, + {[]any{1, 0}, 1, false, false}, + {[]any{0, 1}, 1, false, false}, + {[]any{0, 0}, 0, false, false}, + {[]any{2, -1}, 0, false, false}, + {[]any{"a", "0"}, 0, false, false}, + {[]any{"a", "1"}, 1, false, false}, + {[]any{"1a", "0"}, 1, false, false}, + {[]any{"1a", "1"}, 0, false, false}, + {[]any{0, nil}, 0, true, false}, + {[]any{nil, 0}, 0, true, false}, + {[]any{nil, 1}, 0, true, false}, + {[]any{0.5000, 0.4999}, 1, false, false}, + {[]any{0.5000, 1.0}, 0, false, false}, + {[]any{0.4999, 1.0}, 1, false, false}, + {[]any{nil, 0.000}, 0, true, false}, + {[]any{nil, 0.001}, 0, true, false}, + {[]any{types.NewDecFromStringForTest("0.000001"), 0.00001}, 0, false, false}, + {[]any{types.NewDecFromStringForTest("0.000001"), 1}, 1, false, false}, + {[]any{types.NewDecFromStringForTest("0.000000"), nil}, 0, true, false}, + {[]any{types.NewDecFromStringForTest("0.000001"), nil}, 0, true, false}, + + {[]any{errors.New("must error"), 1}, 0, false, true}, } for _, t := range cases { diff --git a/expression/builtin_op_vec_test.go b/expression/builtin_op_vec_test.go index 464e487a4..fcf1ee59e 100644 --- a/expression/builtin_op_vec_test.go +++ b/expression/builtin_op_vec_test.go @@ -96,12 +96,12 @@ var vecBuiltinOpCases = map[string][]vecExprBenchCase{ // the construction time. If this slice is exhausted, it falls back to // the fallback generator. type givenValsGener struct { - given []interface{} + given []any idx int fallback dataGenerator } -func (g *givenValsGener) gen() interface{} { +func (g *givenValsGener) gen() any { if g.idx >= len(g.given) { return g.fallback.gen() } @@ -110,7 +110,7 @@ func (g *givenValsGener) gen() interface{} { return v } -func makeGivenValsOrDefaultGener(vals []interface{}, eType types.EvalType) *givenValsGener { +func makeGivenValsOrDefaultGener(vals []any, eType types.EvalType) *givenValsGener { g := &givenValsGener{} g.given = vals g.fallback = newDefaultGener(0.2, eType) @@ -119,7 +119,7 @@ func makeGivenValsOrDefaultGener(vals []interface{}, eType types.EvalType) *give func makeBinaryLogicOpDataGeners() []dataGenerator { // TODO: rename this to makeBinaryOpDataGenerator, since the BIT ops are also using it? - pairs := [][]interface{}{ + pairs := [][]any{ {nil, nil}, {0, nil}, {nil, 0}, @@ -132,7 +132,7 @@ func makeBinaryLogicOpDataGeners() []dataGenerator { {-1, 1}, } - maybeToInt64 := func(v interface{}) interface{} { + maybeToInt64 := func(v any) any { if v == nil { return nil } @@ -140,8 +140,8 @@ func makeBinaryLogicOpDataGeners() []dataGenerator { } n := len(pairs) - arg0s := make([]interface{}, n) - arg1s := make([]interface{}, n) + arg0s := make([]any, n) + arg1s := make([]any, n) for i, p := range pairs { arg0s[i] = maybeToInt64(p[0]) arg1s[i] = maybeToInt64(p[1]) diff --git a/expression/builtin_other_test.go b/expression/builtin_other_test.go index 05e921216..c9ca02cc2 100644 --- a/expression/builtin_other_test.go +++ b/expression/builtin_other_test.go @@ -37,8 +37,8 @@ func (s *testEvaluatorSuite) TestBitCount(c *C) { }() fc := funcs[ast.BitCount] var bitCountCases = []struct { - origin interface{} - count interface{} + origin any + count any }{ {int64(8), int64(1)}, {int64(29), int64(4)}, @@ -92,31 +92,31 @@ func (s *testEvaluatorSuite) TestInFunc(c *C) { json3 := json.CreateBinary("123.2") json4 := json.CreateBinary("123.3") testCases := []struct { - args []interface{} - res interface{} + args []any + res any }{ - {[]interface{}{1, 1, 2, 3}, int64(1)}, - {[]interface{}{1, 0, 2, 3}, int64(0)}, - {[]interface{}{1, nil, 2, 3}, nil}, - {[]interface{}{nil, nil, 2, 3}, nil}, - {[]interface{}{uint64(0), 0, 2, 3}, int64(1)}, - {[]interface{}{uint64(math.MaxUint64), uint64(math.MaxUint64), 2, 3}, int64(1)}, - {[]interface{}{-1, uint64(math.MaxUint64), 2, 3}, int64(0)}, - {[]interface{}{uint64(math.MaxUint64), -1, 2, 3}, int64(0)}, - {[]interface{}{1, 0, 2, 3}, int64(0)}, - {[]interface{}{1.1, 1.2, 1.3}, int64(0)}, - {[]interface{}{1.1, 1.1, 1.2, 1.3}, int64(1)}, - {[]interface{}{decimal1, decimal2, decimal3, decimal4}, int64(0)}, - {[]interface{}{decimal1, decimal2, decimal3, decimal1}, int64(1)}, - {[]interface{}{"1.1", "1.1", "1.2", "1.3"}, int64(1)}, - {[]interface{}{"1.1", hack.Slice("1.1"), "1.2", "1.3"}, int64(1)}, - {[]interface{}{hack.Slice("1.1"), "1.1", "1.2", "1.3"}, int64(1)}, - {[]interface{}{time1, time2, time3, time1}, int64(1)}, - {[]interface{}{time1, time2, time3, time4}, int64(0)}, - {[]interface{}{duration1, duration2, duration3, duration4}, int64(0)}, - {[]interface{}{duration1, duration2, duration1, duration4}, int64(1)}, - {[]interface{}{json1, json2, json3, json4}, int64(0)}, - {[]interface{}{json1, json1, json3, json4}, int64(1)}, + {[]any{1, 1, 2, 3}, int64(1)}, + {[]any{1, 0, 2, 3}, int64(0)}, + {[]any{1, nil, 2, 3}, nil}, + {[]any{nil, nil, 2, 3}, nil}, + {[]any{uint64(0), 0, 2, 3}, int64(1)}, + {[]any{uint64(math.MaxUint64), uint64(math.MaxUint64), 2, 3}, int64(1)}, + {[]any{-1, uint64(math.MaxUint64), 2, 3}, int64(0)}, + {[]any{uint64(math.MaxUint64), -1, 2, 3}, int64(0)}, + {[]any{1, 0, 2, 3}, int64(0)}, + {[]any{1.1, 1.2, 1.3}, int64(0)}, + {[]any{1.1, 1.1, 1.2, 1.3}, int64(1)}, + {[]any{decimal1, decimal2, decimal3, decimal4}, int64(0)}, + {[]any{decimal1, decimal2, decimal3, decimal1}, int64(1)}, + {[]any{"1.1", "1.1", "1.2", "1.3"}, int64(1)}, + {[]any{"1.1", hack.Slice("1.1"), "1.2", "1.3"}, int64(1)}, + {[]any{hack.Slice("1.1"), "1.1", "1.2", "1.3"}, int64(1)}, + {[]any{time1, time2, time3, time1}, int64(1)}, + {[]any{time1, time2, time3, time4}, int64(0)}, + {[]any{duration1, duration2, duration3, duration4}, int64(0)}, + {[]any{duration1, duration2, duration1, duration4}, int64(1)}, + {[]any{json1, json2, json3, json4}, int64(0)}, + {[]any{json1, json1, json3, json4}, int64(1)}, } for _, tc := range testCases { fn, err := fc.getFunction(s.ctx, s.datumsToConstants(types.MakeDatums(tc.args...))) @@ -145,21 +145,21 @@ func (s *testEvaluatorSuite) TestInFunc(c *C) { func (s *testEvaluatorSuite) TestRowFunc(c *C) { fc := funcs[ast.RowFunc] - _, err := fc.getFunction(s.ctx, s.datumsToConstants(types.MakeDatums([]interface{}{"1", 1.2, true, 120}...))) + _, err := fc.getFunction(s.ctx, s.datumsToConstants(types.MakeDatums([]any{"1", 1.2, true, 120}...))) c.Assert(err, IsNil) } func (s *testEvaluatorSuite) TestSetVar(c *C) { fc := funcs[ast.SetVar] testCases := []struct { - args []interface{} - res interface{} + args []any + res any }{ - {[]interface{}{"a", "12"}, "12"}, - {[]interface{}{"b", "34"}, "34"}, - {[]interface{}{"c", nil}, ""}, - {[]interface{}{"c", "ABC"}, "ABC"}, - {[]interface{}{"c", "dEf"}, "dEf"}, + {[]any{"a", "12"}, "12"}, + {[]any{"b", "34"}, "34"}, + {[]any{"c", nil}, ""}, + {[]any{"c", "ABC"}, "ABC"}, + {[]any{"c", "dEf"}, "dEf"}, } for _, tc := range testCases { fn, err := fc.getFunction(s.ctx, s.datumsToConstants(types.MakeDatums(tc.args...))) @@ -195,13 +195,13 @@ func (s *testEvaluatorSuite) TestGetVar(c *C) { } testCases := []struct { - args []interface{} - res interface{} + args []any + res any }{ - {[]interface{}{"a"}, "中"}, - {[]interface{}{"b"}, "文字符chuan"}, - {[]interface{}{"c"}, ""}, - {[]interface{}{"d"}, ""}, + {[]any{"a"}, "中"}, + {[]any{"b"}, "文字符chuan"}, + {[]any{"c"}, ""}, + {[]any{"d"}, ""}, } for _, tc := range testCases { fn, err := fc.getFunction(s.ctx, s.datumsToConstants(types.MakeDatums(tc.args...))) diff --git a/expression/builtin_other_vec_generated_test.go b/expression/builtin_other_vec_generated_test.go index 13c6cc9c9..f9cb92adb 100644 --- a/expression/builtin_other_vec_generated_test.go +++ b/expression/builtin_other_vec_generated_test.go @@ -32,7 +32,7 @@ type inGener struct { defaultGener } -func (g inGener) gen() interface{} { +func (g inGener) gen() any { if rand.Float64() < g.nullRation { return nil } diff --git a/expression/builtin_string_test.go b/expression/builtin_string_test.go index e5693654f..58ccdba71 100644 --- a/expression/builtin_string_test.go +++ b/expression/builtin_string_test.go @@ -36,7 +36,7 @@ import ( func (s *testEvaluatorSuite) TestLengthAndOctetLength(c *C) { cases := []struct { - args interface{} + args any expected int64 isNil bool getErr bool @@ -57,7 +57,7 @@ func (s *testEvaluatorSuite) TestLengthAndOctetLength(c *C) { lengthMethods := []string{ast.Length, ast.OctetLength} for _, lengthMethod := range lengthMethods { for _, t := range cases { - f, err := newFunctionForTest(s.ctx, lengthMethod, s.primitiveValsToConstants([]interface{}{t.args})...) + f, err := newFunctionForTest(s.ctx, lengthMethod, s.primitiveValsToConstants([]any{t.args})...) c.Assert(err, IsNil) d, err := f.Eval(chunk.Row{}) if t.getErr { @@ -79,7 +79,7 @@ func (s *testEvaluatorSuite) TestLengthAndOctetLength(c *C) { func (s *testEvaluatorSuite) TestASCII(c *C) { cases := []struct { - args interface{} + args any expected int64 isNil bool getErr bool @@ -94,7 +94,7 @@ func (s *testEvaluatorSuite) TestASCII(c *C) { {"你好", 228, false, false}, } for _, t := range cases { - f, err := newFunctionForTest(s.ctx, ast.ASCII, s.primitiveValsToConstants([]interface{}{t.args})...) + f, err := newFunctionForTest(s.ctx, ast.ASCII, s.primitiveValsToConstants([]any{t.args})...) c.Assert(err, IsNil) d, err := f.Eval(chunk.Row{}) @@ -115,19 +115,19 @@ func (s *testEvaluatorSuite) TestASCII(c *C) { func (s *testEvaluatorSuite) TestConcat(c *C) { cases := []struct { - args []interface{} + args []any isNil bool getErr bool res string retType *types.FieldType }{ { - []interface{}{nil}, + []any{nil}, true, false, "", &types.FieldType{Tp: mysql.TypeVarString, Flen: 0, Decimal: types.UnspecifiedLength, Charset: charset.CharsetBin, Collate: charset.CollationBin, Flag: mysql.BinaryFlag}, }, { - []interface{}{"a", "b", + []any{"a", "b", 1, 2, 1.1, 1.2, types.NewDecFromFloatForTest(1.1), @@ -140,12 +140,12 @@ func (s *testEvaluatorSuite) TestConcat(c *C) { &types.FieldType{Tp: mysql.TypeVarString, Flen: 40, Decimal: types.UnspecifiedLength, Charset: charset.CharsetBin, Collate: charset.CollationBin, Flag: mysql.BinaryFlag}, }, { - []interface{}{"a", "b", nil, "c"}, + []any{"a", "b", nil, "c"}, true, false, "", &types.FieldType{Tp: mysql.TypeVarString, Flen: 3, Decimal: types.UnspecifiedLength, Charset: charset.CharsetBin, Collate: charset.CollationBin, Flag: mysql.BinaryFlag}, }, { - []interface{}{errors.New("must error")}, + []any{errors.New("must error")}, false, true, "", &types.FieldType{Tp: mysql.TypeVarString, Flen: types.UnspecifiedLength, Decimal: types.UnspecifiedLength, Charset: charset.CharsetBin, Collate: charset.CollationBin, Flag: mysql.BinaryFlag}, }, @@ -182,14 +182,14 @@ func (s *testEvaluatorSuite) TestConcatSig(c *C) { concat := &builtinConcatSig{base, 5} cases := []struct { - args []interface{} + args []any warnings int res string }{ - {[]interface{}{"a", "b"}, 0, "ab"}, - {[]interface{}{"aaa", "bbb"}, 1, ""}, - {[]interface{}{"中", "a"}, 0, "中a"}, - {[]interface{}{"中文", "a"}, 2, ""}, + {[]any{"a", "b"}, 0, "ab"}, + {[]any{"aaa", "bbb"}, 1, ""}, + {[]any{"中", "a"}, 0, "中a"}, + {[]any{"中文", "a"}, 2, ""}, } for _, t := range cases { @@ -214,40 +214,40 @@ func (s *testEvaluatorSuite) TestConcatSig(c *C) { func (s *testEvaluatorSuite) TestConcatWS(c *C) { cases := []struct { - args []interface{} + args []any isNil bool getErr bool expected string }{ { - []interface{}{nil, nil}, + []any{nil, nil}, true, false, "", }, { - []interface{}{nil, "a", "b"}, + []any{nil, "a", "b"}, true, false, "", }, { - []interface{}{",", "a", "b", "hello", `$^%`}, + []any{",", "a", "b", "hello", `$^%`}, false, false, `a,b,hello,$^%`, }, { - []interface{}{"|", "a", nil, "b", "c"}, + []any{"|", "a", nil, "b", "c"}, false, false, "a|b|c", }, { - []interface{}{",", "a", ",", "b", "c"}, + []any{",", "a", ",", "b", "c"}, false, false, "a,,,b,c", }, { - []interface{}{errors.New("must error"), "a", "b"}, + []any{errors.New("must error"), "a", "b"}, false, true, "", }, { - []interface{}{",", "a", "b", 1, 2, 1.1, 0.11, + []any{",", "a", "b", 1, 2, 1.1, 0.11, types.NewDecFromFloatForTest(1.1), types.NewTime(types.FromDate(2000, 1, 1, 12, 01, 01, 0), mysql.TypeDatetime, types.DefaultFsp), types.Duration{ @@ -260,7 +260,7 @@ func (s *testEvaluatorSuite) TestConcatWS(c *C) { fcName := ast.ConcatWS // ERROR 1582 (42000): Incorrect parameter count in the call to native function 'concat_ws' - _, err := newFunctionForTest(s.ctx, fcName, s.primitiveValsToConstants([]interface{}{nil})...) + _, err := newFunctionForTest(s.ctx, fcName, s.primitiveValsToConstants([]any{nil})...) c.Assert(err, NotNil) for _, t := range cases { @@ -279,7 +279,7 @@ func (s *testEvaluatorSuite) TestConcatWS(c *C) { } } - _, err = funcs[ast.ConcatWS].getFunction(s.ctx, s.primitiveValsToConstants([]interface{}{nil, nil})) + _, err = funcs[ast.ConcatWS].getFunction(s.ctx, s.primitiveValsToConstants([]any{nil, nil})) c.Assert(err, IsNil) } @@ -299,14 +299,14 @@ func (s *testEvaluatorSuite) TestConcatWSSig(c *C) { concat := &builtinConcatWSSig{base, 6} cases := []struct { - args []interface{} + args []any warnings int res string }{ - {[]interface{}{",", "a", "b"}, 0, "a,b"}, - {[]interface{}{",", "aaa", "bbb"}, 1, ""}, - {[]interface{}{",", "中", "a"}, 0, "中,a"}, - {[]interface{}{",", "中文", "a"}, 2, ""}, + {[]any{",", "a", "b"}, 0, "a,b"}, + {[]any{",", "aaa", "bbb"}, 1, ""}, + {[]any{",", "中", "a"}, 0, "中,a"}, + {[]any{",", "中文", "a"}, 2, ""}, } for _, t := range cases { @@ -339,25 +339,25 @@ func (s *testEvaluatorSuite) TestLeft(c *C) { }() cases := []struct { - args []interface{} + args []any isNil bool getErr bool res string }{ - {[]interface{}{"abcde", 3}, false, false, "abc"}, - {[]interface{}{"abcde", 0}, false, false, ""}, - {[]interface{}{"abcde", 1.2}, false, false, "a"}, - {[]interface{}{"abcde", 1.9}, false, false, "ab"}, - {[]interface{}{"abcde", -1}, false, false, ""}, - {[]interface{}{"abcde", 100}, false, false, "abcde"}, - {[]interface{}{"abcde", nil}, true, false, ""}, - {[]interface{}{nil, 3}, true, false, ""}, - {[]interface{}{"abcde", "3"}, false, false, "abc"}, - {[]interface{}{"abcde", "a"}, false, false, ""}, - {[]interface{}{1234, 3}, false, false, "123"}, - {[]interface{}{12.34, 3}, false, false, "12."}, - {[]interface{}{types.NewBinaryLiteralFromUint(0x0102, -1), 1}, false, false, string([]byte{0x01})}, - {[]interface{}{errors.New("must err"), 0}, false, true, ""}, + {[]any{"abcde", 3}, false, false, "abc"}, + {[]any{"abcde", 0}, false, false, ""}, + {[]any{"abcde", 1.2}, false, false, "a"}, + {[]any{"abcde", 1.9}, false, false, "ab"}, + {[]any{"abcde", -1}, false, false, ""}, + {[]any{"abcde", 100}, false, false, "abcde"}, + {[]any{"abcde", nil}, true, false, ""}, + {[]any{nil, 3}, true, false, ""}, + {[]any{"abcde", "3"}, false, false, "abc"}, + {[]any{"abcde", "a"}, false, false, ""}, + {[]any{1234, 3}, false, false, "123"}, + {[]any{12.34, 3}, false, false, "12."}, + {[]any{types.NewBinaryLiteralFromUint(0x0102, -1), 1}, false, false, string([]byte{0x01})}, + {[]any{errors.New("must err"), 0}, false, true, ""}, } for _, t := range cases { f, err := newFunctionForTest(s.ctx, ast.Left, s.primitiveValsToConstants(t.args)...) @@ -388,25 +388,25 @@ func (s *testEvaluatorSuite) TestRight(c *C) { }() cases := []struct { - args []interface{} + args []any isNil bool getErr bool res string }{ - {[]interface{}{"abcde", 3}, false, false, "cde"}, - {[]interface{}{"abcde", 0}, false, false, ""}, - {[]interface{}{"abcde", 1.2}, false, false, "e"}, - {[]interface{}{"abcde", 1.9}, false, false, "de"}, - {[]interface{}{"abcde", -1}, false, false, ""}, - {[]interface{}{"abcde", 100}, false, false, "abcde"}, - {[]interface{}{"abcde", nil}, true, false, ""}, - {[]interface{}{nil, 1}, true, false, ""}, - {[]interface{}{"abcde", "3"}, false, false, "cde"}, - {[]interface{}{"abcde", "a"}, false, false, ""}, - {[]interface{}{1234, 3}, false, false, "234"}, - {[]interface{}{12.34, 3}, false, false, ".34"}, - {[]interface{}{types.NewBinaryLiteralFromUint(0x0102, -1), 1}, false, false, string([]byte{0x02})}, - {[]interface{}{errors.New("must err"), 0}, false, true, ""}, + {[]any{"abcde", 3}, false, false, "cde"}, + {[]any{"abcde", 0}, false, false, ""}, + {[]any{"abcde", 1.2}, false, false, "e"}, + {[]any{"abcde", 1.9}, false, false, "de"}, + {[]any{"abcde", -1}, false, false, ""}, + {[]any{"abcde", 100}, false, false, "abcde"}, + {[]any{"abcde", nil}, true, false, ""}, + {[]any{nil, 1}, true, false, ""}, + {[]any{"abcde", "3"}, false, false, "cde"}, + {[]any{"abcde", "a"}, false, false, ""}, + {[]any{1234, 3}, false, false, "234"}, + {[]any{12.34, 3}, false, false, ".34"}, + {[]any{types.NewBinaryLiteralFromUint(0x0102, -1), 1}, false, false, string([]byte{0x02})}, + {[]any{errors.New("must err"), 0}, false, true, ""}, } for _, t := range cases { f, err := newFunctionForTest(s.ctx, ast.Right, s.primitiveValsToConstants(t.args)...) @@ -429,7 +429,7 @@ func (s *testEvaluatorSuite) TestRight(c *C) { } func (s *testEvaluatorSuite) TestRepeat(c *C) { - args := []interface{}{"a", int64(2)} + args := []any{"a", int64(2)} fc := funcs[ast.Repeat] f, err := fc.getFunction(s.ctx, s.datumsToConstants(types.MakeDatums(args...))) c.Assert(err, IsNil) @@ -437,42 +437,42 @@ func (s *testEvaluatorSuite) TestRepeat(c *C) { c.Assert(err, IsNil) c.Assert(v.GetString(), Equals, "aa") - args = []interface{}{"a", uint64(2)} + args = []any{"a", uint64(2)} f, err = fc.getFunction(s.ctx, s.datumsToConstants(types.MakeDatums(args...))) c.Assert(err, IsNil) v, err = evalBuiltinFunc(f, chunk.Row{}) c.Assert(err, IsNil) c.Assert(v.GetString(), Equals, "aa") - args = []interface{}{"a", uint64(16777217)} + args = []any{"a", uint64(16777217)} f, err = fc.getFunction(s.ctx, s.datumsToConstants(types.MakeDatums(args...))) c.Assert(err, IsNil) v, err = evalBuiltinFunc(f, chunk.Row{}) c.Assert(err, IsNil) c.Assert(v.IsNull(), IsTrue) - args = []interface{}{"a", uint64(16777216)} + args = []any{"a", uint64(16777216)} f, err = fc.getFunction(s.ctx, s.datumsToConstants(types.MakeDatums(args...))) c.Assert(err, IsNil) v, err = evalBuiltinFunc(f, chunk.Row{}) c.Assert(err, IsNil) c.Assert(v.IsNull(), IsFalse) - args = []interface{}{"a", int64(-1)} + args = []any{"a", int64(-1)} f, err = fc.getFunction(s.ctx, s.datumsToConstants(types.MakeDatums(args...))) c.Assert(err, IsNil) v, err = evalBuiltinFunc(f, chunk.Row{}) c.Assert(err, IsNil) c.Assert(v.GetString(), Equals, "") - args = []interface{}{"a", int64(0)} + args = []any{"a", int64(0)} f, err = fc.getFunction(s.ctx, s.datumsToConstants(types.MakeDatums(args...))) c.Assert(err, IsNil) v, err = evalBuiltinFunc(f, chunk.Row{}) c.Assert(err, IsNil) c.Assert(v.GetString(), Equals, "") - args = []interface{}{"a", uint64(0)} + args = []any{"a", uint64(0)} f, err = fc.getFunction(s.ctx, s.datumsToConstants(types.MakeDatums(args...))) c.Assert(err, IsNil) v, err = evalBuiltinFunc(f, chunk.Row{}) @@ -494,14 +494,14 @@ func (s *testEvaluatorSuite) TestRepeatSig(c *C) { repeat := &builtinRepeatSig{base, 1000} cases := []struct { - args []interface{} + args []any warning int res string }{ - {[]interface{}{"a", int64(6)}, 0, "aaaaaa"}, - {[]interface{}{"a", int64(10001)}, 1, ""}, - {[]interface{}{"毅", int64(6)}, 0, "毅毅毅毅毅毅"}, - {[]interface{}{"毅", int64(334)}, 2, ""}, + {[]any{"a", int64(6)}, 0, "aaaaaa"}, + {[]any{"a", int64(10001)}, 1, ""}, + {[]any{"毅", int64(6)}, 0, "毅毅毅毅毅毅"}, + {[]any{"毅", int64(334)}, 2, ""}, } for _, t := range cases { @@ -527,18 +527,18 @@ func (s *testEvaluatorSuite) TestRepeatSig(c *C) { func (s *testEvaluatorSuite) TestLower(c *C) { cases := []struct { - args []interface{} + args []any isNil bool getErr bool res string }{ - {[]interface{}{nil}, true, false, ""}, - {[]interface{}{"ab"}, false, false, "ab"}, - {[]interface{}{1}, false, false, "1"}, - {[]interface{}{"one week’s time TEST"}, false, false, "one week’s time test"}, - {[]interface{}{"one week's time TEST"}, false, false, "one week's time test"}, - {[]interface{}{"ABC测试DEF"}, false, false, "abc测试def"}, - {[]interface{}{"ABCテストDEF"}, false, false, "abcテストdef"}, + {[]any{nil}, true, false, ""}, + {[]any{"ab"}, false, false, "ab"}, + {[]any{1}, false, false, "1"}, + {[]any{"one week’s time TEST"}, false, false, "one week’s time test"}, + {[]any{"one week's time TEST"}, false, false, "one week's time test"}, + {[]any{"ABC测试DEF"}, false, false, "abc测试def"}, + {[]any{"ABCテストDEF"}, false, false, "abcテストdef"}, } for _, t := range cases { @@ -563,18 +563,18 @@ func (s *testEvaluatorSuite) TestLower(c *C) { func (s *testEvaluatorSuite) TestUpper(c *C) { cases := []struct { - args []interface{} + args []any isNil bool getErr bool res string }{ - {[]interface{}{nil}, true, false, ""}, - {[]interface{}{"ab"}, false, false, "ab"}, - {[]interface{}{1}, false, false, "1"}, - {[]interface{}{"one week’s time TEST"}, false, false, "ONE WEEK’S TIME TEST"}, - {[]interface{}{"one week's time TEST"}, false, false, "ONE WEEK'S TIME TEST"}, - {[]interface{}{"abc测试def"}, false, false, "ABC测试DEF"}, - {[]interface{}{"abcテストdef"}, false, false, "ABCテストDEF"}, + {[]any{nil}, true, false, ""}, + {[]any{"ab"}, false, false, "ab"}, + {[]any{1}, false, false, "1"}, + {[]any{"one week’s time TEST"}, false, false, "ONE WEEK’S TIME TEST"}, + {[]any{"one week's time TEST"}, false, false, "ONE WEEK'S TIME TEST"}, + {[]any{"abc测试def"}, false, false, "ABC测试DEF"}, + {[]any{"abcテストdef"}, false, false, "ABCテストDEF"}, } for _, t := range cases { @@ -606,7 +606,7 @@ func (s *testEvaluatorSuite) TestReverse(c *C) { c.Assert(d.Kind(), Equals, types.KindNull) tbl := []struct { - Input interface{} + Input any Expect string }{ {"abc", "cba"}, @@ -629,26 +629,26 @@ func (s *testEvaluatorSuite) TestReverse(c *C) { func (s *testEvaluatorSuite) TestStrcmp(c *C) { cases := []struct { - args []interface{} + args []any isNil bool getErr bool res int64 }{ - {[]interface{}{"123", "123"}, false, false, 0}, - {[]interface{}{"123", "1"}, false, false, 1}, - {[]interface{}{"1", "123"}, false, false, -1}, - {[]interface{}{"123", "45"}, false, false, -1}, - {[]interface{}{123, "123"}, false, false, 0}, - {[]interface{}{"12.34", 12.34}, false, false, 0}, - {[]interface{}{nil, "123"}, true, false, 0}, - {[]interface{}{"123", nil}, true, false, 0}, - {[]interface{}{"", "123"}, false, false, -1}, - {[]interface{}{"123", ""}, false, false, 1}, - {[]interface{}{"", ""}, false, false, 0}, - {[]interface{}{"", nil}, true, false, 0}, - {[]interface{}{nil, ""}, true, false, 0}, - {[]interface{}{nil, nil}, true, false, 0}, - {[]interface{}{"123", errors.New("must err")}, false, true, 0}, + {[]any{"123", "123"}, false, false, 0}, + {[]any{"123", "1"}, false, false, 1}, + {[]any{"1", "123"}, false, false, -1}, + {[]any{"123", "45"}, false, false, -1}, + {[]any{123, "123"}, false, false, 0}, + {[]any{"12.34", 12.34}, false, false, 0}, + {[]any{nil, "123"}, true, false, 0}, + {[]any{"123", nil}, true, false, 0}, + {[]any{"", "123"}, false, false, -1}, + {[]any{"123", ""}, false, false, 1}, + {[]any{"", ""}, false, false, 0}, + {[]any{"", nil}, true, false, 0}, + {[]any{nil, ""}, true, false, 0}, + {[]any{nil, nil}, true, false, 0}, + {[]any{"123", errors.New("must err")}, false, true, 0}, } for _, t := range cases { f, err := newFunctionForTest(s.ctx, ast.Strcmp, s.primitiveValsToConstants(t.args)...) @@ -669,22 +669,22 @@ func (s *testEvaluatorSuite) TestStrcmp(c *C) { func (s *testEvaluatorSuite) TestReplace(c *C) { cases := []struct { - args []interface{} + args []any isNil bool getErr bool res string flen int }{ - {[]interface{}{"www.mysql.com", "mysql", "pingcap"}, false, false, "www.pingcap.com", 17}, - {[]interface{}{"www.mysql.com", "w", 1}, false, false, "111.mysql.com", 260}, - {[]interface{}{1234, 2, 55}, false, false, "15534", 20}, - {[]interface{}{"", "a", "b"}, false, false, "", 0}, - {[]interface{}{"abc", "", "d"}, false, false, "abc", 3}, - {[]interface{}{"aaa", "a", ""}, false, false, "", 3}, - {[]interface{}{nil, "a", "b"}, true, false, "", 0}, - {[]interface{}{"a", nil, "b"}, true, false, "", 1}, - {[]interface{}{"a", "b", nil}, true, false, "", 1}, - {[]interface{}{errors.New("must err"), "a", "b"}, false, true, "", -1}, + {[]any{"www.mysql.com", "mysql", "pingcap"}, false, false, "www.pingcap.com", 17}, + {[]any{"www.mysql.com", "w", 1}, false, false, "111.mysql.com", 260}, + {[]any{1234, 2, 55}, false, false, "15534", 20}, + {[]any{"", "a", "b"}, false, false, "", 0}, + {[]any{"abc", "", "d"}, false, false, "abc", 3}, + {[]any{"aaa", "a", ""}, false, false, "", 3}, + {[]any{nil, "a", "b"}, true, false, "", 0}, + {[]any{"a", nil, "b"}, true, false, "", 1}, + {[]any{"a", "b", nil}, true, false, "", 1}, + {[]any{errors.New("must err"), "a", "b"}, false, true, "", -1}, } for i, t := range cases { f, err := newFunctionForTest(s.ctx, ast.Replace, s.primitiveValsToConstants(t.args)...) @@ -709,27 +709,27 @@ func (s *testEvaluatorSuite) TestReplace(c *C) { func (s *testEvaluatorSuite) TestSubstring(c *C) { cases := []struct { - args []interface{} + args []any isNil bool getErr bool res string }{ - {[]interface{}{"Quadratically", 5}, false, false, "ratically"}, - {[]interface{}{"Sakila", 1}, false, false, "Sakila"}, - {[]interface{}{"Sakila", 2}, false, false, "akila"}, - {[]interface{}{"Sakila", -3}, false, false, "ila"}, - {[]interface{}{"Sakila", 0}, false, false, ""}, - {[]interface{}{"Sakila", 100}, false, false, ""}, - {[]interface{}{"Sakila", -100}, false, false, ""}, - {[]interface{}{"Quadratically", 5, 6}, false, false, "ratica"}, - {[]interface{}{"Sakila", -5, 3}, false, false, "aki"}, - {[]interface{}{"Sakila", 2, 0}, false, false, ""}, - {[]interface{}{"Sakila", 2, -1}, false, false, ""}, - {[]interface{}{"Sakila", 2, 100}, false, false, "akila"}, - {[]interface{}{nil, 2, 3}, true, false, ""}, - {[]interface{}{"Sakila", nil, 3}, true, false, ""}, - {[]interface{}{"Sakila", 2, nil}, true, false, ""}, - {[]interface{}{errors.New("must error"), 2, 3}, false, true, ""}, + {[]any{"Quadratically", 5}, false, false, "ratically"}, + {[]any{"Sakila", 1}, false, false, "Sakila"}, + {[]any{"Sakila", 2}, false, false, "akila"}, + {[]any{"Sakila", -3}, false, false, "ila"}, + {[]any{"Sakila", 0}, false, false, ""}, + {[]any{"Sakila", 100}, false, false, ""}, + {[]any{"Sakila", -100}, false, false, ""}, + {[]any{"Quadratically", 5, 6}, false, false, "ratica"}, + {[]any{"Sakila", -5, 3}, false, false, "aki"}, + {[]any{"Sakila", 2, 0}, false, false, ""}, + {[]any{"Sakila", 2, -1}, false, false, ""}, + {[]any{"Sakila", 2, 100}, false, false, "akila"}, + {[]any{nil, 2, 3}, true, false, ""}, + {[]any{"Sakila", nil, 3}, true, false, ""}, + {[]any{"Sakila", 2, nil}, true, false, ""}, + {[]any{errors.New("must error"), 2, 3}, false, true, ""}, } for _, t := range cases { f, err := newFunctionForTest(s.ctx, ast.Substring, s.primitiveValsToConstants(t.args)...) @@ -756,7 +756,7 @@ func (s *testEvaluatorSuite) TestSubstring(c *C) { func (s *testEvaluatorSuite) TestConvert(c *C) { tbl := []struct { - str interface{} + str any cs string result string hasBinaryFlag bool @@ -788,7 +788,7 @@ func (s *testEvaluatorSuite) TestConvert(c *C) { // Test case for getFunction() error errTbl := []struct { - str interface{} + str any cs string err string }{ @@ -815,29 +815,29 @@ func (s *testEvaluatorSuite) TestConvert(c *C) { func (s *testEvaluatorSuite) TestSubstringIndex(c *C) { cases := []struct { - args []interface{} + args []any isNil bool getErr bool res string }{ - {[]interface{}{"www.pingcap.com", ".", 2}, false, false, "www.pingcap"}, - {[]interface{}{"www.pingcap.com", ".", -2}, false, false, "pingcap.com"}, - {[]interface{}{"www.pingcap.com", ".", 0}, false, false, ""}, - {[]interface{}{"www.pingcap.com", ".", 100}, false, false, "www.pingcap.com"}, - {[]interface{}{"www.pingcap.com", ".", -100}, false, false, "www.pingcap.com"}, - {[]interface{}{"www.pingcap.com", "d", 0}, false, false, ""}, - {[]interface{}{"www.pingcap.com", "d", 1}, false, false, "www.pingcap.com"}, - {[]interface{}{"www.pingcap.com", "d", -1}, false, false, "www.pingcap.com"}, - {[]interface{}{"www.pingcap.com", "", 0}, false, false, ""}, - {[]interface{}{"www.pingcap.com", "", 1}, false, false, ""}, - {[]interface{}{"www.pingcap.com", "", -1}, false, false, ""}, - {[]interface{}{"", ".", 0}, false, false, ""}, - {[]interface{}{"", ".", 1}, false, false, ""}, - {[]interface{}{"", ".", -1}, false, false, ""}, - {[]interface{}{nil, ".", 1}, true, false, ""}, - {[]interface{}{"www.pingcap.com", nil, 1}, true, false, ""}, - {[]interface{}{"www.pingcap.com", ".", nil}, true, false, ""}, - {[]interface{}{errors.New("must error"), ".", 1}, false, true, ""}, + {[]any{"www.pingcap.com", ".", 2}, false, false, "www.pingcap"}, + {[]any{"www.pingcap.com", ".", -2}, false, false, "pingcap.com"}, + {[]any{"www.pingcap.com", ".", 0}, false, false, ""}, + {[]any{"www.pingcap.com", ".", 100}, false, false, "www.pingcap.com"}, + {[]any{"www.pingcap.com", ".", -100}, false, false, "www.pingcap.com"}, + {[]any{"www.pingcap.com", "d", 0}, false, false, ""}, + {[]any{"www.pingcap.com", "d", 1}, false, false, "www.pingcap.com"}, + {[]any{"www.pingcap.com", "d", -1}, false, false, "www.pingcap.com"}, + {[]any{"www.pingcap.com", "", 0}, false, false, ""}, + {[]any{"www.pingcap.com", "", 1}, false, false, ""}, + {[]any{"www.pingcap.com", "", -1}, false, false, ""}, + {[]any{"", ".", 0}, false, false, ""}, + {[]any{"", ".", 1}, false, false, ""}, + {[]any{"", ".", -1}, false, false, ""}, + {[]any{nil, ".", 1}, true, false, ""}, + {[]any{"www.pingcap.com", nil, 1}, true, false, ""}, + {[]any{"www.pingcap.com", ".", nil}, true, false, ""}, + {[]any{errors.New("must error"), ".", 1}, false, true, ""}, } for _, t := range cases { f, err := newFunctionForTest(s.ctx, ast.SubstringIndex, s.primitiveValsToConstants(t.args)...) @@ -868,7 +868,7 @@ func (s *testEvaluatorSuite) TestSpace(c *C) { }() cases := []struct { - arg interface{} + arg any isNil bool getErr bool res string @@ -885,7 +885,7 @@ func (s *testEvaluatorSuite) TestSpace(c *C) { {errors.New("must error"), false, true, ""}, } for _, t := range cases { - f, err := newFunctionForTest(s.ctx, ast.Space, s.primitiveValsToConstants([]interface{}{t.arg})...) + f, err := newFunctionForTest(s.ctx, ast.Space, s.primitiveValsToConstants([]any{t.arg})...) c.Assert(err, IsNil) d, err := f.Eval(chunk.Row{}) if t.getErr { @@ -934,38 +934,38 @@ func (s *testEvaluatorSuite) TestSpaceSig(c *C) { func (s *testEvaluatorSuite) TestLocate(c *C) { // 1. Test LOCATE without binary input. tbl := []struct { - Args []interface{} - Want interface{} + Args []any + Want any }{ - {[]interface{}{"bar", "foobarbar"}, 4}, - {[]interface{}{"xbar", "foobar"}, 0}, - {[]interface{}{"", "foobar"}, 1}, - {[]interface{}{"foobar", ""}, 0}, - {[]interface{}{"", ""}, 1}, - {[]interface{}{"好世", "你好世界"}, 2}, - {[]interface{}{"界面", "你好世界"}, 0}, - {[]interface{}{"b", "中a英b文"}, 4}, - {[]interface{}{"BaR", "foobArbar"}, 4}, - {[]interface{}{nil, "foobar"}, nil}, - {[]interface{}{"bar", nil}, nil}, - {[]interface{}{"bar", "foobarbar", 5}, 7}, - {[]interface{}{"xbar", "foobar", 1}, 0}, - {[]interface{}{"", "foobar", 2}, 2}, - {[]interface{}{"foobar", "", 1}, 0}, - {[]interface{}{"", "", 2}, 0}, - {[]interface{}{"A", "大A写的A", 0}, 0}, - {[]interface{}{"A", "大A写的A", 1}, 2}, - {[]interface{}{"A", "大A写的A", 2}, 2}, - {[]interface{}{"A", "大A写的A", 3}, 5}, - {[]interface{}{"bAr", "foobarBaR", 5}, 7}, - {[]interface{}{nil, nil}, nil}, - {[]interface{}{"", nil}, nil}, - {[]interface{}{nil, ""}, nil}, - {[]interface{}{nil, nil, 1}, nil}, - {[]interface{}{"", nil, 1}, nil}, - {[]interface{}{nil, "", 1}, nil}, - {[]interface{}{"foo", nil, -1}, nil}, - {[]interface{}{nil, "bar", 0}, nil}, + {[]any{"bar", "foobarbar"}, 4}, + {[]any{"xbar", "foobar"}, 0}, + {[]any{"", "foobar"}, 1}, + {[]any{"foobar", ""}, 0}, + {[]any{"", ""}, 1}, + {[]any{"好世", "你好世界"}, 2}, + {[]any{"界面", "你好世界"}, 0}, + {[]any{"b", "中a英b文"}, 4}, + {[]any{"BaR", "foobArbar"}, 4}, + {[]any{nil, "foobar"}, nil}, + {[]any{"bar", nil}, nil}, + {[]any{"bar", "foobarbar", 5}, 7}, + {[]any{"xbar", "foobar", 1}, 0}, + {[]any{"", "foobar", 2}, 2}, + {[]any{"foobar", "", 1}, 0}, + {[]any{"", "", 2}, 0}, + {[]any{"A", "大A写的A", 0}, 0}, + {[]any{"A", "大A写的A", 1}, 2}, + {[]any{"A", "大A写的A", 2}, 2}, + {[]any{"A", "大A写的A", 3}, 5}, + {[]any{"bAr", "foobarBaR", 5}, 7}, + {[]any{nil, nil}, nil}, + {[]any{"", nil}, nil}, + {[]any{nil, ""}, nil}, + {[]any{nil, nil, 1}, nil}, + {[]any{"", nil, 1}, nil}, + {[]any{nil, "", 1}, nil}, + {[]any{"foo", nil, -1}, nil}, + {[]any{nil, "bar", 0}, nil}, } Dtbl := tblToDtbl(tbl) instr := funcs[ast.Locate] @@ -979,14 +979,14 @@ func (s *testEvaluatorSuite) TestLocate(c *C) { } // 2. Test LOCATE with binary input tbl2 := []struct { - Args []interface{} - Want interface{} + Args []any + Want any }{ - {[]interface{}{[]byte("BaR"), "foobArbar"}, 0}, - {[]interface{}{"BaR", []byte("foobArbar")}, 0}, - {[]interface{}{[]byte("bAr"), "foobarBaR", 5}, 0}, - {[]interface{}{"bAr", []byte("foobarBaR"), 5}, 0}, - {[]interface{}{"bAr", []byte("foobarbAr"), 5}, 7}, + {[]any{[]byte("BaR"), "foobArbar"}, 0}, + {[]any{"BaR", []byte("foobArbar")}, 0}, + {[]any{[]byte("bAr"), "foobarBaR", 5}, 0}, + {[]any{"bAr", []byte("foobarBaR"), 5}, 0}, + {[]any{"bAr", []byte("foobarbAr"), 5}, 7}, } Dtbl2 := tblToDtbl(tbl2) for i, t := range Dtbl2 { @@ -1004,29 +1004,29 @@ func (s *testEvaluatorSuite) TestLocate(c *C) { func (s *testEvaluatorSuite) TestTrim(c *C) { cases := []struct { - args []interface{} + args []any isNil bool getErr bool res string }{ - {[]interface{}{" bar "}, false, false, "bar"}, - {[]interface{}{"\t bar \n"}, false, false, "\t bar \n"}, - {[]interface{}{"\r bar \t"}, false, false, "\r bar \t"}, - {[]interface{}{" \tbar\n "}, false, false, "\tbar\n"}, - {[]interface{}{""}, false, false, ""}, - {[]interface{}{nil}, true, false, ""}, - {[]interface{}{"xxxbarxxx", "x"}, false, false, "bar"}, - {[]interface{}{"bar", "x"}, false, false, "bar"}, - {[]interface{}{" bar ", ""}, false, false, " bar "}, - {[]interface{}{"", "x"}, false, false, ""}, - {[]interface{}{"bar", nil}, true, false, ""}, - {[]interface{}{nil, "x"}, true, false, ""}, - {[]interface{}{"xxxbarxxx", "x", int(ast.TrimLeading)}, false, false, "barxxx"}, - {[]interface{}{"barxxyz", "xyz", int(ast.TrimTrailing)}, false, false, "barx"}, - {[]interface{}{"xxxbarxxx", "x", int(ast.TrimBoth)}, false, false, "bar"}, + {[]any{" bar "}, false, false, "bar"}, + {[]any{"\t bar \n"}, false, false, "\t bar \n"}, + {[]any{"\r bar \t"}, false, false, "\r bar \t"}, + {[]any{" \tbar\n "}, false, false, "\tbar\n"}, + {[]any{""}, false, false, ""}, + {[]any{nil}, true, false, ""}, + {[]any{"xxxbarxxx", "x"}, false, false, "bar"}, + {[]any{"bar", "x"}, false, false, "bar"}, + {[]any{" bar ", ""}, false, false, " bar "}, + {[]any{"", "x"}, false, false, ""}, + {[]any{"bar", nil}, true, false, ""}, + {[]any{nil, "x"}, true, false, ""}, + {[]any{"xxxbarxxx", "x", int(ast.TrimLeading)}, false, false, "barxxx"}, + {[]any{"barxxyz", "xyz", int(ast.TrimTrailing)}, false, false, "barx"}, + {[]any{"xxxbarxxx", "x", int(ast.TrimBoth)}, false, false, "bar"}, // FIXME: the result for this test shuold be nil, current is "bar" - {[]interface{}{"bar", nil, int(ast.TrimLeading)}, false, false, "bar"}, - {[]interface{}{errors.New("must error")}, false, true, ""}, + {[]any{"bar", nil, int(ast.TrimLeading)}, false, false, "bar"}, + {[]any{errors.New("must error")}, false, true, ""}, } for _, t := range cases { f, err := newFunctionForTest(s.ctx, ast.Trim, s.primitiveValsToConstants(t.args)...) @@ -1056,7 +1056,7 @@ func (s *testEvaluatorSuite) TestTrim(c *C) { func (s *testEvaluatorSuite) TestLTrim(c *C) { cases := []struct { - arg interface{} + arg any isNil bool getErr bool res string @@ -1076,7 +1076,7 @@ func (s *testEvaluatorSuite) TestLTrim(c *C) { {errors.New("must error"), false, true, ""}, } for _, t := range cases { - f, err := newFunctionForTest(s.ctx, ast.LTrim, s.primitiveValsToConstants([]interface{}{t.arg})...) + f, err := newFunctionForTest(s.ctx, ast.LTrim, s.primitiveValsToConstants([]any{t.arg})...) c.Assert(err, IsNil) d, err := f.Eval(chunk.Row{}) if t.getErr { @@ -1097,7 +1097,7 @@ func (s *testEvaluatorSuite) TestLTrim(c *C) { func (s *testEvaluatorSuite) TestRTrim(c *C) { cases := []struct { - arg interface{} + arg any isNil bool getErr bool res string @@ -1115,7 +1115,7 @@ func (s *testEvaluatorSuite) TestRTrim(c *C) { {errors.New("must error"), false, true, ""}, } for _, t := range cases { - f, err := newFunctionForTest(s.ctx, ast.RTrim, s.primitiveValsToConstants([]interface{}{t.arg})...) + f, err := newFunctionForTest(s.ctx, ast.RTrim, s.primitiveValsToConstants([]any{t.arg})...) c.Assert(err, IsNil) d, err := f.Eval(chunk.Row{}) if t.getErr { @@ -1136,7 +1136,7 @@ func (s *testEvaluatorSuite) TestRTrim(c *C) { func (s *testEvaluatorSuite) TestHexFunc(c *C) { cases := []struct { - arg interface{} + arg any isNil bool getErr bool res string @@ -1155,7 +1155,7 @@ func (s *testEvaluatorSuite) TestHexFunc(c *C) { {errors.New("must err"), false, true, ""}, } for _, t := range cases { - f, err := newFunctionForTest(s.ctx, ast.Hex, s.primitiveValsToConstants([]interface{}{t.arg})...) + f, err := newFunctionForTest(s.ctx, ast.Hex, s.primitiveValsToConstants([]any{t.arg})...) c.Assert(err, IsNil) d, err := f.Eval(chunk.Row{}) if t.getErr { @@ -1179,7 +1179,7 @@ func (s *testEvaluatorSuite) TestHexFunc(c *C) { func (s *testEvaluatorSuite) TestUnhexFunc(c *C) { cases := []struct { - arg interface{} + arg any isNil bool getErr bool res string @@ -1197,7 +1197,7 @@ func (s *testEvaluatorSuite) TestUnhexFunc(c *C) { {errors.New("must error"), false, true, ""}, } for _, t := range cases { - f, err := newFunctionForTest(s.ctx, ast.Unhex, s.primitiveValsToConstants([]interface{}{t.arg})...) + f, err := newFunctionForTest(s.ctx, ast.Unhex, s.primitiveValsToConstants([]any{t.arg})...) c.Assert(err, IsNil) d, err := f.Eval(chunk.Row{}) if t.getErr { @@ -1218,7 +1218,7 @@ func (s *testEvaluatorSuite) TestUnhexFunc(c *C) { func (s *testEvaluatorSuite) TestBitLength(c *C) { cases := []struct { - args interface{} + args any expected int64 isNil bool getErr bool @@ -1229,7 +1229,7 @@ func (s *testEvaluatorSuite) TestBitLength(c *C) { } for _, t := range cases { - f, err := newFunctionForTest(s.ctx, ast.BitLength, s.primitiveValsToConstants([]interface{}{t.args})...) + f, err := newFunctionForTest(s.ctx, ast.BitLength, s.primitiveValsToConstants([]any{t.args})...) c.Assert(err, IsNil) d, err := f.Eval(chunk.Row{}) if t.getErr { @@ -1268,7 +1268,7 @@ func (s *testEvaluatorSuite) TestChar(c *C) { {"a", -1, 67.5, "\x00\xff\xff\xff\xffD"}, // invalid 'a' } for _, v := range tbl { - for _, char := range []interface{}{"utf8", nil} { + for _, char := range []any{"utf8", nil} { fc := funcs[ast.CharFunc] f, err := fc.getFunction(s.ctx, s.datumsToConstants(types.MakeDatums(v.str, v.iNum, v.fNum, char))) c.Assert(err, IsNil) @@ -1296,8 +1296,8 @@ func (s *testEvaluatorSuite) TestChar(c *C) { func (s *testEvaluatorSuite) TestCharLength(c *C) { tbl := []struct { - input interface{} - result interface{} + input any + result any }{ {"33", 2}, // string {"你好", 2}, // mb string @@ -1316,8 +1316,8 @@ func (s *testEvaluatorSuite) TestCharLength(c *C) { // Test binary string tbl = []struct { - input interface{} - result interface{} + input any + result any }{ {"33", 2}, // string {"你好", 6}, // mb string @@ -1344,9 +1344,9 @@ func (s *testEvaluatorSuite) TestCharLength(c *C) { func (s *testEvaluatorSuite) TestFindInSet(c *C) { for _, t := range []struct { - str interface{} - strlst interface{} - ret interface{} + str any + strlst any + ret any }{ {"foo", "foo,bar", 1}, {"foo", "foobar,bar", 0}, @@ -1378,19 +1378,19 @@ func (s *testEvaluatorSuite) TestField(c *C) { }() tbl := []struct { - argLst []interface{} - ret interface{} + argLst []any + ret any }{ - {[]interface{}{"ej", "Hej", "ej", "Heja", "hej", "foo"}, int64(2)}, - {[]interface{}{"fo", "Hej", "ej", "Heja", "hej", "foo"}, int64(0)}, - {[]interface{}{"ej", "Hej", "ej", "Heja", "ej", "hej", "foo"}, int64(2)}, - {[]interface{}{1, 2, 3, 11, 1}, int64(4)}, - {[]interface{}{nil, 2, 3, 11, 1}, int64(0)}, - {[]interface{}{1.1, 2.1, 3.1, 11.1, 1.1}, int64(4)}, - {[]interface{}{1.1, "2.1", "3.1", "11.1", "1.1"}, int64(4)}, - {[]interface{}{"1.1a", 2.1, 3.1, 11.1, 1.1}, int64(4)}, - {[]interface{}{1.10, 0, 11e-1}, int64(2)}, - {[]interface{}{"abc", 0, 1, 11.1, 1.1}, int64(1)}, + {[]any{"ej", "Hej", "ej", "Heja", "hej", "foo"}, int64(2)}, + {[]any{"fo", "Hej", "ej", "Heja", "hej", "foo"}, int64(0)}, + {[]any{"ej", "Hej", "ej", "Heja", "ej", "hej", "foo"}, int64(2)}, + {[]any{1, 2, 3, 11, 1}, int64(4)}, + {[]any{nil, 2, 3, 11, 1}, int64(0)}, + {[]any{1.1, 2.1, 3.1, 11.1, 1.1}, int64(4)}, + {[]any{1.1, "2.1", "3.1", "11.1", "1.1"}, int64(4)}, + {[]any{"1.1a", 2.1, 3.1, 11.1, 1.1}, int64(4)}, + {[]any{1.10, 0, 11e-1}, int64(2)}, + {[]any{"abc", 0, 1, 11.1, 1.1}, int64(1)}, } for _, t := range tbl { fc := funcs[ast.Field] @@ -1408,7 +1408,7 @@ func (s *testEvaluatorSuite) TestLpad(c *C) { str string len int64 padStr string - expect interface{} + expect any }{ {"hi", 5, "?", "???hi"}, {"hi", 1, "?", "h"}, @@ -1443,7 +1443,7 @@ func (s *testEvaluatorSuite) TestRpad(c *C) { str string len int64 padStr string - expect interface{} + expect any }{ {"hi", 5, "?", "hi???"}, {"hi", 1, "?", "h"}, @@ -1606,34 +1606,34 @@ func (s *testEvaluatorSuite) TestInsertBinarySig(c *C) { func (s *testEvaluatorSuite) TestInstr(c *C) { tbl := []struct { - Args []interface{} - Want interface{} + Args []any + Want any }{ - {[]interface{}{"foobarbar", "bar"}, 4}, - {[]interface{}{"xbar", "foobar"}, 0}, + {[]any{"foobarbar", "bar"}, 4}, + {[]any{"xbar", "foobar"}, 0}, - {[]interface{}{123456234, 234}, 2}, - {[]interface{}{123456, 567}, 0}, - {[]interface{}{1e10, 1e2}, 1}, - {[]interface{}{1.234, ".234"}, 2}, - {[]interface{}{1.234, ""}, 1}, - {[]interface{}{"", 123}, 0}, - {[]interface{}{"", ""}, 1}, + {[]any{123456234, 234}, 2}, + {[]any{123456, 567}, 0}, + {[]any{1e10, 1e2}, 1}, + {[]any{1.234, ".234"}, 2}, + {[]any{1.234, ""}, 1}, + {[]any{"", 123}, 0}, + {[]any{"", ""}, 1}, - {[]interface{}{"中文美好", "美好"}, 3}, - {[]interface{}{"中文美好", "世界"}, 0}, - {[]interface{}{"中文abc", "a"}, 3}, + {[]any{"中文美好", "美好"}, 3}, + {[]any{"中文美好", "世界"}, 0}, + {[]any{"中文abc", "a"}, 3}, - {[]interface{}{"live LONG and prosper", "long"}, 6}, + {[]any{"live LONG and prosper", "long"}, 6}, - {[]interface{}{"not BINARY string", "binary"}, 5}, - {[]interface{}{"UPPER case", "upper"}, 1}, - {[]interface{}{"UPPER case", "CASE"}, 7}, - {[]interface{}{"中文abc", "abc"}, 3}, + {[]any{"not BINARY string", "binary"}, 5}, + {[]any{"UPPER case", "upper"}, 1}, + {[]any{"UPPER case", "CASE"}, 7}, + {[]any{"中文abc", "abc"}, 3}, - {[]interface{}{"foobar", nil}, nil}, - {[]interface{}{nil, "foobar"}, nil}, - {[]interface{}{nil, nil}, nil}, + {[]any{"foobar", nil}, nil}, + {[]any{nil, "foobar"}, nil}, + {[]any{nil, nil}, nil}, } Dtbl := tblToDtbl(tbl) @@ -1650,16 +1650,16 @@ func (s *testEvaluatorSuite) TestInstr(c *C) { func (s *testEvaluatorSuite) TestMakeSet(c *C) { tbl := []struct { - argList []interface{} - ret interface{} + argList []any + ret any }{ - {[]interface{}{1, "a", "b", "c"}, "a"}, - {[]interface{}{1 | 4, "hello", "nice", "world"}, "hello,world"}, - {[]interface{}{1 | 4, "hello", "nice", nil, "world"}, "hello"}, - {[]interface{}{0, "a", "b", "c"}, ""}, - {[]interface{}{nil, "a", "b", "c"}, nil}, - {[]interface{}{-100 | 4, "hello", "nice", "abc", "world"}, "abc,world"}, - {[]interface{}{-1, "hello", "nice", "abc", "world"}, "hello,nice,abc,world"}, + {[]any{1, "a", "b", "c"}, "a"}, + {[]any{1 | 4, "hello", "nice", "world"}, "hello,world"}, + {[]any{1 | 4, "hello", "nice", nil, "world"}, "hello"}, + {[]any{0, "a", "b", "c"}, ""}, + {[]any{nil, "a", "b", "c"}, nil}, + {[]any{-100 | 4, "hello", "nice", "abc", "world"}, "abc,world"}, + {[]any{-1, "hello", "nice", "abc", "world"}, "hello,nice,abc,world"}, } for _, t := range tbl { @@ -1675,7 +1675,7 @@ func (s *testEvaluatorSuite) TestMakeSet(c *C) { func (s *testEvaluatorSuite) TestOct(c *C) { octTests := []struct { - origin interface{} + origin any ret string }{ {"-2.7", "1777777777777777777776"}, @@ -1723,18 +1723,18 @@ func (s *testEvaluatorSuite) TestOct(c *C) { func (s *testEvaluatorSuite) TestFormat(c *C) { formatTests := []struct { - number interface{} - precision interface{} + number any + precision any locale string - ret interface{} + ret any }{ {12332.12341111111111111111111111111111111111111, 4, "en_US", "12,332.1234"}, {nil, 22, "en_US", nil}, } formatTests1 := []struct { - number interface{} - precision interface{} - ret interface{} + number any + precision any + ret any warnings int }{ // issue #8796 @@ -1773,22 +1773,22 @@ func (s *testEvaluatorSuite) TestFormat(c *C) { {1, "", "1", 1}, } formatTests2 := struct { - number interface{} - precision interface{} + number any + precision any locale string - ret interface{} + ret any }{-12332.123456, -4, "zh_CN", nil} formatTests3 := struct { - number interface{} - precision interface{} + number any + precision any locale string - ret interface{} + ret any }{"-12332.123456", "4", "de_GE", nil} formatTests4 := struct { - number interface{} - precision interface{} - locale interface{} - ret interface{} + number any + precision any + locale any + ret any }{1, 4, nil, "1.0000"} fc := funcs[ast.Format] @@ -1849,8 +1849,8 @@ func (s *testEvaluatorSuite) TestFormat(c *C) { func (s *testEvaluatorSuite) TestFromBase64(c *C) { tests := []struct { - args interface{} - expect interface{} + args any + expect any }{ {"", ""}, {"YWJj", "abc"}, @@ -1945,32 +1945,32 @@ func (s *testEvaluatorSuite) TestFromBase64Sig(c *C) { func (s *testEvaluatorSuite) TestInsert(c *C) { tests := []struct { - args []interface{} - expect interface{} + args []any + expect any }{ - {[]interface{}{"Quadratic", 3, 4, "What"}, "QuWhattic"}, - {[]interface{}{"Quadratic", -1, 4, "What"}, "Quadratic"}, - {[]interface{}{"Quadratic", 3, 100, "What"}, "QuWhat"}, - {[]interface{}{nil, 3, 100, "What"}, nil}, - {[]interface{}{"Quadratic", nil, 4, "What"}, nil}, - {[]interface{}{"Quadratic", 3, nil, "What"}, nil}, - {[]interface{}{"Quadratic", 3, 4, nil}, nil}, - {[]interface{}{"Quadratic", 3, -1, "What"}, "QuWhat"}, - {[]interface{}{"Quadratic", 3, 1, "What"}, "QuWhatdratic"}, - {[]interface{}{"Quadratic", -1, nil, "What"}, nil}, - {[]interface{}{"Quadratic", -1, 4, nil}, nil}, - - {[]interface{}{"我叫小雨呀", 3, 2, "王雨叶"}, "我叫王雨叶呀"}, - {[]interface{}{"我叫小雨呀", -1, 2, "王雨叶"}, "我叫小雨呀"}, - {[]interface{}{"我叫小雨呀", 3, 100, "王雨叶"}, "我叫王雨叶"}, - {[]interface{}{nil, 3, 100, "王雨叶"}, nil}, - {[]interface{}{"我叫小雨呀", nil, 4, "王雨叶"}, nil}, - {[]interface{}{"我叫小雨呀", 3, nil, "王雨叶"}, nil}, - {[]interface{}{"我叫小雨呀", 3, 4, nil}, nil}, - {[]interface{}{"我叫小雨呀", 3, -1, "王雨叶"}, "我叫王雨叶"}, - {[]interface{}{"我叫小雨呀", 3, 1, "王雨叶"}, "我叫王雨叶雨呀"}, - {[]interface{}{"我叫小雨呀", -1, nil, "王雨叶"}, nil}, - {[]interface{}{"我叫小雨呀", -1, 2, nil}, nil}, + {[]any{"Quadratic", 3, 4, "What"}, "QuWhattic"}, + {[]any{"Quadratic", -1, 4, "What"}, "Quadratic"}, + {[]any{"Quadratic", 3, 100, "What"}, "QuWhat"}, + {[]any{nil, 3, 100, "What"}, nil}, + {[]any{"Quadratic", nil, 4, "What"}, nil}, + {[]any{"Quadratic", 3, nil, "What"}, nil}, + {[]any{"Quadratic", 3, 4, nil}, nil}, + {[]any{"Quadratic", 3, -1, "What"}, "QuWhat"}, + {[]any{"Quadratic", 3, 1, "What"}, "QuWhatdratic"}, + {[]any{"Quadratic", -1, nil, "What"}, nil}, + {[]any{"Quadratic", -1, 4, nil}, nil}, + + {[]any{"我叫小雨呀", 3, 2, "王雨叶"}, "我叫王雨叶呀"}, + {[]any{"我叫小雨呀", -1, 2, "王雨叶"}, "我叫小雨呀"}, + {[]any{"我叫小雨呀", 3, 100, "王雨叶"}, "我叫王雨叶"}, + {[]any{nil, 3, 100, "王雨叶"}, nil}, + {[]any{"我叫小雨呀", nil, 4, "王雨叶"}, nil}, + {[]any{"我叫小雨呀", 3, nil, "王雨叶"}, nil}, + {[]any{"我叫小雨呀", 3, 4, nil}, nil}, + {[]any{"我叫小雨呀", 3, -1, "王雨叶"}, "我叫王雨叶"}, + {[]any{"我叫小雨呀", 3, 1, "王雨叶"}, "我叫王雨叶雨呀"}, + {[]any{"我叫小雨呀", -1, nil, "王雨叶"}, nil}, + {[]any{"我叫小雨呀", -1, 2, nil}, nil}, } fc := funcs[ast.InsertFunc] for _, test := range tests { @@ -1990,7 +1990,7 @@ func (s *testEvaluatorSuite) TestInsert(c *C) { func (s *testEvaluatorSuite) TestOrd(c *C) { cases := []struct { - args interface{} + args any expected int64 isNil bool getErr bool @@ -2009,7 +2009,7 @@ func (s *testEvaluatorSuite) TestOrd(c *C) { {"א", 55184, false, false}, } for _, t := range cases { - f, err := newFunctionForTest(s.ctx, ast.Ord, s.primitiveValsToConstants([]interface{}{t.args})...) + f, err := newFunctionForTest(s.ctx, ast.Ord, s.primitiveValsToConstants([]any{t.args})...) c.Assert(err, IsNil) d, err := f.Eval(chunk.Row{}) @@ -2030,15 +2030,15 @@ func (s *testEvaluatorSuite) TestOrd(c *C) { func (s *testEvaluatorSuite) TestElt(c *C) { tbl := []struct { - argLst []interface{} - ret interface{} + argLst []any + ret any }{ - {[]interface{}{1, "Hej", "ej", "Heja", "hej", "foo"}, "Hej"}, - {[]interface{}{9, "Hej", "ej", "Heja", "hej", "foo"}, nil}, - {[]interface{}{-1, "Hej", "ej", "Heja", "ej", "hej", "foo"}, nil}, - {[]interface{}{0, 2, 3, 11, 1}, nil}, - {[]interface{}{3, 2, 3, 11, 1}, "11"}, - {[]interface{}{1.1, "2.1", "3.1", "11.1", "1.1"}, "2.1"}, + {[]any{1, "Hej", "ej", "Heja", "hej", "foo"}, "Hej"}, + {[]any{9, "Hej", "ej", "Heja", "hej", "foo"}, nil}, + {[]any{-1, "Hej", "ej", "Heja", "ej", "hej", "foo"}, nil}, + {[]any{0, 2, 3, 11, 1}, nil}, + {[]any{3, 2, 3, 11, 1}, "11"}, + {[]any{1.1, "2.1", "3.1", "11.1", "1.1"}, "2.1"}, } for _, t := range tbl { fc := funcs[ast.Elt] @@ -2052,19 +2052,19 @@ func (s *testEvaluatorSuite) TestElt(c *C) { func (s *testEvaluatorSuite) TestExportSet(c *C) { estd := []struct { - argLst []interface{} + argLst []any res string }{ - {[]interface{}{-9223372036854775807, "Y", "N", ",", 5}, "Y,N,N,N,N"}, - {[]interface{}{-6, "Y", "N", ",", 5}, "N,Y,N,Y,Y"}, - {[]interface{}{5, "Y", "N", ",", 4}, "Y,N,Y,N"}, - {[]interface{}{5, "Y", "N", ",", 0}, ""}, - {[]interface{}{5, "Y", "N", ",", 1}, "Y"}, - {[]interface{}{6, "1", "0", ",", 10}, "0,1,1,0,0,0,0,0,0,0"}, - {[]interface{}{333333, "Ysss", "sN", "---", 9}, "Ysss---sN---Ysss---sN---Ysss---sN---sN---sN---sN"}, - {[]interface{}{7, "Y", "N"}, "Y,Y,Y,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N"}, - {[]interface{}{7, "Y", "N", 6}, "Y6Y6Y6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N"}, - {[]interface{}{7, "Y", "N", 6, 133}, "Y6Y6Y6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N"}, + {[]any{-9223372036854775807, "Y", "N", ",", 5}, "Y,N,N,N,N"}, + {[]any{-6, "Y", "N", ",", 5}, "N,Y,N,Y,Y"}, + {[]any{5, "Y", "N", ",", 4}, "Y,N,Y,N"}, + {[]any{5, "Y", "N", ",", 0}, ""}, + {[]any{5, "Y", "N", ",", 1}, "Y"}, + {[]any{6, "1", "0", ",", 10}, "0,1,1,0,0,0,0,0,0,0"}, + {[]any{333333, "Ysss", "sN", "---", 9}, "Ysss---sN---Ysss---sN---Ysss---sN---sN---sN---sN"}, + {[]any{7, "Y", "N"}, "Y,Y,Y,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N"}, + {[]any{7, "Y", "N", 6}, "Y6Y6Y6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N"}, + {[]any{7, "Y", "N", 6, 133}, "Y6Y6Y6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N6N"}, } fc := funcs[ast.ExportSet] for _, t := range estd { @@ -2081,8 +2081,8 @@ func (s *testEvaluatorSuite) TestExportSet(c *C) { func (s *testEvaluatorSuite) TestBin(c *C) { tbl := []struct { - Input interface{} - Expected interface{} + Input any + Expected any }{ {"10", "1010"}, {"10.2", "1010"}, @@ -2112,8 +2112,8 @@ func (s *testEvaluatorSuite) TestBin(c *C) { func (s *testEvaluatorSuite) TestQuote(c *C) { tbl := []struct { - arg interface{} - ret interface{} + arg any + ret any }{ {`Don\'t!`, `'Don\\\'t!'`}, {`Don't`, `'Don\'t'`}, @@ -2140,7 +2140,7 @@ func (s *testEvaluatorSuite) TestQuote(c *C) { func (s *testEvaluatorSuite) TestToBase64(c *C) { tests := []struct { - args interface{} + args any expect string isNil bool getErr bool @@ -2175,7 +2175,7 @@ func (s *testEvaluatorSuite) TestToBase64(c *C) { } if strconv.IntSize == 32 { tests = append(tests, struct { - args interface{} + args any expect string isNil bool getErr bool @@ -2188,7 +2188,7 @@ func (s *testEvaluatorSuite) TestToBase64(c *C) { } for _, test := range tests { - f, err := newFunctionForTest(s.ctx, ast.ToBase64, s.primitiveValsToConstants([]interface{}{test.args})...) + f, err := newFunctionForTest(s.ctx, ast.ToBase64, s.primitiveValsToConstants([]any{test.args})...) c.Assert(err, IsNil) d, err := f.Eval(chunk.Row{}) if test.getErr { @@ -2278,9 +2278,9 @@ func (s *testEvaluatorSuite) TestToBase64Sig(c *C) { func (s *testEvaluatorSuite) TestStringRight(c *C) { fc := funcs[ast.Right] tests := []struct { - str interface{} - length interface{} - expect interface{} + str any + length any + expect any }{ {"helloworld", 5, "world"}, {"helloworld", 10, "helloworld"}, @@ -2309,10 +2309,10 @@ func (s *testEvaluatorSuite) TestStringRight(c *C) { func (s *testEvaluatorSuite) TestWeightString(c *C) { fc := funcs[ast.WeightString] tests := []struct { - expr interface{} + expr any padding string length int - expect interface{} + expect any }{ {nil, "NONE", 0, nil}, {7, "NONE", 0, nil}, @@ -2387,7 +2387,7 @@ func (s *testEvaluatorSerialSuites) TestCIWeightString(c *C) { str string padding string length int - expect interface{} + expect any }{ {"aAÁàãăâ", "NONE", 0, "\x00A\x00A\x00A\x00A\x00A\x00A\x00A"}, {"中", "NONE", 0, "\x4E\x2D"}, diff --git a/expression/builtin_string_vec_test.go b/expression/builtin_string_vec_test.go index 909829445..3e243bdf4 100644 --- a/expression/builtin_string_vec_test.go +++ b/expression/builtin_string_vec_test.go @@ -29,7 +29,7 @@ type randSpaceStrGener struct { lenEnd int } -func (g *randSpaceStrGener) gen() interface{} { +func (g *randSpaceStrGener) gen() any { n := rand.Intn(g.lenEnd-g.lenBegin) + g.lenBegin buf := make([]byte, n) for i := range buf { diff --git a/expression/builtin_test.go b/expression/builtin_test.go index 2c6b19986..85e96a6c2 100644 --- a/expression/builtin_test.go +++ b/expression/builtin_test.go @@ -28,7 +28,7 @@ import ( func evalBuiltinFunc(f builtinFunc, row chunk.Row) (d types.Datum, err error) { var ( - res interface{} + res any isNull bool ) switch f.getRetTp().EvalType() { @@ -63,7 +63,7 @@ func evalBuiltinFunc(f builtinFunc, row chunk.Row) (d types.Datum, err error) { } // tblToDtbl is a util function for test. -func tblToDtbl(i interface{}) []map[string][]types.Datum { +func tblToDtbl(i any) []map[string][]types.Datum { l := reflect.ValueOf(i).Len() tbl := make([]map[string][]types.Datum, l) for j := 0; j < l; j++ { @@ -80,7 +80,7 @@ func tblToDtbl(i interface{}) []map[string][]types.Datum { return tbl } -func makeDatums(i interface{}) []types.Datum { +func makeDatums(i any) []types.Datum { if i != nil { t := reflect.TypeOf(i) val := reflect.ValueOf(i) diff --git a/expression/builtin_time_test.go b/expression/builtin_time_test.go index 575b354fa..ef6639760 100644 --- a/expression/builtin_time_test.go +++ b/expression/builtin_time_test.go @@ -44,8 +44,8 @@ func init() { func (s *testEvaluatorSuite) TestDate(c *C) { tblDate := []struct { - Input interface{} - Expect interface{} + Input any + Expect any }{ {"2011-11-11", "2011-11-11"}, {nil, nil}, @@ -164,18 +164,18 @@ func (s *testEvaluatorSuite) TestDate(c *C) { // test nil tblNil := []struct { - Input interface{} - Year interface{} - Month interface{} - MonthName interface{} - DayOfMonth interface{} - DayOfWeek interface{} - DayOfYear interface{} - WeekDay interface{} - DayName interface{} - Week interface{} - WeekOfYear interface{} - YearWeek interface{} + Input any + Year any + Month any + MonthName any + DayOfMonth any + DayOfWeek any + DayOfYear any + WeekDay any + DayName any + Week any + WeekOfYear any + YearWeek any }{ {nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil}, {"0000-00-00 00:00:00", 0, 0, nil, 0, nil, nil, nil, nil, nil, nil, nil}, @@ -265,18 +265,18 @@ func (s *testEvaluatorSuite) TestDate(c *C) { // test nil with 'NO_ZERO_DATE' set in sql_mode tblNil = []struct { - Input interface{} - Year interface{} - Month interface{} - MonthName interface{} - DayOfMonth interface{} - DayOfWeek interface{} - DayOfYear interface{} - WeekDay interface{} - DayName interface{} - Week interface{} - WeekOfYear interface{} - YearWeek interface{} + Input any + Year any + Month any + MonthName any + DayOfMonth any + DayOfWeek any + DayOfYear any + WeekDay any + DayName any + Week any + WeekOfYear any + YearWeek any }{ {nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil}, {"0000-00-00 00:00:00", nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil}, @@ -370,7 +370,7 @@ func (s *testEvaluatorSuite) TestMonthName(c *C) { sc := s.ctx.GetSessionVars().StmtCtx sc.IgnoreZeroInDate = true cases := []struct { - args interface{} + args any expected string isNil bool getErr bool @@ -382,7 +382,7 @@ func (s *testEvaluatorSuite) TestMonthName(c *C) { {"0000-00-00 00:00:11.000000", "", true, false}, } for _, t := range cases { - f, err := newFunctionForTest(s.ctx, ast.MonthName, s.primitiveValsToConstants([]interface{}{t.args})...) + f, err := newFunctionForTest(s.ctx, ast.MonthName, s.primitiveValsToConstants([]any{t.args})...) c.Assert(err, IsNil) d, err := f.Eval(chunk.Row{}) if t.getErr { @@ -405,7 +405,7 @@ func (s *testEvaluatorSuite) TestDayName(c *C) { sc := s.ctx.GetSessionVars().StmtCtx sc.IgnoreZeroInDate = true cases := []struct { - args interface{} + args any expected string isNil bool getErr bool @@ -419,7 +419,7 @@ func (s *testEvaluatorSuite) TestDayName(c *C) { {"0000-00-00 00:00:11.000000", "", true, false}, } for _, t := range cases { - f, err := newFunctionForTest(s.ctx, ast.DayName, s.primitiveValsToConstants([]interface{}{t.args})...) + f, err := newFunctionForTest(s.ctx, ast.DayName, s.primitiveValsToConstants([]any{t.args})...) c.Assert(err, IsNil) d, err := f.Eval(chunk.Row{}) if t.getErr { @@ -442,7 +442,7 @@ func (s *testEvaluatorSuite) TestDayOfWeek(c *C) { sc := s.ctx.GetSessionVars().StmtCtx sc.IgnoreZeroInDate = true cases := []struct { - args interface{} + args any expected int64 isNil bool getErr bool @@ -454,7 +454,7 @@ func (s *testEvaluatorSuite) TestDayOfWeek(c *C) { {"0000-00-00 12:12:12", 1, true, false}, } for _, t := range cases { - f, err := newFunctionForTest(s.ctx, ast.DayOfWeek, s.primitiveValsToConstants([]interface{}{t.args})...) + f, err := newFunctionForTest(s.ctx, ast.DayOfWeek, s.primitiveValsToConstants([]any{t.args})...) c.Assert(err, IsNil) d, err := f.Eval(chunk.Row{}) if t.getErr { @@ -477,7 +477,7 @@ func (s *testEvaluatorSuite) TestDayOfMonth(c *C) { sc := s.ctx.GetSessionVars().StmtCtx sc.IgnoreZeroInDate = true cases := []struct { - args interface{} + args any expected int64 isNil bool getErr bool @@ -489,7 +489,7 @@ func (s *testEvaluatorSuite) TestDayOfMonth(c *C) { {"0000-00-00 12:12:12", 0, false, false}, } for _, t := range cases { - f, err := newFunctionForTest(s.ctx, ast.DayOfMonth, s.primitiveValsToConstants([]interface{}{t.args})...) + f, err := newFunctionForTest(s.ctx, ast.DayOfMonth, s.primitiveValsToConstants([]any{t.args})...) c.Assert(err, IsNil) d, err := f.Eval(chunk.Row{}) if t.getErr { @@ -512,7 +512,7 @@ func (s *testEvaluatorSuite) TestDayOfYear(c *C) { sc := s.ctx.GetSessionVars().StmtCtx sc.IgnoreZeroInDate = true cases := []struct { - args interface{} + args any expected int64 isNil bool getErr bool @@ -524,7 +524,7 @@ func (s *testEvaluatorSuite) TestDayOfYear(c *C) { {"0000-00-00 12:12:12", 0, true, false}, } for _, t := range cases { - f, err := newFunctionForTest(s.ctx, ast.DayOfYear, s.primitiveValsToConstants([]interface{}{t.args})...) + f, err := newFunctionForTest(s.ctx, ast.DayOfYear, s.primitiveValsToConstants([]any{t.args})...) c.Assert(err, IsNil) d, err := f.Eval(chunk.Row{}) if t.getErr { @@ -556,7 +556,7 @@ func (s *testEvaluatorSuite) TestDateFormat(c *C) { tblDate := []struct { Input []string - Expect interface{} + Expect any }{ {[]string{"2010-01-07 23:12:34.12345", `%b %M %m %c %D %d %e %j %k %h %i %p %r %T %s %f %U %u %V %v %a %W %w %X %x %Y %y %%`}, @@ -719,7 +719,7 @@ func (s *testEvaluatorSuite) TestClock(c *C) { func (s *testEvaluatorSuite) TestTime(c *C) { cases := []struct { - args interface{} + args any expected string isNil bool getErr bool @@ -732,7 +732,7 @@ func (s *testEvaluatorSuite) TestTime(c *C) { } for _, t := range cases { - f, err := newFunctionForTest(s.ctx, ast.Time, s.primitiveValsToConstants([]interface{}{t.args})...) + f, err := newFunctionForTest(s.ctx, ast.Time, s.primitiveValsToConstants([]any{t.args})...) c.Assert(err, IsNil) tp := f.GetType() c.Assert(tp.Tp, Equals, mysql.TypeDuration) @@ -928,8 +928,8 @@ func (s *testEvaluatorSuite) TestAddTimeSig(c *C) { } tblWarning := []struct { - Input interface{} - InputDuration interface{} + Input any + InputDuration any warning *terror.Error }{ {"0", "-32073", types.ErrTruncatedWrongVal}, @@ -1020,8 +1020,8 @@ func (s *testEvaluatorSuite) TestSubTimeSig(c *C) { } tblWarning := []struct { - Input interface{} - InputDuration interface{} + Input any + InputDuration any warning *terror.Error }{ {"0", "-32073", types.ErrTruncatedWrongVal}, @@ -1286,7 +1286,7 @@ func (s *testEvaluatorSuite) TestUTCTime(c *C) { fc := funcs[ast.UTCTime] tests := []struct { - param interface{} + param any expect int }{{0, 8}, {3, 12}, {6, 15}, {-1, 0}, {7, 0}} @@ -1487,18 +1487,18 @@ func (s *testEvaluatorSuite) TestTimeDiff(c *C) { sc.IgnoreZeroInDate = true // Test cases from https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_timediff tests := []struct { - args []interface{} + args []any expectStr string isNil bool fsp int8 getErr bool }{ - {[]interface{}{"2000:01:01 00:00:00", "2000:01:01 00:00:00.000001"}, "-00:00:00.000001", false, 6, false}, - {[]interface{}{"2008-12-31 23:59:59.000001", "2008-12-30 01:01:01.000002"}, "46:58:57.999999", false, 6, false}, - {[]interface{}{"2016-12-00 12:00:00", "2016-12-01 12:00:00"}, "-24:00:00", false, 0, false}, - {[]interface{}{"10:10:10", "10:9:0"}, "00:01:10", false, 0, false}, - {[]interface{}{"2016-12-00 12:00:00", "10:9:0"}, "", true, 0, false}, - {[]interface{}{"2016-12-00 12:00:00", ""}, "", true, 0, true}, + {[]any{"2000:01:01 00:00:00", "2000:01:01 00:00:00.000001"}, "-00:00:00.000001", false, 6, false}, + {[]any{"2008-12-31 23:59:59.000001", "2008-12-30 01:01:01.000002"}, "46:58:57.999999", false, 6, false}, + {[]any{"2016-12-00 12:00:00", "2016-12-01 12:00:00"}, "-24:00:00", false, 0, false}, + {[]any{"10:10:10", "10:9:0"}, "00:01:10", false, 0, false}, + {[]any{"2016-12-00 12:00:00", "10:9:0"}, "", true, 0, false}, + {[]any{"2016-12-00 12:00:00", ""}, "", true, 0, true}, } for _, t := range tests { @@ -1872,7 +1872,7 @@ func (s *testEvaluatorSuite) TestDateArithFuncs(c *C) { dur string fsp int8 unit string - format interface{} + format any expected string }{ { @@ -2030,29 +2030,29 @@ func (s *testEvaluatorSuite) TestTimestamp(c *C) { func (s *testEvaluatorSuite) TestMakeDate(c *C) { cases := []struct { - args []interface{} + args []any expected string isNil bool getErr bool }{ - {[]interface{}{71, 1}, "1971-01-01", false, false}, - {[]interface{}{71.1, 1.89}, "1971-01-02", false, false}, - {[]interface{}{99, 1}, "1999-01-01", false, false}, - {[]interface{}{100, 1}, "0100-01-01", false, false}, - {[]interface{}{69, 1}, "2069-01-01", false, false}, - {[]interface{}{70, 1}, "1970-01-01", false, false}, - {[]interface{}{1000, 1}, "1000-01-01", false, false}, - {[]interface{}{-1, 3660}, "", true, false}, - {[]interface{}{10000, 3660}, "", true, false}, - {[]interface{}{2060, 2900025}, "9999-12-31", false, false}, - {[]interface{}{2060, 2900026}, "", true, false}, - {[]interface{}{"71", 1}, "1971-01-01", false, false}, - {[]interface{}{71, "1"}, "1971-01-01", false, false}, - {[]interface{}{"71", "1"}, "1971-01-01", false, false}, - {[]interface{}{nil, 2900025}, "", true, false}, - {[]interface{}{2060, nil}, "", true, false}, - {[]interface{}{nil, nil}, "", true, false}, - {[]interface{}{errors.New("must error"), errors.New("must error")}, "", false, true}, + {[]any{71, 1}, "1971-01-01", false, false}, + {[]any{71.1, 1.89}, "1971-01-02", false, false}, + {[]any{99, 1}, "1999-01-01", false, false}, + {[]any{100, 1}, "0100-01-01", false, false}, + {[]any{69, 1}, "2069-01-01", false, false}, + {[]any{70, 1}, "1970-01-01", false, false}, + {[]any{1000, 1}, "1000-01-01", false, false}, + {[]any{-1, 3660}, "", true, false}, + {[]any{10000, 3660}, "", true, false}, + {[]any{2060, 2900025}, "9999-12-31", false, false}, + {[]any{2060, 2900026}, "", true, false}, + {[]any{"71", 1}, "1971-01-01", false, false}, + {[]any{71, "1"}, "1971-01-01", false, false}, + {[]any{"71", "1"}, "1971-01-01", false, false}, + {[]any{nil, 2900025}, "", true, false}, + {[]any{2060, nil}, "", true, false}, + {[]any{nil, nil}, "", true, false}, + {[]any{errors.New("must error"), errors.New("must error")}, "", false, true}, } for _, t := range cases { @@ -2083,55 +2083,55 @@ func (s *testEvaluatorSuite) TestMakeDate(c *C) { func (s *testEvaluatorSuite) TestMakeTime(c *C) { tbl := []struct { - Args []interface{} - Want interface{} + Args []any + Want any }{ - {[]interface{}{12, 15, 30}, "12:15:30"}, - {[]interface{}{25, 15, 30}, "25:15:30"}, - {[]interface{}{-25, 15, 30}, "-25:15:30"}, - {[]interface{}{12, -15, 30}, nil}, - {[]interface{}{12, 15, -30}, nil}, - - {[]interface{}{12, 15, "30.10"}, "12:15:30.100000"}, - {[]interface{}{12, 15, "30.20"}, "12:15:30.200000"}, - {[]interface{}{12, 15, 30.3000001}, "12:15:30.300000"}, - {[]interface{}{12, 15, 30.0000005}, "12:15:30.000001"}, - {[]interface{}{"12", "15", 30.1}, "12:15:30.100000"}, - - {[]interface{}{0, 58.4, 0}, "00:58:00"}, - {[]interface{}{0, "58.4", 0}, "00:58:00"}, - {[]interface{}{0, 58.5, 1}, "00:59:01"}, - {[]interface{}{0, "58.5", 1}, "00:58:01"}, - {[]interface{}{0, 59.5, 1}, nil}, - {[]interface{}{0, "59.5", 1}, "00:59:01"}, - {[]interface{}{0, 1, 59.1}, "00:01:59.100000"}, - {[]interface{}{0, 1, "59.1"}, "00:01:59.100000"}, - {[]interface{}{0, 1, 59.5}, "00:01:59.500000"}, - {[]interface{}{0, 1, "59.5"}, "00:01:59.500000"}, - {[]interface{}{23.5, 1, 10}, "24:01:10"}, - {[]interface{}{"23.5", 1, 10}, "23:01:10"}, - - {[]interface{}{0, 0, 0}, "00:00:00"}, - - {[]interface{}{837, 59, 59.1}, "837:59:59.100000"}, - {[]interface{}{838, 59, 59.1}, "838:59:59.000000"}, - {[]interface{}{-838, 59, 59.1}, "-838:59:59.000000"}, - {[]interface{}{1000, 1, 1}, "838:59:59"}, - {[]interface{}{-1000, 1, 1.23}, "-838:59:59.000000"}, - {[]interface{}{1000, 59.1, 1}, "838:59:59"}, - {[]interface{}{1000, 59.5, 1}, nil}, - {[]interface{}{1000, 1, 59.1}, "838:59:59.000000"}, - {[]interface{}{1000, 1, 59.5}, "838:59:59.000000"}, - - {[]interface{}{12, 15, 60}, nil}, - {[]interface{}{12, 15, "60"}, nil}, - {[]interface{}{12, 60, 0}, nil}, - {[]interface{}{12, "60", 0}, nil}, - - {[]interface{}{12, 15, nil}, nil}, - {[]interface{}{12, nil, 0}, nil}, - {[]interface{}{nil, 15, 0}, nil}, - {[]interface{}{nil, nil, nil}, nil}, + {[]any{12, 15, 30}, "12:15:30"}, + {[]any{25, 15, 30}, "25:15:30"}, + {[]any{-25, 15, 30}, "-25:15:30"}, + {[]any{12, -15, 30}, nil}, + {[]any{12, 15, -30}, nil}, + + {[]any{12, 15, "30.10"}, "12:15:30.100000"}, + {[]any{12, 15, "30.20"}, "12:15:30.200000"}, + {[]any{12, 15, 30.3000001}, "12:15:30.300000"}, + {[]any{12, 15, 30.0000005}, "12:15:30.000001"}, + {[]any{"12", "15", 30.1}, "12:15:30.100000"}, + + {[]any{0, 58.4, 0}, "00:58:00"}, + {[]any{0, "58.4", 0}, "00:58:00"}, + {[]any{0, 58.5, 1}, "00:59:01"}, + {[]any{0, "58.5", 1}, "00:58:01"}, + {[]any{0, 59.5, 1}, nil}, + {[]any{0, "59.5", 1}, "00:59:01"}, + {[]any{0, 1, 59.1}, "00:01:59.100000"}, + {[]any{0, 1, "59.1"}, "00:01:59.100000"}, + {[]any{0, 1, 59.5}, "00:01:59.500000"}, + {[]any{0, 1, "59.5"}, "00:01:59.500000"}, + {[]any{23.5, 1, 10}, "24:01:10"}, + {[]any{"23.5", 1, 10}, "23:01:10"}, + + {[]any{0, 0, 0}, "00:00:00"}, + + {[]any{837, 59, 59.1}, "837:59:59.100000"}, + {[]any{838, 59, 59.1}, "838:59:59.000000"}, + {[]any{-838, 59, 59.1}, "-838:59:59.000000"}, + {[]any{1000, 1, 1}, "838:59:59"}, + {[]any{-1000, 1, 1.23}, "-838:59:59.000000"}, + {[]any{1000, 59.1, 1}, "838:59:59"}, + {[]any{1000, 59.5, 1}, nil}, + {[]any{1000, 1, 59.1}, "838:59:59.000000"}, + {[]any{1000, 1, 59.5}, "838:59:59.000000"}, + + {[]any{12, 15, 60}, nil}, + {[]any{12, 15, "60"}, nil}, + {[]any{12, 60, 0}, nil}, + {[]any{12, "60", 0}, nil}, + + {[]any{12, 15, nil}, nil}, + {[]any{12, nil, 0}, nil}, + {[]any{nil, 15, 0}, nil}, + {[]any{nil, nil, nil}, nil}, } Dtbl := tblToDtbl(tbl) @@ -2168,11 +2168,11 @@ func (s *testEvaluatorSuite) TestMakeTime(c *C) { c.Assert(got.GetMysqlDuration().String(), Equals, "838:59:59") tbl = []struct { - Args []interface{} - Want interface{} + Args []any + Want any }{ - {[]interface{}{"", "", ""}, "00:00:00"}, - {[]interface{}{"h", "m", "s"}, "00:00:00"}, + {[]any{"", "", ""}, "00:00:00"}, + {[]any{"h", "m", "s"}, "00:00:00"}, } Dtbl = tblToDtbl(tbl) maketime = funcs[ast.MakeTime] @@ -2268,7 +2268,7 @@ func (s *testEvaluatorSuite) TestToSeconds(c *C) { sc := s.ctx.GetSessionVars().StmtCtx sc.IgnoreZeroInDate = true tests := []struct { - param interface{} + param any expect int64 }{ {950501, 62966505600}, @@ -2288,7 +2288,7 @@ func (s *testEvaluatorSuite) TestToSeconds(c *C) { c.Assert(d.GetInt64(), Equals, test.expect) } - testsNull := []interface{}{ + testsNull := []any{ "0000-00-00", "1992-13-00", "2007-10-07 23:59:61", @@ -2308,7 +2308,7 @@ func (s *testEvaluatorSuite) TestToDays(c *C) { sc := s.ctx.GetSessionVars().StmtCtx sc.IgnoreZeroInDate = true tests := []struct { - param interface{} + param any expect int64 }{ {950501, 728779}, @@ -2329,7 +2329,7 @@ func (s *testEvaluatorSuite) TestToDays(c *C) { c.Assert(d.GetInt64(), Equals, test.expect) } - testsNull := []interface{}{ + testsNull := []any{ "0000-00-00", "1992-13-00", "2007-10-07 23:59:61", @@ -2349,7 +2349,7 @@ func (s *testEvaluatorSuite) TestTimestampAdd(c *C) { tests := []struct { unit string interval int64 - date interface{} + date any expect string }{ {"MINUTE", 1, "2003-01-02", "2003-01-02 00:01:00"}, @@ -2416,7 +2416,7 @@ func (s *testEvaluatorSuite) TestTimeFormat(c *C) { tblDate := []struct { Input []string - Expect interface{} + Expect any }{ {[]string{"23:00:00", `%H %k %h %I %l`}, "23 23 11 11 11"}, @@ -2533,9 +2533,9 @@ func (s *testEvaluatorSuite) TestSecToTime(c *C) { func (s *testEvaluatorSuite) TestConvertTz(c *C) { tests := []struct { - t interface{} - fromTz interface{} - toTz interface{} + t any + fromTz any + toTz any Success bool expect string }{ @@ -2656,7 +2656,7 @@ func (s *testEvaluatorSuite) TestPeriodDiff(c *C) { func (s *testEvaluatorSuite) TestLastDay(c *C) { tests := []struct { - param interface{} + param any expect string }{ {"2003-02-05", "2003-02-28"}, @@ -2676,7 +2676,7 @@ func (s *testEvaluatorSuite) TestLastDay(c *C) { c.Assert(result, Equals, test.expect) } - testsNull := []interface{}{ + testsNull := []any{ "0000-00-00", "1992-13-00", "2007-10-07 23:59:61", @@ -2741,7 +2741,7 @@ func (s *testEvaluatorSuite) TestWithTimeZone(c *C) { func (s *testEvaluatorSuite) TestTidbParseTso(c *C) { s.ctx.GetSessionVars().TimeZone = time.UTC tests := []struct { - param interface{} + param any expect string }{ {404411537129996288, "2018-11-20 09:53:04.877000"}, @@ -2760,7 +2760,7 @@ func (s *testEvaluatorSuite) TestTidbParseTso(c *C) { c.Assert(result, Equals, test.expect) } - testsNull := []interface{}{ + testsNull := []any{ 0, -1, "-1"} diff --git a/expression/builtin_time_vec_generated_test.go b/expression/builtin_time_vec_generated_test.go index 9d35c8a84..140ecfa3f 100644 --- a/expression/builtin_time_vec_generated_test.go +++ b/expression/builtin_time_vec_generated_test.go @@ -29,7 +29,7 @@ type gener struct { defaultGener } -func (g gener) gen() interface{} { +func (g gener) gen() any { result := g.defaultGener.gen() if _, ok := result.(string); ok { dg := newDefaultGener(0, types.ETDuration) diff --git a/expression/builtin_time_vec_test.go b/expression/builtin_time_vec_test.go index 55a829c13..a0d3256eb 100644 --- a/expression/builtin_time_vec_test.go +++ b/expression/builtin_time_vec_test.go @@ -34,7 +34,7 @@ func newPeriodGener() *periodGener { return &periodGener{newDefaultRandGen()} } -func (g *periodGener) gen() interface{} { +func (g *periodGener) gen() any { return int64((g.randGen.Intn(2500)+1)*100 + g.randGen.Intn(12) + 1) } @@ -47,7 +47,7 @@ func newUnitStrGener() *unitStrGener { return &unitStrGener{newDefaultRandGen()} } -func (g *unitStrGener) gen() interface{} { +func (g *unitStrGener) gen() any { units := []string{ "MICROSECOND", "SECOND", @@ -75,7 +75,7 @@ func newDateTimeUnitStrGener() *dateTimeUnitStrGener { // tzStrGener is used to generate strings which are timezones type tzStrGener struct{} -func (g *tzStrGener) gen() interface{} { +func (g *tzStrGener) gen() any { tzs := []string{ "", "GMT", @@ -88,7 +88,7 @@ func (g *tzStrGener) gen() interface{} { return tzs[n] } -func (g *dateTimeUnitStrGener) gen() interface{} { +func (g *dateTimeUnitStrGener) gen() any { dateTimes := []string{ "DAY", "WEEK", diff --git a/expression/evaluator_test.go b/expression/evaluator_test.go index ccac5e729..31a468ae5 100644 --- a/expression/evaluator_test.go +++ b/expression/evaluator_test.go @@ -143,7 +143,7 @@ func (s *testEvaluatorSuiteBase) datumsToConstants(datums []types.Datum) []Expre return constants } -func (s *testEvaluatorSuiteBase) primitiveValsToConstants(args []interface{}) []Expression { +func (s *testEvaluatorSuiteBase) primitiveValsToConstants(args []any) []Expression { cons := s.datumsToConstants(types.MakeDatums(args...)) char, col := s.ctx.GetSessionVars().GetCharsetInfo() for i, arg := range args { @@ -220,9 +220,9 @@ func (s *testEvaluatorSuite) TestSleep(c *C) { func (s *testEvaluatorSuite) TestBinopComparison(c *C) { tbl := []struct { - lhs interface{} + lhs any op string - rhs interface{} + rhs any result int64 // 0 for false, 1 for true }{ // test EQ @@ -267,9 +267,9 @@ func (s *testEvaluatorSuite) TestBinopComparison(c *C) { // test nil nilTbl := []struct { - lhs interface{} + lhs any op string - rhs interface{} + rhs any }{ {nil, ast.EQ, nil}, {nil, ast.EQ, 1}, @@ -297,10 +297,10 @@ func (s *testEvaluatorSuite) TestBinopComparison(c *C) { func (s *testEvaluatorSuite) TestBinopLogic(c *C) { tbl := []struct { - lhs interface{} + lhs any op string - rhs interface{} - ret interface{} + rhs any + ret any }{ {nil, ast.LogicAnd, 1, nil}, {nil, ast.LogicAnd, 0, 0}, @@ -335,10 +335,10 @@ func (s *testEvaluatorSuite) TestBinopLogic(c *C) { func (s *testEvaluatorSuite) TestBinopBitop(c *C) { tbl := []struct { - lhs interface{} + lhs any op string - rhs interface{} - ret interface{} + rhs any + ret any }{ {1, ast.And, 1, 1}, {1, ast.Or, 1, 1}, @@ -371,10 +371,10 @@ func (s *testEvaluatorSuite) TestBinopBitop(c *C) { func (s *testEvaluatorSuite) TestBinopNumeric(c *C) { tbl := []struct { - lhs interface{} + lhs any op string - rhs interface{} - ret interface{} + rhs any + ret any }{ // plus {1, ast.Plus, 1, 2}, @@ -468,9 +468,9 @@ func (s *testEvaluatorSuite) TestBinopNumeric(c *C) { } testcases := []struct { - lhs interface{} + lhs any op string - rhs interface{} + rhs any }{ // div {1, ast.Div, float64(0)}, @@ -567,9 +567,9 @@ func (s *testEvaluatorSuite) TestExtract(c *C) { func (s *testEvaluatorSuite) TestUnaryOp(c *C) { tbl := []struct { - arg interface{} + arg any op string - result interface{} + result any }{ // test NOT. {1, ast.UnaryNot, int64(0)}, @@ -608,9 +608,9 @@ func (s *testEvaluatorSuite) TestUnaryOp(c *C) { } tbl = []struct { - arg interface{} + arg any op string - result interface{} + result any }{ {types.NewDecFromInt(1), ast.UnaryMinus, types.NewDecFromInt(-1)}, {types.ZeroDuration, ast.UnaryMinus, new(types.MyDecimal)}, diff --git a/expression/expression.go b/expression/expression.go index 578a6caf8..3ef6ae879 100644 --- a/expression/expression.go +++ b/expression/expression.go @@ -199,8 +199,9 @@ func IsEQCondFromIn(expr Expression) bool { // HandleOverflowOnSelection handles Overflow errors when evaluating selection filters. // We should ignore overflow errors when evaluating selection conditions: -// INSERT INTO t VALUES ("999999999999999999"); -// SELECT * FROM t WHERE v; +// +// INSERT INTO t VALUES ("999999999999999999"); +// SELECT * FROM t WHERE v; func HandleOverflowOnSelection(sc *stmtctx.StatementContext, val int64, err error) (int64, error) { if sc.InSelectStmt && err != nil && types.ErrOverflow.Equal(err) { return -1, nil @@ -253,12 +254,12 @@ func EvalBool(ctx sessionctx.Context, exprList CNFExprs, row chunk.Row) (bool, b var ( defaultChunkSize = 1024 selPool = sync.Pool{ - New: func() interface{} { + New: func() any { return make([]int, defaultChunkSize) }, } zeroPool = sync.Pool{ - New: func() interface{} { + New: func() any { return make([]int8, defaultChunkSize) }, } diff --git a/expression/generator/compare_vec.go b/expression/generator/compare_vec.go index 0f22af2f3..6d49c5c1c 100644 --- a/expression/generator/compare_vec.go +++ b/expression/generator/compare_vec.go @@ -11,6 +11,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +//go:build ignore // +build ignore package main @@ -327,7 +328,7 @@ func generateDotGo(fileName string, compares []CompareContext, types []TypeConte w.WriteString(newLine) w.WriteString(builtinCompareImports) - var ctx = make(map[string]interface{}) + var ctx = make(map[string]any) for _, compareCtx := range compares { for _, typeCtx := range types { ctx["compare"] = compareCtx diff --git a/expression/generator/control_vec.go b/expression/generator/control_vec.go index 733c73603..63dd53882 100644 --- a/expression/generator/control_vec.go +++ b/expression/generator/control_vec.go @@ -11,6 +11,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +//go:build ignore // +build ignore package main diff --git a/expression/generator/other_vec.go b/expression/generator/other_vec.go index 6c510b591..816fb09b2 100644 --- a/expression/generator/other_vec.go +++ b/expression/generator/other_vec.go @@ -11,6 +11,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +//go:build ignore // +build ignore package main diff --git a/expression/generator/time_vec.go b/expression/generator/time_vec.go index 7587a3a21..6af95fee2 100644 --- a/expression/generator/time_vec.go +++ b/expression/generator/time_vec.go @@ -11,6 +11,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +//go:build ignore // +build ignore package main diff --git a/expression/helper.go b/expression/helper.go index e3c5b3a17..50abf6c2a 100644 --- a/expression/helper.go +++ b/expression/helper.go @@ -55,7 +55,7 @@ func IsValidCurrentTimestampExpr(exprNode ast.ExprNode, fieldType *types.FieldTy } // GetTimeValue gets the time value with type tp. -func GetTimeValue(ctx sessionctx.Context, v interface{}, tp byte, fsp int8) (d types.Datum, err error) { +func GetTimeValue(ctx sessionctx.Context, v any, tp byte, fsp int8) (d types.Datum, err error) { value := types.NewTime(types.ZeroCoreTime, tp, fsp) sc := ctx.GetSessionVars().StmtCtx diff --git a/expression/helper_test.go b/expression/helper_test.go index 369333e37..4e2f6081f 100644 --- a/expression/helper_test.go +++ b/expression/helper_test.go @@ -64,8 +64,8 @@ func (s *testExpressionSuite) TestGetTimeValue(c *C) { variable.SetSessionSystemVar(sessionVars, "timestamp", types.NewStringDatum("1234")) tbl := []struct { - Expr interface{} - Ret interface{} + Expr any + Ret any }{ {"2012-12-12 00:00:00", "2012-12-12 00:00:00"}, {ast.CurrentTimestamp, time.Unix(1234, 0).Format(types.TimeFormat)}, @@ -91,7 +91,7 @@ func (s *testExpressionSuite) TestGetTimeValue(c *C) { } errTbl := []struct { - Expr interface{} + Expr any }{ {"2012-13-12 00:00:00"}, {ast.NewValueExpr("2012-13-12 00:00:00", charset.CharsetUTF8MB4, charset.CollationUTF8MB4)}, diff --git a/expression/scalar_function.go b/expression/scalar_function.go index cda801c63..7b0fc9a6b 100755 --- a/expression/scalar_function.go +++ b/expression/scalar_function.go @@ -307,7 +307,7 @@ func (sf *ScalarFunction) Decorrelate(schema *Schema) Expression { // Eval implements Expression interface. func (sf *ScalarFunction) Eval(row chunk.Row) (d types.Datum, err error) { var ( - res interface{} + res any isNull bool ) switch tp, evalType := sf.GetType(), sf.GetType().EvalType(); evalType { diff --git a/expression/util_test.go b/expression/util_test.go index fe0c4c96c..33d348c4b 100644 --- a/expression/util_test.go +++ b/expression/util_test.go @@ -461,7 +461,7 @@ func BenchmarkExprFromSchema(b *testing.B) { type MockExpr struct { err error t *types.FieldType - i interface{} + i any } func (m *MockExpr) VecEvalInt(ctx sessionctx.Context, input *chunk.Chunk, result *chunk.Column) error { diff --git a/infoschema/tables.go b/infoschema/tables.go index 2419feb8a..144378f2b 100644 --- a/infoschema/tables.go +++ b/infoschema/tables.go @@ -218,7 +218,7 @@ type columnInfo struct { size int decimal int flag uint - deflt interface{} + deflt any comment string } @@ -1105,13 +1105,14 @@ var tableStatementsSummaryCols = []columnInfo{ // GetShardingInfo returns a nil or description string for the sharding information of given TableInfo. // The returned description string may be: -// - "NOT_SHARDED": for tables that SHARD_ROW_ID_BITS is not specified. -// - "NOT_SHARDED(PK_IS_HANDLE)": for tables of which primary key is row id. -// - "PK_AUTO_RANDOM_BITS={bit_number}": for tables of which primary key is sharded row id. -// - "SHARD_BITS={bit_number}": for tables that with SHARD_ROW_ID_BITS. +// - "NOT_SHARDED": for tables that SHARD_ROW_ID_BITS is not specified. +// - "NOT_SHARDED(PK_IS_HANDLE)": for tables of which primary key is row id. +// - "PK_AUTO_RANDOM_BITS={bit_number}": for tables of which primary key is sharded row id. +// - "SHARD_BITS={bit_number}": for tables that with SHARD_ROW_ID_BITS. +// // The returned nil indicates that sharding information is not suitable for the table(for example, when the table is a View). // This function is exported for unit test. -func GetShardingInfo(dbInfo *model.DBInfo, tableInfo *model.TableInfo) interface{} { +func GetShardingInfo(dbInfo *model.DBInfo, tableInfo *model.TableInfo) any { if dbInfo == nil || tableInfo == nil || tableInfo.IsView() || util.IsMemOrSysDB(dbInfo.Name.L) { return nil } diff --git a/infoschema/tables_test.go b/infoschema/tables_test.go index 38b7671ba..61b039f7f 100644 --- a/infoschema/tables_test.go +++ b/infoschema/tables_test.go @@ -145,7 +145,7 @@ func (s *testClusterTableSuite) setUpMockPDHTTPServer() (*httptest.Server, strin })) // mock PD API router.Handle(pdapi.ClusterVersion, fn.Wrap(func() (string, error) { return "4.0.0-alpha", nil })) - router.Handle(pdapi.Status, fn.Wrap(func() (interface{}, error) { + router.Handle(pdapi.Status, fn.Wrap(func() (any, error) { return struct { GitHash string `json:"git_hash"` StartTimestamp int64 `json:"start_timestamp"` @@ -154,14 +154,14 @@ func (s *testClusterTableSuite) setUpMockPDHTTPServer() (*httptest.Server, strin StartTimestamp: s.startTime.Unix(), }, nil })) - var mockConfig = func() (map[string]interface{}, error) { - configuration := map[string]interface{}{ + var mockConfig = func() (map[string]any, error) { + configuration := map[string]any{ "key1": "value1", "key2": map[string]string{ "nest1": "n-value1", "nest2": "n-value2", }, - "key3": map[string]interface{}{ + "key3": map[string]any{ "nest1": "n-value1", "nest2": "n-value2", "key4": map[string]string{ @@ -540,7 +540,7 @@ func (s *testTableSuite) TestTableRowIDShardingInfo(c *C) { tk.MustExec("DROP DATABASE IF EXISTS `sharding_info_test_db`") tk.MustExec("CREATE DATABASE `sharding_info_test_db`") - assertShardingInfo := func(tableName string, expectInfo interface{}) { + assertShardingInfo := func(tableName string, expectInfo any) { querySQL := fmt.Sprintf("select tidb_row_id_sharding_info from information_schema.tables where table_schema = 'sharding_info_test_db' and table_name = '%s'", tableName) info := tk.MustQuery(querySQL).Rows()[0][0] if expectInfo == nil { @@ -561,7 +561,7 @@ func (s *testTableSuite) TestTableRowIDShardingInfo(c *C) { tk.MustExec("CREATE VIEW `sharding_info_test_db`.`tv` AS select 1") assertShardingInfo("tv", nil) - testFunc := func(dbName string, expectInfo interface{}) { + testFunc := func(dbName string, expectInfo any) { dbInfo := model.DBInfo{Name: model.NewCIStr(dbName)} tableInfo := model.TableInfo{} diff --git a/kv/interface_mock_test.go b/kv/interface_mock_test.go index 9e5c12fe0..db318a246 100644 --- a/kv/interface_mock_test.go +++ b/kv/interface_mock_test.go @@ -21,7 +21,7 @@ import ( // mockTxn is a txn that returns a retryAble error when called Commit. type mockTxn struct { - opts map[Option]interface{} + opts map[Option]any valid bool } @@ -43,7 +43,7 @@ func (t *mockTxn) LockKeys(_ context.Context, _ *LockCtx, _ ...Key) error { return nil } -func (t *mockTxn) SetOption(opt Option, val interface{}) { +func (t *mockTxn) SetOption(opt Option, val any) { t.opts[opt] = val } @@ -51,7 +51,7 @@ func (t *mockTxn) DelOption(opt Option) { delete(t.opts, opt) } -func (t *mockTxn) GetOption(opt Option) interface{} { +func (t *mockTxn) GetOption(opt Option) any { return t.opts[opt] } @@ -128,7 +128,7 @@ func (t *mockTxn) SetVars(vars *Variables) { // newMockTxn new a mockTxn. func newMockTxn() Transaction { return &mockTxn{ - opts: make(map[Option]interface{}), + opts: make(map[Option]any), valid: true, } } @@ -189,7 +189,7 @@ func (s *mockStorage) Describe() string { return "KVMockStorage is a mock Store implementation, only for unittests in KV package" } -func (s *mockStorage) ShowStatus(ctx context.Context, key string) (interface{}, error) { +func (s *mockStorage) ShowStatus(ctx context.Context, key string) (any, error) { return nil, nil } @@ -233,5 +233,5 @@ func (s *mockSnapshot) IterReverse(k Key) (Iterator, error) { return s.store.IterReverse(k) } -func (s *mockSnapshot) SetOption(opt Option, val interface{}) {} -func (s *mockSnapshot) DelOption(opt Option) {} +func (s *mockSnapshot) SetOption(opt Option, val any) {} +func (s *mockSnapshot) DelOption(opt Option) {} diff --git a/kv/key.go b/kv/key.go index 386059a24..6623cd4e8 100644 --- a/kv/key.go +++ b/kv/key.go @@ -38,10 +38,10 @@ func (k Key) Next() Key { // // Assume there are keys like: // -// rowkey1 -// rowkey1_column1 -// rowkey1_column2 -// rowKey2 +// rowkey1 +// rowkey1_column1 +// rowkey1_column2 +// rowKey2 // // If we seek 'rowkey1' Next, we will get 'rowkey1_column1'. // If we seek 'rowkey1' PrefixNext, we will get 'rowkey2'. @@ -312,26 +312,26 @@ func (ch *CommonHandle) String() string { // HandleMap is the map for Handle. type HandleMap struct { - ints map[int64]interface{} + ints map[int64]any strs map[string]strHandleVal } type strHandleVal struct { h Handle - val interface{} + val any } // NewHandleMap creates a new map for handle. func NewHandleMap() *HandleMap { // Initialize the two maps to avoid checking nil. return &HandleMap{ - ints: map[int64]interface{}{}, + ints: map[int64]any{}, strs: map[string]strHandleVal{}, } } // Get gets a value by a Handle. -func (m *HandleMap) Get(h Handle) (v interface{}, ok bool) { +func (m *HandleMap) Get(h Handle) (v any, ok bool) { if h.IsInt() { v, ok = m.ints[h.IntValue()] } else { @@ -343,7 +343,7 @@ func (m *HandleMap) Get(h Handle) (v interface{}, ok bool) { } // Set sets a value with a Handle. -func (m *HandleMap) Set(h Handle, val interface{}) { +func (m *HandleMap) Set(h Handle, val any) { if h.IsInt() { m.ints[h.IntValue()] = val } else { @@ -369,7 +369,7 @@ func (m *HandleMap) Len() int { } // Range iterates the HandleMap with fn, the fn returns true to continue, returns false to stop. -func (m *HandleMap) Range(fn func(h Handle, val interface{}) bool) { +func (m *HandleMap) Range(fn func(h Handle, val any) bool) { for h, val := range m.ints { if !fn(IntHandle(h), val) { return diff --git a/kv/key_test.go b/kv/key_test.go index 515bf0dc4..f7ac34819 100644 --- a/kv/key_test.go +++ b/kv/key_test.go @@ -167,7 +167,7 @@ func (s *testKeySuite) TestHandleMap(c *C) { m.Set(ch3, "c") c.Assert(m.Len(), Equals, 3) cnt := 0 - m.Range(func(h Handle, val interface{}) bool { + m.Range(func(h Handle, val any) bool { cnt++ if h.Equal(ch) { c.Assert(val, Equals, "a") @@ -184,7 +184,7 @@ func (s *testKeySuite) TestHandleMap(c *C) { c.Assert(cnt, Equals, 2) } -func mustNewCommonHandle(c *C, values ...interface{}) *CommonHandle { +func mustNewCommonHandle(c *C, values ...any) *CommonHandle { encoded, err := codec.EncodeKey(new(stmtctx.StatementContext), nil, types.MakeDatums(values...)...) c.Assert(err, IsNil) ch, err := NewCommonHandle(encoded) diff --git a/kv/kv.go b/kv/kv.go index 1bbc1653a..41c1ab42e 100644 --- a/kv/kv.go +++ b/kv/kv.go @@ -184,7 +184,7 @@ type Transaction interface { LockKeys(ctx context.Context, lockCtx *LockCtx, keys ...Key) error // SetOption sets an option with a value, when val is nil, uses the default // value of this option. - SetOption(opt Option, val interface{}) + SetOption(opt Option, val any) // DelOption deletes an option. DelOption(opt Option) // IsReadOnly checks if the transaction has only performed read operations. @@ -352,7 +352,7 @@ type Snapshot interface { BatchGet(ctx context.Context, keys []Key) (map[string][]byte, error) // SetOption sets an option with a value, when val is nil, uses the default // value of this option. Only ReplicaRead is supported for snapshot - SetOption(opt Option, val interface{}) + SetOption(opt Option, val any) // DelOption deletes an option. DelOption(opt Option) } @@ -397,7 +397,7 @@ type Storage interface { // Describe returns of brief introduction of the storage Describe() string // ShowStatus returns the specified status of the storage - ShowStatus(ctx context.Context, key string) (interface{}, error) + ShowStatus(ctx context.Context, key string) (any, error) } // FnKeyCmp is the function for iterator the keys diff --git a/kv/union_store.go b/kv/union_store.go index 6b96bc5d7..88e9b0ca4 100644 --- a/kv/union_store.go +++ b/kv/union_store.go @@ -29,11 +29,11 @@ type UnionStore interface { WalkBuffer(f func(k Key, v []byte) error) error // SetOption sets an option with a value, when val is nil, uses the default // value of this option. - SetOption(opt Option, val interface{}) + SetOption(opt Option, val any) // DelOption deletes an option. DelOption(opt Option) // GetOption gets an option. - GetOption(opt Option) interface{} + GetOption(opt Option) any // GetMemBuffer return the MemBuffer binding to this UnionStore. GetMemBuffer() MemBuffer } @@ -54,7 +54,7 @@ type Option int // Options is an interface of a set of options. Each option is associated with a value. type Options interface { // Get gets an option value. - Get(opt Option) (v interface{}, ok bool) + Get(opt Option) (v any, ok bool) } type existErrInfo struct { @@ -95,7 +95,7 @@ func NewUnionStore(snapshot Snapshot) UnionStore { return &unionStore{ BufferStore: NewBufferStore(snapshot), keyExistErrs: make(map[string]*existErrInfo), - opts: make(map[Option]interface{}), + opts: make(map[Option]any), } } @@ -133,7 +133,7 @@ func (us *unionStore) DeleteKeyExistErrInfo(k Key) { } // SetOption implements the UnionStore SetOption interface. -func (us *unionStore) SetOption(opt Option, val interface{}) { +func (us *unionStore) SetOption(opt Option, val any) { us.opts[opt] = val } @@ -143,7 +143,7 @@ func (us *unionStore) DelOption(opt Option) { } // GetOption implements the UnionStore GetOption interface. -func (us *unionStore) GetOption(opt Option) interface{} { +func (us *unionStore) GetOption(opt Option) any { return us.opts[opt] } @@ -164,9 +164,9 @@ func (us *unionStore) Discard() { us.BufferStore.Discard() } -type options map[Option]interface{} +type options map[Option]any -func (opts options) Get(opt Option) (interface{}, bool) { +func (opts options) Get(opt Option) (any, bool) { v, ok := opts[opt] return v, ok } diff --git a/planner/core/cache.go b/planner/core/cache.go index c793a6356..988c0ac51 100644 --- a/planner/core/cache.go +++ b/planner/core/cache.go @@ -148,8 +148,8 @@ func NewPSTMTPlanCacheValue(plan Plan, names []*types.FieldName, srcMap map[*mod type CachedPrepareStmt struct { PreparedAst *ast.Prepared VisitInfos []visitInfo - ColumnInfos interface{} - Executor interface{} + ColumnInfos any + Executor any NormalizedSQL string NormalizedPlan string SQLDigest string diff --git a/planner/core/encode.go b/planner/core/encode.go index ca8ee7bca..83c634b15 100644 --- a/planner/core/encode.go +++ b/planner/core/encode.go @@ -25,7 +25,7 @@ import ( ) var encoderPool = sync.Pool{ - New: func() interface{} { + New: func() any { return &planEncoder{} }, } @@ -86,7 +86,7 @@ func (pn *planEncoder) encodePlan(p PhysicalPlan, isRoot bool, depth int) { } var digesterPool = sync.Pool{ - New: func() interface{} { + New: func() any { return &planDigester{ hasher: sha256.New(), } diff --git a/planner/core/logical_plan_builder.go b/planner/core/logical_plan_builder.go index c0c4aafa6..5ab276485 100644 --- a/planner/core/logical_plan_builder.go +++ b/planner/core/logical_plan_builder.go @@ -605,10 +605,10 @@ func (b *PlanBuilder) buildJoin(ctx context.Context, joinNode *ast.Join) (Logica // on the "USING" clause. // // According to the standard SQL, columns are ordered in the following way: -// 1. coalesced common columns of "leftPlan" and "rightPlan", in the order they -// appears in "leftPlan". -// 2. the rest columns in "leftPlan", in the order they appears in "leftPlan". -// 3. the rest columns in "rightPlan", in the order they appears in "rightPlan". +// 1. coalesced common columns of "leftPlan" and "rightPlan", in the order they +// appears in "leftPlan". +// 2. the rest columns in "leftPlan", in the order they appears in "leftPlan". +// 3. the rest columns in "rightPlan", in the order they appears in "rightPlan". func (b *PlanBuilder) buildUsingClause(p *LogicalJoin, leftPlan, rightPlan LogicalPlan, join *ast.Join) error { filter := make(map[string]bool, len(join.Using)) for _, col := range join.Using { @@ -620,9 +620,10 @@ func (b *PlanBuilder) buildUsingClause(p *LogicalJoin, leftPlan, rightPlan Logic // buildNaturalJoin builds natural join output schema. It finds out all the common columns // then using the same mechanism as buildUsingClause to eliminate redundant columns and build join conditions. // According to standard SQL, producing this display order: -// All the common columns -// Every column in the first (left) table that is not a common column -// Every column in the second (right) table that is not a common column +// +// All the common columns +// Every column in the first (left) table that is not a common column +// Every column in the second (right) table that is not a common column func (b *PlanBuilder) buildNaturalJoin(p *LogicalJoin, leftPlan, rightPlan LogicalPlan, join *ast.Join) error { return b.coalesceCommonColumns(p, leftPlan, rightPlan, join.Tp, nil) } @@ -1234,7 +1235,7 @@ func (b *PlanBuilder) buildSort(ctx context.Context, p LogicalPlan, byItems []*a // For ordinary statement, node should be uint64 constant value. // For prepared statement, node is string. We should convert it to uint64. func getUintFromNode(ctx sessionctx.Context, n ast.Node) (uVal uint64, isNull bool, isExpectedType bool) { - var val interface{} + var val any switch v := n.(type) { case *driver.ValueExpr: val = v.GetValue() diff --git a/planner/core/preprocess.go b/planner/core/preprocess.go index 8d9f7e8a2..91f442086 100644 --- a/planner/core/preprocess.go +++ b/planner/core/preprocess.go @@ -49,7 +49,7 @@ func InTxnRetry(p *preprocessor) { // Preprocess resolves table names of the node, and checks some statements validation. func Preprocess(ctx sessionctx.Context, node ast.Node, is infoschema.InfoSchema, preprocessOpt ...PreprocessOpt) error { - v := preprocessor{is: is, ctx: ctx, tableAliasInJoin: make([]map[string]interface{}, 0)} + v := preprocessor{is: is, ctx: ctx, tableAliasInJoin: make([]map[string]any, 0)} for _, optFn := range preprocessOpt { optFn(&v) } @@ -85,7 +85,7 @@ type preprocessor struct { // tableAliasInJoin is a stack that keeps the table alias names for joins. // len(tableAliasInJoin) may bigger than 1 because the left/right child of join may be subquery that contains `JOIN` - tableAliasInJoin []map[string]interface{} + tableAliasInJoin []map[string]any } func (p *preprocessor) Enter(in ast.Node) (out ast.Node, skipChildren bool) { @@ -523,7 +523,7 @@ func (p *preprocessor) checkDropTableNames(tables []*ast.TableName) { func (p *preprocessor) checkNonUniqTableAlias(stmt *ast.Join) { if p.flag&parentIsJoin == 0 { - p.tableAliasInJoin = append(p.tableAliasInJoin, make(map[string]interface{})) + p.tableAliasInJoin = append(p.tableAliasInJoin, make(map[string]any)) } tableAliases := p.tableAliasInJoin[len(p.tableAliasInJoin)-1] if err := isTableAliasDuplicate(stmt.Left, tableAliases); err != nil { @@ -537,7 +537,7 @@ func (p *preprocessor) checkNonUniqTableAlias(stmt *ast.Join) { p.flag |= parentIsJoin } -func isTableAliasDuplicate(node ast.ResultSetNode, tableAliases map[string]interface{}) error { +func isTableAliasDuplicate(node ast.ResultSetNode, tableAliases map[string]any) error { if ts, ok := node.(*ast.TableSource); ok { tabName := ts.AsName if tabName.L == "" { diff --git a/planner/core/util.go b/planner/core/util.go index dcfc7c56b..e39617ba2 100644 --- a/planner/core/util.go +++ b/planner/core/util.go @@ -216,7 +216,7 @@ func BuildPhysicalJoinSchema(joinType JoinType, join PhysicalPlan) *expression.S } // GetStatsInfo gets the statistics info from a physical plan tree. -func GetStatsInfo(i interface{}) map[string]uint64 { +func GetStatsInfo(i any) map[string]uint64 { p := i.(Plan) var physicalPlan PhysicalPlan switch x := p.(type) { diff --git a/planner/memo/group_expr.go b/planner/memo/group_expr.go index cdb681d84..90bc116d4 100644 --- a/planner/memo/group_expr.go +++ b/planner/memo/group_expr.go @@ -79,13 +79,13 @@ func (e *GroupExpr) Schema() *expression.Schema { } // AddAppliedRule adds a rule into the appliedRuleSet. -func (e *GroupExpr) AddAppliedRule(rule interface{}) { +func (e *GroupExpr) AddAppliedRule(rule any) { ruleID := reflect.ValueOf(rule).Pointer() e.appliedRuleSet[uint64(ruleID)] = struct{}{} } // HasAppliedRule returns if the rule has been applied. -func (e *GroupExpr) HasAppliedRule(rule interface{}) bool { +func (e *GroupExpr) HasAppliedRule(rule any) bool { ruleID := reflect.ValueOf(rule).Pointer() _, ok := e.appliedRuleSet[uint64(ruleID)] return ok diff --git a/plugin/spi.go b/plugin/spi.go index 1efab55ac..82b5572e8 100644 --- a/plugin/spi.go +++ b/plugin/spi.go @@ -59,7 +59,7 @@ type Manifest struct { // ExportManifest exports a manifest to TiDB as a known format. // it just casts sub-manifest to manifest. -func ExportManifest(m interface{}) *Manifest { +func ExportManifest(m any) *Manifest { v := reflect.ValueOf(m) return (*Manifest)(unsafe.Pointer(v.Pointer())) } diff --git a/server/conn_stmt.go b/server/conn_stmt.go index e1aea7868..9222a5250 100644 --- a/server/conn_stmt.go +++ b/server/conn_stmt.go @@ -265,7 +265,7 @@ func parseStmtFetchCmd(data []byte) (uint32, uint32, error) { func parseExecArgs(sc *stmtctx.StatementContext, args []types.Datum, boundParams [][]byte, nullBitmap, paramTypes, paramValues []byte) (err error) { pos := 0 var ( - tmp interface{} + tmp any v []byte n int isNull bool diff --git a/server/conn_stmt_test.go b/server/conn_stmt_test.go index 038e05cb3..e8678d39f 100644 --- a/server/conn_stmt_test.go +++ b/server/conn_stmt_test.go @@ -32,7 +32,7 @@ func (ts *ConnTestSuite) TestParseExecArgs(c *C) { tests := []struct { args args err error - expect interface{} + expect any }{ // Tests for int overflow { diff --git a/server/driver.go b/server/driver.go index 389f9f270..4690ee53c 100644 --- a/server/driver.go +++ b/server/driver.go @@ -48,10 +48,10 @@ type QueryCtx interface { AffectedRows() uint64 // Value returns the value associated with this context for key. - Value(key fmt.Stringer) interface{} + Value(key fmt.Stringer) any // SetValue saves a value associated with this context for key. - SetValue(key fmt.Stringer, value interface{}) + SetValue(key fmt.Stringer, value any) SetProcessInfo(sql string, t time.Time, command byte, maxExecutionTime uint64) diff --git a/server/driver_tidb.go b/server/driver_tidb.go index 985721776..bce24e303 100644 --- a/server/driver_tidb.go +++ b/server/driver_tidb.go @@ -199,12 +199,12 @@ func (tc *TiDBContext) LastInsertID() uint64 { } // Value implements QueryCtx Value method. -func (tc *TiDBContext) Value(key fmt.Stringer) interface{} { +func (tc *TiDBContext) Value(key fmt.Stringer) any { return tc.session.Value(key) } // SetValue implements QueryCtx SetValue method. -func (tc *TiDBContext) SetValue(key fmt.Stringer, value interface{}) { +func (tc *TiDBContext) SetValue(key fmt.Stringer, value any) { tc.session.SetValue(key, value) } diff --git a/server/http_handler.go b/server/http_handler.go index b85e09702..8dae3bad7 100644 --- a/server/http_handler.go +++ b/server/http_handler.go @@ -100,7 +100,7 @@ func writeError(w http.ResponseWriter, err error) { terror.Log(errors.Trace(err)) } -func writeData(w http.ResponseWriter, data interface{}) { +func writeData(w http.ResponseWriter, data any) { js, err := json.MarshalIndent(data, "", " ") if err != nil { writeError(w, err) @@ -1350,7 +1350,7 @@ func (h regionHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { writeError(w, err) return } - writeData(w, map[string]interface{}{ + writeData(w, map[string]any{ "write": hotWrite, "read": hotRead, }) @@ -1451,7 +1451,7 @@ func parseQuery(query string, m url.Values, shouldUnescape bool) error { // ServeHTTP handles request of list a table's regions. func (h mvccTxnHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { - var data interface{} + var data any params := mux.Vars(req) var err error switch h.op { @@ -1497,7 +1497,7 @@ func extractTableAndPartitionName(str string) (string, string) { } // handleMvccGetByIdx gets MVCC info by an index key. -func (h mvccTxnHandler) handleMvccGetByIdx(params map[string]string, values url.Values) (interface{}, error) { +func (h mvccTxnHandler) handleMvccGetByIdx(params map[string]string, values url.Values) (any, error) { dbName := params[pDBName] tableName := params[pTableName] handleStr := params[pHandle] @@ -1524,7 +1524,7 @@ func (h mvccTxnHandler) handleMvccGetByIdx(params map[string]string, values url. return h.getMvccByIdxValue(idx, values, idxCols, handleStr) } -func (h mvccTxnHandler) handleMvccGetByKey(params map[string]string, decodeData bool) (interface{}, error) { +func (h mvccTxnHandler) handleMvccGetByKey(params map[string]string, decodeData bool) (any, error) { handle, err := strconv.ParseInt(params[pHandle], 0, 64) if err != nil { return nil, errors.Trace(err) @@ -1547,7 +1547,7 @@ func (h mvccTxnHandler) handleMvccGetByKey(params map[string]string, decodeData } respValue := resp.Value - var result interface{} = resp + var result any = resp if respValue.Info != nil { datas := make(map[string][]map[string]string) for _, w := range respValue.Info.Writes { @@ -1563,7 +1563,7 @@ func (h mvccTxnHandler) handleMvccGetByKey(params map[string]string, decodeData } if len(datas) > 0 { - re := map[string]interface{}{ + re := map[string]any{ "key": resp.Key, "info": respValue.Info, "data": datas, @@ -1593,7 +1593,7 @@ func (h mvccTxnHandler) decodeMvccData(bs []byte, colMap map[int64]*types.FieldT return record, err } -func (h *mvccTxnHandler) handleMvccGetByTxn(params map[string]string) (interface{}, error) { +func (h *mvccTxnHandler) handleMvccGetByTxn(params map[string]string) (any, error) { startTS, err := strconv.ParseInt(params[pStartTS], 0, 64) if err != nil { return nil, errors.Trace(err) @@ -1694,7 +1694,7 @@ type dbTableInfo struct { SchemaVersion int64 `json:"schema_version"` } -//ServeHTTP handles request of database information and table information by tableID. +// ServeHTTP handles request of database information and table information by tableID. func (h dbTableHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { params := mux.Vars(req) tableID := params[pTableID] diff --git a/server/http_handler_test.go b/server/http_handler_test.go index 74f383135..ceb63a104 100644 --- a/server/http_handler_test.go +++ b/server/http_handler_test.go @@ -469,7 +469,7 @@ func (ts *HTTPHandlerTestSuite) TestGetTableMVCC(c *C) { resp, err = ts.fetchStatus(fmt.Sprintf("/mvcc/key/tidb/test/1?decode=true")) c.Assert(err, IsNil) decoder = json.NewDecoder(resp.Body) - var data3 map[string]interface{} + var data3 map[string]any err = decoder.Decode(&data3) c.Assert(err, IsNil) c.Assert(data3["key"], NotNil) @@ -481,7 +481,7 @@ func (ts *HTTPHandlerTestSuite) TestGetTableMVCC(c *C) { c.Assert(err, IsNil) defer resp.Body.Close() decoder = json.NewDecoder(resp.Body) - var data4 map[string]interface{} + var data4 map[string]any err = decoder.Decode(&data4) c.Assert(err, IsNil) c.Assert(data4["key"], NotNil) @@ -711,7 +711,7 @@ func (ts *HTTPHandlerTestSuite) TestDecodeColumnValue(c *C) { resp, err := ts.fetchStatus(path) c.Assert(err, IsNil, Commentf("url:%s", ts.statusURL(path))) decoder := json.NewDecoder(resp.Body) - var data interface{} + var data any err = decoder.Decode(&data) c.Assert(err, IsNil, Commentf("url:%v\ndata%v", ts.statusURL(path), data)) colVal, err := types.DatumsToString([]types.Datum{row[col.id-1]}, false) diff --git a/server/server_test.go b/server/server_test.go index cca091c0f..d95cd0d15 100644 --- a/server/server_test.go +++ b/server/server_test.go @@ -184,31 +184,31 @@ func (dbt *DBTest) mustPrepare(query string) *sql.Stmt { return stmt } -func (dbt *DBTest) mustExecPrepared(stmt *sql.Stmt, args ...interface{}) sql.Result { +func (dbt *DBTest) mustExecPrepared(stmt *sql.Stmt, args ...any) sql.Result { res, err := stmt.Exec(args...) dbt.Assert(err, IsNil, Commentf("Execute prepared with args: %s", args)) return res } -func (dbt *DBTest) mustQueryPrepared(stmt *sql.Stmt, args ...interface{}) *sql.Rows { +func (dbt *DBTest) mustQueryPrepared(stmt *sql.Stmt, args ...any) *sql.Rows { rows, err := stmt.Query(args...) dbt.Assert(err, IsNil, Commentf("Query prepared with args: %s", args)) return rows } -func (dbt *DBTest) mustExec(query string, args ...interface{}) (res sql.Result) { +func (dbt *DBTest) mustExec(query string, args ...any) (res sql.Result) { res, err := dbt.db.Exec(query, args...) dbt.Assert(err, IsNil, Commentf("Exec %s", query)) return res } -func (dbt *DBTest) mustQuery(query string, args ...interface{}) (rows *sql.Rows) { +func (dbt *DBTest) mustQuery(query string, args ...any) (rows *sql.Rows) { rows, err := dbt.db.Query(query, args...) dbt.Assert(err, IsNil, Commentf("Query %s", query)) return rows } -func (dbt *DBTest) mustQueryRows(query string, args ...interface{}) { +func (dbt *DBTest) mustQueryRows(query string, args ...any) { rows := dbt.mustQuery(query, args...) dbt.Assert(rows.Next(), IsTrue) rows.Close() @@ -425,11 +425,11 @@ func (cli *testServerClient) runTestLoadDataWithSelectIntoOutfile(c *C, server * dbt.mustExec("create table t1 (i int, r real, d decimal(10, 5), s varchar(100), dt datetime, ts timestamp, j json)") dbt.mustExec(fmt.Sprintf("load data local infile %q into table t1", outfile)) - fetchResults := func(table string) [][]interface{} { - var res [][]interface{} + fetchResults := func(table string) [][]any { + var res [][]any row := dbt.mustQuery("select * from " + table + " order by i") for row.Next() { - r := make([]interface{}, 7) + r := make([]any, 7) c.Assert(row.Scan(&r[0], &r[1], &r[2], &r[3], &r[4], &r[5], &r[6]), IsNil) res = append(res, r) } diff --git a/server/statistics_handler_test.go b/server/statistics_handler_test.go index ecaa2f70b..86cae58db 100644 --- a/server/statistics_handler_test.go +++ b/server/statistics_handler_test.go @@ -228,7 +228,7 @@ func (ds *testDumpStatsSuite) checkData(c *C, path string) { dbt.Check(rows.Next(), IsTrue, Commentf("unexpected data")) var dbName, tableName string var modifyCount, count int64 - var other interface{} + var other any err = rows.Scan(&dbName, &tableName, &other, &other, &modifyCount, &count) dbt.Check(err, IsNil) dbt.Check(dbName, Equals, "tidb") diff --git a/session/bootstrap_test.go b/session/bootstrap_test.go index f03e66300..c1307e1db 100644 --- a/session/bootstrap_test.go +++ b/session/bootstrap_test.go @@ -120,7 +120,7 @@ func (s *testBootstrapSuite) bootstrapWithOnlyDDLWork(store kv.Storage, c *C) { sessionVars: variable.NewSessionVars(), } ss.txn.init() - ss.mu.values = make(map[fmt.Stringer]interface{}) + ss.mu.values = make(map[fmt.Stringer]any) ss.SetValue(sessionctx.Initing, true) dom, err := domap.Get(store) c.Assert(err, IsNil) diff --git a/session/session.go b/session/session.go index fdbad0077..8a8b4510c 100644 --- a/session/session.go +++ b/session/session.go @@ -160,7 +160,7 @@ type session struct { mu struct { sync.RWMutex - values map[fmt.Stringer]interface{} + values map[fmt.Stringer]any } currentPlan plannercore.Plan @@ -341,7 +341,7 @@ func (s *session) GetSessionManager() util.SessionManager { return s.sessionManager } -func (s *session) StoreQueryFeedback(feedback interface{}) { +func (s *session) StoreQueryFeedback(feedback any) { if s.statsCollector != nil { do, err := GetDomain(s.store) if err != nil { @@ -549,7 +549,7 @@ func (s *session) GetClient() kv.Client { func (s *session) String() string { // TODO: how to print binded context in values appropriately? sessVars := s.sessionVars - data := map[string]interface{}{ + data := map[string]any{ "id": sessVars.ConnectionID, "user": sessVars.User, "currDBName": sessVars.CurrentDB, @@ -1527,13 +1527,13 @@ func (s *session) NewTxn(ctx context.Context) error { return nil } -func (s *session) SetValue(key fmt.Stringer, value interface{}) { +func (s *session) SetValue(key fmt.Stringer, value any) { s.mu.Lock() s.mu.values[key] = value s.mu.Unlock() } -func (s *session) Value(key fmt.Stringer) interface{} { +func (s *session) Value(key fmt.Stringer) any { s.mu.RLock() value := s.mu.values[key] s.mu.RUnlock() @@ -1878,7 +1878,7 @@ func createSessionWithOpt(store kv.Storage, opt *Opt) (*session, error) { plannercore.PreparedPlanCacheMemoryGuardRatio, plannercore.PreparedPlanCacheMaxMemory.Load()) } } - s.mu.values = make(map[fmt.Stringer]interface{}) + s.mu.values = make(map[fmt.Stringer]any) s.lockedTables = make(map[int64]model.TableLockTpInfo) domain.BindDomain(s, dom) // session implements variable.GlobalVarAccessor. Bind it to ctx. @@ -1906,7 +1906,7 @@ func CreateSessionWithDomain(store kv.Storage, dom *domain.Domain) (*session, er s.preparedPlanCache = kvcache.NewSimpleLRUCache(plannercore.PreparedPlanCacheCapacity, plannercore.PreparedPlanCacheMemoryGuardRatio, plannercore.PreparedPlanCacheMaxMemory.Load()) } - s.mu.values = make(map[fmt.Stringer]interface{}) + s.mu.values = make(map[fmt.Stringer]any) s.lockedTables = make(map[int64]model.TableLockTpInfo) domain.BindDomain(s, dom) // session implements variable.GlobalVarAccessor. Bind it to ctx. diff --git a/session/tidb_test.go b/session/tidb_test.go index 7a77003d1..b2ce9388c 100644 --- a/session/tidb_test.go +++ b/session/tidb_test.go @@ -134,7 +134,7 @@ func removeStore(c *C, dbPath string) { os.RemoveAll(dbPath) } -func exec(se Session, sql string, args ...interface{}) (sqlexec.RecordSet, error) { +func exec(se Session, sql string, args ...any) (sqlexec.RecordSet, error) { ctx := context.Background() if len(args) == 0 { rs, err := se.Execute(ctx, sql) @@ -158,13 +158,13 @@ func exec(se Session, sql string, args ...interface{}) (sqlexec.RecordSet, error return rs, nil } -func mustExecSQL(c *C, se Session, sql string, args ...interface{}) sqlexec.RecordSet { +func mustExecSQL(c *C, se Session, sql string, args ...any) sqlexec.RecordSet { rs, err := exec(se, sql, args...) c.Assert(err, IsNil) return rs } -func match(c *C, row []types.Datum, expected ...interface{}) { +func match(c *C, row []types.Datum, expected ...any) { c.Assert(len(row), Equals, len(expected)) for i := range row { got := fmt.Sprintf("%v", row[i].GetValue()) diff --git a/sessionctx/context.go b/sessionctx/context.go index 4112d0e90..706bab179 100644 --- a/sessionctx/context.go +++ b/sessionctx/context.go @@ -44,10 +44,10 @@ type Context interface { GetClient() kv.Client // SetValue saves a value associated with this context for key. - SetValue(key fmt.Stringer, value interface{}) + SetValue(key fmt.Stringer, value any) // Value returns the value associated with this context for key. - Value(key fmt.Stringer) interface{} + Value(key fmt.Stringer) any // ClearValue clears the value associated with this context for key. ClearValue(key fmt.Stringer) @@ -72,7 +72,7 @@ type Context interface { PreparedPlanCache() *kvcache.SimpleLRUCache // StoreQueryFeedback stores the query feedback. - StoreQueryFeedback(feedback interface{}) + StoreQueryFeedback(feedback any) // HasDirtyContent checks whether there's dirty update on the given table. HasDirtyContent(tid int64) bool diff --git a/sessionctx/variable/session.go b/sessionctx/variable/session.go index 32a701173..235f12331 100644 --- a/sessionctx/variable/session.go +++ b/sessionctx/variable/session.go @@ -130,10 +130,10 @@ type stmtFuture struct { type TransactionContext struct { forUpdateTS uint64 stmtFuture oracle.Future - DirtyDB interface{} - Binlog interface{} - InfoSchema interface{} - History interface{} + DirtyDB any + Binlog any + InfoSchema any + History any SchemaVersion int64 StartTS uint64 Shard *int64 @@ -306,7 +306,7 @@ type SessionVars struct { // SysErrorCount is the system variable "error_count", because it is on the hot path, so we extract it from the systems SysErrorCount uint16 // PreparedStmts stores prepared statement. - PreparedStmts map[uint32]interface{} + PreparedStmts map[uint32]any PreparedStmtNameToID map[string]uint32 // preparedStmtID is id of prepared statement. preparedStmtID uint32 @@ -367,7 +367,7 @@ type SessionVars struct { // SnapshotInfoschema is used with SnapshotTS, when the schema version at snapshotTS less than current schema // version, we load an old version schema for query. - SnapshotInfoschema interface{} + SnapshotInfoschema any // BinlogClient is used to write binlog. BinlogClient *pumpcli.PumpsClient @@ -636,7 +636,7 @@ func NewSessionVars() *SessionVars { vars := &SessionVars{ Users: make(map[string]types.Datum), systems: make(map[string]string), - PreparedStmts: make(map[uint32]interface{}), + PreparedStmts: make(map[uint32]any), PreparedStmtNameToID: make(map[string]uint32), PreparedParams: make([]types.Datum, 0, 10), TxnCtx: &TransactionContext{}, @@ -945,7 +945,7 @@ func (s *SessionVars) setDDLReorgPriority(val string) { } // AddPreparedStmt adds prepareStmt to current session and count in global. -func (s *SessionVars) AddPreparedStmt(stmtID uint32, stmt interface{}) error { +func (s *SessionVars) AddPreparedStmt(stmtID uint32, stmt any) error { if _, exists := s.PreparedStmts[stmtID]; !exists { valStr, _ := s.GetSystemVar(MaxPreparedStmtCount) maxPreparedStmtCount, err := strconv.ParseInt(valStr, 10, 64) diff --git a/sessionctx/variable/session_test.go b/sessionctx/variable/session_test.go index 8e5136beb..50b6d100c 100644 --- a/sessionctx/variable/session_test.go +++ b/sessionctx/variable/session_test.go @@ -37,7 +37,7 @@ func (*testSessionSuite) TestSetSystemVariable(c *C) { v.TimeZone = time.UTC tests := []struct { key string - value interface{} + value any err bool }{ {variable.TxnIsolation, "SERIALIZABLE", true}, diff --git a/sessionctx/variable/statusvar.go b/sessionctx/variable/statusvar.go index 0d3a4eee1..b56f8a4e1 100644 --- a/sessionctx/variable/statusvar.go +++ b/sessionctx/variable/statusvar.go @@ -30,7 +30,7 @@ var DefaultStatusVarScopeFlag = ScopeGlobal | ScopeSession // StatusVal is the value of the corresponding status variable. type StatusVal struct { Scope ScopeFlag - Value interface{} + Value any } // Statistics is the interface of statistics. @@ -38,7 +38,7 @@ type Statistics interface { // GetScope gets the status variables scope. GetScope(status string) ScopeFlag // Stats returns the statistics status variables. - Stats(*SessionVars) (map[string]interface{}, error) + Stats(*SessionVars) (map[string]any, error) } // RegisterStatistics registers statistics. @@ -124,8 +124,8 @@ func (s defaultStatusStat) GetScope(status string) ScopeFlag { return defaultStatus[status].Scope } -func (s defaultStatusStat) Stats(vars *SessionVars) (map[string]interface{}, error) { - statusVars := make(map[string]interface{}, len(defaultStatus)) +func (s defaultStatusStat) Stats(vars *SessionVars) (map[string]any, error) { + statusVars := make(map[string]any, len(defaultStatus)) for name, v := range defaultStatus { statusVars[name] = v.Value diff --git a/sessionctx/variable/statusvar_test.go b/sessionctx/variable/statusvar_test.go index 5e0050063..5a0b8fc2d 100644 --- a/sessionctx/variable/statusvar_test.go +++ b/sessionctx/variable/statusvar_test.go @@ -51,8 +51,8 @@ func (ms *mockStatistics) GetScope(status string) ScopeFlag { return scope } -func (ms *mockStatistics) Stats(vars *SessionVars) (map[string]interface{}, error) { - m := make(map[string]interface{}, len(specificStatusScopes)) +func (ms *mockStatistics) Stats(vars *SessionVars) (map[string]any, error) { + m := make(map[string]any, len(specificStatusScopes)) m[testStatus] = testStatusVal return m, nil diff --git a/statistics/handle/update.go b/statistics/handle/update.go index 1be5056db..6c35be0e1 100644 --- a/statistics/handle/update.go +++ b/statistics/handle/update.go @@ -174,7 +174,7 @@ var ( ) // StoreQueryFeedback will merges the feedback into stats collector. -func (s *SessionStatsCollector) StoreQueryFeedback(feedback interface{}, h *Handle) error { +func (s *SessionStatsCollector) StoreQueryFeedback(feedback any, h *Handle) error { q := feedback.(*statistics.QueryFeedback) // TODO: If the error rate is small or actual scan count is small, we do not need to store the feed back. if !q.Valid || q.Hist == nil { @@ -615,11 +615,11 @@ func TableAnalyzed(tbl *statistics.Table) bool { } // NeedAnalyzeTable checks if we need to analyze the table: -// 1. If the table has never been analyzed, we need to analyze it when it has -// not been modified for a while. -// 2. If the table had been analyzed before, we need to analyze it when -// "tbl.ModifyCount/tbl.Count > autoAnalyzeRatio" and the current time is -// between `start` and `end`. +// 1. If the table has never been analyzed, we need to analyze it when it has +// not been modified for a while. +// 2. If the table had been analyzed before, we need to analyze it when +// "tbl.ModifyCount/tbl.Count > autoAnalyzeRatio" and the current time is +// between `start` and `end`. func NeedAnalyzeTable(tbl *statistics.Table, limit time.Duration, autoAnalyzeRatio float64, start, end, now time.Time) (bool, string) { analyzed := TableAnalyzed(tbl) if !analyzed { diff --git a/store/helper/helper.go b/store/helper/helper.go index 22c944b8b..e545a1852 100644 --- a/store/helper/helper.go +++ b/store/helper/helper.go @@ -616,7 +616,7 @@ func (h *Helper) GetRegionInfoByID(regionID uint64) (*RegionInfo, error) { } // request PD API, decode the response body into res -func (h *Helper) requestPD(method, uri string, body io.Reader, res interface{}) error { +func (h *Helper) requestPD(method, uri string, body io.Reader, res any) error { etcd, ok := h.Store.(tikv.EtcdBackend) if !ok { return errors.WithStack(errors.New("not implemented")) diff --git a/store/mockstore/mocktikv/cop_handler_dag.go b/store/mockstore/mocktikv/cop_handler_dag.go index 0ecbee01d..1cc646922 100644 --- a/store/mockstore/mocktikv/cop_handler_dag.go +++ b/store/mockstore/mocktikv/cop_handler_dag.go @@ -492,10 +492,10 @@ func (mockClientStream) CloseSend() error { return nil } func (mockClientStream) Context() context.Context { return nil } // SendMsg implements grpc.ClientStream interface -func (mockClientStream) SendMsg(m interface{}) error { return nil } +func (mockClientStream) SendMsg(m any) error { return nil } // RecvMsg implements grpc.ClientStream interface -func (mockClientStream) RecvMsg(m interface{}) error { return nil } +func (mockClientStream) RecvMsg(m any) error { return nil } type mockCopStreamClient struct { mockClientStream diff --git a/store/mockstore/mocktikv/mvcc.go b/store/mockstore/mocktikv/mvcc.go index c02c3d718..5ea9ce55b 100644 --- a/store/mockstore/mocktikv/mvcc.go +++ b/store/mockstore/mocktikv/mvcc.go @@ -135,7 +135,7 @@ func (mh *marshalHelper) WriteSlice(buf io.Writer, slice []byte) { } } -func (mh *marshalHelper) WriteNumber(buf io.Writer, n interface{}) { +func (mh *marshalHelper) WriteNumber(buf io.Writer, n any) { if mh.err != nil { return } @@ -157,7 +157,7 @@ func writeFull(w io.Writer, slice []byte) error { return nil } -func (mh *marshalHelper) ReadNumber(r io.Reader, n interface{}) { +func (mh *marshalHelper) ReadNumber(r io.Reader, n any) { if mh.err != nil { return } diff --git a/store/mockstore/mocktikv/topn.go b/store/mockstore/mocktikv/topn.go index 3b2a5d952..63da676dc 100644 --- a/store/mockstore/mocktikv/topn.go +++ b/store/mockstore/mocktikv/topn.go @@ -83,12 +83,12 @@ func (t *topNHeap) Len() int { return t.heapSize } -func (t *topNHeap) Push(x interface{}) { +func (t *topNHeap) Push(x any) { t.rows = append(t.rows, x.(*sortRow)) t.heapSize++ } -func (t *topNHeap) Pop() interface{} { +func (t *topNHeap) Pop() any { return nil } diff --git a/store/tikv/backoff.go b/store/tikv/backoff.go index 48c993bdc..7992905ae 100644 --- a/store/tikv/backoff.go +++ b/store/tikv/backoff.go @@ -349,7 +349,7 @@ func (b *Backoffer) BackoffWithMaxSleep(typ backoffType, maxSleepMs int, err err } } - var startTs interface{} + var startTs any if ts := b.ctx.Value(txnStartKey); ts != nil { startTs = ts } diff --git a/store/tikv/client_batch.go b/store/tikv/client_batch.go index 08520afc5..339670de7 100644 --- a/store/tikv/client_batch.go +++ b/store/tikv/client_batch.go @@ -249,7 +249,7 @@ func (c *batchCommandsClient) recv() (*tikvpb.BatchCommandsResponse, error) { // `failPendingRequests` must be called in locked contexts in order to avoid double closing channels. func (c *batchCommandsClient) failPendingRequests(err error) { failpoint.Inject("panicInFailPendingRequests", nil) - c.batched.Range(func(key, value interface{}) bool { + c.batched.Range(func(key, value any) bool { id, _ := key.(uint64) entry, _ := value.(*batchCommandsEntry) entry.err = err diff --git a/store/tikv/client_collapse.go b/store/tikv/client_collapse.go index 5b0386ef7..6428c34d0 100644 --- a/store/tikv/client_collapse.go +++ b/store/tikv/client_collapse.go @@ -69,7 +69,7 @@ func (r reqCollapse) tryCollapseRequest(ctx context.Context, addr string, req *t func (r reqCollapse) collapse(ctx context.Context, key string, sf *singleflight.Group, addr string, req *tikvrpc.Request, timeout time.Duration) (resp *tikvrpc.Response, err error) { - rsC := sf.DoChan(key, func() (interface{}, error) { + rsC := sf.DoChan(key, func() (any, error) { return r.Client.SendRequest(context.Background(), addr, req, readTimeoutShort) // use resolveLock timeout. }) timer := time.NewTimer(timeout) diff --git a/store/tikv/gcworker/gc_worker.go b/store/tikv/gcworker/gc_worker.go index 0386f3988..4c8fa3261 100644 --- a/store/tikv/gcworker/gc_worker.go +++ b/store/tikv/gcworker/gc_worker.go @@ -1174,7 +1174,7 @@ func (w *GCWorker) registerLockObservers(ctx context.Context, safePoint uint64, // checkLockObservers checks the state of each store's lock observer. If any lock collected by the observers, resolve // them. Returns ids of clean stores. -func (w *GCWorker) checkLockObservers(ctx context.Context, safePoint uint64, stores map[uint64]*metapb.Store) (map[uint64]interface{}, error) { +func (w *GCWorker) checkLockObservers(ctx context.Context, safePoint uint64, stores map[uint64]*metapb.Store) (map[uint64]any, error) { logutil.Logger(ctx).Info("[gc worker] checking lock observers", zap.String("uuid", w.uuid), zap.Uint64("safePoint", safePoint)) @@ -1182,7 +1182,7 @@ func (w *GCWorker) checkLockObservers(ctx context.Context, safePoint uint64, sto req := tikvrpc.NewRequest(tikvrpc.CmdCheckLockObserver, &kvrpcpb.CheckLockObserverRequest{ MaxTs: safePoint, }) - cleanStores := make(map[uint64]interface{}, len(stores)) + cleanStores := make(map[uint64]any, len(stores)) logError := func(store *metapb.Store, err error) { logutil.Logger(ctx).Error("[gc worker] failed to check lock observer for store", @@ -1280,7 +1280,7 @@ func (w *GCWorker) removeLockObservers(ctx context.Context, safePoint uint64, st } // physicalScanAndResolveLocks performs physical scan lock and resolves these locks. Returns successful stores -func (w *GCWorker) physicalScanAndResolveLocks(ctx context.Context, safePoint uint64, stores map[uint64]*metapb.Store) (map[uint64]interface{}, error) { +func (w *GCWorker) physicalScanAndResolveLocks(ctx context.Context, safePoint uint64, stores map[uint64]*metapb.Store) (map[uint64]any, error) { ctx, cancel := context.WithCancel(ctx) // Cancel all spawned goroutines for lock scanning and resolving. defer cancel() @@ -1891,11 +1891,11 @@ func (r mergeReceiver) Swap(i, j int) { r[i], r[j] = r[j], r[i] } -func (r *mergeReceiver) Push(x interface{}) { +func (r *mergeReceiver) Push(x any) { *r = append(*r, x.(*receiver)) } -func (r *mergeReceiver) Pop() interface{} { +func (r *mergeReceiver) Pop() any { receivers := *r res := receivers[len(receivers)-1] *r = receivers[:len(receivers)-1] @@ -1981,8 +1981,8 @@ func (s *mergeLockScanner) NextBatch(batchSize int) []*tikv.Lock { } // GetSucceededStores gets a set of successfully scanned stores. Only call this after finishing scanning all locks. -func (s *mergeLockScanner) GetSucceededStores() map[uint64]interface{} { - stores := make(map[uint64]interface{}, len(s.receivers)) +func (s *mergeLockScanner) GetSucceededStores() map[uint64]any { + stores := make(map[uint64]any, len(s.receivers)) for _, receiver := range s.receivers { if receiver.Err == nil { stores[receiver.StoreID] = nil diff --git a/store/tikv/gcworker/gc_worker_test.go b/store/tikv/gcworker/gc_worker_test.go index 1a5cb78bf..17487f44b 100644 --- a/store/tikv/gcworker/gc_worker_test.go +++ b/store/tikv/gcworker/gc_worker_test.go @@ -1038,8 +1038,8 @@ func (s *testGCWorkerSuite) TestMergeLockScanner(c *C) { // Shortcuts to make the following test code simpler // Get stores by index, and get their store IDs. - makeIDSet := func(storeIDs []uint64, indices ...uint64) map[uint64]interface{} { - res := make(map[uint64]interface{}) + makeIDSet := func(storeIDs []uint64, indices ...uint64) map[uint64]any { + res := make(map[uint64]any) for _, i := range indices { res[storeIDs[i]] = nil } @@ -1381,7 +1381,7 @@ func (s *testGCWorkerSuite) TestPhyscailScanLockDeadlock(c *C) { c.Assert(failpoint.Disable("github.com/pingcap/tidb/store/tikv/gcworker/resolveLocksAcrossRegionsErr"), IsNil) }() - done := make(chan interface{}) + done := make(chan any) go func() { defer close(done) storesMap := map[uint64]*metapb.Store{stores[0].Id: stores[0]} diff --git a/store/tikv/kv.go b/store/tikv/kv.go index 262b8046e..d83eabb48 100644 --- a/store/tikv/kv.go +++ b/store/tikv/kv.go @@ -388,7 +388,7 @@ func (s *tikvStore) Describe() string { return "TiKV is a distributed transactional key-value database" } -func (s *tikvStore) ShowStatus(ctx context.Context, key string) (interface{}, error) { +func (s *tikvStore) ShowStatus(ctx context.Context, key string) (any, error) { return nil, kv.ErrNotImplemented } diff --git a/store/tikv/region_cache.go b/store/tikv/region_cache.go index 8a6d1704e..5c561a355 100644 --- a/store/tikv/region_cache.go +++ b/store/tikv/region_cache.go @@ -1461,7 +1461,7 @@ func (s *Store) requestLiveness(bo *Backoffer) (l livenessState) { l = unknown return } - rsCh := livenessSf.DoChan(saddr, func() (interface{}, error) { + rsCh := livenessSf.DoChan(saddr, func() (any, error) { return invokeKVStatusAPI(saddr, storeLivenessTimeout), nil }) var ctx context.Context diff --git a/store/tikv/snapshot.go b/store/tikv/snapshot.go index 9117d1907..ba07e9c92 100644 --- a/store/tikv/snapshot.go +++ b/store/tikv/snapshot.go @@ -399,7 +399,7 @@ func (s *tikvSnapshot) IterReverse(k kv.Key) (kv.Iterator, error) { // SetOption sets an option with a value, when val is nil, uses the default // value of this option. Only ReplicaRead is supported for snapshot -func (s *tikvSnapshot) SetOption(opt kv.Option, val interface{}) { +func (s *tikvSnapshot) SetOption(opt kv.Option, val any) { switch opt { case kv.ReplicaRead: s.replicaRead = val.(kv.ReplicaReadType) diff --git a/store/tikv/split_region.go b/store/tikv/split_region.go index 65594c0e6..ba57e4482 100644 --- a/store/tikv/split_region.go +++ b/store/tikv/split_region.go @@ -75,7 +75,7 @@ func (s *tikvStore) splitBatchRegionsReq(bo *Backoffer, keys [][]byte, scatter b case <-bo.ctx.Done(): ch <- singleBatchResp{err: bo.ctx.Err()} } - }, func(r interface{}) { + }, func(r any) { if r != nil { ch <- singleBatchResp{err: errors.Errorf("%v", r)} } diff --git a/store/tikv/tikvrpc/tikvrpc.go b/store/tikv/tikvrpc/tikvrpc.go index 0e54aee45..c2e96b606 100644 --- a/store/tikv/tikvrpc/tikvrpc.go +++ b/store/tikv/tikvrpc/tikvrpc.go @@ -158,14 +158,14 @@ func (t CmdType) String() string { // Request wraps all kv/coprocessor requests. type Request struct { Type CmdType - req interface{} + req any kvrpcpb.Context ReplicaReadSeed uint32 StoreTp kv.StoreType } // NewRequest returns new kv rpc request. -func NewRequest(typ CmdType, pointer interface{}, ctxs ...kvrpcpb.Context) *Request { +func NewRequest(typ CmdType, pointer any, ctxs ...kvrpcpb.Context) *Request { if len(ctxs) > 0 { return &Request{ Type: typ, @@ -180,7 +180,7 @@ func NewRequest(typ CmdType, pointer interface{}, ctxs ...kvrpcpb.Context) *Requ } // NewReplicaReadRequest returns new kv rpc request with replica read. -func NewReplicaReadRequest(typ CmdType, pointer interface{}, replicaReadType kv.ReplicaReadType, replicaReadSeed uint32, ctxs ...kvrpcpb.Context) *Request { +func NewReplicaReadRequest(typ CmdType, pointer any, replicaReadType kv.ReplicaReadType, replicaReadSeed uint32, ctxs ...kvrpcpb.Context) *Request { req := NewRequest(typ, pointer, ctxs...) req.ReplicaRead = replicaReadType.IsFollowerRead() req.ReplicaReadSeed = replicaReadSeed @@ -430,7 +430,7 @@ func (req *Request) IsDebugReq() bool { // Response wraps all kv/coprocessor responses. type Response struct { - Resp interface{} + Resp any } // FromBatchCommandsResponse converts a BatchCommands response to Response. @@ -600,7 +600,7 @@ func SetContext(req *Request, region *metapb.Region, peer *metapb.Peer) error { // GenRegionErrorResp returns corresponding Response with specified RegionError // according to the given req. func GenRegionErrorResp(req *Request, e *errorpb.Error) (*Response, error) { - var p interface{} + var p any resp := &Response{} switch req.Type { case CmdGet: diff --git a/store/tikv/txn.go b/store/tikv/txn.go index b148686fb..68a6b18e3 100644 --- a/store/tikv/txn.go +++ b/store/tikv/txn.go @@ -186,7 +186,7 @@ func (txn *tikvTxn) Delete(k kv.Key) error { return txn.us.Delete(k) } -func (txn *tikvTxn) SetOption(opt kv.Option, val interface{}) { +func (txn *tikvTxn) SetOption(opt kv.Option, val any) { txn.us.SetOption(opt, val) switch opt { case kv.Priority: diff --git a/table/column.go b/table/column.go index 5ddf268d0..5bef4c8d6 100644 --- a/table/column.go +++ b/table/column.go @@ -224,12 +224,12 @@ type ColDesc struct { Field string Type string // Charset is nil if the column doesn't have a charset, or a string indicating the charset name. - Charset interface{} + Charset any // Collation is nil if the column doesn't have a collation, or a string indicating the collation name. - Collation interface{} + Collation any Null string Key string - DefaultValue interface{} + DefaultValue any Extra string Privileges string Comment string @@ -256,7 +256,7 @@ func NewColDesc(col *Column) *ColDesc { } else if mysql.HasMultipleKeyFlag(col.Flag) { keyFlag = "MUL" } - var defaultValue interface{} + var defaultValue any if !mysql.HasNoDefaultValueFlag(col.Flag) { defaultValue = col.GetDefaultValue() if defaultValStr, ok := defaultValue.(string); ok { @@ -415,7 +415,7 @@ func getColDefaultExprValue(ctx sessionctx.Context, col *model.ColumnInfo, defau return value, nil } -func getColDefaultValue(ctx sessionctx.Context, col *model.ColumnInfo, defaultVal interface{}) (types.Datum, error) { +func getColDefaultValue(ctx sessionctx.Context, col *model.ColumnInfo, defaultVal any) (types.Datum, error) { if defaultVal == nil { return getColDefaultValueFromNil(ctx, col) } diff --git a/table/tables/tables.go b/table/tables/tables.go index 7d17fa58e..4d2e118cc 100644 --- a/table/tables/tables.go +++ b/table/tables/tables.go @@ -1236,7 +1236,7 @@ func (s *sequenceCommon) GetSequenceBaseEndRound() (int64, int64, int64) { // GetSequenceNextVal implements util.SequenceTable GetSequenceNextVal interface. // Caching the sequence value in table, we can easily be notified with the cache empty, // and write the binlogInfo in table level rather than in allocator. -func (t *TableCommon) GetSequenceNextVal(ctx interface{}, dbName, seqName string) (nextVal int64, err error) { +func (t *TableCommon) GetSequenceNextVal(ctx any, dbName, seqName string) (nextVal int64, err error) { seq := t.sequence if seq == nil { // TODO: refine the error. @@ -1319,7 +1319,7 @@ func (t *TableCommon) GetSequenceNextVal(ctx interface{}, dbName, seqName string // SetSequenceVal implements util.SequenceTable SetSequenceVal interface. // The returned bool indicates the newVal is already under the base. -func (t *TableCommon) SetSequenceVal(ctx interface{}, newVal int64, dbName, seqName string) (int64, bool, error) { +func (t *TableCommon) SetSequenceVal(ctx any, newVal int64, dbName, seqName string) (int64, bool, error) { seq := t.sequence if seq == nil { // TODO: refine the error. diff --git a/tidb-server/main.go b/tidb-server/main.go index e50e1c89d..5f299e3f8 100644 --- a/tidb-server/main.go +++ b/tidb-server/main.go @@ -602,7 +602,7 @@ func setupLog() { err = logutil.InitLogger(cfg.Log.ToLogConfig()) terror.MustNil(err) // Disable automaxprocs log - nopLog := func(string, ...interface{}) {} + nopLog := func(string, ...any) {} _, err = maxprocs.Set(maxprocs.Logger(nopLog)) terror.MustNil(err) diff --git a/types/compare_test.go b/types/compare_test.go index 4e509ec55..1c9ab7315 100644 --- a/types/compare_test.go +++ b/types/compare_test.go @@ -31,8 +31,8 @@ type testCompareSuite struct { func (s *testCompareSuite) TestCompare(c *C) { defer testleak.AfterTest(c)() cmpTbl := []struct { - lhs interface{} - rhs interface{} + lhs any + rhs any ret int // 0, 1, -1 }{ {float64(1), float64(1), 0}, @@ -150,7 +150,7 @@ func (s *testCompareSuite) TestCompare(c *C) { } } -func compareForTest(a, b interface{}) (int, error) { +func compareForTest(a, b any) (int, error) { sc := new(stmtctx.StatementContext) sc.IgnoreTruncate = true aDatum := NewDatum(a) diff --git a/types/convert.go b/types/convert.go index 0d6b7ff2a..b2bb0b743 100644 --- a/types/convert.go +++ b/types/convert.go @@ -672,7 +672,7 @@ func getValidFloatPrefix(sc *stmtctx.StatementContext, s string) (valid string, } // ToString converts an interface to a string. -func ToString(value interface{}) (string, error) { +func ToString(value any) (string, error) { switch v := value.(type) { case bool: if v { diff --git a/types/convert_test.go b/types/convert_test.go index 22d7478f7..48238e1b3 100644 --- a/types/convert_test.go +++ b/types/convert_test.go @@ -38,7 +38,7 @@ type invalidMockType struct { } // Convert converts the val with type tp. -func Convert(val interface{}, target *FieldType) (v interface{}, err error) { +func Convert(val any, target *FieldType) (v any, err error) { d := NewDatum(val) sc := new(stmtctx.StatementContext) sc.TimeZone = time.UTC @@ -306,7 +306,7 @@ func (s *testTypeConvertSuite) TestConvertType(c *C) { c.Assert(err, NotNil) } -func testToString(c *C, val interface{}, expect string) { +func testToString(c *C, val any, expect string) { b, err := ToString(val) c.Assert(err, IsNil) c.Assert(b, Equals, expect) @@ -503,7 +503,7 @@ func (s *testTypeConvertSuite) TestFieldTypeToStr(c *C) { c.Assert(v, Equals, "binary") } -func accept(c *C, tp byte, value interface{}, unsigned bool, expected string) { +func accept(c *C, tp byte, value any, unsigned bool, expected string) { ft := NewFieldType(tp) if unsigned { ft.Flag |= mysql.UnsignedFlag @@ -523,15 +523,15 @@ func accept(c *C, tp byte, value interface{}, unsigned bool, expected string) { } } -func unsignedAccept(c *C, tp byte, value interface{}, expected string) { +func unsignedAccept(c *C, tp byte, value any, expected string) { accept(c, tp, value, true, expected) } -func signedAccept(c *C, tp byte, value interface{}, expected string) { +func signedAccept(c *C, tp byte, value any, expected string) { accept(c, tp, value, false, expected) } -func deny(c *C, tp byte, value interface{}, unsigned bool, expected string) { +func deny(c *C, tp byte, value any, unsigned bool, expected string) { ft := NewFieldType(tp) if unsigned { ft.Flag |= mysql.UnsignedFlag @@ -549,15 +549,15 @@ func deny(c *C, tp byte, value interface{}, unsigned bool, expected string) { } } -func unsignedDeny(c *C, tp byte, value interface{}, expected string) { +func unsignedDeny(c *C, tp byte, value any, expected string) { deny(c, tp, value, true, expected) } -func signedDeny(c *C, tp byte, value interface{}, expected string) { +func signedDeny(c *C, tp byte, value any, expected string) { deny(c, tp, value, false, expected) } -func strvalue(v interface{}) string { +func strvalue(v any) string { return fmt.Sprintf("%v", v) } @@ -972,12 +972,12 @@ func (s *testTypeConvertSuite) TestConvertJSONToInt(c *C) { func (s *testTypeConvertSuite) TestConvertJSONToFloat(c *C) { var tests = []struct { - In interface{} + In any Out float64 ty json.TypeCode }{ - {make(map[string]interface{}), 0, json.TypeCodeObject}, - {make([]interface{}, 0), 0, json.TypeCodeArray}, + {make(map[string]any), 0, json.TypeCodeObject}, + {make([]any, 0), 0, json.TypeCodeArray}, {int64(3), 3, json.TypeCodeInt64}, {int64(-3), -3, json.TypeCodeInt64}, {uint64(1 << 63), 1 << 63, json.TypeCodeUint64}, diff --git a/types/datum.go b/types/datum.go index f4bf7f9e3..53dc5f165 100644 --- a/types/datum.go +++ b/types/datum.go @@ -61,13 +61,13 @@ const ( // Datum is a data box holds different kind of data. // It has better performance and is easier to use than `interface{}`. type Datum struct { - k byte // datum kind. - collation string // collation hold the collation information for string value. - decimal uint16 // decimal can hold uint16 values. - length uint32 // length can hold uint32 values. - i int64 // i can hold int64 uint64 float64 values. - b []byte // b can hold string or []byte values. - x interface{} // x hold all other types. + k byte // datum kind. + collation string // collation hold the collation information for string value. + decimal uint16 // decimal can hold uint16 values. + length uint32 // length can hold uint32 values. + i int64 // i can hold int64 uint64 float64 values. + b []byte // b can hold string or []byte values. + x any // x hold all other types. } // Clone create a deep copy of the Datum. @@ -210,12 +210,12 @@ func (d *Datum) SetBytesAsString(b []byte, collation string, length uint32) { } // GetInterface gets interface value. -func (d *Datum) GetInterface() interface{} { +func (d *Datum) GetInterface() any { return d.x } // SetInterface sets interface to datum. -func (d *Datum) SetInterface(x interface{}) { +func (d *Datum) SetInterface(x any) { d.k = KindInterface d.x = x } @@ -395,7 +395,7 @@ func (d Datum) String() string { } // GetValue gets the value of the datum of any kind. -func (d *Datum) GetValue() interface{} { +func (d *Datum) GetValue() any { switch d.k { case KindInt64: return d.GetInt64() @@ -429,7 +429,7 @@ func (d *Datum) GetValue() interface{} { } // SetValueWithDefaultCollation sets any kind of value. -func (d *Datum) SetValueWithDefaultCollation(val interface{}) { +func (d *Datum) SetValueWithDefaultCollation(val any) { switch x := val.(type) { case nil: d.SetNull() @@ -477,7 +477,7 @@ func (d *Datum) SetValueWithDefaultCollation(val interface{}) { } // SetValue sets any kind of value. -func (d *Datum) SetValue(val interface{}, tp *types.FieldType) { +func (d *Datum) SetValue(val any, tp *types.FieldType) { switch x := val.(type) { case nil: d.SetNull() @@ -1689,7 +1689,7 @@ func (d *Datum) ToBytes() ([]byte, error) { // ToMysqlJSON is similar to convertToMysqlJSON, except the // latter parses from string, but the former uses it as primitive. func (d *Datum) ToMysqlJSON() (j json.BinaryJSON, err error) { - var in interface{} + var in any switch d.Kind() { case KindMysqlJSON: j = d.GetMysqlJSON() @@ -1724,9 +1724,9 @@ func invalidConv(d *Datum, tp byte) (Datum, error) { } // NewDatum creates a new Datum from an interface{}. -func NewDatum(in interface{}) (d Datum) { +func NewDatum(in any) (d Datum) { switch x := in.(type) { - case []interface{}: + case []any: d.SetValueWithDefaultCollation(MakeDatums(x...)) default: d.SetValueWithDefaultCollation(in) @@ -1831,7 +1831,7 @@ func NewMysqlSetDatum(e Set, collation string) (d Datum) { } // MakeDatums creates datum slice from interfaces. -func MakeDatums(args ...interface{}) []Datum { +func MakeDatums(args ...any) []Datum { datums := make([]Datum, len(args)) for i, v := range args { datums[i] = NewDatum(v) @@ -2050,14 +2050,17 @@ func getDatumBound(retType *FieldType, rType RoundingType) Datum { // ChangeReverseResultByUpperLowerBound is for expression's reverse evaluation. // Here is an example for what's effort for the function: CastRealAsInt(t.a), -// if the type of column `t.a` is mysql.TypeDouble, and there is a row that t.a == MaxFloat64 -// then the cast function will arrive a result MaxInt64. But when we do the reverse evaluation, -// if the result is MaxInt64, and the rounding type is ceiling. Then we should get the MaxFloat64 -// instead of float64(MaxInt64). +// +// if the type of column `t.a` is mysql.TypeDouble, and there is a row that t.a == MaxFloat64 +// then the cast function will arrive a result MaxInt64. But when we do the reverse evaluation, +// if the result is MaxInt64, and the rounding type is ceiling. Then we should get the MaxFloat64 +// instead of float64(MaxInt64). +// // Another example: cast(1.1 as signed) = 1, -// when we get the answer 1, we can only reversely evaluate 1.0 as the column value. So in this -// case, we should judge whether the rounding type are ceiling. If it is, then we should plus one for -// 1.0 and get the reverse result 2.0. +// +// when we get the answer 1, we can only reversely evaluate 1.0 as the column value. So in this +// case, we should judge whether the rounding type are ceiling. If it is, then we should plus one for +// 1.0 and get the reverse result 2.0. func ChangeReverseResultByUpperLowerBound( sc *stmtctx.StatementContext, retType *FieldType, diff --git a/types/datum_test.go b/types/datum_test.go index c9adb255c..2288df2a0 100644 --- a/types/datum_test.go +++ b/types/datum_test.go @@ -34,7 +34,7 @@ type testDatumSuite struct { } func (ts *testDatumSuite) TestDatum(c *C) { - values := []interface{}{ + values := []any{ int64(1), uint64(1), 1.1, @@ -53,7 +53,7 @@ func (ts *testDatumSuite) TestDatum(c *C) { } } -func testDatumToBool(c *C, in interface{}, res int) { +func testDatumToBool(c *C, in any, res int) { datum := NewDatum(in) res64 := int64(res) sc := new(stmtctx.StatementContext) @@ -101,33 +101,33 @@ func (ts *testDatumSuite) TestToBool(c *C) { func (ts *testDatumSuite) TestEqualDatums(c *C) { tests := []struct { - a []interface{} - b []interface{} + a []any + b []any same bool }{ // Positive cases - {[]interface{}{1}, []interface{}{1}, true}, - {[]interface{}{1, "aa"}, []interface{}{1, "aa"}, true}, - {[]interface{}{1, "aa", 1}, []interface{}{1, "aa", 1}, true}, + {[]any{1}, []any{1}, true}, + {[]any{1, "aa"}, []any{1, "aa"}, true}, + {[]any{1, "aa", 1}, []any{1, "aa", 1}, true}, // negative cases - {[]interface{}{1}, []interface{}{2}, false}, - {[]interface{}{1, "a"}, []interface{}{1, "aaaaaa"}, false}, - {[]interface{}{1, "aa", 3}, []interface{}{1, "aa", 2}, false}, + {[]any{1}, []any{2}, false}, + {[]any{1, "a"}, []any{1, "aaaaaa"}, false}, + {[]any{1, "aa", 3}, []any{1, "aa", 2}, false}, // Corner cases - {[]interface{}{}, []interface{}{}, true}, - {[]interface{}{nil}, []interface{}{nil}, true}, - {[]interface{}{}, []interface{}{1}, false}, - {[]interface{}{1}, []interface{}{1, 1}, false}, - {[]interface{}{nil}, []interface{}{1}, false}, + {[]any{}, []any{}, true}, + {[]any{nil}, []any{nil}, true}, + {[]any{}, []any{1}, false}, + {[]any{1}, []any{1, 1}, false}, + {[]any{nil}, []any{1}, false}, } for _, tt := range tests { testEqualDatums(c, tt.a, tt.b, tt.same) } } -func testEqualDatums(c *C, a []interface{}, b []interface{}, same bool) { +func testEqualDatums(c *C, a []any, b []any, same bool) { sc := new(stmtctx.StatementContext) sc.IgnoreTruncate = true res, err := EqualDatums(sc, MakeDatums(a...), MakeDatums(b...)) @@ -135,7 +135,7 @@ func testEqualDatums(c *C, a []interface{}, b []interface{}, same bool) { c.Assert(res, Equals, same, Commentf("a: %v, b: %v", a, b)) } -func testDatumToInt64(c *C, val interface{}, expect int64) { +func testDatumToInt64(c *C, val any, expect int64) { d := NewDatum(val) sc := new(stmtctx.StatementContext) sc.IgnoreTruncate = true @@ -278,7 +278,7 @@ func (ts *testDatumSuite) TestToJSON(c *C) { func (ts *testDatumSuite) TestIsNull(c *C) { tests := []struct { - data interface{} + data any isnull bool }{ {nil, true}, @@ -293,7 +293,7 @@ func (ts *testDatumSuite) TestIsNull(c *C) { } } -func testIsNull(c *C, data interface{}, isnull bool) { +func testIsNull(c *C, data any, isnull bool) { d := NewDatum(data) c.Assert(d.IsNull(), Equals, isnull, Commentf("data: %v, isnull: %v", data, isnull)) } diff --git a/types/etc.go b/types/etc.go index e29c91171..369d1d0c6 100644 --- a/types/etc.go +++ b/types/etc.go @@ -135,6 +135,7 @@ func KindStr(kind byte) (r string) { // It is used for converting Text to Blob, // or converting Char to Binary. // Args: +// // tp: type enum // cs: charset var TypeToStr = ast.TypeToStr @@ -149,12 +150,12 @@ func EOFAsNil(err error) error { } // InvOp2 returns an invalid operation error. -func InvOp2(x, y interface{}, o opcode.Op) (interface{}, error) { +func InvOp2(x, y any, o opcode.Op) (any, error) { return nil, errors.Errorf("Invalid operation: %v %v %v (mismatched types %T and %T)", x, o, y, x, y) } // overflow returns an overflowed error. -func overflow(v interface{}, tp byte) error { +func overflow(v any, tp byte) error { return ErrOverflow.GenWithStack("constant %v overflows %s", v, TypeStr(tp)) } diff --git a/types/field_type.go b/types/field_type.go index ae4ca8bc1..4de313a95 100644 --- a/types/field_type.go +++ b/types/field_type.go @@ -140,7 +140,7 @@ func setTypeFlag(flag *uint, flagItem uint, on bool) { } // DefaultParamTypeForValue returns the default FieldType for the parameterized value. -func DefaultParamTypeForValue(value interface{}, tp *FieldType) { +func DefaultParamTypeForValue(value any, tp *FieldType) { switch value.(type) { case nil: tp.Tp = mysql.TypeVarString @@ -167,7 +167,7 @@ func hasVariantFieldLength(tp *FieldType) bool { } // DefaultTypeForValue returns the default FieldType for the value. -func DefaultTypeForValue(value interface{}, tp *FieldType, char string, collate string) { +func DefaultTypeForValue(value any, tp *FieldType, char string, collate string) { switch x := value.(type) { case nil: tp.Tp = mysql.TypeNull diff --git a/types/field_type_test.go b/types/field_type_test.go index e3f156e0f..a5a382012 100644 --- a/types/field_type_test.go +++ b/types/field_type_test.go @@ -161,7 +161,7 @@ func (s *testFieldTypeSuite) TestFieldType(c *C) { func (s *testFieldTypeSuite) TestDefaultTypeForValue(c *C) { defer testleak.AfterTest(c)() tests := []struct { - value interface{} + value any tp byte flen int decimal int diff --git a/types/json/binary.go b/types/json/binary.go index a386aa5d4..e0ac38463 100644 --- a/types/json/binary.go +++ b/types/json/binary.go @@ -390,7 +390,7 @@ func ParseBinaryFromString(s string) (bj BinaryJSON, err error) { func (bj *BinaryJSON) UnmarshalJSON(data []byte) error { var decoder = json.NewDecoder(bytes.NewReader(data)) decoder.UseNumber() - var in interface{} + var in any err := decoder.Decode(&in) if err != nil { return errors.Trace(err) @@ -407,7 +407,7 @@ func (bj *BinaryJSON) UnmarshalJSON(data []byte) error { } // CreateBinary creates a BinaryJSON from interface. -func CreateBinary(in interface{}) BinaryJSON { +func CreateBinary(in any) BinaryJSON { typeCode, buf, err := appendBinary(nil, in) if err != nil { panic(err) @@ -415,7 +415,7 @@ func CreateBinary(in interface{}) BinaryJSON { return BinaryJSON{TypeCode: typeCode, Value: buf} } -func appendBinary(buf []byte, in interface{}) (TypeCode, []byte, error) { +func appendBinary(buf []byte, in any) (TypeCode, []byte, error) { var typeCode byte var err error switch x := in.(type) { @@ -449,13 +449,13 @@ func appendBinary(buf []byte, in interface{}) (TypeCode, []byte, error) { case BinaryJSON: typeCode = x.TypeCode buf = append(buf, x.Value...) - case []interface{}: + case []any: typeCode = TypeCodeArray buf, err = appendBinaryArray(buf, x) if err != nil { return typeCode, nil, errors.Trace(err) } - case map[string]interface{}: + case map[string]any: typeCode = TypeCodeObject buf, err = appendBinaryObject(buf, x) if err != nil { @@ -536,7 +536,7 @@ func appendBinaryUint64(buf []byte, v uint64) []byte { return buf } -func appendBinaryArray(buf []byte, array []interface{}) ([]byte, error) { +func appendBinaryArray(buf []byte, array []any) ([]byte, error) { docOff := len(buf) buf = appendUint32(buf, uint32(len(array))) buf = appendZero(buf, dataSizeOff) @@ -554,7 +554,7 @@ func appendBinaryArray(buf []byte, array []interface{}) ([]byte, error) { return buf, nil } -func appendBinaryValElem(buf []byte, docOff, valEntryOff int, val interface{}) ([]byte, error) { +func appendBinaryValElem(buf []byte, docOff, valEntryOff int, val any) ([]byte, error) { var typeCode TypeCode var err error elemDocOff := len(buf) @@ -578,10 +578,10 @@ func appendBinaryValElem(buf []byte, docOff, valEntryOff int, val interface{}) ( type field struct { key string - val interface{} + val any } -func appendBinaryObject(buf []byte, x map[string]interface{}) ([]byte, error) { +func appendBinaryObject(buf []byte, x map[string]any) ([]byte, error) { docOff := len(buf) buf = appendUint32(buf, uint32(len(x))) buf = appendZero(buf, dataSizeOff) diff --git a/types/json/binary_functions.go b/types/json/binary_functions.go index 735e298e4..f4a6b6401 100644 --- a/types/json/binary_functions.go +++ b/types/json/binary_functions.go @@ -209,8 +209,9 @@ func quoteString(s string) string { } // Extract receives several path expressions as arguments, matches them in bj, and returns: -// ret: target JSON matched any path expressions. maybe autowrapped as an array. -// found: true if any path expressions matched. +// +// ret: target JSON matched any path expressions. maybe autowrapped as an array. +// found: true if any path expressions matched. func (bj BinaryJSON) Extract(pathExprList []PathExpression) (ret BinaryJSON, found bool) { buf := make([]BinaryJSON, 0, 1) for _, pathExpr := range pathExprList { @@ -890,7 +891,7 @@ func (bj BinaryJSON) Search(containType string, search string, escape byte, path } patChars, patTypes := stringutil.CompilePattern(search, escape) - result := make([]interface{}, 0) + result := make([]any, 0) walkFn := func(fullpath PathExpression, bj BinaryJSON) (stop bool, err error) { if bj.TypeCode == TypeCodeString && stringutil.DoMatch(string(bj.GetString()), patChars, patTypes) { result = append(result, fullpath.String()) @@ -926,7 +927,9 @@ func (bj BinaryJSON) Search(containType string, search string, escape byte, path type extractCallbackFn func(fullpath PathExpression, bj BinaryJSON) (stop bool, err error) // extractToCallback: callback alternative of extractTo -// would be more effective when walk through the whole JSON is unnecessary +// +// would be more effective when walk through the whole JSON is unnecessary +// // NOTICE: path [0] & [*] for JSON object other than array is INVALID, which is different from extractTo. func (bj BinaryJSON) extractToCallback(pathExpr PathExpression, callbackFn extractCallbackFn, fullpath PathExpression) (stop bool, err error) { if len(pathExpr.legs) == 0 { diff --git a/types/parser_driver/value_expr.go b/types/parser_driver/value_expr.go index a2398f42a..c1f0da0c3 100644 --- a/types/parser_driver/value_expr.go +++ b/types/parser_driver/value_expr.go @@ -42,16 +42,16 @@ import ( func init() { ast.NewValueExpr = newValueExpr ast.NewParamMarkerExpr = newParamMarkerExpr - ast.NewDecimal = func(str string) (interface{}, error) { + ast.NewDecimal = func(str string) (any, error) { dec := new(types.MyDecimal) err := dec.FromString(hack.Slice(str)) return dec, err } - ast.NewHexLiteral = func(str string) (interface{}, error) { + ast.NewHexLiteral = func(str string) (any, error) { h, err := types.NewHexLiteral(str) return h, err } - ast.NewBitLiteral = func(str string) (interface{}, error) { + ast.NewBitLiteral = func(str string) (any, error) { b, err := types.NewBitLiteral(str) return b, err } @@ -70,7 +70,7 @@ type ValueExpr struct { } // SetValue implements interface of ast.ValueExpr. -func (n *ValueExpr) SetValue(res interface{}) { +func (n *ValueExpr) SetValue(res any) { n.Datum.SetValueWithDefaultCollation(res) } @@ -168,7 +168,7 @@ func (n *ValueExpr) Format(w io.Writer) { } // newValueExpr creates a ValueExpr with value, and sets default field type. -func newValueExpr(value interface{}, charset string, collate string) ast.ValueExpr { +func newValueExpr(value any, charset string, collate string) ast.ValueExpr { if ve, ok := value.(*ValueExpr); ok { return ve } diff --git a/util/chunk/disk.go b/util/chunk/disk.go index f7ec0f745..d1c555b8b 100644 --- a/util/chunk/disk.go +++ b/util/chunk/disk.go @@ -35,11 +35,11 @@ const ( ) var bufWriterPool = sync.Pool{ - New: func() interface{} { return bufio.NewWriterSize(nil, writeBufSize) }, + New: func() any { return bufio.NewWriterSize(nil, writeBufSize) }, } var bufReaderPool = sync.Pool{ - New: func() interface{} { return bufio.NewReaderSize(nil, readBufSize) }, + New: func() any { return bufio.NewReaderSize(nil, readBufSize) }, } // ListInDisk represents a slice of chunks storing in temporary disk. diff --git a/util/chunk/mutrow.go b/util/chunk/mutrow.go index f0f2138cb..3fb268956 100644 --- a/util/chunk/mutrow.go +++ b/util/chunk/mutrow.go @@ -51,7 +51,7 @@ func (mr MutRow) Clone() MutRow { } // MutRowFromValues creates a MutRow from a interface slice. -func MutRowFromValues(vals ...interface{}) MutRow { +func MutRowFromValues(vals ...any) MutRow { c := &Chunk{columns: make([]*Column, 0, len(vals))} for _, val := range vals { col := makeMutRowColumn(val) @@ -80,7 +80,7 @@ func MutRowFromTypes(types []*types.FieldType) MutRow { return MutRow{c: c, idx: 0} } -func zeroValForType(tp *types.FieldType) interface{} { +func zeroValForType(tp *types.FieldType) any { switch tp.Tp { case mysql.TypeFloat: return float32(0) @@ -118,7 +118,7 @@ func zeroValForType(tp *types.FieldType) interface{} { } } -func makeMutRowColumn(in interface{}) *Column { +func makeMutRowColumn(in any) *Column { switch x := in.(type) { case nil: col := makeMutRowUint64Column(uint64(0)) @@ -229,14 +229,14 @@ func (mr MutRow) SetRow(row Row) { } // SetValues sets the MutRow with values. -func (mr MutRow) SetValues(vals ...interface{}) { +func (mr MutRow) SetValues(vals ...any) { for i, v := range vals { mr.SetValue(i, v) } } // SetValue sets the MutRow with colIdx and value. -func (mr MutRow) SetValue(colIdx int, val interface{}) { +func (mr MutRow) SetValue(colIdx int, val any) { col := mr.c.columns[colIdx] if val == nil { col.nullBitmap[0] = 0 diff --git a/util/chunk/mutrow_test.go b/util/chunk/mutrow_test.go index d55603ff8..8034d5ff9 100644 --- a/util/chunk/mutrow_test.go +++ b/util/chunk/mutrow_test.go @@ -137,7 +137,7 @@ func BenchmarkMutRowFromDatums(b *testing.B) { func BenchmarkMutRowFromValues(b *testing.B) { b.ReportAllocs() - values := []interface{}{1, "abc"} + values := []any{1, "abc"} for i := 0; i < b.N; i++ { MutRowFromValues(values) } diff --git a/util/chunk/pool.go b/util/chunk/pool.go index a378fbe4c..fca59a8c7 100644 --- a/util/chunk/pool.go +++ b/util/chunk/pool.go @@ -35,11 +35,11 @@ type Pool struct { func NewPool(initCap int) *Pool { return &Pool{ initCap: initCap, - varLenColPool: &sync.Pool{New: func() interface{} { return newVarLenColumn(initCap, nil) }}, - fixLenColPool4: &sync.Pool{New: func() interface{} { return newFixedLenColumn(4, initCap) }}, - fixLenColPool8: &sync.Pool{New: func() interface{} { return newFixedLenColumn(8, initCap) }}, - fixLenColPool16: &sync.Pool{New: func() interface{} { return newFixedLenColumn(16, initCap) }}, - fixLenColPool40: &sync.Pool{New: func() interface{} { return newFixedLenColumn(40, initCap) }}, + varLenColPool: &sync.Pool{New: func() any { return newVarLenColumn(initCap, nil) }}, + fixLenColPool4: &sync.Pool{New: func() any { return newFixedLenColumn(4, initCap) }}, + fixLenColPool8: &sync.Pool{New: func() any { return newFixedLenColumn(8, initCap) }}, + fixLenColPool16: &sync.Pool{New: func() any { return newFixedLenColumn(16, initCap) }}, + fixLenColPool40: &sync.Pool{New: func() any { return newFixedLenColumn(40, initCap) }}, } } diff --git a/util/codec/codec_test.go b/util/codec/codec_test.go index 560560935..192384560 100644 --- a/util/codec/codec_test.go +++ b/util/codec/codec_test.go @@ -663,8 +663,8 @@ func (s *testCodecSuite) TestDecimal(c *C) { } tblCmp := []struct { - Arg1 interface{} - Arg2 interface{} + Arg1 any + Arg2 any Ret int }{ // Test for float type decimal. @@ -956,7 +956,7 @@ func (s *testCodecSuite) TestDecodeOneToChunk(c *C) { func datumsForTest(sc *stmtctx.StatementContext) ([]types.Datum, []*types.FieldType) { table := []struct { - value interface{} + value any tp *types.FieldType }{ {nil, types.NewFieldType(mysql.TypeNull)}, @@ -1035,7 +1035,7 @@ func (s *testCodecSuite) TestDecodeRange(c *C) { } } -func testHashChunkRowEqual(c *C, a, b interface{}, equal bool) { +func testHashChunkRowEqual(c *C, a, b any, equal bool) { sc := &stmtctx.StatementContext{TimeZone: time.Local} buf1 := make([]byte, 1) buf2 := make([]byte, 1) diff --git a/util/expensivequery/expensivequerey_test.go b/util/expensivequery/expensivequerey_test.go index 066db5873..8e2dbda04 100644 --- a/util/expensivequery/expensivequerey_test.go +++ b/util/expensivequery/expensivequerey_test.go @@ -47,7 +47,7 @@ func (s *testSuite) TestLogFormat(c *C) { DB: "Database", Info: "select * from table where a > 1", CurTxnStartTS: 23333, - StatsInfo: func(interface{}) map[string]uint64 { + StatsInfo: func(any) map[string]uint64 { return nil }, StmtCtx: &stmtctx.StatementContext{ diff --git a/util/filesort/filesort.go b/util/filesort/filesort.go index 509ab0f87..271ffd2fb 100644 --- a/util/filesort/filesort.go +++ b/util/filesort/filesort.go @@ -94,12 +94,12 @@ func (rh *rowHeap) Less(i, j int) bool { } // Push pushes an element into rowHeap. -func (rh *rowHeap) Push(x interface{}) { +func (rh *rowHeap) Push(x any) { rh.ims = append(rh.ims, x.(*item)) } // Pop pops the last element from rowHeap. -func (rh *rowHeap) Pop() interface{} { +func (rh *rowHeap) Pop() any { old := rh.ims n := len(old) x := old[n-1] diff --git a/util/format/format.go b/util/format/format.go index 0a14a6d36..255953b1d 100644 --- a/util/format/format.go +++ b/util/format/format.go @@ -33,7 +33,7 @@ const ( // Formatter is an io.Writer extended formatter by a fmt.Printf like function Format. type Formatter interface { io.Writer - Format(format string, args ...interface{}) (n int, errno error) + Format(format string, args ...any) (n int, errno error) } type indentFormatter struct { @@ -55,26 +55,33 @@ var replace = map[rune]string{ // nest. The Formatter writes to io.Writer 'w' and inserts one 'indent' // string per current indent level value. // Behaviour of commands reaching negative indent levels is undefined. -// IndentFormatter(os.Stdout, "\t").Format("abc%d%%e%i\nx\ny\n%uz\n", 3) +// +// IndentFormatter(os.Stdout, "\t").Format("abc%d%%e%i\nx\ny\n%uz\n", 3) +// // output: -// abc3%e -// x -// y -// z +// +// abc3%e +// x +// y +// z +// // The Go quoted string literal form of the above is: -// "abc%%e\n\tx\n\tx\nz\n" +// +// "abc%%e\n\tx\n\tx\nz\n" +// // The commands can be scattered between separate invocations of Format(), // i.e. the formatter keeps track of the indent level and knows if it is // positioned on start of a line and should emit indentation(s). // The same output as above can be produced by e.g.: -// f := IndentFormatter(os.Stdout, " ") -// f.Format("abc%d%%e%i\nx\n", 3) -// f.Format("y\n%uz\n") +// +// f := IndentFormatter(os.Stdout, " ") +// f.Format("abc%d%%e%i\nx\n", 3) +// f.Format("y\n%uz\n") func IndentFormatter(w io.Writer, indent string) Formatter { return &indentFormatter{w, []byte(indent), 0, stBOL} } -func (f *indentFormatter) format(flat bool, format string, args ...interface{}) (n int, errno error) { +func (f *indentFormatter) format(flat bool, format string, args ...any) (n int, errno error) { var buf = make([]byte, 0) for i := 0; i < len(format); i++ { c := format[i] @@ -153,7 +160,7 @@ func (f *indentFormatter) format(flat bool, format string, args ...interface{}) } // Format implements Format interface. -func (f *indentFormatter) Format(format string, args ...interface{}) (n int, errno error) { +func (f *indentFormatter) Format(format string, args ...any) (n int, errno error) { return f.format(false, format, args...) } @@ -168,15 +175,18 @@ type flatFormatter indentFormatter // // The FlatFormatter is intended for flattening of normally nested structure textual representation to // a one top level structure per line form. -// FlatFormatter(os.Stdout, " ").Format("abc%d%%e%i\nx\ny\n%uz\n", 3) +// +// FlatFormatter(os.Stdout, " ").Format("abc%d%%e%i\nx\ny\n%uz\n", 3) +// // output in the form of a Go quoted string literal: -// "abc3%%e x y z\n" +// +// "abc3%%e x y z\n" func FlatFormatter(w io.Writer) Formatter { return (*flatFormatter)(IndentFormatter(w, "").(*indentFormatter)) } // Format implements Format interface. -func (f *flatFormatter) Format(format string, args ...interface{}) (n int, errno error) { +func (f *flatFormatter) Format(format string, args ...any) (n int, errno error) { return (*indentFormatter)(f).format(true, format, args...) } diff --git a/util/localpool/localpool.go b/util/localpool/localpool.go index 0f77e6f02..cbfe12da5 100644 --- a/util/localpool/localpool.go +++ b/util/localpool/localpool.go @@ -25,12 +25,12 @@ import ( type LocalPool struct { sizePerProc int slots []*slot - newFn func() interface{} - resetFn func(obj interface{}) + newFn func() any + resetFn func(obj any) } type slot struct { - objs []interface{} + objs []any getHit int getMiss int putHit int @@ -42,11 +42,11 @@ type slot struct { // It can only be used when the GOMAXPROCS never change after the pool created. // newFn is the function to create a new object. // resetFn is the function called before put back to the pool, it can be nil. -func NewLocalPool(sizePerProc int, newFn func() interface{}, resetFn func(obj interface{})) *LocalPool { +func NewLocalPool(sizePerProc int, newFn func() any, resetFn func(obj any)) *LocalPool { slots := make([]*slot, runtime.GOMAXPROCS(0)) for i := 0; i < len(slots); i++ { slots[i] = &slot{ - objs: make([]interface{}, 0, sizePerProc), + objs: make([]any, 0, sizePerProc), } } return &LocalPool{ diff --git a/util/localpool/localpool_norace.go b/util/localpool/localpool_norace.go index c509ae5c5..22b68c812 100644 --- a/util/localpool/localpool_norace.go +++ b/util/localpool/localpool_norace.go @@ -11,16 +11,17 @@ // See the License for the specific language governing permissions and // limitations under the License. +//go:build !race // +build !race package localpool // Get gets an object from the pool. -func (p *LocalPool) Get() interface{} { +func (p *LocalPool) Get() any { pid := procPin() slot := p.slots[pid] objLen := len(slot.objs) - var result interface{} + var result any if objLen > 0 { lastIdx := objLen - 1 result = slot.objs[lastIdx] @@ -39,7 +40,7 @@ func (p *LocalPool) Get() interface{} { // Put puts an object back to the pool. // It returns true if the pool is not full and the obj is successfully put into the pool. -func (p *LocalPool) Put(obj interface{}) bool { +func (p *LocalPool) Put(obj any) bool { if p.resetFn != nil { p.resetFn(obj) } diff --git a/util/localpool/localpool_race.go b/util/localpool/localpool_race.go index e204557d0..c82f1de94 100644 --- a/util/localpool/localpool_race.go +++ b/util/localpool/localpool_race.go @@ -11,16 +11,17 @@ // See the License for the specific language governing permissions and // limitations under the License. +//go:build race // +build race package localpool // Get gets an object from the pool. -func (p *LocalPool) Get() interface{} { +func (p *LocalPool) Get() any { return p.newFn() } // Put puts an object back to the pool. -func (p *LocalPool) Put(obj interface{}) bool { +func (p *LocalPool) Put(obj any) bool { return false } diff --git a/util/localpool/localpool_test.go b/util/localpool/localpool_test.go index fc62c8058..8ade9e30a 100644 --- a/util/localpool/localpool_test.go +++ b/util/localpool/localpool_test.go @@ -11,6 +11,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +//go:build !race // +build !race package localpool @@ -41,7 +42,7 @@ func (s *testPoolSuite) TestPool(c *C) { numWorkers := runtime.GOMAXPROCS(0) wg := new(sync.WaitGroup) wg.Add(numWorkers) - pool := NewLocalPool(16, func() interface{} { + pool := NewLocalPool(16, func() any { return new(Obj) }, nil) n := 1000 @@ -66,7 +67,7 @@ func (s *testPoolSuite) TestPool(c *C) { } func GetAndPut(pool *LocalPool) { - objs := make([]interface{}, rand.Intn(4)+1) + objs := make([]any, rand.Intn(4)+1) for i := 0; i < len(objs); i++ { objs[i] = pool.Get() } diff --git a/util/logutil/log.go b/util/logutil/log.go index 49429c70a..bfca84e3d 100644 --- a/util/logutil/log.go +++ b/util/logutil/log.go @@ -377,14 +377,14 @@ func Event(ctx context.Context, event string) { } // Eventf records event in current tracing span with format support. -func Eventf(ctx context.Context, format string, args ...interface{}) { +func Eventf(ctx context.Context, format string, args ...any) { if span := opentracing.SpanFromContext(ctx); span != nil && span.Tracer() != nil { span.LogFields(tlog.String(TraceEventKey, fmt.Sprintf(format, args...))) } } // SetTag sets tag kv-pair in current tracing span -func SetTag(ctx context.Context, key string, value interface{}) { +func SetTag(ctx context.Context, key string, value any) { if span := opentracing.SpanFromContext(ctx); span != nil && span.Tracer() != nil { span.SetTag(key, value) } diff --git a/util/misc.go b/util/misc.go index 1abc7eb26..e20b51b6b 100644 --- a/util/misc.go +++ b/util/misc.go @@ -76,9 +76,10 @@ func GetStack() []byte { // WithRecovery wraps goroutine startup call with force recovery. // it will dump current goroutine stack into log if catch any recover result. -// exec: execute logic function. -// recoverFn: handler will be called after recover and before dump stack, passing `nil` means noop. -func WithRecovery(exec func(), recoverFn func(r interface{})) { +// +// exec: execute logic function. +// recoverFn: handler will be called after recover and before dump stack, passing `nil` means noop. +func WithRecovery(exec func(), recoverFn func(r any)) { defer func() { r := recover() if recoverFn != nil { @@ -351,8 +352,8 @@ type SequenceSchema interface { // Otherwise calling table will cause import cycle problem. type SequenceTable interface { GetSequenceID() int64 - GetSequenceNextVal(ctx interface{}, dbName, seqName string) (int64, error) - SetSequenceVal(ctx interface{}, newVal int64, dbName, seqName string) (int64, bool, error) + GetSequenceNextVal(ctx any, dbName, seqName string) (int64, error) + SetSequenceVal(ctx any, newVal int64, dbName, seqName string) (int64, bool, error) } // LoadTLSCertificates loads CA/KEY/CERT for special paths. diff --git a/util/misc_test.go b/util/misc_test.go index 30a9a52f5..5cb883817 100644 --- a/util/misc_test.go +++ b/util/misc_test.go @@ -148,10 +148,10 @@ func (s *testMiscSuite) TestBasicFunc(c *C) { c.Assert(len(b) < 4096, IsTrue) // Test for WithRecovery. - var recover interface{} + var recover any WithRecovery(func() { panic("test") - }, func(r interface{}) { + }, func(r any) { recover = r }) c.Assert(recover, Equals, "test") diff --git a/util/mock/context.go b/util/mock/context.go index aa16b35d8..b1735f04d 100644 --- a/util/mock/context.go +++ b/util/mock/context.go @@ -39,7 +39,7 @@ var _ sqlexec.SQLExecutor = (*Context)(nil) // Context represents mocked sessionctx.Context. type Context struct { - values map[fmt.Stringer]interface{} + values map[fmt.Stringer]any txn wrapTxn // mock global variable Store kv.Storage // mock global variable sessionVars *variable.SessionVars @@ -77,12 +77,12 @@ func (c *Context) DDLOwnerChecker() owner.DDLOwnerChecker { } // SetValue implements sessionctx.Context SetValue interface. -func (c *Context) SetValue(key fmt.Stringer, value interface{}) { +func (c *Context) SetValue(key fmt.Stringer, value any) { c.values[key] = value } // Value implements sessionctx.Context Value interface. -func (c *Context) Value(key fmt.Stringer) interface{} { +func (c *Context) Value(key fmt.Stringer) any { value := c.values[key] return value } @@ -205,7 +205,7 @@ func (c *Context) GoCtx() context.Context { } // StoreQueryFeedback stores the query feedback. -func (c *Context) StoreQueryFeedback(_ interface{}) {} +func (c *Context) StoreQueryFeedback(_ any) {} // StmtCommit implements the sessionctx.Context interface. func (c *Context) StmtCommit(tracker *memory.Tracker) error { @@ -268,7 +268,7 @@ func (c *Context) Close() { func NewContext() *Context { ctx, cancel := context.WithCancel(context.Background()) sctx := &Context{ - values: make(map[fmt.Stringer]interface{}), + values: make(map[fmt.Stringer]any), sessionVars: variable.NewSessionVars(), ctx: ctx, cancel: cancel, diff --git a/util/mock/store.go b/util/mock/store.go index 032201713..4e746e4ab 100644 --- a/util/mock/store.go +++ b/util/mock/store.go @@ -61,4 +61,4 @@ func (s *Store) Describe() string { } // ShowStatus implements kv.Storage interface. -func (s *Store) ShowStatus(ctx context.Context, key string) (interface{}, error) { return nil, nil } +func (s *Store) ShowStatus(ctx context.Context, key string) (any, error) { return nil, nil } diff --git a/util/plancodec/codec.go b/util/plancodec/codec.go index 971bb94d8..129fd7081 100644 --- a/util/plancodec/codec.go +++ b/util/plancodec/codec.go @@ -39,7 +39,7 @@ const ( ) var decoderPool = sync.Pool{ - New: func() interface{} { + New: func() any { return &planDecoder{} }, } diff --git a/util/prefix_helper_test.go b/util/prefix_helper_test.go index 2c0543406..de07677d9 100644 --- a/util/prefix_helper_test.go +++ b/util/prefix_helper_test.go @@ -63,16 +63,16 @@ func encodeInt(n int) []byte { type MockContext struct { prefix int - values map[fmt.Stringer]interface{} + values map[fmt.Stringer]any kv.Storage txn kv.Transaction } -func (c *MockContext) SetValue(key fmt.Stringer, value interface{}) { +func (c *MockContext) SetValue(key fmt.Stringer, value any) { c.values[key] = value } -func (c *MockContext) Value(key fmt.Stringer) interface{} { +func (c *MockContext) Value(key fmt.Stringer) any { value := c.values[key] return value } @@ -116,7 +116,7 @@ func (c *MockContext) CommitTxn() error { } func (s *testPrefixSuite) TestPrefix(c *C) { - ctx := &MockContext{10000000, make(map[fmt.Stringer]interface{}), s.s, nil} + ctx := &MockContext{10000000, make(map[fmt.Stringer]any), s.s, nil} ctx.fillTxn() txn, err := ctx.GetTxn(false) c.Assert(err, IsNil) diff --git a/util/processinfo.go b/util/processinfo.go index 79a3e6ec4..7e2d0b20d 100644 --- a/util/processinfo.go +++ b/util/processinfo.go @@ -30,12 +30,12 @@ type ProcessInfo struct { User string Host string DB string - Plan interface{} + Plan any Time time.Time Info string CurTxnStartTS uint64 StmtCtx *stmtctx.StatementContext - StatsInfo func(interface{}) map[string]uint64 + StatsInfo func(any) map[string]uint64 // MaxExecutionTime is the timeout for select statement, in milliseconds. // If the query takes too long, kill it. MaxExecutionTime uint64 @@ -46,8 +46,8 @@ type ProcessInfo struct { } // ToRowForShow returns []interface{} for the row data of "SHOW [FULL] PROCESSLIST". -func (pi *ProcessInfo) ToRowForShow(full bool) []interface{} { - var info interface{} +func (pi *ProcessInfo) ToRowForShow(full bool) []any { + var info any if len(pi.Info) > 0 { if full { info = pi.Info @@ -56,11 +56,11 @@ func (pi *ProcessInfo) ToRowForShow(full bool) []interface{} { } } t := uint64(time.Since(pi.Time) / time.Second) - var db interface{} + var db any if len(pi.DB) > 0 { db = pi.DB } - return []interface{}{ + return []any{ pi.ID, pi.User, pi.Host, @@ -82,7 +82,7 @@ func (pi *ProcessInfo) txnStartTs(tz *time.Location) (txnStart string) { // ToRow returns []interface{} for the row data of // "SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST". -func (pi *ProcessInfo) ToRow(tz *time.Location) []interface{} { +func (pi *ProcessInfo) ToRow(tz *time.Location) []any { bytesConsumed := int64(0) if pi.StmtCtx != nil && pi.StmtCtx.MemTracker != nil { bytesConsumed = pi.StmtCtx.MemTracker.BytesConsumed() diff --git a/util/stmtsummary/statement_summary.go b/util/stmtsummary/statement_summary.go index 12558adae..0d64d3981 100644 --- a/util/stmtsummary/statement_summary.go +++ b/util/stmtsummary/statement_summary.go @@ -833,7 +833,7 @@ func formatSQL(sql string) string { } // Format the backoffType map to a string or nil. -func formatBackoffTypes(backoffMap map[fmt.Stringer]int) interface{} { +func formatBackoffTypes(backoffMap map[fmt.Stringer]int) any { type backoffStat struct { backoffType fmt.Stringer count int @@ -878,7 +878,7 @@ func avgFloat(sum int64, count int64) float64 { return 0 } -func convertEmptyToNil(str string) interface{} { +func convertEmptyToNil(str string) any { if str == "" { return nil } diff --git a/util/stmtsummary/statement_summary_test.go b/util/stmtsummary/statement_summary_test.go index 1f08ecd9e..aa73d5b8c 100644 --- a/util/stmtsummary/statement_summary_test.go +++ b/util/stmtsummary/statement_summary_test.go @@ -497,7 +497,7 @@ func matchStmtSummaryByDigest(first, second *stmtSummaryByDigest) bool { return true } -func match(c *C, row []types.Datum, expected ...interface{}) { +func match(c *C, row []types.Datum, expected ...any) { c.Assert(len(row), Equals, len(expected)) for i := range row { got := fmt.Sprintf("%v", row[i].GetValue()) @@ -585,7 +585,7 @@ func (s *testStmtSummarySuite) TestToDatum(c *C) { n := types.NewTime(types.FromGoTime(time.Unix(s.ssMap.beginTimeForCurInterval, 0)), mysql.TypeTimestamp, types.DefaultFsp) e := types.NewTime(types.FromGoTime(time.Unix(s.ssMap.beginTimeForCurInterval+1800, 0)), mysql.TypeTimestamp, types.DefaultFsp) t := types.NewTime(types.FromGoTime(stmtExecInfo1.StartTime), mysql.TypeTimestamp, types.DefaultFsp) - expectedDatum := []interface{}{n, e, "select", stmtExecInfo1.SchemaName, stmtExecInfo1.Digest, stmtExecInfo1.NormalizedSQL, + expectedDatum := []any{n, e, "select", stmtExecInfo1.SchemaName, stmtExecInfo1.Digest, stmtExecInfo1.NormalizedSQL, "db1.tb1,db2.tb2", "a", stmtExecInfo1.User, 1, 0, 0, int64(stmtExecInfo1.TotalLatency), int64(stmtExecInfo1.TotalLatency), int64(stmtExecInfo1.TotalLatency), int64(stmtExecInfo1.TotalLatency), int64(stmtExecInfo1.ParseLatency), int64(stmtExecInfo1.ParseLatency), int64(stmtExecInfo1.CompileLatency), diff --git a/util/testkit/ctestkit.go b/util/testkit/ctestkit.go index d3f936886..ed60b0dbb 100644 --- a/util/testkit/ctestkit.go +++ b/util/testkit/ctestkit.go @@ -11,6 +11,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +//go:build !codes // +build !codes package testkit @@ -86,7 +87,7 @@ func (tk *CTestKit) CloseSession(ctx context.Context) { } // Exec executes a sql statement. -func (tk *CTestKit) Exec(ctx context.Context, sql string, args ...interface{}) (sqlexec.RecordSet, error) { +func (tk *CTestKit) Exec(ctx context.Context, sql string, args ...any) (sqlexec.RecordSet, error) { var err error tk.c.Assert(getSession(ctx), check.NotNil) if len(args) == 0 { @@ -124,7 +125,7 @@ func (tk *CTestKit) CheckExecResult(ctx context.Context, affectedRows, insertID } // MustExec executes a sql statement and asserts nil error. -func (tk *CTestKit) MustExec(ctx context.Context, sql string, args ...interface{}) { +func (tk *CTestKit) MustExec(ctx context.Context, sql string, args ...any) { res, err := tk.Exec(ctx, sql, args...) tk.c.Assert(err, check.IsNil, check.Commentf("sql:%s, %v, error stack %v", sql, args, errors.ErrorStack(err))) if res != nil { @@ -134,7 +135,7 @@ func (tk *CTestKit) MustExec(ctx context.Context, sql string, args ...interface{ // MustQuery query the statements and returns result rows. // If expected result is set it asserts the query result equals expected result. -func (tk *CTestKit) MustQuery(ctx context.Context, sql string, args ...interface{}) *Result { +func (tk *CTestKit) MustQuery(ctx context.Context, sql string, args ...any) *Result { comment := check.Commentf("sql:%s, args:%v", sql, args) rs, err := tk.Exec(ctx, sql, args...) tk.c.Assert(errors.ErrorStack(err), check.Equals, "", comment) @@ -175,17 +176,17 @@ func (tk *CTestKit) resultSetToResult(ctx context.Context, rs sqlexec.RecordSet, // works like create table better be put in front of this method calling. // see more example at TestBatchInsertWithOnDuplicate func (tk *CTestKit) ConcurrentRun(c *check.C, concurrent int, loops int, - prepareFunc func(ctx context.Context, tk *CTestKit, concurrent int, currentLoop int) [][][]interface{}, - writeFunc func(ctx context.Context, tk *CTestKit, input [][]interface{}), + prepareFunc func(ctx context.Context, tk *CTestKit, concurrent int, currentLoop int) [][][]any, + writeFunc func(ctx context.Context, tk *CTestKit, input [][]any), checkFunc func(ctx context.Context, tk *CTestKit)) { var ( - channel = make([]chan [][]interface{}, concurrent) + channel = make([]chan [][]any, concurrent) ctxs = make([]context.Context, concurrent) dones = make([]context.CancelFunc, concurrent) ) for i := 0; i < concurrent; i++ { w := i - channel[w] = make(chan [][]interface{}, 1) + channel[w] = make(chan [][]any, 1) ctxs[w], dones[w] = context.WithCancel(context.Background()) ctxs[w] = tk.OpenSessionWithDB(ctxs[w], "test") go func() { @@ -229,9 +230,9 @@ func (tk *CTestKit) ConcurrentRun(c *check.C, concurrent int, loops int, } // PermInt returns, as a slice of n ints, a pseudo-random permutation of the integers [0,n). -func (tk *CTestKit) PermInt(n int) []interface{} { +func (tk *CTestKit) PermInt(n int) []any { randPermSlice := rand.Perm(n) - v := make([]interface{}, 0, len(randPermSlice)) + v := make([]any, 0, len(randPermSlice)) for _, i := range randPermSlice { v = append(v, i) } diff --git a/util/testkit/testkit.go b/util/testkit/testkit.go index cd7c38938..8ecd8f8f2 100644 --- a/util/testkit/testkit.go +++ b/util/testkit/testkit.go @@ -11,6 +11,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +//go:build !codes // +build !codes package testkit @@ -50,7 +51,7 @@ type Result struct { } // Check asserts the result equals the expected results. -func (res *Result) Check(expected [][]interface{}) { +func (res *Result) Check(expected [][]any) { resBuff := bytes.NewBufferString("") for _, row := range res.rows { fmt.Fprintf(resBuff, "%s\n", row) @@ -63,7 +64,7 @@ func (res *Result) Check(expected [][]interface{}) { } // CheckAt asserts the result of selected columns equals the expected results. -func (res *Result) CheckAt(cols []int, expected [][]interface{}) { +func (res *Result) CheckAt(cols []int, expected [][]any) { for _, e := range expected { res.c.Assert(len(cols), check.Equals, len(e)) } @@ -82,10 +83,10 @@ func (res *Result) CheckAt(cols []int, expected [][]interface{}) { } // Rows returns the result data. -func (res *Result) Rows() [][]interface{} { - ifacesSlice := make([][]interface{}, len(res.rows)) +func (res *Result) Rows() [][]any { + ifacesSlice := make([][]any, len(res.rows)) for i := range res.rows { - ifaces := make([]interface{}, len(res.rows[i])) + ifaces := make([]any, len(res.rows[i])) for j := range res.rows[i] { ifaces[j] = res.rows[i][j] } @@ -130,7 +131,7 @@ func NewTestKitWithInit(c *check.C, store kv.Storage) *TestKit { var connectionID uint64 // Exec executes a sql statement. -func (tk *TestKit) Exec(sql string, args ...interface{}) (sqlexec.RecordSet, error) { +func (tk *TestKit) Exec(sql string, args ...any) (sqlexec.RecordSet, error) { var err error if tk.Se == nil { tk.Se, err = session.CreateSession4Test(tk.store) @@ -178,7 +179,7 @@ func (tk *TestKit) CheckLastMessage(msg string) { } // MustExec executes a sql statement and asserts nil error. -func (tk *TestKit) MustExec(sql string, args ...interface{}) { +func (tk *TestKit) MustExec(sql string, args ...any) { res, err := tk.Exec(sql, args...) tk.c.Assert(err, check.IsNil, check.Commentf("sql:%s, %v, error stack %v", sql, args, errors.ErrorStack(err))) if res != nil { @@ -187,7 +188,7 @@ func (tk *TestKit) MustExec(sql string, args ...interface{}) { } // HasPlan checks if the result execution plan contains specific plan. -func (tk *TestKit) HasPlan(sql string, plan string, args ...interface{}) bool { +func (tk *TestKit) HasPlan(sql string, plan string, args ...any) bool { rs := tk.MustQuery("explain "+sql, args...) for i := range rs.rows { if strings.Contains(rs.rows[i][0], plan) { @@ -198,7 +199,7 @@ func (tk *TestKit) HasPlan(sql string, plan string, args ...interface{}) bool { } // MustUseIndex checks if the result execution plan contains specific index(es). -func (tk *TestKit) MustUseIndex(sql string, index string, args ...interface{}) bool { +func (tk *TestKit) MustUseIndex(sql string, index string, args ...any) bool { rs := tk.MustQuery("explain "+sql, args...) for i := range rs.rows { if strings.Contains(rs.rows[i][3], "index:"+index) { @@ -209,19 +210,19 @@ func (tk *TestKit) MustUseIndex(sql string, index string, args ...interface{}) b } // MustIndexLookup checks whether the plan for the sql is IndexLookUp. -func (tk *TestKit) MustIndexLookup(sql string, args ...interface{}) *Result { +func (tk *TestKit) MustIndexLookup(sql string, args ...any) *Result { tk.c.Assert(tk.HasPlan(sql, "IndexLookUp", args...), check.IsTrue) return tk.MustQuery(sql, args...) } // MustTableDual checks whether the plan for the sql is TableDual. -func (tk *TestKit) MustTableDual(sql string, args ...interface{}) *Result { +func (tk *TestKit) MustTableDual(sql string, args ...any) *Result { tk.c.Assert(tk.HasPlan(sql, "TableDual", args...), check.IsTrue) return tk.MustQuery(sql, args...) } // MustPointGet checks whether the plan for the sql is Point_Get. -func (tk *TestKit) MustPointGet(sql string, args ...interface{}) *Result { +func (tk *TestKit) MustPointGet(sql string, args ...any) *Result { rs := tk.MustQuery("explain "+sql, args...) tk.c.Assert(len(rs.rows), check.Equals, 1) tk.c.Assert(strings.Contains(rs.rows[0][0], "Point_Get"), check.IsTrue, check.Commentf("plan %v", rs.rows[0][0])) @@ -230,7 +231,7 @@ func (tk *TestKit) MustPointGet(sql string, args ...interface{}) *Result { // MustQuery query the statements and returns result rows. // If expected result is set it asserts the query result equals expected result. -func (tk *TestKit) MustQuery(sql string, args ...interface{}) *Result { +func (tk *TestKit) MustQuery(sql string, args ...any) *Result { comment := check.Commentf("sql:%s, args:%v", sql, args) rs, err := tk.Exec(sql, args...) tk.c.Assert(errors.ErrorStack(err), check.Equals, "", comment) @@ -239,7 +240,7 @@ func (tk *TestKit) MustQuery(sql string, args ...interface{}) *Result { } // QueryToErr executes a sql statement and discard results. -func (tk *TestKit) QueryToErr(sql string, args ...interface{}) error { +func (tk *TestKit) QueryToErr(sql string, args ...any) error { comment := check.Commentf("sql:%s, args:%v", sql, args) res, err := tk.Exec(sql, args...) tk.c.Assert(errors.ErrorStack(err), check.Equals, "", comment) @@ -250,7 +251,7 @@ func (tk *TestKit) QueryToErr(sql string, args ...interface{}) error { } // ExecToErr executes a sql statement and discard results. -func (tk *TestKit) ExecToErr(sql string, args ...interface{}) error { +func (tk *TestKit) ExecToErr(sql string, args ...any) error { res, err := tk.Exec(sql, args...) if res != nil { tk.c.Assert(res.Close(), check.IsNil) @@ -290,7 +291,7 @@ func (tk *TestKit) ResultSetToResultWithCtx(ctx context.Context, rs sqlexec.Reco } // Rows is similar to RowsWithSep, use white space as separator string. -func Rows(args ...string) [][]interface{} { +func Rows(args ...string) [][]any { return testutil.RowsWithSep(" ", args...) } diff --git a/util/testutil/testutil.go b/util/testutil/testutil.go index b36578e9d..9304827d1 100644 --- a/util/testutil/testutil.go +++ b/util/testutil/testutil.go @@ -11,6 +11,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +//go:build !codes // +build !codes package testutil @@ -83,12 +84,13 @@ type datumEqualsChecker struct { // DatumEquals checker verifies that the obtained value is equal to // the expected value. // For example: -// c.Assert(value, DatumEquals, NewDatum(42)) +// +// c.Assert(value, DatumEquals, NewDatum(42)) var DatumEquals check.Checker = &datumEqualsChecker{ &check.CheckerInfo{Name: "DatumEquals", Params: []string{"obtained", "expected"}}, } -func (checker *datumEqualsChecker) Check(params []interface{}, names []string) (result bool, error string) { +func (checker *datumEqualsChecker) Check(params []any, names []string) (result bool, error string) { defer func() { if v := recover(); v != nil { result = false @@ -116,11 +118,11 @@ func (checker *datumEqualsChecker) Check(params []interface{}, names []string) ( // RowsWithSep is a convenient function to wrap args to a slice of []interface. // The arg represents a row, split by sep. -func RowsWithSep(sep string, args ...string) [][]interface{} { - rows := make([][]interface{}, len(args)) +func RowsWithSep(sep string, args ...string) [][]any { + rows := make([][]any, len(args)) for i, v := range args { strs := strings.Split(v, sep) - row := make([]interface{}, len(strs)) + row := make([]any, len(strs)) for j, s := range strs { row[j] = s } @@ -139,7 +141,7 @@ func init() { type testCases struct { Name string Cases *json.RawMessage // For delayed parse. - decodedOut interface{} // For generate output. + decodedOut any // For generate output. } // TestData stores all the data of a test suite. @@ -202,7 +204,7 @@ func loadTestSuiteCases(filePath string) (res []testCases, err error) { } // GetTestCasesByName gets the test cases for a test function by its name. -func (t *TestData) GetTestCasesByName(caseName string, c *check.C, in interface{}, out interface{}) { +func (t *TestData) GetTestCasesByName(caseName string, c *check.C, in any, out any) { casesIdx, ok := t.funcMap[caseName] c.Assert(ok, check.IsTrue, check.Commentf("Must get test %s", caseName)) err := json.Unmarshal(*t.input[casesIdx].Cases, in) @@ -222,7 +224,7 @@ func (t *TestData) GetTestCasesByName(caseName string, c *check.C, in interface{ } // GetTestCases gets the test cases for a test function. -func (t *TestData) GetTestCases(c *check.C, in interface{}, out interface{}) { +func (t *TestData) GetTestCases(c *check.C, in any, out any) { // Extract caller's name. pc, _, _, ok := runtime.Caller(1) c.Assert(ok, check.IsTrue) @@ -256,7 +258,7 @@ func (t *TestData) OnRecord(updateFunc func()) { } // ConvertRowsToStrings converts [][]interface{} to []string. -func (t *TestData) ConvertRowsToStrings(rows [][]interface{}) (rs []string) { +func (t *TestData) ConvertRowsToStrings(rows [][]any) (rs []string) { for _, row := range rows { s := fmt.Sprintf("%v", row) // Trim the leftmost `[` and rightmost `]`.