Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issues found by golangci-lint #22754

Closed
ngaut opened this issue Feb 6, 2021 · 4 comments
Closed

Issues found by golangci-lint #22754

ngaut opened this issue Feb 6, 2021 · 4 comments
Labels
help wanted Denotes an issue that needs help from a contributor. Must meet "help wanted" guidelines. type/enhancement The issue or PR belongs to an enhancement.

Comments

@ngaut
Copy link
Member

ngaut commented Feb 6, 2021

Development Task

 tidb git:(5d27db31d) ✗ golangci-lint run  --timeout=600s ./...
executor/seqtest/prepared_test.go:162:10: Error return value of `tk.Exec` is not checked (errcheck)
		tk.Exec("create table prepare2 (a int)")
		       ^
executor/seqtest/prepared_test.go:255:12: Error return value of `exec.Next` is not checked (errcheck)
		exec.Next(ctx, nil)
		         ^
executor/seqtest/prepared_test.go:450:17: Error return value of `counter.Write` is not checked (errcheck)
			counter.Write(pb)
			             ^
executor/seqtest/prepared_test.go:456:17: Error return value of `counter.Write` is not checked (errcheck)
			counter.Write(pb)
			             ^
executor/seqtest/prepared_test.go:462:17: Error return value of `counter.Write` is not checked (errcheck)
			counter.Write(pb)
			             ^
executor/seqtest/seq_executor_test.go:68:20: Error return value of `logutil.InitLogger` is not checked (errcheck)
	logutil.InitLogger(logutil.NewLogConfig(logLevel, logutil.DefaultLogFormat, "", logutil.EmptyFileLogConfig, false))
	                  ^
executor/seqtest/seq_executor_test.go:665:37: Error return value of `(*github.com/pingcap/tidb/statistics/handle.Handle).DumpStatsDeltaToKV` is not checked (errcheck)
	do.StatsHandle().DumpStatsDeltaToKV(handle.DumpAll)
	                                   ^
executor/seqtest/seq_executor_test.go:669:37: Error return value of `(*github.com/pingcap/tidb/statistics/handle.Handle).DumpStatsDeltaToKV` is not checked (errcheck)
	do.StatsHandle().DumpStatsDeltaToKV(handle.DumpAll)
	                                   ^
executor/seqtest/seq_executor_test.go:670:25: Error return value of `(*github.com/pingcap/tidb/statistics/handle.Handle).Update` is not checked (errcheck)
	do.StatsHandle().Update(do.InfoSchema())
	                       ^
executor/seqtest/seq_executor_test.go:675:37: Error return value of `(*github.com/pingcap/tidb/statistics/handle.Handle).DumpStatsDeltaToKV` is not checked (errcheck)
	do.StatsHandle().DumpStatsDeltaToKV(handle.DumpAll)
	                                   ^
executor/seqtest/seq_executor_test.go:676:25: Error return value of `(*github.com/pingcap/tidb/statistics/handle.Handle).Update` is not checked (errcheck)
	do.StatsHandle().Update(do.InfoSchema())
	                       ^
executor/seqtest/seq_executor_test.go:782:17: Error return value of `profile.WriteTo` is not checked (errcheck)
	profile.WriteTo(buf, 1)
	               ^
executor/seqtest/seq_executor_test.go:84:2: `ctx` is unused (structcheck)
	ctx *mock.Context
	^
plugin/conn_ip_example/conn_ip_example.go:25:6: `Validate` is unused (deadcode)
func Validate(ctx context.Context, m *plugin.Manifest) error {
     ^
plugin/conn_ip_example/conn_ip_example.go:31:6: `OnInit` is unused (deadcode)
func OnInit(ctx context.Context, manifest *plugin.Manifest) error {
     ^
plugin/conn_ip_example/conn_ip_example.go:38:6: `OnShutdown` is unused (deadcode)
func OnShutdown(ctx context.Context, manifest *plugin.Manifest) error {
     ^
plugin/conn_ip_example/conn_ip_example.go:44:6: `OnGeneralEvent` is unused (deadcode)
func OnGeneralEvent(ctx context.Context, sctx *variable.SessionVars, event plugin.GeneralEvent, cmd string) {
     ^
plugin/conn_ip_example/conn_ip_example.go:51:6: `OnConnectionEvent` is unused (deadcode)
func OnConnectionEvent(ctx context.Context, event plugin.ConnectionEvent, info *variable.ConnectionInfo) error {
     ^
planner/core/common_plans.go:1318:6: `buildSchemaAndNameFromIndex` is unused (deadcode)
func buildSchemaAndNameFromIndex(cols []*expression.Column, dbName model.CIStr, tblInfo *model.TableInfo, idxInfo *model.IndexInfo) (*expression.Schema, types.NameSlice) {
     ^
planner/core/common_plans.go:1335:6: `buildSchemaAndNameFromPKCol` is unused (deadcode)
func buildSchemaAndNameFromPKCol(pkCol *expression.Column, dbName model.CIStr, tblInfo *model.TableInfo) (*expression.Schema, types.NameSlice) {
     ^
planner/core/common_plans.go:1350:6: `locateHashPartition` is unused (deadcode)
func locateHashPartition(ctx sessionctx.Context, expr expression.Expression, pi *model.PartitionInfo, r []types.Datum) (int, error) {
     ^
planner/core/find_best_task.go:95:5: `wholeTaskTypes` is unused (deadcode)
var wholeTaskTypes = [...]property.TaskType{property.CopSingleReadTaskType, property.CopDoubleReadTaskType, property.RootTaskType}
    ^
planner/core/point_get_plan.go:1340:6: `findHandleCol` is unused (deadcode)
func findHandleCol(tbl *model.TableInfo, schema *expression.Schema) *expression.Column {
     ^
planner/core/encode.go:132:16: Error return value of `d.hasher.Write` is not checked (errcheck)
	d.hasher.Write(d.buf.Bytes())
	              ^
planner/core/indexmerge_test.go:93:13: Error return value of `Preprocess` is not checked (errcheck)
		Preprocess(s.ctx, stmt, s.is)
		          ^
planner/core/logical_plan_test.go:445:13: Error return value of `Preprocess` is not checked (errcheck)
		Preprocess(s.ctx, stmt, s.is)
		          ^
planner/core/logical_plan_test.go:470:13: Error return value of `Preprocess` is not checked (errcheck)
		Preprocess(s.ctx, stmt, s.is)
		          ^
planner/core/rule_join_reorder.go:124:2: `curJoinGroup` is unused (structcheck)
	curJoinGroup []*jrNode
	^
planner/core/logical_plans.go:271:2: `calculateGenCols` is unused (structcheck)
	calculateGenCols bool
	^
planner/core/exhaust_physical_plans.go:830:2: `chosenIndexInfo` is unused (structcheck)
	chosenIndexInfo *model.IndexInfo
	^
planner/core/partition_pruning_test.go:134:2: `lessThan` is unused (structcheck)
	lessThan lessThanDataInt
	^
planner/core/physical_plans.go:790:2: `outerSchema` is unused (structcheck)
	outerSchema *expression.Schema
	^
planner/core/preprocess.go:772:2: S1023: redundant `return` statement (gosimple)
	return
	^
planner/core/stringer.go:273:9: S1039: unnecessary use of fmt.Sprintf (gosimple)
		str = fmt.Sprintf("PointGet(")
		      ^
planner/core/stringer.go:280:9: S1039: unnecessary use of fmt.Sprintf (gosimple)
		str = fmt.Sprintf("BatchPointGet(")
		      ^
planner/core/stringer.go:287:9: S1039: unnecessary use of fmt.Sprintf (gosimple)
		str = fmt.Sprintf("Recv(")
		      ^
planner/core/rule_partition_processor.go:1188:3: S1028: should use fmt.Errorf(...) instead of errors.New(fmt.Sprintf(...)) (gosimple)
		errors.New(fmt.Sprintf("Unknown partitions (%s) in optimizer hint %s",
		^
planner/core/physical_plans.go:874:2: S1011: should replace loop with `cloned.CompareFuncs = append(cloned.CompareFuncs, p.CompareFuncs...)` (gosimple)
	for _, cf := range p.CompareFuncs {
	^
planner/core/pb_to_plan.go:262:9: S1034: assigning the result of this type assertion to a variable (switch p := p.(type)) could eliminate type assertions in switch cases (gosimple)
	switch p.(type) {
	       ^
planner/core/util.go:287:9: S1025: the argument is already a string, there's no need to use fmt.Sprintf (gosimple)
	return fmt.Sprintf("%s", strings.Join(l, ","))
	       ^
planner/core/common_plans.go:1071:3: SA4006: this value of `err` is never used (staticcheck)
		err = e.explainPlanInRowFormat(x.indexPlan, "cop[tikv]", "(Build)", childIndent, false)
		^
planner/core/common_plans.go:1075:4: SA4006: this value of `err` is never used (staticcheck)
			err = e.explainPlanInRowFormat(pchild, "cop[tikv]", "(Build)", childIndent, false)
			^
planner/core/logical_plan_builder.go:933:3: SA4006: this value of `leftPlan` is never used (staticcheck)
		leftPlan, rightPlan = rightPlan, leftPlan
		^
planner/core/memtable_predicate_extractor.go:792:2: SA4006: this value of `remained` is never used (staticcheck)
	remained, quantileSkip, quantiles := e.extractCol(schema, names, predicates, "quantile", false)
	^
planner/core/explain.go:537:4: SA9003: empty branch (staticcheck)
			if err != nil {
			^
store/mockstore/mocktikv/cluster_test.go:66:10: Error return value of `txn.Set` is not checked (errcheck)
		txn.Set(rowKey, rowValue)
		       ^
store/mockstore/mocktikv/cluster_test.go:71:10: Error return value of `txn.Set` is not checked (errcheck)
		txn.Set(idxKey, []byte{'0'})
		       ^
util/localpool/localpool_test.go:28:2: `val` is unused (structcheck)
	val int64
	^
util/rowcodec/rowcodec_test.go:673:10: SA4010: this result of append is never used, except maybe in other appends (staticcheck)
			fts = append(fts, t.ft)
			      ^
bindinfo/bind_test.go:51:20: Error return value of `logutil.InitLogger` is not checked (errcheck)
	logutil.InitLogger(logutil.NewLogConfig(logLevel, logutil.DefaultLogFormat, "", logutil.EmptyFileLogConfig, false))
	                  ^
bindinfo/bind_test.go:361:84: Error return value of `(github.com/prometheus/client_golang/prometheus.Metric).Write` is not checked (errcheck)
		metrics.BindTotalGauge.WithLabelValues(metrics.ScopeGlobal, bindinfo.Using).Write(pb)
		                                                                                 ^
bindinfo/bind_test.go:363:85: Error return value of `(github.com/prometheus/client_golang/prometheus.Metric).Write` is not checked (errcheck)
		metrics.BindMemoryUsage.WithLabelValues(metrics.ScopeGlobal, bindinfo.Using).Write(pb)
		                                                                                  ^
bindinfo/bind_test.go:418:84: Error return value of `(github.com/prometheus/client_golang/prometheus.Metric).Write` is not checked (errcheck)
		metrics.BindTotalGauge.WithLabelValues(metrics.ScopeGlobal, bindinfo.Using).Write(pb)
		                                                                                 ^
ddl/util/syncer_test.go:77:14: Error return value of `d.Stop` is not checked (errcheck)
	defer d.Stop()
	            ^
ddl/util/syncer_test.go:113:15: Error return value of `d1.Stop` is not checked (errcheck)
	defer d1.Stop()
	             ^
expression/integration_test.go:3901:9: Error return value of `tk.Exec` is not checked (errcheck)
	tk.Exec("set sql_mode=''")
	       ^
planner/cascades/implementation_rules.go:98:2: S1008: should use 'return !(!prop.IsEmpty())' instead of 'if !prop.IsEmpty() { return false }; return true' (gosimple)
	if !prop.IsEmpty() {
	^
planner/cascades/implementation_rules.go:119:2: S1008: should use 'return !(!prop.IsEmpty())' instead of 'if !prop.IsEmpty() { return false }; return true' (gosimple)
	if !prop.IsEmpty() {
	^
planner/cascades/transformation_rules.go:1510:2: S1008: should use 'return !plannercore.ExprsHasSideEffects(proj.Exprs)' instead of 'if plannercore.ExprsHasSideEffects(proj.Exprs) { return false }; return true' (gosimple)
	if plannercore.ExprsHasSideEffects(proj.Exprs) {
	^
planner/cascades/transformation_rules.go:598:19: SA4010: this result of append is never used, except maybe in other appends (staticcheck)
		exprsOriginal = append(exprsOriginal, aggFunc.Args[0])
		                ^
privilege/privileges/privileges_test.go:576:23: Error return value of `url.UnmarshalBinary` is not checked (errcheck)
			url.UnmarshalBinary([]byte("spiffe://mesh.pingcap.com/ns/timesh/sa/me1"))
			                   ^
privilege/privileges/privileges_test.go:1041:16: Error return value of `fp.WriteString` is not checked (errcheck)
	fp.WriteString("1\n")
	              ^
store/tikv/batch_coprocessor_test.go:94:25: Error return value of `failpoint.Disable` is not checked (errcheck)
	defer failpoint.Disable("github.com/pingcap/tidb/infoschema/mockTiFlashStoreCount")
	                       ^
store/tikv/batch_coprocessor_test.go:129:25: Error return value of `failpoint.Disable` is not checked (errcheck)
	defer failpoint.Disable("github.com/pingcap/tidb/infoschema/mockTiFlashStoreCount")
	                       ^
sessionctx/variable/varsutil_test.go:152:21: Error return value of `SetSessionSystemVar` is not checked (errcheck)
	SetSessionSystemVar(v, "sql_mode", types.NewStringDatum(""))
	                   ^
sessionctx/variable/varsutil_test.go:194:23: Error return value of `SetSessionSystemVar` is not checked (errcheck)
			SetSessionSystemVar(v, TimeZone, types.NewStringDatum(tt.input))
			                   ^
sessionctx/variable/varsutil_test.go:206:22: Error return value of `SetSessionSystemVar` is not checked (errcheck)
		SetSessionSystemVar(v, "sql_mode", types.NewStringDatum(str))
		                   ^
sessionctx/variable/statusvar.go:106:2: SA1019: tls.VersionSSL30 is deprecated: SSLv3 is cryptographically broken, and is no longer supported by this package. See golang.org/issue/32716.  (staticcheck)
	tls.VersionSSL30: "SSLv3",
	^
sessionctx/variable/session.go:1573:4: SA4006: this value of `err` is never used (staticcheck)
			coll, err = collate.GetCollationByName(charset.CollationUTF8MB4)
			^
structure/structure_test.go:56:20: Error return value of `txn.Rollback` is not checked (errcheck)
	defer txn.Rollback()
	                  ^
structure/structure_test.go:105:20: Error return value of `txn.Rollback` is not checked (errcheck)
	defer txn.Rollback()
	                  ^
structure/structure_test.go:213:20: Error return value of `txn.Rollback` is not checked (errcheck)
	defer txn.Rollback()
	                  ^
table/column_test.go:107:11: Error return value of `CheckOnce` is not checked (errcheck)
	CheckOnce(cols)
	         ^
table/column_test.go:109:14: Error return value of `CheckNotNull` is not checked (errcheck)
	CheckNotNull(cols, types.MakeDatums(nil))
	            ^
table/column_test.go:111:14: Error return value of `CheckNotNull` is not checked (errcheck)
	CheckNotNull(cols, types.MakeDatums(nil))
	            ^
table/column_test.go:112:11: Error return value of `CheckOnce` is not checked (errcheck)
	CheckOnce([]*Column{})
	         ^
cmd/importcheck/importcheck.go:96:12: S1028: should use fmt.Errorf(...) instead of errors.New(fmt.Sprintf(...)) (gosimple)
				return errors.New(fmt.Sprintf("stdlib %s need be group together and before non-stdlib group in %s", im.Path.Value, path))
				       ^
cmd/importcheck/importcheck.go:106:12: S1028: should use fmt.Errorf(...) instead of errors.New(fmt.Sprintf(...)) (gosimple)
				return errors.New(fmt.Sprintf("non-stdlib %s need be group together and after stdlib group in %s", im.Path.Value, path))
				       ^
cmd/ddltest/column_test.go:193:11: Error return value of `s.exec` is not checked (errcheck)
				s.exec(fmt.Sprintf("insert into test_column values (%d, %d, %d)", key, key, key))
				      ^
cmd/ddltest/column_test.go:196:11: Error return value of `s.exec` is not checked (errcheck)
				s.exec(fmt.Sprintf("update test_column set c2 = %d, c3 = %d where c1 = %d",
				      ^
cmd/ddltest/column_test.go:216:12: Error return value of `s1.Execute` is not checked (errcheck)
	s1.Execute(ctx, "begin")
	          ^
cmd/ddltest/column_test.go:217:12: Error return value of `s1.Execute` is not checked (errcheck)
	s1.Execute(ctx, "insert into test_commit values (3, 3)")
	          ^
cmd/ddltest/column_test.go:222:12: Error return value of `s1.Execute` is not checked (errcheck)
	s1.Execute(ctx, "insert into test_commit values (4, 4)")
	          ^
cmd/ddltest/ddl_test.go:100:20: Error return value of `logutil.InitLogger` is not checked (errcheck)
	logutil.InitLogger(&logutil.LogConfig{Config: zaplog.Config{Level: *logLevel}})
	                  ^
cmd/ddltest/ddl_test.go:636:11: Error return value of `s.exec` is not checked (errcheck)
				s.exec(fmt.Sprintf("insert into %s values (%d, %d)", tblName, k, k))
				      ^
cmd/ddltest/ddl_test.go:1064:16: Error return value of `store.Register` is not checked (errcheck)
	store.Register("tikv", tikv.Driver{})
	              ^
config/config_test.go:111:13: Error return value of `f.Truncate` is not checked (errcheck)
		f.Truncate(0)
		          ^
config/config_test.go:112:9: Error return value of `f.Seek` is not checked (errcheck)
		f.Seek(0, 0)
		      ^
config/config_test.go:177:12: Error return value of `f.Truncate` is not checked (errcheck)
	f.Truncate(0)
	          ^
config/config_util.go:144:9: S1034: assigning the result of this type assertion to a variable (switch nested := nested.(type)) could eliminate type assertions in switch cases (gosimple)
	switch nested.(type) {
	       ^
store/mockstore/unistore/raw_handler_test.go:44:25: SA1012: do not pass a nil Context, even if a function permits it; pass context.TODO if you are unsure about which Context to use (staticcheck)
	putResp, _ := h.RawPut(nil, &kvrpcpb.RawPutRequest{Key: keys[0], Value: vals[0]})
	                       ^
store/mockstore/unistore/raw_handler_test.go:46:25: SA1012: do not pass a nil Context, even if a function permits it; pass context.TODO if you are unsure about which Context to use (staticcheck)
	getResp, _ := h.RawGet(nil, &kvrpcpb.RawGetRequest{Key: keys[0]})
	                       ^
store/mockstore/unistore/raw_handler_test.go:49:28: SA1012: do not pass a nil Context, even if a function permits it; pass context.TODO if you are unsure about which Context to use (staticcheck)
	delResp, _ := h.RawDelete(nil, &kvrpcpb.RawDeleteRequest{Key: keys[0]})
	                          ^
infoschema/metrics_schema.go:103:2: S1017: should replace this if statement with an unconditional strings.Replace (gosimple)
	if strings.Contains(promQL, promQLQuantileKey) {
	^
infoschema/metrics_schema.go:107:2: S1017: should replace this if statement with an unconditional strings.Replace (gosimple)
	if strings.Contains(promQL, promQLLabelConditionKey) {
	^
infoschema/metrics_schema.go:111:2: S1017: should replace this if statement with an unconditional strings.Replace (gosimple)
	if strings.Contains(promQL, promQRangeDurationKey) {
	^
domain/infosync/info.go:86:5: `errPlacementRulesDisabled` is unused (deadcode)
var errPlacementRulesDisabled = errors.New("placement rules feature is disabled")
    ^
util/checksum/checksum.go:142:2: SA6002: argument should be pointer-like to avoid allocations (staticcheck)
	defer checksumReaderBufPool.Put(buf)
	^
util/timeutil/time.go:84:7: S1003: should use strings.Contains(path, "posixrules") instead (gosimple)
			if strings.Index(path, "posixrules") != -1 {
			   ^
ddl/column_type_change_test.go:44:2: `dbInfo` is unused (structcheck)
	dbInfo *model.DBInfo
	^
ddl/db_test.go:2281:3: S1000: should use a simple channel send/receive instead of `select` with a single case (gosimple)
		select {
		^
ddl/column_type_change_test.go:290:44: SA1019: dbterror.ClassDDL.New is deprecated: use NewStd or NewStdErr instead.  (staticcheck)
	mockTerrorMap[model.StateNone.String()] = dbterror.ClassDDL.New(1, "MockRollingBackInCallBack-"+model.StateNone.String())
	                                          ^
ddl/column_type_change_test.go:291:50: SA1019: dbterror.ClassDDL.New is deprecated: use NewStd or NewStdErr instead.  (staticcheck)
	mockTerrorMap[model.StateDeleteOnly.String()] = dbterror.ClassDDL.New(1, "MockRollingBackInCallBack-"+model.StateDeleteOnly.String())
	                                                ^
ddl/column_type_change_test.go:292:49: SA1019: dbterror.ClassDDL.New is deprecated: use NewStd or NewStdErr instead.  (staticcheck)
	mockTerrorMap[model.StateWriteOnly.String()] = dbterror.ClassDDL.New(1, "MockRollingBackInCallBack-"+model.StateWriteOnly.String())
	                                               ^
ddl/serial_test.go:405:2: SA4006: this value of `is` is never used (staticcheck)
	is = s.dom.InfoSchema()
	^
util/profile/trackerRecorder.go:31:2: S1000: should use for range instead of for { select {} } (gosimple)
	for {
	^
store/tikv/backoff.go:241:2: `scatterRegionBackoff` is unused (deadcode)
	scatterRegionBackoff           = 20000
	^
store/tikv/coprocessor.go:472:2: `sizeofCommitDetails` is unused (deadcode)
	sizeofCommitDetails = int(unsafe.Sizeof(execdetails.CommitDetails{}))
	^
store/tikv/coprocessor.go:994:2: `minLogKVWaitTime` is unused (deadcode)
	minLogKVWaitTime    = 200
	^
store/tikv/region_cache.go:1668:2: `offline` is unused (deadcode)
	offline
	^
store/tikv/batch_coprocessor.go:215:2: `replicaReadSeed` is unused (structcheck)
	replicaReadSeed uint32
	^
store/tikv/txn.go:76:2: `assertions` is unused (structcheck)
	assertions []assertionPair
	^
store/tikv/txn.go:80:2: `dirty` is unused (structcheck)
	dirty bool
	^
store/tikv/txn.go:77:2: `confirmed` is unused (structcheck)
	confirmed  int
	^
store/tikv/2pc.go:91:2: `prewriteOnlyKeys` is unused (structcheck)
	prewriteOnlyKeys int
	^
store/tikv/2pc.go:92:2: `ignoredKeys` is unused (structcheck)
	ignoredKeys      int
	^
store/tikv/region_request.go:442:4: S1000: should use a simple channel send/receive instead of `select` with a single case (gosimple)
			select {
			^
store/tikv/txn.go:508:4: S1005: unnecessary assignment to the blank identifier (gosimple)
			val, _ := lockCtx.Values[string(key)]
			^
store/tikv/region_cache.go:184:2: S1008: should use 'return !(!s.IsLabelsMatch(op.labels))' instead of 'if !s.IsLabelsMatch(op.labels) { return false }; return true' (gosimple)
	if !s.IsLabelsMatch(op.labels) {
	^
util/collate/collate_bench_test.go:30:3: SA9003: empty branch (staticcheck)
		if collator.Compare(s1, s2) != 0 {
		^
util/expensivequery/memory_usage_alarm.go:86:2: S1023: redundant `return` statement (gosimple)
	return
	^
domain/domain.go:721:6: SA1019: grpc.WithBackoffMaxDelay is deprecated: use WithConnectParams instead. Will be supported throughout 1.x.  (staticcheck)
					grpc.WithBackoffMaxDelay(time.Second * 3),
					^
types/const_test.go:37:2: `mvccStore` is unused (structcheck)
	mvccStore mocktikv.MVCCStore
	^
util/rowDecoder/decoder.go:45:2: `haveGenColumn` is unused (structcheck)
	haveGenColumn bool
	^
store/mockstore/mocktikv/mvcc.go:247:2: `value` is unused (structcheck)
	value []byte
	^
store/mockstore/mocktikv/cluster.go:663:2: `tokenCount` is unused (structcheck)
	tokenCount atomic.Int64
	^
meta/meta_test.go:561:6: `mustNewCommonHandle` is unused (deadcode)
func mustNewCommonHandle(c *C, values ...interface{}) *kv.CommonHandle {
     ^
util/rowcodec/decoder.go:265:4: S1008: should use 'return err == nil' instead of 'if err != nil { return false }; return true' (gosimple)
			if err != nil {
			^
util/stmtsummary/statement_summary.go:173:2: `sumExecRetryCount` is unused (structcheck)
	sumExecRetryCount    int64
	^
util/stmtsummary/statement_summary.go:174:2: `sumExecRetryTime` is unused (structcheck)
	sumExecRetryTime     time.Duration
	^
ddl/ddl.go:446:6: `checkJobMaxInterval` is unused (deadcode)
func checkJobMaxInterval(job *model.Job) time.Duration {
     ^
ddl/error.go:56:2: `errUnknownTypeLength` is unused (deadcode)
	errUnknownTypeLength                      = dbterror.ClassDDL.NewStd(mysql.ErrUnknownTypeLength)
	^
ddl/error.go:57:2: `errUnknownFractionLength` is unused (deadcode)
	errUnknownFractionLength                  = dbterror.ClassDDL.NewStd(mysql.ErrUnknownFractionLength)
	^
ddl/error.go:101:2: `errUnsupportedExchangePartition` is unused (deadcode)
	errUnsupportedExchangePartition   = dbterror.ClassDDL.NewStdErr(mysql.ErrUnsupportedDDLOperation, parser_mysql.Message(fmt.Sprintf(mysql.MySQLErrName[mysql.ErrUnsupportedDDLOperation].Raw, "exchange partition"), nil))
	^
ddl/partition.go:586:6: `stringSliceEqual` is unused (deadcode)
func stringSliceEqual(a, b []string) bool {
     ^
ddl/partition.go:814:6: `validRangePartitionType` is unused (deadcode)
func validRangePartitionType(col *model.ColumnInfo) bool {
     ^
ddl/partition.go:1395:6: `checkNoRangePartitions` is unused (deadcode)
func checkNoRangePartitions(partitionNum int) error {
     ^
ddl/reorg.go:89:6: `toString` is unused (deadcode)
func toString(handle kv.Handle) string {
     ^
ddl/partition.go:1669:2: `expr` is unused (structcheck)
	expr       ast.ExprNode
	^
ddl/ddl_worker.go:797:3: S1000: should use a simple channel send/receive instead of `select` with a single case (gosimple)
		select {
		^
session/bootstrap.go:1291:6: `upgradeToVer60` is unused (deadcode)
func upgradeToVer60(s Session, ver int64) {
     ^
session/session.go:1798:2: SA9003: empty branch (staticcheck)
	if err != nil {
	^
util/hack/hack.go:42:13: unsafeptr: possible misuse of reflect.StringHeader (govet)
	pstring := *(*reflect.StringHeader)(unsafe.Pointer(&s))
	           ^
session/session_test.go:2184:49: SA1029: should not use built-in type string as key for value; define your own type to avoid collisions (staticcheck)
	ctx := context.WithValue(context.Background(), "__preCommitHook", hook)
	                                               ^
session/session_test.go:2623:49: SA1029: should not use built-in type string as key for value; define your own type to avoid collisions (staticcheck)
	ctx := context.WithValue(context.Background(), "CheckSelectRequestHook", func(req *kv.Request) {
	                                               ^
session/session_test.go:2629:48: SA1029: should not use built-in type string as key for value; define your own type to avoid collisions (staticcheck)
	ctx = context.WithValue(context.Background(), "CheckSelectRequestHook", func(req *kv.Request) {
	                                              ^
session/session_test.go:134:4: SA1019: grpc.WithBackoffMaxDelay is deprecated: use WithConnectParams instead. Will be supported throughout 1.x.  (staticcheck)
			grpc.WithBackoffMaxDelay(time.Second * 3),
			^
types/mydecimal_test.go:685:3: `err` is unused (structcheck)
		err    error
		^
util/execdetails/execdetails.go:875:2: S1011: should replace loop with `e.concurrency = append(e.concurrency, infos...)` (gosimple)
	for _, info := range infos {
	^
errno/errcode.go:19:2: SA9004: only the first constant in this group has an explicit type (staticcheck)
	ErrErrorFirst                                            uint16 = 1000
	^
statistics/handle/handle.go:304:2: S1023: redundant `return` statement (gosimple)
	return
	^
store/tikv/gcworker/gc_worker_test.go:1116:3: S1011: should replace loop with `res = append(res, locks...)` (gosimple)
		for _, lock := range locks {
		^
executor/update_test.go:37:2: `ctx` is unused (structcheck)
	ctx *mock.Context
	^
executor/tiflash_test.go:33:2: `cluster` is unused (structcheck)
	cluster cluster.Cluster
	^
executor/tiflash_test.go:37:2: `ctx` is unused (structcheck)
	ctx *mock.Context
	^
owner/manager.go:388:26: SA1019: grpc.ErrClientConnClosing is deprecated: this error should not be relied upon by users; use the status code of Canceled instead.  (staticcheck)
		terror.ErrorEqual(err, grpc.ErrClientConnClosing) {
		                       ^
owner/fail_test.go:97:38: SA1019: grpc.ErrClientConnClosing is deprecated: this error should not be relied upon by users; use the status code of Canceled instead.  (staticcheck)
		isContextDone := terror.ErrorEqual(grpc.ErrClientConnClosing, err) || terror.ErrorEqual(context.Canceled, err)
		                                   ^
owner/fail_test.go:115:38: SA1019: grpc.ErrClientConnClosing is deprecated: this error should not be relied upon by users; use the status code of Canceled instead.  (staticcheck)
		isContextDone := terror.ErrorEqual(grpc.ErrClientConnClosing, err) || terror.ErrorEqual(context.Canceled, err)
		                                   ^
executor/aggfuncs/func_max_min.go:29:2: `h` is unused (structcheck)
	h       heap.Interface
	^
executor/aggfuncs/func_first_row.go:54:2: `gotFirstRow` is unused (structcheck)
	gotFirstRow bool
	^
executor/aggfuncs/func_first_row.go:51:2: `isNull` is unused (structcheck)
	isNull bool
	^
executor/aggfuncs/func_group_concat.go:87:2: `valsBuf` is unused (structcheck)
	valsBuf *bytes.Buffer
	^
executor/aggfuncs/func_group_concat.go:88:2: `buffer` is unused (structcheck)
	buffer  *bytes.Buffer
	^
executor/aggfuncs/func_first_row.go:518:3: SA4004: the surrounding loop is unconditionally terminated (staticcheck)
		break
		^
executor/aggfuncs/func_first_row.go:566:3: SA4004: the surrounding loop is unconditionally terminated (staticcheck)
		break
		^
executor/adapter.go:691:6: `extractConflictCommitTS` is unused (deadcode)
func extractConflictCommitTS(errStr string) uint64 {
     ^
executor/batch_checker.go:51:6: `encodeNewRow` is unused (deadcode)
func encodeNewRow(ctx sessionctx.Context, t table.Table, row []types.Datum) ([]byte, error) {
     ^
executor/distsql.go:140:6: `handleIsExtra` is unused (deadcode)
func handleIsExtra(col *expression.Column) bool {
     ^
executor/hash_table.go:39:2: `estCountMaxFactor` is unused (deadcode)
	estCountMaxFactor = 10 * 1024
	^
executor/hash_table.go:45:2: `estCountMinFactor` is unused (deadcode)
	estCountMinFactor = 8
	^
executor/hash_table.go:49:2: `estCountDivisor` is unused (deadcode)
	estCountDivisor = 8
	^
executor/merge_join.go:57:2: `innerTableLabel` is unused (deadcode)
	innerTableLabel fmt.Stringer = stringutil.StringerStr("innerTable")
	^
executor/merge_join.go:58:2: `outerTableLabel` is unused (deadcode)
	outerTableLabel fmt.Stringer = stringutil.StringerStr("outerTable")
	^
executor/partition_table.go:49:6: `innerNextPartition` is unused (deadcode)
type innerNextPartition interface {
     ^
executor/benchmark_test.go:1618:6: `defaultMergeJoinTestCase` is unused (deadcode)
func defaultMergeJoinTestCase() *mergeJoinTestCase {
     ^
executor/union_scan.go:50:2: `sortErr` is unused (structcheck)
	sortErr             error
	^
executor/distsql.go:416:2: `idxTblCols` is unused (structcheck)
	idxTblCols []*table.Column
	^
executor/split.go:62:2: `splitRegions` is unused (structcheck)
	splitRegions     int
	^
executor/split.go:63:2: `finishScatterNum` is unused (structcheck)
	finishScatterNum int
	^
executor/partition_table.go:46:2: `nextRange` is unused (structcheck)
	nextRange       map[int64][]*ranger.Range
	^
executor/executor.go:430:2: `done` is unused (structcheck)
	done      bool
	^
executor/split.go:53:2: `handleCols` is unused (structcheck)
	handleCols     core.HandleCols
	^
executor/analyze.go:268:2: `priority` is unused (structcheck)
	priority       int
	^
executor/sample.go:47:2: `tablePlan` is unused (structcheck)
	tablePlan plannercore.PhysicalPlan
	^
executor/parallel_apply.go:53:2: `outerRowMutex` is unused (structcheck)
	outerRowMutex sync.Mutex
	^
executor/parallel_apply.go:49:2: `cursor` is unused (structcheck)
	cursor        int
	^
executor/analyze.go:467:2: `priority` is unused (structcheck)
	priority      int
	^
executor/index_merge_reader.go:107:2: `idxCols` is unused (structcheck)
	idxCols         [][]*expression.Column
	^
executor/index_merge_reader.go:108:2: `colLens` is unused (structcheck)
	colLens         [][]int
	^
executor/index_merge_reader.go:102:2: `corColInIdxSide` is unused (structcheck)
	corColInIdxSide bool
	^
executor/index_merge_reader.go:104:2: `corColInTblSide` is unused (structcheck)
	corColInTblSide bool
	^
executor/index_merge_reader.go:106:2: `corColInAccess` is unused (structcheck)
	corColInAccess  bool
	^
executor/sort.go:43:2: `keyExprs` is unused (structcheck)
	keyExprs []expression.Expression
	^
executor/sort.go:44:2: `keyTypes` is unused (structcheck)
	keyTypes []*types.FieldType
	^
executor/executor.go:440:2: `cacheJobs` is unused (structcheck)
	cacheJobs      []*model.Job
	^
executor/memtable_reader.go:230:13: S1034: assigning the result of this type assertion to a variable (switch val := val.(type)) could eliminate type assertions in switch cases (gosimple)
					switch val.(type) {
					       ^
executor/delete.go:191:4: S1008: should use 'return err == nil' instead of 'if err != nil { return false }; return true' (gosimple)
			if err != nil {
			^
executor/executor.go:1164:4: SA4004: the surrounding loop is unconditionally terminated (staticcheck)
			return row, err
			^
executor/builder.go:3028:17: SA4010: this result of append is never used, except maybe in other appends (staticcheck)
			keepOrders = append(keepOrders, is.KeepOrder)
			             ^
executor/analyze.go:792:4: SA4006: this value of `rollbackFn` is never used (staticcheck)
			rollbackFn = func() error {
			^
util/selection/selection.go:84:6: `pivotFunc` is unused (deadcode)
type pivotFunc func(Interface, int, int) int
     ^
util/selection/selection.go:86:6: `medianOf3Pivot` is unused (deadcode)
func medianOf3Pivot(data Interface, left, right int) int {
     ^
server/server.go:71:2: `baseConnID` is unused (deadcode)
	baseConnID  uint32
	^
server/server.go:691:2: `codeUnknownFieldType` is unused (deadcode)
	codeUnknownFieldType = 1
	^
server/server.go:692:2: `codeInvalidSequence` is unused (deadcode)
	codeInvalidSequence  = 3
	^
server/server.go:693:2: `codeInvalidType` is unused (deadcode)
	codeInvalidType      = 4
	^
util/chunk/list.go:45:5: `chunkListLabel` is unused (deadcode)
var chunkListLabel fmt.Stringer = stringutil.StringerStr("chunk.List")
    ^
sessionctx/binloginfo/binloginfo.go:49:5: `autoRandomPat` is unused (deadcode)
var autoRandomPat = regexp.MustCompile(`AUTO_RANDOM\s*\(\s*\d+\s*\)\s*`)
    ^
sessionctx/binloginfo/binloginfo.go:157:2: S1000: should use for range instead of for { select {} } (gosimple)
	for {
	^
sessionctx/binloginfo/binloginfo_test.go:107:9: SA1019: grpc.WithDialer is deprecated: use WithContextDialer instead.  Will be supported throughout 1.x.  (staticcheck)
	opt := grpc.WithDialer(func(addr string, timeout time.Duration) (net.Conn, error) {
	       ^
expression/errors.go:45:2: `errBadField` is unused (deadcode)
	errBadField                      = dbterror.ClassExpression.NewStd(mysql.ErrBadField)
	^
expression/bench_test.go:709:6: `newDateTimeGener` is unused (deadcode)
func newDateTimeGener(fsp, year, month, day int) *dateTimeGener {
     ^
expression/builtin_time_vec_test.go:71:6: `newDateTimeUnitStrGener` is unused (deadcode)
func newDateTimeUnitStrGener() *dateTimeUnitStrGener {
     ^
expression/constant_test.go:53:6: `newDate` is unused (deadcode)
func newDate(year, month, day int) *Constant {
     ^
expression/constant_test.go:57:6: `newTimestamp` is unused (deadcode)
func newTimestamp(yy, mm, dd, hh, min, ss int) *Constant {
     ^
expression/builtin_encryption_vec.go:540:16: SA6002: argument should be pointer-like to avoid allocations (staticcheck)
		bytePool.Put(b)
		             ^
expression/expression.go:293:15: SA6002: argument should be pointer-like to avoid allocations (staticcheck)
		selPool.Put(sel)
		            ^
expression/builtin_like.go:146:23: SA1019: from.memorizedRegexp.Copy is deprecated: In earlier releases, when using a Regexp in multiple goroutines, giving each goroutine its own copy helped to avoid lock contention. As of Go 1.12, using Copy is no longer necessary to avoid lock contention. Copy may still be appropriate if the reason for its use is to make two copies with different Longest settings.  (staticcheck)
		b.memorizedRegexp = from.memorizedRegexp.Copy()
		                    ^
store/mockstore/unistore/cophandler/mpp.go:41:2: `taskInit` is unused (deadcode)
	taskInit int32 = iota
	^
store/mockstore/unistore/cophandler/closure_exec.go:163:3: S1011: should replace loop with `outputFieldTypes = append(outputFieldTypes, originalOutputFieldTypes...)` (gosimple)
		for _, tp := range originalOutputFieldTypes {
		^
store/mockstore/unistore/cophandler/cop_handler.go:303:23: func `(*evalContext).decodeRelatedColumnVals` is unused (unused)
store/mockstore/unistore/cophandler/mpp.go:127:26: func `(*MPPTaskHandler).getAndActiveTunnel` is unused (unused)
executor/builder.go:3326:6: type `kvRangeBuilderFromFunc` is unused (unused)
executor/index_merge_reader.go:100:2: field `checkIndexValue` is unused (unused)
executor/hash_table.go:198:26: func `(*hashRowContainer).getJoinKeyFromChkRow` is unused (unused)
executor/inspection_result.go:75:27: func `inspectionFilter.exist` is unused (unused)
executor/join.go:1074:28: func `(*joinRuntimeStats).setHashStat` is unused (unused)
executor/hash_table_test.go:30:24: func `(*pkgTestSuite).testHashTables` is unused (unused)
expression/util.go:658:6: type `exprStack` is unused (unused)
store/tikv/oracle/oracles/export_test.go:37:6: func `ClearOracleHook` is unused (unused)
planner/core/rule_join_reorder_dp.go:285:31: func `(*joinReorderDPSolver).newJoinWithConds` is unused (unused)
planner/core/planbuilder.go:1143:23: func `(*PlanBuilder).getGenExprs` is unused (unused)
planner/core/planbuilder.go:479:29: func `(*handleColHelper).appendColToLastMap` is unused (unused)
expression/bench_test.go:873:6: type `randDurString` is unused (unused)
expression/bench_test.go:296:6: type `charsetStringGener` is unused (unused)
expression/util_test.go:39:25: func `(*testUtilSuite).checkPanic` is unused (unused)
expression/constant_test.go:61:6: func `newTimeConst` is unused (unused)
expression/builtin_time_vec_test.go:67:6: type `dateTimeUnitStrGener` is unused (unused)
server/statistics_handler_test.go:239:31: func `(*testDumpStatsSuite).clearData` is unused (unused)
server/server_test.go:165:20: func `(*DBTest).fail` is unused (unused)
planner/core/partition_pruner_test.go:41:34: func `(*testPartitionPruneSuit).cleanEnv` is unused (unused)
store/tikv/store_test.go:109:24: func `(*mockPDClient).enable` is unused (unused)
store/mockstore/mocktikv/mvcc.go:245:6: type `rawEntry` is unused (unused)
store/tikv/txn.go:125:6: type `assertionPair` is unused (unused)
util/execdetails/execdetails.go:536:29: func `(*CopRuntimeStats).writeFieldValue` is unused (unused)
util/execdetails/execdetails.go:532:29: func `(*CopRuntimeStats).writeField` is unused (unused)
expression/integration_test.go:4659:32: func `(*testIntegrationSuite).testTiDBIsOwnerFunc` is unused (unused)
expression/flag_simplify_test.go:37:33: func `(*testFlagSimplifySuite).cleanEnv` is unused (unused)
expression/constant_propagation_test.go:37:21: func `(*testSuite).cleanEnv` is unused (unused)
server/http_handler.go:1354:6: type `hotRegion` is unused (unused)
server/http_handler.go:1358:6: type `hotRegions` is unused (unused)
server/conn.go:1847:23: func `(*clientConn).writeMultiResultset` is unused (unused)
plugin/conn_ip_example/conn_ip_example_test.go:24:6: func `LoadRunShutdownPluginExample` is unused (unused)
@ngaut ngaut added the type/enhancement The issue or PR belongs to an enhancement. label Feb 6, 2021
@morgo
Copy link
Contributor

morgo commented Feb 7, 2021

See also: #20859

@morgo morgo added the help wanted Denotes an issue that needs help from a contributor. Must meet "help wanted" guidelines. label Feb 7, 2021
@Rustin170506
Copy link
Member

If anyone wants to help fix the issue, a better way is to add a GitHub action to automatically detect these issues.
Please refer to https://github.com/golangci/golangci-lint-action.
Also maybe we need to do some configuration of errcheck to ignore the errcheck checks in the test file.

@morgo
Copy link
Contributor

morgo commented Feb 9, 2021

If anyone wants to help fix the issue, a better way is to add a GitHub action to automatically detect these issues.
Please refer to https://github.com/golangci/golangci-lint-action.
Also maybe we need to do some configuration of errcheck to ignore the errcheck checks in the test file.

The last time I looked at golangci-lint, this was not feasible. But it looks like it is now! See: https://golangci-lint.run/usage/faq/#how-to-integrate-golangci-lint-into-large-project-with-thousands-of-issues

@zimulala
Copy link
Contributor

I added a more detailed issue(#22979) for everyone to cooperate in the development, which is a duplicate of this issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
help wanted Denotes an issue that needs help from a contributor. Must meet "help wanted" guidelines. type/enhancement The issue or PR belongs to an enhancement.
Projects
None yet
Development

No branches or pull requests

4 participants