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: SQL review in Azure DevOps pipeline (#7368)
ecmadaof12f82ff19f1
diff --git a/backend/api/v1/project_service.go b/backend/api/v1/project_service.goindex b108d97026..1303686450 100644--- a/backend/api/v1/project_service.go+++ b/backend/api/v1/project_service.go@@ -1278,7 +1278,7 @@ func (s *ProjectService) setupVCSSQLReviewCIForAzureDevOps(branch *vcsPlugin.BranchInfo,sqlReviewEndpoint string,) error {- sqlReviewConfig := azure.SetupSQLReviewCI(sqlReviewEndpoint, repository.BranchFilter)+ sqlReviewConfig := azure.SetupSQLReviewCI(sqlReviewEndpoint, repository.BranchFilter, repository.WebhookSecretToken)fileLastCommitID := ""fileSHA := ""diff --git a/backend/plugin/vcs/azure/azure.go b/backend/plugin/vcs/azure/azure.goindex ae3fd6061b..e643fc8031 100644--- a/backend/plugin/vcs/azure/azure.go+++ b/backend/plugin/vcs/azure/azure.go@@ -142,8 +142,12 @@ type project struct {State string `json:"state"`}type repository struct {- ID string `json:"id"`- Name string `json:"name"`+ ID string `json:"id"`+ Name string `json:"name"`+ // RemoteURL is the repo url in https://{org name}@dev.azure.com/{org name}/{project name}/_git/{repo name}+ // The pipeline ci will use this url, so we need this url+ RemoteURL string `json:"remoteUrl"`+ // WebURL is the repo url in https://dev.azure.com/{org name}/{project name}/_git/{repo name}WebURL string `json:"webUrl"`Project project `json:"project"`}@@ -489,7 +493,7 @@ func (p *Provider) FetchAllRepositoryList(ctx context.Context, oauthCtx common.OID: fmt.Sprintf("%s/%s/%s", organization, r.Project.ID, r.ID),Name: r.Name,FullPath: fmt.Sprintf("%s/%s/%s", organization, r.Project.Name, r.Name),- WebURL: r.WebURL,+ WebURL: r.RemoteURL,})}return nil@@ -1178,7 +1182,7 @@ func (p *Provider) listChangedFilesInCommit(ctx context.Context, oauthCtx commonurlParams := &url.Values{}urlParams.Set("api-version", "7.0")- url := fmt.Sprintf("%s/commits/%s?%s", apiURL, commitID, urlParams.Encode())+ url := fmt.Sprintf("%s/commits/%s/changes?%s", apiURL, commitID, urlParams.Encode())code, _, resp, err := oauth.Get(ctx,@@ -1305,6 +1309,7 @@ func (p *Provider) CreatePullRequest(ctx context.Context, oauthCtx common.OauthC// UpsertEnvironmentVariable creates or updates the environment variable in the repository.func (*Provider) UpsertEnvironmentVariable(context.Context, common.OauthContext, string, string, string, string) error {+ // TODO: set api token to pipeline variable.return nil}diff --git a/backend/plugin/vcs/azure/bytebase-sql-review.yml b/backend/plugin/vcs/azure/bytebase-sql-review.ymlindex 02be4098e9..510db3d98c 100644--- a/backend/plugin/vcs/azure/bytebase-sql-review.yml+++ b/backend/plugin/vcs/azure/bytebase-sql-review.yml@@ -27,32 +27,28 @@ jobs:--arg 'webURL' "$BUILD_REPOSITORY_URI" \'$ARGS.named')- response=$(curl --silent --write-out "HTTPSTATUS:%{http_code}" -X POST ${{ variables.api }} \+ response=$(curl -s --show-error -X POST ${{ variables.api }} \+ -H "X-SQL-Review-Token: %s" \-H "Content-Type: application/json" \-d "$request_body")echo "response: $response"- http_code=$(echo $response | tr -d '\n' | sed -e 's/.*HTTPSTATUS://')- body=$(echo $response | sed -e 's/HTTPSTATUS\:.*//g')-- if [[ $http_code != 200 ]]; then- echo "Failed to check SQL with response code $http_code and body $body"- exit 1- fi-- content=$(echo $body | jq -r '.content')+ content=$(echo $response | jq -r '.content')len=$(echo $content | jq '. | length')if [[ $len == 0 ]]; then exit 0; fimsg=$(echo $content | jq -r '.[0]')echo $msg >> bytebase-sql-review.xml- status=$(echo $body | jq -r '.status')- if [[ "$status" == "ERROR" ]]; then exit 1; fi+ result=$(echo $response | jq -r '.status')+ echo "##vso[task.setvariable variable=status]$result"displayName: SQL Review- task: PublishTestResults@2inputs:testResultsFormat: "JUnit"testResultsFiles: "**/bytebase-sql-review.xml"displayName: Upload artifacts+ - bash: |+ if [[ "$STATUS" == "ERROR" ]]; then exit 1; fi+ displayName: Check SQL Review Resultdiff --git a/backend/plugin/vcs/azure/sql_review.go b/backend/plugin/vcs/azure/sql_review.goindex 927050c9fa..a6eed0c949 100644--- a/backend/plugin/vcs/azure/sql_review.go+++ b/backend/plugin/vcs/azure/sql_review.go@@ -18,6 +18,6 @@ const (// SetupSQLReviewCI will setup the SQL review CI content with SQL review endpoint.// Users need to enable the branch policy to trigger pipeline in the pull request.// https://learn.microsoft.com/en-us/azure/devops/pipelines/repos/azure-repos-git?view=azure-devops&tabs=yaml#pr-triggers-func SetupSQLReviewCI(endpoint, branch string) string {- return fmt.Sprintf(sqlReviewPipeline, endpoint, branch)+func SetupSQLReviewCI(endpoint, branch, token string) string {+ return fmt.Sprintf(sqlReviewPipeline, endpoint, branch, token)}diff --git a/backend/server/webhook.go b/backend/server/webhook.goindex 1ff2543f4a..1186fb7e29 100644--- a/backend/server/webhook.go+++ b/backend/server/webhook.go@@ -364,6 +364,9 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to list repositories").SetInternal(err)}+ if len(repositories) == 0 {+ return c.String(http.StatusOK, "No repository matched")+ }// Check the consistence of the repositories, it should not throw any error by right.for i := 1; i < len(repositories); i++ {if repositories[i].ExternalID != repositories[0].ExternalID {@@ -409,6 +412,11 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {return c.String(http.StatusOK, "No repository matched")}+ setting, err := s.store.GetWorkspaceGeneralSetting(ctx)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find workspace setting").SetInternal(err)+ }+// 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@@ -423,6 +431,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {AccessToken: repositoryList[0].repository.AccessToken,RefreshToken: repositoryList[0].repository.RefreshToken,Refresher: utils.RefreshToken(ctx, s.store, repositoryList[0].repository.WebURL),+ RedirectURL: fmt.Sprintf("%s/oauth/callback", setting.ExternalUrl),}, repositoryList[0].repository.ExternalID, commit.CommitID)if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to get changes by commit %q", commit.CommitID)).SetInternal(err)@@ -459,6 +468,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {AccessToken: repositoryList[0].repository.AccessToken,RefreshToken: repositoryList[0].repository.RefreshToken,Refresher: utils.RefreshToken(ctx, s.store, repositoryList[0].repository.WebURL),+ RedirectURL: fmt.Sprintf("%s/oauth/callback", setting.ExternalUrl),}, repositoryList[0].repository.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)@@ -493,6 +503,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {}return c.String(http.StatusOK, strings.Join(createdMessages, "\n"))})+// id is the webhookEndpointID in repository// This endpoint is generated and injected into GitHub action & GitLab CI during the VCS setup.g.POST("/sql-review/:id", func(c echo.Context) error {@@ -569,9 +580,10 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {AccessToken: repo.repository.AccessToken,RefreshToken: repo.repository.RefreshToken,Refresher: utils.RefreshToken(ctx, s.store, repo.repository.WebURL),+ RedirectURL: fmt.Sprintf("%s/oauth/callback", setting.ExternalUrl),},repo.vcs.InstanceURL,- request.RepositoryID,+ repo.repository.ExternalID,request.PullRequestID,)if err != nil {@@ -643,6 +655,8 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {response = convertSQLAdviceToGitHubActionResult(sqlFileName2Advice)case vcs.GitLab:response = convertSQLAdviceToGitLabCIResult(sqlFileName2Advice)+ case vcs.AzureDevOps:+ response = convertSQLAdviceToGitLabCIResult(sqlFileName2Advice)}log.Debug("SQL review finished",@@ -896,6 +910,7 @@ func (s *Server) sqlAdviceForFile(AccessToken: fileInfo.repoInfo.repository.AccessToken,RefreshToken: fileInfo.repoInfo.repository.RefreshToken,Refresher: utils.RefreshToken(ctx, s.store, fileInfo.repoInfo.repository.WebURL),+ RedirectURL: fmt.Sprintf("%s/oauth/callback", externalURL),},fileInfo.repoInfo.vcs.InstanceURL,fileInfo.repoInfo.repository.ExternalID,@@ -1043,9 +1058,17 @@ func (s *Server) filterRepository(ctx context.Context, webhookEndpointID string,continue}- if pushEventRepositoryID != repo.ExternalID {- log.Debug("Skipping repo due to external ID mismatch", zap.Int("repoID", repo.UID), zap.String("pushEventExternalID", pushEventRepositoryID), zap.String("repoExternalID", repo.ExternalID))- continue+ switch externalVCS.Type {+ case vcs.AzureDevOps:+ if !strings.HasSuffix(repo.ExternalID, pushEventRepositoryID) {+ log.Debug("Skipping repo due to external ID mismatch", zap.Int("repoID", repo.UID), zap.String("pushEventExternalID", pushEventRepositoryID), zap.String("repoExternalID", repo.ExternalID))+ continue+ }+ default:+ if pushEventRepositoryID != repo.ExternalID {+ log.Debug("Skipping repo due to external ID mismatch", zap.Int("repoID", repo.UID), zap.String("pushEventExternalID", pushEventRepositoryID), zap.String("repoExternalID", repo.ExternalID))+ continue+ }}ok, err := filter(repo)diff --git a/frontend/src/components/RepositorySetupWizard.vue b/frontend/src/components/RepositorySetupWizard.vueindex ec624178e4..d2e2e070eb 100644--- a/frontend/src/components/RepositorySetupWizard.vue+++ b/frontend/src/components/RepositorySetupWizard.vue@@ -283,6 +283,8 @@ const createSQLReviewCI = async () => {const pullRequestURL = await repositoryV1Store.setupSQLReviewCI(props.project.name);+ // refresh repository+ await repositoryV1Store.fetchRepositoryByProject(props.project.name, true);state.sqlReviewCIPullRequestURL = pullRequestURL;state.showSetupSQLReviewCIModal = true;window.open(pullRequestURL, "_blank");diff --git a/frontend/src/store/modules/v1/repository.ts b/frontend/src/store/modules/v1/repository.tsindex 246f5c0e2b..5e2923c7cc 100644--- a/frontend/src/store/modules/v1/repository.ts+++ b/frontend/src/store/modules/v1/repository.ts@@ -126,6 +126,7 @@ export const useRepositoryV1Store = defineStore("repository_v1", () => {getRepositoryByProject,getOrFetchRepositoryByProject,fetchRepositoryListByVCS,+ fetchRepositoryByProject,getRepositoryListByVCS,};});