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: rework webhook step1 (#11323)
Danny Xu49b130163fd6
diff --git a/backend/api/gitops/webhook.go b/backend/api/gitops/webhook.goindex ca3960bccd..64fa30b345 100644--- a/backend/api/gitops/webhook.go+++ b/backend/api/gitops/webhook.go@@ -12,9 +12,8 @@ import ("log/slog""net/http""net/mail"- "net/url"- "path""path/filepath"+ "regexp""sort""strconv""strings"@@ -22,13 +21,11 @@ import ("github.com/google/uuid""github.com/labstack/echo/v4""github.com/pkg/errors"- "gopkg.in/yaml.v3""github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/log""github.com/bytebase/bytebase/backend/component/activity"api "github.com/bytebase/bytebase/backend/legacyapi"- "github.com/bytebase/bytebase/backend/plugin/advisor""github.com/bytebase/bytebase/backend/plugin/db""github.com/bytebase/bytebase/backend/plugin/vcs""github.com/bytebase/bytebase/backend/store/model"@@ -45,15 +42,10 @@ import ()const (- // sqlReviewDocs is the URL for SQL review doc.- sqlReviewDocs = "https://www.bytebase.com/docs/reference/error-code/advisor"-// issueNameTemplate should be consistent with UI issue names generated from the frontend except for the timestamp.// Because we cannot get the correct timezone of the client here.- // Example: "[db-5] Alter schema: add an email column".- issueNameTemplate = "[%s] %s: %s"- sdlIssueNameTemplate = "[%s] %s"- batchIssueNameTemplate = "%s: %s"+ // Example: "Alter schema: add an email column".+ issueNameTemplate = "%s: %s")func (s *Service) RegisterWebhookRoutes(g *echo.Group) {@@ -799,7 +791,6 @@ func filterFilesByCommitsDiff(type fileInfo struct {item vcs.DistinctFileItemmigrationInfo *db.MigrationInfo- fType fileTyperepoInfo *repoInfo}@@ -820,7 +811,7 @@ func groupFileInfoByRepo(distinctFileList []vcs.DistinctFileItem, repoInfoList [repoID2FileItemList := make(map[int][]fileInfo)for _, item := range distinctFileList {slog.Debug("Processing file", slog.String("file", item.FileName), slog.String("commit", item.Commit.ID))- migrationInfo, fType, repoInfo, err := getFileInfo(item, repoInfoList)+ migrationInfo, repoInfo, err := getFileInfo(item, repoInfoList)if err != nil {slog.Warn("Failed to get file info for the ignored repository file",slog.String("file", item.FileName),@@ -831,98 +822,64 @@ func groupFileInfoByRepo(distinctFileList []vcs.DistinctFileItem, repoInfoList [repoID2FileItemList[repoInfo.repository.UID] = append(repoID2FileItemList[repoInfo.repository.UID], fileInfo{item: item,migrationInfo: migrationInfo,- fType: fType,repoInfo: repoInfo,})}return repoID2FileItemList}-type fileType int--const (- fileTypeUnknown fileType = iota- fileTypeMigration- fileTypeSchema-)-// getFileInfo processes the file item against the candidate list of// repositories and returns the parsed migration information, file change type// and a single matched repository. It returns an error when none or multiple// repositories are matched.-func getFileInfo(fileItem vcs.DistinctFileItem, repoInfoList []*repoInfo) (*db.MigrationInfo, fileType, *repoInfo, error) {+func getFileInfo(fileItem vcs.DistinctFileItem, repoInfoList []*repoInfo) (*db.MigrationInfo, *repoInfo, error) {var migrationInfo *db.MigrationInfo- var fType fileTypevar fileRepositoryList []*repoInfofor _, repoInfo := range repoInfoList {- if !strings.HasPrefix(fileItem.FileName, repoInfo.repository.BaseDirectory) {- slog.Debug("Ignored file outside the base directory",- slog.String("file", fileItem.FileName),- slog.String("base_directory", repoInfo.repository.BaseDirectory),- )+ if filepath.Dir(fileItem.FileName) != repoInfo.repository.BaseDirectory {continue}-- // NOTE: We do not want to use filepath.Join here because we always need "/" as the path separator.- filePathTemplate := path.Join(repoInfo.repository.BaseDirectory, repoInfo.repository.FilePathTemplate)- allowOmitDatabaseName := false- if repoInfo.project.TenantMode == api.TenantModeTenant {- allowOmitDatabaseName = true- // If the committed file is a YAML file, then the user may have opted-in- // advanced mode, we need to alter the FilePathTemplate to match ".yml" instead- // of ".sql".- if fileItem.IsYAML {- filePathTemplate = strings.Replace(filePathTemplate, ".sql", ".yml", 1)- }- }-- mi, err := db.ParseMigrationInfo(fileItem.FileName, filePathTemplate, allowOmitDatabaseName)- if err != nil {- slog.Error("Failed to parse migration file info",- slog.String("project", repoInfo.repository.ProjectResourceID),- slog.String("file", fileItem.FileName),- log.BBError(err),- )+ filename := filepath.Base(fileItem.FileName)+ if filepath.Ext(filename) != ".sql" {continue}- if mi != nil {- if fileItem.IsYAML && mi.Type != db.Data {- return nil, fileTypeUnknown, nil, errors.New("only DML is allowed for YAML files in a tenant project")- }-- migrationInfo = mi- fType = fileTypeMigration- fileRepositoryList = append(fileRepositoryList, repoInfo)+ filename = strings.TrimSuffix(filename, filepath.Ext(filename))+ re := regexp.MustCompile(`^[0-9]+`)+ matches := re.FindAllString(filename, -1)+ if len(matches) == 0 {continue}-- si, err := db.ParseSchemaFileInfo(repoInfo.repository.BaseDirectory, repoInfo.repository.SchemaPathTemplate, fileItem.FileName)- if err != nil {- slog.Debug("Failed to parse schema file info",- slog.String("file", fileItem.FileName),- log.BBError(err),- )- continue+ version := matches[0]+ description := strings.TrimPrefix(filename, version)+ description = strings.TrimLeft(description, "_#")+ migrationType := db.Migrate+ if strings.Contains(description, "dml") || strings.Contains(description, "data") {+ migrationType = db.Data}- if si != nil {- migrationInfo = si- fType = fileTypeSchema- fileRepositoryList = append(fileRepositoryList, repoInfo)- continue+ description = strings.TrimPrefix(description, "ddl")+ description = strings.TrimPrefix(description, "dml")+ description = strings.TrimPrefix(description, "migrate")+ description = strings.TrimPrefix(description, "data")+ description = strings.TrimLeft(description, "_#")+ migrationInfo = &db.MigrationInfo{+ Version: model.Version{Version: version},+ Type: migrationType,+ Description: description,}+ fileRepositoryList = append(fileRepositoryList, repoInfo)}switch len(fileRepositoryList) {case 0:- return nil, fileTypeUnknown, nil, errors.Errorf("file change is not associated with any project")+ return nil, nil, errors.Errorf("file change is not associated with any project")case 1:- return migrationInfo, fType, fileRepositoryList[0], nil+ return migrationInfo, fileRepositoryList[0], nildefault:var projectList []stringfor _, repoInfo := range fileRepositoryList {projectList = append(projectList, repoInfo.project.Title)}- return nil, fileTypeUnknown, nil, errors.Errorf("file change should be associated with exactly one project but found %s", strings.Join(projectList, ", "))+ return nil, nil, errors.Errorf("file change should be associated with exactly one project but found %s", strings.Join(projectList, ", "))}}@@ -933,13 +890,6 @@ func getFileInfo(fileItem vcs.DistinctFileItem, repoInfoList []*repoInfo) (*db.M// along with the creation message to be presented in the UI. An *echo.HTTPError// is returned in case of the error during the process.func (s *Service) processFilesInProject(ctx context.Context, oauthContext *common.OauthContext, pushEvent vcs.PushEvent, repoInfo *repoInfo, fileInfoList []fileInfo) (string, bool, []*store.ActivityMessage, *echo.HTTPError) {- if repoInfo.project.TenantMode == api.TenantModeTenant {- if err := s.licenseService.IsFeatureEnabled(api.FeatureMultiTenancy); err != nil {- return "", false, nil, echo.NewHTTPError(http.StatusForbidden, err.Error())- }- return s.processFilesInBatchProject(ctx, oauthContext, pushEvent, repoInfo, fileInfoList)- }-var migrationDetailList []*migrationDetailvar activityCreateList []*store.ActivityMessagevar createdIssueList []string@@ -947,21 +897,12 @@ func (s *Service) processFilesInProject(ctx context.Context, oauthContext *commocreatorID := s.getIssueCreatorID(ctx, pushEvent.CommitList[0].AuthorEmail)for _, fileInfo := range fileInfoList {- if fileInfo.fType == fileTypeSchema {- slog.Debug("Ignored schema file for non-SDL project", slog.String("fileName", fileInfo.item.FileName), slog.String("type", string(fileInfo.item.ItemType)))- } else { // fileInfo.fType == fileTypeMigration- // This is a migration-based DDL or DML file and we would allow it for both DDL and SDL schema change type project.- // For DDL schema change type project, this is expected.- // For SDL schema change type project, we allow it because:- // 1) DML is always migration-based.- // 2) We may have a limitation in SDL implementation.- // 3) User just wants to break the glass.- migrationDetailListForFile, activityCreateListForFile := s.prepareIssueFromFile(ctx, oauthContext, repoInfo, pushEvent, fileInfo)- activityCreateList = append(activityCreateList, activityCreateListForFile...)- migrationDetailList = append(migrationDetailList, migrationDetailListForFile...)- if len(migrationDetailListForFile) != 0 {- fileNameList = append(fileNameList, strings.TrimPrefix(fileInfo.item.FileName, repoInfo.repository.BaseDirectory+"/"))- }+ // This is a migration-based DDL or DML file.+ migrationDetailListForFile, activityCreateListForFile := s.prepareIssueFromFile(ctx, oauthContext, repoInfo, pushEvent, fileInfo)+ activityCreateList = append(activityCreateList, activityCreateListForFile...)+ migrationDetailList = append(migrationDetailList, migrationDetailListForFile...)+ if len(migrationDetailListForFile) != 0 {+ fileNameList = append(fileNameList, strings.TrimPrefix(fileInfo.item.FileName, repoInfo.repository.BaseDirectory+"/"))}}@@ -977,10 +918,8 @@ func (s *Service) processFilesInProject(ctx context.Context, oauthContext *commobreak}}- // The files are grouped by database names before calling this function, so they have the same database name here.- databaseName := fileInfoList[0].migrationInfo.Databasedescription := strings.ReplaceAll(fileInfoList[0].migrationInfo.Description, "_", " ")- issueName := fmt.Sprintf(issueNameTemplate, databaseName, migrateType, description)+ issueName := fmt.Sprintf(issueNameTemplate, migrateType, description)issueDescription := fmt.Sprintf("By VCS files:\n\n%s\n", strings.Join(fileNameList, "\n"))if err := s.createIssueFromMigrationDetailsV2(ctx, repoInfo.project, issueName, issueDescription, pushEvent, creatorID, migrationDetailList); err != nil {return "", len(createdIssueList) != 0, activityCreateList, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to create issue %s, error %v", issueName, err)).SetInternal(err)@@ -990,39 +929,6 @@ func (s *Service) processFilesInProject(ctx context.Context, oauthContext *commoreturn fmt.Sprintf("Created issue %q from push event", strings.Join(createdIssueList, ",")), true, activityCreateList, nil}-// processFilesInBatchProject creates issues for a batch project.-func (s *Service) processFilesInBatchProject(ctx context.Context, oauthContext *common.OauthContext, pushEvent vcs.PushEvent, repoInfo *repoInfo, fileInfoList []fileInfo) (string, bool, []*store.ActivityMessage, *echo.HTTPError) {- var activityCreateList []*store.ActivityMessage- var createdIssueList []string-- creatorID := s.getIssueCreatorID(ctx, pushEvent.CommitList[0].AuthorEmail)- for _, fileInfo := range fileInfoList {- if fileInfo.fType == fileTypeSchema {- slog.Debug("Ignored schema file for non-SDL project", slog.String("fileName", fileInfo.item.FileName), slog.String("type", string(fileInfo.item.ItemType)))- } else { // fileInfo.fType == fileTypeMigration- migrationDetailListForFile, activityCreateListForFile := s.prepareIssueFromFile(ctx, oauthContext, repoInfo, pushEvent, fileInfo)- if len(migrationDetailListForFile) != 1 {- slog.Error("Unexpected number of file number")- }- migrationDetail := migrationDetailListForFile[0]- activityCreateList = append(activityCreateList, activityCreateListForFile...)- migrateType := "Change data"- if migrationDetail.migrationType == db.Migrate {- migrateType = "Alter schema"- }- description := strings.ReplaceAll(fileInfoList[0].migrationInfo.Description, "_", " ")- issueName := fmt.Sprintf(batchIssueNameTemplate, migrateType, description)- issueDescription := fmt.Sprintf("By VCS file: %s\n", fileInfo.item.FileName)- if err := s.createIssueFromMigrationDetailsV2(ctx, repoInfo.project, issueName, issueDescription, pushEvent, creatorID, migrationDetailListForFile); err != nil {- return "", len(createdIssueList) != 0, activityCreateList, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to create issue %s, error %v", issueName, err)).SetInternal(err)- }- createdIssueList = append(createdIssueList, issueName)- }- }-- return fmt.Sprintf("Created issue %q from push event", strings.Join(createdIssueList, ",")), true, activityCreateList, nil-}-func sortFilesBySchemaVersion(fileInfoList []fileInfo) []fileInfo {var ret []fileInforet = append(ret, fileInfoList...)@@ -1050,77 +956,56 @@ func (s *Service) createIssueFromMigrationDetailsV2(ctx context.Context, project}var steps []*v1pb.Plan_Step- if len(migrationDetailList) == 1 && migrationDetailList[0].databaseID == 0 {- migrationDetail := migrationDetailList[0]- changeType := getChangeType(migrationDetail.migrationType)- steps = []*v1pb.Plan_Step{- {- Specs: []*v1pb.Plan_Spec{- {- Id: uuid.NewString(),- Config: &v1pb.Plan_Spec_ChangeDatabaseConfig{- ChangeDatabaseConfig: &v1pb.Plan_ChangeDatabaseConfig{- Type: changeType,- Target: fmt.Sprintf("projects/%s/deploymentConfigs/default", project.ResourceID),- Sheet: fmt.Sprintf("projects/%s/sheets/%d", project.ResourceID, migrationDetail.sheetID),- SchemaVersion: migrationDetail.schemaVersion.Version,- },- },- },- },- },++ environments, err := s.store.ListEnvironmentV2(ctx, &store.FindEnvironmentMessage{})+ if err != nil {+ return err+ }+ orderIndex := make(map[int32]int)+ for i, environment := range environments {+ orderIndex[environment.Order] = i+ }+ allSteps := make([]*v1pb.Plan_Step, len(environments))+ for _, migrationDetail := range migrationDetailList {+ if migrationDetail.databaseID == 0 {+ // TODO(d): should never reach this.+ return errors.Errorf("tenant database is not supported yet")}- } else {- environments, err := s.store.ListEnvironmentV2(ctx, &store.FindEnvironmentMessage{})+ database, err := s.store.GetDatabaseV2(ctx, &store.FindDatabaseMessage{UID: &migrationDetail.databaseID})if err != nil {return err}- orderIndex := make(map[int32]int)- for i, environment := range environments {- orderIndex[environment.Order] = i+ if database == nil {+ return errors.Errorf("database %d not found", migrationDetail.databaseID)+ }+ environment, err := s.store.GetEnvironmentV2(ctx, &store.FindEnvironmentMessage{ResourceID: &database.EffectiveEnvironmentID})+ if err != nil {+ return err+ }+ if environment == nil {+ return errors.Errorf("environment %q not found", database.EffectiveEnvironmentID)}- allSteps := make([]*v1pb.Plan_Step, len(environments))- for _, migrationDetail := range migrationDetailList {- if migrationDetail.databaseID == 0 {- // TODO(d): should never reach this.- return errors.Errorf("tenant database is not supported yet")- }- database, err := s.store.GetDatabaseV2(ctx, &store.FindDatabaseMessage{UID: &migrationDetail.databaseID})- if err != nil {- return err- }- if database == nil {- return errors.Errorf("database %d not found", migrationDetail.databaseID)- }- environment, err := s.store.GetEnvironmentV2(ctx, &store.FindEnvironmentMessage{ResourceID: &database.EffectiveEnvironmentID})- if err != nil {- return err- }- if environment == nil {- return errors.Errorf("environment %q not found", database.EffectiveEnvironmentID)- }- step := allSteps[orderIndex[environment.Order]]- if step == nil {- allSteps[orderIndex[environment.Order]] = &v1pb.Plan_Step{}- step = allSteps[orderIndex[environment.Order]]- }- step.Specs = append(step.Specs, &v1pb.Plan_Spec{- Id: uuid.NewString(),- Config: &v1pb.Plan_Spec_ChangeDatabaseConfig{- ChangeDatabaseConfig: &v1pb.Plan_ChangeDatabaseConfig{- Type: getChangeType(migrationDetail.migrationType),- Target: common.FormatDatabase(database.InstanceID, database.DatabaseName),- Sheet: fmt.Sprintf("projects/%s/sheets/%d", project.ResourceID, migrationDetail.sheetID),- SchemaVersion: migrationDetail.schemaVersion.Version,- },- },- })+ step := allSteps[orderIndex[environment.Order]]+ if step == nil {+ allSteps[orderIndex[environment.Order]] = &v1pb.Plan_Step{}+ step = allSteps[orderIndex[environment.Order]]}- for _, step := range allSteps {- if step != nil && len(step.Specs) > 0 {- steps = append(steps, step)- }+ step.Specs = append(step.Specs, &v1pb.Plan_Spec{+ Id: uuid.NewString(),+ Config: &v1pb.Plan_Spec_ChangeDatabaseConfig{+ ChangeDatabaseConfig: &v1pb.Plan_ChangeDatabaseConfig{+ Type: getChangeType(migrationDetail.migrationType),+ Target: common.FormatDatabase(database.InstanceID, database.DatabaseName),+ Sheet: fmt.Sprintf("projects/%s/sheets/%d", project.ResourceID, migrationDetail.sheetID),+ SchemaVersion: migrationDetail.schemaVersion.Version,+ },+ },+ })+ }+ for _, step := range allSteps {+ if step != nil && len(step.Specs) > 0 {+ steps = append(steps, step)}}childCtx := context.WithValue(ctx, common.PrincipalIDContextKey, creatorID)@@ -1221,10 +1106,7 @@ func (s *Service) getIssueCreatorID(ctx context.Context, email string) int {return creatorID}-// findProjectDatabases finds the list of databases with given name in the-// project. If the environmentResourceID is not empty, it will be used as a filter condition-// for the result list.-func (s *Service) findProjectDatabases(ctx context.Context, projectID int, dbName, environmentResourceID string) ([]*store.DatabaseMessage, error) {+func (s *Service) findProjectDatabases(ctx context.Context, projectID int) ([]*store.DatabaseMessage, error) {// Retrieve the current schema from the databaseproject, err := s.store.GetProjectV2(ctx, &store.FindProjectMessage{UID: &projectID})if err != nil {@@ -1236,67 +1118,15 @@ func (s *Service) findProjectDatabases(ctx context.Context, projectID int, dbNam// The database name for PostgreSQL, Oracle, Snowflake and some databases are case sensitive.// But the database name for MySQL, TiDB and other databases are case insensitive.// So we should find databases by case-insensitive and double-check for case sensitive database engines.- caseInsensitiveDatabases, err := s.store.ListDatabases(ctx,+ databases, err := s.store.ListDatabases(ctx,&store.FindDatabaseMessage{- ProjectID: &project.ResourceID,- DatabaseName: &dbName,- IgnoreCaseSensitive: true,+ ProjectID: &project.ResourceID,},)if err != nil {return nil, errors.Wrap(err, "find database")}- var foundDatabases []*store.DatabaseMessage- for _, database := range caseInsensitiveDatabases {- database := database- instance, err := s.store.GetInstanceV2(ctx, &store.FindInstanceMessage{ResourceID: &database.InstanceID})- if err != nil {- return nil, errors.Wrap(err, "find instance")- }- if store.IgnoreDatabaseAndTableCaseSensitive(instance) || database.DatabaseName == dbName {- foundDatabases = append(foundDatabases, database)- }- }- if len(foundDatabases) == 0 {- return nil, errors.Errorf("project %d does not have database %q", projectID, dbName)- }-- // We support 3 patterns on how to organize the schema files.- // Pattern 1: The database name is the same across all environments. Each environment will have its own directory, so the- // schema file looks like "dev/v1##db1", "staging/v1##db1".- //- // Pattern 2: Like 1, the database name is the same across all environments. All environment shares the same schema file,- // say v1##db1, when a new file is added like v2##db1##add_column, we will create a multi stage pipeline where- // each stage corresponds to an environment.- //- // Pattern 3: The database name is different among different environments. In such case, the database name alone is enough- // to identify ambiguity.-- // Further filter by environment name if applicable.- var filteredDatabases []*store.DatabaseMessage- if environmentResourceID != "" {- for _, database := range foundDatabases {- // Environment resource ID comparison is case-sensitive.- if database.EffectiveEnvironmentID == environmentResourceID {- filteredDatabases = append(filteredDatabases, database)- }- }- if len(filteredDatabases) == 0 {- return nil, errors.Errorf("project %d does not have database %q with environment id %q", projectID, dbName, environmentResourceID)- }- } else {- filteredDatabases = foundDatabases- }-- // In case there are databases with identical name in a project for the same environment.- marked := make(map[string]bool)- for _, database := range filteredDatabases {- if _, ok := marked[database.EffectiveEnvironmentID]; ok {- return nil, errors.Errorf("project %d has multiple databases %q for environment %q", projectID, dbName, environmentResourceID)- }- marked[database.EffectiveEnvironmentID] = true- }- return filteredDatabases, nil+ return databases, nil}// getIgnoredFileActivityCreate get a warning project activityCreate for the ignored file with given error.@@ -1389,85 +1219,8 @@ func (s *Service) prepareIssueFromFile(PushEvent: utils.ConvertVcsPushEvent(&pushEvent),},}- if repoInfo.project.TenantMode == api.TenantModeTenant {- // A non-YAML file means the whole file content is the SQL statement- if !fileInfo.item.IsYAML {- sheet, err := s.store.CreateSheet(ctx, &store.SheetMessage{- CreatorID: api.SystemBotID,- ProjectUID: repoInfo.project.UID,- Title: fileInfo.item.FileName,- Statement: content,- Payload: sheetPayload,- })- if err != nil {- activityCreate := getIgnoredFileActivityCreate(repoInfo.project, pushEvent, fileInfo.item.FileName, errors.Wrap(err, "Failed to create a sheet"))- return nil, []*store.ActivityMessage{activityCreate}- }- return []*migrationDetail{- {- migrationType: fileInfo.migrationInfo.Type,- sheetID: sheet.UID,- schemaVersion: model.Version{Version: fmt.Sprintf("%s-%s", fileInfo.migrationInfo.Version.Version, fileInfo.migrationInfo.Type.GetVersionTypeSuffix())},- },- }, nil- }-- var migrationFile MigrationFileYAML- err = yaml.Unmarshal([]byte(content), &migrationFile)- if err != nil {- return nil, []*store.ActivityMessage{- getIgnoredFileActivityCreate(- repoInfo.project,- pushEvent,- fileInfo.item.FileName,- errors.Wrap(err, "Failed to parse file content as YAML"),- ),- }- }-- sheet, err := s.store.CreateSheet(ctx, &store.SheetMessage{- CreatorID: api.SystemBotID,- ProjectUID: repoInfo.project.UID,- Title: fileInfo.item.FileName,- Statement: migrationFile.Statement,- Payload: sheetPayload,- })- if err != nil {- activityCreate := getIgnoredFileActivityCreate(repoInfo.project, pushEvent, fileInfo.item.FileName, errors.Wrap(err, "Failed to create a sheet"))- return nil, []*store.ActivityMessage{activityCreate}- }-- var migrationDetailList []*migrationDetail- for _, database := range migrationFile.Databases {- dbList, err := s.findProjectDatabases(ctx, repoInfo.project.UID, database.Name, "")- if err != nil {- return nil, []*store.ActivityMessage{- getIgnoredFileActivityCreate(- repoInfo.project,- pushEvent,- fileInfo.item.FileName,- errors.Wrapf(err, "Failed to find project database %q", database.Name),- ),- }- }-- for _, db := range dbList {- migrationDetailList = append(migrationDetailList,- &migrationDetail{- migrationType: fileInfo.migrationInfo.Type,- databaseID: db.UID,- sheetID: sheet.UID,- schemaVersion: model.Version{Version: fmt.Sprintf("%s-%s", fileInfo.migrationInfo.Version.Version, fileInfo.migrationInfo.Type.GetVersionTypeSuffix())},- },- )- }- }- return migrationDetailList, nil- }-- // TODO(dragonly): handle modified file for tenant mode.- databases, err := s.findProjectDatabases(ctx, repoInfo.project.UID, fileInfo.migrationInfo.Database, fileInfo.migrationInfo.Environment)+ databases, err := s.findProjectDatabases(ctx, repoInfo.project.UID)if err != nil {activityCreate := getIgnoredFileActivityCreate(repoInfo.project, pushEvent, fileInfo.item.FileName, errors.Wrap(err, "Failed to find project databases"))return nil, []*store.ActivityMessage{activityCreate}@@ -1659,155 +1412,6 @@ func patchTask(ctx context.Context, stores *store.Store, activityManager *activireturn nil}-// convertSQLAdviceToGitLabCIResult will convert SQL advice map to GitLab test output format.-// GitLab test report: https://docs.gitlab.com/ee/ci/testing/unit_test_reports.html-// junit XML format: https://llg.cubic.org/docs/junit/-func convertSQLAdviceToGitLabCIResult(adviceMap map[string][]advisor.Advice) *api.VCSSQLReviewResult {- testsuiteList := []string{}- status := advisor.Success-- fileList := getSQLAdviceFileList(adviceMap)- for _, filePath := range fileList {- adviceList := adviceMap[filePath]- testcaseList := []string{}- pathes := strings.Split(filePath, "/")- filename := pathes[len(pathes)-1]-- errorCount := 0- failureCount := 0- for _, advice := range adviceList {- if advice.Code == 0 {- continue- }-- line := advice.Line- if line <= 0 {- line = 1- }-- if advice.Status == advisor.Error {- status = advice.Status- errorCount++- } else if advice.Status == advisor.Warn {- failureCount++- if status != advisor.Error {- status = advice.Status- }- }-- content := fmt.Sprintf("Error: %s.\nPlease check the docs at %s#%d",- advice.Content,- sqlReviewDocs,- advice.Code,- )-- testcase := fmt.Sprintf(- "<testcase name=\"%s\" classname=\"%s\" file=\"%s#L%d\">\n<failure>\n%s\n</failure>\n</testcase>",- fmt.Sprintf("[%s] %s#L%d: %s", advice.Status, filename, line, advice.Title),- filePath,- filePath,- line,- content,- )-- testcaseList = append(testcaseList, testcase)- }-- if len(testcaseList) > 0 {- testsuiteList = append(- testsuiteList,- fmt.Sprintf("<testsuite errors=\"%d\" failures=\"%d\" tests=\"%d\" name=\"%s\">\n%s\n</testsuite>", errorCount, failureCount, len(adviceList), filePath, strings.Join(testcaseList, "\n")),- )- }- }-- return &api.VCSSQLReviewResult{- Status: status,- Content: []string{- fmt.Sprintf(- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<testsuites name=\"SQL Review\">\n%s\n</testsuites>",- strings.Join(testsuiteList, "\n"),- ),- },- }-}--// convertSQLAdviceToGitHubActionResult will convert SQL advice map to GitHub action output format.-// GitHub action output message: https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions-func convertSQLAdviceToGitHubActionResult(adviceMap map[string][]advisor.Advice) *api.VCSSQLReviewResult {- messageList := []string{}- status := advisor.Success-- fileList := getSQLAdviceFileList(adviceMap)- for _, filePath := range fileList {- adviceList := adviceMap[filePath]- for _, advice := range adviceList {- if advice.Code == 0 || advice.Status == advisor.Success {- continue- }-- line := advice.Line- if line <= 0 {- line = 1- }-- prefix := ""- if advice.Status == advisor.Error {- prefix = "error"- status = advice.Status- } else {- prefix = "warning"- if status != advisor.Error {- status = advice.Status- }- }-- msg := fmt.Sprintf(- "::%s file=%s,line=%d,col=1,endColumn=2,title=%s (%d)::%s\nDoc: %s#%d",- prefix,- filePath,- line,- advice.Title,- advice.Code,- advice.Content,- sqlReviewDocs,- advice.Code,- )- // To indent the output message in action- messageList = append(messageList, strings.ReplaceAll(msg, "\n", "%0A"))- }- }- return &api.VCSSQLReviewResult{- Status: status,- Content: messageList,- }-}--func getSQLAdviceFileList(adviceMap map[string][]advisor.Advice) []string {- fileList := []string{}- fileToErrorCount := map[string]int{}- for filePath, adviceList := range adviceMap {- fileList = append(fileList, filePath)-- errorCount := 0- for _, advice := range adviceList {- if advice.Status == advisor.Error {- errorCount++- }- }- fileToErrorCount[filePath] = errorCount- }- sort.Strings(fileList)- sort.Slice(fileList, func(i int, j int) bool {- if fileToErrorCount[fileList[i]] == fileToErrorCount[fileList[j]] {- return i < j- }- return fileToErrorCount[fileList[i]] > fileToErrorCount[fileList[j]]- })-- return fileList-}-func filterAzureBytebaseCommit(list []azure.ServiceHookCodePushEventResourceCommit) []azure.ServiceHookCodePushEventResourceCommit {var result []azure.ServiceHookCodePushEventResourceCommitfor _, commit := range list {@@ -1852,21 +1456,3 @@ func filterBitbucketBytebaseCommit(list []bitbucket.WebhookCommit) []bitbucket.W}return result}--// extractDBTypeFromJDBCConnectionString will extract the DB type from JDBC connection string. Only support MySQL and Postgres for now.-// It will return UnknownType if the DB type is not supported, and returns error if cannot parse the JDBC connection string.-func extractDBTypeFromJDBCConnectionString(jdbcURL string) (storepb.Engine, error) {- trimmed := strings.TrimPrefix(strings.TrimSpace(jdbcURL), "jdbc:")- u, err := url.Parse(trimmed)- if err != nil {- return storepb.Engine_ENGINE_UNSPECIFIED, err- }-- switch {- case strings.HasPrefix(u.Scheme, "mysql"):- return storepb.Engine_MYSQL, nil- case strings.HasPrefix(u.Scheme, "postgresql"):- return storepb.Engine_POSTGRES, nil- }- return storepb.Engine_ENGINE_UNSPECIFIED, nil-}diff --git a/backend/api/gitops/webhook_test.go b/backend/api/gitops/webhook_test.goindex 4879a56d4c..d601ddd0de 100644--- a/backend/api/gitops/webhook_test.go+++ b/backend/api/gitops/webhook_test.go@@ -4,15 +4,6 @@ import ("testing""github.com/stretchr/testify/assert"- "github.com/stretchr/testify/require"-- api "github.com/bytebase/bytebase/backend/legacyapi"- "github.com/bytebase/bytebase/backend/plugin/advisor"- "github.com/bytebase/bytebase/backend/plugin/db"- "github.com/bytebase/bytebase/backend/plugin/vcs"- "github.com/bytebase/bytebase/backend/store"- "github.com/bytebase/bytebase/backend/store/model"- storepb "github.com/bytebase/bytebase/proto/generated-go/store")// TODO(d): fix the double underscore "__".@@ -87,306 +78,3 @@ func TestParseBranchNameFromGitHubRefs(t *testing.T) {}}}--var mockSQLAdviceMap = map[string][]advisor.Advice{- "file1.sql": {- {- Status: advisor.Success,- Code: advisor.Ok,- Title: "OK",- Content: "",- },- {- Status: advisor.Warn,- Code: advisor.ColumnCannotNull,- Title: "column.no-null",- Content: `Column "id" in "public"."book" cannot have NULL value`,- Line: 1,- },- {- Status: advisor.Error,- Code: advisor.NamingIndexConventionMismatch,- Title: "naming.index.idx",- Content: "Index in table \"tech_book\" mismatches the naming convention, expect \"^$|^idx_tech_book_id_name$\" but found \"tech_book_id_name\"",- Line: 2,- },- },- "file2.sql": {- {- Status: advisor.Warn,- Code: advisor.NamingTableConventionMismatch,- Title: "naming.table",- Content: "\"techBook\" mismatches table naming convention, naming format should be \"^[a-z]+(_[a-z]+)*$\"",- Line: 1,- },- {- Status: advisor.Success,- Code: advisor.Ok,- Title: "OK",- Content: "",- },- {- Status: advisor.Error,- Code: advisor.NamingUKConventionMismatch,- Title: "naming.index.uk",- Content: "Unique key in table \"tech_book\" mismatches the naming convention, expect \"^$|^uk_tech_book_id_name$\" but found \"tech_book_id_name\"",- Line: 4,- },- },-}--func TestVCSSQLReview_ConvertSQLAdviceToGitLabCIResult(t *testing.T) {- expect :=- `<?xml version="1.0" encoding="UTF-8"?>-<testsuites name="SQL Review">-<testsuite errors="1" failures="1" tests="3" name="file1.sql">-<testcase name="[WARN] file1.sql#L1: column.no-null" classname="file1.sql" file="file1.sql#L1">-<failure>-Error: Column "id" in "public"."book" cannot have NULL value.-Please check the docs at https://www.bytebase.com/docs/reference/error-code/advisor#402-</failure>-</testcase>-<testcase name="[ERROR] file1.sql#L2: naming.index.idx" classname="file1.sql" file="file1.sql#L2">-<failure>-Error: Index in table "tech_book" mismatches the naming convention, expect "^$|^idx_tech_book_id_name$" but found "tech_book_id_name".-Please check the docs at https://www.bytebase.com/docs/reference/error-code/advisor#303-</failure>-</testcase>-</testsuite>-<testsuite errors="1" failures="1" tests="3" name="file2.sql">-<testcase name="[WARN] file2.sql#L1: naming.table" classname="file2.sql" file="file2.sql#L1">-<failure>-Error: "techBook" mismatches table naming convention, naming format should be "^[a-z]+(_[a-z]+)*$".-Please check the docs at https://www.bytebase.com/docs/reference/error-code/advisor#301-</failure>-</testcase>-<testcase name="[ERROR] file2.sql#L4: naming.index.uk" classname="file2.sql" file="file2.sql#L4">-<failure>-Error: Unique key in table "tech_book" mismatches the naming convention, expect "^$|^uk_tech_book_id_name$" but found "tech_book_id_name".-Please check the docs at https://www.bytebase.com/docs/reference/error-code/advisor#304-</failure>-</testcase>-</testsuite>-</testsuites>`- res := convertSQLAdviceToGitLabCIResult(mockSQLAdviceMap)- assert.Equal(t, advisor.Error, res.Status)- assert.Equal(t, 1, len(res.Content))- assert.Equal(t, expect, res.Content[0])-}--func TestVCSSQLReview_ConvertSQLAdviceToGitHubActionResult(t *testing.T) {- expect := []string{- "::warning file=file1.sql,line=1,col=1,endColumn=2,title=column.no-null (402)::Column \"id\" in \"public\".\"book\" cannot have NULL value%0ADoc: https://www.bytebase.com/docs/reference/error-code/advisor#402",- "::error file=file1.sql,line=2,col=1,endColumn=2,title=naming.index.idx (303)::Index in table \"tech_book\" mismatches the naming convention, expect \"^$|^idx_tech_book_id_name$\" but found \"tech_book_id_name\"%0ADoc: https://www.bytebase.com/docs/reference/error-code/advisor#303",- "::warning file=file2.sql,line=1,col=1,endColumn=2,title=naming.table (301)::\"techBook\" mismatches table naming convention, naming format should be \"^[a-z]+(_[a-z]+)*$\"%0ADoc: https://www.bytebase.com/docs/reference/error-code/advisor#301",- "::error file=file2.sql,line=4,col=1,endColumn=2,title=naming.index.uk (304)::Unique key in table \"tech_book\" mismatches the naming convention, expect \"^$|^uk_tech_book_id_name$\" but found \"tech_book_id_name\"%0ADoc: https://www.bytebase.com/docs/reference/error-code/advisor#304",- }- res := convertSQLAdviceToGitHubActionResult(mockSQLAdviceMap)- assert.Equal(t, advisor.Error, res.Status)- assert.Equal(t, 4, len(res.Content))- assert.Equal(t, expect, res.Content)-}--func TestGetFileInfo(t *testing.T) {- t.Run("a SQL format DDL", func(t *testing.T) {- mi, fileType, repoInfo, err := getFileInfo(- vcs.DistinctFileItem{- FileName: "db##0001##migrate.sql",- ItemType: vcs.FileItemTypeAdded,- },- []*repoInfo{- {- repository: &store.RepositoryMessage{- UID: 1,- FilePathTemplate: "{{DB_NAME}}##{{VERSION}}##{{TYPE}}.sql",- },- project: &store.ProjectMessage{},- vcs: &store.VCSProviderMessage{},- },- },- )- require.NoError(t, err)- assert.Equal(t, 1, repoInfo.repository.UID)- assert.Equal(t, fileTypeMigration, fileType)-- want := &db.MigrationInfo{- Version: model.Version{Version: "0001"},- Namespace: "db",- Database: "db",- Source: db.VCS,- Type: db.Migrate,- Description: "Create db schema migration",- }- assert.Equal(t, want, mi)- })-- t.Run("a SQL format DML", func(t *testing.T) {- mi, fileType, repoInfo, err := getFileInfo(- vcs.DistinctFileItem{- FileName: "db##0001##data.sql",- ItemType: vcs.FileItemTypeAdded,- },- []*repoInfo{- {- repository: &store.RepositoryMessage{- UID: 1,- FilePathTemplate: "{{DB_NAME}}##{{VERSION}}##{{TYPE}}.sql",- },- project: &store.ProjectMessage{},- vcs: &store.VCSProviderMessage{},- },- },- )- require.NoError(t, err)- assert.Equal(t, 1, repoInfo.repository.UID)- assert.Equal(t, fileTypeMigration, fileType)-- want := &db.MigrationInfo{- Version: model.Version{Version: "0001"},- Namespace: "db",- Database: "db",- Source: db.VCS,- Type: db.Data,- Description: "Create db data change",- }- assert.Equal(t, want, mi)- })-- t.Run("a YAML format DML in a tenant project", func(t *testing.T) {- mi, fileType, repoInfo, err := getFileInfo(- vcs.DistinctFileItem{- FileName: "db##0001##data.yml",- ItemType: vcs.FileItemTypeAdded,- IsYAML: true,- },- []*repoInfo{- {- repository: &store.RepositoryMessage{- UID: 1,- FilePathTemplate: "{{DB_NAME}}##{{VERSION}}##{{TYPE}}.sql",- },- project: &store.ProjectMessage{- TenantMode: api.TenantModeTenant,- },- vcs: &store.VCSProviderMessage{},- },- },- )- require.NoError(t, err)- assert.Equal(t, 1, repoInfo.repository.UID)- assert.Equal(t, fileTypeMigration, fileType)-- want := &db.MigrationInfo{- Version: model.Version{Version: "0001"},- Namespace: "db",- Database: "db",- Source: db.VCS,- Type: db.Data,- Description: "Create db data change",- }- assert.Equal(t, want, mi)- })-- t.Run("a YAML format DDL is not allowed in a tenant project", func(t *testing.T) {- _, _, _, err := getFileInfo(- vcs.DistinctFileItem{- FileName: "db##0001##migrate.yml",- ItemType: vcs.FileItemTypeAdded,- IsYAML: true,- },- []*repoInfo{- {- repository: &store.RepositoryMessage{- UID: 1,- FilePathTemplate: "{{DB_NAME}}##{{VERSION}}##{{TYPE}}.sql",- },- project: &store.ProjectMessage{- TenantMode: api.TenantModeTenant,- },- vcs: &store.VCSProviderMessage{},- },- },- )- require.EqualError(t, err, "only DML is allowed for YAML files in a tenant project")- })-- t.Run("no matching repository", func(t *testing.T) {- _, _, _, err := getFileInfo(- vcs.DistinctFileItem{- FileName: "db##0001##migrate.sql",- ItemType: vcs.FileItemTypeAdded,- },- []*repoInfo{- {- repository: &store.RepositoryMessage{- UID: 1,- BaseDirectory: "bytebase",- FilePathTemplate: "{{DB_NAME}}##{{VERSION}}##{{TYPE}}.sql",- },- project: &store.ProjectMessage{},- vcs: &store.VCSProviderMessage{},- },- },- )- require.EqualError(t, err, "file change is not associated with any project")- })-- t.Run("matching multiple repositories", func(t *testing.T) {- _, _, _, err := getFileInfo(- vcs.DistinctFileItem{- FileName: "db##0001##migrate.sql",- ItemType: vcs.FileItemTypeAdded,- },- []*repoInfo{- {- repository: &store.RepositoryMessage{- UID: 1,- FilePathTemplate: "{{DB_NAME}}##{{VERSION}}##{{TYPE}}.sql",- },- project: &store.ProjectMessage{- Title: "project-1",- },- vcs: &store.VCSProviderMessage{},- },- {- repository: &store.RepositoryMessage{- UID: 2,- FilePathTemplate: "{{DB_NAME}}##{{VERSION}}##{{TYPE}}.sql",- },- project: &store.ProjectMessage{- Title: "project-2",- },- vcs: &store.VCSProviderMessage{},- },- },- )- require.EqualError(t, err, "file change should be associated with exactly one project but found project-1, project-2")- })-}--func TestExtractDBTypeFromJDBCConnectionString(t *testing.T) {- testCases := []struct {- jdbcConnectionString string- want storepb.Engine- wantErr bool- }{- {- jdbcConnectionString: "jdbc:mysql://localhost:3306/bytebase?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC",- want: storepb.Engine_MYSQL,- },- {- jdbcConnectionString: "jdbc:mysql+srv+loadbalance://localhost:3306/bytebase?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC",- want: storepb.Engine_MYSQL,- },- {- jdbcConnectionString: "jdbc:postgresql://localhost:5432/bytebase?currentSchema=public&sslmode=disable",- want: storepb.Engine_POSTGRES,- },- }-- for _, tc := range testCases {- dbType, err := extractDBTypeFromJDBCConnectionString(tc.jdbcConnectionString)- require.NoError(t, err)- assert.Equal(t, tc.want, dbType)- }-}diff --git a/backend/api/v1/project_service.go b/backend/api/v1/project_service.goindex d2f3da4b5f..c99a52aa0e 100644--- a/backend/api/v1/project_service.go+++ b/backend/api/v1/project_service.go@@ -479,16 +479,6 @@ func (s *ProjectService) UpdateProjectGitOpsInfo(ctx context.Context, request *vbaseDir = strings.Trim(request.ProjectGitopsInfo.BaseDirectory, "/")}patch.BaseDirectory = &baseDir- case "file_path_template":- if err := api.ValidateRepositoryFilePathTemplate(request.ProjectGitopsInfo.FilePathTemplate, project.TenantMode); err != nil {- return nil, status.Errorf(codes.InvalidArgument, "invalid file_path_template: %s", err.Error())- }- patch.FilePathTemplate = &request.ProjectGitopsInfo.FilePathTemplate- case "schema_path_template":- if err := api.ValidateRepositorySchemaPathTemplate(request.ProjectGitopsInfo.SchemaPathTemplate, project.TenantMode); err != nil {- return nil, status.Errorf(codes.InvalidArgument, "invalid schema_path_template: %s", err.Error())- }- patch.SchemaPathTemplate = &request.ProjectGitopsInfo.SchemaPathTemplate}}@@ -994,16 +984,14 @@ func (s *ProjectService) createProjectGitOpsInfo(ctx context.Context, request *vVCSResourceID: vcs.ResourceID,ProjectResourceID: project.ResourceID,// TODO(d): pass in the resource ID from API.- ResourceID: "default",- WebhookURLHost: setting.ExternalUrl,- Title: request.ProjectGitopsInfo.Title,- FullPath: request.ProjectGitopsInfo.FullPath,- WebURL: request.ProjectGitopsInfo.WebUrl,- BranchFilter: request.ProjectGitopsInfo.BranchFilter,- BaseDirectory: baseDir,- FilePathTemplate: request.ProjectGitopsInfo.FilePathTemplate,- SchemaPathTemplate: request.ProjectGitopsInfo.SchemaPathTemplate,- ExternalID: request.ProjectGitopsInfo.ExternalId,+ ResourceID: "default",+ WebhookURLHost: setting.ExternalUrl,+ Title: request.ProjectGitopsInfo.Title,+ FullPath: request.ProjectGitopsInfo.FullPath,+ WebURL: request.ProjectGitopsInfo.WebUrl,+ BranchFilter: request.ProjectGitopsInfo.BranchFilter,+ BaseDirectory: baseDir,+ ExternalID: request.ProjectGitopsInfo.ExternalId,}if repositoryCreate.BranchFilter == "" {@@ -1016,14 +1004,6 @@ func (s *ProjectService) createProjectGitOpsInfo(ctx context.Context, request *vreturn nil, status.Errorf(codes.InvalidArgument, "invalid base directory and filepath template combination: %v", err.Error())}- if err := api.ValidateRepositoryFilePathTemplate(repositoryCreate.FilePathTemplate, project.TenantMode); err != nil {- return nil, status.Errorf(codes.InvalidArgument, "invalid file_path_template: %v", err.Error())- }-- if err := api.ValidateRepositorySchemaPathTemplate(repositoryCreate.SchemaPathTemplate, project.TenantMode); err != nil {- return nil, status.Errorf(codes.InvalidArgument, "invalid schema_path_template: %s", err.Error())- }-// When the branch names doesn't contain wildcards, we should make sure the branch exists in the repo.if !strings.Contains(repositoryCreate.BranchFilter, "*") {notFound, err := isBranchNotFound(@@ -2466,17 +2446,15 @@ func validateMember(member string) error {func convertToProjectGitOpsInfo(repository *store.RepositoryMessage) *v1pb.ProjectGitOpsInfo {return &v1pb.ProjectGitOpsInfo{- Name: fmt.Sprintf("%s%s/gitOpsInfo", common.ProjectNamePrefix, repository.ProjectResourceID),- Vcs: fmt.Sprintf("%s%s", common.VCSProviderPrefix, repository.VCSResourceID),- Title: repository.Title,- FullPath: repository.FullPath,- WebUrl: repository.WebURL,- BranchFilter: repository.BranchFilter,- BaseDirectory: repository.BaseDirectory,- FilePathTemplate: repository.FilePathTemplate,- SchemaPathTemplate: repository.SchemaPathTemplate,- WebhookEndpointId: repository.WebhookEndpointID,- ExternalId: repository.ExternalID,+ Name: fmt.Sprintf("%s%s/gitOpsInfo", common.ProjectNamePrefix, repository.ProjectResourceID),+ Vcs: fmt.Sprintf("%s%s", common.VCSProviderPrefix, repository.VCSResourceID),+ Title: repository.Title,+ FullPath: repository.FullPath,+ WebUrl: repository.WebURL,+ BranchFilter: repository.BranchFilter,+ BaseDirectory: repository.BaseDirectory,+ WebhookEndpointId: repository.WebhookEndpointID,+ ExternalId: repository.ExternalID,}}diff --git a/backend/common/util.go b/backend/common/util.goindex d52f96bc44..528563c9b5 100644--- a/backend/common/util.go+++ b/backend/common/util.go@@ -8,7 +8,6 @@ import ("os""path""path/filepath"- "regexp""strconv""strings""time"@@ -85,27 +84,6 @@ func DefaultMigrationVersion() model.Version {return model.Version{Version: time.Now().Format("20060102150405")}}-// ParseTemplateTokens parses the template and returns template tokens and their delimiters.-// For example, if the template is "{{DB_NAME}}_hello_{{LOCATION}}", then the tokens will be ["{{DB_NAME}}", "{{LOCATION}}"],-// and the delimiters will be ["_hello_"].-// The caller will usually replace the tokens with a normal string, or a regexp. In the latter case, it will be a problem-// if there are special regexp characters such as "$" in the delimiters. The caller should escape the delimiters in such cases.-func ParseTemplateTokens(template string) ([]string, []string) {- r := regexp.MustCompile(`{{[^{}]+}}`)- tokens := r.FindAllString(template, -1)- if len(tokens) > 0 {- split := r.Split(template, -1)- var delimiters []string- for _, s := range split {- if s != "" {- delimiters = append(delimiters, s)- }- }- return tokens, delimiters- }- return nil, nil-}-// GetFileSizeSum calculates the sum of file sizes for file names in the list.func GetFileSizeSum(fileNameList []string) (int64, error) {var sum int64diff --git a/backend/legacyapi/project.go b/backend/legacyapi/project.goindex 9f7c7db6dd..60ecc4981e 100644--- a/backend/legacyapi/project.go+++ b/backend/legacyapi/project.go@@ -1,11 +1,5 @@package api-import (- "github.com/pkg/errors"-- "github.com/bytebase/bytebase/backend/common"-)-const (// DefaultProjectUID is the UID for the default project.DefaultProjectUID = 1@@ -39,16 +33,6 @@ const (VCSWorkflow ProjectWorkflowType = "VCS")-// ProjectVisibility is the visibility of a project.-type ProjectVisibility string--const (- // Public is the project visibility for PUBLIC.- Public ProjectVisibility = "PUBLIC"- // Private is the project visibility for PRIVATE.- Private ProjectVisibility = "PRIVATE"-)-// ProjectTenantMode is the tenant mode setting for project.type ProjectTenantMode string@@ -58,95 +42,3 @@ const (// TenantModeTenant is the TENANT value for ProjectTenantMode.TenantModeTenant ProjectTenantMode = "TENANT")--var (- // DBNameToken is the token for database name.- DBNameToken = "{{DB_NAME}}"- // EnvironmentToken is the token for environment.- EnvironmentToken = "{{ENV_ID}}"- // LocationToken is the token for location.- LocationToken = "{{LOCATION}}"- // TenantToken is the token for tenant.- TenantToken = "{{TENANT}}"-- // boolean indicates whether it's a required or optional token.- repositoryFilePathTemplateTokens = map[string]bool{- "{{VERSION}}": true,- DBNameToken: true,- "{{TYPE}}": true,- EnvironmentToken: false,- "{{DESCRIPTION}}": false,- }- tenantRepositoryFilePathTemplateTokens = map[string]bool{- "{{VERSION}}": true,- "{{TYPE}}": true,- "{{DESCRIPTION}}": false,- }- schemaPathTemplateTokens = map[string]bool{- DBNameToken: true,- EnvironmentToken: false,- }- tenantSchemaPathTemplateTokens = map[string]bool{}-)--// ValidateRepositoryFilePathTemplate validates the repository file path template.-func ValidateRepositoryFilePathTemplate(filePathTemplate string, tenantMode ProjectTenantMode) error {- tokens, _ := common.ParseTemplateTokens(filePathTemplate)- tokenMap := make(map[string]bool)- for _, token := range tokens {- tokenMap[token] = true- }-- filePathTemplateTokens := repositoryFilePathTemplateTokens- if tenantMode == TenantModeTenant {- filePathTemplateTokens = tenantRepositoryFilePathTemplateTokens- }- for token, required := range filePathTemplateTokens {- // Skip checking tokens that are not required- if !required {- continue- }-- if _, ok := tokenMap[token]; !ok {- return errors.Errorf("missing %s in file path template", token)- }- }- for token := range tokenMap {- if _, ok := filePathTemplateTokens[token]; !ok {- return errors.Errorf("unknown token %s in file path template", token)- }- }- return nil-}--// ValidateRepositorySchemaPathTemplate validates the repository schema path template.-func ValidateRepositorySchemaPathTemplate(schemaPathTemplate string, tenantMode ProjectTenantMode) error {- if schemaPathTemplate == "" {- return nil- }- tokens, _ := common.ParseTemplateTokens(schemaPathTemplate)- tokenMap := make(map[string]bool)- for _, token := range tokens {- tokenMap[token] = true- }-- allowedTokens := schemaPathTemplateTokens- if tenantMode == TenantModeTenant {- allowedTokens = tenantSchemaPathTemplateTokens- }-- for token, required := range allowedTokens {- if required {- if _, ok := tokenMap[token]; !ok {- return errors.Errorf("missing %s in schema path template", token)- }- }- }-- for token := range tokenMap {- if _, ok := allowedTokens[token]; !ok {- return errors.Errorf("unknown token %s in schema path template", token)- }- }- return nil-}diff --git a/backend/legacyapi/project_test.go b/backend/legacyapi/project_test.godeleted file mode 100644index 5f7ddaa613..0000000000--- a/backend/legacyapi/project_test.go+++ /dev/null@@ -1,152 +0,0 @@-package api--import (- "testing"-- "github.com/stretchr/testify/require"-- "github.com/bytebase/bytebase/backend/common"-)--func TestGetTemplateTokens(t *testing.T) {- tests := []struct {- name string- template string- tokens []string- delimiters []string- }{- {- "NoToken",- "helloworld",- nil,- nil,- }, {- "TwoTokens",- "{{DB_NAME}}_{{LOCATION}}",- []string{"{{DB_NAME}}", "{{LOCATION}}"},- []string{"_"},- }, {- "ExtraPrefix",- "hello_{{DB_NAME}}_{{LOCATION}}",- []string{"{{DB_NAME}}", "{{LOCATION}}"},- []string{"hello_", "_"},- },- }-- for _, test := range tests {- tokens, delimiters := common.ParseTemplateTokens(test.template)- require.Equal(t, test.tokens, tokens)- require.Equal(t, test.delimiters, delimiters)- }-}--func TestValidateRepositoryFilePathTemplate(t *testing.T) {- tests := []struct {- name string- template string- tenantMode ProjectTenantMode- errPart string- }{- {- "OK",- "{{DB_NAME}}_{{TYPE}}_{{VERSION}}.sql",- TenantModeDisabled,- "",- }, {- "OK with optional tokens",- "{{ENV_ID}}/{{DB_NAME}}_{{TYPE}}_{{VERSION}}_{{DESCRIPTION}}.sql",- TenantModeDisabled,- "",- }, {- "Missing {{VERSION}}",- "{{DB_NAME}}_{{TYPE}}.sql",- TenantModeDisabled,- "missing {{VERSION}}",- }, {- "UnknownToken",- "{{DB_NAME}}_{{TYPE}}_{{VERSION}}_{{UNKNOWN}}.sql",- TenantModeDisabled,- "unknown token {{UNKNOWN}}",- }, {- "UnknownToken",- "{{DB_NAME}}_{{TYPE}}_{{VERSION}}_{{UNKNOWN}}.sql",- TenantModeDisabled,- "unknown token {{UNKNOWN}}",- },- {- "Tenant mode {{ENV_ID}}",- "{{ENV_ID}}/{{VERSION}}_{{TYPE}}.sql",- TenantModeTenant,- "in file path template",- },- {- "Tenant mode {{DB_NAME}}",- "{{DB_NAME}}_{{VERSION}}_{{TYPE}}.sql",- TenantModeTenant,- "in file path template",- }, {- "Tenant mode okay",- "{{VERSION}}_{{TYPE}}.sql",- TenantModeTenant,- "",- },- }-- for _, test := range tests {- // Fix the problem that closure in a for loop will always use the last element.- test := test- t.Run(test.name, func(t *testing.T) {- err := ValidateRepositoryFilePathTemplate(test.template, test.tenantMode)- if test.errPart == "" {- require.NoError(t, err)- } else {- require.ErrorContains(t, err, test.errPart, test.name)- }- })- }-}--func TestValidateRepositorySchemaPathTemplate(t *testing.T) {- tests := []struct {- name string- template string- tenantMode ProjectTenantMode- errPart string- }{- {- "OK",- "{{DB_NAME}}_hello.sql",- TenantModeDisabled,- "",- }, {- "OK with optional tokens",- "{{ENV_ID}}/{{DB_NAME}}.sql",- TenantModeDisabled,- "",- }, {- "UnknownToken",- "{{DB_NAME}}_{{TYPE}}.sql",- TenantModeDisabled,- "unknown token {{TYPE}}",- }, {- "Tenant mode {{ENV_ID}}",- "{{ENV_ID}}/LATEST.sql",- TenantModeTenant,- "in schema path template",- }, {- "Tenant mode {{DB_NAME}}",- "{{DB_NAME}}_LATEST.sql",- TenantModeTenant,- "in schema path template",- },- }-- for _, test := range tests {- err := ValidateRepositorySchemaPathTemplate(test.template, test.tenantMode)- if test.errPart == "" {- require.NoError(t, err)- } else {- require.ErrorContains(t, err, test.errPart, test.name)- }- }-}diff --git a/backend/plugin/db/driver.go b/backend/plugin/db/driver.goindex e756ad5e23..bb0918783b 100644--- a/backend/plugin/db/driver.go+++ b/backend/plugin/db/driver.go@@ -6,12 +6,8 @@ import ("database/sql""fmt""io"- "path"- "regexp"- "strings""sync""time"- "unicode""github.com/pkg/errors"@@ -160,156 +156,6 @@ type MigrationInfo struct {Payload *storepb.InstanceChangeHistoryPayload}-// placeholderRegexp is the regexp for placeholder.-// Refer to https://stackoverflow.com/a/6222235/19075342, but we support "." for now.-const placeholderRegexp = `[^\\/?%*:|"<>]+`--// ParseMigrationInfo matches filePath against filePathTemplate-// If filePath matches, then it will derive MigrationInfo from the filePath.-// Both filePath and filePathTemplate are the full file path (including the base directory) of the repository.-// It returns (nil, nil) if it doesn't look like a migration file path.-func ParseMigrationInfo(filePath, filePathTemplate string, allowOmitDatabaseName bool) (*MigrationInfo, error) {- placeholderList := []string{- "ENV_ID",- "VERSION",- "DB_NAME",- "TYPE",- "DESCRIPTION",- }-- // Escape "." characters to match literals instead of using it as a wildcard.- filePathRegex := strings.ReplaceAll(filePathTemplate, `.`, `\.`)-- // We need using for-loop to handle the continuous "*" case.- // For example, if filePathTemplate is "foo/*/*/bar", then we need to convert it to "foo/[^/]+/[^/]+/bar",- // but strings.ReplaceAll(filePathRegex, `/*/`, `/[^/]+/`) will only replace the first "*" to "/[^/]+/"(i.e "foo/[^/]+/*/bar")- tempFilePathRegex := strings.ReplaceAll(filePathRegex, `/*/`, `/[^/]+/`)- for tempFilePathRegex != filePathRegex {- filePathRegex = tempFilePathRegex- tempFilePathRegex = strings.ReplaceAll(filePathRegex, `/*/`, `/[^/]+/`)- }-- // After the previous for-loop, filePathRegex will not include any "/*/" anymore, so we can safely replace all ** to .*.- filePathRegex = strings.ReplaceAll(filePathRegex, `**`, `.*`)-- for _, placeholder := range placeholderList {- filePathRegex = strings.ReplaceAll(filePathRegex, fmt.Sprintf("{{%s}}", placeholder), fmt.Sprintf(`(?P<%s>%s)`, placeholder, placeholderRegexp))- }- myRegex, err := regexp.Compile(filePathRegex)- if err != nil {- return nil, errors.Errorf("invalid file path template: %q", filePathTemplate)- }- if !myRegex.MatchString(filePath) {- // File path does not match file path template.- return nil, nil- }-- mi := &MigrationInfo{- Source: VCS,- Type: Migrate,- }- matchList := myRegex.FindStringSubmatch(filePath)- for _, placeholder := range placeholderList {- index := myRegex.SubexpIndex(placeholder)- if index >= 0 {- switch placeholder {- case "ENV_ID":- mi.Environment = matchList[index]- case "VERSION":- mi.Version = model.Version{Version: matchList[index]}- case "DB_NAME":- mi.Namespace = matchList[index]- mi.Database = matchList[index]- case "TYPE":- switch matchList[index] {- case "data":- mi.Type = Data- case "dml":- mi.Type = Data- case "migrate":- mi.Type = Migrate- case "ddl":- mi.Type = Migrate- default:- return nil, errors.Errorf("file path %q contains invalid migration type %q, must be 'migrate'('ddl') or 'data'('dml')", filePath, matchList[index])- }- case "DESCRIPTION":- mi.Description = matchList[index]- }- }- }-- if mi.Version.Version == "" {- return nil, errors.Errorf("file path %q does not contain {{VERSION}}, configured file path template %q", filePath, filePathTemplate)- }- if mi.Namespace == "" && !allowOmitDatabaseName {- return nil, errors.Errorf("file path %q does not contain {{DB_NAME}}, configured file path template %q", filePath, filePathTemplate)- }-- if mi.Description == "" {- switch mi.Type {- case Baseline:- mi.Description = fmt.Sprintf("Create %s baseline", mi.Database)- case Data:- mi.Description = fmt.Sprintf("Create %s data change", mi.Database)- default:- mi.Description = fmt.Sprintf("Create %s schema migration", mi.Database)- }- } else {- // Replace _ with space- mi.Description = strings.ReplaceAll(mi.Description, "_", " ")- // Capitalize first letter- description := []rune(mi.Description)- description[0] = unicode.ToUpper(description[0])- mi.Description = string(description)- }-- return mi, nil-}--// ParseSchemaFileInfo attempts to parse the given schema file path to extract-// the schema file info.-// It returns (nil, nil) if it doesn't look like a schema file path.-func ParseSchemaFileInfo(baseDirectory, schemaPathTemplate, file string) (*MigrationInfo, error) {- if schemaPathTemplate == "" {- return nil, nil- }-- // Escape "." characters to match literals instead of using it as a wildcard.- schemaFilePathRegex := strings.ReplaceAll(schemaPathTemplate, ".", `\.`)-- placeholders := []string{- "ENV_ID",- "DB_NAME",- }- for _, placeholder := range placeholders {- schemaFilePathRegex = strings.ReplaceAll(schemaFilePathRegex, fmt.Sprintf("{{%s}}", placeholder), fmt.Sprintf("(?P<%s>[a-zA-Z0-9+-=/_#?!$. ]+)", placeholder))- }-- // NOTE: We do not want to use filepath.Join here because we always need "/" as the path separator.- re, err := regexp.Compile(path.Join(baseDirectory, schemaFilePathRegex))- if err != nil {- return nil, errors.Wrap(err, "compile schema file path regex")- }- match := re.FindStringSubmatch(file)- if len(match) == 0 {- return nil, nil- }-- info := make(map[string]string)- // Skip the first item because it is always the empty string, see docstring of- // the SubexpNames() method.- for i, name := range re.SubexpNames()[1:] {- info[name] = match[i+1]- }- return &MigrationInfo{- Source: VCS,- Type: Migrate,- Environment: info["ENV_ID"],- Database: info["DB_NAME"],- }, nil-}-// ConnectionConfig is the configuration for connections.type ConnectionConfig struct {Host stringdiff --git a/backend/plugin/db/driver_test.go b/backend/plugin/db/driver_test.godeleted file mode 100644index a1abad30d3..0000000000--- a/backend/plugin/db/driver_test.go+++ /dev/null@@ -1,322 +0,0 @@-package db--import (- "fmt"- "testing"-- "github.com/stretchr/testify/assert"- "github.com/stretchr/testify/require"-- "github.com/bytebase/bytebase/backend/store/model"-)--func TestParseMigrationInfo(t *testing.T) {- type test struct {- filePath string- filePathTemplate string- allowOmitDatabaseName bool- want *MigrationInfo- wantErr string- }-- tests := []test{- {- filePath: "db1##001foo",- filePathTemplate: "{{DB_NAME}}##{{VERSION}}",- want: &MigrationInfo{- Version: model.Version{Version: "001foo"},- Namespace: "db1",- Database: "db1",- Environment: "",- Source: VCS,- Type: Migrate,- Description: "Create db1 schema migration",- Creator: "",- },- wantErr: "",- },- {- filePath: "db foo_+-=_#!$.##1.2.3",- filePathTemplate: "{{DB_NAME}}##{{VERSION}}",- want: &MigrationInfo{- Version: model.Version{Version: "1.2.3"},- Namespace: "db foo_+-=_#!$.",- Database: "db foo_+-=_#!$.",- Environment: "",- Source: VCS,- Type: Migrate,- Description: "Create db foo_+-=_#!$. schema migration",- Creator: "",- },- wantErr: "",- },- {- filePath: "bytebase/db1##001foo",- filePathTemplate: "bytebase/{{DB_NAME}}##{{VERSION}}",- want: &MigrationInfo{- Version: model.Version{Version: "001foo"},- Namespace: "db1",- Database: "db1",- Environment: "",- Source: VCS,- Type: Migrate,- Description: "Create db1 schema migration",- Creator: "",- },- wantErr: "",- },- {- filePath: "bytebase/dev/db1##001foo",- filePathTemplate: "bytebase/{{ENV_ID}}/{{DB_NAME}}##{{VERSION}}",- want: &MigrationInfo{- Version: model.Version{Version: "001foo"},- Namespace: "db1",- Database: "db1",- Environment: "dev",- Source: VCS,- Type: Migrate,- Description: "Create db1 schema migration",- Creator: "",- },- wantErr: "",- },- {- filePath: "db1##001foo##create_t1",- filePathTemplate: "{{DB_NAME}}##{{VERSION}}##{{DESCRIPTION}}",- want: &MigrationInfo{- Version: model.Version{Version: "001foo"},- Namespace: "db1",- Database: "db1",- Environment: "",- Source: VCS,- Type: Migrate,- Description: "Create t1",- Creator: "",- },- wantErr: "",- },- {- filePath: "db1##001foo##migrate",- filePathTemplate: "{{DB_NAME}}##{{VERSION}}##{{TYPE}}",- want: &MigrationInfo{- Version: model.Version{Version: "001foo"},- Namespace: "db1",- Database: "db1",- Environment: "",- Source: VCS,- Type: Migrate,- Description: "Create db1 schema migration",- Creator: "",- },- wantErr: "",- },- {- filePath: "db1##001foo##ddl",- filePathTemplate: "{{DB_NAME}}##{{VERSION}}##{{TYPE}}",- want: &MigrationInfo{- Version: model.Version{Version: "001foo"},- Namespace: "db1",- Database: "db1",- Environment: "",- Source: VCS,- Type: Migrate,- Description: "Create db1 schema migration",- Creator: "",- },- wantErr: "",- },- {- filePath: "db1##001foo##dml",- filePathTemplate: "{{DB_NAME}}##{{VERSION}}##{{TYPE}}",- want: &MigrationInfo{- Version: model.Version{Version: "001foo"},- Namespace: "db1",- Database: "db1",- Environment: "",- Source: VCS,- Type: Data,- Description: "Create db1 data change",- Creator: "",- },- wantErr: "",- },- {- filePath: "db_shop1##001foo##data",- filePathTemplate: "{{DB_NAME}}##{{VERSION}}##{{TYPE}}",- want: &MigrationInfo{- Version: model.Version{Version: "001foo"},- Namespace: "db_shop1",- Database: "db_shop1",- Environment: "",- Source: VCS,- Type: Data,- Description: "Create db_shop1 data change",- Creator: "",- },- wantErr: "",- },- {- filePath: "db_shop1##001foo##data##fix_customer_info",- filePathTemplate: "{{DB_NAME}}##{{VERSION}}##{{TYPE}}##{{DESCRIPTION}}",- want: &MigrationInfo{- Version: model.Version{Version: "001foo"},- Namespace: "db_shop1",- Database: "db_shop1",- Environment: "",- Source: VCS,- Type: Data,- Description: "Fix customer info",- Creator: "",- },- wantErr: "",- },- {- filePath: ".db##20220811.sql",- filePathTemplate: ".{{DB_NAME}}##{{VERSION}}.sql",- want: &MigrationInfo{- Version: model.Version{Version: "20220811"},- Namespace: "db",- Database: "db",- Environment: "",- Source: VCS,- Type: Migrate,- Description: "Create db schema migration",- Creator: "",- },- wantErr: "",- },- {- filePath: "db1##001foo##baseline",- filePathTemplate: "{{DB_NAME}}##{{VERSION}}##{{TYPE}}",- want: &MigrationInfo{- Version: model.Version{Version: "001foo"},- Namespace: "db1",- Database: "db1",- Environment: "",- Source: VCS,- Type: Baseline,- Description: "Create db1 baseline",- Creator: "",- },- wantErr: "contains invalid migration type \"baseline\"",- },- {- filePath: "db",- filePathTemplate: "{{DB_NAME}}##{{VERSION}}",- want: nil,- wantErr: "",- },- { // Make sure the "." is escaped and should only match literals not as a wildcard- filePath: ".db##20220811.sql",- filePathTemplate: "A{{DB_NAME}}##{{VERSION}}Asql",- want: nil,- wantErr: "",- },-- {- filePath: "001foo##ddl",- filePathTemplate: "{{VERSION}}##{{TYPE}}",- want: nil,- wantErr: "does not contain {{DB_NAME}}",- },- {- filePath: "001foo##ddl",- filePathTemplate: "{{VERSION}}##{{TYPE}}",- allowOmitDatabaseName: true,- want: &MigrationInfo{- Version: model.Version{Version: "001foo"},- Source: VCS,- Type: Migrate,- Description: "Create schema migration",- },- wantErr: "",- },- }- for _, tc := range tests {- t.Run(tc.filePath, func(t *testing.T) {- mi, err := ParseMigrationInfo(tc.filePath, tc.filePathTemplate, tc.allowOmitDatabaseName)- if tc.wantErr != "" {- got := fmt.Sprintf("%v", err)- require.Contains(t, got, tc.wantErr)- return- }- require.NoError(t, err)- if tc.want == nil {- require.Nil(t, mi)- } else {- require.NotNil(t, mi)- require.Equal(t, *tc.want, *mi)- }- })- }-}--func TestParseSchemaFileInfo(t *testing.T) {- tests := []struct {- name string- baseDirectory string- schemaPathTemplate string- file string- schemaInfo *MigrationInfo- }{- {- name: "no schemaPathTemplate",- baseDirectory: "",- schemaPathTemplate: "",- file: "Test/testdb##LATEST.sql",- schemaInfo: nil,- },- {- name: "only has DB_NAME",- baseDirectory: "",- schemaPathTemplate: "{{DB_NAME}}##LATEST.sql",- file: "testdb##LATEST.sql",- schemaInfo: &MigrationInfo{- Source: VCS,- Type: Migrate,- Database: "testdb",- },- },- {- name: "has both ENV_ID and DB_NAME",- baseDirectory: "",- schemaPathTemplate: "{{ENV_ID}}/{{DB_NAME}}##LATEST.sql",- file: "Test/testdb##LATEST.sql",- schemaInfo: &MigrationInfo{- Source: VCS,- Type: Migrate,- Environment: "Test",- Database: "testdb",- },- },-- {- name: "baseDirectory does not match",- baseDirectory: "bytebase",- schemaPathTemplate: "{{ENV_ID}}/{{DB_NAME}}##LATEST.sql",- file: "Test/testdb##LATEST.sql",- schemaInfo: nil,- },- {- name: "baseDirectory with both ENV_ID and DB_NAME",- baseDirectory: "bytebase",- schemaPathTemplate: "{{ENV_ID}}/{{DB_NAME}}##LATEST.sql",- file: "bytebase/Test/testdb##LATEST.sql",- schemaInfo: &MigrationInfo{- Source: VCS,- Type: Migrate,- Environment: "Test",- Database: "testdb",- },- },- }- for _, test := range tests {- // Fix the problem that closure in a for loop will always use the last element.- test := test- t.Run(test.name, func(t *testing.T) {- got, err := ParseSchemaFileInfo(test.baseDirectory, test.schemaPathTemplate, test.file)- require.NoError(t, err)- assert.Equal(t, test.schemaInfo, got)- })- }-}diff --git a/backend/tests/schema_update_test.go b/backend/tests/schema_update_test.goindex 8f9e1836e3..f451a121e7 100644--- a/backend/tests/schema_update_test.go+++ b/backend/tests/schema_update_test.go@@ -16,8 +16,6 @@ import (api "github.com/bytebase/bytebase/backend/legacyapi""github.com/bytebase/bytebase/backend/plugin/vcs"- "github.com/bytebase/bytebase/backend/plugin/vcs/bitbucket"- "github.com/bytebase/bytebase/backend/plugin/vcs/github""github.com/bytebase/bytebase/backend/plugin/vcs/gitlab""github.com/bytebase/bytebase/backend/resources/mysql""github.com/bytebase/bytebase/backend/resources/postgres"@@ -172,108 +170,6 @@ func TestSimpleVCS(t *testing.T) {}},},- {- name: "GitHub",- vcsProviderCreator: fake.NewGitHub,- vcsType: v1pb.VCSProvider_GITHUB,- externalID: "octocat/Hello-World",- repositoryFullPath: "octocat/Hello-World",- newWebhookPushEvent: func(added, modified [][]string, beforeSHA, afterSHA string) any {- var commits []github.WebhookCommit- for i := range added {- commits = append(commits, github.WebhookCommit{- ID: "fake_github_commit_id",- Distinct: true,- Message: "Fake GitHub commit message",- Timestamp: time.Now(),- URL: "https://api.github.com/octocat/Hello-World/commits/fake_github_commit_id",- Author: github.WebhookCommitAuthor{- Name: "fake_github_author",- Email: "fake_github_author@localhost",- },- Added: added[i],- Modified: modified[i],- })- }- return github.WebhookPushEvent{- Ref: "refs/heads/feature/foo",- Before: beforeSHA,- After: afterSHA,- Repository: github.WebhookRepository{- ID: 211,- FullName: "octocat/Hello-World",- HTMLURL: "https://github.com/octocat/Hello-World",- },- Sender: github.WebhookSender{- Login: "fake_github_author",- },- Commits: commits,- }- },- },- {- name: "Bitbucket",- vcsProviderCreator: fake.NewBitbucket,- vcsType: v1pb.VCSProvider_BITBUCKET,- externalID: "octocat/Hello-World",- repositoryFullPath: "octocat/Hello-World",- newWebhookPushEvent: func(added, _ [][]string, beforeSHA, afterSHA string) any {- var commits []bitbucket.WebhookCommit- for range added {- commits = append(commits, bitbucket.WebhookCommit{- Hash: afterSHA,- Date: time.Now(),- Author: bitbucket.Author{- Raw: "fake_bitbucket_author <fake_bitbucket_author@localhost>",- User: bitbucket.User{- Nickname: "fake_bitbucket_author",- },- },- Message: "Fake Bitbucket commit message",- Links: bitbucket.Links{- HTML: bitbucket.Link{- Href: "https://bitbucket.org/octocat/Hello-World/commits/fake_github_commit_id",- },- },- Parents: []bitbucket.Target{- {Hash: beforeSHA},- },- })- }- return bitbucket.WebhookPushEvent{- Push: bitbucket.WebhookPush{- Changes: []bitbucket.WebhookPushChange{- {- Old: bitbucket.Branch{- Name: "feature/foo",- Target: bitbucket.Target{- Hash: beforeSHA,- },- },- New: bitbucket.Branch{- Name: "feature/foo",- Target: bitbucket.Target{- Hash: afterSHA,- },- },- Commits: commits,- },- },- },- Repository: bitbucket.Repository{- FullName: "octocat/Hello-World",- Links: bitbucket.Links{- HTML: bitbucket.Link{- Href: "https://bitbuket.org/octocat/Hello-World",- },- },- },- Actor: bitbucket.User{- Nickname: "fake_bitbucket_author",- },- }- },- },}for _, test := range tests {// Fix the problem that closure in a for loop will always use the last element.@@ -356,19 +252,19 @@ func TestSimpleVCS(t *testing.T) {// Simulate Git commits for schema update.// We create multiple commits in one push event to test for the behavior of creating one issue per database.- gitFile3 := "bbtest/prod/testVCSSchemaUpdate##ver3##migrate##create_table_book3.sql"+ gitFile3 := "bbtest/0003##migrate##create_table_book3.sql"err = ctl.vcsProvider.AddFiles(test.externalID, map[string]string{gitFile3: migrationStatement3})a.NoError(err)- gitFile2 := "bbtest/prod/testVCSSchemaUpdate##ver2##migrate##新建create_table_book2.sql"+ gitFile2 := "bbtest/0002##migrate##新建create_table_book2.sql"err = ctl.vcsProvider.AddFiles(test.externalID, map[string]string{gitFile2: migrationStatement2})a.NoError(err)- gitFile1 := "bbtest/prod/testVCSSchemaUpdate##ver1##migrate##😊create_table_book.sql"+ gitFile1 := "bbtest/0001##migrate##😊create_table_book.sql"err = ctl.vcsProvider.AddFiles(test.externalID, map[string]string{gitFile1: migrationStatement})a.NoError(err)// This file is merged from other branch and included in this push event's commits.// But it is already merged into the main branch and the commits diff does not contain it.// So this file should be excluded when generating the issue.- gitFileMergeFromOtherBranch := "bbtest/prod/testVCSSchemaUpdate##ver0##migrate##merge_from_other_branch.sql"+ gitFileMergeFromOtherBranch := "bbtest/0000##migrate##merge_from_other_branch.sql"err = ctl.vcsProvider.AddFiles(test.externalID, map[string]string{gitFileMergeFromOtherBranch: "SELECT 1;"})a.NoError(err)err = ctl.vcsProvider.AddCommitsDiff(test.externalID, "1", "2", []vcs.FileDiff{@@ -388,8 +284,8 @@ func TestSimpleVCS(t *testing.T) {a.NoError(err)err = ctl.waitRollout(ctx, issue.Name, issue.Rollout)a.NoError(err)- a.Equal("[testVCSSchemaUpdate] Alter schema: 😊create table book", issue.Title)- a.Equal("By VCS files:\n\nprod/testVCSSchemaUpdate##ver1##migrate##😊create_table_book.sql\nprod/testVCSSchemaUpdate##ver2##migrate##新建create_table_book2.sql\nprod/testVCSSchemaUpdate##ver3##migrate##create_table_book3.sql\n", issue.Description)+ a.Equal("Alter schema: 😊create table book", issue.Title)+ a.Equal("By VCS files:\n\n0001##migrate##😊create_table_book.sql\n0002##migrate##新建create_table_book2.sql\n0003##migrate##create_table_book3.sql\n", issue.Description)err = ctl.closeIssue(ctx, ctl.project, issue.Name)a.NoError(err)@@ -399,7 +295,7 @@ func TestSimpleVCS(t *testing.T) {a.Equal(want3BookSchema, dbMetadata.Schema)// Simulate Git commits for failed data update.- gitFile4 := "bbtest/prod/testVCSSchemaUpdate##ver4##data##insert_data.sql"+ gitFile4 := "bbtest/0004##data##insert_data.sql"err = ctl.vcsProvider.AddFiles(test.externalID, map[string]string{gitFile4: dataUpdateStatementWrong})a.NoError(err)err = ctl.vcsProvider.AddCommitsDiff(test.externalID, "2", "3", []vcs.FileDiff{@@ -446,8 +342,8 @@ func TestSimpleVCS(t *testing.T) {err = ctl.waitRollout(ctx, issue.Name, issue.Rollout)a.NoError(err)- a.Equal("[testVCSSchemaUpdate] Change data: Insert data", issue.Title)- a.Equal("By VCS files:\n\nprod/testVCSSchemaUpdate##ver4##data##insert_data.sql\n", issue.Description)+ a.Equal("Change data: insert data", issue.Title)+ a.Equal("By VCS files:\n\n0004##data##insert_data.sql\n", issue.Description)err = ctl.closeIssue(ctx, ctl.project, issue.Name)a.NoError(err)@@ -517,10 +413,10 @@ func TestSimpleVCS(t *testing.T) {a.NotEqual(history.Version, "")}- a.Equal("ver4-dml", histories[1].Version)- a.Equal("ver3-ddl", histories[2].Version)- a.Equal("ver2-ddl", histories[3].Version)- a.Equal("ver1-ddl", histories[4].Version)+ a.Equal("0004-dml", histories[1].Version)+ a.Equal("0003-ddl", histories[2].Version)+ a.Equal("0002-ddl", histories[3].Version)+ a.Equal("0001-ddl", histories[4].Version)})}}