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: integration test for vcs sql review endpoint (#3076)
ecmadao6578e8522811
diff --git a/api/repository.go b/api/repository.goindex 77f6e4224e..13be989d53 100644--- a/api/repository.go+++ b/api/repository.go@@ -45,7 +45,7 @@ type Repository struct {ExternalID string `jsonapi:"attr,externalId"`ExternalWebhookID stringWebhookURLHost string- WebhookEndpointID string+ WebhookEndpointID string `jsonapi:"attr,webhookEndpointID"`WebhookSecretToken string// These will be exclusively used on the server side and we don't return it to the client.AccessToken stringdiff --git a/api/vcs.go b/api/vcs.goindex 98ba59e7b0..6d5ef3f134 100644--- a/api/vcs.go+++ b/api/vcs.go@@ -3,6 +3,7 @@ package apiimport ("encoding/json"+ "github.com/bytebase/bytebase/plugin/advisor""github.com/bytebase/bytebase/plugin/vcs")@@ -97,3 +98,20 @@ type VCSExchangeToken struct {ClientID string `jsonapi:"attr,clientId"`ClientSecret string `jsonapi:"attr,clientSecret"`}++// VCSSQLReviewResult the is SQL review result in VCS workflow.+type VCSSQLReviewResult struct {+ Status advisor.Status `json:"status"`+ Content []string `json:"content"`+}++// VCSSQLReviewRequest is the request from SQL review CI in VCS workflow.+// In the VCS SQL review workflow, the CI will generate the request body then POST /hook/sql-review/:webhook_endpoint_id.+type VCSSQLReviewRequest struct {+ RepositoryID string `json:"repositoryId"`+ PullRequestID string `json:"pullRequestId"`+ // WebURL is the server URL for GitOps CI.+ // In GitHub, the URL should be "https://github.com". Docs: https://docs.github.com/en/actions/learn-github-actions/environment-variables+ // In GitLab, the URL should be the base URL of the GitLab instance like "https://gitlab.bytebase.com". Docs: https://docs.gitlab.com/ee/ci/variables/predefined_variables.html+ WebURL string `json:"webURL"`+}diff --git a/plugin/vcs/github/github.go b/plugin/vcs/github/github.goindex 41a68e41e3..1baff0cb28 100644--- a/plugin/vcs/github/github.go+++ b/plugin/vcs/github/github.go@@ -785,7 +785,8 @@ func (p *Provider) readFile(ctx context.Context, oauthCtx common.OauthContext, ireturn &file, nil}-type githubPullRequestFile struct {+// PullRequestFile is the API message for files in GitHub pull request.+type PullRequestFile struct {FileName string `json:"filename"`SHA string `json:"sha"`// The file status in GitHub PR.@@ -800,7 +801,7 @@ type githubPullRequestFile struct {//// Docs: https://docs.github.com/en/rest/pulls/pulls#list-pull-requests-filesfunc (p *Provider) ListPullRequestFile(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, pullRequestID string) ([]*vcs.PullRequestFile, error) {- var allPRFiles []githubPullRequestFile+ var allPRFiles []PullRequestFilepage := 1for {fileList, err := p.listPaginatedPullRequestFile(ctx, oauthCtx, instanceURL, repositoryID, pullRequestID, page)@@ -826,7 +827,8 @@ func (p *Provider) ListPullRequestFile(ctx context.Context, oauthCtx common.Oaut)continue}- m, _ := url.ParseQuery(u.RawQuery)++ m, err := url.ParseQuery(u.RawQuery)if err != nil {log.Debug("Failed to parse query for file",zap.String("content_url", file.ContentsURL),@@ -851,7 +853,7 @@ func (p *Provider) ListPullRequestFile(ctx context.Context, oauthCtx common.Oaut}// listPaginatedPullRequestFile lists the changed files in the pull request with pagination.-func (p *Provider) listPaginatedPullRequestFile(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, pullRequestID string, page int) ([]githubPullRequestFile, error) {+func (p *Provider) listPaginatedPullRequestFile(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, pullRequestID string, page int) ([]PullRequestFile, error) {requestURL := fmt.Sprintf("%s/repos/%s/pulls/%s/files?per_page=%d&page=%d", p.APIURL(instanceURL), repositoryID, pullRequestID, apiPageSize, page)code, _, body, err := oauth.Get(ctx,@@ -881,7 +883,7 @@ func (p *Provider) listPaginatedPullRequestFile(ctx context.Context, oauthCtx co)}- var prFiles []githubPullRequestFile+ var prFiles []PullRequestFileif err := json.Unmarshal([]byte(body), &prFiles); err != nil {return nil, err}diff --git a/plugin/vcs/gitlab/gitlab.go b/plugin/vcs/gitlab/gitlab.goindex ea08b0e277..b48d76943c 100644--- a/plugin/vcs/gitlab/gitlab.go+++ b/plugin/vcs/gitlab/gitlab.go@@ -759,12 +759,14 @@ func (p *Provider) ReadFileContent(ctx context.Context, oauthCtx common.OauthConreturn file.Content, nil}-type gitlabMergeRequestChange struct {- SHA string `json:"sha"`- Changes []gitlabMergeRequestFile `json:"changes"`+// MergeRequestChange is the API message for GitLab merge request changes.+type MergeRequestChange struct {+ SHA string `json:"sha"`+ Changes []MergeRequestFile `json:"changes"`}-type gitlabMergeRequestFile struct {+// MergeRequestFile is the API message for files in GitLab merge request.+type MergeRequestFile struct {NewPath string `json:"new_path"`NewFile bool `json:"new_file"`RenamedFile bool `json:"renamed_file"`@@ -804,7 +806,7 @@ func (p *Provider) ListPullRequestFile(ctx context.Context, oauthCtx common.Oaut)}- pr := new(gitlabMergeRequestChange)+ pr := new(MergeRequestChange)if err := json.Unmarshal([]byte(body), pr); err != nil {return nil, err}diff --git a/server/server.go b/server/server.goindex a532344ef6..d7cc30cebb 100644--- a/server/server.go+++ b/server/server.go@@ -541,3 +541,8 @@ func (s *Server) Shutdown(ctx context.Context) error {func (s *Server) GetEcho() *echo.Echo {return s.e}++// GetWorkspaceID returns the workspace id.+func (s *Server) GetWorkspaceID() string {+ return s.workspaceID+}diff --git a/server/webhook.go b/server/webhook.goindex 95aa696959..e92b64ea3c 100644--- a/server/webhook.go+++ b/server/webhook.go@@ -30,23 +30,6 @@ import ("github.com/bytebase/bytebase/plugin/vcs/gitlab")-// vcsSQLReviewResult the is SQL review result in VCS workflow.-type vcsSQLReviewResult struct {- Status advisor.Status `json:"status"`- Content []string `json:"content"`-}--// vcsSQLReviewRequest is the request from SQL review CI in VCS workflow.-// In the VCS SQL review workflow, the CI will generate the request body then POST /hook/sql-review/:webhook_endpoint_id.-type vcsSQLReviewRequest struct {- RepositoryID string `json:"repositoryId"`- PullRequestID string `json:"pullRequestId"`- // WebURL is the server URL for GitOps CI.- // In GitHub, the URL should be "https://github.com". Docs: https://docs.github.com/en/actions/learn-github-actions/environment-variables- // In GitLab, the URL should be the base URL of the GitLab instance like "https://gitlab.bytebase.com". Docs: https://docs.gitlab.com/ee/ci/variables/predefined_variables.html- WebURL string `json:"webURL"`-}-const (// sqlReviewDocs is the URL for SQL review doc.sqlReviewDocs = "https://www.bytebase.com/docs/reference/error-code/advisor"@@ -169,7 +152,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {zap.String("request", string(body)),)- var request vcsSQLReviewRequest+ var request api.VCSSQLReviewRequestif err := json.Unmarshal(body, &request); err != nil {return echo.NewHTTPError(http.StatusBadRequest, "Malformed SQL review request").SetInternal(err)}@@ -189,7 +172,22 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {)return false, nil}- return c.Request().Header.Get("X-SQL-Review-Token") == repo.WebhookSecretToken && strings.HasPrefix(repo.WebURL, request.WebURL), nil++ if !strings.HasPrefix(repo.WebURL, request.WebURL) {+ log.Debug("Skip repository as the web URL is not matched.",+ zap.String("request_web_url", request.WebURL),+ zap.String("repo_web_url", repo.WebURL),+ )+ return false, nil+ }++ token := c.Request().Header.Get("X-SQL-Review-Token")+ if token == s.workspaceID && s.profile.Mode == common.ReleaseModeDev {+ // We will use workspace id as token in integration test.+ return true, nil+ }++ return c.Request().Header.Get("X-SQL-Review-Token") == repo.WebhookSecretToken, nil}ctx := c.Request().Context()repositoryList, err := s.filterRepository(ctx, c.Param("id"), request.RepositoryID, filter)@@ -198,7 +196,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {}if len(repositoryList) == 0 {log.Debug("Empty handle repo list. Ignore this request.")- return c.JSON(http.StatusOK, &vcsSQLReviewResult{+ return c.JSON(http.StatusOK, &api.VCSSQLReviewResult{Status: advisor.Success,Content: []string{},})@@ -261,7 +259,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {wg.Wait()- response := &vcsSQLReviewResult{}+ response := &api.VCSSQLReviewResult{}switch repo.VCS.Type {case vcs.GitHubCom:response = convertSQLAdiceToGitHubActionResult(sqlCheckAdvice)@@ -1057,7 +1055,7 @@ func (s *Server) tryUpdateTasksFromModifiedFile(ctx context.Context, databases [// GitLab test report: https://docs.gitlab.com/ee/ci/testing/unit_test_reports.html// junit XML format: https://llg.cubic.org/docs/junit/// nolint:unused-func convertSQLAdviceToGitLabCIResult(adviceMap map[string][]advisor.Advice) *vcsSQLReviewResult {+func convertSQLAdviceToGitLabCIResult(adviceMap map[string][]advisor.Advice) *api.VCSSQLReviewResult {testsuiteList := []string{}status := advisor.Success@@ -1112,7 +1110,7 @@ func convertSQLAdviceToGitLabCIResult(adviceMap map[string][]advisor.Advice) *vc}}- return &vcsSQLReviewResult{+ return &api.VCSSQLReviewResult{Status: status,Content: []string{fmt.Sprintf(@@ -1126,7 +1124,7 @@ func convertSQLAdviceToGitLabCIResult(adviceMap map[string][]advisor.Advice) *vc// convertSQLAdiceToGitHubActionResult 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// nolint:unused-func convertSQLAdiceToGitHubActionResult(adviceMap map[string][]advisor.Advice) *vcsSQLReviewResult {+func convertSQLAdiceToGitHubActionResult(adviceMap map[string][]advisor.Advice) *api.VCSSQLReviewResult {messageList := []string{}status := advisor.Success@@ -1174,7 +1172,7 @@ func convertSQLAdiceToGitHubActionResult(adviceMap map[string][]advisor.Advice)messageList = append(messageList, strings.ReplaceAll(msg, "\n", "%0A"))}}- return &vcsSQLReviewResult{+ return &api.VCSSQLReviewResult{Status: status,Content: messageList,}diff --git a/tests/fake/github.go b/tests/fake/github.goindex 33dcea5b11..b9d983039c 100644--- a/tests/fake/github.go+++ b/tests/fake/github.go@@ -13,6 +13,7 @@ import ("net/http""net/url""path"+ "strconv""time""github.com/labstack/echo/v4"@@ -49,7 +50,10 @@ type repositoryData struct {secrets map[string]*github.RepositorySecret// pullRequests is the map for repository pull request.// the map key is the pull request id.- pullRequests map[int]*github.PullRequest+ pullRequests map[int]struct {+ Files []*github.PullRequestFile+ *github.PullRequest+ }}// NewGitHub creates a new fake implementation of GitHub VCS provider.@@ -80,6 +84,7 @@ func NewGitHub(port int) VCSProvider {gh.getRepositoryPublicKey,)g.PUT("/repos/:owner/:repo/actions/secrets/:keyName", gh.updateRepositoryPublicKey)+ g.GET("/repos/:owner/:repo/pulls/:prID/files", gh.listPullRequestFile)return gh}@@ -289,8 +294,14 @@ func (gh *GitHub) createRepositoryPullRequest(c echo.Context) error {}prID := len(r.pullRequests) + 1- r.pullRequests[prID] = &github.PullRequest{- HTMLURL: fmt.Sprintf("https://github.com/%s/%s/pull/%d", c.Param("owner"), c.Param("repo"), prID),+ r.pullRequests[prID] = struct {+ Files []*github.PullRequestFile+ *github.PullRequest+ }{+ Files: []*github.PullRequestFile{},+ PullRequest: &github.PullRequest{+ HTMLURL: fmt.Sprintf("https://github.com/%s/%s/pull/%d", c.Param("owner"), c.Param("repo"), prID),+ },}buf, err := json.Marshal(@@ -347,6 +358,39 @@ func (gh *GitHub) updateRepositoryPublicKey(c echo.Context) error {return c.String(http.StatusOK, "")}+func (gh *GitHub) listPullRequestFile(c echo.Context) error {+ r, err := gh.validRepository(c)+ if err != nil {+ return err+ }++ prNumber, err := strconv.Atoi(c.Param("prID"))+ if err != nil {+ return c.String(http.StatusBadRequest, fmt.Sprintf("The pull request id is invalid: %v", c.Param("prID")))+ }++ pullRequest, ok := r.pullRequests[prNumber]+ if !ok {+ return c.String(http.StatusNotFound, fmt.Sprintf("Cannot found the pull request: %v", c.Param("prID")))+ }++ page, err := strconv.Atoi(c.QueryParam("page"))+ if err != nil {+ return c.String(http.StatusBadRequest, fmt.Sprintf("Invalid page parameter %v", c.Param("page")))+ }++ prFiles := []*github.PullRequestFile{}+ if page == 1 {+ prFiles = pullRequest.Files+ }++ buf, err := json.Marshal(prFiles)+ if err != nil {+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to marshal response body: %v", err))+ }+ return c.String(http.StatusOK, string(buf))+}+func (gh *GitHub) validRepository(c echo.Context) (*repositoryData, error) {repositoryID := fmt.Sprintf("%s/%s", c.Param("owner"), c.Param("repo"))r, ok := gh.repositories[repositoryID]@@ -388,8 +432,11 @@ func (gh *GitHub) CreateRepository(id string) {Key: "YJf3Ojcv8TSEBCtR0wtTR/F2bD3nBl1lxiwkfV/TYQk=",},},- refs: map[string]*github.Branch{},- pullRequests: map[int]*github.PullRequest{},+ refs: map[string]*github.Branch{},+ pullRequests: map[int]struct {+ Files []*github.PullRequestFile+ *github.PullRequest+ }{},}}@@ -463,3 +510,37 @@ func (gh *GitHub) GetFiles(repositoryID string, filePaths ...string) (map[string}return files, nil}++// AddPullRequest creates a new pull request and add changed files to it.+func (gh *GitHub) AddPullRequest(repositoryID string, prID int, files []*vcs.PullRequestFile) error {+ r, ok := gh.repositories[repositoryID]+ if !ok {+ return errors.Errorf("github repository %q does not exist", repositoryID)+ }++ pullRequestFiles := []*github.PullRequestFile{}+ for _, file := range files {+ status := ""+ if file.IsDeleted {+ status = "removed"+ }+ pullRequestFiles = append(pullRequestFiles, &github.PullRequestFile{+ FileName: file.Path,+ Status: status,+ SHA: file.LastCommitID,+ ContentsURL: fmt.Sprintf("https://github.com/%s/%s?ref=%s", repositoryID, url.QueryEscape(file.Path), file.LastCommitID),+ })+ }++ r.pullRequests[prID] = struct {+ Files []*github.PullRequestFile+ *github.PullRequest+ }{+ Files: pullRequestFiles,+ PullRequest: &github.PullRequest{+ HTMLURL: fmt.Sprintf("https://github.com/%s/pull/%d", repositoryID, prID),+ },+ }++ return nil+}diff --git a/tests/fake/gitlab.go b/tests/fake/gitlab.goindex 2ef8ab3dfc..09a344e156 100644--- a/tests/fake/gitlab.go+++ b/tests/fake/gitlab.go@@ -45,7 +45,10 @@ type projectData struct {variables map[string]*gitlab.EnvironmentVariable// mergeRequests is the map for project merge request.// the map key is the merge request id.- mergeRequests map[int]*gitlab.MergeRequest+ mergeRequests map[int]struct {+ *gitlab.MergeRequestChange+ *gitlab.MergeRequest+ }}// NewGitLab creates a new fake implementation of GitLab VCS provider.@@ -77,6 +80,7 @@ func NewGitLab(port int) VCSProvider {projectGroup.GET("/projects/:id/variables/:variableKey", gl.getProjectEnvironmentVariable)projectGroup.POST("/projects/:id/variables", gl.createProjectEnvironmentVariable)projectGroup.PUT("/projects/:id/variables/:variableKey", gl.updateProjectEnvironmentVariable)+ projectGroup.GET("/projects/:id/merge_requests/:mrID/changes", gl.getMergeRequestChanges)return gl}@@ -104,10 +108,13 @@ func (*GitLab) APIURL(instanceURL string) string {// CreateRepository creates a GitLab project with given ID.func (gl *GitLab) CreateRepository(id string) {gl.projects[id] = &projectData{- files: map[string]string{},- branches: map[string]*gitlab.Branch{},- variables: map[string]*gitlab.EnvironmentVariable{},- mergeRequests: map[int]*gitlab.MergeRequest{},+ files: map[string]string{},+ branches: map[string]*gitlab.Branch{},+ variables: map[string]*gitlab.EnvironmentVariable{},+ mergeRequests: map[int]struct {+ *gitlab.MergeRequestChange+ *gitlab.MergeRequest+ }{},}}@@ -326,9 +333,15 @@ func (gl *GitLab) createProjectPullRequest(c echo.Context) error {}mrID := len(pd.mergeRequests) + 1- pd.mergeRequests[mrID] = &gitlab.MergeRequest{- // TODO: the URL for merge request is invalid.- WebURL: fmt.Sprintf("http://gitlab.example.com/my-group/my-project/merge_requests/%d", mrID),+ pd.mergeRequests[mrID] = struct {+ *gitlab.MergeRequestChange+ *gitlab.MergeRequest+ }{+ MergeRequestChange: &gitlab.MergeRequestChange{},+ MergeRequest: &gitlab.MergeRequest{+ // TODO: the URL for merge request is invalid.+ WebURL: fmt.Sprintf("http://gitlab.example.com/my-group/my-project/merge_requests/%d", mrID),+ },}buf, err := json.Marshal(@@ -411,6 +424,29 @@ func (gl *GitLab) updateProjectEnvironmentVariable(c echo.Context) error {return c.String(http.StatusOK, "")}+func (gl *GitLab) getMergeRequestChanges(c echo.Context) error {+ pd, err := gl.validProject(c)+ if err != nil {+ return err+ }++ mrNumber, err := strconv.Atoi(c.Param("mrID"))+ if err != nil {+ return c.String(http.StatusBadRequest, fmt.Sprintf("The merge request id is invalid: %v", c.Param("mrID")))+ }++ mergeRequest, ok := pd.mergeRequests[mrNumber]+ if !ok {+ return c.String(http.StatusNotFound, fmt.Sprintf("Cannot found the merge request: %v", c.Param("mrID")))+ }++ buf, err := json.Marshal(mergeRequest.MergeRequestChange)+ if err != nil {+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to marshal response body: %v", err))+ }+ return c.String(http.StatusOK, string(buf))+}+// SendWebhookPush sends out a webhook for a push event for the GitLab project// using given payload.func (gl *GitLab) SendWebhookPush(projectID string, payload []byte) error {@@ -475,3 +511,40 @@ func (gl *GitLab) GetFiles(projectID string, filePaths ...string) (map[string]st}return files, nil}++// AddPullRequest creates a new merge request and add changed files to it.+func (gl *GitLab) AddPullRequest(projectID string, mrID int, files []*vcs.PullRequestFile) error {+ pd, ok := gl.projects[projectID]+ if !ok {+ return errors.Errorf("gitlab project %q doesn't exist", projectID)+ }++ if len(files) == 0 {+ return nil+ }++ changes := []gitlab.MergeRequestFile{}+ for _, file := range files {+ changes = append(changes, gitlab.MergeRequestFile{+ NewPath: file.Path,+ NewFile: true,+ RenamedFile: false,+ DeletedFile: file.IsDeleted,+ })+ }++ pd.mergeRequests[mrID] = struct {+ *gitlab.MergeRequestChange+ *gitlab.MergeRequest+ }{+ MergeRequestChange: &gitlab.MergeRequestChange{+ SHA: files[0].LastCommitID,+ Changes: changes,+ },+ MergeRequest: &gitlab.MergeRequest{+ // TODO: the URL for merge request is invalid.+ WebURL: fmt.Sprintf("http://gitlab.example.com/my-group/my-project/merge_requests/%d", mrID),+ },+ }+ return nil+}diff --git a/tests/fake/provider.go b/tests/fake/provider.goindex ed2b391919..7df9106a76 100644--- a/tests/fake/provider.go+++ b/tests/fake/provider.go@@ -2,6 +2,8 @@ package fakeimport ("net"++ "github.com/bytebase/bytebase/plugin/vcs")// VCSProvider is a fake implementation of a VCS provider.@@ -24,6 +26,8 @@ type VCSProvider interface {AddFiles(repositoryID string, files map[string]string) error// GetFiles returns files with given paths from the repository.GetFiles(repositoryID string, filePaths ...string) (map[string]string, error)+ // AddPullRequest creates a new pull request and add changed files to it.+ AddPullRequest(repositoryID string, prID int, files []*vcs.PullRequestFile) error}// VCSProviderCreator a function to create a new VCSProvider.diff --git a/tests/schema_update_test.go b/tests/schema_update_test.goindex cc5940261c..507b9259ae 100644--- a/tests/schema_update_test.go+++ b/tests/schema_update_test.go@@ -1,19 +1,25 @@package testsimport (+ "bytes""context""database/sql""encoding/json""fmt"+ "io"+ "math/rand"+ "net/http""os""path""strconv""testing""time"+ "github.com/pkg/errors""github.com/stretchr/testify/require""github.com/bytebase/bytebase/api"+ "github.com/bytebase/bytebase/plugin/advisor""github.com/bytebase/bytebase/plugin/db""github.com/bytebase/bytebase/plugin/vcs""github.com/bytebase/bytebase/plugin/vcs/github"@@ -1335,3 +1341,285 @@ func TestWildcardInVCSFilePathTemplate(t *testing.T) {})}}++func TestVCS_SQL_Review(t *testing.T) {+ tests := []struct {+ name string+ vcsProviderCreator fake.VCSProviderCreator+ vcsType vcs.Type+ externalID string+ repositoryFullPath string+ getEmptySQLReviewResult func(repo *api.Repository, filePath, rootURL string) *api.VCSSQLReviewResult+ getSQLReviewResult func(repo *api.Repository, filePath string) *api.VCSSQLReviewResult+ }{+ {+ name: "GitLab",+ vcsProviderCreator: fake.NewGitLab,+ vcsType: vcs.GitLabSelfHost,+ externalID: "121",+ repositoryFullPath: "test/schemaUpdate",+ getEmptySQLReviewResult: func(repo *api.Repository, filePath, rootURL string) *api.VCSSQLReviewResult {+ return &api.VCSSQLReviewResult{+ Status: advisor.Warn,+ Content: []string{+ fmt.Sprintf(+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<testsuites name=\"SQL Review\">\n<testsuite name=\"%s\">\n<testcase name=\"SQL review policy not found\" classname=\"%s\" file=\"%s#L1\">\n<failure>\nError: You can configure the SQL review policy on %s/setting/sql-review.\nYou can check the docs at https://www.bytebase.com/docs/reference/error-code/advisor#2\n</failure>\n</testcase>\n</testsuite>\n</testsuites>",+ filePath,+ filePath,+ filePath,+ rootURL,+ ),+ },+ }+ },+ getSQLReviewResult: func(repo *api.Repository, filePath string) *api.VCSSQLReviewResult {+ return &api.VCSSQLReviewResult{+ Status: advisor.Warn,+ Content: []string{+ fmt.Sprintf(+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<testsuites name=\"SQL Review\">\n<testsuite name=\"%s\">\n<testcase name=\"naming.index.pk\" classname=\"%s\" file=\"%s#L1\">\n<failure>\nError: Primary key in table \"book\" mismatches the naming convention, expect \"^pk_book_id$\" but found \"\".\nYou can check the docs at https://www.bytebase.com/docs/reference/error-code/advisor#306\n</failure>\n</testcase>\n<testcase name=\"column.required\" classname=\"%s\" file=\"%s#L1\">\n<failure>\nError: Table \"book\" requires columns: created_ts, creator_id, updated_ts, updater_id.\nYou can check the docs at https://www.bytebase.com/docs/reference/error-code/advisor#401\n</failure>\n</testcase>\n<testcase name=\"column.no-null\" classname=\"%s\" file=\"%s#L1\">\n<failure>\nError: Column \"name\" in \"public\".\"book\" cannot have NULL value.\nYou can check the docs at https://www.bytebase.com/docs/reference/error-code/advisor#402\n</failure>\n</testcase>\n</testsuite>\n</testsuites>",+ filePath,+ filePath,+ filePath,+ filePath,+ filePath,+ filePath,+ filePath,+ ),+ },+ }+ },+ },+ {+ name: "GitHub",+ vcsProviderCreator: fake.NewGitHub,+ vcsType: vcs.GitHubCom,+ externalID: "octocat/Hello-World",+ repositoryFullPath: "octocat/Hello-World",+ getEmptySQLReviewResult: func(repo *api.Repository, filePath, rootURL string) *api.VCSSQLReviewResult {+ return &api.VCSSQLReviewResult{+ Status: advisor.Warn,+ Content: []string{+ fmt.Sprintf(+ "::warning file=%s,line=1,col=1,endColumn=2,title=SQL review policy not found (2)::You can configure the SQL review policy on %s/setting/sql-review%%0ADoc: https://www.bytebase.com/docs/reference/error-code/advisor#2",+ filePath,+ rootURL,+ ),+ },+ }+ },+ getSQLReviewResult: func(repo *api.Repository, filePath string) *api.VCSSQLReviewResult {+ return &api.VCSSQLReviewResult{+ Status: advisor.Warn,+ Content: []string{+ fmt.Sprintf(+ "::warning file=%s,line=1,col=1,endColumn=2,title=naming.index.pk (306)::Primary key in table \"book\" mismatches the naming convention, expect \"^pk_book_id$\" but found \"\"%%0ADoc: https://www.bytebase.com/docs/reference/error-code/advisor#306",+ filePath,+ ),+ fmt.Sprintf(+ "::warning file=%s,line=1,col=1,endColumn=2,title=column.required (401)::Table \"book\" requires columns: created_ts, creator_id, updated_ts, updater_id%%0ADoc: https://www.bytebase.com/docs/reference/error-code/advisor#401",+ filePath,+ ),+ fmt.Sprintf(+ "::warning file=%s,line=1,col=1,endColumn=2,title=column.no-null (402)::Column \"name\" in \"public\".\"book\" cannot have NULL value%%0ADoc: https://www.bytebase.com/docs/reference/error-code/advisor#402",+ filePath,+ ),+ },+ }+ },+ },+ }++ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ a := require.New(t)+ ctx := context.Background()+ ctl := &controller{}+ err := ctl.StartServer(ctx, t.TempDir(), test.vcsProviderCreator, getTestPort(t.Name()))+ a.NoError(err)+ defer func() {+ _ = ctl.Close(ctx)+ }()++ err = ctl.Login()+ a.NoError(err)+ err = ctl.setLicense()+ a.NoError(err)++ // Create a PostgreSQL instance.+ port := getTestPort(t.Name()) + 3+ _, stopInstance := postgres.SetupTestInstance(t, port)+ defer stopInstance()++ pgDB, err := sql.Open("pgx", fmt.Sprintf("host=127.0.0.1 port=%d user=root database=postgres", port))+ a.NoError(err)+ defer func() {+ _ = pgDB.Close()+ }()++ err = pgDB.Ping()+ a.NoError(err)++ const databaseName = "testVCSSchemaUpdate"+ _, err = pgDB.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS %v", databaseName))+ a.NoError(err)+ _, err = pgDB.Exec("CREATE USER bytebase WITH ENCRYPTED PASSWORD 'bytebase'")+ a.NoError(err)+ _, err = pgDB.Exec("ALTER USER bytebase WITH SUPERUSER")+ a.NoError(err)++ // Create a VCS.+ vcsData, err := ctl.createVCS(+ api.VCSCreate{+ Name: t.Name(),+ Type: test.vcsType,+ InstanceURL: ctl.vcsURL,+ APIURL: ctl.vcsProvider.APIURL(ctl.vcsURL),+ ApplicationID: "testApplicationID",+ Secret: "testApplicationSecret",+ },+ )+ a.NoError(err)++ // Create a project.+ project, err := ctl.createProject(+ api.ProjectCreate{+ Name: "Test VCS Project",+ Key: "TestVCSSchemaUpdate",+ },+ )+ a.NoError(err)++ environments, err := ctl.getEnvironments()+ a.NoError(err)+ prodEnvironment, err := findEnvironment(environments, "Prod")+ a.NoError(err)++ // Add an instance.+ instance, err := ctl.addInstance(api.InstanceCreate{+ EnvironmentID: prodEnvironment.ID,+ Name: "pgInstance",+ Engine: db.Postgres,+ Host: "127.0.0.1",+ Port: strconv.Itoa(port),+ Username: "bytebase",+ Password: "bytebase",+ })+ a.NoError(err)++ // Create an issue that creates a database.+ err = ctl.createDatabase(project, instance, databaseName, "bytebase", nil)+ a.NoError(err)++ // Create a repository.+ ctl.vcsProvider.CreateRepository(test.externalID)+ repository, err := ctl.createRepository(+ api.RepositoryCreate{+ VCSID: vcsData.ID,+ ProjectID: project.ID,+ Name: "Test Repository",+ FullPath: test.repositoryFullPath,+ WebURL: fmt.Sprintf("%s/%s", ctl.vcsURL, test.repositoryFullPath),+ BranchFilter: "feature/foo",+ BaseDirectory: baseDirectory,+ FilePathTemplate: "{{ENV_NAME}}/{{DB_NAME}}##{{VERSION}}##{{TYPE}}##{{DESCRIPTION}}.sql",+ SchemaPathTemplate: "{{ENV_NAME}}/.{{DB_NAME}}##LATEST.sql",+ ExternalID: test.externalID,+ AccessToken: "accessToken1",+ RefreshToken: "refreshToken1",+ EnableSQLReviewCI: true,+ },+ )+ a.NoError(err)+ a.NotNil(repository)++ // Simulate Git commits and pull request for SQL review.++ prID := rand.Int()+ gitFile := "bbtest/Prod/testVCSSchemaUpdate##ver3##migrate##create_table_book.sql"+ fileContent := "CREATE TABLE book (id serial PRIMARY KEY, name TEXT);"+ err = ctl.vcsProvider.AddFiles(test.externalID, map[string]string{gitFile: fileContent})+ a.NoError(err)++ err = ctl.vcsProvider.AddPullRequest(+ test.externalID,+ prID,+ []*vcs.PullRequestFile{+ {+ Path: gitFile,+ LastCommitID: "last_commit_id",+ IsDeleted: false,+ },+ },+ )+ a.NoError(err)++ // trigger SQL review with empty policy.+ res, err := postVCSSQLReview(ctl, repository, &api.VCSSQLReviewRequest{+ RepositoryID: repository.ExternalID,+ PullRequestID: fmt.Sprintf("%d", prID),+ WebURL: repository.WebURL,+ })+ a.NoError(err)++ emptySQLReview := test.getEmptySQLReviewResult(repository, gitFile, ctl.rootURL)+ a.Equal(emptySQLReview.Status, res.Status)+ a.Equal(emptySQLReview.Content, res.Content)++ // create the SQL review policy then re-trigger the VCS SQL review.+ policyPayload, err := prodTemplateSQLReviewPolicy()+ a.NoError(err)++ err = ctl.upsertPolicy(api.PolicyUpsert{+ EnvironmentID: prodEnvironment.ID,+ Type: api.PolicyTypeSQLReview,+ Payload: &policyPayload,+ })+ a.NoError(err)++ reviewResult, err := postVCSSQLReview(ctl, repository, &api.VCSSQLReviewRequest{+ RepositoryID: repository.ExternalID,+ PullRequestID: fmt.Sprintf("%d", prID),+ WebURL: repository.WebURL,+ })+ a.NoError(err)++ expectResult := test.getSQLReviewResult(repository, gitFile)+ a.Equal(expectResult.Status, reviewResult.Status)+ a.Equal(expectResult.Content, reviewResult.Content)+ })+ }+}++// postVCSSQLReview will creates the VCS SQL review and get the response.+func postVCSSQLReview(ctl *controller, repo *api.Repository, request *api.VCSSQLReviewRequest) (*api.VCSSQLReviewResult, error) {+ url := fmt.Sprintf("%s/hook/sql-review/%s", ctl.rootURL, repo.WebhookEndpointID)++ payload, err := json.Marshal(request)+ if err != nil {+ return nil, err+ }+ req, err := http.NewRequest("POST", url, bytes.NewReader(payload))+ if err != nil {+ return nil, errors.Wrapf(err, "failed to create a new POST request to %q", url)+ }+ req.Header.Set("X-SQL-Review-Token", ctl.server.GetWorkspaceID())++ client := &http.Client{}+ resp, err := client.Do(req)+ if err != nil {+ return nil, err+ }++ body, err := io.ReadAll(resp.Body)+ if err != nil {+ return nil, errors.Wrap(err, "failed to read response body")+ }++ res := new(api.VCSSQLReviewResult)+ if err := json.Unmarshal([]byte(body), res); err != nil {+ return nil, err+ }++ return res, nil+}diff --git a/tests/tests.go b/tests/tests.goindex 208265c322..2a0583d7b4 100644--- a/tests/tests.go+++ b/tests/tests.go@@ -153,6 +153,8 @@ func getTestPort(testName string) int {"TestSchemaAndDataUpdate","TestVCS/GitLab","TestVCS/GitHub",+ "TestVCS_SQL_Review/GitLab",+ "TestVCS_SQL_Review/GitHub","TestVCS_SDL/GitLab","TestVCS_SDL/GitHub","TestWildcardInVCSFilePathTemplate/emptyBaseAndMixAsterisks",