Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

chore: enable linter gocritic (#1373)

Yilong Lib74c84e042d0
diff --git a/.golangci.yaml b/.golangci.yaml
index fed456ea80..8e1f852b56 100644
--- a/.golangci.yaml
+++ b/.golangci.yaml
@@ -6,6 +6,7 @@ linters:
- govet
- staticcheck
- misspell
+ - gocritic
# golangci-lint run --exclude="Rollback,logger.Sync,pgInstance.Stop"
issues:
@@ -30,3 +31,6 @@ linters-settings:
arguments:
- checkPrivateReceivers
- sayRepetitiveInsteadOfStutters
+ gocritic:
+ disabled-checks:
+ - ifElseChain
diff --git a/api/deploy.go b/api/deploy.go
index 428613c681..b21510b464 100644
--- a/api/deploy.go
+++ b/api/deploy.go
@@ -116,7 +116,7 @@ func ValidateAndGetDeploymentSchedule(payload string) (*DeploymentSchedule, erro
for _, e := range d.Spec.Selector.MatchExpressions {
switch e.Operator {
case InOperatorType:
- if len(e.Values) <= 0 {
+ if len(e.Values) == 0 {
return nil, common.Errorf(common.Invalid, fmt.Errorf("expression key %q with %q operator should have at least one value", e.Key, e.Operator))
}
case ExistsOperatorType:
diff --git a/api/label.go b/api/label.go
index 0c13bbef6d..df67cd6349 100644
--- a/api/label.go
+++ b/api/label.go
@@ -60,7 +60,7 @@ type LabelKeyPatch struct {
// Validate validates the sanity of patch values.
func (patch *LabelKeyPatch) Validate() error {
for _, v := range patch.ValueList {
- if len(v) <= 0 || len(v) > labelLengthMax {
+ if len(v) == 0 || len(v) > labelLengthMax {
return fmt.Errorf("label value has a maximum length of %v characters and cannot be empty", labelLengthMax)
}
}
diff --git a/api/project_member.go b/api/project_member.go
index 9a7993e8b7..8963313723 100644
--- a/api/project_member.go
+++ b/api/project_member.go
@@ -26,7 +26,7 @@ func (e ProjectRoleProvider) String() string {
return ""
}
-//ProjectRoleProviderPayload is the payload for role provider
+// ProjectRoleProviderPayload is the payload for role provider
type ProjectRoleProviderPayload struct {
VCSRole string `json:"vcsRole"`
LastSyncTs int64 `json:"lastSyncTs"`
diff --git a/api/sheet.go b/api/sheet.go
index c95ed88f32..ebe90dd920 100644
--- a/api/sheet.go
+++ b/api/sheet.go
@@ -65,9 +65,10 @@ func (v SheetType) String() string {
switch v {
case SheetForSQL:
return "SQL"
+ default:
+ // Default sheet type is SQL.
+ return "SQL"
}
- // Default sheet type is SQL.
- return "SQL"
}
// SheetVCSPayload is the additional data payload of the VCS sheet.
diff --git a/bin/bb/cmd/migrate.go b/bin/bb/cmd/migrate.go
index 5da343f757..89108e8048 100644
--- a/bin/bb/cmd/migrate.go
+++ b/bin/bb/cmd/migrate.go
@@ -34,7 +34,7 @@ func newMigrateCmd() *cobra.Command {
var sqlReaders []io.Reader
- //TODO(qsliu): support file and command combined as the passed order.
+ // TODO(qsliu): support file and command combined as the passed order.
for _, file := range fileList {
f, err := os.Open(file)
if err != nil {
diff --git a/plugin/db/mysql/mysql.go b/plugin/db/mysql/mysql.go
index d2a605034a..a0bf60afe9 100644
--- a/plugin/db/mysql/mysql.go
+++ b/plugin/db/mysql/mysql.go
@@ -1332,7 +1332,7 @@ func exportTableData(txn *sql.Tx, dbName, tblName string, includeDbPrefix bool,
if err != nil {
return err
}
- if len(cols) <= 0 {
+ if len(cols) == 0 {
return nil
}
values := make([]*sql.NullString, len(cols))
diff --git a/plugin/db/pg/pg.go b/plugin/db/pg/pg.go
index 535f1ae5d6..dc0a62c909 100644
--- a/plugin/db/pg/pg.go
+++ b/plugin/db/pg/pg.go
@@ -1201,7 +1201,7 @@ func (c *columnSchema) Statement() string {
s += fmt.Sprintf("(%s)", c.characterMaximumLength)
}
if !c.isNullable {
- s = s + " NOT NULL"
+ s += " NOT NULL"
}
if c.columnDefault != "" {
s += fmt.Sprintf(" DEFAULT %s", c.columnDefault)
@@ -1704,7 +1704,7 @@ func getIndexColumnExpressions(stmt string) ([]string, error) {
var cols []string
re := regexp.MustCompile(`\(\(.*\)\)`)
for {
- if len(columnStmt) <= 0 {
+ if len(columnStmt) == 0 {
break
}
// Get a token
@@ -1751,7 +1751,7 @@ func exportTableData(txn *sql.Tx, tbl *tableSchema, out io.Writer) error {
if err != nil {
return err
}
- if len(cols) <= 0 {
+ if len(cols) == 0 {
return nil
}
values := make([]*sql.NullString, len(cols))
diff --git a/plugin/db/sqlite/sqlite.go b/plugin/db/sqlite/sqlite.go
index 051f518e82..5b760ce76a 100644
--- a/plugin/db/sqlite/sqlite.go
+++ b/plugin/db/sqlite/sqlite.go
@@ -738,7 +738,7 @@ func exportTableData(txn *sql.Tx, tblName string, out io.Writer) error {
if err != nil {
return err
}
- if len(cols) <= 0 {
+ if len(cols) == 0 {
return nil
}
values := make([]*sql.NullString, len(cols))
diff --git a/plugin/restore/mysql/mysql.go b/plugin/restore/mysql/mysql.go
index 3abcf86c10..3a828a84ba 100644
--- a/plugin/restore/mysql/mysql.go
+++ b/plugin/restore/mysql/mysql.go
@@ -311,7 +311,7 @@ func (r *Restore) getBinlogFilesMetaOnServer(ctx context.Context) ([]mysql.Binlo
// showLatestBinlogFile returns the metadata of latest binlog
func (r *Restore) getLatestBinlogFileMeta(ctx context.Context) (*mysql.BinlogFile, error) {
- //TODO(zp): refactor to reuse getBinlogInfo() in plugin/db/mysql.go
+ // TODO(zp): refactor to reuse getBinlogInfo() in plugin/db/mysql.go
db, err := r.driver.GetDbConnection(ctx, "")
if err != nil {
return nil, err
diff --git a/plugin/vcs/gitlab/gitlab.go b/plugin/vcs/gitlab/gitlab.go
index f5318f02ae..ad4b369fdd 100644
--- a/plugin/vcs/gitlab/gitlab.go
+++ b/plugin/vcs/gitlab/gitlab.go
@@ -43,8 +43,9 @@ func (e WebhookType) String() string {
switch e {
case WebhookPush:
return "push"
+ default:
+ return "UNKNOWN"
}
- return "UNKNOWN"
}
// WebhookInfo is the API message for webhook info.
diff --git a/server/acl.go b/server/acl.go
index dece8c313a..06106cef55 100644
--- a/server/acl.go
+++ b/server/acl.go
@@ -61,7 +61,7 @@ func aclMiddleware(l *zap.Logger, s *Server, ce *casbin.Enforcer, next echo.Hand
if isSelf, err := isOperatingSelf(ctx, c, s, principalID, method); err != nil {
return err
} else if isSelf {
- method = method + "_SELF"
+ method += "_SELF"
}
}
diff --git a/server/auth.go b/server/auth.go
index 6d329fabdc..8640e7339d 100644
--- a/server/auth.go
+++ b/server/auth.go
@@ -217,14 +217,14 @@ func (s *Server) registerAuthRoutes(g *echo.Group) {
})
}
-func trySignUp(ctx context.Context, s *Server, signUp *api.SignUp, CreatorID int) (*api.Principal, *echo.HTTPError) {
+func trySignUp(ctx context.Context, s *Server, signUp *api.SignUp, creatorID int) (*api.Principal, *echo.HTTPError) {
passwordHash, err := bcrypt.GenerateFromPassword([]byte(signUp.Password), bcrypt.DefaultCost)
if err != nil {
return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate password hash").SetInternal(err)
}
principalCreate := &api.PrincipalCreate{
- CreatorID: CreatorID,
+ CreatorID: creatorID,
Type: api.EndUser,
Name: signUp.Name,
Email: signUp.Email,
@@ -254,7 +254,7 @@ func trySignUp(ctx context.Context, s *Server, signUp *api.SignUp, CreatorID int
role = api.Owner
}
memberCreate := &api.MemberCreate{
- CreatorID: CreatorID,
+ CreatorID: creatorID,
Status: api.Active,
Role: role,
PrincipalID: user.ID,
diff --git a/server/project.go b/server/project.go
index e960795114..5f10784b07 100644
--- a/server/project.go
+++ b/server/project.go
@@ -215,8 +215,7 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
// Create webhook and retrieve the created webhook id
var webhookCreatePayload []byte
- switch vcs.Type {
- case "GITLAB_SELF_HOST":
+ if vcs.Type == "GITLAB_SELF_HOST" {
webhookPost := gitlab.WebhookPost{
URL: fmt.Sprintf("%s:%d/%s/%s", s.profile.BackendHost, s.profile.BackendPort, gitLabWebhookPath, repositoryCreate.WebhookEndpointID),
SecretToken: repositoryCreate.WebhookSecretToken,
@@ -367,8 +366,7 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
// This is because in case the webhook update fails, we can still have a reconcile process to reconcile the webhook state.
// If we update it before we update the repository, then if the repository update fails, then the reconcile process will reconcile the webhook to the pre-update state which is likely not intended.
var webhookPatchPayload []byte
- switch vcs.Type {
- case "GITLAB_SELF_HOST":
+ if vcs.Type == "GITLAB_SELF_HOST" {
webhookPut := gitlab.WebhookPut{
URL: fmt.Sprintf("%s:%d/%s/%s", s.profile.BackendHost, s.profile.BackendPort, gitLabWebhookPath, updatedRepo.WebhookEndpointID),
PushEventsBranchFilter: *repoPatch.BranchFilter,
diff --git a/server/task.go b/server/task.go
index 4d4b341f86..93a8bcd555 100644
--- a/server/task.go
+++ b/server/task.go
@@ -319,10 +319,8 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {
if currentPrincipal.Role != api.Owner && currentPrincipal.Role != api.DBA {
return echo.NewHTTPError(http.StatusUnauthorized, "Only allow Owner/DBA system account to update this task status")
}
- } else {
- if issue.AssigneeID != currentPrincipalID {
- return echo.NewHTTPError(http.StatusUnauthorized, "Only allow the assignee to update task status")
- }
+ } else if issue.AssigneeID != currentPrincipalID {
+ return echo.NewHTTPError(http.StatusUnauthorized, "Only allow the assignee to update task status")
}
taskPatched, err := s.changeTaskStatusWithPatch(ctx, task, taskStatusPatch)
diff --git a/server/task_check_executor_statement_advisor_composite.go b/server/task_check_executor_statement_advisor_composite.go
index c12f917031..284554096e 100644
--- a/server/task_check_executor_statement_advisor_composite.go
+++ b/server/task_check_executor_statement_advisor_composite.go
@@ -195,8 +195,7 @@ func getAdvisorTypeByRule(ruleType api.SchemaReviewRuleType, engine db.Type) (ad
return advisor.MySQLTableRequirePK, nil
}
case api.SchemaRuleMySQLEngine:
- switch engine {
- case db.MySQL:
+ if engine == db.MySQL {
return advisor.MySQLUseInnoDB, nil
}
}
diff --git a/store/pg_engine.go b/store/pg_engine.go
index 070cc0e46f..745166b295 100644
--- a/store/pg_engine.go
+++ b/store/pg_engine.go
@@ -279,7 +279,7 @@ func migrate(ctx context.Context, d dbdriver.Driver, curVer *semver.Version, mod
l.Info("The database schema has not been setup.")
} else {
l.Info(fmt.Sprintf("Current schema version before migration: %s", curVer))
- major := (*curVer).Major
+ major := curVer.Major
if major != majorSchemaVersion {
return fmt.Errorf("current major schema version %d is different from the major schema version %d this release %s expects", major, majorSchemaVersion, serverVersion)
}
diff --git a/tests/tenant_test.go b/tests/tenant_test.go
index e33c8fd1e8..469457b8f7 100644
--- a/tests/tenant_test.go
+++ b/tests/tenant_test.go
@@ -184,7 +184,9 @@ func TestTenant(t *testing.T) {
}
// Query migration history
- instances := append(stagingInstances, prodInstances...)
+ var instances []*api.Instance
+ instances = append(instances, stagingInstances...)
+ instances = append(instances, prodInstances...)
hm1 := map[string]bool{}
hm2 := map[string]bool{}
for _, instance := range instances {
@@ -407,7 +409,9 @@ func TestTenantVCS(t *testing.T) {
}
// Query migration history
- instances := append(stagingInstances, prodInstances...)
+ var instances []*api.Instance
+ instances = append(instances, stagingInstances...)
+ instances = append(instances, prodInstances...)
hm1 := map[string]bool{}
hm2 := map[string]bool{}
for _, instance := range instances {
diff --git a/tests/tests.go b/tests/tests.go
index eefe5691a7..f96c9a8037 100644
--- a/tests/tests.go
+++ b/tests/tests.go
@@ -1051,7 +1051,9 @@ func (ctl *controller) addLabelValues(key string, values []string) error {
if labelKey == nil {
return fmt.Errorf("failed to find label with key %q", key)
}
- valueList := append(labelKey.ValueList, values...)
+ var valueList []string
+ valueList = append(valueList, labelKey.ValueList...)
+ valueList = append(valueList, values...)
_, err = ctl.patchLabelKey(api.LabelKeyPatch{
ID: labelKey.ID,
ValueList: valueList,