Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: add linter to forbid usage of fmt.Errorf (#2303)
Yilong Li5d3b02ac5edb
diff --git a/.golangci.yaml b/.golangci.yamlindex 093c0d17f3..c06f9ab4b8 100644--- a/.golangci.yaml+++ b/.golangci.yaml@@ -11,6 +11,7 @@ linters:- rowserrcheck- nilerr- godot+ - forbidigo# golangci-lint run --exclude="Rollback,logger.Sync,pgInstance.Stop"issues:@@ -76,3 +77,6 @@ linters-settings:printf: # The name of the analyzer, run `go tool vet help` to see the list of all analyzersfuncs: # Run `go tool vet help printf` to see the full configuration of `printf`- common.Errorf+ forbidigo:+ forbid:+ - 'fmt\.Errorf(# Please use errors\.Wrap\|Wrapf\|Errorf instead)?'diff --git a/api/api.go b/api/api.goindex 955a0d52ce..a7aeeac87a 100644--- a/api/api.go+++ b/api/api.go@@ -1,8 +1,9 @@package apiimport (- "fmt""strings"++ "github.com/pkg/errors")// UnknownID is the ID for unknowns.@@ -36,5 +37,5 @@ func StringToSortOrder(s string) (SortOrder, error) {case string(DESC):return DESC, nil}- return SortOrder(""), fmt.Errorf("%q cannot be converted to SortOrder", s)+ return SortOrder(""), errors.Errorf("%q cannot be converted to SortOrder", s)}diff --git a/api/label.go b/api/label.goindex 8c3a291531..f764004e58 100644--- a/api/label.go+++ b/api/label.go@@ -1,8 +1,6 @@package api-import (- "fmt"-)+import "github.com/pkg/errors"const (// EnvironmentKeyName is the reserved key for environment.@@ -61,7 +59,7 @@ type LabelKeyPatch struct {func (patch *LabelKeyPatch) Validate() error {for _, v := range patch.ValueList {if len(v) == 0 || len(v) > labelLengthMax {- return fmt.Errorf("label value has a maximum length of %v characters and cannot be empty", labelLengthMax)+ return errors.Errorf("label value has a maximum length of %v characters and cannot be empty", labelLengthMax)}}return nildiff --git a/api/policy.go b/api/policy.goindex 53c9098fac..7e77bfeedb 100644--- a/api/policy.go+++ b/api/policy.go@@ -2,7 +2,6 @@ package apiimport ("encoding/json"- "fmt""github.com/bytebase/bytebase/plugin/advisor""github.com/pkg/errors"@@ -197,7 +196,7 @@ func UnmarshalSQLReviewPolicy(payload string) (*advisor.SQLReviewPolicy, error)// ValidatePolicy will validate the policy type and payload values.func ValidatePolicy(pType PolicyType, payload string) error {if !PolicyTypes[pType] {- return fmt.Errorf("invalid policy type: %s", pType)+ return errors.Errorf("invalid policy type: %s", pType)}if payload == "" {return nil@@ -210,17 +209,17 @@ func ValidatePolicy(pType PolicyType, payload string) error {return err}if pa.Value != PipelineApprovalValueManualNever && pa.Value != PipelineApprovalValueManualAlways {- return fmt.Errorf("invalid approval policy value: %q", payload)+ return errors.Errorf("invalid approval policy value: %q", payload)}issueTypeSeen := make(map[IssueType]bool)for _, group := range pa.AssigneeGroupList {if group.IssueType != IssueDatabaseSchemaUpdate &&group.IssueType != IssueDatabaseSchemaUpdateGhost &&group.IssueType != IssueDatabaseDataUpdate {- return fmt.Errorf("found invalid assignee group issue type %q in pipeline approval policy", group.IssueType)+ return errors.Errorf("found invalid assignee group issue type %q in pipeline approval policy", group.IssueType)}if issueTypeSeen[group.IssueType] {- return fmt.Errorf("found duplicated assignee group issue type %q in pipeline approval policy", group.IssueType)+ return errors.Errorf("found duplicated assignee group issue type %q in pipeline approval policy", group.IssueType)}issueTypeSeen[group.IssueType] = true}@@ -230,7 +229,7 @@ func ValidatePolicy(pType PolicyType, payload string) error {return err}if bp.Schedule != BackupPlanPolicyScheduleUnset && bp.Schedule != BackupPlanPolicyScheduleDaily && bp.Schedule != BackupPlanPolicyScheduleWeekly {- return fmt.Errorf("invalid backup plan policy schedule: %q", bp.Schedule)+ return errors.Errorf("invalid backup plan policy schedule: %q", bp.Schedule)}case PolicyTypeSQLReview:sr, err := UnmarshalSQLReviewPolicy(payload)diff --git a/api/project.go b/api/project.goindex 8bc794aeba..3f33abbc99 100644--- a/api/project.go+++ b/api/project.go@@ -2,11 +2,11 @@ package apiimport ("encoding/json"- "fmt""regexp""strings""github.com/bytebase/bytebase/common"+ "github.com/pkg/errors")// DefaultProjectID is the ID for the default project.@@ -158,20 +158,20 @@ func ValidateRepositoryFilePathTemplate(filePathTemplate string, tenantMode Proj}if tenantMode == TenantModeTenant {if _, ok := tokenMap[EnvironmentToken]; ok {- return &common.Error{Code: common.Invalid, Err: fmt.Errorf("%q is not allowed in the template for projects in tenant mode", EnvironmentToken)}+ return &common.Error{Code: common.Invalid, Err: errors.Errorf("%q is not allowed in the template for projects in tenant mode", EnvironmentToken)}}}for token, required := range repositoryFilePathTemplateTokens {if required {if _, ok := tokenMap[token]; !ok {- return fmt.Errorf("missing %s in file path template", token)+ return errors.Errorf("missing %s in file path template", token)}}}for token := range tokenMap {if _, ok := repositoryFilePathTemplateTokens[token]; !ok {- return fmt.Errorf("unknown token %s in file path template", token)+ return errors.Errorf("unknown token %s in file path template", token)}}return nil@@ -189,20 +189,20 @@ func ValidateRepositorySchemaPathTemplate(schemaPathTemplate string, tenantMode}if tenantMode == TenantModeTenant {if _, ok := tokenMap[EnvironmentToken]; ok {- return &common.Error{Code: common.Invalid, Err: fmt.Errorf("%q is not allowed in the template for projects in tenant mode", EnvironmentToken)}+ return &common.Error{Code: common.Invalid, Err: errors.Errorf("%q is not allowed in the template for projects in tenant mode", EnvironmentToken)}}}for token, required := range schemaPathTemplateTokens {if required {if _, ok := tokenMap[token]; !ok {- return fmt.Errorf("missing %s in schema path template", token)+ return errors.Errorf("missing %s in schema path template", token)}}}for token := range tokenMap {if _, ok := schemaPathTemplateTokens[token]; !ok {- return fmt.Errorf("unknown token %s in schema path template", token)+ return errors.Errorf("unknown token %s in schema path template", token)}}return nil@@ -221,11 +221,11 @@ func ValidateProjectDBNameTemplate(template string) error {hasDBName = true}if _, ok := allowedProjectDBNameTemplateTokens[token]; !ok {- return fmt.Errorf("invalid token %v in database name template", token)+ return errors.Errorf("invalid token %v in database name template", token)}}if !hasDBName {- return fmt.Errorf("project database name template must include token %v", DBNameToken)+ return errors.Errorf("project database name template must include token %v", DBNameToken)}return nil}@@ -236,7 +236,7 @@ func FormatTemplate(template string, tokens map[string]string) (string, error) {keys, _ := common.ParseTemplateTokens(template)for _, key := range keys {if _, ok := tokens[key]; !ok {- return "", fmt.Errorf("token %q not found", key)+ return "", errors.Errorf("token %q not found", key)}template = strings.ReplaceAll(template, key, tokens[key])}@@ -249,7 +249,7 @@ func formatTemplateRegexp(template string, tokens map[string]string) (string, erkeys, delimiters := common.ParseTemplateTokens(template)for _, key := range keys {if _, ok := tokens[key]; !ok {- return "", fmt.Errorf("token %q not found", key)+ return "", errors.Errorf("token %q not found", key)}template = strings.ReplaceAll(template, key, tokens[key])}@@ -287,15 +287,15 @@ func GetBaseDatabaseName(databaseName, dbNameTemplate, labelsJSON string) (strinexpr, err := formatTemplateRegexp(dbNameTemplate, labelMap)if err != nil {- return "", fmt.Errorf("FormatTemplate(%q, %+v) failed with error: %v", dbNameTemplate, labelMap, err)+ return "", errors.Wrapf(err, "FormatTemplate(%q, %+v) failed", dbNameTemplate, labelMap)}re, err := regexp.Compile(expr)if err != nil {- return "", fmt.Errorf("regexp %q compiled failure, error: %v", expr, err)+ return "", errors.Wrapf(err, "regexp %q compiled failure", expr)}names := re.FindStringSubmatch(databaseName)if len(names) != 2 || names[1] == "" {- return "", fmt.Errorf("database name %q doesn't follow database name template %q", databaseName, dbNameTemplate)+ return "", errors.Errorf("database name %q doesn't follow database name template %q", databaseName, dbNameTemplate)}return names[1], nil}diff --git a/bin/bb/cmd/utils.go b/bin/bb/cmd/utils.goindex a7743a65bd..56e425151a 100644--- a/bin/bb/cmd/utils.go+++ b/bin/bb/cmd/utils.go@@ -2,7 +2,6 @@ package cmdimport ("context"- "fmt""os""github.com/bytebase/bytebase/plugin/db"@@ -44,7 +43,7 @@ func open(ctx context.Context, u *dburl.URL) (db.Driver, error) {}pgInstanceDir = pgInstance.BaseDirdefault:- return nil, fmt.Errorf("database type %q not supported; supported types: mysql, pg", u.Driver)+ return nil, errors.Errorf("database type %q not supported; supported types: mysql, pg", u.Driver)}passwd, _ := u.User.Password()driver, err := db.Open(diff --git a/common/error.go b/common/error.goindex e04a482ff4..41017f4576 100644--- a/common/error.go+++ b/common/error.go@@ -2,7 +2,8 @@ package commonimport ("errors"- "fmt"++ pkgerrors "github.com/pkg/errors")// Code is the error code.@@ -90,17 +91,24 @@ func ErrorMessage(err error) string {return "Internal error."}-// Errorf is a helper function to return an Error with given code, format and-// arguments.+// Wrapf is a helper function to wrap an Error with given code and formatted message.+func Wrapf(err error, code Code, format string, args ...interface{}) *Error {+ return &Error{+ Code: code,+ Err: pkgerrors.Wrapf(err, format, args...),+ }+}++// Errorf is a helper function to create an Error with given code and formatted message.func Errorf(code Code, format string, args ...interface{}) *Error {return &Error{Code: code,- Err: fmt.Errorf(format, args...),+ Err: pkgerrors.Errorf(format, args...),}}-// WithError is a helper function to return an Error with given code and error.-func WithError(code Code, err error) *Error {+// Wrap is a helper function to wrap an Error with given code.+func Wrap(err error, code Code) *Error {return &Error{Code: code,Err: err,diff --git a/enterprise/api/license.go b/enterprise/api/license.goindex 56c9a7978a..09d57169cd 100644--- a/enterprise/api/license.go+++ b/enterprise/api/license.go@@ -1,11 +1,11 @@package apiimport (- "fmt""strings""time""github.com/bytebase/bytebase/api"+ "github.com/pkg/errors")// validPlans is a string array of valid plan types.@@ -28,7 +28,7 @@ type License struct {// Valid will check if license expired or has correct plan type.func (l *License) Valid() error {if expireTime := time.Unix(l.ExpiresTs, 0); expireTime.Before(time.Now()) {- return fmt.Errorf("license has expired at %v", expireTime)+ return errors.Errorf("license has expired at %v", expireTime)}return l.validPlanType()@@ -41,7 +41,7 @@ func (l *License) validPlanType() error {}}- return fmt.Errorf("plan %q is not valid, expect %s or %s",+ return errors.Errorf("plan %q is not valid, expect %s or %s",l.Plan.String(),api.TEAM.String(),api.ENTERPRISE.String(),diff --git a/enterprise/config/config.go b/enterprise/config/config.goindex 17b817740c..00ad08dd0e 100644--- a/enterprise/config/config.go+++ b/enterprise/config/config.go@@ -7,6 +7,7 @@ import ("github.com/bytebase/bytebase/common""github.com/bytebase/bytebase/common/log"+ "github.com/pkg/errors""go.uber.org/zap")@@ -45,7 +46,7 @@ func NewConfig(mode common.ReleaseMode) (*Config, error) {filename := fmt.Sprintf("keys/%s.pub.pem", mode)licensePubKey, err := fs.ReadFile(keysFS, fmt.Sprintf("keys/%s.pub.pem", mode))if err != nil {- return nil, fmt.Errorf("cannot read license public key for env %s", mode)+ return nil, errors.Errorf("cannot read license public key for env %s", mode)}log.Info("load public pem", zap.String("file", filename))diff --git a/enterprise/config/keys/README.md b/enterprise/config/keys/README.mdindex 596fb7d84b..86fee12349 100644--- a/enterprise/config/keys/README.md+++ b/enterprise/config/keys/README.md@@ -29,7 +29,7 @@ In `enterprise/service/license.go`, we will use public key to parse JWT```gotoken, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {- return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])+ return nil, errors.Errorf("unexpected signing method: %v", token.Header["alg"])}key, err := jwt.ParseRSAPublicKeyFromPEM([]byte(env.Conf.LicensePubKey))diff --git a/enterprise/service/license.go b/enterprise/service/license.goindex 0f9978a7df..11d5cfcb96 100644--- a/enterprise/service/license.go+++ b/enterprise/service/license.go@@ -2,9 +2,9 @@ package serviceimport ("context"- "fmt""github.com/golang-jwt/jwt/v4"+ "github.com/pkg/errors""github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common"@@ -79,13 +79,13 @@ func (s *LicenseService) parseLicense(license string) (*enterpriseAPI.License, ekey, err := jwt.ParseRSAPublicKeyFromPEM([]byte(s.config.PublicKey))if err != nil {- return nil, common.WithError(common.Invalid, err)+ return nil, common.Wrap(err, common.Invalid)}return key, nil})if err != nil {- return nil, common.WithError(common.Invalid, err)+ return nil, common.Wrap(err, common.Invalid)}if !token.Valid {@@ -99,7 +99,7 @@ func (s *LicenseService) parseLicense(license string) (*enterpriseAPI.License, efunc (s *LicenseService) parseClaims(claims *Claims) (*enterpriseAPI.License, error) {err := claims.Valid()if err != nil {- return nil, common.WithError(common.Invalid, err)+ return nil, common.Wrap(err, common.Invalid)}verifyIssuer := claims.VerifyIssuer(s.config.Issuer, true)@@ -133,7 +133,7 @@ func (s *LicenseService) parseClaims(claims *Claims) (*enterpriseAPI.License, er}if err := license.Valid(); err != nil {- return nil, common.WithError(common.Invalid, err)+ return nil, common.Wrap(err, common.Invalid)}return license, nil@@ -147,7 +147,7 @@ func (s *LicenseService) readLicense() (string, error) {})if len(settings) == 0 {- return "", common.Errorf(common.NotFound, "cannot find license with error %w", err)+ return "", common.Wrapf(err, common.NotFound, "cannot find license")}return settings[0].Value, nil@@ -172,6 +172,6 @@ func convertPlanType(candidate string) (api.PlanType, error) {case api.FREE.String():return api.FREE, nildefault:- return api.FREE, fmt.Errorf("cannot conver plan type %q", candidate)+ return api.FREE, errors.Errorf("cannot conver plan type %q", candidate)}}diff --git a/plugin/advisor/advisor.go b/plugin/advisor/advisor.goindex d37edf645e..13504d345e 100644--- a/plugin/advisor/advisor.go+++ b/plugin/advisor/advisor.go@@ -8,6 +8,7 @@ import ("github.com/bytebase/bytebase/plugin/advisor/catalog""github.com/bytebase/bytebase/plugin/advisor/db"+ "github.com/pkg/errors""go.uber.org/zap/zapcore")@@ -34,7 +35,7 @@ func NewStatusBySQLReviewRuleLevel(level SQLReviewRuleLevel) (Status, error) {case SchemaRuleLevelWarning:return Warn, nil}- return "", fmt.Errorf("unexpected rule level type: %s", level)+ return "", errors.Errorf("unexpected rule level type: %s", level)}// Type is the type of advisor.@@ -226,12 +227,12 @@ func Check(dbType db.Type, advType Type, ctx Context, statement string) ([]AdvicdbAdvisors, ok := advisors[dbType]defer advisorMu.RUnlock()if !ok {- return nil, fmt.Errorf("advisor: unknown db advisor type %v", dbType)+ return nil, errors.Errorf("advisor: unknown db advisor type %v", dbType)}f, ok := dbAdvisors[advType]if !ok {- return nil, fmt.Errorf("advisor: unknown advisor %v for %v", advType, dbType)+ return nil, errors.Errorf("advisor: unknown advisor %v for %v", advType, dbType)}return f.Check(ctx, statement)diff --git a/plugin/advisor/config.go b/plugin/advisor/config.goindex 05f7ceadcf..bf70115cc3 100644--- a/plugin/advisor/config.go+++ b/plugin/advisor/config.go@@ -3,8 +3,8 @@ package advisorimport (_ "embed""encoding/json"- "fmt"+ "github.com/pkg/errors""gopkg.in/yaml.v3")@@ -52,7 +52,7 @@ func MergeSQLReviewRules(override *SQLReviewConfigOverride) ([]*SQLReviewRule, etemplate := findTemplate(templateList, override.Template)if template == nil {- return nil, fmt.Errorf("cannot find the template: %v", override.Template)+ return nil, errors.Errorf("cannot find the template: %v", override.Template)}ruleUpdateMap := make(map[SQLReviewRuleType]*SQLReviewRuleData)diff --git a/plugin/advisor/db/db.go b/plugin/advisor/db/db.goindex 10d4a495ff..38dfbdf1b8 100644--- a/plugin/advisor/db/db.go+++ b/plugin/advisor/db/db.go@@ -1,8 +1,9 @@package dbimport (- "fmt""strings"++ "github.com/pkg/errors")// Type is the type of a database.@@ -29,5 +30,5 @@ func ConvertToAdvisorDBType(dbType string) (Type, error) {return TiDB, nil}- return "", fmt.Errorf("unsupported db type %s for advisor", dbType)+ return "", errors.Errorf("unsupported db type %s for advisor", dbType)}diff --git a/plugin/advisor/sql_review.go b/plugin/advisor/sql_review.goindex d00a1ecb98..21a04bb6ef 100644--- a/plugin/advisor/sql_review.go+++ b/plugin/advisor/sql_review.go@@ -3,7 +3,6 @@ package advisorimport ("context""encoding/json"- "fmt""log""regexp"@@ -126,7 +125,7 @@ type SQLReviewPolicy struct {// Validate validates the SQLReviewPolicy. It also validates the each review rule.func (policy *SQLReviewPolicy) Validate() error {if policy.Name == "" || len(policy.RuleList) == 0 {- return fmt.Errorf("invalid payload, name or rule list cannot be empty")+ return errors.Errorf("invalid payload, name or rule list cannot be empty")}for _, rule := range policy.RuleList {if err := rule.Validate(); err != nil {@@ -211,7 +210,7 @@ func UnmarshalNamingRulePayloadAsTemplate(ruleType SQLReviewRuleType, payload stfor _, key := range keys {if _, ok := TemplateNamingTokens[ruleType][key]; !ok {- return "", nil, 0, fmt.Errorf("invalid template %s for rule %s", key, ruleType)+ return "", nil, 0, errors.Errorf("invalid template %s for rule %s", key, ruleType)}}@@ -252,7 +251,7 @@ func UnmarshalRequiredColumnRulePayload(payload string) (*RequiredColumnRulePaylreturn nil, errors.Wrapf(err, "failed to unmarshal required column rule payload %q", payload)}if len(rcr.ColumnList) == 0 {- return nil, fmt.Errorf("invalid required column rule payload, column list cannot be empty")+ return nil, errors.Errorf("invalid required column rule payload, column list cannot be empty")}return &rcr, nil}@@ -428,5 +427,5 @@ func getAdvisorTypeByRule(ruleType SQLReviewRuleType, engine db.Type) (Type, errreturn MySQLDatabaseAllowDropIfEmpty, nil}}- return Fake, fmt.Errorf("unknown SQL review rule type %v for %v", ruleType, engine)+ return Fake, errors.Errorf("unknown SQL review rule type %v for %v", ruleType, engine)}diff --git a/plugin/db/driver.go b/plugin/db/driver.goindex 26475fda9c..288c859cc2 100644--- a/plugin/db/driver.go+++ b/plugin/db/driver.go@@ -10,6 +10,7 @@ import ("sync""github.com/bytebase/bytebase/plugin/vcs"+ "github.com/pkg/errors")// Type is the type of a database.@@ -259,10 +260,10 @@ func ParseMigrationInfo(filePath string, filePathTemplate string) (*MigrationInf}myRegex, err := regexp.Compile(filePathRegex)if err != nil {- return nil, fmt.Errorf("invalid file path template: %q", filePathTemplate)+ return nil, errors.Errorf("invalid file path template: %q", filePathTemplate)}if !myRegex.MatchString(filePath) {- return nil, fmt.Errorf("file path %q does not match file path template %q", filePath, filePathTemplate)+ return nil, errors.Errorf("file path %q does not match file path template %q", filePath, filePathTemplate)}mi := &MigrationInfo{@@ -288,7 +289,7 @@ func ParseMigrationInfo(filePath string, filePathTemplate string) (*MigrationInfcase "migrate":mi.Type = Migratedefault:- return nil, fmt.Errorf("file path %q contains invalid migration type %q, must be 'migrate' or 'data'", filePath, matchList[index])+ return nil, errors.Errorf("file path %q contains invalid migration type %q, must be 'migrate' or 'data'", filePath, matchList[index])}case "DESCRIPTION":mi.Description = matchList[index]@@ -297,10 +298,10 @@ func ParseMigrationInfo(filePath string, filePathTemplate string) (*MigrationInf}if mi.Version == "" {- return nil, fmt.Errorf("file path %q does not contain {{VERSION}}, configured file path template %q", filePath, filePathTemplate)+ return nil, errors.Errorf("file path %q does not contain {{VERSION}}, configured file path template %q", filePath, filePathTemplate)}if mi.Namespace == "" {- return nil, fmt.Errorf("file path %q does not contain {{DB_NAME}}, configured file path template %q", filePath, filePathTemplate)+ return nil, errors.Errorf("file path %q does not contain {{DB_NAME}}, configured file path template %q", filePath, filePathTemplate)}if mi.Description == "" {@@ -446,7 +447,7 @@ func Open(ctx context.Context, dbType Type, driverConfig DriverConfig, connectiof, ok := drivers[dbType]driversMu.RUnlock()if !ok {- return nil, fmt.Errorf("db: unknown driver %v", dbType)+ return nil, errors.Errorf("db: unknown driver %v", dbType)}driver, err := f(driverConfig).Open(ctx, dbType, connectionConfig, connCtx)diff --git a/plugin/db/mysql/dump.go b/plugin/db/mysql/dump.goindex 2294e08606..eed635d9b4 100644--- a/plugin/db/mysql/dump.go+++ b/plugin/db/mysql/dump.go@@ -415,7 +415,7 @@ func getTableStmt(txn *sql.Tx, dbName, tblName, tblType string) (string, error)}return fmt.Sprintf(viewStmtFmt, tblName, createStmt), nildefault:- return "", fmt.Errorf("unrecognized table type %q for database %q table %q", tblType, dbName, tblName)+ return "", errors.Errorf("unrecognized table type %q for database %q table %q", tblType, dbName, tblName)}}@@ -686,7 +686,7 @@ func (driver *Driver) restoreImpl(ctx context.Context, backup io.Reader, databasmysqlCmd.Stderr = &stderrif err := mysqlCmd.Run(); err != nil {- return fmt.Errorf("mysql command fails, error: %w, %s", err, stderr.String())+ return errors.Wrapf(err, "mysql command fails: %s", stderr.String())}return nildiff --git a/plugin/db/mysql/restore.go b/plugin/db/mysql/restore.goindex 9a7e4c68bd..b9ad6ea108 100644--- a/plugin/db/mysql/restore.go+++ b/plugin/db/mysql/restore.go@@ -119,7 +119,7 @@ func (driver *Driver) replayBinlog(ctx context.Context, originalDatabase, targetcase LetterCaseOnDiskLowerCaseCmp:originalDBName = strings.ToLower(originalDatabase)default:- return fmt.Errorf("expecting value of %s in range [%d, %d, %d], but get %s", caseVariable, 0, 1, 2, identifierCaseSensitive)+ return errors.Errorf("expecting value of %s in range [%d, %d, %d], but get %s", caseVariable, 0, 1, 2, identifierCaseSensitive)}// Extract the SQL statements from the binlog and replay them to the pitrDatabase via the mysql client by pipe.@@ -256,18 +256,18 @@ func GetBinlogReplayList(startBinlogInfo api.BinlogInfo, binlogDir string) ([]st}if len(binlogFilesToReplay) == 0 {log.Error("No binlog files found locally after given start binlog info", zap.Any("startBinlogInfo", startBinlogInfo))- return nil, fmt.Errorf("no binlog files found locally after given start binlog info: %v", startBinlogInfo)+ return nil, errors.Errorf("no binlog files found locally after given start binlog info: %v", startBinlogInfo)}binlogFilesToReplaySorted := sortBinlogFiles(binlogFilesToReplay)if binlogFilesToReplaySorted[0].Seq != startBinlogSeq {log.Error("The starting binlog file does not exist locally", zap.String("filename", startBinlogInfo.FileName))- return nil, fmt.Errorf("the starting binlog file %q does not exist locally", startBinlogInfo.FileName)+ return nil, errors.Errorf("the starting binlog file %q does not exist locally", startBinlogInfo.FileName)}if !binlogFilesAreContinuous(binlogFilesToReplaySorted) {- return nil, fmt.Errorf("discontinuous binlog file extensions detected, skip ")+ return nil, errors.Errorf("discontinuous binlog file extensions detected, skip ")}var binlogReplayList []string@@ -294,7 +294,7 @@ func sortBinlogFiles(binlogFiles []BinlogFile) []BinlogFile {// The backupList should only contain DONE backups.func (driver *Driver) GetLatestBackupBeforeOrEqualTs(ctx context.Context, backupList []*api.Backup, targetTs int64, mode common.ReleaseMode) (*api.Backup, error) {if len(backupList) == 0 {- return nil, fmt.Errorf("no valid backup")+ return nil, errors.Errorf("no valid backup")}targetBinlogCoordinate, err := driver.getBinlogCoordinateByTs(ctx, targetTs)@@ -344,10 +344,10 @@ func (driver *Driver) getLatestBackupBeforeOrEqualBinlogCoord(backupList []*api.break}if bc.backup.Status == api.BackupStatusFailed && bc.backup.Type == api.BackupTypePITR {- return nil, fmt.Errorf("the backup %q taken after a former PITR cutover is failed, so we cannot recover to a point in time before this backup", bc.backup.Name)+ return nil, errors.Errorf("the backup %q taken after a former PITR cutover is failed, so we cannot recover to a point in time before this backup", bc.backup.Name)}if bc.backup.Status == api.BackupStatusPendingCreate && bc.backup.Type == api.BackupTypePITR {- return nil, fmt.Errorf("the backup %q taken after a former PITR cutover is still in progress, please try again later", bc.backup.Name)+ return nil, errors.Errorf("the backup %q taken after a former PITR cutover is still in progress, please try again later", bc.backup.Name)}}}@@ -371,7 +371,7 @@ func (driver *Driver) getLatestBackupBeforeOrEqualBinlogCoord(backupList []*api.log.Error("The target binlog coordinate is earlier than the oldest backup's binlog coordinate",zap.Any("targetBinlogCoordinate", targetBinlogCoordinate),zap.Any("oldestBackupBinlogCoordinate", oldestBackupBinlogCoordinate))- return nil, fmt.Errorf("the target binlog coordinate %v is earlier than the oldest backup's binlog coordinate %v", targetBinlogCoordinate, oldestBackupBinlogCoordinate)+ return nil, errors.Errorf("the target binlog coordinate %v is earlier than the oldest backup's binlog coordinate %v", targetBinlogCoordinate, oldestBackupBinlogCoordinate)}return backup, nil@@ -600,7 +600,7 @@ func (driver *Driver) downloadBinlogFile(ctx context.Context, binlogFileToDownlozap.Int64("sizeInfo", binlogFileToDownload.Size),zap.Int64("downloadedSize", fileInfo.Size()),)- return fmt.Errorf("downloaded archived binlog file %q size %d is not equal to size %d queried on MySQL server earlier", resultFilePath, fileInfo.Size(), binlogFileToDownload.Size)+ return errors.Errorf("downloaded archived binlog file %q size %d is not equal to size %d queried on MySQL server earlier", resultFilePath, fileInfo.Size(), binlogFileToDownload.Size)}return nil@@ -648,10 +648,10 @@ func (driver *Driver) getBinlogCoordinateByTs(ctx context.Context, targetTs int6return nil, errors.Wrap(err, "failed to read sorted local binlog files")}if len(binlogFilesLocalSorted) == 0 {- return nil, fmt.Errorf("no local binlog files found")+ return nil, errors.Errorf("no local binlog files found")}if !binlogFilesAreContinuous(binlogFilesLocalSorted) {- return nil, fmt.Errorf("local binlog files are not continuous")+ return nil, errors.Errorf("local binlog files are not continuous")}var binlogFileTarget *BinlogFile@@ -663,7 +663,7 @@ func (driver *Driver) getBinlogCoordinateByTs(ctx context.Context, targetTs int6log.Debug("Parsed first binlog event ts", zap.String("file", file.Name), zap.Int64("eventTs", eventTs))if eventTs >= targetTs {if i == 0 {- return nil, fmt.Errorf("the targetTs %d is before the first event ts %d of the oldest binlog file %q", targetTs, eventTs, file.Name)+ return nil, errors.Errorf("the targetTs %d is before the first event ts %d of the oldest binlog file %q", targetTs, eventTs, file.Name)}// The previous local binlog file contains targetTs.binlogFileTarget = &binlogFilesLocalSorted[i-1]@@ -681,7 +681,7 @@ func (driver *Driver) getBinlogCoordinateByTs(ctx context.Context, targetTs int6log.Debug("Found potential binlog file containing targetTs", zap.String("binlogFile", binlogFileTarget.Name), zap.Int64("targetTs", targetTs), zap.Bool("isLastBinlogFile", isLastBinlogFile))targetSeq, err := GetBinlogNameSeq(binlogFileTarget.Name)if err != nil {- return nil, fmt.Errorf("failed to parse seq from binlog file name %q", binlogFileTarget.Name)+ return nil, errors.Errorf("failed to parse seq from binlog file name %q", binlogFileTarget.Name)}eventPos, err := driver.getBinlogEventPositionAtOrAfterTs(ctx, *binlogFileTarget, targetTs)@@ -691,7 +691,7 @@ func (driver *Driver) getBinlogCoordinateByTs(ctx context.Context, targetTs int6// If this is the last binlog file, the user wants to recover to a time in the future and we should return an error.// Otherwise, we should return the end position of the current binlog file.if isLastBinlogFile {- return nil, fmt.Errorf("the targetTs %d is after the last event ts of the latest binlog file %q", targetTs, binlogFileTarget.Name)+ return nil, errors.Errorf("the targetTs %d is after the last event ts of the latest binlog file %q", targetTs, binlogFileTarget.Name)}return &binlogCoordinate{Seq: targetSeq, Pos: math.MaxInt64}, nil}@@ -714,7 +714,7 @@ func parseBinlogEventTsInLine(line string) (eventTs int64, found bool, err error// fields should starts with ["#220421", "14:49:26", "server", "id", "1", "end_log_pos", "34794"]if len(fields) < 7 ||(len(fields[0]) != 7 || fields[2] != "server" || fields[3] != "id" || fields[5] != "end_log_pos") {- return 0, false, fmt.Errorf("found unexpected mysqlbinlog output line %q when parsing binlog event timestamp", line)+ return 0, false, errors.Errorf("found unexpected mysqlbinlog output line %q when parsing binlog event timestamp", line)}datetime, err := time.ParseInLocation("060102 15:04:05", fmt.Sprintf("%s %s", fields[0][1:], fields[1]), time.Local)if err != nil {@@ -731,7 +731,7 @@ func parseBinlogEventPosInLine(line string) (pos int64, found bool, err error) {// This is the line containing the start position of the binlog event.fields := strings.Fields(line)if len(fields) != 3 {- return 0, false, fmt.Errorf("unexpected mysqlbinlog output line %q when parsing binlog event start position", line)+ return 0, false, errors.Errorf("unexpected mysqlbinlog output line %q when parsing binlog event start position", line)}pos, err = strconv.ParseInt(fields[2], 10, 0)if err != nil {@@ -840,7 +840,7 @@ func (driver *Driver) getBinlogEventPositionAtOrAfterTs(ctx context.Context, binfunc GetBinlogNameSeq(name string) (int64, error) {s := strings.Split(name, ".")if len(s) != 2 {- return 0, fmt.Errorf("failed to parse binlog extension, expecting two parts in the binlog file name %q but got %d", name, len(s))+ return 0, errors.Errorf("failed to parse binlog extension, expecting two parts in the binlog file name %q but got %d", name, len(s))}return strconv.ParseInt(s[1], 10, 0)}@@ -853,7 +853,7 @@ func checkVersionForPITR(version string) error {}v8 := semver.MustParse("8.0.0")if v.LT(v8) {- return fmt.Errorf("version %s is not supported for PITR; the minimum supported version is 8.0", version)+ return errors.Errorf("version %s is not supported for PITR; the minimum supported version is 8.0", version)}return nil}@@ -895,7 +895,7 @@ func (driver *Driver) CheckEngineInnoDB(ctx context.Context, database string) erreturn util.FormatErrorWithQuery(err, query)}if len(tablesNotInnoDB) != 0 {- return fmt.Errorf("tables %v of database %s do not use the InnoDB engine, which is required for PITR", tablesNotInnoDB, database)+ return errors.Errorf("tables %v of database %s do not use the InnoDB engine, which is required for PITR", tablesNotInnoDB, database)}return nil}@@ -915,7 +915,7 @@ func (driver *Driver) getServerVariable(ctx context.Context, varName string) (streturn "", util.FormatErrorWithQuery(err, query)}if varName != varNameFound {- return "", fmt.Errorf("expecting variable %s, but got %s", varName, varNameFound)+ return "", errors.Errorf("expecting variable %s, but got %s", varName, varNameFound)}return value, nil}@@ -927,7 +927,7 @@ func (driver *Driver) CheckBinlogEnabled(ctx context.Context) error {return err}if strings.ToUpper(value) != "ON" {- return fmt.Errorf("binlog is not enabled")+ return errors.Errorf("binlog is not enabled")}return nil}@@ -939,7 +939,7 @@ func (driver *Driver) CheckBinlogRowFormat(ctx context.Context) error {return err}if strings.ToUpper(value) != "ROW" {- return fmt.Errorf("binlog format is not ROW but %s", value)+ return errors.Errorf("binlog format is not ROW but %s", value)}return nil}diff --git a/plugin/db/pg/dump.go b/plugin/db/pg/dump.goindex e13c95aec8..fc90990ad1 100644--- a/plugin/db/pg/dump.go+++ b/plugin/db/pg/dump.go@@ -35,7 +35,7 @@ func (driver *Driver) Dump(ctx context.Context, database string, out io.Writer,}}if !exist {- return "", fmt.Errorf("database %s not found", database)+ return "", errors.Errorf("database %s not found", database)}dumpableDbNames = []string{database}} else {diff --git a/plugin/db/pg/pg.go b/plugin/db/pg/pg.goindex be1a79ba5d..282e06f045 100644--- a/plugin/db/pg/pg.go+++ b/plugin/db/pg/pg.go@@ -9,6 +9,7 @@ import (// Import pg driver.// init() in pgx/v4/stdlib will register it's pgx driver._ "github.com/jackc/pgx/v4/stdlib"+ "github.com/pkg/errors""github.com/bytebase/bytebase/common""github.com/bytebase/bytebase/plugin/db"@@ -57,7 +58,7 @@ func newDriver(config db.DriverConfig) db.Driver {func (driver *Driver) Open(_ context.Context, _ db.Type, config db.ConnectionConfig, connCtx db.ConnectionContext) (db.Driver, error) {if (config.TLSConfig.SslCert == "" && config.TLSConfig.SslKey != "") ||(config.TLSConfig.SslCert != "" && config.TLSConfig.SslKey == "") {- return nil, fmt.Errorf("ssl-cert and ssl-key must be both set or unset")+ return nil, errors.Errorf("ssl-cert and ssl-key must be both set or unset")}databaseName, dsn, err := guessDSN(@@ -153,9 +154,9 @@ func guessDSN(username, password, hostname, port, database, sslCA, sslCert, sslK}if database != "" {- return "", "", fmt.Errorf("cannot connecting %q, make sure the connection info is correct and the database exists", database)+ return "", "", errors.Errorf("cannot connecting %q, make sure the connection info is correct and the database exists", database)}- return "", "", fmt.Errorf("cannot connecting instance, make sure the connection info is correct")+ return "", "", errors.Errorf("cannot connecting instance, make sure the connection info is correct")}// Close closes the driver.@@ -257,7 +258,7 @@ func (driver *Driver) Execute(ctx context.Context, statement string) error {// For the case of `\connect "dbname";`, we need to use GetDBConnection() instead of executing the statement.parts := strings.Split(stmt, `"`)if len(parts) != 3 {- return fmt.Errorf("invalid statement %q", stmt)+ return errors.Errorf("invalid statement %q", stmt)}if _, err = driver.GetDBConnection(ctx, parts[1]); err != nil {return err@@ -311,7 +312,7 @@ func getDatabaseInCreateDatabaseStatement(createDatabaseStatement string) (strinraw = strings.TrimPrefix(raw, "CREATE DATABASE")tokens := strings.Fields(raw)if len(tokens) == 0 {- return "", fmt.Errorf("database name not found")+ return "", errors.Errorf("database name not found")}databaseName := strings.TrimLeft(tokens[0], `"`)databaseName = strings.TrimRight(databaseName, `"`)@@ -345,7 +346,7 @@ func (driver *Driver) getCurrentDatabaseOwner() (string, error) {return "", err}if owner == "" {- return "", fmt.Errorf("owner not found for the current database")+ return "", errors.Errorf("owner not found for the current database")}return owner, nil}diff --git a/plugin/db/pg/sync.go b/plugin/db/pg/sync.goindex afc67a2601..fadb4cb077 100644--- a/plugin/db/pg/sync.go+++ b/plugin/db/pg/sync.go@@ -494,7 +494,7 @@ func getViews(txn *sql.Tx) ([]*viewSchema, error) {// Return error on NULL view definition.// https://github.com/bytebase/bytebase/issues/343if !def.Valid {- return nil, fmt.Errorf("schema %q view %q has empty definition; please check whether proper privileges have been granted to Bytebase", view.schemaName, view.name)+ return nil, errors.Errorf("schema %q view %q has empty definition; please check whether proper privileges have been granted to Bytebase", view.schemaName, view.name)}view.definition = def.Stringviews = append(views, &view)@@ -647,7 +647,7 @@ func convertBoolFromYesNo(s string) (bool, error) {case "NO":return false, nildefault:- return false, fmt.Errorf("unrecognized isNullable type %q", s)+ return false, errors.Errorf("unrecognized isNullable type %q", s)}}@@ -664,7 +664,7 @@ func getIndexColumnExpressions(stmt string) ([]string, error) {rc := regexp.MustCompile(`\((.*)\)`)rm := rc.FindStringSubmatch(stmt)if len(rm) == 0 {- return nil, fmt.Errorf("invalid index statement: %q", stmt)+ return nil, errors.Errorf("invalid index statement: %q", stmt)}columnStmt := rm[1]@@ -689,7 +689,7 @@ func getIndexColumnExpressions(stmt string) ([]string, error) {}// Strip tokenif len(token) == 0 {- return nil, fmt.Errorf("invalid index statement: %q", stmt)+ return nil, errors.Errorf("invalid index statement: %q", stmt)}columnStmt = columnStmt[len(token):]cols = append(cols, strings.TrimSpace(token))diff --git a/plugin/db/snowflake/snowflake.go b/plugin/db/snowflake/snowflake.goindex 29d1faf83f..fe1fc1e80a 100644--- a/plugin/db/snowflake/snowflake.go+++ b/plugin/db/snowflake/snowflake.go@@ -10,6 +10,7 @@ import ("github.com/bytebase/bytebase/common/log""github.com/bytebase/bytebase/plugin/db""github.com/bytebase/bytebase/plugin/db/util"+ "github.com/pkg/errors"snow "github.com/snowflakedb/gosnowflake""go.uber.org/zap"@@ -52,7 +53,7 @@ func (driver *Driver) Open(_ context.Context, dbType db.Type, config db.Connectiif strings.Contains(config.Host, "@") {parts := strings.Split(config.Host, "@")if len(parts) != 2 {- return nil, fmt.Errorf("driver.Open() has invalid host %q", config.Host)+ return nil, errors.Errorf("driver.Open() has invalid host %q", config.Host)}account, host = parts[0], parts[1]} else {diff --git a/plugin/db/sqlite/dump.go b/plugin/db/sqlite/dump.goindex 2351f657ef..7fe5b9e258 100644--- a/plugin/db/sqlite/dump.go+++ b/plugin/db/sqlite/dump.go@@ -14,7 +14,7 @@ import (// Dump dumps the database.func (driver *Driver) Dump(ctx context.Context, database string, out io.Writer, schemaOnly bool) (string, error) {if database == "" {- return "", fmt.Errorf("SQLite can dump one database only at a time")+ return "", errors.Errorf("SQLite can dump one database only at a time")}// Find all dumpable databases and make sure the existence of the database to be dumped.@@ -30,7 +30,7 @@ func (driver *Driver) Dump(ctx context.Context, database string, out io.Writer,}}if !exist {- return "", fmt.Errorf("database %s not found", database)+ return "", errors.Errorf("database %s not found", database)}if err := driver.dumpOneDatabase(ctx, database, out, schemaOnly); err != nil {diff --git a/plugin/db/sqlite/sqlite.go b/plugin/db/sqlite/sqlite.goindex ab4d161c8f..8d721ce03c 100644--- a/plugin/db/sqlite/sqlite.go+++ b/plugin/db/sqlite/sqlite.go@@ -130,7 +130,7 @@ func (driver *Driver) Execute(ctx context.Context, statement string) error {if strings.HasPrefix(stmt, "CREATE DATABASE ") {parts := strings.Split(stmt, `'`)if len(parts) != 3 {- return fmt.Errorf("invalid statement %q", stmt)+ return errors.Errorf("invalid statement %q", stmt)}db, err := driver.GetDBConnection(ctx, parts[1])if err != nil {diff --git a/plugin/db/ssl.go b/plugin/db/ssl.goindex a2fa592dcc..dbc3cf88cf 100644--- a/plugin/db/ssl.go+++ b/plugin/db/ssl.go@@ -3,7 +3,6 @@ package dbimport ("crypto/tls""crypto/x509"- "fmt""github.com/pkg/errors")@@ -22,14 +21,14 @@ func (tc TLSConfig) GetSslConfig() (*tls.Config, error) {}rootCertPool := x509.NewCertPool()if ok := rootCertPool.AppendCertsFromPEM([]byte(tc.SslCA)); !ok {- return nil, fmt.Errorf("rootCertPool.AppendCertsFromPEM() failed to append server CA pem")+ return nil, errors.Errorf("rootCertPool.AppendCertsFromPEM() failed to append server CA pem")}cfg := &tls.Config{RootCAs: rootCertPool,}if (tc.SslCert == "" && tc.SslKey != "") || (tc.SslCert != "" && tc.SslKey == "") {- return nil, fmt.Errorf("ssl-cert and ssl-key must be both set or unset")+ return nil, errors.Errorf("ssl-cert and ssl-key must be both set or unset")}if tc.SslCert != "" && tc.SslKey != "" {var clientCert []tls.Certificate@@ -45,7 +44,7 @@ func (tc TLSConfig) GetSslConfig() (*tls.Config, error) {cfg.InsecureSkipVerify = truecfg.VerifyPeerCertificate = func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {if len(rawCerts) == 0 {- return fmt.Errorf("empty certificate to verify")+ return errors.Errorf("empty certificate to verify")}cert, err := x509.ParseCertificate(rawCerts[0])if err != nil {diff --git a/plugin/db/util/driverutil.go b/plugin/db/util/driverutil.goindex d378607381..d23096a214 100644--- a/plugin/db/util/driverutil.go+++ b/plugin/db/util/driverutil.go@@ -22,7 +22,7 @@ import (// FormatErrorWithQuery will format the error with failed query.func FormatErrorWithQuery(err error, query string) error {- return common.Errorf(common.DbExecutionError, "failed to execute query %q, error: %w", query, err)+ return common.Wrapf(err, common.DbExecutionError, "failed to execute query %q", query)}// ApplyMultiStatements will apply the split statements from scanner.@@ -39,7 +39,7 @@ func ApplyMultiStatements(sc io.Reader, f func(string) error) error {case strings.HasPrefix(line, "/*"):if strings.Contains(line, "*/") {if !strings.HasSuffix(line, "*/") {- return fmt.Errorf("`*/` must be the end of the line; new statement should start as a new line")+ return errors.Errorf("`*/` must be the end of the line; new statement should start as a new line")}} else {comment = true@@ -50,7 +50,7 @@ func ApplyMultiStatements(sc io.Reader, f func(string) error) error {continuecase comment && strings.Contains(line, "*/"):if !strings.HasSuffix(line, "*/") {- return fmt.Errorf("`*/` must be the end of the line; new statement should start as a new line")+ return errors.Errorf("`*/` must be the end of the line; new statement should start as a new line")}comment = falsecontinue@@ -214,21 +214,21 @@ func BeginMigration(ctx context.Context, executor MigrationExecutor, m *db.Migrareturn int64(list[0].ID),common.Errorf(common.MigrationAlreadyApplied, "database %q has already applied version %s", m.Database, m.Version)case db.Pending:- err := fmt.Errorf("database %q version %s migration is already in progress", m.Database, m.Version)+ err := errors.Errorf("database %q version %s migration is already in progress", m.Database, m.Version)log.Debug(err.Error())// For force migration, we will ignore the existing migration history and continue to migration.if m.Force {return int64(list[0].ID), nil}- return -1, common.WithError(common.MigrationPending, err)+ return -1, common.Wrap(err, common.MigrationPending)case db.Failed:- err := fmt.Errorf("database %q version %s migration has failed, please check your database to make sure things are fine and then start a new migration using a new version ", m.Database, m.Version)+ err := errors.Errorf("database %q version %s migration has failed, please check your database to make sure things are fine and then start a new migration using a new version ", m.Database, m.Version)log.Debug(err.Error())// For force migration, we will ignore the existing migration history and continue to migration.if m.Force {return int64(list[0].ID), nil}- return -1, common.WithError(common.MigrationFailed, err)+ return -1, common.Wrap(err, common.MigrationFailed)}}@@ -471,9 +471,9 @@ func FormatError(err error) error {}if strings.Contains(err.Error(), "bytebase_idx_unique_migration_history_namespace_version") {- return fmt.Errorf("version has already been applied")+ return errors.Errorf("version has already been applied")} else if strings.Contains(err.Error(), "bytebase_idx_unique_migration_history_namespace_sequence") {- return fmt.Errorf("concurrent migration")+ return errors.Errorf("concurrent migration")}return err@@ -495,7 +495,7 @@ func ToStoredVersion(useSemanticVersion bool, version, semanticVersionSuffix str}major, minor, patch := fmt.Sprintf("%d", v.Major), fmt.Sprintf("%d", v.Minor), fmt.Sprintf("%d", v.Patch)if len(major) > 4 || len(minor) > 4 || len(patch) > 4 {- return "", fmt.Errorf("invalid version %q, major, minor, patch version should be < 10000", version)+ return "", errors.Errorf("invalid version %q, major, minor, patch version should be < 10000", version)}return fmt.Sprintf("%04s.%04s.%04s-%s", major, minor, patch, semanticVersionSuffix), nil}@@ -507,27 +507,27 @@ func fromStoredVersion(storedVersion string) (bool, string, string, error) {}idx := strings.Index(storedVersion, "-")if idx < 0 {- return false, "", "", fmt.Errorf("invalid stored version %q, version should contain '-'", storedVersion)+ return false, "", "", errors.Errorf("invalid stored version %q, version should contain '-'", storedVersion)}prefix, suffix := storedVersion[:idx], storedVersion[idx+1:]parts := strings.Split(prefix, ".")if len(parts) != 3 {- return false, "", "", fmt.Errorf("invalid stored version %q, version prefix %q should be in semantic version format", storedVersion, prefix)+ return false, "", "", errors.Errorf("invalid stored version %q, version prefix %q should be in semantic version format", storedVersion, prefix)}major, err := strconv.Atoi(parts[0])if err != nil {- return false, "", "", fmt.Errorf("invalid stored version %q, version prefix %q should be in semantic version format", storedVersion, prefix)+ return false, "", "", errors.Errorf("invalid stored version %q, version prefix %q should be in semantic version format", storedVersion, prefix)}minor, err := strconv.Atoi(parts[1])if err != nil {- return false, "", "", fmt.Errorf("invalid stored version %q, version prefix %q should be in semantic version format", storedVersion, prefix)+ return false, "", "", errors.Errorf("invalid stored version %q, version prefix %q should be in semantic version format", storedVersion, prefix)}patch, err := strconv.Atoi(parts[2])if err != nil {- return false, "", "", fmt.Errorf("invalid stored version %q, version prefix %q should be in semantic version format", storedVersion, prefix)+ return false, "", "", errors.Errorf("invalid stored version %q, version prefix %q should be in semantic version format", storedVersion, prefix)}if major >= 10000 || minor >= 10000 || patch >= 10000 {- return false, "", "", fmt.Errorf("invalid stored version %q, major, minor, patch version of %q should be < 10000", storedVersion, prefix)+ return false, "", "", errors.Errorf("invalid stored version %q, major, minor, patch version of %q should be < 10000", storedVersion, prefix)}return true, fmt.Sprintf("%d.%d.%d", major, minor, patch), suffix, nil}diff --git a/plugin/parser/engine/pg/convert.go b/plugin/parser/engine/pg/convert.goindex 6f7fdee78a..9188ff5c38 100644--- a/plugin/parser/engine/pg/convert.go+++ b/plugin/parser/engine/pg/convert.go@@ -1,11 +1,10 @@package pgimport (- "fmt"-"github.com/bytebase/bytebase/plugin/parser""github.com/bytebase/bytebase/plugin/parser/ast"pgquery "github.com/pganalyze/pg_query_go/v2"+ "github.com/pkg/errors")// convert converts the pg_query.Node to ast.Node.@@ -575,7 +574,7 @@ func convertSetOperation(t pgquery.SetOperation) (ast.SetOperationType, error) {case pgquery.SetOperation_SETOP_EXCEPT:return ast.SetOperationTypeExcept, nildefault:- return 0, fmt.Errorf("failed to parse set operation: unknown type %s", t)+ return 0, errors.Errorf("failed to parse set operation: unknown type %s", t)}}diff --git a/plugin/parser/engine/pg/parser.go b/plugin/parser/engine/pg/parser.goindex 6b3648f37b..c3229b55db 100644--- a/plugin/parser/engine/pg/parser.go+++ b/plugin/parser/engine/pg/parser.go@@ -1,11 +1,10 @@package pgimport (- "fmt"-"github.com/bytebase/bytebase/plugin/parser""github.com/bytebase/bytebase/plugin/parser/ast"pgquery "github.com/pganalyze/pg_query_go/v2"+ "github.com/pkg/errors")var (@@ -37,7 +36,7 @@ func (*PostgreSQLParser) Parse(_ parser.Context, statement string) ([]ast.Node,return nil, err}if len(res.Stmts) != len(textList) {- return nil, fmt.Errorf("split multi-SQL failed: the length should be %d, but get %d. stmt: \"%s\"", len(res.Stmts), len(textList), statement)+ return nil, errors.Errorf("split multi-SQL failed: the length should be %d, but get %d. stmt: \"%s\"", len(res.Stmts), len(textList), statement)}var nodeList []ast.Nodediff --git a/plugin/parser/error.go b/plugin/parser/error.goindex c046adec3b..b793894912 100644--- a/plugin/parser/error.go+++ b/plugin/parser/error.go@@ -1,6 +1,6 @@package parser-import "fmt"+import "github.com/pkg/errors"// ConvertError is the conversion error.// Because this module is still in its early stages and lacks sufficient testing to ensure compatibility,@@ -18,5 +18,5 @@ func (e *ConvertError) Error() string {// NewConvertErrorf returns the new conversion error.func NewConvertErrorf(format string, a ...interface{}) *ConvertError {- return &ConvertError{err: fmt.Errorf(format, a...)}+ return &ConvertError{err: errors.Errorf(format, a...)}}diff --git a/plugin/parser/parser.go b/plugin/parser/parser.goindex f1cfa59352..80aeaebd30 100644--- a/plugin/parser/parser.go+++ b/plugin/parser/parser.go@@ -1,9 +1,10 @@package parserimport (- "fmt""sync"+ "github.com/pkg/errors"+"github.com/bytebase/bytebase/plugin/parser/ast")@@ -54,7 +55,7 @@ func Parse(engineType EngineType, ctx Context, statement string) ([]ast.Node, erp, ok := parsers[engineType]parserMu.RUnlock()if !ok {- return nil, fmt.Errorf("engine: unknown engine type %v", engineType)+ return nil, errors.Errorf("engine: unknown engine type %v", engineType)}return p.Parse(ctx, statement)}diff --git a/plugin/parser/split_multi_sql_test.go b/plugin/parser/split_multi_sql_test.goindex 08b4c45e3d..39971576a9 100644--- a/plugin/parser/split_multi_sql_test.go+++ b/plugin/parser/split_multi_sql_test.go@@ -1,7 +1,6 @@package parserimport (- "fmt""testing""github.com/stretchr/testify/require"@@ -14,7 +13,7 @@ type testData struct {type resData struct {res []SingleSQL- err error+ err string}func TestPGSplitMultiSQL(t *testing.T) {@@ -150,31 +149,35 @@ func TestPGSplitMultiSQL(t *testing.T) {{statement: `INSERT INTO t VALUES ('klajfas)`,want: resData{- err: fmt.Errorf("invalid string: not found delimiter: ', but found EOF"),+ err: "invalid string: not found delimiter: ', but found EOF",},},{statement: `INSERT INTO "t VALUES ('klajfas)`,want: resData{- err: fmt.Errorf("invalid indentifier: not found delimiter: \", but found EOF"),+ err: "invalid indentifier: not found delimiter: \", but found EOF",},},{statement: `/*INSERT INTO "t VALUES ('klajfas)`,want: resData{- err: fmt.Errorf("invalid comment: not found */, but found EOF"),+ err: "invalid comment: not found */, but found EOF",},},{statement: `$$INSERT INTO "t VALUES ('klajfas)`,want: resData{- err: fmt.Errorf("scanTo failed: delimiter \"$$\" not found"),+ err: "scanTo failed: delimiter \"$$\" not found",},},}for _, test := range tests {res, err := SplitMultiSQL(Postgres, test.statement)- require.Equal(t, test.want, resData{res, err}, test.statement)+ errStr := ""+ if err != nil {+ errStr = err.Error()+ }+ require.Equal(t, test.want, resData{res, errStr}, test.statement)}}diff --git a/plugin/parser/tokenizer.go b/plugin/parser/tokenizer.goindex 99f25fd777..b9a710bc44 100644--- a/plugin/parser/tokenizer.go+++ b/plugin/parser/tokenizer.go@@ -1,8 +1,9 @@package parserimport (- "fmt""unicode"++ "github.com/pkg/errors")const (@@ -103,7 +104,7 @@ func (t *tokenizer) splitPostgreSQLMultiSQL() ([]SingleSQL, error) {t.skip(uint(len(beginRuneList)))t.skipBlank()if t.equalWordCaseInsensitive(atomicRuneList) {- return nil, fmt.Errorf("not support BEGIN ATOMIC ... END in PostgreSQL CREATE PROCEDURE statement, please use double doller style($$ or $tag$) instead of it")+ return nil, errors.Errorf("not support BEGIN ATOMIC ... END in PostgreSQL CREATE PROCEDURE statement, please use double doller style($$ or $tag$) instead of it")}case t.char(0) == '\n':t.line++@@ -118,7 +119,7 @@ func (t *tokenizer) splitPostgreSQLMultiSQL() ([]SingleSQL, error) {// See https://www.postgresql.org/docs/current/sql-syntax-lexical.html.func (t *tokenizer) scanIdentifier(delimiter rune) error {if t.char(0) != delimiter {- return fmt.Errorf("delimiter doesn't start with delimiter: %c, but found: %c", delimiter, t.char(0))+ return errors.Errorf("delimiter doesn't start with delimiter: %c, but found: %c", delimiter, t.char(0))}t.skip(1)@@ -128,7 +129,7 @@ func (t *tokenizer) scanIdentifier(delimiter rune) error {t.skip(1)return nilcase eofRune:- return fmt.Errorf("invalid indentifier: not found delimiter: %c, but found EOF", delimiter)+ return errors.Errorf("invalid indentifier: not found delimiter: %c, but found EOF", delimiter)default:t.skip(1)}@@ -147,7 +148,7 @@ func (t *tokenizer) scanIdentifier(delimiter rune) error {// And this is extensible.func (t *tokenizer) scanString(delimiter rune) error {if t.char(0) != delimiter {- return fmt.Errorf("string doesn't start with delimiter: %c, but found: %c", delimiter, t.char(0))+ return errors.Errorf("string doesn't start with delimiter: %c, but found: %c", delimiter, t.char(0))}t.skip(1)@@ -157,7 +158,7 @@ func (t *tokenizer) scanString(delimiter rune) error {t.skip(1)return nilcase eofRune:- return fmt.Errorf("invalid string: not found delimiter: %c, but found EOF", delimiter)+ return errors.Errorf("invalid string: not found delimiter: %c, but found EOF", delimiter)case '\\':// skip two because we want to skip \' and \\.t.skip(2)@@ -196,7 +197,7 @@ func (t *tokenizer) scanComment() error {t.skip(2)return nilcase t.char(0) == eofRune:- return fmt.Errorf("invalid comment: not found */, but found EOF")+ return errors.Errorf("invalid comment: not found */, but found EOF")case t.char(0) == '\n':t.line++t.skip(1)@@ -219,13 +220,13 @@ func (t *tokenizer) scanComment() error {}}}- return fmt.Errorf("no comment found")+ return errors.Errorf("no comment found")}// scanTo scans to delimiter. Use KMP algorithm.func (t *tokenizer) scanTo(delimiter []rune) error {if len(delimiter) == 0 {- return fmt.Errorf("scanTo failed: delimiter can not be nil")+ return errors.Errorf("scanTo failed: delimiter can not be nil")}// KMP algorithm.@@ -257,7 +258,7 @@ func (t *tokenizer) scanTo(delimiter []rune) error {return nil}if t.char(0) == eofRune {- return fmt.Errorf("scanTo failed: delimiter %q not found", string(delimiter))+ return errors.Errorf("scanTo failed: delimiter %q not found", string(delimiter))}if t.char(0) == '\n' {t.line++diff --git a/plugin/parser/utils.go b/plugin/parser/utils.goindex 333d385ae1..da0e06e990 100644--- a/plugin/parser/utils.go+++ b/plugin/parser/utils.go@@ -1,6 +1,6 @@package parser-import "fmt"+import "github.com/pkg/errors"// SingleSQL is a separate SQL split from multi-SQL.type SingleSQL struct {@@ -15,6 +15,6 @@ func SplitMultiSQL(engineType EngineType, statement string) ([]SingleSQL, error)t := newTokenizer(statement)return t.splitPostgreSQLMultiSQL()default:- return nil, fmt.Errorf("engine type is not supported: %s", engineType)+ return nil, errors.Errorf("engine type is not supported: %s", engineType)}}diff --git a/plugin/vcs/github/github.go b/plugin/vcs/github/github.goindex d639bd28f5..619d6be2a6 100644--- a/plugin/vcs/github/github.go+++ b/plugin/vcs/github/github.go@@ -224,7 +224,7 @@ func (p *Provider) fetchUserInfoImpl(ctx context.Context, oauthCtx common.OauthCif code == http.StatusNotFound {return nil, common.Errorf(common.NotFound, "failed to read user info from URL %s", url)} else if code >= 300 {- return nil, fmt.Errorf("failed to read user info from URL %s, status code: %d, body: %s", url, code, body)+ return nil, errors.Errorf("failed to read user info from URL %s, status code: %d, body: %s", url, code, body)}var user User@@ -290,7 +290,7 @@ func (p *Provider) FetchCommitByID(ctx context.Context, oauthCtx common.OauthConif code == http.StatusNotFound {return nil, common.Errorf(common.NotFound, "failed to fetch commit data from URL %s", url)} else if code >= 300 {- return nil, fmt.Errorf("failed to fetch commit data from URL %s, status code: %d, body: %s", url, code, body)+ return nil, errors.Errorf("failed to fetch commit data from URL %s, status code: %d, body: %s", url, code, body)}commit := &Commit{}@@ -374,7 +374,7 @@ func (p *Provider) FetchRepositoryActiveMemberList(ctx context.Context, oauthCtx}if len(emptyEmailUserList) != 0 {- return nil, fmt.Errorf("[ %v ] did not configure their public email in GitHub, please make sure every members' public email is configured before syncing, see https://docs.github.com/en/account-and-profile", strings.Join(emptyEmailUserList, ", "))+ return nil, errors.Errorf("[ %v ] did not configure their public email in GitHub, please make sure every members' public email is configured before syncing, see https://docs.github.com/en/account-and-profile", strings.Join(emptyEmailUserList, ", "))}return allMembers, nil@@ -408,7 +408,7 @@ func (p *Provider) fetchPaginatedRepositoryCollaborators(ctx context.Context, oareturn nil, false, common.Errorf(common.NotFound, "failed to fetch repository collaborators from URL %s", url)} else if code >= 300 {return nil, false,- fmt.Errorf("failed to read repository collaborators from URL %s, status code: %d, body: %s",+ errors.Errorf("failed to read repository collaborators from URL %s, status code: %d, body: %s",url,code,body,@@ -552,7 +552,7 @@ func (p *Provider) fetchPaginatedRepositoryList(ctx context.Context, oauthCtx coreturn nil, false, common.Errorf(common.NotFound, "failed to fetch repository list from URL %s", url)} else if code >= 300 {return nil, false,- fmt.Errorf("failed to fetch repository list from URL %s, status code: %d, body: %s",+ errors.Errorf("failed to fetch repository list from URL %s, status code: %d, body: %s",url,code,body,@@ -603,7 +603,7 @@ func (p *Provider) FetchRepositoryFileList(ctx context.Context, oauthCtx common.return nil, common.Errorf(common.NotFound, "failed to fetch repository file list from URL %s", url)} else if code >= 300 {return nil,- fmt.Errorf("failed to fetch repository file list from URL %s, status code: %d, body: %s",+ errors.Errorf("failed to fetch repository file list from URL %s, status code: %d, body: %s",url,code,body,@@ -675,7 +675,7 @@ func (p *Provider) CreateFile(ctx context.Context, oauthCtx common.OauthContext,if code == http.StatusNotFound {return common.Errorf(common.NotFound, "failed to create/update file through URL %s", url)} else if code >= 300 {- return fmt.Errorf("failed to create/update file through URL %s, status code: %d, body: %s",+ return errors.Errorf("failed to create/update file through URL %s, status code: %d, body: %s",url,code,body,@@ -745,7 +745,7 @@ func (p *Provider) readFile(ctx context.Context, oauthCtx common.OauthContext, ireturn nil, common.Errorf(common.NotFound, "failed to read file from URL %s", url)} else if code >= 300 {return nil,- fmt.Errorf("failed to read file from URL %s, status code: %d, body: %s",+ errors.Errorf("failed to read file from URL %s, status code: %d, body: %s",url,code,body,@@ -805,7 +805,7 @@ func (p *Provider) CreateWebhook(ctx context.Context, oauthCtx common.OauthConte// GitHub returns 201 HTTP status codes upon successful webhook creation,// see https://docs.github.com/en/rest/webhooks/repos#create-a-repository-webhook for details.if code != http.StatusCreated {- return "", fmt.Errorf("failed to create webhook through URL %s, status code: %d, body: %s",+ return "", errors.Errorf("failed to create webhook through URL %s, status code: %d, body: %s",url,code,body,@@ -847,7 +847,7 @@ func (p *Provider) PatchWebhook(ctx context.Context, oauthCtx common.OauthContexif code == http.StatusNotFound {return common.Errorf(common.NotFound, "failed to patch webhook through URL %s", url)} else if code >= 300 {- return fmt.Errorf("failed to patch webhook through URL %s, status code: %d, body: %s",+ return errors.Errorf("failed to patch webhook through URL %s, status code: %d, body: %s",url,code,body,@@ -883,7 +883,7 @@ func (p *Provider) DeleteWebhook(ctx context.Context, oauthCtx common.OauthConteif code == http.StatusNotFound {return nil // It is OK if the webhook has already gone} else if code >= 300 {- return fmt.Errorf("failed to delete webhook through URL %s, status code: %d, body: %s",+ return errors.Errorf("failed to delete webhook through URL %s, status code: %d, body: %s",url,code,body,diff --git a/plugin/vcs/gitlab/gitlab.go b/plugin/vcs/gitlab/gitlab.goindex 0fc6d16359..2a6bb10a91 100644--- a/plugin/vcs/gitlab/gitlab.go+++ b/plugin/vcs/gitlab/gitlab.go@@ -318,7 +318,7 @@ func (p *Provider) fetchPaginatedRepositoryList(ctx context.Context, oauthCtx coreturn nil, false, common.Errorf(common.NotFound, "failed to fetch repository list from URL %s", url)} else if code >= 300 {return nil, false,- fmt.Errorf("failed to fetch repository list from URL %s, status code: %d, body: %s",+ errors.Errorf("failed to fetch repository list from URL %s, status code: %d, body: %s",url,code,body,@@ -362,7 +362,7 @@ func (p *Provider) fetchUserInfoImpl(ctx context.Context, oauthCtx common.OauthCif code == http.StatusNotFound {return nil, common.Errorf(common.NotFound, "failed to read user info from URL %s", url)} else if code >= 300 {- return nil, fmt.Errorf("failed to read user info from URL %s, status code: %d, body: %s",+ return nil, errors.Errorf("failed to read user info from URL %s, status code: %d, body: %s",url,code,body,@@ -405,7 +405,7 @@ func (p *Provider) FetchCommitByID(ctx context.Context, oauthCtx common.OauthConif code == http.StatusNotFound {return nil, common.Errorf(common.NotFound, "failed to fetch commit data from URL %s", url)} else if code >= 300 {- return nil, fmt.Errorf("failed to fetch commit data from URL %s, status code: %d, body: %s",+ return nil, errors.Errorf("failed to fetch commit data from URL %s, status code: %d, body: %s",url,code,body,@@ -511,7 +511,7 @@ func (p *Provider) FetchRepositoryActiveMemberList(ctx context.Context, oauthCtx}if len(emptyEmailUserList) != 0 {- return nil, fmt.Errorf("[ %v ] did not configure their public email in GitLab, please make sure every members' public email is configured before syncing, see https://docs.gitlab.com/ee/user/profile", strings.Join(emptyEmailUserList, ", "))+ return nil, errors.Errorf("[ %v ] did not configure their public email in GitLab, please make sure every members' public email is configured before syncing, see https://docs.gitlab.com/ee/user/profile", strings.Join(emptyEmailUserList, ", "))}return activeMembers, nil@@ -547,7 +547,7 @@ func (p *Provider) fetchPaginatedRepositoryActiveMemberList(ctx context.Context,return nil, false, common.Errorf(common.NotFound, "failed to fetch repository members from URL %s", url)} else if code >= 300 {return nil, false,- fmt.Errorf("failed to fetch repository members from URL %s, status code: %d, body: %s",+ errors.Errorf("failed to fetch repository members from URL %s, status code: %d, body: %s",url,code,body,@@ -627,7 +627,7 @@ func (p *Provider) fetchPaginatedRepositoryFileList(ctx context.Context, oauthCtreturn nil, false, common.Errorf(common.NotFound, "failed to fetch repository file list from URL %s", url)} else if code >= 300 {return nil, false,- fmt.Errorf("failed to fetch repository file list from URL %s, status code: %d, body: %s",+ errors.Errorf("failed to fetch repository file list from URL %s, status code: %d, body: %s",url,code,body,@@ -684,7 +684,7 @@ func (p *Provider) CreateFile(ctx context.Context, oauthCtx common.OauthContext,if code == http.StatusNotFound {return common.Errorf(common.NotFound, "failed to create file through URL %s", url)} else if code >= 300 {- return fmt.Errorf("failed to create file through URL %s, status code: %d, body: %s",+ return errors.Errorf("failed to create file through URL %s, status code: %d, body: %s",url,code,body,@@ -733,7 +733,7 @@ func (p *Provider) OverwriteFile(ctx context.Context, oauthCtx common.OauthConteif code == http.StatusNotFound {return common.Errorf(common.NotFound, "failed to overwrite file through URL %s", url)} else if code >= 300 {- return fmt.Errorf("failed to overwrite file through URL %s, status code: %d, body: %s",+ return errors.Errorf("failed to overwrite file through URL %s, status code: %d, body: %s",url,code,body,@@ -849,7 +849,7 @@ func (p *Provider) PatchWebhook(ctx context.Context, oauthCtx common.OauthContexif code == http.StatusNotFound {return common.Errorf(common.NotFound, "failed to patch webhook through URL %s", url)} else if code >= 300 {- return fmt.Errorf("failed to patch webhook through URL %s, status code: %d, body: %s",+ return errors.Errorf("failed to patch webhook through URL %s, status code: %d, body: %s",url,code,body,@@ -885,7 +885,7 @@ func (p *Provider) DeleteWebhook(ctx context.Context, oauthCtx common.OauthConteif code == http.StatusNotFound {return nil // It is OK if the webhook has already gone} else if code >= 300 {- return fmt.Errorf("failed to delete webhook through URL %s, status code: %d, body: %s",+ return errors.Errorf("failed to delete webhook through URL %s, status code: %d, body: %s",url,code,body,@@ -923,7 +923,7 @@ func (p *Provider) readFile(ctx context.Context, oauthCtx common.OauthContext, ireturn nil, common.Errorf(common.NotFound, "failed to read file from URL %s", url)} else if code >= 300 {return nil,- fmt.Errorf("failed to read file from URL %s, status code: %d, body: %s",+ errors.Errorf("failed to read file from URL %s, status code: %d, body: %s",url,code,body,diff --git a/plugin/vcs/util.go b/plugin/vcs/util.goindex 6fd1592c80..c158739a79 100644--- a/plugin/vcs/util.go+++ b/plugin/vcs/util.go@@ -1,8 +1,9 @@package vcsimport (- "fmt""strings"++ "github.com/pkg/errors")// Branch is the helper function returns the branch name from reference name.@@ -13,5 +14,5 @@ func Branch(ref string) (string, error) {return strings.TrimPrefix(ref, "refs/heads/"), nil}- return "", fmt.Errorf("invalid Git ref: %s", ref)+ return "", errors.Errorf("invalid Git ref: %s", ref)}diff --git a/plugin/webhook/webhook.go b/plugin/webhook/webhook.goindex 2dfc2ef1e6..00f24d1fce 100644--- a/plugin/webhook/webhook.go+++ b/plugin/webhook/webhook.go@@ -1,9 +1,10 @@package webhookimport (- "fmt""sync""time"++ "github.com/pkg/errors")var (@@ -111,7 +112,7 @@ func Post(webhookType string, context Context) error {r, ok := receivers[webhookType]receiverMu.RUnlock()if !ok {- return fmt.Errorf("webhook: no applicable receiver for webhook type: %v", webhookType)+ return errors.Errorf("webhook: no applicable receiver for webhook type: %v", webhookType)}return r.post(context)diff --git a/resources/mysql/mysql.go b/resources/mysql/mysql.goindex 4187efc0d7..eee8c07437 100644--- a/resources/mysql/mysql.go+++ b/resources/mysql/mysql.go@@ -71,7 +71,7 @@ func (i *Instance) Start(port int, stdout, stderr io.Writer) (err error) {if err != nil {return errors.Wrapf(err, "mysql instance has started as process %d, but failed to kill it", i.proc.Pid)}- return fmt.Errorf("failed to connect to mysql")+ return errors.Errorf("failed to connect to mysql")}}@@ -98,7 +98,7 @@ func Install(basedir, datadir, user string) (*Instance, error) {version = "mysql-8.0.28-linux-glibc2.17-x86_64-minimal"extractFn = utils.ExtractTarXzdefault:- return nil, fmt.Errorf("unsupported os %q and arch %q", runtime.GOOS, runtime.GOARCH)+ return nil, errors.Errorf("unsupported os %q and arch %q", runtime.GOOS, runtime.GOARCH)}tarF, err := resources.Open(tarName)diff --git a/resources/mysqlutil/mysqlutil.go b/resources/mysqlutil/mysqlutil.goindex 8ca10ec85a..b0e52ecbd6 100644--- a/resources/mysqlutil/mysqlutil.go+++ b/resources/mysqlutil/mysqlutil.go@@ -55,7 +55,7 @@ func getExecutableVersion(binName binaryName, resourceDir string) (string, errorcase MySQLDump:cmd = exec.Command(GetPath(MySQLDump, resourceDir), "-V")default:- return "", fmt.Errorf("unknown binary name: %s", binName)+ return "", errors.Errorf("unknown binary name: %s", binName)}cmd.Stdout = &version@@ -76,7 +76,7 @@ func getTarNameAndVersion() (tarname string, version string, err error) {case runtime.GOOS == "linux" && runtime.GOARCH == "amd64":tarName = "mysqlutil-8.0.28-linux-glibc2.17-x86_64.tar.gz"default:- return "", "", fmt.Errorf("unsupported combination of OS %q and ARCH %q", runtime.GOOS, runtime.GOARCH)+ return "", "", errors.Errorf("unsupported combination of OS %q and ARCH %q", runtime.GOOS, runtime.GOARCH)}return tarName, strings.TrimRight(tarName, "tar.gz"), nil}diff --git a/resources/postgres/postgres.go b/resources/postgres/postgres.goindex e1415aab9b..356ff82b00 100644--- a/resources/postgres/postgres.go+++ b/resources/postgres/postgres.go@@ -101,7 +101,7 @@ func Install(resourceDir, pgDataDir, pgUser string) (*Instance, error) {case "linux":tarName = "postgres-linux-x86_64.txz"default:- return nil, fmt.Errorf("OS %q is not supported", runtime.GOOS)+ return nil, errors.Errorf("OS %q is not supported", runtime.GOOS)}version := strings.TrimRight(tarName, ".txz")pgBinDir := path.Join(resourceDir, version)@@ -229,7 +229,7 @@ func shouldSwitchUser() (int, int, bool, error) {if bytebaseUser.Username == "root" {bytebaseUser, err = user.Lookup("bytebase")if err != nil {- return 0, 0, false, fmt.Errorf("please run Bytebase as non-root user. You can use the following command to create a dedicated \"bytebase\" user to run the application: addgroup --gid 113 --system bytebase && adduser --uid 113 --system bytebase && adduser bytebase bytebase")+ return 0, 0, false, errors.Errorf("please run Bytebase as non-root user. You can use the following command to create a dedicated \"bytebase\" user to run the application: addgroup --gid 113 --system bytebase && adduser --uid 113 --system bytebase && adduser bytebase bytebase")}sameUser = false}diff --git a/resources/utils/extract.go b/resources/utils/extract.goindex 21b8c3ac61..059cc9de76 100644--- a/resources/utils/extract.go+++ b/resources/utils/extract.go@@ -3,7 +3,6 @@ package utilsimport ("archive/tar""compress/gzip"- "fmt""io""os""path"@@ -52,7 +51,7 @@ func extractTar(r io.Reader, targetDir string) error {// Ensure that output paths constructed from zip archive entries// are validated to prevent writing files to unexpected locations.if strings.Contains(targetPath, "..") {- return fmt.Errorf("invalid path %q", targetPath)+ return errors.Errorf("invalid path %q", targetPath)}if err := os.MkdirAll(path.Dir(targetPath), os.ModePerm); err != nil {@@ -89,7 +88,7 @@ func extractTar(r io.Reader, targetDir string) error {return err}default:- return fmt.Errorf("unsupported type flag %d", header.Typeflag)+ return errors.Errorf("unsupported type flag %d", header.Typeflag)}}diff --git a/server/acl.go b/server/acl.goindex b0e2fab6b0..5757f056e6 100644--- a/server/acl.go+++ b/server/acl.go@@ -8,6 +8,7 @@ import ("strings""github.com/casbin/casbin/v2"+ "github.com/pkg/errors""github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common"@@ -84,7 +85,7 @@ func aclMiddleware(s *Server, ce *casbin.Enforcer, next echo.HandlerFunc, readonif !pass {return echo.NewHTTPError(http.StatusUnauthorized).SetInternal(- fmt.Errorf("rejected by the ACL policy; %s %s u%d/%s", method, path, principalID, role))+ errors.Errorf("rejected by the ACL policy; %s %s u%d/%s", method, path, principalID, role))}// Stores role into context.diff --git a/server/activity_manager.go b/server/activity_manager.goindex ea24b9ba89..c1a55272b3 100644--- a/server/activity_manager.go+++ b/server/activity_manager.go@@ -72,7 +72,7 @@ func (m *ActivityManager) CreateActivity(ctx context.Context, create *api.Activireturn nil, errors.Wrapf(err, "failed to find updater for posting webhook event after changing the issue status: %v", meta.issue.Name)}if updater == nil {- return nil, fmt.Errorf("updater principal not found for ID %v", create.CreatorID)+ return nil, errors.Errorf("updater principal not found for ID %v", create.CreatorID)}// Call external webhook endpoint in Go routine to avoid blocking web serving thread.@@ -151,7 +151,7 @@ func (m *ActivityManager) getWebhookContext(ctx context.Context, activity *api.Areturn webhookCtx, err}if oldAssignee == nil {- err := fmt.Errorf("failed to post webhook event after changing the issue assignee, old assignee not found for ID %v", oldID)+ err := errors.Errorf("failed to post webhook event after changing the issue assignee, old assignee not found for ID %v", oldID)log.Warn(err.Error(),zap.String("issue_name", meta.issue.Name),zap.String("old_assignee_id", update.OldValue),@@ -178,7 +178,7 @@ func (m *ActivityManager) getWebhookContext(ctx context.Context, activity *api.Areturn webhookCtx, err}if newAssignee == nil {- err := fmt.Errorf("failed to post webhook event after changing the issue assignee, new assignee not found for ID %v", newID)+ err := errors.Errorf("failed to post webhook event after changing the issue assignee, new assignee not found for ID %v", newID)log.Warn(err.Error(),zap.String("issue_name", meta.issue.Name),zap.String("new_assignee_id", update.NewValue),@@ -220,7 +220,7 @@ func (m *ActivityManager) getWebhookContext(ctx context.Context, activity *api.Areturn webhookCtx, err}if task == nil {- err := fmt.Errorf("failed to post webhook event after changing the issue task status, task not found for ID %v", update.TaskID)+ err := errors.Errorf("failed to post webhook event after changing the issue task status, task not found for ID %v", update.TaskID)log.Warn(err.Error(),zap.String("issue_name", meta.issue.Name),zap.Int("task_id", update.TaskID),diff --git a/server/anomaly_scanner.go b/server/anomaly_scanner.goindex 42203b770e..c2a6a03ff2 100644--- a/server/anomaly_scanner.go+++ b/server/anomaly_scanner.go@@ -12,6 +12,7 @@ import ("github.com/bytebase/bytebase/common""github.com/bytebase/bytebase/common/log""github.com/bytebase/bytebase/plugin/db"+ "github.com/pkg/errors""go.uber.org/zap")@@ -50,7 +51,7 @@ func (s *AnomalyScanner) Run(ctx context.Context, wg *sync.WaitGroup) {if r := recover(); r != nil {err, ok := r.(error)if !ok {- err = fmt.Errorf("%v", r)+ err = errors.Errorf("%v", r)}log.Error("Anomaly scanner PANIC RECOVER", zap.Error(err))}diff --git a/server/backup_runner.go b/server/backup_runner.goindex 41ddf78a1c..3aaf54c63e 100644--- a/server/backup_runner.go+++ b/server/backup_runner.go@@ -57,7 +57,7 @@ func (r *BackupRunner) Run(ctx context.Context, wg *sync.WaitGroup) {if r := recover(); r != nil {err, ok := r.(error)if !ok {- err = fmt.Errorf("%v", r)+ err = errors.Errorf("%v", r)}log.Error("Auto backup runner PANIC RECOVER", zap.Error(err))}diff --git a/server/database.go b/server/database.goindex 1d0c36b470..c4169a65ac 100644--- a/server/database.go+++ b/server/database.go@@ -33,7 +33,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find instance").SetInternal(err)}if instance == nil {- err := fmt.Errorf("instance ID not found %v", databaseCreate.InstanceID)+ err := errors.Errorf("instance ID not found %v", databaseCreate.InstanceID)return echo.NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err)}databaseCreate.EnvironmentID = instance.EnvironmentID@@ -42,7 +42,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to find project with ID %d", databaseCreate.ProjectID)).SetInternal(err)}if project == nil {- err := fmt.Errorf("project ID not found %v", databaseCreate.ProjectID)+ err := errors.Errorf("project ID not found %v", databaseCreate.ProjectID)return echo.NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err)}if project.TenantMode == api.TenantModeTenant && !s.feature(api.FeatureMultiTenancy) {@@ -788,7 +788,7 @@ func (s *Server) setDatabaseLabels(ctx context.Context, labelsJSON string, datab// For scalability, each database can have up to four labels for now.if len(labels) > api.DatabaseLabelSizeMax {- err := fmt.Errorf("database labels are up to a maximum of %d", api.DatabaseLabelSizeMax)+ err := errors.Errorf("database labels are up to a maximum of %d", api.DatabaseLabelSizeMax)return echo.NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err)}@@ -813,7 +813,7 @@ func (s *Server) setDatabaseLabels(ctx context.Context, labelsJSON string, databreturn errors.Wrapf(err, "api.GetBaseDatabaseName(%q, %q, %q) failed", database.Name, project.DBNameTemplate, labelsJSON)}if _, err := formatDatabaseName(baseDatabaseName, project.DBNameTemplate, tokens); err != nil {- err := fmt.Errorf("database labels don't match with database name template %q", project.DBNameTemplate)+ err := errors.Errorf("database labels don't match with database name template %q", project.DBNameTemplate)return echo.NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err)}}@@ -928,7 +928,7 @@ func getDatabaseDriver(ctx context.Context, engine db.Type, driverConfig db.DrivconnCtx,)if err != nil {- return nil, common.Errorf(common.DbConnectionFailure, "failed to connect database at %s:%s with user %q, error: %w", connectionConfig.Host, connectionConfig.Port, connectionConfig.Username, err)+ return nil, common.Wrapf(err, common.DbConnectionFailure, "failed to connect database at %s:%s with user %q", connectionConfig.Host, connectionConfig.Port, connectionConfig.Username)}return driver, nil}diff --git a/server/environment.go b/server/environment.goindex 17731d899c..33d2fc9799 100644--- a/server/environment.go+++ b/server/environment.go@@ -1,7 +1,6 @@package serverimport (- "errors""fmt""net/http""reflect"@@ -9,6 +8,7 @@ import ("github.com/google/jsonapi""github.com/labstack/echo/v4"+ "github.com/pkg/errors""github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common"@@ -81,7 +81,7 @@ func (s *Server) registerEnvironmentRoutes(g *echo.Group) {RowStatus: &normalStatus,})if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Errorf("failed to find instances in the environment %d", id)).SetInternal(err)+ return echo.NewHTTPError(http.StatusInternalServerError, errors.Errorf("failed to find instances in the environment %d", id)).SetInternal(err)}if len(instances) > 0 {return echo.NewHTTPError(http.StatusBadRequest, "You should archive all instances under the environment before archiving the environment.")diff --git a/server/instance.go b/server/instance.goindex 557964ddfa..19f498bd8c 100644--- a/server/instance.go+++ b/server/instance.go@@ -9,6 +9,7 @@ import ("github.com/google/jsonapi""github.com/labstack/echo/v4"+ "github.com/pkg/errors""go.uber.org/zap""github.com/bytebase/bytebase/api"@@ -159,7 +160,7 @@ func (s *Server) registerInstanceRoutes(g *echo.Group) {databases, err := s.store.FindDatabase(ctx, &api.DatabaseFind{InstanceID: &id})if err != nil {return echo.NewHTTPError(http.StatusInternalServerError,- fmt.Errorf("failed to find databases in the instance %d", id)).SetInternal(err)+ errors.Errorf("failed to find databases in the instance %d", id)).SetInternal(err)}var databaseNameList []stringfor _, database := range databases {@@ -464,7 +465,7 @@ func (s *Server) instanceCountGuard(ctx context.Context) error {func (s *Server) disallowBytebaseStore(engine db.Type, host, port string) error {// Even when Postgres opens Unix domain socket only for connection, it still requires a port as socket file extension to differentiate different Postgres instances.if engine == db.Postgres && port == fmt.Sprintf("%v", s.profile.DatastorePort) && host == common.GetPostgresSocketDir() {- return fmt.Errorf("instance doesn't exist for host %q and port %q", host, port)+ return errors.Errorf("instance doesn't exist for host %q and port %q", host, port)}return nil}diff --git a/server/issue.go b/server/issue.goindex 52b22b5155..963ac394f2 100644--- a/server/issue.go+++ b/server/issue.go@@ -351,7 +351,7 @@ func (s *Server) createPipeline(ctx context.Context, issueCreate *api.IssueCreat}}if !hasTask {- err := fmt.Errorf("issue has no task to be executed")+ err := errors.Errorf("issue has no task to be executed")return nil, echo.NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err)}@@ -432,7 +432,7 @@ func (s *Server) getPipelineCreateForDatabaseCreate(ctx context.Context, issueCrreturn nil, err}if instance == nil {- return nil, fmt.Errorf("instance ID not found %v", c.InstanceID)+ return nil, errors.Errorf("instance ID not found %v", c.InstanceID)}// Find project.project, err := s.store.GetProjectByID(ctx, issueCreate.ProjectID)@@ -440,7 +440,7 @@ func (s *Server) getPipelineCreateForDatabaseCreate(ctx context.Context, issueCrreturn nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch project with ID %d", issueCreate.ProjectID)).SetInternal(err)}if project == nil {- err := fmt.Errorf("project ID not found %v", issueCreate.ProjectID)+ err := errors.Errorf("project ID not found %v", issueCreate.ProjectID)return nil, echo.NewHTTPError(http.StatusInternalServerError, err.Error()).SetInternal(err)}@@ -452,10 +452,10 @@ func (s *Server) getPipelineCreateForDatabaseCreate(ctx context.Context, issueCrif c.BackupID != 0 {backup, err := s.store.GetBackupByID(ctx, c.BackupID)if err != nil {- return nil, fmt.Errorf("failed to find backup %v", c.BackupID)+ return nil, errors.Errorf("failed to find backup %v", c.BackupID)}if backup == nil {- return nil, fmt.Errorf("backup not found with ID %d", c.BackupID)+ return nil, errors.Errorf("backup not found with ID %d", c.BackupID)}restorePayload := api.TaskDatabaseRestorePayload{}restorePayload.DatabaseName = c.DatabaseName@@ -648,7 +648,7 @@ func (s *Server) getPipelineCreateForDatabaseSchemaAndDataUpdate(ctx context.Confor k := range environmentSet {environments = append(environments, k)}- err := fmt.Errorf("all databases in a stage should have the same environment; got %s", strings.Join(environments, ","))+ err := errors.Errorf("all databases in a stage should have the same environment; got %s", strings.Join(environments, ","))return nil, echo.NewHTTPError(http.StatusInternalServerError, err.Error()).SetInternal(err)}@@ -1004,33 +1004,33 @@ func checkCharacterSetCollationOwner(dbType db.Type, characterSet, collation, owcase db.ClickHouse:// ClickHouse does not support character set and collation at the database level.if characterSet != "" {- return fmt.Errorf("ClickHouse does not support character set, but got %s", characterSet)+ return errors.Errorf("ClickHouse does not support character set, but got %s", characterSet)}if collation != "" {- return fmt.Errorf("ClickHouse does not support collation, but got %s", collation)+ return errors.Errorf("ClickHouse does not support collation, but got %s", collation)}case db.Snowflake:if characterSet != "" {- return fmt.Errorf("Snowflake does not support character set, but got %s", characterSet)+ return errors.Errorf("Snowflake does not support character set, but got %s", characterSet)}if collation != "" {- return fmt.Errorf("Snowflake does not support collation, but got %s", collation)+ return errors.Errorf("Snowflake does not support collation, but got %s", collation)}case db.Postgres:if owner == "" {- return fmt.Errorf("database owner is required for PostgreSQL")+ return errors.Errorf("database owner is required for PostgreSQL")}case db.SQLite:// no-op.default:if characterSet == "" {- return fmt.Errorf("character set missing for %s", string(dbType))+ return errors.Errorf("character set missing for %s", string(dbType))}// For postgres, we don't explicitly specify a default since the default might be UNSET (denoted by "C").// If that's the case, setting an explicit default such as "en_US.UTF-8" might fail if the instance doesn't// install it.if collation == "" {- return fmt.Errorf("collation missing for %s", string(dbType))+ return errors.Errorf("collation missing for %s", string(dbType))}}return nil@@ -1104,7 +1104,7 @@ func (s *Server) changeIssueStatus(ctx context.Context, issue *api.Issue, newStafor _, stage := range issue.Pipeline.StageList {for _, task := range stage.TaskList {if task.Status != api.TaskDone {- return nil, &common.Error{Code: common.Conflict, Err: fmt.Errorf("failed to resolve issue: %v, task %v has not finished", issue.Name, task.Name)}+ return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("failed to resolve issue: %v, task %v has not finished", issue.Name, task.Name)}}}}@@ -1278,7 +1278,7 @@ func (s *Server) getSchemaFromPeerTenantDatabase(ctx context.Context, instance *}}if found {- err := fmt.Errorf("conflicting database name, project has existing base database named %q, but it's not from the selected peer tenants", baseDatabaseName)+ err := errors.Errorf("conflicting database name, project has existing base database named %q, but it's not from the selected peer tenants", baseDatabaseName)return "", "", echo.NewHTTPError(http.StatusBadRequest, err.Error()).SetInternal(err)}return "", "", nildiff --git a/server/jwt.go b/server/jwt.goindex 27dd54317b..606f6e0ca9 100644--- a/server/jwt.go+++ b/server/jwt.go@@ -190,14 +190,14 @@ func JWTMiddleware(principalStore *store.Store, next echo.HandlerFunc, mode commclaims := &Claims{}accessToken, err := jwt.ParseWithClaims(cookie.Value, claims, func(t *jwt.Token) (interface{}, error) {if t.Method.Alg() != jwt.SigningMethodHS256.Name {- return nil, fmt.Errorf("unexpected access token signing method=%v, expect %v", t.Header["alg"], jwt.SigningMethodHS256)+ return nil, pkgerrors.Errorf("unexpected access token signing method=%v, expect %v", t.Header["alg"], jwt.SigningMethodHS256)}if kid, ok := t.Header["kid"].(string); ok {if kid == "v1" {return []byte(secret), nil}}- return nil, fmt.Errorf("unexpected access token kid=%v", t.Header["kid"])+ return nil, pkgerrors.Errorf("unexpected access token kid=%v", t.Header["kid"])})if !audienceContains(claims.Audience, fmt.Sprintf(accessTokenAudienceFmt, mode)) {@@ -250,7 +250,7 @@ func JWTMiddleware(principalStore *store.Store, next echo.HandlerFunc, mode commrefreshTokenClaims := &Claims{}refreshToken, err := jwt.ParseWithClaims(rc.Value, refreshTokenClaims, func(t *jwt.Token) (interface{}, error) {if t.Method.Alg() != jwt.SigningMethodHS256.Name {- return nil, fmt.Errorf("unexpected refresh token signing method=%v, expected %v", t.Header["alg"], jwt.SigningMethodHS256)+ return nil, pkgerrors.Errorf("unexpected refresh token signing method=%v, expected %v", t.Header["alg"], jwt.SigningMethodHS256)}if kid, ok := t.Header["kid"].(string); ok {@@ -258,7 +258,7 @@ func JWTMiddleware(principalStore *store.Store, next echo.HandlerFunc, mode commreturn []byte(secret), nil}}- return nil, fmt.Errorf("unexpected refresh token kid=%v", t.Header["kid"])+ return nil, pkgerrors.Errorf("unexpected refresh token kid=%v", t.Header["kid"])})if err != nil {if err == jwt.ErrSignatureInvalid {diff --git a/server/metric_reporter.go b/server/metric_reporter.goindex da7ce0a2e5..c79e61c4ab 100644--- a/server/metric_reporter.go+++ b/server/metric_reporter.go@@ -12,6 +12,7 @@ import ("github.com/bytebase/bytebase/plugin/metric""github.com/bytebase/bytebase/plugin/metric/segment""github.com/bytebase/bytebase/store"+ "github.com/pkg/errors""go.uber.org/zap")@@ -71,7 +72,7 @@ func (m *MetricReporter) Run(ctx context.Context, wg *sync.WaitGroup) {if r := recover(); r != nil {err, ok := r.(error)if !ok {- err = fmt.Errorf("%v", r)+ err = errors.Errorf("%v", r)}log.Error("Metrics reporter PANIC RECOVER", zap.Error(err))}diff --git a/server/policy.go b/server/policy.goindex be8d96b3dd..9494e6be3f 100644--- a/server/policy.go+++ b/server/policy.go@@ -7,6 +7,7 @@ import ("github.com/google/jsonapi""github.com/labstack/echo/v4"+ "github.com/pkg/errors""github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common"@@ -31,15 +32,15 @@ func (s *Server) hasAccessToUpsertPolicy(policyUpsert *api.PolicyUpsert) error {switch policyUpsert.Type {case api.PolicyTypePipelineApproval:if !s.feature(api.FeatureApprovalPolicy) {- return fmt.Errorf(api.FeatureApprovalPolicy.AccessErrorMessage())+ return errors.Errorf(api.FeatureApprovalPolicy.AccessErrorMessage())}case api.PolicyTypeBackupPlan:if !s.feature(api.FeatureBackupPolicy) {- return fmt.Errorf(api.FeatureBackupPolicy.AccessErrorMessage())+ return errors.Errorf(api.FeatureBackupPolicy.AccessErrorMessage())}case api.PolicyTypeSQLReview:if !s.feature(api.FeatureSQLReviewPolicy) {- return fmt.Errorf(api.FeatureSQLReviewPolicy.AccessErrorMessage())+ return errors.Errorf(api.FeatureSQLReviewPolicy.AccessErrorMessage())}}return nildiff --git a/server/project.go b/server/project.goindex d631842402..5a24c8a269 100644--- a/server/project.go+++ b/server/project.go@@ -11,6 +11,7 @@ import ("github.com/google/jsonapi""github.com/google/uuid""github.com/labstack/echo/v4"+ "github.com/pkg/errors""go.uber.org/zap""github.com/bytebase/bytebase/api"@@ -161,7 +162,7 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {if v := projectPatch.RowStatus; v != nil && *v == string(api.Archived) {databases, err := s.store.FindDatabase(ctx, &api.DatabaseFind{ProjectID: &id})if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Errorf("failed to find databases in the project %d", id)).SetInternal(err)+ return echo.NewHTTPError(http.StatusInternalServerError, errors.Errorf("failed to find databases in the project %d", id)).SetInternal(err)}if len(databases) > 0 {return echo.NewHTTPError(http.StatusBadRequest, "You should transfer all databases under the project before archiving the project.")diff --git a/server/recover.go b/server/recover.goindex 0948e219f7..0a7895b10a 100644--- a/server/recover.go+++ b/server/recover.go@@ -1,10 +1,9 @@package serverimport (- "fmt"-"github.com/bytebase/bytebase/common/log""github.com/labstack/echo/v4"+ "github.com/pkg/errors""go.uber.org/zap")@@ -14,7 +13,7 @@ func recoverMiddleware(next echo.HandlerFunc) echo.HandlerFunc {if r := recover(); r != nil {err, ok := r.(error)if !ok {- err = fmt.Errorf("%v", r)+ err = errors.Errorf("%v", r)}log.Error("Middleware PANIC RECOVER", zap.Error(err))diff --git a/server/schema_syncer.go b/server/schema_syncer.goindex a19cd941f5..07a1055072 100644--- a/server/schema_syncer.go+++ b/server/schema_syncer.go@@ -8,6 +8,7 @@ import ("github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common/log"+ "github.com/pkg/errors""go.uber.org/zap")@@ -44,7 +45,7 @@ func (s *SchemaSyncer) Run(ctx context.Context, wg *sync.WaitGroup) {if r := recover(); r != nil {err, ok := r.(error)if !ok {- err = fmt.Errorf("%v", r)+ err = errors.Errorf("%v", r)}log.Error("Schema syncer PANIC RECOVER", zap.Error(err))}diff --git a/server/sheet.go b/server/sheet.goindex a9ca4a5b7b..e26910ebd9 100644--- a/server/sheet.go+++ b/server/sheet.go@@ -452,14 +452,14 @@ func composeCommonSheetFindByQueryParams(queryParams url.Values) (*api.SheetFindif projectIDStr := queryParams.Get("projectId"); projectIDStr != "" {projectID, err := strconv.Atoi(projectIDStr)if err != nil {- return nil, fmt.Errorf("project ID is not a number: %s", queryParams.Get("projectId"))+ return nil, errors.Errorf("project ID is not a number: %s", queryParams.Get("projectId"))}sheetFind.ProjectID = &projectID}if databaseIDStr := queryParams.Get("databaseId"); databaseIDStr != "" {databaseID, err := strconv.Atoi(databaseIDStr)if err != nil {- return nil, fmt.Errorf("database ID is not a number: %s", queryParams.Get("databaseId"))+ return nil, errors.Errorf("database ID is not a number: %s", queryParams.Get("databaseId"))}sheetFind.DatabaseID = &databaseID}@@ -491,7 +491,7 @@ func parseSheetInfo(sheetPath string, sheetPathTemplate string) (*SheetInfo, errreturn nil, errors.Wrapf(err, "invalid sheet path template %q", sheetPathTemplate)}if !sheetRegex.MatchString(sheetPath) {- return nil, fmt.Errorf("sheet path %q does not match sheet path template %q", sheetPath, sheetPathTemplate)+ return nil, errors.Errorf("sheet path %q does not match sheet path template %q", sheetPath, sheetPathTemplate)}matchList := sheetRegex.FindStringSubmatch(sheetPath)diff --git a/server/sheet_test.go b/server/sheet_test.goindex 83fb0b7838..54fef7c39b 100644--- a/server/sheet_test.go+++ b/server/sheet_test.go@@ -1,9 +1,9 @@package serverimport (- "fmt""testing"+ "github.com/pkg/errors""github.com/stretchr/testify/require")@@ -68,13 +68,13 @@ func TestParseSheetInfo(t *testing.T) {filePath: "sheet/db/test.sql",sheetPathTemplate: "sheet/{{NAME}}.sql",want: nil,- err: fmt.Errorf("sheet path \"sheet/db/test.sql\" does not match sheet path template \"sheet/{{NAME}}.sql\""),+ err: errors.Errorf("sheet path \"sheet/db/test.sql\" does not match sheet path template \"sheet/{{NAME}}.sql\""),},{filePath: "my-sheet/test.sql",sheetPathTemplate: "sheet/{{NAME}}.sql",want: nil,- err: fmt.Errorf("sheet path \"my-sheet/test.sql\" does not match sheet path template \"sheet/{{NAME}}.sql\""),+ err: errors.Errorf("sheet path \"my-sheet/test.sql\" does not match sheet path template \"sheet/{{NAME}}.sql\""),},}diff --git a/server/sql.go b/server/sql.goindex 4f58e754ec..abb6ab3729 100644--- a/server/sql.go+++ b/server/sql.go@@ -359,7 +359,7 @@ func (s *Server) syncEngineVersionAndSchema(ctx context.Context, instance *api.I}}if len(errorList) > 0 {- return fmt.Errorf("sync database schema errors, %s", strings.Join(errorList, ", "))+ return errors.Errorf("sync database schema errors, %s", strings.Join(errorList, ", "))}return nil@@ -468,7 +468,7 @@ func (s *Server) syncInstanceSchema(ctx context.Context, instance *api.Instance,}if _, err := s.store.CreateDatabase(ctx, databaseCreate); err != nil {if common.ErrorCode(err) == common.Conflict {- return nil, fmt.Errorf("failed to sync database for instance: %s. Database name already exists: %s", instance.Name, databaseCreate.Name)+ return nil, errors.Errorf("failed to sync database for instance: %s. Database name already exists: %s", instance.Name, databaseCreate.Name)}return nil, errors.Wrapf(err, "failed to sync database for instance: %s. Failed to import new database: %s", instance.Name, databaseCreate.Name)}@@ -496,7 +496,7 @@ func (s *Server) syncInstanceSchema(ctx context.Context, instance *api.Instance,database, err := s.store.PatchDatabase(ctx, databasePatch)if err != nil {if common.ErrorCode(err) == common.NotFound {- return nil, fmt.Errorf("failed to sync database for instance: %s. Database not found: %s", instance.Name, database.Name)+ return nil, errors.Errorf("failed to sync database for instance: %s. Database not found: %s", instance.Name, database.Name)}return nil, errors.Wrapf(err, "failed to sync database for instance: %s. Failed to update database: %s", instance.Name, database.Name)}@@ -554,7 +554,7 @@ func (s *Server) syncDatabaseSchema(ctx context.Context, instance *api.Instance,dbPatched, err := s.store.PatchDatabase(ctx, databasePatch)if err != nil {if common.ErrorCode(err) == common.NotFound {- return fmt.Errorf("failed to sync database for instance: %s. Database not found: %v", instance.Name, matchedDb.Name)+ return errors.Errorf("failed to sync database for instance: %s. Database not found: %v", instance.Name, matchedDb.Name)}return errors.Wrapf(err, "failed to sync database for instance: %s. Failed to update database: %s", instance.Name, matchedDb.Name)}@@ -573,7 +573,7 @@ func (s *Server) syncDatabaseSchema(ctx context.Context, instance *api.Instance,createdDatabase, err := s.store.CreateDatabase(ctx, databaseCreate)if err != nil {if common.ErrorCode(err) == common.Conflict {- return fmt.Errorf("failed to sync database for instance: %s. Database name already exists: %s", instance.Name, databaseCreate.Name)+ return errors.Errorf("failed to sync database for instance: %s. Database name already exists: %s", instance.Name, databaseCreate.Name)}return errors.Wrapf(err, "failed to sync database for instance: %s. Failed to import new database: %s", instance.Name, databaseCreate.Name)}diff --git a/server/task.go b/server/task.goindex b872750f6b..ea45c8c327 100644--- a/server/task.go+++ b/server/task.go@@ -334,7 +334,7 @@ func (s *Server) patchTask(ctx context.Context, task *api.Task, taskPatch *api.Tif taskPatched.Type == api.TaskDatabaseSchemaUpdate || taskPatched.Type == api.TaskDatabaseDataUpdate || taskPatched.Type == api.TaskDatabaseSchemaUpdateGhostSync {if oldStatement != newStatement {if issue == nil {- err := fmt.Errorf("issue not found with pipeline ID %v", task.PipelineID)+ err := errors.Errorf("issue not found with pipeline ID %v", task.PipelineID)return nil, echo.NewHTTPError(http.StatusNotFound, err).SetInternal(err)}@@ -431,7 +431,7 @@ func (s *Server) patchTask(ctx context.Context, task *api.Task, taskPatch *api.Tif taskPatched.EarliestAllowedTs != task.EarliestAllowedTs {// create an activityif issue == nil {- err := fmt.Errorf("issue not found with pipeline ID %v", task.PipelineID)+ err := errors.Errorf("issue not found with pipeline ID %v", task.PipelineID)return nil, echo.NewHTTPError(http.StatusNotFound, err.Error()).SetInternal(err)}@@ -516,7 +516,7 @@ func (s *Server) canPrincipalBeAssignee(ctx context.Context, principalID int, en// the assignee group is the workspace owner and DBA.principal, err := s.store.GetPrincipalByID(ctx, principalID)if err != nil {- return false, common.Errorf(common.Internal, "failed to get principal by ID %d, error: %w", principalID, err)+ return false, common.Wrapf(err, common.Internal, "failed to get principal by ID %d", principalID)}if principal == nil {return false, common.Errorf(common.NotFound, "principal not found by ID %d", principalID)@@ -531,7 +531,7 @@ func (s *Server) canPrincipalBeAssignee(ctx context.Context, principalID int, enPrincipalID: &principalID,})if err != nil {- return false, common.Errorf(common.Internal, "failed to get project member by projectID %d, principalID %d, error: %w", projectID, principalID, err)+ return false, common.Wrapf(err, common.Internal, "failed to get project member by projectID %d, principalID %d", projectID, principalID)}if member == nil {return false, common.Errorf(common.NotFound, "project member not found by projectID %d, principalID %d", projectID, principalID)@@ -548,7 +548,7 @@ func (s *Server) canPrincipalChangeTaskStatus(ctx context.Context, principalID i// the workspace owner and DBA roles can always change task status.principal, err := s.store.GetPrincipalByID(ctx, principalID)if err != nil {- return false, common.Errorf(common.Internal, "failed to get principal by ID %d, error: %w", principalID, err)+ return false, common.Wrapf(err, common.Internal, "failed to get principal by ID %d", principalID)}if principal == nil {return false, common.Errorf(common.NotFound, "principal not found by ID %d", principalID)@@ -559,14 +559,14 @@ func (s *Server) canPrincipalChangeTaskStatus(ctx context.Context, principalID iissue, err := s.store.GetIssueByPipelineID(ctx, task.PipelineID)if err != nil {- return false, common.Errorf(common.Internal, "failed to find issue, error: %w", err)+ return false, common.Wrapf(err, common.Internal, "failed to find issue")}if issue == nil {return false, common.Errorf(common.NotFound, "issue not found by pipeline ID: %d", task.PipelineID)}groupValue, err := s.getGroupValueForTask(ctx, issue, task)if err != nil {- return false, common.Errorf(common.Internal, "failed to get assignee group value for taskID %d, error: %w", task.ID, err)+ return false, common.Wrapf(err, common.Internal, "failed to get assignee group value for taskID %d", task.ID)}if groupValue == nil {return false, nil@@ -578,7 +578,7 @@ func (s *Server) canPrincipalChangeTaskStatus(ctx context.Context, principalID iPrincipalID: &principalID,})if err != nil {- return false, common.Errorf(common.Internal, "failed to get project member by projectID %d, principalID %d, error: %w", issue.ProjectID, principalID, err)+ return false, common.Wrapf(err, common.Internal, "failed to get project member by projectID %d, principalID %d", issue.ProjectID, principalID)}if member != nil && member.Role == string(api.Owner) {return true, nil@@ -601,7 +601,7 @@ func (s *Server) getGroupValueForTask(ctx context.Context, issue *api.Issue, taspolicy, err := s.store.GetPipelineApprovalPolicy(ctx, environmentID)if err != nil {- return nil, common.Errorf(common.Internal, "failed to get pipeline approval policy by environmentID %d, error: %w", environmentID, err)+ return nil, common.Wrapf(err, common.Internal, "failed to get pipeline approval policy by environmentID %d", environmentID)}for _, assigneeGroup := range policy.AssigneeGroupList {@@ -627,7 +627,7 @@ func (s *Server) patchTaskStatus(ctx context.Context, task *api.Task, taskStatusif !isTaskStatusTransitionAllowed(task.Status, taskStatusPatch.Status) {return nil, &common.Error{Code: common.Invalid,- Err: fmt.Errorf("invalid task status transition from %v to %v. Applicable transition(s) %v", task.Status, taskStatusPatch.Status, applicableTaskStatusTransition[task.Status])}+ Err: errors.Errorf("invalid task status transition from %v to %v. Applicable transition(s) %v", task.Status, taskStatusPatch.Status, applicableTaskStatusTransition[task.Status])}}taskPatched, err := s.store.PatchTaskStatus(ctx, taskStatusPatch)@@ -713,10 +713,10 @@ func (s *Server) patchTaskStatus(ctx context.Context, task *api.Task, taskStatusif taskPatched.Status == "DONE" && (issue == nil || issue.AssigneeID == api.SystemBotID) {pipeline, err := s.store.GetPipelineByID(ctx, taskPatched.PipelineID)if err != nil {- return nil, fmt.Errorf("failed to fetch pipeline/issue as DONE after completing task %v", taskPatched.Name)+ return nil, errors.Errorf("failed to fetch pipeline/issue as DONE after completing task %v", taskPatched.Name)}if pipeline == nil {- return nil, fmt.Errorf("pipeline not found for ID %v", taskPatched.PipelineID)+ return nil, errors.Errorf("pipeline not found for ID %v", taskPatched.PipelineID)}lastStage := pipeline.StageList[len(pipeline.StageList)-1]if lastStage.TaskList[len(lastStage.TaskList)-1].ID == taskPatched.ID {diff --git a/server/task_check_executor_database_connect.go b/server/task_check_executor_database_connect.goindex bdeb3b4ed5..debacb497e 100644--- a/server/task_check_executor_database_connect.go+++ b/server/task_check_executor_database_connect.go@@ -21,7 +21,7 @@ type TaskCheckDatabaseConnectExecutor struct {func (*TaskCheckDatabaseConnectExecutor) Run(ctx context.Context, server *Server, taskCheckRun *api.TaskCheckRun) (result []api.TaskCheckResult, err error) {task, err := server.store.GetTaskByID(ctx, taskCheckRun.TaskID)if err != nil {- return []api.TaskCheckResult{}, common.WithError(common.Internal, err)+ return []api.TaskCheckResult{}, common.Wrap(err, common.Internal)}if task == nil {return []api.TaskCheckResult{@@ -37,7 +37,7 @@ func (*TaskCheckDatabaseConnectExecutor) Run(ctx context.Context, server *Serverdatabase, err := server.store.GetDatabase(ctx, &api.DatabaseFind{ID: task.DatabaseID})if err != nil {- return []api.TaskCheckResult{}, common.WithError(common.Internal, err)+ return []api.TaskCheckResult{}, common.Wrap(err, common.Internal)}if database == nil {return []api.TaskCheckResult{}, common.Errorf(common.Internal, "database ID not found %v", task.DatabaseID)diff --git a/server/task_check_executor_ghost_sync.go b/server/task_check_executor_ghost_sync.goindex 31b4cc47b5..957ce431cd 100644--- a/server/task_check_executor_ghost_sync.go+++ b/server/task_check_executor_ghost_sync.go@@ -6,6 +6,7 @@ import ("fmt""github.com/github/gh-ost/go/logic"+ "github.com/pkg/errors""github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common"@@ -29,7 +30,7 @@ func (*TaskCheckGhostSyncExecutor) Run(ctx context.Context, server *Server, taskif r := recover(); r != nil {panicErr, ok := r.(error)if !ok {- panicErr = fmt.Errorf("%v", r)+ panicErr = errors.Errorf("%v", r)}result = []api.TaskCheckResult{{@@ -45,7 +46,7 @@ func (*TaskCheckGhostSyncExecutor) Run(ctx context.Context, server *Server, task}()task, err := server.store.GetTaskByID(ctx, taskCheckRun.TaskID)if err != nil {- return []api.TaskCheckResult{}, common.WithError(common.Internal, err)+ return []api.TaskCheckResult{}, common.Wrap(err, common.Internal)}if task == nil {return []api.TaskCheckResult{@@ -76,13 +77,13 @@ func (*TaskCheckGhostSyncExecutor) Run(ctx context.Context, server *Server, taskpayload := &api.TaskDatabaseSchemaUpdateGhostSyncPayload{}if err := json.Unmarshal([]byte(task.Payload), payload); err != nil {- return []api.TaskCheckResult{}, common.Errorf(common.Internal, "invalid database schema update gh-ost sync payload: %w", err)+ return []api.TaskCheckResult{}, common.Wrapf(err, common.Internal, "invalid database schema update gh-ost sync payload")}databaseName := database.NametableName, err := getTableNameFromStatement(payload.Statement)if err != nil {- return []api.TaskCheckResult{}, common.Errorf(common.Internal, "failed to parse table name from statement, statement: %v, error: %w", payload.Statement, err)+ return []api.TaskCheckResult{}, common.Wrapf(err, common.Internal, "failed to parse table name from statement, statement: %v", payload.Statement)}migrationContext, err := newMigrationContext(ghostConfig{@@ -102,7 +103,7 @@ func (*TaskCheckGhostSyncExecutor) Run(ctx context.Context, server *Server, taskserverID: 20000000 + uint(taskCheckRun.ID),})if err != nil {- return []api.TaskCheckResult{}, common.Errorf(common.Internal, "failed to create migration context, error: %w", err)+ return []api.TaskCheckResult{}, common.Wrapf(err, common.Internal, "failed to create migration context")}migrator := logic.NewMigrator(migrationContext, "bb")diff --git a/server/task_check_executor_migration_schema.go b/server/task_check_executor_migration_schema.goindex 463e86c803..4bfc2cd957 100644--- a/server/task_check_executor_migration_schema.go+++ b/server/task_check_executor_migration_schema.go@@ -21,7 +21,7 @@ type TaskCheckMigrationSchemaExecutor struct {func (*TaskCheckMigrationSchemaExecutor) Run(ctx context.Context, server *Server, taskCheckRun *api.TaskCheckRun) (result []api.TaskCheckResult, err error) {task, err := server.store.GetTaskByID(ctx, taskCheckRun.TaskID)if err != nil {- return []api.TaskCheckResult{}, common.WithError(common.Internal, err)+ return []api.TaskCheckResult{}, common.Wrap(err, common.Internal)}if task == nil {return []api.TaskCheckResult{diff --git a/server/task_check_executor_statement_advisor_composite.go b/server/task_check_executor_statement_advisor_composite.goindex a4eaa78627..cb60721445 100644--- a/server/task_check_executor_statement_advisor_composite.go+++ b/server/task_check_executor_statement_advisor_composite.go@@ -37,7 +37,7 @@ func (*TaskCheckStatementAdvisorCompositeExecutor) Run(ctx context.Context, servpayload := &api.TaskCheckDatabaseStatementAdvisePayload{}if err := json.Unmarshal([]byte(taskCheckRun.Payload), payload); err != nil {- return nil, common.Errorf(common.Invalid, "invalid check statement advise payload: %w", err)+ return nil, common.Wrapf(err, common.Invalid, "invalid check statement advise payload")}policy, err := server.store.GetNormalSQLReviewPolicy(ctx, &api.PolicyFind{ID: &payload.PolicyID})@@ -53,12 +53,12 @@ func (*TaskCheckStatementAdvisorCompositeExecutor) Run(ctx context.Context, serv},}, nil}- return nil, common.Errorf(common.Internal, "failed to get SQL review policy: %w", err)+ return nil, common.Wrapf(err, common.Internal, "failed to get SQL review policy")}task, err := server.store.GetTaskByID(ctx, taskCheckRun.TaskID)if err != nil {- return nil, common.Errorf(common.Internal, "failed to get task by id: %w", err)+ return nil, common.Wrapf(err, common.Internal, "failed to get task by id")}catalog := store.NewCatalog(task.DatabaseID, server.store, payload.DbType)diff --git a/server/task_check_executor_statement_advisor_simple.go b/server/task_check_executor_statement_advisor_simple.goindex f9d8166f10..49ef77e34a 100644--- a/server/task_check_executor_statement_advisor_simple.go+++ b/server/task_check_executor_statement_advisor_simple.go@@ -24,7 +24,7 @@ type TaskCheckStatementAdvisorSimpleExecutor struct {func (*TaskCheckStatementAdvisorSimpleExecutor) Run(_ context.Context, _ *Server, taskCheckRun *api.TaskCheckRun) (result []api.TaskCheckResult, err error) {payload := &api.TaskCheckDatabaseStatementAdvisePayload{}if err := json.Unmarshal([]byte(taskCheckRun.Payload), payload); err != nil {- return nil, common.Errorf(common.Invalid, "invalid check statement advise payload: %w", err)+ return nil, common.Wrapf(err, common.Invalid, "invalid check statement advise payload")}var advisorType advisor.Type@@ -57,7 +57,7 @@ func (*TaskCheckStatementAdvisorSimpleExecutor) Run(_ context.Context, _ *Serverpayload.Statement,)if err != nil {- return nil, common.Errorf(common.Internal, "failed to check statement: %w", err)+ return nil, common.Wrapf(err, common.Internal, "failed to check statement")}result = []api.TaskCheckResult{}diff --git a/server/task_check_executor_statement_type.go b/server/task_check_executor_statement_type.goindex 27b82f6f5c..c6a0ce887f 100644--- a/server/task_check_executor_statement_type.go+++ b/server/task_check_executor_statement_type.go@@ -26,7 +26,7 @@ type TaskCheckStatementTypeExecutor struct {func (*TaskCheckStatementTypeExecutor) Run(ctx context.Context, server *Server, taskCheckRun *api.TaskCheckRun) (result []api.TaskCheckResult, err error) {task, err := server.store.GetTaskByID(ctx, taskCheckRun.TaskID)if err != nil {- return []api.TaskCheckResult{}, common.WithError(common.Internal, err)+ return []api.TaskCheckResult{}, common.Wrap(err, common.Internal)}if task == nil {return []api.TaskCheckResult{@@ -42,7 +42,7 @@ func (*TaskCheckStatementTypeExecutor) Run(ctx context.Context, server *Server,payload := &api.TaskCheckDatabaseStatementTypePayload{}if err := json.Unmarshal([]byte(taskCheckRun.Payload), payload); err != nil {- return nil, common.Errorf(common.Invalid, "invalid check statement type payload: %w", err)+ return nil, common.Wrapf(err, common.Invalid, "invalid check statement type payload")}if payload.DbType != db.Postgres {diff --git a/server/task_check_executor_timing.go b/server/task_check_executor_timing.goindex 0a3c055b26..b47289cd29 100644--- a/server/task_check_executor_timing.go+++ b/server/task_check_executor_timing.go@@ -25,7 +25,7 @@ const dataFormat = "2006-01-02 15:04:05"func (*TaskCheckTimingExecutor) Run(_ context.Context, _ *Server, taskCheckRun *api.TaskCheckRun) (result []api.TaskCheckResult, err error) {payload := &api.TaskCheckEarliestAllowedTimePayload{}if err := json.Unmarshal([]byte(taskCheckRun.Payload), payload); err != nil {- return []api.TaskCheckResult{}, common.Errorf(common.Invalid, "invalid check timing payload: %w", err)+ return []api.TaskCheckResult{}, common.Wrapf(err, common.Invalid, "invalid check timing payload")}if payload.EarliestAllowedTs == 0 {diff --git a/server/task_check_scheduler.go b/server/task_check_scheduler.goindex c8ef2a19e2..e6844b119b 100644--- a/server/task_check_scheduler.go+++ b/server/task_check_scheduler.go@@ -46,7 +46,7 @@ func (s *TaskCheckScheduler) Run(ctx context.Context, wg *sync.WaitGroup) {if r := recover(); r != nil {err, ok := r.(error)if !ok {- err = fmt.Errorf("%v", r)+ err = errors.Errorf("%v", r)}log.Error("Task check scheduler PANIC RECOVER", zap.Error(err))}@@ -278,7 +278,7 @@ func (s *TaskCheckScheduler) ScheduleCheckIfNeeded(ctx context.Context, task *apreturn nil, err}if database == nil {- return nil, fmt.Errorf("database ID not found %v", task.DatabaseID)+ return nil, errors.Errorf("database ID not found %v", task.DatabaseID)}_, err = s.server.store.CreateTaskCheckRunIfNeeded(ctx, &api.TaskCheckRunCreate{diff --git a/server/task_executor.go b/server/task_executor.goindex 6a760cbbd9..ae77c8ccc2 100644--- a/server/task_executor.go+++ b/server/task_executor.go@@ -40,12 +40,12 @@ func RunTaskExecutorOnce(ctx context.Context, exec TaskExecutor, server *Server,if r := recover(); r != nil {panicErr, ok := r.(error)if !ok {- panicErr = fmt.Errorf("%v", r)+ panicErr = errors.Errorf("%v", r)}log.Error("TaskExecutor PANIC RECOVER", zap.Error(panicErr))terminated = trueresult = nil- err = fmt.Errorf("encounter internal error when executing task")+ err = errors.Errorf("encounter internal error when executing task")}}()@@ -58,7 +58,7 @@ func preMigration(ctx context.Context, server *Server, task *api.Task, migrationif migrationType == db.Data {msg = "missing database when updating data"}- return nil, fmt.Errorf(msg)+ return nil, errors.Errorf(msg)}databaseName := task.Database.Name@@ -121,7 +121,7 @@ func preMigration(ctx context.Context, server *Server, task *api.Task, migrationstatement = strings.TrimSpace(statement)// Only baseline can have empty sql statement, which indicates empty database.if mi.Type != db.Baseline && statement == "" {- return nil, fmt.Errorf("empty statement")+ return nil, errors.Errorf("empty statement")}// We will force migration for baseline and migrate type of migrations.// This usually happens when the previous attempt fails and the client retries the migration.@@ -219,10 +219,10 @@ func postMigration(ctx context.Context, server *Server, task *api.Task, vcsPushEvcs, err := server.store.GetVCSByID(ctx, repo.VCSID)if err != nil {- return true, nil, fmt.Errorf("failed to sync schema file %s after applying migration %s to %q", latestSchemaFile, mi.Version, databaseName)+ return true, nil, errors.Errorf("failed to sync schema file %s after applying migration %s to %q", latestSchemaFile, mi.Version, databaseName)}if vcs == nil {- return true, nil, fmt.Errorf("VCS ID not found: %d", repo.VCSID)+ return true, nil, errors.Errorf("VCS ID not found: %d", repo.VCSID)}repo.VCS = vcs@@ -331,10 +331,10 @@ func findRepositoryByTask(ctx context.Context, server *Server, task *api.Task) (}repo, err := server.store.GetRepository(ctx, repoFind)if err != nil {- return nil, fmt.Errorf("failed to find linked repository for database %q", task.Database.Name)+ return nil, errors.Errorf("failed to find linked repository for database %q", task.Database.Name)}if repo == nil {- return nil, fmt.Errorf("repository not found with project ID %v", task.Database.ProjectID)+ return nil, errors.Errorf("repository not found with project ID %v", task.Database.ProjectID)}return repo, nil}@@ -387,7 +387,7 @@ func writeBackLatestSchema(ctx context.Context, server *Server, repository *api.return "", errors.Wrap(err, "failed to fetch repository for schema write-back")}if repo2 == nil {- return "", fmt.Errorf("repository not found for schema write-back: %v", repository.ID)+ return "", errors.Errorf("repository not found for schema write-back: %v", repository.ID)}schemaFileCommit := vcsPlugin.FileCommitCreate{@@ -451,7 +451,7 @@ func writeBackLatestSchema(ctx context.Context, server *Server, repository *api.return "", errors.Wrap(err, "failed to fetch repository after schema write-back")}if repo2 == nil {- return "", fmt.Errorf("repository not found after schema write-back: %v", repository.ID)+ return "", errors.Errorf("repository not found after schema write-back: %v", repository.ID)}// VCS such as GitLab API doesn't return the commit on write, so we have to call ReadFileMeta againschemaFileMeta, err = vcsPlugin.Get(repo2.VCS.Type, vcsPlugin.ProviderConfig{}).ReadFileMeta(diff --git a/server/task_executor_database_backup.go b/server/task_executor_database_backup.goindex 39f9b05ba7..8133a5d7f8 100644--- a/server/task_executor_database_backup.go+++ b/server/task_executor_database_backup.go@@ -47,7 +47,7 @@ func (exec *DatabaseBackupTaskExecutor) RunOnce(ctx context.Context, server *Serreturn true, nil, errors.Wrapf(err, "failed to find backup with ID %d", payload.BackupID)}if backup == nil {- return true, nil, fmt.Errorf("backup %v not found", payload.BackupID)+ return true, nil, errors.Errorf("backup %v not found", payload.BackupID)}log.Debug("Start database backup...",zap.String("instance", task.Instance.Name),@@ -90,7 +90,7 @@ func (*DatabaseBackupTaskExecutor) backupDatabase(ctx context.Context, server *Sf, err := os.Create(filepath.Join(server.profile.DataDir, backup.Path))if err != nil {- return "", fmt.Errorf("failed to open backup path: %s", backup.Path)+ return "", errors.Errorf("failed to open backup path: %s", backup.Path)}defer f.Close()diff --git a/server/task_executor_database_create.go b/server/task_executor_database_create.goindex 1fff704564..1e2d84905d 100644--- a/server/task_executor_database_create.go+++ b/server/task_executor_database_create.go@@ -45,7 +45,7 @@ func (exec *DatabaseCreateTaskExecutor) RunOnce(ctx context.Context, server *Serstatement := strings.TrimSpace(payload.Statement)if statement == "" {- return true, nil, fmt.Errorf("empty create database statement")+ return true, nil, errors.Errorf("empty create database statement")}instance := task.Instance@@ -97,7 +97,7 @@ func (exec *DatabaseCreateTaskExecutor) RunOnce(ctx context.Context, server *Ser)}if issue == nil {- err := fmt.Errorf("failed to fetch containing issue for composing the migration info, issue not found with pipeline ID %v", task.PipelineID)+ err := errors.Errorf("failed to fetch containing issue for composing the migration info, issue not found with pipeline ID %v", task.PipelineID)log.Error(err.Error(),zap.Int("task_id", task.ID),zap.Error(err),@@ -167,16 +167,16 @@ func (exec *DatabaseCreateTaskExecutor) RunOnce(ctx context.Context, server *Serif payload.Labels != "" {project, err := server.store.GetProjectByID(ctx, payload.ProjectID)if err != nil {- return true, nil, fmt.Errorf("failed to find project with ID %d", payload.ProjectID)+ return true, nil, errors.Errorf("failed to find project with ID %d", payload.ProjectID)}if project == nil {- return true, nil, fmt.Errorf("project not found with ID %d", payload.ProjectID)+ return true, nil, errors.Errorf("project not found with ID %d", payload.ProjectID)}// Set database labels, except bb.environment is immutable and must match instance environment.err = server.setDatabaseLabels(ctx, payload.Labels, database, project, database.CreatorID, false)if err != nil {- return true, nil, fmt.Errorf("failed to record database labels after creating database %v", database.ID)+ return true, nil, errors.Errorf("failed to record database labels after creating database %v", database.ID)}}diff --git a/server/task_executor_database_restore.go b/server/task_executor_database_restore.goindex 8ff8e1e67a..934e2212bf 100644--- a/server/task_executor_database_restore.go+++ b/server/task_executor_database_restore.go@@ -51,7 +51,7 @@ func (exec *DatabaseRestoreTaskExecutor) RunOnce(ctx context.Context, server *Sereturn true, nil, errors.Wrapf(err, "failed to find backup with ID %d", payload.BackupID)}if backup == nil {- return true, nil, fmt.Errorf("backup with ID %d not found", payload.BackupID)+ return true, nil, errors.Errorf("backup with ID %d not found", payload.BackupID)}sourceDatabase, err := server.store.GetDatabase(ctx, &api.DatabaseFind{ID: &backup.DatabaseID})@@ -59,7 +59,7 @@ func (exec *DatabaseRestoreTaskExecutor) RunOnce(ctx context.Context, server *Sereturn true, nil, errors.Wrap(err, "failed to find database for the backup")}if sourceDatabase == nil {- return true, nil, fmt.Errorf("source database ID not found %v", backup.DatabaseID)+ return true, nil, errors.Errorf("source database ID not found %v", backup.DatabaseID)}targetDatabaseFind := &api.DatabaseFind{diff --git a/server/task_executor_pitr_cutover.go b/server/task_executor_pitr_cutover.goindex abdcc5c8de..8d719daf9a 100644--- a/server/task_executor_pitr_cutover.go+++ b/server/task_executor_pitr_cutover.go@@ -106,7 +106,7 @@ func (exec *PITRCutoverTaskExecutor) pitrCutover(ctx context.Context, task *api.return true, nil, errors.Wrap(err, "failed to do cutover for MySQL")}default:- return true, nil, fmt.Errorf("invalid database type %q for cutover task", task.Instance.Engine)+ return true, nil, errors.Errorf("invalid database type %q for cutover task", task.Instance.Engine)}log.Debug("Appending new migration history record")diff --git a/server/task_executor_pitr_restore.go b/server/task_executor_pitr_restore.goindex 9a5327ec53..be6cd3311d 100644--- a/server/task_executor_pitr_restore.go+++ b/server/task_executor_pitr_restore.go@@ -42,11 +42,11 @@ func (exec *PITRRestoreTaskExecutor) RunOnce(ctx context.Context, server *Server}if (payload.BackupID == nil) == (payload.PointInTimeTs == nil) {- return true, nil, fmt.Errorf("only one of BackupID and time point can be set")+ return true, nil, errors.Errorf("only one of BackupID and time point can be set")}if !((payload.DatabaseName == nil) == (payload.TargetInstanceID == nil)) {- return true, nil, fmt.Errorf("DatabaseName and TargetInstanceID must be both set or unset")+ return true, nil, errors.Errorf("DatabaseName and TargetInstanceID must be both set or unset")}// There are 2 * 2 = 4 kinds of task by combination of the following cases:@@ -83,7 +83,7 @@ func (exec *PITRRestoreTaskExecutor) doBackupRestore(ctx context.Context, serverreturn nil, errors.Wrapf(err, "failed to find backup with ID %d", *payload.BackupID)}if backup == nil {- return nil, fmt.Errorf("backup with ID %d not found", *payload.BackupID)+ return nil, errors.Errorf("backup with ID %d not found", *payload.BackupID)}// TODO(dragonly): We should let users restore the backup even if the source database is gone.@@ -92,7 +92,7 @@ func (exec *PITRRestoreTaskExecutor) doBackupRestore(ctx context.Context, serverreturn nil, errors.Wrap(err, "failed to find database for the backup")}if sourceDatabase == nil {- return nil, fmt.Errorf("source database ID not found %v", backup.DatabaseID)+ return nil, errors.Errorf("source database ID not found %v", backup.DatabaseID)}if payload.TargetInstanceID == nil {@@ -104,7 +104,7 @@ func (exec *PITRRestoreTaskExecutor) doBackupRestore(ctx context.Context, server}return exec.doRestoreInPlacePostgres(ctx, server, issue, task, payload)}- return nil, fmt.Errorf("we only support backup restore replace for PostgreSQL now")+ return nil, errors.Errorf("we only support backup restore replace for PostgreSQL now")}targetInstanceID := *payload.TargetInstanceID@@ -203,7 +203,7 @@ func (exec *PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, server *mysqlTargetDriver, targetOk := targetDriver.(*mysql.Driver)if (!sourceOk) || (!targetOk) {log.Error("Failed to cast driver to mysql.Driver")- return nil, fmt.Errorf("[internal] cast driver to mysql.Driver failed")+ return nil, errors.Errorf("[internal] cast driver to mysql.Driver failed")}log.Debug("Downloading all binlog files")@@ -289,7 +289,7 @@ func (exec *PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, server *func (*PITRRestoreTaskExecutor) doRestoreInPlacePostgres(ctx context.Context, server *Server, issue *api.Issue, task *api.Task, payload api.TaskDatabasePITRRestorePayload) (*api.TaskRunResultPayload, error) {if payload.BackupID == nil {- return nil, fmt.Errorf("PITR for Postgres is not implemented")+ return nil, errors.Errorf("PITR for Postgres is not implemented")}backup, err := server.store.GetBackupByID(ctx, *payload.BackupID)@@ -297,7 +297,7 @@ func (*PITRRestoreTaskExecutor) doRestoreInPlacePostgres(ctx context.Context, sereturn nil, errors.Wrapf(err, "failed to find backup with ID %d", *payload.BackupID)}if backup == nil {- return nil, fmt.Errorf("backup with ID %d not found", *payload.BackupID)+ return nil, errors.Errorf("backup with ID %d not found", *payload.BackupID)}backupFileName := getBackupAbsFilePath(server.profile.DataDir, backup.DatabaseID, backup.Name)backupFile, err := os.Open(backupFileName)@@ -393,7 +393,7 @@ func getIssueByPipelineID(ctx context.Context, store *store.Store, pid int) (*ap}if issue == nil {log.Error("issue not found with PipelineID", zap.Int("PipelineID", pid))- return nil, fmt.Errorf("issue not found with PipelineID: %d", pid)+ return nil, errors.Errorf("issue not found with PipelineID: %d", pid)}return issue, nil}diff --git a/server/task_executor_schema_update_ghost_cutover.go b/server/task_executor_schema_update_ghost_cutover.goindex 48595ee5bd..d821998896 100644--- a/server/task_executor_schema_update_ghost_cutover.go+++ b/server/task_executor_schema_update_ghost_cutover.go@@ -4,7 +4,6 @@ import ("bytes""context""encoding/json"- "fmt""os""strings""sync/atomic"@@ -62,7 +61,7 @@ func (exec *SchemaUpdateGhostCutoverTaskExecutor) RunOnce(ctx context.Context, svalue, ok := server.TaskScheduler.sharedTaskState.Load(syncTaskID)if !ok {- return true, nil, fmt.Errorf("failed to get gh-ost state from sync task")+ return true, nil, errors.Errorf("failed to get gh-ost state from sync task")}sharedGhost := value.(sharedGhostState)@@ -101,7 +100,7 @@ func cutover(ctx context.Context, server *Server, task *api.Task, statement, sch// try to make the time gap between the migration history insertion and the actual cutover as close as possible.cancelled := waitForCutover(ctx, migrationContext)if cancelled {- return -1, "", fmt.Errorf("cutover poller cancelled")+ return -1, "", errors.Errorf("cutover poller cancelled")}insertedID, err := util.BeginMigration(ctx, executor, mi, prevSchemaBuf.String(), statement, db.BytebaseDatabase)@@ -127,7 +126,7 @@ func cutover(ctx context.Context, server *Server, task *api.Task, statement, sch}if migrationErr := <-errCh; migrationErr != nil {- return -1, "", fmt.Errorf("failed to run gh-ost migration, err: %w", migrationErr)+ return -1, "", errors.Wrapf(migrationErr, "failed to run gh-ost migration")}var afterSchemaBuf bytes.Bufferdiff --git a/server/task_executor_schema_update_ghost_sync.go b/server/task_executor_schema_update_ghost_sync.goindex d3391ed896..b3608938c8 100644--- a/server/task_executor_schema_update_ghost_sync.go+++ b/server/task_executor_schema_update_ghost_sync.go@@ -69,7 +69,7 @@ func getTableNameFromStatement(statement string) (string, error) {statement = strings.Join(strings.Fields(statement), " ")parser := ghostsql.NewParserFromAlterStatement(statement)if !parser.HasExplicitTable() {- return "", fmt.Errorf("failed to parse table name from statement, statement: %v", statement)+ return "", errors.Errorf("failed to parse table name from statement, statement: %v", statement)}return parser.GetExplicitTable(), nil}@@ -139,20 +139,20 @@ func newMigrationContext(config ghostConfig) (*base.MigrationContext, error) {migrationContext.ThrottleHTTPTimeoutMillis = throttleHTTPTimeoutMillisif migrationContext.AlterStatement == "" {- return nil, fmt.Errorf("alterStatement must be provided and must not be empty")+ return nil, errors.Errorf("alterStatement must be provided and must not be empty")}parser := ghostsql.NewParserFromAlterStatement(migrationContext.AlterStatement)migrationContext.AlterStatementOptions = parser.GetAlterStatementOptions()if migrationContext.DatabaseName == "" {if !parser.HasExplicitSchema() {- return nil, fmt.Errorf("database must be provided and database name must not be empty, or alterStatement must specify database name")+ return nil, errors.Errorf("database must be provided and database name must not be empty, or alterStatement must specify database name")}migrationContext.DatabaseName = parser.GetExplicitSchema()}if migrationContext.OriginalTableName == "" {if !parser.HasExplicitTable() {- return nil, fmt.Errorf("table must be provided and table name must not be empty, or alterStatement must specify table name")+ return nil, errors.Errorf("table must be provided and table name must not be empty, or alterStatement must specify table name")}migrationContext.OriginalTableName = parser.GetExplicitTable()}diff --git a/server/task_scheduler.go b/server/task_scheduler.goindex 2aae805c09..76a196b7bc 100644--- a/server/task_scheduler.go+++ b/server/task_scheduler.go@@ -53,7 +53,7 @@ func (s *TaskScheduler) Run(ctx context.Context, wg *sync.WaitGroup) {if r := recover(); r != nil {err, ok := r.(error)if !ok {- err = fmt.Errorf("%v", r)+ err = errors.Errorf("%v", r)}log.Error("Task scheduler PANIC RECOVER", zap.Error(err))}@@ -256,7 +256,7 @@ func (s *TaskScheduler) passAllCheck(ctx context.Context, task *api.Task, allowereturn false, err}if instance == nil {- return false, fmt.Errorf("instance ID not found %v", task.InstanceID)+ return false, errors.Errorf("instance ID not found %v", task.InstanceID)}if api.IsSyntaxCheckSupported(instance.Engine, s.server.profile.Mode) {diff --git a/server/webhook.go b/server/webhook.goindex 8ad367d61a..397554411e 100644--- a/server/webhook.go+++ b/server/webhook.go@@ -62,7 +62,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {}if repo.VCS == nil {- err := fmt.Errorf("VCS not found for ID: %v", repo.VCSID)+ err := errors.Errorf("VCS not found for ID: %v", repo.VCSID)return echo.NewHTTPError(http.StatusInternalServerError, err).SetInternal(err)}@@ -142,7 +142,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {}if repo.VCS == nil {- err := fmt.Errorf("VCS not found for ID: %v", repo.VCSID)+ err := errors.Errorf("VCS not found for ID: %v", repo.VCSID)return echo.NewHTTPError(http.StatusInternalServerError, err).SetInternal(err)}@@ -320,9 +320,9 @@ func (s *Server) createSchemaUpdateIssue(ctx context.Context, repository *api.Re}databaseList, err := s.store.FindDatabase(ctx, databaseFind)if err != nil {- return "", fmt.Errorf("failed to find database matching database %q referenced by the committed file", mi.Database)+ return "", errors.Errorf("failed to find database matching database %q referenced by the committed file", mi.Database)} else if len(databaseList) == 0 {- return "", fmt.Errorf("project with ID %d does not own database %q referenced by the committed file", repository.ProjectID, mi.Database)+ return "", errors.Errorf("project with ID %d does not own database %q referenced by the committed file", repository.ProjectID, mi.Database)}// We support 3 patterns on how to organize the schema files.@@ -346,7 +346,7 @@ func (s *Server) createSchemaUpdateIssue(ctx context.Context, repository *api.Re}}if len(filteredDatabaseList) == 0 {- return "", fmt.Errorf("project does not contain committed file database %q for environment %q", mi.Database, mi.Environment)+ return "", errors.Errorf("project does not contain committed file database %q for environment %q", mi.Database, mi.Environment)}} else {filteredDatabaseList = databaseList@@ -365,7 +365,7 @@ func (s *Server) createSchemaUpdateIssue(ctx context.Context, repository *api.Re}}if len(multipleDatabaseForSameEnv) > 0 {- return "", fmt.Errorf("ignored committed files with multiple ambiguous databases %s", strings.Join(multipleDatabaseForSameEnv, ", "))+ return "", errors.Errorf("ignored committed files with multiple ambiguous databases %s", strings.Join(multipleDatabaseForSameEnv, ", "))}// Compose the new issue@@ -390,7 +390,7 @@ func (s *Server) createSchemaUpdateIssue(ctx context.Context, repository *api.Refunc createTenantSchemaUpdateIssue(mi *db.MigrationInfo, vcsPushEvent vcs.PushEvent, statement string) (string, error) {// We don't take environment for tenant mode project because the databases needing schema update are determined by database name and deployment configuration.if mi.Environment != "" {- return "", fmt.Errorf("environment isn't accepted in schema update for tenant mode project")+ return "", errors.Errorf("environment isn't accepted in schema update for tenant mode project")}m := &api.UpdateSchemaContext{MigrationType: mi.Type,diff --git a/store/activity.go b/store/activity.goindex 0f88fa3adb..df7ccda598 100644--- a/store/activity.go+++ b/store/activity.go@@ -171,7 +171,7 @@ func (s *Store) getActivityRawByID(ctx context.Context, id int) (*activityRaw, eif len(list) == 0 {return nil, nil} else if len(list) > 1 {- return nil, &common.Error{Code: common.Conflict, Err: fmt.Errorf("found %d activities with filter %+v, expect 1. ", len(list), find)}+ return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d activities with filter %+v, expect 1. ", len(list), find)}}return list[0], nil}@@ -369,7 +369,7 @@ func patchActivityImpl(ctx context.Context, tx *sql.Tx, patch *api.ActivityPatch&activityRaw.Payload,); err != nil {if err == sql.ErrNoRows {- return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("activity ID not found: %d", patch.ID)}+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("activity ID not found: %d", patch.ID)}}return nil, FormatError(err)}diff --git a/store/anomaly.go b/store/anomaly.goindex 29ae1606fb..0f8070a02f 100644--- a/store/anomaly.go+++ b/store/anomaly.go@@ -149,7 +149,7 @@ func (s *Store) upsertActiveAnomalyRaw(ctx context.Context, upsert *api.AnomalyUreturn nil, err}} else {- return nil, &common.Error{Code: common.Conflict, Err: fmt.Errorf("found %d active anomalies with filter %+v, expect 1", len(list), find)}+ return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d active anomalies with filter %+v, expect 1", len(list), find)}}if err := tx.PTx.Commit(); err != nil {@@ -383,10 +383,10 @@ func patchAnomalyImpl(ctx context.Context, tx *sql.Tx, patch *anomalyPatch) (*an// archiveAnomalyImpl archives an anomaly by ID.func archiveAnomalyImpl(ctx context.Context, tx *sql.Tx, archive *api.AnomalyArchive) error {if archive.InstanceID == nil && archive.DatabaseID == nil {- return &common.Error{Code: common.Internal, Err: fmt.Errorf("failed to close anomaly, should specify either instanceID or databaseID")}+ return &common.Error{Code: common.Internal, Err: errors.Errorf("failed to close anomaly, should specify either instanceID or databaseID")}}if archive.InstanceID != nil && archive.DatabaseID != nil {- return &common.Error{Code: common.Internal, Err: fmt.Errorf("failed to close anomaly, should specify either instanceID or databaseID, but not both")}+ return &common.Error{Code: common.Internal, Err: errors.Errorf("failed to close anomaly, should specify either instanceID or databaseID, but not both")}}// Remove row from database.if archive.InstanceID != nil {@@ -402,7 +402,7 @@ func archiveAnomalyImpl(ctx context.Context, tx *sql.Tx, archive *api.AnomalyArcrows, _ := result.RowsAffected()if rows == 0 {- return &common.Error{Code: common.NotFound, Err: fmt.Errorf("anomaly not found instance: %d type: %s", *archive.InstanceID, archive.Type)}+ return &common.Error{Code: common.NotFound, Err: errors.Errorf("anomaly not found instance: %d type: %s", *archive.InstanceID, archive.Type)}}} else if archive.DatabaseID != nil {result, err := tx.ExecContext(ctx,@@ -417,7 +417,7 @@ func archiveAnomalyImpl(ctx context.Context, tx *sql.Tx, archive *api.AnomalyArcrows, _ := result.RowsAffected()if rows == 0 {- return &common.Error{Code: common.NotFound, Err: fmt.Errorf("anomaly not found database: %d type: %s", *archive.DatabaseID, archive.Type)}+ return &common.Error{Code: common.NotFound, Err: errors.Errorf("anomaly not found database: %d type: %s", *archive.DatabaseID, archive.Type)}}}diff --git a/store/backup.go b/store/backup.goindex 6c734728e4..620943782a 100644--- a/store/backup.go+++ b/store/backup.go@@ -321,7 +321,7 @@ func (s *Store) getBackupRawByID(ctx context.Context, id int) (*backupRaw, errorif len(backupRawList) == 0 {return nil, nil} else if len(backupRawList) > 1 {- return nil, &common.Error{Code: common.Conflict, Err: fmt.Errorf("found %d backups with filter %+v, expect 1. ", len(backupRawList), find)}+ return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d backups with filter %+v, expect 1. ", len(backupRawList), find)}}return backupRawList[0], nil}@@ -372,16 +372,16 @@ func (s *Store) upsertBackupSettingRaw(ctx context.Context, upsert *api.BackupSe// Backup plan policy check for backup setting mutation.if backupPlanPolicy.Schedule != api.BackupPlanPolicyScheduleUnset {if !upsert.Enabled {- return nil, &common.Error{Code: common.Invalid, Err: fmt.Errorf("backup setting should not be disabled for backup plan policy schedule %q", backupPlanPolicy.Schedule)}+ return nil, &common.Error{Code: common.Invalid, Err: errors.Errorf("backup setting should not be disabled for backup plan policy schedule %q", backupPlanPolicy.Schedule)}}switch backupPlanPolicy.Schedule {case api.BackupPlanPolicyScheduleDaily:if upsert.DayOfWeek != -1 {- return nil, &common.Error{Code: common.Invalid, Err: fmt.Errorf("backup setting DayOfWeek should be unset for backup plan policy schedule %q", backupPlanPolicy.Schedule)}+ return nil, &common.Error{Code: common.Invalid, Err: errors.Errorf("backup setting DayOfWeek should be unset for backup plan policy schedule %q", backupPlanPolicy.Schedule)}}case api.BackupPlanPolicyScheduleWeekly:if upsert.DayOfWeek == -1 {- return nil, &common.Error{Code: common.Invalid, Err: fmt.Errorf("backup setting DayOfWeek should be set for backup plan policy schedule %q", backupPlanPolicy.Schedule)}+ return nil, &common.Error{Code: common.Invalid, Err: errors.Errorf("backup setting DayOfWeek should be set for backup plan policy schedule %q", backupPlanPolicy.Schedule)}}}}@@ -576,7 +576,7 @@ func (*Store) patchBackupImpl(ctx context.Context, tx *sql.Tx, patch *api.Backup&payload,); err != nil {if err == sql.ErrNoRows {- return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("backup ID not found: %d", patch.ID)}+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("backup ID not found: %d", patch.ID)}}return nil, FormatError(err)}@@ -603,7 +603,7 @@ func (s *Store) getBackupSettingRaw(ctx context.Context, find *api.BackupSettingif len(list) == 0 {return nil, nil} else if len(list) > 1 {- return nil, &common.Error{Code: common.Conflict, Err: fmt.Errorf("found %d backup settings with filter %+v, expect 1. ", len(list), find)}+ return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d backup settings with filter %+v, expect 1. ", len(list), find)}}return list[0], nil}diff --git a/store/bookmark.go b/store/bookmark.goindex f87fa35d05..9c7d0bc365 100644--- a/store/bookmark.go+++ b/store/bookmark.go@@ -167,7 +167,7 @@ func (s *Store) getBookmarkRaw(ctx context.Context, find *api.BookmarkFind) (*boif len(bookmarkRawList) == 0 {return nil, nil} else if len(bookmarkRawList) > 1 {- return nil, &common.Error{Code: common.Conflict, Err: fmt.Errorf("found %d activities with filter %+v, expect 1. ", len(bookmarkRawList), find)}+ return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d activities with filter %+v, expect 1. ", len(bookmarkRawList), find)}}return bookmarkRawList[0], nil}@@ -291,7 +291,7 @@ func (*Store) deleteBookmarkImpl(ctx context.Context, tx *sql.Tx, delete *api.Borows, _ := result.RowsAffected()if rows == 0 {- return &common.Error{Code: common.NotFound, Err: fmt.Errorf("bookmark ID not found: %d", delete.ID)}+ return &common.Error{Code: common.NotFound, Err: errors.Errorf("bookmark ID not found: %d", delete.ID)}}return nildiff --git a/store/catalog.go b/store/catalog.goindex 7edabf1b86..b7279fc0bd 100644--- a/store/catalog.go+++ b/store/catalog.go@@ -2,7 +2,6 @@ package storeimport ("context"- "fmt""sort""strings"@@ -10,6 +9,7 @@ import ("github.com/bytebase/bytebase/plugin/advisor/catalog"advisorDB "github.com/bytebase/bytebase/plugin/advisor/db""github.com/bytebase/bytebase/plugin/db"+ "github.com/pkg/errors")var (@@ -169,7 +169,7 @@ func (c *Catalog) getSchemaList(ctx context.Context) ([]*catalog.Schema, error)func splitPGSchema(name string) (string, string, error) {list := strings.Split(name, ".")if len(list) != 2 {- return "", "", fmt.Errorf("split failed: the expected name is schemaName.name, but get %s", name)+ return "", "", errors.Errorf("split failed: the expected name is schemaName.name, but get %s", name)}return list[0], list[1], nil}diff --git a/store/data_source.go b/store/data_source.goindex e301c9d107..d58e84cd3b 100644--- a/store/data_source.go+++ b/store/data_source.go@@ -207,7 +207,7 @@ func (s *Store) getDataSourceRaw(ctx context.Context, find *api.DataSourceFind)if len(list) == 0 {return nil, nil} else if len(list) > 1 {- return nil, &common.Error{Code: common.Conflict, Err: fmt.Errorf("found %d data sources with filter %+v, expect 1", len(list), find)}+ return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d data sources with filter %+v, expect 1", len(list), find)}}return list[0], nil}@@ -410,7 +410,7 @@ func (*Store) patchDataSourceImpl(ctx context.Context, tx *sql.Tx, patch *api.Da&dataSourceRaw.SslCa,); err != nil {if err == sql.ErrNoRows {- return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("DataSource not found with ID %d", patch.ID)}+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("DataSource not found with ID %d", patch.ID)}}return nil, FormatError(err)}diff --git a/store/database.go b/store/database.goindex 804bd043f4..e44ce26237 100644--- a/store/database.go+++ b/store/database.go@@ -397,7 +397,7 @@ func (s *Store) getDatabaseRaw(ctx context.Context, find *api.DatabaseFind) (*daif len(list) == 0 {return nil, nil} else if len(list) > 1 {- return nil, &common.Error{Code: common.Conflict, Err: fmt.Errorf("found %d databases with filter %+v, expect 1. ", len(list), find)}+ return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d databases with filter %+v, expect 1. ", len(list), find)}}if err := s.cache.UpsertCache(api.DatabaseCache, list[0].ID, list[0]); err != nil {@@ -643,7 +643,7 @@ func (*Store) patchDatabaseImpl(ctx context.Context, tx *sql.Tx, patch *api.Data&databaseRaw.SchemaVersion,); err != nil {if err == sql.ErrNoRows {- return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("database ID not found: %d", patch.ID)}+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("database ID not found: %d", patch.ID)}}return nil, FormatError(err)}diff --git a/store/deploy.go b/store/deploy.goindex fb962023ad..f757f55bd1 100644--- a/store/deploy.go+++ b/store/deploy.go@@ -198,7 +198,7 @@ func (s *Store) getDeploymentConfigImpl(ctx context.Context, find *api.Deploymencase 1:return ret[0], nildefault:- return nil, &common.Error{Code: common.Conflict, Err: fmt.Errorf("found %d deployment configurations with filter %+v, expect 1", len(ret), find)}+ return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d deployment configurations with filter %+v, expect 1", len(ret), find)}}}diff --git a/store/environment.go b/store/environment.goindex 5083c07db9..c170444582 100644--- a/store/environment.go+++ b/store/environment.go@@ -203,7 +203,7 @@ func (s *Store) getEnvironmentByIDRaw(ctx context.Context, id int) (*environmentif len(envRawList) == 0 {return nil, nil} else if len(envRawList) > 1 {- return nil, &common.Error{Code: common.Conflict, Err: fmt.Errorf("found %d environments with filter %+v, expect 1", len(envRawList), find)}+ return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d environments with filter %+v, expect 1", len(envRawList), find)}}if err := s.cache.UpsertCache(api.EnvironmentCache, envRawList[0].ID, envRawList[0]); err != nil {return nil, err@@ -247,7 +247,7 @@ func (Store) createEnvironmentImpl(ctx context.Context, tx *sql.Tx, create *api.LIMIT 1`).Scan(&order); err != nil {if err == sql.ErrNoRows {- return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("no environment record found")}+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("no environment record found")}}return nil, FormatError(err)}@@ -381,7 +381,7 @@ func (*Store) patchEnvironmentImpl(ctx context.Context, tx *sql.Tx, patch *api.E&environment.Order,); err != nil {if err == sql.ErrNoRows {- return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("environment ID not found: %d", patch.ID)}+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("environment ID not found: %d", patch.ID)}}return nil, FormatError(err)}diff --git a/store/inbox.go b/store/inbox.goindex 54c7d471ba..09c286178d 100644--- a/store/inbox.go+++ b/store/inbox.go@@ -195,7 +195,7 @@ func (s *Store) getInboxRawByID(ctx context.Context, find *api.InboxFind) (*inboif len(list) == 0 {return nil, nil} else if len(list) > 1 {- return nil, &common.Error{Code: common.Conflict, Err: fmt.Errorf("found %d inboxes with filter %+v, expect 1", len(list), find)}+ return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d inboxes with filter %+v, expect 1", len(list), find)}}return list[0], nil}@@ -350,7 +350,7 @@ func (s *Store) patchInboxImpl(ctx context.Context, tx *sql.Tx, patch *api.Inbox&inboxRaw.Status,); err != nil {if err == sql.ErrNoRows {- return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("inbox ID not found: %d", patch.ID)}+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("inbox ID not found: %d", patch.ID)}}return nil, FormatError(err)}diff --git a/store/instance.go b/store/instance.goindex ea871dd750..3130234ebd 100644--- a/store/instance.go+++ b/store/instance.go@@ -260,7 +260,7 @@ func (s *Store) GetInstanceAdminPasswordByID(ctx context.Context, instanceID intreturn dataSourceRaw.Password, nil}}- return "", &common.Error{Code: common.NotFound, Err: fmt.Errorf("missing admin password for instance with ID %d", instanceID)}+ return "", &common.Error{Code: common.NotFound, Err: errors.Errorf("missing admin password for instance with ID %d", instanceID)}}// GetInstanceSslSuiteByID gets ssl suite of instance.@@ -279,7 +279,7 @@ func (s *Store) GetInstanceSslSuiteByID(ctx context.Context, instanceID int) (dbSslCert: dataSourceRaw.SslCert,}, nil}- return db.TLSConfig{}, &common.Error{Code: common.NotFound, Err: fmt.Errorf("missing ssl suite for instance with ID %d", instanceID)}+ return db.TLSConfig{}, &common.Error{Code: common.NotFound, Err: errors.Errorf("missing ssl suite for instance with ID %d", instanceID)}}//@@ -437,7 +437,7 @@ func (s *Store) getInstanceRaw(ctx context.Context, find *api.InstanceFind) (*inif len(list) == 0 {return nil, nil} else if len(list) > 1 {- return nil, &common.Error{Code: common.Conflict, Err: fmt.Errorf("found %d instances with filter %+v, expect 1", len(list), find)}+ return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d instances with filter %+v, expect 1", len(list), find)}}instance := list[0]@@ -629,7 +629,7 @@ func patchInstanceImpl(ctx context.Context, tx *sql.Tx, patch *api.InstancePatch&instanceRaw.Port,); err != nil {if err == sql.ErrNoRows {- return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("instance ID not found: %d", patch.ID)}+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("instance ID not found: %d", patch.ID)}}return nil, FormatError(err)}diff --git a/store/issue.go b/store/issue.goindex 671ea60bc0..95138e6e8a 100644--- a/store/issue.go+++ b/store/issue.go@@ -432,7 +432,7 @@ func (s *Store) getIssueRaw(ctx context.Context, find *api.IssueFind) (*issueRawif len(list) == 0 {return nil, nil} else if len(list) > 1 {- return nil, &common.Error{Code: common.Conflict, Err: fmt.Errorf("found %d issues with filter %+v, expect 1", len(list), find)}+ return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d issues with filter %+v, expect 1", len(list), find)}}if err := s.cache.UpsertCache(api.IssueCache, list[0].ID, list[0]); err != nil {return nil, err@@ -657,7 +657,7 @@ func (*Store) patchIssueImpl(ctx context.Context, tx *sql.Tx, patch *api.IssuePa&issueRaw.Payload,); err != nil {if err == sql.ErrNoRows {- return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("unable to find issue ID to update: %d", patch.ID)}+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("unable to find issue ID to update: %d", patch.ID)}}return nil, FormatError(err)}diff --git a/store/member.go b/store/member.goindex 1212871342..872accbcac 100644--- a/store/member.go+++ b/store/member.go@@ -238,7 +238,7 @@ func (s *Store) getMemberRaw(ctx context.Context, find *api.MemberFind) (*memberif len(list) == 0 {return nil, nil} else if len(list) > 1 {- return nil, &common.Error{Code: common.Conflict, Err: fmt.Errorf("found %d members with filter %+v, expect 1", len(list), find)}+ return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d members with filter %+v, expect 1", len(list), find)}}if err := s.cache.UpsertCache(api.MemberCache, list[0].PrincipalID, list[0]); err != nil {return nil, err@@ -430,7 +430,7 @@ func patchMemberImpl(ctx context.Context, tx *sql.Tx, patch *api.MemberPatch) (*&memberRaw.PrincipalID,); err != nil {if err == sql.ErrNoRows {- return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("member ID not found: %d", patch.ID)}+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("member ID not found: %d", patch.ID)}}return nil, FormatError(err)}diff --git a/store/metadb.go b/store/metadb.goindex 0c24f670c0..7cdf48c2a5 100644--- a/store/metadb.go+++ b/store/metadb.go@@ -10,6 +10,7 @@ import ("github.com/bytebase/bytebase/common/log"dbdriver "github.com/bytebase/bytebase/plugin/db""github.com/bytebase/bytebase/resources/postgres"+ "github.com/pkg/errors""go.uber.org/zap")@@ -90,7 +91,7 @@ func (m *MetadataDB) connectExternal(readonly bool, version string) (*DB, error)log.Info("Establishing external PostgreSQL connection...", zap.String("pgURL", u.Redacted()))if u.Scheme != "postgresql" {- return nil, fmt.Errorf("invalid connection protocol: %s", u.Scheme)+ return nil, errors.Errorf("invalid connection protocol: %s", u.Scheme)}connCfg := dbdriver.ConnectionConfig{@@ -103,7 +104,7 @@ func (m *MetadataDB) connectExternal(readonly bool, version string) (*DB, error)}if connCfg.Username == "" {- return nil, fmt.Errorf("missing user in the --pg connection string")+ return nil, errors.Errorf("missing user in the --pg connection string")}if host, port, err := net.SplitHostPort(u.Host); err != nil {@@ -120,7 +121,7 @@ func (m *MetadataDB) connectExternal(readonly bool, version string) (*DB, error)hostInQuery := q.Get("host")if hostInQuery != "" && host != "" {// In this case, it is impossible to decide whether to use socket or tcp.- return nil, fmt.Errorf("please only using socket or host instead of both")+ return nil, errors.Errorf("please only using socket or host instead of both")}connCfg.Host = hostif hostInQuery != "" {@@ -130,7 +131,7 @@ func (m *MetadataDB) connectExternal(readonly bool, version string) (*DB, error)}if u.Path == "" {- return nil, fmt.Errorf("missing database in the --pg connection string")+ return nil, errors.Errorf("missing database in the --pg connection string")}connCfg.Database = u.Path[1:]diff --git a/store/pg_engine.go b/store/pg_engine.goindex 4d7c7cdfeb..fcba1ec8c0 100644--- a/store/pg_engine.go+++ b/store/pg_engine.go@@ -179,11 +179,10 @@ func (db *DB) Open(ctx context.Context) (err error) {}if err := db.setupDemoData(); err != nil {- return fmt.Errorf("failed to setup demo data: %w."++ return errors.Wrapf(err, "failed to setup demo data."+" It could be Bytebase is running against an old Bytebase schema. If you are developing Bytebase, you can remove pgdata"+" directory under the same directory where the Bytebase binary resides. and restart again to let"+- " Bytebase create the latest schema. If you are running in production and don't want to reset the data, you can contact [email protected] for help",- err)+ " Bytebase create the latest schema. If you are running in production and don't want to reset the data, you can contact [email protected] for help")}return nil@@ -216,7 +215,7 @@ func getLatestVersion(ctx context.Context, d dbdriver.Driver, database string) (return &v, nil}- return nil, fmt.Errorf("failed to find a successful migration history")+ return nil, errors.Errorf("failed to find a successful migration history")}// setupDemoData loads the setupDemoData data for testing.@@ -288,7 +287,7 @@ func migrate(ctx context.Context, d dbdriver.Driver, curVer *semver.Version, modlog.Info(fmt.Sprintf("Current schema version before migration: %s", curVer))major := curVer.Majorif 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)+ return errors.Errorf("current major schema version %d is different from the major schema version %d this release %s expects", major, majorSchemaVersion, serverVersion)}}@@ -449,7 +448,7 @@ func getProdCutoffVersion() (semver.Version, error) {return semver.Version{}, err}if len(versions) == 0 {- return semver.Version{}, fmt.Errorf("migration path %s has no minor version", minorPathPrefix)+ return semver.Version{}, errors.Errorf("migration path %s has no minor version", minorPathPrefix)}minorVersion := versions[len(versions)-1]@@ -463,7 +462,7 @@ func getProdCutoffVersion() (semver.Version, error) {return semver.Version{}, err}if len(patchVersions) == 0 {- return semver.Version{}, fmt.Errorf("migration path %s has no patch version", patchPathPrefix)+ return semver.Version{}, errors.Errorf("migration path %s has no patch version", patchPathPrefix)}return patchVersions[len(patchVersions)-1].version, nil}@@ -536,7 +535,7 @@ func getDevMigrations() ([]devMigration, error) {parts := strings.Split(baseName, "__")if len(parts) != 2 {- return nil, fmt.Errorf("invalid migration file name %q", name)+ return nil, errors.Errorf("invalid migration file name %q", name)}buf, err := fs.ReadFile(migrationFS, name)if err != nil {@@ -576,7 +575,7 @@ func getPatchVersions(minorVersion semver.Version, currentVersion semver.VersionbaseName := filepath.Base(name)parts := strings.Split(baseName, "__")if len(parts) != 2 {- return nil, fmt.Errorf("migration filename %q should include '__'", name)+ return nil, errors.Errorf("migration filename %q should include '__'", name)}patch, err := strconv.ParseInt(parts[0], 10, 64)if err != nil {diff --git a/store/pipeline.go b/store/pipeline.goindex 05a2437b48..e1deef6473 100644--- a/store/pipeline.go+++ b/store/pipeline.go@@ -241,7 +241,7 @@ func (s *Store) getPipelineRaw(ctx context.Context, find *api.PipelineFind) (*piif len(pipelineRawList) == 0 {return nil, nil} else if len(pipelineRawList) > 1 {- return nil, &common.Error{Code: common.Conflict, Err: fmt.Errorf("found %d pipelines with filter %+v, expect 1", len(pipelineRawList), find)}+ return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d pipelines with filter %+v, expect 1", len(pipelineRawList), find)}}if err := s.cache.UpsertCache(api.PipelineCache, pipelineRawList[0].ID, pipelineRawList[0]); err != nil {return nil, err@@ -390,7 +390,7 @@ func (*Store) patchPipelineImpl(ctx context.Context, tx *sql.Tx, patch *api.Pipe&pipelineRaw.Status,); err != nil {if err == sql.ErrNoRows {- return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("pipeline ID not found: %d", patch.ID)}+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("pipeline ID not found: %d", patch.ID)}}return nil, FormatError(err)}diff --git a/store/policy.go b/store/policy.goindex 048dff1c9a..5c8517b8da 100644--- a/store/policy.go+++ b/store/policy.go@@ -85,7 +85,7 @@ func (s *Store) DeletePolicy(ctx context.Context, delete *api.PolicyDelete) erro// Validate policy.// Currently we only support PolicyTypeSQLReview type policy to delete by idif delete.Type != api.PolicyTypeSQLReview {- return &common.Error{Code: common.Invalid, Err: fmt.Errorf("invalid policy type")}+ return &common.Error{Code: common.Invalid, Err: errors.Errorf("invalid policy type")}}tx, err := s.db.BeginTx(ctx, nil)@@ -103,11 +103,11 @@ func (s *Store) DeletePolicy(ctx context.Context, delete *api.PolicyDelete) erroreturn errors.Wrapf(err, "failed to list policy with PolicyFind[%+v]", find)}if len(policyRawList) != 1 {- return &common.Error{Code: common.NotFound, Err: fmt.Errorf("failed to found policy with filter %+v, expect 1. ", find)}+ return &common.Error{Code: common.NotFound, Err: errors.Errorf("failed to found policy with filter %+v, expect 1. ", find)}}policyRaw := policyRawList[0]if policyRaw.RowStatus != api.Archived {- return &common.Error{Code: common.Invalid, Err: fmt.Errorf("failed to delete policy with PolicyDelete[%+v], expect 'ARCHIVED' row_status", delete)}+ return &common.Error{Code: common.Invalid, Err: errors.Errorf("failed to delete policy with PolicyDelete[%+v], expect 'ARCHIVED' row_status", delete)}}if err := s.deletePolicyImpl(ctx, tx.PTx, delete); err != nil {@@ -181,7 +181,7 @@ func (s *Store) GetPipelineApprovalPolicy(ctx context.Context, environmentID int// GetNormalSQLReviewPolicy will get the normal SQL review policy for an environment.func (s *Store) GetNormalSQLReviewPolicy(ctx context.Context, find *api.PolicyFind) (*advisor.SQLReviewPolicy, error) {if find.ID != nil && *find.ID == api.DefaultPolicyID {- return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("SQL review policy not found with ID %d", *find.ID)}+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("SQL review policy not found with ID %d", *find.ID)}}pType := api.PolicyTypeSQLReview@@ -191,10 +191,10 @@ func (s *Store) GetNormalSQLReviewPolicy(ctx context.Context, find *api.PolicyFireturn nil, err}if policy.RowStatus == api.Archived {- return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("SQL review policy ID: %d for environment %d is archived", policy.ID, policy.EnvironmentID)}+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("SQL review policy ID: %d for environment %d is archived", policy.ID, policy.EnvironmentID)}}if policy.ID == api.DefaultPolicyID {- return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("SQL review policy ID: %d for environment %d not found", policy.ID, policy.EnvironmentID)}+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("SQL review policy ID: %d for environment %d not found", policy.ID, policy.EnvironmentID)}}return api.UnmarshalSQLReviewPolicy(policy.Payload)}@@ -271,7 +271,7 @@ func (s *Store) getPolicyRaw(ctx context.Context, find *api.PolicyFind) (*policyret.EnvironmentID = *find.EnvironmentID}} else if len(policyRawList) > 1 {- return nil, &common.Error{Code: common.Conflict, Err: fmt.Errorf("found %d policy with filter %+v, expect 1. ", len(policyRawList), find)}+ return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d policy with filter %+v, expect 1. ", len(policyRawList), find)}} else {ret = policyRawList[0]}@@ -386,7 +386,7 @@ func upsertPolicyImpl(ctx context.Context, tx *sql.Tx, upsert *api.PolicyUpsert)}if len(set) == 0 {- return nil, &common.Error{Code: common.Invalid, Err: fmt.Errorf("invalid policy upsert %+v", upsert)}+ return nil, &common.Error{Code: common.Invalid, Err: errors.Errorf("invalid policy upsert %+v", upsert)}}if upsert.Payload == nil || *upsert.Payload == "" {diff --git a/store/principal.go b/store/principal.goindex fd10e5582a..3c9d902ee1 100644--- a/store/principal.go+++ b/store/principal.go@@ -209,7 +209,7 @@ func (s *Store) getPrincipalRaw(ctx context.Context, find *api.PrincipalFind) (*if len(list) == 0 {return nil, nil} else if len(list) > 1 {- return nil, &common.Error{Code: common.Conflict, Err: fmt.Errorf("found %d principals with PrincipalFind[%+v], expect 1", len(list), find)}+ return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d principals with PrincipalFind[%+v], expect 1", len(list), find)}}if err := s.cache.UpsertCache(api.PrincipalCache, list[0].ID, list[0]); err != nil {return nil, err@@ -400,7 +400,7 @@ func patchPrincipalImpl(ctx context.Context, tx *sql.Tx, patch *api.PrincipalPat&principalRaw.PasswordHash,); err != nil {if err == sql.ErrNoRows {- return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("principal ID not found: %d", patch.ID)}+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("principal ID not found: %d", patch.ID)}}return nil, FormatError(err)}diff --git a/store/project.go b/store/project.goindex ef37d3e139..915c6709e3 100644--- a/store/project.go+++ b/store/project.go@@ -254,7 +254,7 @@ func (s *Store) getProjectRaw(ctx context.Context, find *api.ProjectFind) (*projif len(list) == 0 {return nil, nil} else if len(list) > 1 {- return nil, &common.Error{Code: common.Conflict, Err: fmt.Errorf("found %d projects with filter %+v, expect 1", len(list), find)}+ return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d projects with filter %+v, expect 1", len(list), find)}}if err := s.cache.UpsertCache(api.ProjectCache, list[0].ID, list[0]); err != nil {return nil, err@@ -471,7 +471,7 @@ func patchProjectImpl(ctx context.Context, tx *sql.Tx, patch *api.ProjectPatch)&project.RoleProvider,); err != nil {if err == sql.ErrNoRows {- return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("project ID not found: %d", patch.ID)}+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("project ID not found: %d", patch.ID)}}return nil, FormatError(err)}diff --git a/store/project_member.go b/store/project_member.goindex adb5ee8c9d..ca7dcc7d2e 100644--- a/store/project_member.go+++ b/store/project_member.go@@ -248,7 +248,7 @@ func (s *Store) getProjectMemberRaw(ctx context.Context, find *api.ProjectMemberif len(list) == 0 {return nil, nil} else if len(list) > 1 {- return nil, &common.Error{Code: common.Conflict, Err: fmt.Errorf("found %d project members with filter %+v, expect 1", len(list), find)}+ return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d project members with filter %+v, expect 1", len(list), find)}}return list[0], nil}@@ -550,7 +550,7 @@ func patchProjectMemberImpl(ctx context.Context, tx *sql.Tx, patch *api.ProjectM&projectMemberRaw.Payload,); err != nil {if err == sql.ErrNoRows {- return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("project member ID not found: %d", patch.ID)}+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("project member ID not found: %d", patch.ID)}}return nil, FormatError(err)}diff --git a/store/project_webhook.go b/store/project_webhook.goindex 83e056d637..6e4c502a57 100644--- a/store/project_webhook.go+++ b/store/project_webhook.go@@ -212,7 +212,7 @@ func (s *Store) getProjectWebhookRaw(ctx context.Context, find *api.ProjectWebhoif len(list) == 0 {return nil, nil} else if len(list) > 1 {- return nil, &common.Error{Code: common.Conflict, Err: fmt.Errorf("found %d project hooks with filter %+v, expect 1", len(list), find)}+ return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d project hooks with filter %+v, expect 1", len(list), find)}}return list[0], nil}@@ -401,7 +401,7 @@ func patchProjectWebhookImpl(ctx context.Context, tx *sql.Tx, patch *api.Project&txtArray,); err != nil {if err == sql.ErrNoRows {- return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("project hook ID not found: %d", patch.ID)}+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("project hook ID not found: %d", patch.ID)}}return nil, FormatError(err)}diff --git a/store/repository.go b/store/repository.goindex 2b8debbab3..429b217954 100644--- a/store/repository.go+++ b/store/repository.go@@ -181,7 +181,7 @@ func (s *Store) composeRepository(ctx context.Context, raw *repositoryRaw) (*api}// We should always expect VCS to exist when ID isn't the default zero.if repository.VCSID > 0 && vcs == nil {- return nil, fmt.Errorf("VCS not found for ID: %v", repository.VCSID)+ return nil, errors.Errorf("VCS not found for ID: %v", repository.VCSID)}repository.VCS = vcs@@ -247,7 +247,7 @@ func (s *Store) getRepositoryRaw(ctx context.Context, find *api.RepositoryFind)if len(list) == 0 {return nil, nil} else if len(list) > 1 {- return nil, &common.Error{Code: common.Conflict, Err: fmt.Errorf("found %d repositories with filter %+v, expect 1", len(list), find)}+ return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d repositories with filter %+v, expect 1", len(list), find)}}return list[0], nil}@@ -602,7 +602,7 @@ func patchRepositoryImpl(ctx context.Context, tx *sql.Tx, patch *api.RepositoryP&repository.RefreshToken,); err != nil {if err == sql.ErrNoRows {- return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("repository ID not found: %d", patch.ID)}+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("repository ID not found: %d", patch.ID)}}return nil, FormatError(err)}diff --git a/store/setting.go b/store/setting.goindex 1b81b5a8d3..cb5a274be3 100644--- a/store/setting.go+++ b/store/setting.go@@ -3,7 +3,6 @@ package storeimport ("context""database/sql"- "fmt""strings""github.com/bytebase/bytebase/api"@@ -177,7 +176,7 @@ func (s *Store) getSettingRaw(ctx context.Context, find *api.SettingFind) (*settif len(list) == 0 {return nil, nil} else if len(list) > 1 {- return nil, &common.Error{Code: common.Conflict, Err: fmt.Errorf("found %d activities with filter %+v, expect 1. ", len(list), find)}+ return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d activities with filter %+v, expect 1. ", len(list), find)}}return list[0], nil}@@ -315,7 +314,7 @@ func patchSettingImpl(ctx context.Context, tx *sql.Tx, patch *api.SettingPatch)&settingRaw.Description,); err != nil {if err == sql.ErrNoRows {- return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("setting not found: %s", patch.Name)}+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("setting not found: %s", patch.Name)}}return nil, FormatError(err)}diff --git a/store/sheet.go b/store/sheet.goindex b99aeee06d..1f0df7a2f2 100644--- a/store/sheet.go+++ b/store/sheet.go@@ -309,7 +309,7 @@ func (s *Store) getSheetRaw(ctx context.Context, find *api.SheetFind) (*sheetRawif len(list) == 0 {return nil, nil} else if len(list) > 1 {- return nil, &common.Error{Code: common.Conflict, Err: fmt.Errorf("found %d sheet with filter %+v, expect 1. ", len(list), find)}+ return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d sheet with filter %+v, expect 1. ", len(list), find)}}return list[0], nil}@@ -427,7 +427,7 @@ func patchSheetImpl(ctx context.Context, tx *sql.Tx, patch *api.SheetPatch) (*sh&sheetRaw.Payload,); err != nil {if err == sql.ErrNoRows {- return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("sheet ID not found: %d", patch.ID)}+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("sheet ID not found: %d", patch.ID)}}return nil, FormatError(err)}diff --git a/store/sheet_organizer.go b/store/sheet_organizer.goindex 3b0ac071c6..0b65663e7b 100644--- a/store/sheet_organizer.go+++ b/store/sheet_organizer.go@@ -8,6 +8,7 @@ import ("github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common"+ "github.com/pkg/errors")// sheetOrganizerRaw is the store model for SheetOrganizer.@@ -70,7 +71,7 @@ func (s *Store) FindSheetOrganizer(ctx context.Context, find *api.SheetOrganizerif len(sheetOrganizerRawlist) == 0 {return nil, nil} else if len(sheetOrganizerRawlist) > 1 {- return nil, &common.Error{Code: common.Conflict, Err: fmt.Errorf("found %d sheet organizer with filter %+v, expect 1. ", len(sheetOrganizerRawlist), find)}+ return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d sheet organizer with filter %+v, expect 1. ", len(sheetOrganizerRawlist), find)}}sheetOrganizer := sheetOrganizerRawlist[0].toSheetOrganizer()diff --git a/store/table.go b/store/table.goindex 3457ee4f34..e2d5a565c2 100644--- a/store/table.go+++ b/store/table.go@@ -324,7 +324,7 @@ func (s *Store) getTableRaw(ctx context.Context, find *api.TableFind) (*tableRawif len(list) == 0 {return nil, nil} else if len(list) > 1 {- return nil, &common.Error{Code: common.Conflict, Err: fmt.Errorf("found %d tables with filter %+v, expect 1", len(list), find)}+ return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d tables with filter %+v, expect 1", len(list), find)}}return list[0], nil}@@ -434,7 +434,7 @@ func (*Store) patchTableImpl(ctx context.Context, tx *sql.Tx, patch *api.TablePa&tableRaw.Comment,); err != nil {if err == sql.ErrNoRows {- return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("table ID not found: %d", patch.ID)}+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("table ID not found: %d", patch.ID)}}return nil, FormatError(err)}diff --git a/store/task.go b/store/task.goindex 283eab419b..5f7f934eba 100644--- a/store/task.go+++ b/store/task.go@@ -263,7 +263,7 @@ func (s *Store) composeTask(ctx context.Context, raw *taskRaw) (*api.Task, errorreturn nil, err}if database == nil {- return nil, fmt.Errorf("database not found with ID %v", task.DatabaseID)+ return nil, errors.Errorf("database not found with ID %v", task.DatabaseID)}task.Database = database}@@ -328,7 +328,7 @@ func (s *Store) getTaskRawTx(ctx context.Context, tx *sql.Tx, find *api.TaskFindif len(list) == 0 {return nil, nil} else if len(list) > 1 {- return nil, &common.Error{Code: common.Conflict, Err: fmt.Errorf("found %d tasks with filter %+v, expect 1", len(list), find)}+ return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d tasks with filter %+v, expect 1", len(list), find)}}return list[0], nil}@@ -618,7 +618,7 @@ func (*Store) patchTaskImpl(ctx context.Context, tx *sql.Tx, patch *api.TaskPatc&taskRaw.EarliestAllowedTs,); err != nil {if err == sql.ErrNoRows {- return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("task not found with ID %d", patch.ID)}+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("task not found with ID %d", patch.ID)}}return nil, FormatError(err)}@@ -638,7 +638,7 @@ func (s *Store) patchTaskStatusImpl(ctx context.Context, tx *sql.Tx, patch *api.return nil, err}if taskRawObj == nil {- return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("task ID not found: %d", patch.ID)}+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("task ID not found: %d", patch.ID)}}taskRunFind := &api.TaskRunFind{@@ -667,7 +667,7 @@ func (s *Store) patchTaskStatusImpl(ctx context.Context, tx *sql.Tx, patch *api.}} else {if patch.Status == api.TaskRunning {- return nil, fmt.Errorf("task is already running: %v", taskRawObj.Name)+ return nil, errors.Errorf("task is already running: %v", taskRawObj.Name)}taskRunStatusPatch := &api.TaskRunStatusPatch{ID: &taskRunRaw.ID,diff --git a/store/task_check_run.go b/store/task_check_run.goindex 83934c579a..34d1d2dbd5 100644--- a/store/task_check_run.go+++ b/store/task_check_run.go@@ -323,7 +323,7 @@ func (*Store) patchTaskCheckRunStatusImpl(ctx context.Context, tx *sql.Tx, patch&taskCheckRunRaw.Payload,); err != nil {if err == sql.ErrNoRows {- return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("task check run ID not found: %d", *patch.ID)}+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("task check run ID not found: %d", *patch.ID)}}return nil, FormatError(err)}diff --git a/store/task_dag.go b/store/task_dag.goindex ee426a3900..6c166911f4 100644--- a/store/task_dag.go+++ b/store/task_dag.go@@ -3,7 +3,6 @@ package storeimport ("context""database/sql"- "fmt""github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common"@@ -64,7 +63,7 @@ func (s *Store) GetTaskDAGByToTaskID(ctx context.Context, id int) (*api.TaskDAG,return nil, err}if len(taskDAGList) != 1 {- return nil, &common.Error{Code: common.Conflict, Err: fmt.Errorf("found %d tasks with ToTaskID %v, expect 1", len(taskDAGList), id)}+ return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d tasks with ToTaskID %v, expect 1", len(taskDAGList), id)}}return taskDAGList[0], nil}diff --git a/store/task_run.go b/store/task_run.goindex 023f758f94..d419ba5ac0 100644--- a/store/task_run.go+++ b/store/task_run.go@@ -8,6 +8,7 @@ import ("github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common"+ "github.com/pkg/errors")// taskRunRaw is the store model for an TaskRun.@@ -119,7 +120,7 @@ func (s *Store) getTaskRunRawTx(ctx context.Context, tx *sql.Tx, find *api.TaskRif len(taskRunRawList) == 0 {return nil, nil} else if len(taskRunRawList) > 1 {- return nil, &common.Error{Code: common.Conflict, Err: fmt.Errorf("found %d task runs with filter %+v, expect 1", len(taskRunRawList), find)}+ return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d task runs with filter %+v, expect 1", len(taskRunRawList), find)}}return taskRunRawList[0], nil}@@ -176,7 +177,7 @@ func (*Store) patchTaskRunStatusImpl(ctx context.Context, tx *sql.Tx, patch *api&taskRunRaw.Payload,); err != nil {if err == sql.ErrNoRows {- return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("project ID not found: %d", patch.ID)}+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("project ID not found: %d", patch.ID)}}return nil, FormatError(err)}diff --git a/store/vcs.go b/store/vcs.goindex 984d22878c..a5160f25fb 100644--- a/store/vcs.go+++ b/store/vcs.go@@ -198,7 +198,7 @@ func (s *Store) getVCSRaw(ctx context.Context, id int) (*vcsRaw, error) {if len(list) == 0 {return nil, nil} else if len(list) > 1 {- return nil, &common.Error{Code: common.Conflict, Err: fmt.Errorf("found %d VCSs with filter %+v, expect 1", len(list), find)}+ return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d VCSs with filter %+v, expect 1", len(list), find)}}return list[0], nil}@@ -391,7 +391,7 @@ func patchVCSImpl(ctx context.Context, tx *sql.Tx, patch *api.VCSPatch) (*vcsRaw&vcs.Secret,); err != nil {if err == sql.ErrNoRows {- return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("vcs ID not found: %d", patch.ID)}+ return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("vcs ID not found: %d", patch.ID)}}return nil, FormatError(err)}diff --git a/tests/fake/gitlab.go b/tests/fake/gitlab.goindex 4365635a04..0e657ea902 100644--- a/tests/fake/gitlab.go+++ b/tests/fake/gitlab.go@@ -107,7 +107,7 @@ func (gl *GitLab) createProjectHook(c echo.Context) error {}pd, ok := gl.projects[projectID]if !ok {- return fmt.Errorf("gitlab project %q doesn't exist", projectID)+ return errors.Errorf("gitlab project %q doesn't exist", projectID)}pd.webhooks = append(pd.webhooks, webhookCreate)@@ -259,7 +259,7 @@ func (gl *GitLab) createProjectFile(c echo.Context) error {func (gl *GitLab) SendWebhookPush(projectID string, payload []byte) error {pd, ok := gl.projects[projectID]if !ok {- return fmt.Errorf("gitlab project %q doesn't exist", projectID)+ return errors.Errorf("gitlab project %q doesn't exist", projectID)}// Trigger webhooks.@@ -280,7 +280,7 @@ func (gl *GitLab) SendWebhookPush(projectID string, payload []byte) error {}if resp.StatusCode != http.StatusOK {- return fmt.Errorf("http response error code %v body %q", resp.StatusCode, string(body))+ return errors.Errorf("http response error code %v body %q", resp.StatusCode, string(body))}gl.echo.Logger.Infof("SendWebhookPush response body %s\n", body)}@@ -292,7 +292,7 @@ func (gl *GitLab) SendWebhookPush(projectID string, payload []byte) error {func (gl *GitLab) AddFiles(projectID string, files map[string]string) error {pd, ok := gl.projects[projectID]if !ok {- return fmt.Errorf("gitlab project %q doesn't exist", projectID)+ return errors.Errorf("gitlab project %q doesn't exist", projectID)}// Save files@@ -306,7 +306,7 @@ func (gl *GitLab) AddFiles(projectID string, files map[string]string) error {func (gl *GitLab) GetFiles(projectID string, filePaths ...string) (map[string]string, error) {pd, ok := gl.projects[projectID]if !ok {- return nil, fmt.Errorf("gitlab project %q doesn't exist", projectID)+ return nil, errors.Errorf("gitlab project %q doesn't exist", projectID)}// Get filesdiff --git a/tests/tests.go b/tests/tests.goindex c497852727..f6c372f5ac 100644--- a/tests/tests.go+++ b/tests/tests.go@@ -308,7 +308,7 @@ func (ctl *controller) waitForHealthz() error {return nilcase end := <-timer.C:- return fmt.Errorf("cannot wait for healthz in duration: %v", end.Sub(begin).Seconds())+ return errors.Errorf("cannot wait for healthz in duration: %v", end.Sub(begin).Seconds())}}}@@ -347,7 +347,7 @@ func (ctl *controller) Login() error {}}if cookie == "" {- return fmt.Errorf("unable to find access token in the login response headers")+ return errors.Errorf("unable to find access token in the login response headers")}ctl.cookie = cookie@@ -386,7 +386,7 @@ func (ctl *controller) get(shortURL string, params map[string]string) (io.ReadClif err != nil {return nil, errors.Wrap(err, "failed to read http response body")}- return nil, fmt.Errorf("http response error code %v body %q", resp.StatusCode, string(body))+ return nil, errors.Errorf("http response error code %v body %q", resp.StatusCode, string(body))}return resp.Body, nil}@@ -408,7 +408,7 @@ func (ctl *controller) post(shortURL string, body io.Reader) (io.ReadCloser, errif err != nil {return nil, errors.Wrap(err, "failed to read http response body")}- return nil, fmt.Errorf("http response error code %v body %q", resp.StatusCode, string(body))+ return nil, errors.Errorf("http response error code %v body %q", resp.StatusCode, string(body))}return resp.Body, nil}@@ -430,7 +430,7 @@ func (ctl *controller) patch(shortURL string, body io.Reader) (io.ReadCloser, erif err != nil {return nil, errors.Wrap(err, "failed to read http response body")}- return nil, fmt.Errorf("http response error code %v body %q", resp.StatusCode, string(body))+ return nil, errors.Errorf("http response error code %v body %q", resp.StatusCode, string(body))}return resp.Body, nil}@@ -451,7 +451,7 @@ func (ctl *controller) delete(shortURL string, body io.Reader) (io.ReadCloser, eif err != nil {return nil, errors.Wrap(err, "failed to read http response body")}- return nil, fmt.Errorf("http response error code %v body %q", resp.StatusCode, string(body))+ return nil, errors.Errorf("http response error code %v body %q", resp.StatusCode, string(body))}return resp.Body, nil}@@ -471,7 +471,7 @@ func (ctl *controller) getProjects() ([]*api.Project, error) {for _, p := range ps {project, ok := p.(*api.Project)if !ok {- return nil, fmt.Errorf("fail to convert project")+ return nil, errors.Errorf("fail to convert project")}projects = append(projects, project)}@@ -512,7 +512,7 @@ func (ctl *controller) getEnvironments() ([]*api.Environment, error) {for _, p := range ps {environment, ok := p.(*api.Environment)if !ok {- return nil, fmt.Errorf("fail to convert environment")+ return nil, errors.Errorf("fail to convert environment")}environments = append(environments, environment)}@@ -525,7 +525,7 @@ func findEnvironment(envs []*api.Environment, name string) (*api.Environment, erreturn env, nil}}- return nil, fmt.Errorf("unable to find environment %q", name)+ return nil, errors.Errorf("unable to find environment %q", name)}// getDatabases gets the databases.@@ -550,7 +550,7 @@ func (ctl *controller) getDatabases(databaseFind api.DatabaseFind) ([]*api.Databfor _, p := range ps {database, ok := p.(*api.Database)if !ok {- return nil, fmt.Errorf("fail to convert database")+ return nil, errors.Errorf("fail to convert database")}databases = append(databases, database)}@@ -629,7 +629,7 @@ func (ctl *controller) getInstanceMigrationHistory(find db.MigrationHistoryFind)for _, h := range hs {history, ok := h.(*api.MigrationHistory)if !ok {- return nil, fmt.Errorf("fail to convert migration history")+ return nil, errors.Errorf("fail to convert migration history")}histories = append(histories, history)}@@ -695,7 +695,7 @@ func (ctl *controller) getIssues(issueFind api.IssueFind) ([]*api.Issue, error)for _, p := range ps {issue, ok := p.(*api.Issue)if !ok {- return nil, fmt.Errorf("fail to convert issue")+ return nil, errors.Errorf("fail to convert issue")}issues = append(issues, issue)}@@ -760,7 +760,7 @@ func (ctl *controller) patchStageAllTaskStatus(stageAllTaskStatusPatch api.Stagefor _, t := range untypedTasks {task, ok := t.(*api.Task)if !ok {- return nil, fmt.Errorf("fail to convert task")+ return nil, errors.Errorf("fail to convert task")}tasks = append(tasks, task)}@@ -827,7 +827,7 @@ func getNextTaskStatus(issue *api.Issue) (api.TaskStatus, error) {for _, run := range task.TaskRunList {runs = append(runs, fmt.Sprintf("%+v", run))}- return api.TaskFailed, fmt.Errorf("pipeline task %v failed runs: %v", task.ID, strings.Join(runs, ", "))+ return api.TaskFailed, errors.Errorf("pipeline task %v failed runs: %v", task.ID, strings.Join(runs, ", "))}return task.Status, nil}@@ -924,7 +924,7 @@ func (ctl *controller) query(instance *api.Instance, databaseName, query string)return "", errors.Wrap(err, "failed to execute SQL")}if sqlResultSet.Error != "" {- return "", fmt.Errorf("expect SQL result has no error, got %q", sqlResultSet.Error)+ return "", errors.Errorf("expect SQL result has no error, got %q", sqlResultSet.Error)}return sqlResultSet.Data, nil}@@ -1001,14 +1001,14 @@ func (ctl *controller) createDatabase(project *api.Project, instance *api.Instanreturn errors.Wrap(err, "failed to create database creation issue")}if status, _ := getNextTaskStatus(issue); status != api.TaskPendingApproval {- return fmt.Errorf("issue %v pipeline %v is supposed to be pending manual approval", issue.ID, issue.Pipeline.ID)+ return errors.Errorf("issue %v pipeline %v is supposed to be pending manual approval", issue.ID, issue.Pipeline.ID)}status, err := ctl.waitIssuePipeline(issue.ID)if err != nil {return errors.Wrapf(err, "failed to wait for issue %v pipeline %v", issue.ID, issue.Pipeline.ID)}if status != api.TaskDone {- return fmt.Errorf("issue %v pipeline %v is expected to finish with status done, got %v", issue.ID, issue.Pipeline.ID, status)+ return errors.Errorf("issue %v pipeline %v is expected to finish with status done, got %v", issue.ID, issue.Pipeline.ID, status)}issue, err = ctl.patchIssueStatus(api.IssueStatusPatch{ID: issue.ID,@@ -1049,14 +1049,14 @@ func (ctl *controller) cloneDatabaseFromBackup(project *api.Project, instance *areturn errors.Wrap(err, "failed to create database creation issue")}if status, _ := getNextTaskStatus(issue); status != api.TaskPendingApproval {- return fmt.Errorf("issue %v pipeline %v is supposed to be pending manual approval", issue.ID, issue.Pipeline.ID)+ return errors.Errorf("issue %v pipeline %v is supposed to be pending manual approval", issue.ID, issue.Pipeline.ID)}status, err := ctl.waitIssuePipeline(issue.ID)if err != nil {return errors.Wrapf(err, "failed to wait for issue %v pipeline %v", issue.ID, issue.Pipeline.ID)}if status != api.TaskDone {- return fmt.Errorf("issue %v pipeline %v is expected to finish with status done, got %v", issue.ID, issue.Pipeline.ID, status)+ return errors.Errorf("issue %v pipeline %v is expected to finish with status done, got %v", issue.ID, issue.Pipeline.ID, status)}issue, err = ctl.patchIssueStatus(api.IssueStatusPatch{ID: issue.ID,@@ -1103,7 +1103,7 @@ func (ctl *controller) getLabels() ([]*api.LabelKey, error) {for _, lk := range lks {labelKey, ok := lk.(*api.LabelKey)if !ok {- return nil, fmt.Errorf("fail to convert label key")+ return nil, errors.Errorf("fail to convert label key")}labelKeys = append(labelKeys, labelKey)}@@ -1143,7 +1143,7 @@ func (ctl *controller) addLabelValues(key string, values []string) error {}}if labelKey == nil {- return fmt.Errorf("failed to find label with key %q", key)+ return errors.Errorf("failed to find label with key %q", key)}var valueList []stringvalueList = append(valueList, labelKey.ValueList...)@@ -1234,7 +1234,7 @@ func (ctl *controller) listBackups(databaseID int) ([]*api.Backup, error) {for _, p := range ps {backup, ok := p.(*api.Backup)if !ok {- return nil, fmt.Errorf("fail to convert backup")+ return nil, errors.Errorf("fail to convert backup")}backups = append(backups, backup)}@@ -1260,17 +1260,17 @@ func (ctl *controller) waitBackup(databaseID, backupID int) error {}}if backup == nil {- return fmt.Errorf("backup %v for database %v not found", backupID, databaseID)+ return errors.Errorf("backup %v for database %v not found", backupID, databaseID)}switch backup.Status {case api.BackupStatusDone:return nilcase api.BackupStatusFailed:- return fmt.Errorf("backup %v for database %v failed", backupID, databaseID)+ return errors.Errorf("backup %v for database %v failed", backupID, databaseID)}}// Ideally, this should never happen because the ticker will not stop till the backup is finished.- return fmt.Errorf("failed to wait for backup as this condition should never be reached")+ return errors.Errorf("failed to wait for backup as this condition should never be reached")}// createSheet creates a sheet.@@ -1315,7 +1315,7 @@ func (ctl *controller) listSheets(sheetFind api.SheetFind) ([]*api.Sheet, error)for _, p := range ps {sheet, ok := p.(*api.Sheet)if !ok {- return nil, fmt.Errorf("fail to convert sheet")+ return nil, errors.Errorf("fail to convert sheet")}sheets = append(sheets, sheet)}@@ -1424,7 +1424,7 @@ func (ctl *controller) GetSQLReviewResult(id int) ([]api.TaskCheckResult, error)}if status != api.TaskPendingApproval {- return nil, fmt.Errorf("the status of issue %v is not pending approval", id)+ return nil, errors.Errorf("the status of issue %v is not pending approval", id)}result, yes, err := ctl.sqlReviewTaskCheckRunFinished(issue)@@ -1488,7 +1488,7 @@ func setDefaultSQLReviewRulePayload(ruleTp advisor.SQLReviewRuleType) (string, e},})default:- return "", fmt.Errorf("unknown SQL review type for default payload: %s", ruleTp)+ return "", errors.Errorf("unknown SQL review type for default payload: %s", ruleTp)}if err != nil {