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: gitlab test (#11412)
Danny Xu7abcf887b03c
diff --git a/backend/api/gitops/gitlab.go b/backend/api/gitops/gitlab.goindex ee5785c10c..9eb29f7735 100644--- a/backend/api/gitops/gitlab.go+++ b/backend/api/gitops/gitlab.go@@ -46,9 +46,10 @@ func getMergeRequestChangeFileContent(ctx context.Context, vcsProvider *store.VC}prInfo := &pullRequestInfo{- email: pushEvent.User.Email,- title: pushEvent.ObjectAttributes.Title,- url: pushEvent.ObjectAttributes.URL,+ email: pushEvent.User.Email,+ url: pushEvent.ObjectAttributes.URL,+ title: pushEvent.ObjectAttributes.Title,+ description: pushEvent.ObjectAttributes.Description,}for _, v := range mrFiles {if v.IsDeleted {diff --git a/backend/api/gitops/legacy.go b/backend/api/gitops/legacy.godeleted file mode 100644index 4bb7e34f24..0000000000--- a/backend/api/gitops/legacy.go+++ /dev/null@@ -1,33 +0,0 @@-package gitops--import (- "github.com/bytebase/bytebase/backend/plugin/db"- "github.com/bytebase/bytebase/backend/store/model"-)--// migrationDetail is the detail for database migration such as Migrate, Data.-type migrationDetail struct {- // migrationType is the type of a migration.- // migrationType can be empty for gh-ost type of migration.- migrationType db.MigrationType- // databaseID is the ID of a database.- // This should be unset when a project is in tenant mode. The ProjectID is derived from IssueCreate.- databaseID int- // sheetID is the ID of a sheet. Statement and sheet ID is mutually exclusive.- sheetID int- // schemaVersion is parsed from VCS file name.- // It is automatically generated in the UI workflow.- schemaVersion model.Version-}--// MigrationFileYAMLDatabase contains the information of a database in a YAML-// format migration file.-type MigrationFileYAMLDatabase struct {- Name string `yaml:"name"` // The name of the database-}--// MigrationFileYAML contains the information in a YAML format migration file.-type MigrationFileYAML struct {- Databases []MigrationFileYAMLDatabase `yaml:"databases"` // The list of databases and how to identify them- Statement string `yaml:"statement"` // The SQL statement to be executed to specified list of databases-}diff --git a/backend/api/gitops/webhook.go b/backend/api/gitops/webhook.goindex 0e9b38190a..eae9c2b4d4 100644--- a/backend/api/gitops/webhook.go+++ b/backend/api/gitops/webhook.go@@ -11,9 +11,6 @@ import ("io""log/slog""net/http"- "net/mail"- "path/filepath"- "regexp""sort""strconv""strings"@@ -26,28 +23,12 @@ import ("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/db""github.com/bytebase/bytebase/backend/plugin/vcs"- "github.com/bytebase/bytebase/backend/store/model"- // Register azure plugin.- "github.com/bytebase/bytebase/backend/plugin/vcs/azure"- "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/store"- "github.com/bytebase/bytebase/backend/utils"- storepb "github.com/bytebase/bytebase/proto/generated-go/store"v1pb "github.com/bytebase/bytebase/proto/generated-go/v1")-const (- // 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: "Alter schema: add an email column".- issueNameTemplate = "%s: %s"-)-func (s *Service) RegisterWebhookRoutes(g *echo.Group) {g.POST(":id", func(c echo.Context) error {ctx := c.Request().Context()@@ -117,360 +98,12 @@ func (s *Service) RegisterWebhookRoutes(g *echo.Group) {if err := s.createIssueFromPRInfo(ctx, project, prInfo); err != nil {return c.String(http.StatusOK, fmt.Sprintf("failed to create issue from pull request %s, error %v", prInfo.url, err))}+ return nil}-- var baseVCSPushEvents []vcs.PushEvent-- switch vcsProvider.Type {- case vcs.GitHub:- // This shouldn't happen as we only setup webhook to receive push event, just in case.- eventType := github.WebhookType(c.Request().Header.Get("X-GitHub-Event"))- // https://docs.github.com/en/developers/webhooks-and-events/webhooks/about-webhooks#ping-event- // When we create a new webhook, GitHub will send us a simple ping event to let us know we've set up the webhook correctly.- // We respond to this event so as not to mislead users.- if eventType == github.WebhookPing {- return c.String(http.StatusOK, "OK")- }- if eventType != github.WebhookPush {- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid webhook event type, got %s, want %s", eventType, github.WebhookPush))- }-- var pushEvent github.WebhookPushEvent- if err := json.Unmarshal(body, &pushEvent); err != nil {- return echo.NewHTTPError(http.StatusBadRequest, "Malformed push event").SetInternal(err)- }-- // Check webhook branch.- ok, err := isWebhookEventBranch(pushEvent.Ref, vcsConnector.Payload.Branch)- if err != nil {- return err- }- if !ok {- return c.String(http.StatusOK, fmt.Sprintf("committed to branch %q, want branch %q", pushEvent.Ref, vcsConnector.Payload.Branch))- }-- baseVCSPushEvents = append(baseVCSPushEvents, pushEvent.ToVCS())- case vcs.GitLab:- var pushEvent gitlab.WebhookPushEvent- if err := json.Unmarshal(body, &pushEvent); err != nil {- return c.String(http.StatusBadRequest, fmt.Sprintf("failed to unmarshal push event, error %v", err))- }- // This shouldn't happen as we only setup webhook to receive push event, just in case.- if pushEvent.ObjectKind != gitlab.WebhookPush {- return c.String(http.StatusBadRequest, fmt.Sprintf("Invalid webhook event type, got %s, want push", pushEvent.ObjectKind))- }-- // Check webhook branch.- ok, err := isWebhookEventBranch(pushEvent.Ref, vcsConnector.Payload.Branch)- if err != nil {- return err- }- if !ok {- return c.String(http.StatusOK, fmt.Sprintf("committed to branch %q, want branch %q", pushEvent.Ref, vcsConnector.Payload.Branch))- }-- baseVCSPushEvent, err := pushEvent.ToVCS()- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to convert GitLab commits").SetInternal(err)- }- baseVCSPushEvents = append(baseVCSPushEvents, baseVCSPushEvent)- case vcs.Bitbucket:- // This shouldn't happen as we only set up webhook to receive push event, just in case.- eventType := c.Request().Header.Get("X-Event-Key")- if eventType != "repo:push" {- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid webhook event type, got %q, want %q", eventType, "repo:push"))- }-- var pushEvent bitbucket.WebhookPushEvent- if err := json.Unmarshal(body, &pushEvent); err != nil {- return echo.NewHTTPError(http.StatusBadRequest, "Malformed push event").SetInternal(err)- }-- for _, change := range pushEvent.Push.Changes {- // Check webhook branch.- ref := "refs/heads/" + change.New.Name- ok, err := isWebhookEventBranch(ref, vcsConnector.Payload.Branch)- if err != nil {- return err- }- if !ok {- return c.String(http.StatusOK, fmt.Sprintf("committed to branch %q, want branch %q", ref, vcsConnector.Payload.Branch))- }-- // Squash commits.- oauthContext := &common.OauthContext{- AccessToken: vcsProvider.AccessToken,- }- var commitList []vcs.Commit- for _, commit := range change.Commits {- before := strings.Repeat("0", 40)- if len(commit.Parents) > 0 {- before = commit.Parents[0].Hash- }- fileDiffList, err := vcs.Get(vcsProvider.Type, vcs.ProviderConfig{}).GetDiffFileList(- ctx,- oauthContext,- vcsProvider.InstanceURL,- vcsConnector.Payload.ExternalId,- before,- commit.Hash,- )- if err != nil {- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Failed to get diff file list for commit %q", commit.Hash)).SetInternal(err)- }-- var addedList, modifiedList []string- for _, f := range fileDiffList {- switch f.Type {- case vcs.FileDiffTypeAdded:- addedList = append(addedList, f.Path)- case vcs.FileDiffTypeModified:- modifiedList = append(modifiedList, f.Path)- }- }-- // Per Git convention, the message title and body are separated by two new line characters.- messages := strings.SplitN(commit.Message, "\n\n", 2)- messageTitle := messages[0]-- authorName := commit.Author.User.Nickname- authorEmail := ""- addr, err := mail.ParseAddress(commit.Author.Raw)- if err == nil {- authorName = addr.Name- authorEmail = addr.Address- }-- commitList = append(commitList,- vcs.Commit{- ID: commit.Hash,- Title: messageTitle,- Message: commit.Message,- CreatedTs: commit.Date.Unix(),- URL: commit.Links.HTML.Href,- AuthorName: authorName,- AuthorEmail: authorEmail,- AddedList: addedList,- ModifiedList: modifiedList,- },- )- }-- baseVCSPushEvents = append(baseVCSPushEvents, vcs.PushEvent{- VCSType: vcs.Bitbucket,- Ref: ref,- Before: change.Old.Target.Hash,- After: change.New.Target.Hash,- RepositoryID: pushEvent.Repository.FullName,- RepositoryURL: pushEvent.Repository.Links.HTML.Href,- RepositoryFullPath: pushEvent.Repository.FullName,- AuthorName: pushEvent.Actor.Nickname,- CommitList: commitList,- })- }- case vcs.AzureDevOps:- pushEvent := new(azure.ServiceHookCodePushEvent)- if err := json.Unmarshal(body, pushEvent); err != nil {- return echo.NewHTTPError(http.StatusBadRequest, "Malformed push event").SetInternal(err)- }-- // Validate presumptions.- // This shouldn't happen as we only setup webhook to receive push event, just in case.- if pushEvent.EventType != "git.push" {- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Presumption failed: invalid webhook event type, got %s, want git.push", pushEvent.EventType))- }- // All the examples on https://learn.microsoft.com/en-us/azure/devops/service-hooks/events?view=azure-devops#code-pushed- // have only one ref update.- if len(pushEvent.Resource.RefUpdates) != 1 {- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Presumption failed: the number of ref updates is not 1, got %d", len(pushEvent.Resource.RefUpdates)))- }- if pushEvent.Resource.RefUpdates[0].NewObjectID == strings.Repeat("0", 40) {- // Users delete branch will trigger a push event, but the refUpdates.NewObjectID is all zero.- return c.String(http.StatusOK, "Do not process the push event which is generated by deleting branch")- }-- // Check webhook branch.- refUpdate := pushEvent.Resource.RefUpdates[0]- ok, err := isWebhookEventBranch(refUpdate.Name, vcsConnector.Payload.Branch)- if err != nil {- return err- }- if !ok {- return c.String(http.StatusOK, fmt.Sprintf("committed to branch %q, want branch %q", refUpdate, vcsConnector.Payload.Branch))- }-- // Squash commits.- oauthContext := &common.OauthContext{- AccessToken: vcsProvider.AccessToken,- }- if len(pushEvent.Resource.Commits) == 0 {- // If users merge one branch to our target branch, the commits list is empty in push event.- // And we cannot get the commits in range [refUpdates.oldObjectId, refUpdates.newObjectId] from Azure DevOps API.- // So, when the commit list is empty, we think it is generated by merge,- // then we need to query the queryPullRequest API to find out if the updateRef.newObjectId- // is the last commit of the Pull Request, and then we can use the PullRef.newObjectId API- // to find out if it is the last commit of the Pull Request. Request ID to list the corresponding commits.- probablePullRequests, err := azure.QueryPullRequest(ctx, oauthContext, vcsConnector.Payload.ExternalId, pushEvent.Resource.RefUpdates[0].NewObjectID)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to query pull request").SetInternal(err)- }- var filterOutPullRequestList []*azure.PullRequest- for _, pullRequest := range probablePullRequests {- if pullRequest.Status != "completed" {- continue- }- // We only handle the pull request which is merged to the target branch.- // NOTE: here we should compare with the refUpdates.Name instead of the repository.branch.- if pullRequest.TargetRefName != pushEvent.Resource.RefUpdates[0].Name {- continue- }- filterOutPullRequestList = append(filterOutPullRequestList, pullRequest)- }-- if len(filterOutPullRequestList) == 0 {- return echo.NewHTTPError(http.StatusOK, "No pull request matched")- }- if len(filterOutPullRequestList) != 1 {- return echo.NewHTTPError(http.StatusInternalServerError, errors.Errorf("Expected only one pull request, but got %d, content: %+v", len(filterOutPullRequestList), filterOutPullRequestList).Error())- }- // We should backfill the commit list by the commits in the pull request.- pullRequest := filterOutPullRequestList[0]- commitsInPullRequest, err := azure.GetPullRequestCommits(ctx, oauthContext, vcsConnector.Payload.ExternalId, pullRequest.ID)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to get pull request commits").SetInternal(err)- }- pushEvent.Resource.Commits = commitsInPullRequest- }- // For Azure DevOps, if users create a new branch and push it to the remote. It will trigger a code push event,- // but do not contain any commits in the event. So we do not need to consider the case that the commit id is- // all zero.- for _, commit := range pushEvent.Resource.Commits {- if commit.CommitID == strings.Repeat("0", 40) {- return echo.NewHTTPError(http.StatusBadRequest, "Presumption failed: the commit id is all zero")- }- }- // Azure DevOps' service hook does not contain the file diff information for each commit, so we need to backfill- // the file diff information by ourselves.- // We will use the previous commit id as the base commit id and the current commit id as the target commit id to- // get the file diff information commit by commit. We use the oldObjectId in resources.refUpdates as the base commit id- // for the first commit.- // NOTE: We presume that the sequence of the commits in the code push event is the reverse order of the commit sequence(aka. stack sequence, commit first, appear last) in the repository.- var backfillCommits []vcs.Commit- for _, commit := range pushEvent.Resource.Commits {- changes, err := azure.GetChangesByCommit(ctx, oauthContext, vcsConnector.Payload.ExternalId, commit.CommitID)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to get changes by commit %q", commit.CommitID)).SetInternal(err)- }-- var addedList, modifiedList []string- for _, change := range changes.Changes {- switch change.ChangeType {- case "add":- addedList = append(addedList, change.Item.Path)- case "edit":- modifiedList = append(modifiedList, change.Item.Path)- case "rename":- // To be consistent with VCS, we treat rename as delete + add, but we do not need to handle delete here.- addedList = append(addedList, change.Item.Path)- }- }-- backfillCommits = append(backfillCommits, vcs.Commit{- ID: commit.CommitID,- Title: commit.Comment,- Message: commit.Comment,- CreatedTs: commit.Author.Date.Unix(),- URL: commit.URL,- AuthorName: commit.Author.Name,- AuthorEmail: commit.Author.Email,- AddedList: addedList,- ModifiedList: modifiedList,- })- }- if len(backfillCommits) == 1 && len(backfillCommits[0].AddedList) == 1 && strings.HasSuffix(backfillCommits[0].AddedList[0], azure.SQLReviewPipelineFilePath) {- slog.Debug("start to setup pipeline", slog.String("repository", vcsConnector.Payload.ExternalId))- // Use workspaceID instead of repo secret as SQL review pipeline token, so that we don't need to re-create the pipeline if users disable then enable the CI.- workspaceID, err := s.store.GetWorkspaceID(ctx)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to get workspace id with error").SetInternal(err)- }- // Setup SQL review pipeline and policy.- if err := azure.EnableSQLReviewCI(ctx, oauthContext, vcsConnector.Payload.Title, vcsConnector.Payload.ExternalId, vcsConnector.Payload.Branch, workspaceID); err != nil {- slog.Error("failed to setup pipeline", log.BBError(err), slog.String("repository", vcsConnector.Payload.ExternalId))- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to setup SQL review pipeline").SetInternal(err)- }- return c.String(http.StatusOK, "OK")- }-- // Backfill web url for commits.- if pushEvent.Resource.PushID != 0 {- commitsInPush, err := azure.GetPushCommitsByPushID(ctx, oauthContext, vcsConnector.Payload.ExternalId, pushEvent.Resource.PushID)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to get push commits by push id %d", pushEvent.Resource.PushID)).SetInternal(err)- }- // Convert values to map from commitID to remote url.- commitID2Value := make(map[string]string)- for _, value := range commitsInPush.Value {- commitID2Value[value.CommitID] = value.RemoteURL- }- for i := range backfillCommits {- if remoteURL, ok := commitID2Value[backfillCommits[i].ID]; ok {- backfillCommits[i].URL = remoteURL- }- }- }-- baseVCSPushEvents = append(baseVCSPushEvents, vcs.PushEvent{- VCSType: vcs.AzureDevOps,- Ref: pushEvent.Resource.RefUpdates[0].Name,- Before: pushEvent.Resource.RefUpdates[0].OldObjectID,- After: pushEvent.Resource.RefUpdates[0].NewObjectID,- RepositoryID: vcsConnector.Payload.ExternalId,- RepositoryURL: vcsConnector.Payload.WebUrl,- RepositoryFullPath: vcsConnector.Payload.ExternalId,- AuthorName: pushEvent.Resource.PushedBy.DisplayName,- CommitList: backfillCommits,- })- }-- repo := &repoInfo{- repository: vcsConnector,- project: project,- vcs: vcsProvider,- }- oauthContext := &common.OauthContext{- AccessToken: vcsProvider.AccessToken,- }- var allCreatedMessages []string- for _, baseVCSPushEvent := range baseVCSPushEvents {- createdMessage, err := s.processPushEvent(ctx, oauthContext, repo, baseVCSPushEvent)- if err != nil {- return err- }- allCreatedMessages = append(allCreatedMessages, createdMessage)- }- return c.String(http.StatusOK, strings.Join(allCreatedMessages, "\n"))+ return nil})}-type repoInfo struct {- repository *store.VCSConnectorMessage- project *store.ProjectMessage- vcs *store.VCSProviderMessage-}--func isWebhookEventBranch(pushEventRef, wantBranch string) (bool, error) {- branch, err := parseBranchNameFromRefs(pushEventRef)- if err != nil {- return false, echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid ref: %s", pushEventRef)).SetInternal(err)- }- if branch != wantBranch {- slog.Debug("Skipping repo due to branch filter mismatch", slog.String("branch", branch), slog.String("wantBranch", wantBranch))- return false, nil- }- return true, nil-}-// validateGitHubWebhookSignature256 returns true if the signature matches the// HMAC hex digested SHA256 hash of the body using the given key.func validateGitHubWebhookSignature256(signature, key string, body []byte) (bool, error) {@@ -487,619 +120,6 @@ func validateGitHubWebhookSignature256(signature, key string, body []byte) (boolreturn subtle.ConstantTimeCompare([]byte(signature), []byte(got)) == 1, nil}-// parseBranchNameFromRefs parses the branch name from the refs field in the request.-// https://docs.github.com/en/rest/git/refs-// https://docs.gitlab.com/ee/user/project/integrations/webhook_events.html#push-events-func parseBranchNameFromRefs(ref string) (string, error) {- expectedPrefix := "refs/heads/"- if !strings.HasPrefix(ref, expectedPrefix) || len(expectedPrefix) == len(ref) {- slog.Debug(- "ref is not prefix with expected prefix",- slog.String("ref", ref),- slog.String("expected prefix", expectedPrefix),- )- return ref, errors.Errorf("unexpected ref name %q without prefix %q", ref, expectedPrefix)- }- return ref[len(expectedPrefix):], nil-}--func (s *Service) processPushEvent(ctx context.Context, oauthContext *common.OauthContext, repo *repoInfo, pushEvent vcs.PushEvent) (string, error) {- pushEvent.VCSType = repo.vcs.Type- distinctFileList := pushEvent.GetDistinctFileList()- if len(distinctFileList) == 0 {- var commitIDs []string- for _, c := range pushEvent.CommitList {- commitIDs = append(commitIDs, c.ID)- }- slog.Warn("No files found from the push event",- slog.String("repoURL", pushEvent.RepositoryURL),- slog.String("repoName", pushEvent.RepositoryFullPath),- slog.String("commits", strings.Join(commitIDs, ",")))- return "", nil- }-- filteredDistinctFileList, err := func() ([]vcs.DistinctFileItem, error) {- // The before commit ID is all zeros when the branch is just created and contains no commits yet.- if pushEvent.Before == strings.Repeat("0", 40) {- return distinctFileList, nil- }- return filterFilesByCommitsDiff(ctx, oauthContext, repo, distinctFileList, pushEvent.Before, pushEvent.After)- }()- if err != nil {- return "", errors.Wrapf(err, "failed to filtered distinct files by commits diff")- }-- fileItemList := getFileInfoList(filteredDistinctFileList, repo)-- var migrationDetailList []*migrationDetail- var activityCreateList []*store.ActivityMessage- var createdIssueList []string- var fileNameList []string-- creatorID := s.getIssueCreatorID(ctx, pushEvent.CommitList[0].AuthorEmail)- for _, fileInfo := range fileItemList {- // This is a migration-based DDL or DML file.- migrationDetailListForFile, activityCreateListForFile := s.prepareIssueFromFile(ctx, oauthContext, repo, pushEvent, fileInfo)- activityCreateList = append(activityCreateList, activityCreateListForFile...)- migrationDetailList = append(migrationDetailList, migrationDetailListForFile...)- if len(migrationDetailListForFile) != 0 {- fileNameList = append(fileNameList, strings.TrimPrefix(fileInfo.item.FileName, repo.repository.Payload.BaseDirectory+"/"))- }- }- if len(migrationDetailList) == 0 {- return "", nil- }-- // Create one issue per push event for DDL project, or non-schema files for SDL project.- migrateType := "Change data"- for _, d := range migrationDetailList {- if d.migrationType == db.Migrate {- migrateType = "Alter schema"- break- }- }- description := strings.ReplaceAll(fileItemList[0].migrationInfo.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, repo.project, issueName, issueDescription, pushEvent, creatorID, migrationDetailList); err != nil {- return "", echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to create issue %s, error %v", issueName, err)).SetInternal(err)- }-- for _, activityCreate := range activityCreateList {- if _, err := s.activityManager.CreateActivity(ctx, activityCreate, &activity.Metadata{}); err != nil {- slog.Warn("Failed to create project activity for the ignored repository files", log.BBError(err))- }- }- return fmt.Sprintf("Created issue %q from push event", strings.Join(createdIssueList, ",")), nil-}--// Users may merge commits from other branches,-// and some of the commits merged in may already be merged into the main branch.-// In that case, the commits in the push event contains files which are not added in this PR/MR.-// We use the compare API to get the file diffs and filter files by the diffs.-// TODO(dragonly): generate distinct file change list from the commits diff instead of filter.-func filterFilesByCommitsDiff(- ctx context.Context,- oauthContext *common.OauthContext,- repoInfo *repoInfo,- distinctFileList []vcs.DistinctFileItem,- beforeCommit, afterCommit string,-) ([]vcs.DistinctFileItem, error) {- fileDiffList, err := vcs.Get(repoInfo.vcs.Type, vcs.ProviderConfig{}).GetDiffFileList(- ctx,- oauthContext,- repoInfo.vcs.InstanceURL,- repoInfo.repository.Payload.ExternalId,- beforeCommit,- afterCommit,- )- if err != nil {- return nil, errors.WithMessagef(err, "failed to get file diff list for repository %s", repoInfo.repository.Payload.ExternalId)- }- var filteredDistinctFileList []vcs.DistinctFileItem- for _, file := range distinctFileList {- for _, diff := range fileDiffList {- if file.FileName == diff.Path {- filteredDistinctFileList = append(filteredDistinctFileList, file)- break- }- }- }- return filteredDistinctFileList, nil-}--type fileInfo struct {- item vcs.DistinctFileItem- migrationInfo *db.MigrationInfo-}--func getFileInfoList(distinctFileList []vcs.DistinctFileItem, repo *repoInfo) []fileInfo {- var result []fileInfo- for _, item := range distinctFileList {- slog.Debug("Processing file", slog.String("file", item.FileName), slog.String("commit", item.Commit.ID))- var migrationInfo *db.MigrationInfo- if filepath.Dir(item.FileName) != repo.repository.Payload.BaseDirectory {- continue- }- filename := filepath.Base(item.FileName)- if filepath.Ext(filename) != ".sql" {- continue- }- filename = strings.TrimSuffix(filename, filepath.Ext(filename))- re := regexp.MustCompile(`^[0-9]+`)- matches := re.FindAllString(filename, -1)- if len(matches) == 0 {- 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- }- 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,- }- result = append(result, fileInfo{- item: item,- migrationInfo: migrationInfo,- })- }- sort.Slice(result, func(i, j int) bool {- mi := result[i].migrationInfo- mj := result[j].migrationInfo- return mi.Version.Version < mj.Version.Version- })- return result-}--func (s *Service) createIssueFromMigrationDetailsV2(ctx context.Context, project *store.ProjectMessage, issueName, issueDescription string, pushEvent vcs.PushEvent, creatorID int, migrationDetailList []*migrationDetail) error {- user, err := s.store.GetUserByID(ctx, creatorID)- if err != nil {- return errors.Wrapf(err, "failed to get user %v", creatorID)- }-- var steps []*v1pb.Plan_Step-- 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 {- 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,- },- },- })- }- for _, step := range allSteps {- if step != nil && len(step.Specs) > 0 {- steps = append(steps, step)- }- }- childCtx := context.WithValue(ctx, common.PrincipalIDContextKey, creatorID)- childCtx = context.WithValue(childCtx, common.UserContextKey, user)- childCtx = context.WithValue(childCtx, common.LoopbackContextKey, true)- plan, err := s.rolloutService.CreatePlan(childCtx, &v1pb.CreatePlanRequest{- Parent: fmt.Sprintf("projects/%s", project.ResourceID),- Plan: &v1pb.Plan{- Title: issueName,- Steps: steps,- },- })- if err != nil {- return errors.Wrapf(err, "failed to create plan")- }- issue, err := s.issueService.CreateIssue(childCtx, &v1pb.CreateIssueRequest{- Parent: fmt.Sprintf("projects/%s", project.ResourceID),- Issue: &v1pb.Issue{- Title: issueName,- Description: issueDescription,- Type: v1pb.Issue_DATABASE_CHANGE,- Assignee: fmt.Sprintf("users/%s", api.SystemBotEmail),- Plan: plan.Name,- },- })- if err != nil {- return errors.Wrapf(err, "failed to create issue")- }- if _, err := s.rolloutService.CreateRollout(childCtx, &v1pb.CreateRolloutRequest{- Parent: fmt.Sprintf("projects/%s", project.ResourceID),- Rollout: &v1pb.Rollout{- Plan: plan.Name,- },- }); err != nil {- return errors.Wrapf(err, "failed to create rollout")- }-- issueUID, err := strconv.Atoi(issue.Uid)- if err != nil {- return err- }- // Create a project activity after successfully creating the issue from the push event.- activityPayload, err := json.Marshal(- api.ActivityProjectRepositoryPushPayload{- VCSPushEvent: pushEvent,- IssueID: issueUID,- IssueName: issue.Title,- },- )- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to construct activity payload").SetInternal(err)- }-- activityCreate := &store.ActivityMessage{- CreatorUID: creatorID,- ResourceContainer: project.GetName(),- ContainerUID: project.UID,- Type: api.ActivityProjectRepositoryPush,- Level: api.ActivityInfo,- Comment: fmt.Sprintf("Created issue %q.", issue.Title),- Payload: string(activityPayload),- }- if _, err := s.activityManager.CreateActivity(ctx, activityCreate, &activity.Metadata{}); err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to create project activity after creating issue from repository push event: %d", issueUID)).SetInternal(err)- }-- return nil-}--func getChangeType(migrationType db.MigrationType) v1pb.Plan_ChangeDatabaseConfig_Type {- switch migrationType {- case db.Baseline:- return v1pb.Plan_ChangeDatabaseConfig_BASELINE- case db.Migrate:- return v1pb.Plan_ChangeDatabaseConfig_MIGRATE- case db.MigrateSDL:- return v1pb.Plan_ChangeDatabaseConfig_MIGRATE_SDL- case db.Data:- return v1pb.Plan_ChangeDatabaseConfig_DATA- }- return v1pb.Plan_ChangeDatabaseConfig_TYPE_UNSPECIFIED-}--func (s *Service) getIssueCreatorID(ctx context.Context, email string) int {- creatorID := api.SystemBotID- if email != "" {- committerPrincipal, err := s.store.GetUser(ctx, &store.FindUserMessage{- Email: &email,- })- if err != nil {- slog.Warn("Failed to find the principal with committer email, use system bot instead", slog.String("email", email), log.BBError(err))- } else if committerPrincipal == nil {- slog.Info("Principal with committer email does not exist, use system bot instead", slog.String("email", email))- } else {- creatorID = committerPrincipal.ID- }- }- return creatorID-}--func (s *Service) findProjectDatabases(ctx context.Context, projectID int) ([]*store.DatabaseMessage, error) {- // Retrieve the current schema from the database- project, err := s.store.GetProjectV2(ctx, &store.FindProjectMessage{UID: &projectID})- if err != nil {- return nil, err- }- if project == nil {- return nil, errors.Errorf("project %d not found", projectID)- }- // 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.- databases, err := s.store.ListDatabases(ctx,- &store.FindDatabaseMessage{- ProjectID: &project.ResourceID,- },- )- if err != nil {- return nil, errors.Wrap(err, "find database")- }- return databases, nil-}--// getIgnoredFileActivityCreate get a warning project activityCreate for the ignored file with given error.-func getIgnoredFileActivityCreate(project *store.ProjectMessage, pushEvent vcs.PushEvent, file string, err error) *store.ActivityMessage {- payload, marshalErr := json.Marshal(- api.ActivityProjectRepositoryPushPayload{- VCSPushEvent: pushEvent,- },- )- if marshalErr != nil {- slog.Warn("Failed to construct project activity payload for the ignored repository file",- log.BBError(marshalErr),- )- return nil- }-- return &store.ActivityMessage{- CreatorUID: api.SystemBotID,- ResourceContainer: project.GetName(),- ContainerUID: project.UID,- Type: api.ActivityProjectRepositoryPush,- Level: api.ActivityWarn,- Comment: fmt.Sprintf("Ignored file %q, %v.", file, err),- Payload: string(payload),- }-}--// readFileContent reads the content of the given file from the given repository.-func readFileContent(ctx context.Context, oauthContext *common.OauthContext, pushEvent vcs.PushEvent, repo *repoInfo, file string) (string, error) {- content, err := vcs.Get(repo.vcs.Type, vcs.ProviderConfig{}).ReadFileContent(- ctx,- oauthContext,- repo.vcs.InstanceURL,- repo.repository.Payload.ExternalId,- file,- vcs.RefInfo{- RefType: vcs.RefTypeCommit,- RefName: pushEvent.CommitList[len(pushEvent.CommitList)-1].ID,- },- )- if err != nil {- return "", errors.Wrap(err, "read content")- }- return content, nil-}--// prepareIssueFromFile returns a list of update schema details derived-// from the given push event for DDL.-func (s *Service) prepareIssueFromFile(- ctx context.Context,- oauthContext *common.OauthContext,- repoInfo *repoInfo,- pushEvent vcs.PushEvent,- fileInfo fileInfo,-) ([]*migrationDetail, []*store.ActivityMessage) {- content, err := readFileContent(ctx, oauthContext, pushEvent, repoInfo, fileInfo.item.FileName)- if err != nil {- return nil, []*store.ActivityMessage{- getIgnoredFileActivityCreate(- repoInfo.project,- pushEvent,- fileInfo.item.FileName,- errors.Wrap(err, "Failed to read file content"),- ),- }- }-- sheetPayload := &storepb.SheetPayload{- VcsPayload: &storepb.SheetPayload_VCSPayload{- PushEvent: utils.ConvertVcsPushEvent(&pushEvent),- },- }-- 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}- }-- if fileInfo.item.ItemType == vcs.FileItemTypeAdded {- 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}- }-- var migrationDetailList []*migrationDetail- for _, database := range databases {- migrationDetailList = append(migrationDetailList,- &migrationDetail{- migrationType: fileInfo.migrationInfo.Type,- databaseID: database.UID,- sheetID: sheet.UID,- schemaVersion: model.Version{Version: fmt.Sprintf("%s-%s", fileInfo.migrationInfo.Version.Version, fileInfo.migrationInfo.Type.GetVersionTypeSuffix())},- },- )- }- return migrationDetailList, nil- }-- migrationVersion := fmt.Sprintf("%s-%s", fileInfo.migrationInfo.Version.Version, fileInfo.migrationInfo.Type.GetVersionTypeSuffix())- if err := s.tryUpdateTasksFromModifiedFile(ctx, databases, fileInfo.item.FileName, migrationVersion, content, pushEvent); err != nil {- return nil, []*store.ActivityMessage{- getIgnoredFileActivityCreate(- repoInfo.project,- pushEvent,- fileInfo.item.FileName,- errors.Wrap(err, "Failed to find project task"),- ),- }- }- return nil, nil-}--func (s *Service) tryUpdateTasksFromModifiedFile(ctx context.Context, databases []*store.DatabaseMessage, fileName, schemaVersion, statement string, pushEvent vcs.PushEvent) error {- // For modified files, we try to update the existing issue's statement.- for _, database := range databases {- taskList, err := s.store.ListTasks(ctx, &api.TaskFind{- DatabaseID: &database.UID,- LatestTaskRunStatusList: &[]api.TaskRunStatus{api.TaskRunNotStarted, api.TaskRunFailed},- TypeList: &[]api.TaskType{api.TaskDatabaseSchemaUpdate, api.TaskDatabaseDataUpdate},- Payload: fmt.Sprintf("task.payload->>'schemaVersion' = '%s'", schemaVersion),- })- if err != nil {- return err- }- if len(taskList) == 0 {- continue- }- if len(taskList) > 1 {- slog.Error("Found more than one pending approval or failed tasks for modified VCS file, should be only one task.", slog.Int("databaseID", database.UID), slog.String("schemaVersion", schemaVersion))- return nil- }- task := taskList[0]- issue, err := s.store.GetIssueV2(ctx, &store.FindIssueMessage{PipelineID: &task.PipelineID})- if err != nil {- slog.Error("failed to get issue by pipeline ID", slog.Int("pipeline ID", task.PipelineID), log.BBError(err))- return nil- }- if issue == nil {- slog.Error("issue not found by pipeline ID", slog.Int("pipeline ID", task.PipelineID))- return nil- }-- sheetPayload := &storepb.SheetPayload{- VcsPayload: &storepb.SheetPayload_VCSPayload{- PushEvent: utils.ConvertVcsPushEvent(&pushEvent),- },- }- sheet, err := s.store.CreateSheet(ctx, &store.SheetMessage{- CreatorID: api.SystemBotID,- ProjectUID: issue.Project.UID,- Title: fileName,- Statement: statement,- Payload: sheetPayload,- })- if err != nil {- return err- }-- // TODO(dragonly): Try to patch the failed migration history record to pending, and the statement to the current modified file content.- slog.Debug("Patching task for modified file VCS push event", slog.String("fileName", fileName), slog.Int("issueID", issue.UID), slog.Int("taskID", task.ID))- taskPatch := api.TaskPatch{- ID: task.ID,- SheetID: &sheet.UID,- UpdaterID: api.SystemBotID,- }- if err := patchTask(ctx, s.store, s.activityManager, task, &taskPatch, issue); err != nil {- slog.Error("Failed to patch task with the same migration version", slog.Int("issueID", issue.UID), slog.Int("taskID", task.ID), log.BBError(err))- return nil- }-- if issue.PlanUID != nil {- plan, err := s.store.GetPlan(ctx, &store.FindPlanMessage{UID: issue.PlanUID})- if err != nil {- slog.Error("failed to get plan", slog.Int64("plan ID", *issue.PlanUID), log.BBError(err))- }- for _, step := range plan.Config.Steps {- for _, spec := range step.Specs {- v, ok := spec.Config.(*storepb.PlanConfig_Spec_ChangeDatabaseConfig)- if !ok {- continue- }- if v.ChangeDatabaseConfig.SchemaVersion == schemaVersion && v.ChangeDatabaseConfig.Target == common.FormatDatabase(database.InstanceID, database.DatabaseName) {- v.ChangeDatabaseConfig.Sheet = fmt.Sprintf("projects/%s/sheets/%d", issue.Project.ResourceID, sheet.UID)- }- }- }- if err := s.store.UpdatePlan(ctx, &store.UpdatePlanMessage{- UID: *issue.PlanUID,- Config: plan.Config,- UpdaterID: api.SystemBotID,- }); err != nil {- slog.Error("failed to update plan", slog.Int64("plan ID", *issue.PlanUID), log.BBError(err))- }- }-- // dismiss stale review, re-find the approval template- // it's ok if we failed- if err := func() error {- issue, err := s.store.UpdateIssueV2(ctx, issue.UID, &store.UpdateIssueMessage{- PayloadUpsert: &storepb.IssuePayload{- Approval: &storepb.IssuePayloadApproval{- ApprovalFindingDone: false,- },- },- }, api.SystemBotID)- if err != nil {- return errors.Wrap(err, "failed to update issue payload")- }- s.stateCfg.ApprovalFinding.Store(issue.UID, issue)- return nil- }(); err != nil {- slog.Error("Failed to dismiss stale review", log.BBError(err))- }- }- return nil-}--// patchTask patches the statement for a task.-func patchTask(ctx context.Context, stores *store.Store, activityManager *activity.Manager, task *store.TaskMessage, taskPatch *api.TaskPatch, issue *store.IssueMessage) error {- taskPatched, err := stores.UpdateTaskV2(ctx, taskPatch)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to update task \"%v\"", task.Name)).SetInternal(err)- }- if taskPatch.SheetID != nil {- oldSheetID, err := utils.GetTaskSheetID(task.Payload)- if err != nil {- return errors.Wrap(err, "failed to get old sheet ID")- }- newSheetID := *taskPatch.SheetID-- // create a task sheet update activity- payload, err := json.Marshal(api.ActivityPipelineTaskStatementUpdatePayload{- TaskID: taskPatched.ID,- OldSheetID: oldSheetID,- NewSheetID: newSheetID,- TaskName: task.Name,- IssueName: issue.Title,- })- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create activity after updating task sheet: %v", taskPatched.Name).SetInternal(err)- }- if _, err := activityManager.CreateActivity(ctx, &store.ActivityMessage{- CreatorUID: taskPatch.UpdaterID,- ResourceContainer: issue.Project.GetName(),- ContainerUID: taskPatched.PipelineID,- Type: api.ActivityPipelineTaskStatementUpdate,- Payload: string(payload),- Level: api.ActivityInfo,- }, &activity.Metadata{- Issue: issue,- }); err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to create activity after updating task statement: %v", taskPatched.Name)).SetInternal(err)- }- }- return nil-}-func (s *Service) createIssueFromPRInfo(ctx context.Context, project *store.ProjectMessage, prInfo *pullRequestInfo) error {creatorID := api.SystemBotIDuser, err := s.store.GetUser(ctx, &store.FindUserMessage{Email: &prInfo.email})diff --git a/backend/api/gitops/webhook_test.go b/backend/api/gitops/webhook_test.goindex d601ddd0de..b662ec77d9 100644--- a/backend/api/gitops/webhook_test.go+++ b/backend/api/gitops/webhook_test.go@@ -6,7 +6,6 @@ import ("github.com/stretchr/testify/assert")-// TODO(d): fix the double underscore "__".func TestValidateGitHubWebhookSignature256(t *testing.T) {// nolint:misspellconst payload = `{"ref":"refs/heads/main","before":"07da1e122bdbb81da8499b6d82c6b6302581a5a7","after":"5a96148ac5ef11a53b838b8cc0d9c929420657f3","repository":{"id":470746482,"node_id":"R_kgDOHA8Fcg","name":"bytebase-test","full_name":"unknwon/bytebase-test","private":true,"owner":{"name":"unknwon","email":"[email protected]","login":"unknwon","id":2946214,"node_id":"MDQ6VXNlcjI5NDYyMTQ=","avatar_url":"https://avatars.githubusercontent.com/u/2946214?v=4","gravatar_id":"","url":"https://api.github.com/users/unknwon","html_url":"https://github.com/unknwon","followers_url":"https://api.github.com/users/unknwon/followers","following_url":"https://api.github.com/users/unknwon/following{/other_user}","gists_url":"https://api.github.com/users/unknwon/gists{/gist_id}","starred_url":"https://api.github.com/users/unknwon/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/unknwon/subscriptions","organizations_url":"https://api.github.com/users/unknwon/orgs","repos_url":"https://api.github.com/users/unknwon/repos","events_url":"https://api.github.com/users/unknwon/events{/privacy}","received_events_url":"https://api.github.com/users/unknwon/received_events","type":"User","site_admin":false},"html_url":"https://github.com/unknwon/bytebase-test","description":null,"fork":false,"url":"https://github.com/unknwon/bytebase-test","forks_url":"https://api.github.com/repos/unknwon/bytebase-test/forks","keys_url":"https://api.github.com/repos/unknwon/bytebase-test/keys{/key_id}","collaborators_url":"https://api.github.com/repos/unknwon/bytebase-test/collaborators{/collaborator}","teams_url":"https://api.github.com/repos/unknwon/bytebase-test/teams","hooks_url":"https://api.github.com/repos/unknwon/bytebase-test/hooks","issue_events_url":"https://api.github.com/repos/unknwon/bytebase-test/issues/events{/number}","events_url":"https://api.github.com/repos/unknwon/bytebase-test/events","assignees_url":"https://api.github.com/repos/unknwon/bytebase-test/assignees{/user}","branches_url":"https://api.github.com/repos/unknwon/bytebase-test/branches{/branch}","tags_url":"https://api.github.com/repos/unknwon/bytebase-test/tags","blobs_url":"https://api.github.com/repos/unknwon/bytebase-test/git/blobs{/sha}","git_tags_url":"https://api.github.com/repos/unknwon/bytebase-test/git/tags{/sha}","git_refs_url":"https://api.github.com/repos/unknwon/bytebase-test/git/refs{/sha}","trees_url":"https://api.github.com/repos/unknwon/bytebase-test/git/trees{/sha}","statuses_url":"https://api.github.com/repos/unknwon/bytebase-test/statuses/{sha}","languages_url":"https://api.github.com/repos/unknwon/bytebase-test/languages","stargazers_url":"https://api.github.com/repos/unknwon/bytebase-test/stargazers","contributors_url":"https://api.github.com/repos/unknwon/bytebase-test/contributors","subscribers_url":"https://api.github.com/repos/unknwon/bytebase-test/subscribers","subscription_url":"https://api.github.com/repos/unknwon/bytebase-test/subscription","commits_url":"https://api.github.com/repos/unknwon/bytebase-test/commits{/sha}","git_commits_url":"https://api.github.com/repos/unknwon/bytebase-test/git/commits{/sha}","comments_url":"https://api.github.com/repos/unknwon/bytebase-test/comments{/number}","issue_comment_url":"https://api.github.com/repos/unknwon/bytebase-test/issues/comments{/number}","contents_url":"https://api.github.com/repos/unknwon/bytebase-test/contents/{+path}","compare_url":"https://api.github.com/repos/unknwon/bytebase-test/compare/{base}...{head}","merges_url":"https://api.github.com/repos/unknwon/bytebase-test/merges","archive_url":"https://api.github.com/repos/unknwon/bytebase-test/{archive_format}{/ref}","downloads_url":"https://api.github.com/repos/unknwon/bytebase-test/downloads","issues_url":"https://api.github.com/repos/unknwon/bytebase-test/issues{/number}","pulls_url":"https://api.github.com/repos/unknwon/bytebase-test/pulls{/number}","milestones_url":"https://api.github.com/repos/unknwon/bytebase-test/milestones{/number}","notifications_url":"https://api.github.com/repos/unknwon/bytebase-test/notifications{?since,all,participating}","labels_url":"https://api.github.com/repos/unknwon/bytebase-test/labels{/name}","releases_url":"https://api.github.com/repos/unknwon/bytebase-test/releases{/id}","deployments_url":"https://api.github.com/repos/unknwon/bytebase-test/deployments","created_at":1647463607,"updated_at":"2022-03-16T20:46:47Z","pushed_at":1658671596,"git_url":"git://github.com/unknwon/bytebase-test.git","ssh_url":"[email protected]:unknwon/bytebase-test.git","clone_url":"https://github.com/unknwon/bytebase-test.git","svn_url":"https://github.com/unknwon/bytebase-test","homepage":null,"size":20,"stargazers_count":0,"watchers_count":0,"language":null,"has_issues":true,"has_projects":true,"has_downloads":true,"has_wiki":true,"has_pages":false,"forks_count":0,"mirror_url":null,"archived":false,"disabled":false,"open_issues_count":0,"license":{"key":"apache-2.0","name":"Apache License 2.0","spdx_id":"Apache-2.0","url":"https://api.github.com/licenses/apache-2.0","node_id":"MDc6TGljZW5zZTI="},"allow_forking":true,"is_template":false,"web_commit_signoff_required":false,"topics":[],"visibility":"private","forks":0,"open_issues":0,"watchers":0,"default_branch":"main","stargazers":0,"master_branch":"main"},"pusher":{"name":"unknwon","email":"[email protected]"},"sender":{"login":"unknwon","id":2946214,"node_id":"MDQ6VXNlcjI5NDYyMTQ=","avatar_url":"https://avatars.githubusercontent.com/u/2946214?v=4","gravatar_id":"","url":"https://api.github.com/users/unknwon","html_url":"https://github.com/unknwon","followers_url":"https://api.github.com/users/unknwon/followers","following_url":"https://api.github.com/users/unknwon/following{/other_user}","gists_url":"https://api.github.com/users/unknwon/gists{/gist_id}","starred_url":"https://api.github.com/users/unknwon/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/unknwon/subscriptions","organizations_url":"https://api.github.com/users/unknwon/orgs","repos_url":"https://api.github.com/users/unknwon/repos","events_url":"https://api.github.com/users/unknwon/events{/privacy}","received_events_url":"https://api.github.com/users/unknwon/received_events","type":"User","site_admin":false},"created":false,"deleted":false,"forced":false,"base_ref":null,"compare":"https://github.com/unknwon/bytebase-test/compare/07da1e122bdb...5a96148ac5ef","commits":[{"id":"5a96148ac5ef11a53b838b8cc0d9c929420657f3","tree_id":"8a842b23b62886d2ee12c152eda741cf39b1ceef","distinct":true,"message":"Create testdb_dev__202101131000__baseline__create_tablefoo_for_bar.sql","timestamp":"2022-07-24T22:06:36+08:00","url":"https://github.com/unknwon/bytebase-test/commit/5a96148ac5ef11a53b838b8cc0d9c929420657f3","author":{"name":"Joe Chen","email":"[email protected]","username":"unknwon"},"committer":{"name":"GitHub","email":"[email protected]","username":"web-flow"},"added":["Dev/testdb_dev__202101131000__baseline__create_tablefoo_for_bar.sql"],"removed":[],"modified":[]}],"head_commit":{"id":"5a96148ac5ef11a53b838b8cc0d9c929420657f3","tree_id":"8a842b23b62886d2ee12c152eda741cf39b1ceef","distinct":true,"message":"Create testdb_dev__202101131000__baseline__create_tablefoo_for_bar.sql","timestamp":"2022-07-24T22:06:36+08:00","url":"https://github.com/unknwon/bytebase-test/commit/5a96148ac5ef11a53b838b8cc0d9c929420657f3","author":{"name":"Joe Chen","email":"[email protected]","username":"unknwon"},"committer":{"name":"GitHub","email":"[email protected]","username":"web-flow"},"added":["Dev/testdb_dev__202101131000__baseline__create_tablefoo_for_bar.sql"],"removed":[],"modified":[]}}`@@ -41,40 +40,3 @@ func TestValidateGitHubWebhookSignature256(t *testing.T) {assert.NoError(t, err)})}--func TestParseBranchNameFromGitHubRefs(t *testing.T) {- tests := []struct {- refs string- expect string- err bool- }{- {- refs: "refs/heads/main",- expect: "main",- err: false,- },- {- refs: "refs/heads/feat/heads",- expect: "feat/heads",- err: false,- },- // Broken- {- refs: "ref",- err: true,- },- {- refs: "refs/heads/",- expect: "",- err: true,- },- }- for _, test := range tests {- branch, err := parseBranchNameFromRefs(test.refs)- if test.err {- assert.Error(t, err)- } else {- assert.Equal(t, test.expect, branch)- }- }-}diff --git a/backend/tests/schema_update_test.go b/backend/tests/schema_update_test.goindex 7d46541469..4df40a4141 100644--- a/backend/tests/schema_update_test.go+++ b/backend/tests/schema_update_test.go@@ -2,23 +2,17 @@ package testsimport ("context"- "encoding/json""fmt""strconv""strings""testing"- "time""github.com/google/go-cmp/cmp""github.com/google/uuid""github.com/stretchr/testify/require""google.golang.org/protobuf/testing/protocmp"- "google.golang.org/protobuf/types/known/fieldmaskpb"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/resources/mysql""github.com/bytebase/bytebase/backend/resources/postgres""github.com/bytebase/bytebase/backend/tests/fake"@@ -71,7 +65,7 @@ func TestSchemaAndDataUpdate(t *testing.T) {Parent: ctl.project.Name,Sheet: &v1pb.Sheet{Title: "migration statement sheet",- Content: []byte(migrationStatement),+ Content: []byte(migrationStatement1),},})a.NoError(err)@@ -136,378 +130,6 @@ func TestSchemaAndDataUpdate(t *testing.T) {}}-func TestSimpleVCS(t *testing.T) {- tests := []struct {- name string- vcsProviderCreator fake.VCSProviderCreator- vcsType v1pb.VCSProvider_Type- externalID string- repositoryFullPath string- newWebhookPushEvent func(added, modified [][]string, beforeSHA, afterSHA string) any- }{- {- 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.- test := test- t.Run(test.name, func(t *testing.T) {- t.Parallel()-- a := require.New(t)- ctx := context.Background()- ctl := &controller{}- ctx, err := ctl.StartServerWithExternalPg(ctx, &config{- dataDir: t.TempDir(),- vcsProviderCreator: test.vcsProviderCreator,- })- a.NoError(err)- defer func() {- _ = ctl.Close(ctx)- }()-- // Create a VCS.- evcs, err := ctl.evcsClient.CreateVCSProvider(ctx, &v1pb.CreateVCSProviderRequest{- VcsProvider: &v1pb.VCSProvider{- Title: t.Name(),- Type: test.vcsType,- Url: ctl.vcsURL,- AccessToken: "testApplicationSecret",- },- VcsProviderId: strings.ToLower(test.vcsType.String()),- })- a.NoError(err)- // Create a repository.- ctl.vcsProvider.CreateRepository(test.externalID)- // Create the branch- err = ctl.vcsProvider.CreateBranch(test.externalID, "feature/foo")- a.NoError(err)-- oldVcsConnector, err := ctl.vcsConnectorServiceClient.CreateVCSConnector(ctx, &v1pb.CreateVCSConnectorRequest{- Parent: ctl.project.Name,- VcsConnector: &v1pb.VCSConnector{- VcsProvider: evcs.Name,- Title: "Test VCS Connector",- FullPath: test.repositoryFullPath,- WebUrl: fmt.Sprintf("%s/%s", ctl.vcsURL, test.repositoryFullPath),- Branch: "feature/foo",- BaseDirectory: baseDirectory + "+invalid",- ExternalId: test.externalID,- },- VcsConnectorId: "default",- })- a.NoError(err)- vcsConnector, err := ctl.vcsConnectorServiceClient.UpdateVCSConnector(ctx, &v1pb.UpdateVCSConnectorRequest{- VcsConnector: &v1pb.VCSConnector{- Name: oldVcsConnector.Name,- BaseDirectory: baseDirectory,- },- UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"base_directory"}},- })- a.NoError(err)- a.Equal(baseDirectory, vcsConnector.BaseDirectory)-- // Provision an instance.- instanceName := "testInstance1"- instanceDir, err := ctl.provisionSQLiteInstance(t.TempDir(), instanceName)- a.NoError(err)-- instance, err := ctl.instanceServiceClient.CreateInstance(ctx, &v1pb.CreateInstanceRequest{- InstanceId: generateRandomString("instance", 10),- Instance: &v1pb.Instance{- Title: instanceName,- Engine: v1pb.Engine_SQLITE,- Environment: "environments/prod",- Activation: true,- DataSources: []*v1pb.DataSource{{Type: v1pb.DataSourceType_ADMIN, Host: instanceDir, Id: "admin"}},- },- })- a.NoError(err)-- // Create an issue that creates a database.- databaseName := "testVCSSchemaUpdate"- err = ctl.createDatabaseV2(ctx, ctl.project, instance, nil /* environment */, databaseName, "", nil /* labelMap */)- a.NoError(err)-- database, err := ctl.databaseServiceClient.GetDatabase(ctx, &v1pb.GetDatabaseRequest{- Name: fmt.Sprintf("%s/databases/%s", instance.Name, databaseName),- })- a.NoError(err)-- // 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/0003##migrate##create_table_book3.sql"- err = ctl.vcsProvider.AddFiles(test.externalID, map[string]string{gitFile3: migrationStatement3})- a.NoError(err)- gitFile2 := "bbtest/0002##migrate##新建create_table_book2.sql"- err = ctl.vcsProvider.AddFiles(test.externalID, map[string]string{gitFile2: migrationStatement2})- a.NoError(err)- 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/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{- {Path: gitFile1, Type: vcs.FileDiffTypeAdded},- {Path: gitFile2, Type: vcs.FileDiffTypeAdded},- {Path: gitFile3, Type: vcs.FileDiffTypeAdded},- })- a.NoError(err)-- payload, err := json.Marshal(test.newWebhookPushEvent([][]string{{gitFile1}, {gitFile2}, {gitFile3}, {gitFileMergeFromOtherBranch}}, [][]string{nil, nil, nil, nil}, "1", "2"))- a.NoError(err)- err = ctl.vcsProvider.SendWebhookPush(test.externalID, payload)- a.NoError(err)-- // Get schema update issue.- issue, err := ctl.getLastOpenIssue(ctx, ctl.project)- a.NoError(err)- err = ctl.waitRollout(ctx, issue.Name, issue.Rollout)- a.NoError(err)- 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)-- // Query schema.- dbMetadata, err := ctl.databaseServiceClient.GetDatabaseSchema(ctx, &v1pb.GetDatabaseSchemaRequest{Name: fmt.Sprintf("%s/schema", database.Name)})- a.NoError(err)- a.Equal(want3BookSchema, dbMetadata.Schema)-- // Simulate Git commits for failed data update.- 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{- {Path: gitFile4, Type: vcs.FileDiffTypeAdded},- })- a.NoError(err)- payload, err = json.Marshal(test.newWebhookPushEvent([][]string{{gitFile4}}, [][]string{nil}, "2", "3"))- a.NoError(err)- err = ctl.vcsProvider.SendWebhookPush(test.externalID, payload)- a.NoError(err)-- // Get data update issue.- issue, err = ctl.getLastOpenIssue(ctx, ctl.project)- a.NoError(err)- err = ctl.waitRollout(ctx, issue.Name, issue.Rollout)- a.Error(err)-- // Simulate Git commits for a correct modified date update.- err = ctl.vcsProvider.AddFiles(test.externalID, map[string]string{gitFile4: dataUpdateStatement})- a.NoError(err)- err = ctl.vcsProvider.AddCommitsDiff(test.externalID, "3", "4", []vcs.FileDiff{- {Path: gitFile4, Type: vcs.FileDiffTypeModified},- })- a.NoError(err)- payload, err = json.Marshal(test.newWebhookPushEvent([][]string{nil}, [][]string{{gitFile4}}, "3", "4"))- a.NoError(err)- err = ctl.vcsProvider.SendWebhookPush(test.externalID, payload)- a.NoError(err)-- // TODO(d): waiting for approval finding to complete.- time.Sleep(2 * time.Second)- rollout, err := ctl.rolloutServiceClient.GetRollout(ctx, &v1pb.GetRolloutRequest{Name: issue.Rollout})- a.NoError(err)- a.Len(rollout.Stages, 1)- stage := rollout.Stages[0]- a.Len(stage.Tasks, 1)- task := stage.Tasks[0]- // simulate retrying the failed task.- _, err = ctl.rolloutServiceClient.BatchRunTasks(ctx, &v1pb.BatchRunTasksRequest{- Parent: fmt.Sprintf("%s/stages/-", rollout.Name),- Tasks: []string{task.Name},- })- a.NoError(err)-- err = ctl.waitRollout(ctx, issue.Name, issue.Rollout)- a.NoError(err)- 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)-- sheet, err := ctl.sheetServiceClient.CreateSheet(ctx, &v1pb.CreateSheetRequest{- Parent: ctl.project.Name,- Sheet: &v1pb.Sheet{- Title: "migration statement 4 sheet",- Content: []byte(migrationStatement4),- },- })- a.NoError(err)-- // Schema change from UI.- // Create an issue that updates database schema.- err = ctl.changeDatabase(ctx, ctl.project, database, sheet, v1pb.Plan_ChangeDatabaseConfig_MIGRATE)- a.NoError(err)-- // Get migration history.- resp, err := ctl.databaseServiceClient.ListChangeHistories(ctx, &v1pb.ListChangeHistoriesRequest{- Parent: database.Name,- View: v1pb.ChangeHistoryView_CHANGE_HISTORY_VIEW_FULL,- })- a.NoError(err)- histories := resp.ChangeHistories- wantHistories := []*v1pb.ChangeHistory{- {- Type: v1pb.ChangeHistory_MIGRATE,- Status: v1pb.ChangeHistory_DONE,- Schema: dumpedSchema4,- PrevSchema: dumpedSchema3,- },- {- Type: v1pb.ChangeHistory_DATA,- Status: v1pb.ChangeHistory_DONE,- Schema: dumpedSchema3,- PrevSchema: dumpedSchema3,- },- {- Type: v1pb.ChangeHistory_MIGRATE,- Status: v1pb.ChangeHistory_DONE,- Schema: dumpedSchema3,- PrevSchema: dumpedSchema2,- },- {- Type: v1pb.ChangeHistory_MIGRATE,- Status: v1pb.ChangeHistory_DONE,- Schema: dumpedSchema2,- PrevSchema: dumpedSchema,- },- {- Type: v1pb.ChangeHistory_MIGRATE,- Status: v1pb.ChangeHistory_DONE,- Schema: dumpedSchema,- PrevSchema: "",- },- }- a.Equal(len(wantHistories), len(histories))- for i, history := range histories {- got := &v1pb.ChangeHistory{- Type: history.Type,- Status: history.Status,- Schema: history.Schema,- PrevSchema: history.PrevSchema,- }- want := wantHistories[i]- a.Equal(got, want)- a.NotEqual(history.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)-- _, err = ctl.vcsConnectorServiceClient.DeleteVCSConnector(ctx, &v1pb.DeleteVCSConnectorRequest{Name: vcsConnector.Name})- a.NoError(err)- })- }-}-func TestGetLatestSchema(t *testing.T) {tests := []struct {name string@@ -787,7 +409,7 @@ func TestMarkTaskAsDone(t *testing.T) {Parent: ctl.project.Name,Sheet: &v1pb.Sheet{Title: "migration statement sheet",- Content: []byte(migrationStatement),+ Content: []byte(migrationStatement1),},})a.NoError(err)diff --git a/backend/tests/tenant_test.go b/backend/tests/tenant_test.goindex 9f8a6bcd5a..3d9070524b 100644--- a/backend/tests/tenant_test.go+++ b/backend/tests/tenant_test.go@@ -152,7 +152,7 @@ func TestTenant(t *testing.T) {Parent: project.Name,Sheet: &v1pb.Sheet{Title: "migration statement sheet",- Content: []byte(migrationStatement),+ Content: []byte(migrationStatement1),},})a.NoError(err)diff --git a/backend/tests/test-data/book_3_schema.result b/backend/tests/test-data/book_2_schema.resultsimilarity index 66%rename from backend/tests/test-data/book_3_schema.resultrename to backend/tests/test-data/book_2_schema.resultindex 19cfbcb327..a52d22210d 100644--- a/backend/tests/test-data/book_3_schema.result+++ b/backend/tests/test-data/book_2_schema.result@@ -6,7 +6,3 @@ CREATE TABLE book2 (id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT NULL);-CREATE TABLE book3 (- id INTEGER PRIMARY KEY AUTOINCREMENT,- name TEXT NULL- );diff --git a/backend/tests/tests.go b/backend/tests/tests.goindex 673cadb47c..2dc810236b 100644--- a/backend/tests/tests.go+++ b/backend/tests/tests.go@@ -36,7 +36,7 @@ import ()var (- migrationStatement = `+ migrationStatement1 = `CREATE TABLE book (id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT NULL@@ -46,25 +46,14 @@ var (id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT NULL);`- migrationStatement3 = `- CREATE TABLE book3 (- id INTEGER PRIMARY KEY AUTOINCREMENT,- name TEXT NULL- );`- migrationStatement4 = `- CREATE TABLE book4 (- id INTEGER PRIMARY KEY AUTOINCREMENT,- name TEXT NULL- );`//go:embed test-data/book_schema.resultwantBookSchema string- //go:embed test-data/book_3_schema.result- want3BookSchema string+ //go:embed test-data/book_2_schema.result+ want2BookSchema string- dataUpdateStatementWrong = "INSERT INTO book(name) xxx"- dataUpdateStatement = `+ dataUpdateStatement = `INSERT INTO book(name) VALUES("byte"),(NULL);@@ -83,36 +72,7 @@ CREATE TABLE book2 (name TEXT NULL);`- dumpedSchema3 = `CREATE TABLE book (- id INTEGER PRIMARY KEY AUTOINCREMENT,- name TEXT NULL- );-CREATE TABLE book2 (- id INTEGER PRIMARY KEY AUTOINCREMENT,- name TEXT NULL- );-CREATE TABLE book3 (- id INTEGER PRIMARY KEY AUTOINCREMENT,- name TEXT NULL- );-`- dumpedSchema4 = `CREATE TABLE book (- id INTEGER PRIMARY KEY AUTOINCREMENT,- name TEXT NULL- );-CREATE TABLE book2 (- id INTEGER PRIMARY KEY AUTOINCREMENT,- name TEXT NULL- );-CREATE TABLE book3 (- id INTEGER PRIMARY KEY AUTOINCREMENT,- name TEXT NULL- );-CREATE TABLE book4 (- id INTEGER PRIMARY KEY AUTOINCREMENT,- name TEXT NULL- );-`+deploySchedule = &v1pb.Schedule{Deployments: []*v1pb.ScheduleDeployment{{diff --git a/backend/tests/vcs_test.go b/backend/tests/vcs_test.gonew file mode 100644index 0000000000..a38cb5c95a--- /dev/null+++ b/backend/tests/vcs_test.go@@ -0,0 +1,210 @@+package tests++import (+ "context"+ "encoding/json"+ "fmt"+ "strings"+ "testing"++ "github.com/stretchr/testify/require"+ "google.golang.org/protobuf/types/known/fieldmaskpb"++ "github.com/bytebase/bytebase/backend/plugin/vcs"+ "github.com/bytebase/bytebase/backend/plugin/vcs/gitlab"+ "github.com/bytebase/bytebase/backend/tests/fake"+ v1pb "github.com/bytebase/bytebase/proto/generated-go/v1"+)++func TestVCS(t *testing.T) {+ branchName := "feature/foo"+ pullRequestFiles := []*vcs.PullRequestFile{+ {Path: "bbtest/0001##migrate##😊create_table_book1.sql"},+ {Path: "bbtest/0002##migrate##新建create_table_book2.sql"},+ }+ fileContentMap := map[string]string{+ pullRequestFiles[0].Path: migrationStatement1,+ pullRequestFiles[1].Path: migrationStatement2,+ }+ pullRequestID := 2250+ pullRequestTitle := "TestVCS"+ pullRequestDescription := "TestVCS fun."++ tests := []struct {+ name string+ vcsProviderCreator fake.VCSProviderCreator+ vcsType v1pb.VCSProvider_Type+ externalID string+ repositoryFullPath string+ webhookPushEvent any+ }{+ {+ name: "GitLab",+ vcsProviderCreator: fake.NewGitLab,+ vcsType: v1pb.VCSProvider_GITLAB,+ externalID: "121",+ repositoryFullPath: "test/vcs",+ webhookPushEvent: gitlab.MergeRequestPushEvent{+ ObjectKind: "merge_request",+ ObjectAttributes: gitlab.EventObjectAttributes{+ IID: pullRequestID,+ URL: "https://gitlab.com/test/vcs/-/merge_requests/2250",+ TargetBranch: branchName,+ Action: "merge",+ Title: pullRequestTitle,+ Description: pullRequestDescription,+ LastCommit: gitlab.LastCommit{+ ID: "cc63b0592388a7ab1b05b005ad8c8dc14ce432b1",+ },+ },+ },+ },+ }+ 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) {+ t.Parallel()++ a := require.New(t)+ ctx := context.Background()+ ctl := &controller{}+ ctx, err := ctl.StartServerWithExternalPg(ctx, &config{+ dataDir: t.TempDir(),+ vcsProviderCreator: test.vcsProviderCreator,+ })+ a.NoError(err)+ defer func() {+ _ = ctl.Close(ctx)+ }()++ evcs, err := ctl.evcsClient.CreateVCSProvider(ctx, &v1pb.CreateVCSProviderRequest{+ VcsProvider: &v1pb.VCSProvider{+ Title: t.Name(),+ Type: test.vcsType,+ Url: ctl.vcsURL,+ AccessToken: "testApplicationSecret",+ },+ VcsProviderId: strings.ToLower(test.vcsType.String()),+ })+ a.NoError(err)+ ctl.vcsProvider.CreateRepository(test.externalID)+ err = ctl.vcsProvider.CreateBranch(test.externalID, branchName)+ a.NoError(err)++ oldVcsConnector, err := ctl.vcsConnectorServiceClient.CreateVCSConnector(ctx, &v1pb.CreateVCSConnectorRequest{+ Parent: ctl.project.Name,+ VcsConnector: &v1pb.VCSConnector{+ VcsProvider: evcs.Name,+ Title: "Test VCS Connector",+ FullPath: test.repositoryFullPath,+ WebUrl: fmt.Sprintf("%s/%s", ctl.vcsURL, test.repositoryFullPath),+ Branch: branchName,+ BaseDirectory: baseDirectory + "+invalid",+ ExternalId: test.externalID,+ },+ VcsConnectorId: "default",+ })+ a.NoError(err)+ vcsConnector, err := ctl.vcsConnectorServiceClient.UpdateVCSConnector(ctx, &v1pb.UpdateVCSConnectorRequest{+ VcsConnector: &v1pb.VCSConnector{+ Name: oldVcsConnector.Name,+ BaseDirectory: baseDirectory,+ },+ UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"base_directory"}},+ })+ a.NoError(err)+ a.Equal(baseDirectory, vcsConnector.BaseDirectory)++ instanceName := "testInstance"+ instanceDir, err := ctl.provisionSQLiteInstance(t.TempDir(), instanceName)+ a.NoError(err)++ instance, err := ctl.instanceServiceClient.CreateInstance(ctx, &v1pb.CreateInstanceRequest{+ InstanceId: generateRandomString("instance", 10),+ Instance: &v1pb.Instance{+ Title: instanceName,+ Engine: v1pb.Engine_SQLITE,+ Environment: "environments/prod",+ Activation: true,+ DataSources: []*v1pb.DataSource{{Type: v1pb.DataSourceType_ADMIN, Host: instanceDir, Id: "admin"}},+ },+ })+ a.NoError(err)++ databaseName := "testVCS"+ err = ctl.createDatabaseV2(ctx, ctl.project, instance, nil /* environment */, databaseName, "", nil /* labelMap */)+ a.NoError(err)+ database, err := ctl.databaseServiceClient.GetDatabase(ctx, &v1pb.GetDatabaseRequest{+ Name: fmt.Sprintf("%s/databases/%s", instance.Name, databaseName),+ })+ a.NoError(err)++ err = ctl.vcsProvider.AddPullRequest(test.externalID, pullRequestID, pullRequestFiles)+ a.NoError(err)+ err = ctl.vcsProvider.AddFiles(test.externalID, fileContentMap)+ a.NoError(err)++ payload, err := json.Marshal(test.webhookPushEvent)+ a.NoError(err)+ err = ctl.vcsProvider.SendWebhookPush(test.externalID, payload)+ a.NoError(err)++ // Get schema update issue.+ issue, err := ctl.getLastOpenIssue(ctx, ctl.project)+ a.NoError(err)+ a.NotNil(issue)+ err = ctl.waitRollout(ctx, issue.Name, issue.Rollout)+ a.NoError(err)+ // TODO(d): use pull requst.+ a.Equal(pullRequestTitle, issue.Title)+ a.Equal(pullRequestDescription, issue.Description)+ err = ctl.closeIssue(ctx, ctl.project, issue.Name)+ a.NoError(err)++ // Query schema.+ dbMetadata, err := ctl.databaseServiceClient.GetDatabaseSchema(ctx, &v1pb.GetDatabaseSchemaRequest{Name: fmt.Sprintf("%s/schema", database.Name)})+ a.NoError(err)+ a.Equal(want2BookSchema, dbMetadata.Schema)++ // Get migration history.+ resp, err := ctl.databaseServiceClient.ListChangeHistories(ctx, &v1pb.ListChangeHistoriesRequest{+ Parent: database.Name,+ View: v1pb.ChangeHistoryView_CHANGE_HISTORY_VIEW_FULL,+ })+ a.NoError(err)+ histories := resp.ChangeHistories+ wantHistories := []*v1pb.ChangeHistory{+ {+ Type: v1pb.ChangeHistory_MIGRATE,+ Status: v1pb.ChangeHistory_DONE,+ Schema: dumpedSchema2,+ PrevSchema: dumpedSchema,+ Version: "0002",+ },+ {+ Type: v1pb.ChangeHistory_MIGRATE,+ Status: v1pb.ChangeHistory_DONE,+ Schema: dumpedSchema,+ PrevSchema: "",+ Version: "0001",+ },+ }+ a.Equal(len(wantHistories), len(histories))+ for i, history := range histories {+ got := &v1pb.ChangeHistory{+ Type: history.Type,+ Status: history.Status,+ Schema: history.Schema,+ PrevSchema: history.PrevSchema,+ Version: history.Version,+ }+ want := wantHistories[i]+ a.Equal(got, want)+ }++ _, err = ctl.vcsConnectorServiceClient.DeleteVCSConnector(ctx, &v1pb.DeleteVCSConnectorRequest{Name: vcsConnector.Name})+ a.NoError(err)+ })+ }+}