Skip to content

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

feat: sync sheet from VCS api (#1000)

STEVENaf4b7222a02d
diff --git a/api/sheet.go b/api/sheet.go
index 974162ed14..33822fd06e 100644
--- a/api/sheet.go
+++ b/api/sheet.go
@@ -74,7 +74,7 @@ func (v SheetType) String() string {
// SheetVCSPayload is the additional data payload of the VCS sheet.
type SheetVCSPayload struct {
FileName string `json:"fileName"`
- Path string `json:"path"`
+ FilePath string `json:"filePath"`
Size int64 `json:"size"`
Author string `json:"author"`
LastCommitID string `json:"lastCommitId"`
@@ -196,7 +196,6 @@ type SheetPatch struct {
UpdaterID int
// Related fields
- ProjectID int `jsonapi:"attr,projectId"`
DatabaseID *int `jsonapi:"attr,databaseId"`
// Domain specific fields
@@ -220,6 +219,7 @@ type SheetFind struct {
DatabaseID *int
// Domain fields
+ Name *string
Visibility *SheetVisibility
Source *SheetSource
Type *SheetType
diff --git a/server/acl_casbin_policy_dba.csv b/server/acl_casbin_policy_dba.csv
index 032ab4b433..2b0ba9f14c 100644
--- a/server/acl_casbin_policy_dba.csv
+++ b/server/acl_casbin_policy_dba.csv
@@ -94,5 +94,6 @@ p, DBA, /sheet/{id}, GET
p, DBA, /sheet/{id}, PATCH
p, DBA, /sheet/{id}, PATCH_SELF
p, DBA, /sheet/{id}, DELETE_SELF
+p, DBA, /sheet/project/:projectID/sync, POST
p, DBA, /debug, GET
p, DBA, /debug, PATCH
diff --git a/server/acl_casbin_policy_developer.csv b/server/acl_casbin_policy_developer.csv
index f44b611d7f..bd10b7d837 100644
--- a/server/acl_casbin_policy_developer.csv
+++ b/server/acl_casbin_policy_developer.csv
@@ -82,4 +82,5 @@ p, DEVELOPER, /sheet/{id}, GET
p, DEVELOPER, /sheet/{id}, PATCH
p, DEVELOPER, /sheet/{id}, PATCH_SELF
p, DEVELOPER, /sheet/{id}, DELETE_SELF
+p, DEVELOPER, /sheet/project/:projectID/sync, POST
p, DEVELOPER, /debug, GET
diff --git a/server/acl_casbin_policy_owner.csv b/server/acl_casbin_policy_owner.csv
index 460914e30b..811f2bce75 100644
--- a/server/acl_casbin_policy_owner.csv
+++ b/server/acl_casbin_policy_owner.csv
@@ -99,5 +99,6 @@ p, OWNER, /sheet/{id}, GET
p, OWNER, /sheet/{id}, PATCH
p, OWNER, /sheet/{id}, PATCH_SELF
p, OWNER, /sheet/{id}, DELETE_SELF
+p, OWNER, /sheet/project/:projectID/sync, POST
p, OWNER, /debug, GET
p, OWNER, /debug, PATCH
diff --git a/server/sheet.go b/server/sheet.go
index ccd3f7ede7..2b12a91e6d 100644
--- a/server/sheet.go
+++ b/server/sheet.go
@@ -2,12 +2,18 @@ package server
import (
"context"
+ "encoding/json"
"fmt"
"net/http"
+ "path/filepath"
+ "regexp"
"strconv"
+ "strings"
+ "time"
"github.com/bytebase/bytebase/api"
"github.com/bytebase/bytebase/common"
+ vcsPlugin "github.com/bytebase/bytebase/plugin/vcs"
"github.com/google/jsonapi"
"github.com/labstack/echo/v4"
)
@@ -67,6 +73,211 @@ func (s *Server) registerSheetRoutes(g *echo.Group) {
return nil
})
+ g.POST("/sheet/project/:projectID/sync", func(c echo.Context) error {
+ ctx := context.Background()
+ projectID, err := strconv.Atoi(c.Param("projectID"))
+ if err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Project ID is not a number: %s", c.Param("projectID"))).SetInternal(err)
+ }
+
+ project, err := s.ProjectService.FindProject(ctx, &api.ProjectFind{ID: &projectID})
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Project not found: %d", projectID)).SetInternal(err)
+ }
+ if project == nil {
+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Project not found by ID: %d", projectID))
+ }
+ if project.WorkflowType != api.VCSWorkflow {
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid workflow type: %s, need %s to enable this function", project.WorkflowType, api.VCSWorkflow))
+ }
+
+ repo, err := s.RepositoryService.FindRepository(ctx, &api.RepositoryFind{ProjectID: &projectID})
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to find relevant VCS repo, Project ID: %d", projectID)).SetInternal(err)
+ }
+ if repo == nil {
+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Repository not found by project ID: %d", projectID))
+ }
+
+ vcs, err := s.store.GetVCSByID(ctx, repo.VCSID)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to find VCS for sync sheet: %d", repo.VCSID)).SetInternal(err)
+ }
+ if vcs == nil {
+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("VCS not found by ID: %d", repo.VCSID))
+ }
+
+ basePath := filepath.Dir(repo.SheetPathTemplate)
+ // TODO(Steven): The repo.branchFilter could be `test/*` which cannot be the ref value.
+ fileList, err := vcsPlugin.Get(vcs.Type, vcsPlugin.ProviderConfig{Logger: s.l}).FetchRepositoryFileList(ctx,
+ common.OauthContext{
+ ClientID: vcs.ApplicationID,
+ ClientSecret: vcs.Secret,
+ AccessToken: repo.AccessToken,
+ RefreshToken: repo.RefreshToken,
+ Refresher: s.refreshToken(ctx, repo.ID),
+ },
+ vcs.InstanceURL,
+ repo.ExternalID,
+ repo.BranchFilter,
+ basePath,
+ )
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch repository file list from VCS, instance URL: %s", vcs.InstanceURL)).SetInternal(err)
+ }
+
+ for _, file := range fileList {
+ sheetInfo, err := parseSheetInfo(file.Path, repo.SheetPathTemplate)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to parse sheet info from template").SetInternal(err)
+ }
+ if sheetInfo.SheetName == "" {
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("sheet name cannot be empty from sheet path %s with template %s", file.Path, repo.SheetPathTemplate)).SetInternal(err)
+ }
+
+ fileContent, err := vcsPlugin.Get(vcs.Type, vcsPlugin.ProviderConfig{Logger: s.l}).ReadFileContent(ctx,
+ common.OauthContext{
+ ClientID: vcs.ApplicationID,
+ ClientSecret: vcs.Secret,
+ AccessToken: repo.AccessToken,
+ RefreshToken: repo.RefreshToken,
+ Refresher: s.refreshToken(ctx, repo.ID),
+ },
+ vcs.InstanceURL,
+ repo.ExternalID,
+ file.Path,
+ repo.BranchFilter,
+ )
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch file content from VCS, instance URL: %s, repo ID: %s, file path: %s, branch: %s", vcs.InstanceURL, repo.ExternalID, file.Path, repo.BranchFilter)).SetInternal(err)
+ }
+
+ fileMeta, err := vcsPlugin.Get(vcs.Type, vcsPlugin.ProviderConfig{Logger: s.l}).ReadFileMeta(ctx,
+ common.OauthContext{
+ ClientID: vcs.ApplicationID,
+ ClientSecret: vcs.Secret,
+ AccessToken: repo.AccessToken,
+ RefreshToken: repo.RefreshToken,
+ Refresher: s.refreshToken(ctx, repo.ID),
+ },
+ vcs.InstanceURL,
+ repo.ExternalID,
+ file.Path,
+ repo.BranchFilter,
+ )
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch file meta from VCS, instance URL: %s, repo ID: %s, file path: %s, branch: %s", vcs.InstanceURL, repo.ExternalID, file.Path, repo.BranchFilter)).SetInternal(err)
+ }
+
+ lastCommit, err := vcsPlugin.Get(vcs.Type, vcsPlugin.ProviderConfig{Logger: s.l}).FetchCommitByID(ctx,
+ common.OauthContext{
+ ClientID: vcs.ApplicationID,
+ ClientSecret: vcs.Secret,
+ AccessToken: repo.AccessToken,
+ RefreshToken: repo.RefreshToken,
+ Refresher: s.refreshToken(ctx, repo.ID),
+ },
+ vcs.InstanceURL,
+ repo.ExternalID,
+ fileMeta.LastCommitID,
+ )
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch commit data from VCS, instance URL: %s, repo ID: %s, commit ID: %s", vcs.InstanceURL, repo.ExternalID, fileMeta.LastCommitID)).SetInternal(err)
+ }
+
+ sheetVCSPayload := &api.SheetVCSPayload{
+ FileName: fileMeta.Name,
+ FilePath: fileMeta.Path,
+ Size: fileMeta.Size,
+ Author: lastCommit.AuthorName,
+ LastCommitID: lastCommit.ID,
+ LastSyncTs: time.Now().Unix(),
+ }
+ payload, err := json.Marshal(sheetVCSPayload)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal sheetVCSPayload").SetInternal(err)
+ }
+
+ var databaseID *int
+ // In non-tenant mode, we can set a databaseId for sheet with ENV_NAME and DB_NAME,
+ // and ENV_NAME and DB_NAME is either both present or neither present.
+ if project.TenantMode != api.TenantModeDisabled {
+ if sheetInfo.EnvironmentName != "" && sheetInfo.DatabaseName != "" {
+ databaseList, err := s.composeDatabaseListByFind(ctx, &api.DatabaseFind{
+ Name: &sheetInfo.DatabaseName,
+ ProjectID: &projectID,
+ })
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to find database list with name: %s, project ID: %d", sheetInfo.DatabaseName, projectID)).SetInternal(err)
+ }
+
+ for _, database := range databaseList {
+ if database.Instance.Environment.Name == sheetInfo.EnvironmentName {
+ databaseID = &database.ID
+ break
+ }
+ }
+ }
+ }
+
+ var sheetSource api.SheetSource
+ switch vcs.Type {
+ case vcsPlugin.GitLabSelfHost:
+ sheetSource = api.SheetFromGitLabSelfHost
+ case vcsPlugin.GitHubCom:
+ sheetSource = api.SheetFromGitHubCom
+ }
+ vscSheetType := api.SheetForSQL
+ sheet, err := s.SheetService.FindSheet(ctx, &api.SheetFind{
+ Name: &sheetInfo.SheetName,
+ ProjectID: &project.ID,
+ Source: &sheetSource,
+ Type: &vscSheetType,
+ })
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to find sheet with name: %s, project ID: %d", sheetInfo.SheetName, projectID)).SetInternal(err)
+ }
+
+ if sheet == nil {
+ sheetCreate := api.SheetCreate{
+ ProjectID: projectID,
+ CreatorID: c.Get(getPrincipalIDContextKey()).(int),
+ Name: sheetInfo.SheetName,
+ Statement: fileContent,
+ Visibility: api.ProjectSheet,
+ Source: sheetSource,
+ Type: api.SheetForSQL,
+ Payload: string(payload),
+ }
+ if databaseID != nil {
+ sheetCreate.DatabaseID = databaseID
+ }
+
+ if _, err := s.SheetService.CreateSheet(ctx, &sheetCreate); err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create sheet from VCS").SetInternal(err)
+ }
+ } else {
+ payloadString := string(payload)
+ sheetPatch := api.SheetPatch{
+ ID: sheet.ID,
+ UpdaterID: c.Get(getPrincipalIDContextKey()).(int),
+ Statement: &fileContent,
+ Payload: &payloadString,
+ }
+ if databaseID != nil {
+ sheetPatch.DatabaseID = databaseID
+ }
+
+ if _, err := s.SheetService.PatchSheet(ctx, &sheetPatch); err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to patch sheet from VCS").SetInternal(err)
+ }
+ }
+ }
+
+ c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
+ return nil
+ })
+
g.GET("/sheet", func(c echo.Context) error {
ctx := context.Background()
sheetFind := &api.SheetFind{}
@@ -239,3 +450,49 @@ func (s *Server) composeSheetRelationship(ctx context.Context, raw *api.SheetRaw
return sheet, nil
}
+
+// SheetInfo represents the sheet related information from sheetPathTemplate.
+type SheetInfo struct {
+ EnvironmentName string
+ DatabaseName string
+ SheetName string
+}
+
+// parseSheetInfo matches sheetPath against sheetPathTemplate. If sheetPath matches, then it will derive SheetInfo from the sheetPath.
+// Both sheetPath and sheetPathTemplate are the full file path(including the base directory) of the repository.
+func parseSheetInfo(sheetPath string, sheetPathTemplate string) (*SheetInfo, error) {
+ placeholderList := []string{
+ "ENV_NAME",
+ "DB_NAME",
+ "NAME",
+ }
+ sheetPathRegex := sheetPathTemplate
+ for _, placeholder := range placeholderList {
+ sheetPathRegex = strings.ReplaceAll(sheetPathRegex, fmt.Sprintf("{{%s}}", placeholder), fmt.Sprintf("(?P<%s>[a-zA-Z0-9\\+\\-\\=\\_\\#\\!\\$\\. ]+)", placeholder))
+ }
+ sheetRegex, err := regexp.Compile(fmt.Sprintf("^%s$", sheetPathRegex))
+ if err != nil {
+ return nil, fmt.Errorf("invalid sheet path template: %q, err: %v", sheetPathTemplate, err)
+ }
+ if !sheetRegex.MatchString(sheetPath) {
+ return nil, fmt.Errorf("sheet path %q does not match sheet path template %q", sheetPath, sheetPathTemplate)
+ }
+
+ matchList := sheetRegex.FindStringSubmatch(sheetPath)
+ sheetInfo := &SheetInfo{}
+ for _, placeholder := range placeholderList {
+ index := sheetRegex.SubexpIndex(placeholder)
+ if index >= 0 {
+ switch placeholder {
+ case "ENV_NAME":
+ sheetInfo.EnvironmentName = matchList[index]
+ case "DB_NAME":
+ sheetInfo.DatabaseName = matchList[index]
+ case "NAME":
+ sheetInfo.SheetName = matchList[index]
+ }
+ }
+ }
+
+ return sheetInfo, nil
+}
diff --git a/server/sheet_test.go b/server/sheet_test.go
new file mode 100644
index 0000000000..83fb0b7838
--- /dev/null
+++ b/server/sheet_test.go
@@ -0,0 +1,93 @@
+package server
+
+import (
+ "fmt"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestParseSheetInfo(t *testing.T) {
+ tests := []struct {
+ filePath string
+ sheetPathTemplate string
+ want *SheetInfo
+ err error
+ }{
+ {
+ filePath: "sheet/test.sql",
+ sheetPathTemplate: "sheet/{{NAME}}.sql",
+ want: &SheetInfo{
+ EnvironmentName: "",
+ DatabaseName: "",
+ SheetName: "test",
+ },
+ err: nil,
+ },
+ {
+ filePath: "sheet/DEV__TEST__test.sql",
+ sheetPathTemplate: "sheet/{{ENV_NAME}}__{{DB_NAME}}__{{NAME}}.sql",
+ want: &SheetInfo{
+ EnvironmentName: "DEV",
+ DatabaseName: "TEST",
+ SheetName: "test",
+ },
+ err: nil,
+ },
+ {
+ filePath: "sheet/DEV__test.sql",
+ sheetPathTemplate: "sheet/{{ENV_NAME}}__{{NAME}}.sql",
+ want: &SheetInfo{
+ EnvironmentName: "DEV",
+ DatabaseName: "",
+ SheetName: "test",
+ },
+ err: nil,
+ },
+ {
+ filePath: "sheet/employee__test.sql",
+ sheetPathTemplate: "sheet/{{DB_NAME}}__{{NAME}}.sql",
+ want: &SheetInfo{
+ EnvironmentName: "",
+ DatabaseName: "employee",
+ SheetName: "test",
+ },
+ err: nil,
+ },
+ {
+ filePath: "sheet/db-name.sql",
+ sheetPathTemplate: "sheet/{{DB_NAME}}.sql",
+ want: &SheetInfo{
+ EnvironmentName: "",
+ DatabaseName: "db-name",
+ SheetName: "",
+ },
+ err: nil,
+ },
+ {
+ filePath: "sheet/db/test.sql",
+ sheetPathTemplate: "sheet/{{NAME}}.sql",
+ want: nil,
+ err: fmt.Errorf("sheet path \"sheet/db/test.sql\" does not match sheet path template \"sheet/{{NAME}}.sql\""),
+ },
+ {
+ filePath: "my-sheet/test.sql",
+ sheetPathTemplate: "sheet/{{NAME}}.sql",
+ want: nil,
+ err: fmt.Errorf("sheet path \"my-sheet/test.sql\" does not match sheet path template \"sheet/{{NAME}}.sql\""),
+ },
+ }
+
+ for _, test := range tests {
+ result, err := parseSheetInfo(test.filePath, test.sheetPathTemplate)
+ if err != nil {
+ if test.err != nil {
+ require.Equal(t, test.err.Error(), err.Error())
+ } else {
+ t.Error(err)
+ }
+ } else {
+ require.Equal(t, test.want, result)
+ }
+ }
+}
diff --git a/store/sheet.go b/store/sheet.go
index 1f149867ac..4e0a5936b3 100644
--- a/store/sheet.go
+++ b/store/sheet.go
@@ -245,6 +245,9 @@ func createSheet(ctx context.Context, tx *sql.Tx, create *api.SheetCreate, mode
// patchSheet updates a sheet's name/statement/visibility.
func patchSheet(ctx context.Context, tx *sql.Tx, patch *api.SheetPatch, mode common.ReleaseMode) (*api.SheetRaw, error) {
set, args := []string{"updater_id = $1"}, []interface{}{patch.UpdaterID}
+ if v := patch.DatabaseID; v != nil {
+ set, args = append(set, fmt.Sprintf("database_id = $%d", len(args)+1)), append(args, *v)
+ }
if v := patch.Name; v != nil {
set, args = append(set, fmt.Sprintf("name = $%d", len(args)+1)), append(args, api.RowStatus(*v))
}