Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

chore: VCS SQL review for GitLab (#2875)

ecmadaod4d3aac764bf
diff --git a/api/plan.go b/api/plan.go
index 5325ed83ab..a25a60975b 100644
--- a/api/plan.go
+++ b/api/plan.go
@@ -68,6 +68,8 @@ const (
// in turns belongs to the instance.
// - Support defining extra data source for a database and exposing the related data source UI.
FeatureDataSource FeatureType = "bb.feature.data-source"
+ // FeatureVCSSQLReviewWorkflow allows user to enable the SQL review CI in VCS workflow.
+ FeatureVCSSQLReviewWorkflow FeatureType = "bb.feature.vcs-sql-review"
// FeatureGhost allows user to use gh-ost for MySQL database migration.
FeatureGhost FeatureType = "bb.feature.ghost"
@@ -161,6 +163,8 @@ func (e FeatureType) Name() string {
return "Branding"
case FeatureEnvironmentTierPolicy:
return "Environment tier"
+ case FeatureVCSSQLReviewWorkflow:
+ return "VCS SQL review workflow"
}
return ""
}
@@ -201,6 +205,13 @@ var FeatureMatrix = map[FeatureType][3]bool{
FeatureReadReplicaConnection: {false, false, true},
FeatureBranding: {false, false, true},
FeatureEnvironmentTierPolicy: {false, false, true},
+ FeatureVCSSQLReviewWorkflow: {false, false, true},
+}
+
+// FeatureFlight is the flight map for features.
+// We can disable the hidden feature here. After the feature is released, we can set the bool to true to enable the feature.
+var FeatureFlight = map[FeatureType]bool{
+ FeatureVCSSQLReviewWorkflow: false,
}
// Plan is the API message for a plan.
diff --git a/plugin/vcs/github/github.go b/plugin/vcs/github/github.go
index 7f411a8d1a..244f0e66fe 100644
--- a/plugin/vcs/github/github.go
+++ b/plugin/vcs/github/github.go
@@ -779,6 +779,35 @@ func (p *Provider) readFile(ctx context.Context, oauthCtx common.OauthContext, i
return &file, nil
}
+// GetBranch gets the given branch in the repository.
+//
+// Docs: https://docs.github.com/en/rest/git/refs#create-a-reference
+func (*Provider) GetBranch(_ context.Context, _ common.OauthContext, _, _, _ string) (*vcs.BranchInfo, error) {
+ return nil, errors.Errorf("GetBranch for GitHub is not implemented yet")
+}
+
+// CreateBranch creates the branch in the repository.
+//
+// Docs: https://docs.github.com/en/rest/git/refs#create-a-reference
+func (*Provider) CreateBranch(_ context.Context, _ common.OauthContext, _, _ string, _ *vcs.BranchInfo) error {
+ return errors.Errorf("CreateBranch for GitHub is not implemented yet")
+}
+
+// CreatePullRequest creates the pull request in the repository.
+//
+// Docs: https://docs.github.com/en/rest/pulls/pulls#create-a-pull-request
+func (*Provider) CreatePullRequest(_ context.Context, _ common.OauthContext, _, _ string, _ *vcs.PullRequestCreate) error {
+ return errors.Errorf("CreatePullRequest for GitHub is not implemented yet")
+}
+
+// UpsertEnvironmentVariable creates or updates the environment variable in the repository.
+//
+// https://docs.github.com/en/rest/actions/secrets#get-a-repository-public-key
+// https://docs.github.com/en/rest/actions/secrets#get-a-repository-secret
+func (*Provider) UpsertEnvironmentVariable(_ context.Context, _ common.OauthContext, _, _, _, _ string) error {
+ return errors.Errorf("UpsertEnvironmentVariable for GitHub is not implemented yet")
+}
+
// CreateWebhook creates a webhook in the repository with given payload.
//
// Docs: https://docs.github.com/en/rest/webhooks/repos#create-a-repository-webhook
diff --git a/plugin/vcs/gitlab/gitlab.go b/plugin/vcs/gitlab/gitlab.go
index 1014f1aa83..a0b99b2f5b 100644
--- a/plugin/vcs/gitlab/gitlab.go
+++ b/plugin/vcs/gitlab/gitlab.go
@@ -759,6 +759,318 @@ func (p *Provider) ReadFileContent(ctx context.Context, oauthCtx common.OauthCon
return file.Content, nil
}
+type gitlabBranch struct {
+ Name string `json:"name"`
+ Commit Commit `json:"commit"`
+}
+
+type gitlabBranchCreate struct {
+ Branch string `json:"branch"`
+ Ref string `json:"ref"`
+}
+
+type gitlabMergeRequestCreate struct {
+ Title string `json:"title"`
+ Description string `json:"description"`
+ SourceBranch string `json:"source_branch"`
+ TargetBranch string `json:"target_branch"`
+}
+
+// GetBranch gets the given branch in the repository.
+//
+// Docs: https://docs.gitlab.com/ee/api/branches.html#get-single-repository-branch
+func (p *Provider) GetBranch(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, branchName string) (*vcs.BranchInfo, error) {
+ url := fmt.Sprintf("%s/projects/%s/repository/branches/%s", p.APIURL(instanceURL), repositoryID, branchName)
+ code, _, body, err := oauth.Get(
+ ctx,
+ p.client,
+ url,
+ &oauthCtx.AccessToken,
+ tokenRefresher(
+ instanceURL,
+ oauthContext{
+ ClientID: oauthCtx.ClientID,
+ ClientSecret: oauthCtx.ClientSecret,
+ RefreshToken: oauthCtx.RefreshToken,
+ },
+ oauthCtx.Refresher,
+ ),
+ )
+ if err != nil {
+ return nil, errors.Wrapf(err, "GET %s", url)
+ }
+
+ if code == http.StatusNotFound {
+ return nil, common.Errorf(common.NotFound, "failed to get branch from URL %s", url)
+ } else if code >= 300 {
+ return nil, errors.Errorf("failed to get branch from URL %s, status code: %d, body: %s",
+ url,
+ code,
+ body,
+ )
+ }
+
+ branch := new(gitlabBranch)
+ if err := json.Unmarshal([]byte(body), branch); err != nil {
+ return nil, err
+ }
+
+ return &vcs.BranchInfo{
+ Name: branch.Name,
+ LastCommitID: branch.Commit.ID,
+ }, nil
+}
+
+// CreateBranch creates the branch in the repository.
+//
+// Docs: https://docs.gitlab.com/ee/api/branches.html#create-repository-branch
+func (p *Provider) CreateBranch(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID string, branch *vcs.BranchInfo) error {
+ body, err := json.Marshal(
+ gitlabBranchCreate{
+ Branch: branch.Name,
+ Ref: branch.LastCommitID,
+ },
+ )
+ if err != nil {
+ return errors.Wrap(err, "marshal branch create")
+ }
+
+ url := fmt.Sprintf("%s/projects/%s/repository/branches", p.APIURL(instanceURL), repositoryID)
+ code, _, resp, err := oauth.Post(
+ ctx,
+ p.client,
+ url,
+ &oauthCtx.AccessToken,
+ bytes.NewReader(body),
+ tokenRefresher(
+ instanceURL,
+ oauthContext{
+ ClientID: oauthCtx.ClientID,
+ ClientSecret: oauthCtx.ClientSecret,
+ RefreshToken: oauthCtx.RefreshToken,
+ },
+ oauthCtx.Refresher,
+ ),
+ )
+ if err != nil {
+ return errors.Wrapf(err, "GET %s", url)
+ }
+
+ if code == http.StatusNotFound {
+ return common.Errorf(common.NotFound, "failed to create branch from URL %s", url)
+ } else if code >= 300 {
+ return errors.Errorf("failed to create branch from URL %s, status code: %d, body: %s",
+ url,
+ code,
+ resp,
+ )
+ }
+
+ return nil
+}
+
+// CreatePullRequest creates the pull request in the repository.
+//
+// Docs: https://docs.gitlab.com/ee/api/merge_requests.html#create-mr
+func (p *Provider) CreatePullRequest(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID string, pullRequestCreate *vcs.PullRequestCreate) error {
+ body, err := json.Marshal(
+ gitlabMergeRequestCreate{
+ Title: pullRequestCreate.Title,
+ Description: pullRequestCreate.Body,
+ SourceBranch: pullRequestCreate.Head,
+ TargetBranch: pullRequestCreate.Base,
+ },
+ )
+ if err != nil {
+ return errors.Wrap(err, "marshal pull request create")
+ }
+
+ url := fmt.Sprintf("%s/projects/%s/merge_requests", p.APIURL(instanceURL), repositoryID)
+ code, _, resp, err := oauth.Post(
+ ctx,
+ p.client,
+ url,
+ &oauthCtx.AccessToken,
+ bytes.NewReader(body),
+ tokenRefresher(
+ instanceURL,
+ oauthContext{
+ ClientID: oauthCtx.ClientID,
+ ClientSecret: oauthCtx.ClientSecret,
+ RefreshToken: oauthCtx.RefreshToken,
+ },
+ oauthCtx.Refresher,
+ ),
+ )
+ if err != nil {
+ return errors.Wrapf(err, "GET %s", url)
+ }
+
+ if code == http.StatusNotFound {
+ return common.Errorf(common.NotFound, "failed to create merge request from URL %s", url)
+ } else if code >= 300 {
+ return errors.Errorf("failed to create merge request from URL %s, status code: %d, body: %s",
+ url,
+ code,
+ resp,
+ )
+ }
+
+ return nil
+}
+
+type environmentVariable struct {
+ Key string `json:"key"`
+ Value string `json:"value"`
+}
+
+// UpsertEnvironmentVariable creates or updates the environment variable in the repository.
+func (p *Provider) UpsertEnvironmentVariable(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, key, value string) error {
+ _, err := p.getEnvironmentVariable(ctx, oauthCtx, instanceURL, repositoryID, key)
+ if err != nil {
+ if common.ErrorCode(err) == common.NotFound {
+ return p.createEnvironmentVariable(ctx, oauthCtx, instanceURL, repositoryID, key, value)
+ }
+
+ return err
+ }
+
+ return p.updateEnvironmentVariable(ctx, oauthCtx, instanceURL, repositoryID, key, value)
+}
+
+// getEnvironmentVariable gets the environment variable in the repository.
+//
+// https://docs.gitlab.com/ee/api/project_level_variables.html#get-a-single-variable
+func (p *Provider) getEnvironmentVariable(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, key string) (*environmentVariable, error) {
+ url := fmt.Sprintf("%s/projects/%s/variables/%s", p.APIURL(instanceURL), repositoryID, key)
+ code, _, body, err := oauth.Get(
+ ctx,
+ p.client,
+ url,
+ &oauthCtx.AccessToken,
+ tokenRefresher(
+ instanceURL,
+ oauthContext{
+ ClientID: oauthCtx.ClientID,
+ ClientSecret: oauthCtx.ClientSecret,
+ RefreshToken: oauthCtx.RefreshToken,
+ },
+ oauthCtx.Refresher,
+ ),
+ )
+ if err != nil {
+ return nil, errors.Wrapf(err, "GET %s", url)
+ }
+
+ if code == http.StatusNotFound {
+ return nil, common.Errorf(common.NotFound, "failed to read file from URL %s", url)
+ } else if code >= 300 {
+ return nil,
+ errors.Errorf("failed to read file from URL %s, status code: %d, body: %s",
+ url,
+ code,
+ body,
+ )
+ }
+
+ variable := new(environmentVariable)
+ if err := json.Unmarshal([]byte(body), variable); err != nil {
+ return nil, err
+ }
+
+ return variable, nil
+}
+
+// createEnvironmentVariable creates the environment variable in the repository.
+//
+// https://docs.gitlab.com/ee/api/project_level_variables.html#create-a-variable
+func (p *Provider) createEnvironmentVariable(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, key, value string) error {
+ url := fmt.Sprintf("%s/projects/%s/variables", p.APIURL(instanceURL), repositoryID)
+ body, err := json.Marshal(
+ environmentVariable{
+ Key: key,
+ Value: value,
+ },
+ )
+ if err != nil {
+ return errors.Wrap(err, "marshal environment create")
+ }
+ code, _, resp, err := oauth.Post(
+ ctx,
+ p.client,
+ url,
+ &oauthCtx.AccessToken,
+ bytes.NewReader(body),
+ tokenRefresher(
+ instanceURL,
+ oauthContext{
+ ClientID: oauthCtx.ClientID,
+ ClientSecret: oauthCtx.ClientSecret,
+ RefreshToken: oauthCtx.RefreshToken,
+ },
+ oauthCtx.Refresher,
+ ),
+ )
+ if err != nil {
+ return errors.Wrapf(err, "POST %s", url)
+ }
+ if code == http.StatusNotFound {
+ return common.Errorf(common.NotFound, "failed to create environment variable through URL %s", url)
+ } else if code >= 300 {
+ return errors.Errorf("failed to create environment variable through URL %s, status code: %d, body: %s",
+ url,
+ code,
+ resp,
+ )
+ }
+ return nil
+}
+
+// updateEnvironmentVariable updates the environment variable in the repository.
+//
+// https://docs.gitlab.com/ee/api/project_level_variables.html#update-a-variable
+func (p *Provider) updateEnvironmentVariable(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, key, value string) error {
+ url := fmt.Sprintf("%s/projects/%s/variables/%s", p.APIURL(instanceURL), repositoryID, key)
+ body, err := json.Marshal(
+ environmentVariable{
+ Key: key,
+ Value: value,
+ },
+ )
+ if err != nil {
+ return errors.Wrap(err, "marshal environment create")
+ }
+ code, _, resp, err := oauth.Put(
+ ctx,
+ p.client,
+ url,
+ &oauthCtx.AccessToken,
+ bytes.NewReader(body),
+ tokenRefresher(
+ instanceURL,
+ oauthContext{
+ ClientID: oauthCtx.ClientID,
+ ClientSecret: oauthCtx.ClientSecret,
+ RefreshToken: oauthCtx.RefreshToken,
+ },
+ oauthCtx.Refresher,
+ ),
+ )
+ if err != nil {
+ return errors.Wrapf(err, "PUT %s", url)
+ }
+ if code == http.StatusNotFound {
+ return common.Errorf(common.NotFound, "failed to update environment variable through URL %s", url)
+ } else if code >= 300 {
+ return errors.Errorf("failed to update environment variable through URL %s, status code: %d, body: %s",
+ url,
+ code,
+ resp,
+ )
+ }
+ return nil
+}
+
// CreateWebhook creates a webhook in the repository with given payload.
//
// Docs: https://docs.gitlab.com/ee/api/projects.html#add-project-hook
diff --git a/plugin/vcs/gitlab/sql-review.yml b/plugin/vcs/gitlab/sql-review.yml
new file mode 100644
index 0000000000..0f2a7d4a81
--- /dev/null
+++ b/plugin/vcs/gitlab/sql-review.yml
@@ -0,0 +1,23 @@
+sql-review:
+ only:
+ refs:
+ - merge_requests
+ image: docker:stable
+ variables:
+ API: "%s" # This is the API for SQL reivew.
+ before_script:
+ - apk update && apk add curl
+ - apk update && apk add jq
+ script:
+ - echo "Start request $API/pull/$CI_MERGE_REQUEST_IID"
+ - 'response=$(curl -s --show-error -X GET "$API/pull/$CI_MERGE_REQUEST_IID" -H "Content-type: application/json" -H "X-SQL-Review-Token: $%s")'
+ - echo $response
+ - xml=$(echo $response | jq -r '.content')
+ - status=$(echo $response | jq -r '.status')
+ - for msg in $(echo $content | jq -r '.[]'); do echo $msg >> sql-review.xml; done
+ - if [ "$status" == "ERROR" ]; then exit 1; fi
+ artifacts:
+ when: always
+ reports:
+ junit:
+ - sql-review.xml
diff --git a/plugin/vcs/gitlab/sql_review.go b/plugin/vcs/gitlab/sql_review.go
new file mode 100644
index 0000000000..39bcf6584d
--- /dev/null
+++ b/plugin/vcs/gitlab/sql_review.go
@@ -0,0 +1,52 @@
+package gitlab
+
+import (
+ _ "embed"
+ "fmt"
+
+ "gopkg.in/yaml.v3"
+
+ "github.com/bytebase/bytebase/plugin/vcs"
+)
+
+const (
+ // CIFilePath is the local path for GitLab ci file.
+ CIFilePath = ".gitlab-ci.yml"
+ // SQLReviewCIFilePath is the local path for SQL review CI in GitLab repo.
+ SQLReviewCIFilePath = ".gitlab/sql-review.yml"
+)
+
+// sqlReviewCI is the GitLab CI for SQL review in VCS workflow.
+//
+//go:embed sql-review.yml
+var sqlReviewCI string
+
+// SetupSQLReviewCI will setup the SQL review CI content with SQL review endpoint.
+func SetupSQLReviewCI(endpoint string) string {
+ return fmt.Sprintf(sqlReviewCI, endpoint, vcs.SQLReviewAPISecretName)
+}
+
+// SetupGitLabCI will update the GitLab CI content to add or update the SQL review CI.
+func SetupGitLabCI(gitlabCI map[string]interface{}) (string, error) {
+ if gitlabCI["sql-review"] == nil {
+ // Add include for SQL review CI
+ var includeList []interface{}
+ // Docs for GitLab include syntax: https://docs.gitlab.com/ee/ci/yaml/includes.html
+ switch include := gitlabCI["include"].(type) {
+ case []interface{}:
+ includeList = append(includeList, include...)
+ case string, interface{}:
+ includeList = append(includeList, include)
+ }
+
+ includeList = append(includeList, map[string]string{"local": SQLReviewCIFilePath})
+ gitlabCI["include"] = includeList
+ }
+
+ newContent, err := yaml.Marshal(gitlabCI)
+ if err != nil {
+ return "", err
+ }
+
+ return string(newContent), nil
+}
diff --git a/plugin/vcs/gitlab/sql_review_test.go b/plugin/vcs/gitlab/sql_review_test.go
new file mode 100644
index 0000000000..1a29fb217b
--- /dev/null
+++ b/plugin/vcs/gitlab/sql_review_test.go
@@ -0,0 +1,57 @@
+package gitlab
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+ "gopkg.in/yaml.v3"
+)
+
+const mockGitLabCIContentYAMLStr = `
+image: busybox:latest
+
+include:
+ - local: .gitlab/example.yml
+
+before_script:
+ - echo "Before script section"
+
+after_script:
+ - echo "After script section"
+`
+
+func Test_SetupGitLabCI(t *testing.T) {
+ content := make(map[string]interface{})
+ err := yaml.Unmarshal([]byte(mockGitLabCIContentYAMLStr), &content)
+ require.NoError(t, err)
+
+ newContent, err := SetupGitLabCI(content)
+ require.NoError(t, err)
+
+ err = yaml.Unmarshal([]byte(newContent), &content)
+ require.NoError(t, err)
+
+ assert.NotNil(t, content["image"])
+ assert.NotNil(t, content["include"])
+ assert.NotNil(t, content["before_script"])
+ assert.NotNil(t, content["after_script"])
+
+ include, ok := content["include"].([]interface{})
+ assert.Equal(t, ok, true)
+
+ sqlReviewCI := findSQLReviewCI(include)
+ assert.NotNil(t, sqlReviewCI)
+}
+
+func findSQLReviewCI(include []interface{}) map[string]interface{} {
+ for _, data := range include {
+ if val, ok := data.(map[string]interface{}); ok {
+ if val["local"] == SQLReviewCIFilePath {
+ return val
+ }
+ }
+ }
+
+ return nil
+}
diff --git a/plugin/vcs/vcs.go b/plugin/vcs/vcs.go
index 0bf24fb5e4..2a216931b5 100644
--- a/plugin/vcs/vcs.go
+++ b/plugin/vcs/vcs.go
@@ -22,6 +22,9 @@ const (
GitLabSelfHost Type = "GITLAB_SELF_HOST"
// GitHubCom is the VCS type for GitHub.com.
GitHubCom Type = "GITHUB_COM"
+
+ // SQLReviewAPISecretName is the api secret name used in GitHub action or GitLab CI workflow.
+ SQLReviewAPISecretName = "SQL_REVIEW_API_SECRET"
)
// OAuthToken is the API message for OAuthToken.
@@ -136,6 +139,20 @@ type Repository struct {
WebURL string `json:"webUrl"`
}
+// BranchInfo is the API message for repository branch.
+type BranchInfo struct {
+ Name string
+ LastCommitID string
+}
+
+// PullRequestCreate is the API message to create pull request in repository.
+type PullRequestCreate struct {
+ Title string `json:"title"`
+ Body string `json:"body"`
+ Head string `json:"head"`
+ Base string `json:"base"`
+}
+
// Provider is the interface for VCS provider.
type Provider interface {
// Returns the API URL for a given VCS instance URL
@@ -215,6 +232,35 @@ type Provider interface {
// filePath: file path to be read
// ref: the specific file version to be read, could be a name of branch, tag or commit
ReadFileContent(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, filePath, ref string) (string, error)
+ // GetBranch gets the given branch in the repository.
+ //
+ // oauthCtx: OAuth context to create the webhook
+ // instanceURL: VCS instance URL
+ // repositoryID: the repository ID from the external VCS system (note this is NOT the ID of Bytebase's own repository resource)
+ // branchName: the target branch name
+ GetBranch(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, branchName string) (*BranchInfo, error)
+ // CreateBranch creates the branch in the repository.
+ //
+ // oauthCtx: OAuth context to create the webhook
+ // instanceURL: VCS instance URL
+ // repositoryID: the repository ID from the external VCS system (note this is NOT the ID of Bytebase's own repository resource)
+ // branch: the new branch info
+ CreateBranch(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID string, branch *BranchInfo) error
+ // CreatePullRequest creates the pull request in the repository.
+ //
+ // oauthCtx: OAuth context to create the webhook
+ // instanceURL: VCS instance URL
+ // repositoryID: the repository ID from the external VCS system (note this is NOT the ID of Bytebase's own repository resource)
+ // pullRequestCreate: the new pull request info
+ CreatePullRequest(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID string, pullRequestCreate *PullRequestCreate) error
+ // UpsertEnvironmentVariable creates or updates the environment variable in the repository.
+ //
+ // oauthCtx: OAuth context to create the webhook
+ // instanceURL: VCS instance URL
+ // repositoryID: the repository ID from the external VCS system (note this is NOT the ID of Bytebase's own repository resource)
+ // key: the environment variable name
+ // value: the environment variable value
+ UpsertEnvironmentVariable(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID string, key, value string) error
// Creates a webhook. Returns the created webhook ID on success.
//
// oauthCtx: OAuth context to create the webhook
diff --git a/server/project.go b/server/project.go
index 518bf4c920..905e5779ea 100644
--- a/server/project.go
+++ b/server/project.go
@@ -14,6 +14,7 @@ import (
"github.com/labstack/echo/v4"
"github.com/pkg/errors"
"go.uber.org/zap"
+ "gopkg.in/yaml.v3"
"github.com/bytebase/bytebase/api"
"github.com/bytebase/bytebase/common"
@@ -23,6 +24,11 @@ import (
"github.com/bytebase/bytebase/plugin/vcs/gitlab"
)
+const (
+ // sqlReviewInVCSPRTitle is the pull request title for SQL review CI setup.
+ sqlReviewInVCSPRTitle = "chore: setup SQL review CI for Bytebase"
+)
+
func (s *Server) registerProjectRoutes(g *echo.Group) {
g.POST("/project", func(c echo.Context) error {
ctx := c.Request().Context()
@@ -311,6 +317,13 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to link project repository").SetInternal(err)
}
+ // Setup SQL review CI for VCS
+ if api.FeatureFlight[api.FeatureVCSSQLReviewWorkflow] && s.feature(api.FeatureVCSSQLReviewWorkflow) {
+ if err := s.setupVCSSQLReviewCI(ctx, repository); err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create SQL review CI").SetInternal(err)
+ }
+ }
+
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
if err := jsonapi.MarshalPayload(c.Response().Writer, repository); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal link project repository response").SetInternal(err)
@@ -577,6 +590,235 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
})
}
+// nolint:unused
+func (s *Server) setupVCSSQLReviewCI(ctx context.Context, repository *api.Repository) error {
+ branch, err := s.setupVCSSQLReviewBranch(ctx, repository)
+ if err != nil {
+ return err
+ }
+
+ if err := vcsPlugin.Get(repository.VCS.Type, vcsPlugin.ProviderConfig{}).UpsertEnvironmentVariable(
+ ctx,
+ common.OauthContext{
+ ClientID: repository.VCS.ApplicationID,
+ ClientSecret: repository.VCS.Secret,
+ AccessToken: repository.AccessToken,
+ RefreshToken: repository.RefreshToken,
+ Refresher: s.refreshToken(ctx, repository.WebURL),
+ },
+ repository.VCS.InstanceURL,
+ repository.ExternalID,
+ vcsPlugin.SQLReviewAPISecretName,
+ repository.WebhookSecretToken,
+ ); err != nil {
+ return err
+ }
+
+ switch repository.VCS.Type {
+ case vcsPlugin.GitHubCom:
+ return nil
+ case vcsPlugin.GitLabSelfHost:
+ if err := s.setupVCSSQLReviewCIForGitLab(ctx, repository, branch); err != nil {
+ return err
+ }
+ }
+
+ return vcsPlugin.Get(repository.VCS.Type, vcsPlugin.ProviderConfig{}).CreatePullRequest(
+ ctx,
+ common.OauthContext{
+ ClientID: repository.VCS.ApplicationID,
+ ClientSecret: repository.VCS.Secret,
+ AccessToken: repository.AccessToken,
+ RefreshToken: repository.RefreshToken,
+ Refresher: s.refreshToken(ctx, repository.WebURL),
+ },
+ repository.VCS.InstanceURL,
+ repository.ExternalID,
+ &vcsPlugin.PullRequestCreate{
+ Title: sqlReviewInVCSPRTitle,
+ Body: "This pull request is auto-generated by Bytebase.",
+ Head: branch.Name,
+ Base: repository.BranchFilter,
+ },
+ )
+}
+
+// setupVCSSQLReviewBranch will create a new branch to setup SQL review CI.
+// nolint:unused
+func (s *Server) setupVCSSQLReviewBranch(ctx context.Context, repository *api.Repository) (*vcsPlugin.BranchInfo, error) {
+ branch, err := vcsPlugin.Get(repository.VCS.Type, vcsPlugin.ProviderConfig{}).GetBranch(
+ ctx,
+ common.OauthContext{
+ ClientID: repository.VCS.ApplicationID,
+ ClientSecret: repository.VCS.Secret,
+ AccessToken: repository.AccessToken,
+ RefreshToken: repository.RefreshToken,
+ Refresher: s.refreshToken(ctx, repository.WebURL),
+ },
+ repository.VCS.InstanceURL,
+ repository.ExternalID,
+ repository.BranchFilter,
+ )
+ if err != nil {
+ return nil, err
+ }
+ log.Debug("VCS target branch info", zap.String("last_commit", branch.LastCommitID), zap.String("name", branch.Name))
+
+ branchCreate := &vcsPlugin.BranchInfo{
+ Name: fmt.Sprintf("bytebase-vcs-%d", time.Now().Unix()),
+ LastCommitID: branch.LastCommitID,
+ }
+ if err := vcsPlugin.Get(repository.VCS.Type, vcsPlugin.ProviderConfig{}).CreateBranch(
+ ctx,
+ common.OauthContext{
+ ClientID: repository.VCS.ApplicationID,
+ ClientSecret: repository.VCS.Secret,
+ AccessToken: repository.AccessToken,
+ RefreshToken: repository.RefreshToken,
+ Refresher: s.refreshToken(ctx, repository.WebURL),
+ },
+ repository.VCS.InstanceURL,
+ repository.ExternalID,
+ branchCreate,
+ ); err != nil {
+ return nil, err
+ }
+
+ return branchCreate, nil
+}
+
+// setupVCSSQLReviewCIForGitLab will create or update SQL review related files in GitLab to setup SQL review CI.
+// nolint:unused
+func (s *Server) setupVCSSQLReviewCIForGitLab(ctx context.Context, repository *api.Repository, branch *vcsPlugin.BranchInfo) error {
+ // create or update the .gitlab-ci.yml
+ if err := s.createOrUpdateVCSSQLReviewFileForGitLab(ctx, repository, branch, gitlab.CIFilePath, func(fileMeta *vcsPlugin.FileMeta) (string, error) {
+ content := make(map[string]interface{})
+
+ if fileMeta != nil {
+ ciFileContent, err := vcsPlugin.Get(repository.VCS.Type, vcsPlugin.ProviderConfig{}).ReadFileContent(
+ ctx,
+ common.OauthContext{
+ ClientID: repository.VCS.ApplicationID,
+ ClientSecret: repository.VCS.Secret,
+ AccessToken: repository.AccessToken,
+ RefreshToken: repository.RefreshToken,
+ Refresher: s.refreshToken(ctx, repository.WebURL),
+ },
+ repository.VCS.InstanceURL,
+ repository.ExternalID,
+ gitlab.CIFilePath,
+ fileMeta.LastCommitID,
+ )
+ if err != nil {
+ return "", err
+ }
+ if err := yaml.Unmarshal([]byte(ciFileContent), &content); err != nil {
+ return "", err
+ }
+ }
+
+ newContent, err := gitlab.SetupGitLabCI(content)
+ if err != nil {
+ return "", err
+ }
+
+ return newContent, nil
+ }); err != nil {
+ return err
+ }
+
+ // create or update the SQL review CI.
+ return s.createOrUpdateVCSSQLReviewFileForGitLab(ctx, repository, branch, gitlab.SQLReviewCIFilePath, func(_ *vcsPlugin.FileMeta) (string, error) {
+ sqlReviewEndpoint := fmt.Sprintf("%s/hook/sql-review/%d", s.profile.ExternalURL, repository.ProjectID)
+ return gitlab.SetupSQLReviewCI(sqlReviewEndpoint), nil
+ })
+}
+
+// createOrUpdateVCSSQLReviewFileForGitLab will create or update SQL review file for GitLab CI.
+// nolint:unused
+func (s *Server) createOrUpdateVCSSQLReviewFileForGitLab(
+ ctx context.Context,
+ repository *api.Repository,
+ branch *vcsPlugin.BranchInfo,
+ fileName string,
+ getNewContent func(meta *vcsPlugin.FileMeta) (string, error),
+) error {
+ fileExisted := true
+ fileMeta, err := vcsPlugin.Get(repository.VCS.Type, vcsPlugin.ProviderConfig{}).ReadFileMeta(
+ ctx,
+ common.OauthContext{
+ ClientID: repository.VCS.ApplicationID,
+ ClientSecret: repository.VCS.Secret,
+ AccessToken: repository.AccessToken,
+ RefreshToken: repository.RefreshToken,
+ Refresher: s.refreshToken(ctx, repository.WebURL),
+ },
+ repository.VCS.InstanceURL,
+ repository.ExternalID,
+ fileName,
+ branch.Name,
+ )
+ if err != nil {
+ log.Debug(
+ "Failed to get file meta",
+ zap.String("last_commit", branch.LastCommitID),
+ zap.Int("code", common.ErrorCode(err).Int()),
+ zap.Error(err),
+ )
+ if common.ErrorCode(err) == common.NotFound {
+ fileExisted = false
+ } else {
+ return err
+ }
+ }
+
+ newContent, err := getNewContent(fileMeta)
+ if err != nil {
+ return err
+ }
+
+ if fileExisted {
+ return vcsPlugin.Get(repository.VCS.Type, vcsPlugin.ProviderConfig{}).OverwriteFile(
+ ctx,
+ common.OauthContext{
+ ClientID: repository.VCS.ApplicationID,
+ ClientSecret: repository.VCS.Secret,
+ AccessToken: repository.AccessToken,
+ RefreshToken: repository.RefreshToken,
+ Refresher: s.refreshToken(ctx, repository.WebURL),
+ },
+ repository.VCS.InstanceURL,
+ repository.ExternalID,
+ fileName,
+ vcsPlugin.FileCommitCreate{
+ Branch: branch.Name,
+ CommitMessage: sqlReviewInVCSPRTitle,
+ Content: newContent,
+ LastCommitID: fileMeta.LastCommitID,
+ },
+ )
+ }
+
+ return vcsPlugin.Get(repository.VCS.Type, vcsPlugin.ProviderConfig{}).CreateFile(
+ ctx,
+ common.OauthContext{
+ ClientID: repository.VCS.ApplicationID,
+ ClientSecret: repository.VCS.Secret,
+ AccessToken: repository.AccessToken,
+ RefreshToken: repository.RefreshToken,
+ Refresher: s.refreshToken(ctx, repository.WebURL),
+ },
+ repository.VCS.InstanceURL,
+ repository.ExternalID,
+ fileName,
+ vcsPlugin.FileCommitCreate{
+ Branch: branch.Name,
+ CommitMessage: sqlReviewInVCSPRTitle,
+ Content: newContent,
+ },
+ )
+}
+
func (s *Server) createVCSWebhook(ctx context.Context, vcsType vcsPlugin.Type, webhookEndpointID, secretToken, accessToken, instanceURL, externalRepoID string) (string, error) {
// Create a new webhook and retrieve the created webhook ID
var webhookCreatePayload []byte