Skip to content

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

feat(webhook): support both DDL and SDL for GitLab (#2488)

Joe Chen444880b60f2a
diff --git a/plugin/db/driver.go b/plugin/db/driver.go
index e17100711a..0d91d2a5d5 100644
--- a/plugin/db/driver.go
+++ b/plugin/db/driver.go
@@ -250,7 +250,7 @@ const placeholderRegexp = `[^\\/?%*:|"<>]+`
// ParseMigrationInfo matches filePath against filePathTemplate
// If filePath matches, then it will derive MigrationInfo from the filePath.
// Both filePath and filePathTemplate are the full file path (including the base directory) of the repository.
-func ParseMigrationInfo(filePath string, filePathTemplate string) (*MigrationInfo, error) {
+func ParseMigrationInfo(filePath, filePathTemplate string) (*MigrationInfo, error) {
placeholderList := []string{
"ENV_NAME",
"VERSION",
diff --git a/server/task_executor.go b/server/task_executor.go
index 088868d545..0099f22a51 100644
--- a/server/task_executor.go
+++ b/server/task_executor.go
@@ -8,9 +8,8 @@ import (
"strconv"
"strings"
- "go.uber.org/zap"
-
"github.com/pkg/errors"
+ "go.uber.org/zap"
"github.com/bytebase/bytebase/api"
"github.com/bytebase/bytebase/common"
@@ -180,8 +179,10 @@ func postMigration(ctx context.Context, server *Server, task *api.Task, vcsPushE
return true, nil, err
}
}
- // If VCS based and schema path template is specified, then we will write back the latest schema file after migration.
- writeBack := (vcsPushEvent != nil) && (repo.SchemaPathTemplate != "")
+
+ // We write back the latest schema after migration for VCS-based projects if the
+ // schema path template is specified and the schema migration type is not SDL.
+ writeBack := (vcsPushEvent != nil) && (repo.Project.SchemaMigrationType != api.ProjectSchemaMigrationTypeSDL) && (repo.SchemaPathTemplate != "")
project, err := server.store.GetProjectByID(ctx, task.Database.ProjectID)
if err != nil {
return true, nil, err
diff --git a/server/webhook.go b/server/webhook.go
index 95ec1a82f5..4234c38171 100644
--- a/server/webhook.go
+++ b/server/webhook.go
@@ -1,6 +1,7 @@
package server
import (
+ "bytes"
"context"
"crypto/hmac"
"crypto/sha256"
@@ -24,6 +25,7 @@ import (
"github.com/bytebase/bytebase/common"
"github.com/bytebase/bytebase/common/log"
"github.com/bytebase/bytebase/plugin/db"
+ "github.com/bytebase/bytebase/plugin/parser"
"github.com/bytebase/bytebase/plugin/vcs"
"github.com/bytebase/bytebase/plugin/vcs/github"
"github.com/bytebase/bytebase/plugin/vcs/gitlab"
@@ -35,6 +37,38 @@ var (
)
func (s *Server) registerWebhookRoutes(g *echo.Group) {
+ readFileContent := func(ctx context.Context, pushEvent vcs.PushEvent, webhookEndpointID, file string) (string, error) {
+ // Retrieve the latest AccessToken and RefreshToken as the previous
+ // ReadFileContent call may have updated the stored token pair. ReadFileContent
+ // will fetch and store the new token pair if the existing token pair has
+ // expired.
+ repo, err := s.store.GetRepository(ctx, &api.RepositoryFind{WebhookEndpointID: &webhookEndpointID})
+ if err != nil {
+ return "", errors.Wrapf(err, "get repository by webhook endpoint %q", webhookEndpointID)
+ } else if repo == nil {
+ return "", errors.Wrapf(err, "repository not found by webhook endpoint %q", webhookEndpointID)
+ }
+
+ content, err := vcs.Get(repo.VCS.Type, vcs.ProviderConfig{}).ReadFileContent(
+ ctx,
+ common.OauthContext{
+ ClientID: repo.VCS.ApplicationID,
+ ClientSecret: repo.VCS.Secret,
+ AccessToken: repo.AccessToken,
+ RefreshToken: repo.RefreshToken,
+ Refresher: s.refreshToken(ctx, repo.ID),
+ },
+ repo.VCS.InstanceURL,
+ repo.ExternalID,
+ file,
+ pushEvent.FileCommit.ID,
+ )
+ if err != nil {
+ return "", errors.Wrap(err, "read content")
+ }
+ return content, nil
+ }
+
g.POST("/gitlab/:id", func(c echo.Context) error {
ctx := c.Request().Context()
body, err := io.ReadAll(c.Request().Body)
@@ -78,34 +112,194 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
zap.String("project", repo.Project.Name),
)
- distinctFileList := dedupMigrationFilesFromCommitList(pushEvent.CommitList, false /* includeModified */)
var createdMessageList []string
+ includeModified := repo.Project.SchemaMigrationType == api.ProjectSchemaMigrationTypeSDL
+ distinctFileList := dedupMigrationFilesFromCommitList(pushEvent.CommitList, includeModified)
+ fileList:
for _, item := range distinctFileList {
- createdMessage, created, httpErr := s.createIssueFromPushEvent(
- ctx,
- repo,
- vcs.PushEvent{
- VCSType: repo.VCS.Type,
- BaseDirectory: repo.BaseDirectory,
- Ref: pushEvent.Ref,
- RepositoryID: strconv.Itoa(pushEvent.Project.ID),
- RepositoryURL: pushEvent.Project.WebURL,
- RepositoryFullPath: pushEvent.Project.FullPath,
- AuthorName: pushEvent.AuthorName,
- FileCommit: vcs.FileCommit{
- ID: item.commit.ID,
- Title: item.commit.Title,
- Message: item.commit.Message,
- CreatedTs: item.createdTime.Unix(),
- URL: item.commit.URL,
- AuthorName: item.commit.Author.Name,
- AuthorEmail: item.commit.Author.Email,
- Added: common.EscapeForLogging(item.fileName),
- },
- },
- item.fileName,
- webhookEndpointID,
+ fileEscaped := common.EscapeForLogging(item.fileName)
+ log.Debug("Processing file",
+ zap.String("file", fileEscaped),
+ zap.String("commit", common.EscapeForLogging(item.commit.ID)),
)
+
+ if !strings.HasPrefix(fileEscaped, repo.BaseDirectory) {
+ log.Debug("Ignored file outside the base directory",
+ zap.String("file", fileEscaped),
+ zap.String("base_directory", repo.BaseDirectory),
+ )
+ continue
+ }
+
+ schemaInfo, err := parseSchemaFileInfo(repo.BaseDirectory, repo.SchemaPathTemplate, fileEscaped)
+ if err != nil {
+ log.Debug("Failed to parse schema file info",
+ zap.String("file", fileEscaped),
+ zap.Error(err),
+ )
+ continue
+ }
+
+ pushEvent := vcs.PushEvent{
+ VCSType: repo.VCS.Type,
+ BaseDirectory: repo.BaseDirectory,
+ Ref: pushEvent.Ref,
+ RepositoryID: strconv.Itoa(pushEvent.Project.ID),
+ RepositoryURL: pushEvent.Project.WebURL,
+ RepositoryFullPath: pushEvent.Project.FullPath,
+ AuthorName: pushEvent.AuthorName,
+ FileCommit: vcs.FileCommit{
+ ID: item.commit.ID,
+ Title: item.commit.Title,
+ Message: item.commit.Message,
+ CreatedTs: item.createdTime.Unix(),
+ URL: item.commit.URL,
+ AuthorName: item.commit.Author.Name,
+ AuthorEmail: item.commit.Author.Email,
+ Added: fileEscaped,
+ },
+ }
+
+ var migrationInfo *db.MigrationInfo
+ var updateSchemaDetails []*api.UpdateSchemaDetail
+ if repo.Project.SchemaMigrationType == api.ProjectSchemaMigrationTypeSDL {
+ if schemaInfo == nil {
+ log.Debug("Ignored non-schema file for SDL",
+ zap.String("file", fileEscaped),
+ )
+ continue
+ }
+
+ dbName := schemaInfo["DB_NAME"]
+ if dbName == "" {
+ log.Debug("Ignored schema file without a database name",
+ zap.String("file", fileEscaped),
+ )
+ continue
+ }
+
+ envName := schemaInfo["ENV_NAME"]
+ databases, err := s.findProjectDatabases(ctx, repo.ProjectID, dbName, envName)
+ if err != nil {
+ s.createIgnoredFileActivity(
+ ctx,
+ repo.ProjectID,
+ pushEvent,
+ fileEscaped,
+ errors.Wrap(err, "Failed to find project databases"),
+ )
+ continue
+ }
+
+ content, err := readFileContent(ctx, pushEvent, webhookEndpointID, fileEscaped)
+ if err != nil {
+ s.createIgnoredFileActivity(
+ ctx,
+ repo.ProjectID,
+ pushEvent,
+ fileEscaped,
+ errors.Wrap(err, "Failed to read file content"),
+ )
+ continue
+ }
+
+ for _, database := range databases {
+ diff, err := s.computeDatabaseSchemaDiff(ctx, database, content)
+ if err != nil {
+ s.createIgnoredFileActivity(
+ ctx,
+ repo.ProjectID,
+ pushEvent,
+ fileEscaped,
+ errors.Wrap(err, "Failed to compute database schema diff"),
+ )
+ continue fileList
+ }
+
+ updateSchemaDetails = append(updateSchemaDetails,
+ &api.UpdateSchemaDetail{
+ DatabaseID: database.ID,
+ Statement: diff,
+ },
+ )
+ }
+
+ migrationInfo = &db.MigrationInfo{
+ Version: common.DefaultMigrationVersion(),
+ Namespace: dbName,
+ Database: dbName,
+ Environment: envName,
+ Source: db.VCS,
+ Type: db.Migrate,
+ Description: "Apply schema diff",
+ }
+
+ added := strings.NewReplacer(
+ "{{ENV_NAME}}", envName,
+ "{{DB_NAME}}", dbName,
+ "{{VERSION}}", migrationInfo.Version,
+ "{{TYPE}}", strings.ToLower(string(migrationInfo.Type)),
+ "{{DESCRIPTION}}", strings.ReplaceAll(migrationInfo.Description, " ", "_"),
+ ).Replace(repo.FilePathTemplate)
+ // NOTE: We do not want to use filepath.Join here because we always need "/" as the path separator.
+ pushEvent.FileCommit.Added = path.Join(repo.BaseDirectory, added)
+ } else {
+ if item.itemType != fileItemTypeAdded || schemaInfo != nil {
+ log.Debug("Ignored non-added or schema file for non-SDL",
+ zap.String("file", fileEscaped),
+ zap.String("type", string(item.itemType)),
+ )
+ continue
+ }
+
+ // NOTE: We do not want to use filepath.Join here because we always need "/" as the path separator.
+ migrationInfo, err = db.ParseMigrationInfo(fileEscaped, path.Join(repo.BaseDirectory, repo.FilePathTemplate))
+ if err != nil {
+ s.createIgnoredFileActivity(
+ ctx,
+ repo.ProjectID,
+ pushEvent,
+ fileEscaped,
+ errors.Wrap(err, "Failed to parse migration info"),
+ )
+ continue
+ }
+
+ databases, err := s.findProjectDatabases(ctx, repo.ProjectID, migrationInfo.Database, migrationInfo.Environment)
+ if err != nil {
+ s.createIgnoredFileActivity(
+ ctx,
+ repo.ProjectID,
+ pushEvent,
+ fileEscaped,
+ errors.Wrap(err, "Failed to find project databases"),
+ )
+ continue
+ }
+
+ content, err := readFileContent(ctx, pushEvent, webhookEndpointID, fileEscaped)
+ if err != nil {
+ s.createIgnoredFileActivity(
+ ctx,
+ repo.ProjectID,
+ pushEvent,
+ fileEscaped,
+ errors.Wrap(err, "Failed to read file content"),
+ )
+ continue
+ }
+
+ for _, database := range databases {
+ updateSchemaDetails = append(updateSchemaDetails,
+ &api.UpdateSchemaDetail{
+ DatabaseID: database.ID,
+ Statement: content,
+ },
+ )
+ }
+ }
+
+ createdMessage, created, httpErr := s.createIssueFromPushEvent(ctx, pushEvent, repo, fileEscaped, migrationInfo, updateSchemaDetails)
if httpErr != nil {
return httpErr
}
@@ -116,8 +310,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
}
if len(createdMessageList) == 0 {
- msg := "Ignored push event. No applicable file found in the commit list."
- log.Warn(msg,
+ log.Warn("Ignored push event because no applicable file found in the commit list",
zap.String("project", repo.Project.Name),
)
}
@@ -200,7 +393,7 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
messages := strings.SplitN(commit.Message, "\n\n", 2)
messageTitle := messages[0]
- createdMessage, created, httpErr := s.createIssueFromPushEvent(
+ createdMessage, created, httpErr := s.createIssueFromPushEventLegacy(
ctx,
repo,
vcs.PushEvent{
@@ -272,6 +465,15 @@ func parseBranchNameFromGitHubRefs(ref string) (string, error) {
return ref[len(expectedPrefix):], nil
}
+// fileItemType is the type of a file item.
+type fileItemType string
+
+// The list of file item types.
+const (
+ fileItemTypeAdded fileItemType = "added"
+ fileItemTypeModified fileItemType = "modified"
+)
+
// We are observing the push webhook event so that we will receive the event either when:
// 1. A commit is directly pushed to a branch.
// 2. One or more commits are merged to a branch.
@@ -296,6 +498,7 @@ type distinctFileItem struct {
createdTime time.Time
commit gitlab.WebhookCommit
fileName string
+ itemType fileItemType
}
func dedupMigrationFilesFromCommitList(commitList []gitlab.WebhookCommit, includeModified bool) []distinctFileItem {
@@ -312,11 +515,12 @@ func dedupMigrationFilesFromCommitList(commitList []gitlab.WebhookCommit, includ
log.Warn("Ignored commit, failed to parse commit timestamp.", zap.String("commit", common.EscapeForLogging(commit.ID)), zap.String("timestamp", common.EscapeForLogging(commit.Timestamp)), zap.Error(err))
}
- addDistinctFile := func(fileName string) {
+ addDistinctFile := func(fileName string, itemType fileItemType) {
item := distinctFileItem{
createdTime: createdTime,
commit: commit,
fileName: fileName,
+ itemType: itemType,
}
for i, file := range distinctFileList {
// For the migration file with the same name, keep the one from the latest commit
@@ -331,18 +535,73 @@ func dedupMigrationFilesFromCommitList(commitList []gitlab.WebhookCommit, includ
}
for _, added := range commit.AddedList {
- addDistinctFile(added)
+ addDistinctFile(added, fileItemTypeAdded)
}
if includeModified {
for _, modified := range commit.ModifiedList {
- addDistinctFile(modified)
+ addDistinctFile(modified, fileItemTypeModified)
}
}
}
return distinctFileList
}
+// findProjectDatabases finds the list of databases with given name in the
+// project. If the `envName` is not empty, it will be used as a filter condition
+// for the result list.
+func (s *Server) findProjectDatabases(ctx context.Context, projectID int, dbName, envName string) ([]*api.Database, error) {
+ // Retrieve the current schema from the database
+ foundDatabases, err := s.store.FindDatabase(ctx,
+ &api.DatabaseFind{
+ ProjectID: &projectID,
+ Name: &dbName,
+ },
+ )
+ if err != nil {
+ return nil, errors.Wrap(err, "find database")
+ } else if len(foundDatabases) == 0 {
+ return nil, errors.Errorf("project %d does not have database %q", projectID, dbName)
+ }
+
+ // We support 3 patterns on how to organize the schema files.
+ // Pattern 1: The database name is the same across all environments. Each environment will have its own directory, so the
+ // schema file looks like "dev/v1__db1", "staging/v1__db1".
+ //
+ // Pattern 2: Like 1, the database name is the same across all environments. All environment shares the same schema file,
+ // say v1__db1, when a new file is added like v2__db1__add_column, we will create a multi stage pipeline where
+ // each stage corresponds to an environment.
+ //
+ // Pattern 3: The database name is different among different environments. In such case, the database name alone is enough
+ // to identify ambiguity.
+
+ // Further filter by environment name if applicable.
+ var filteredDatabases []*api.Database
+ if envName != "" {
+ for _, database := range foundDatabases {
+ // Environment name comparison is case insensitive
+ if strings.EqualFold(database.Instance.Environment.Name, envName) {
+ filteredDatabases = append(filteredDatabases, database)
+ }
+ }
+ if len(filteredDatabases) == 0 {
+ return nil, errors.Errorf("project %d does not have database %q for environment %q", projectID, dbName, envName)
+ }
+ } else {
+ filteredDatabases = foundDatabases
+ }
+
+ // In case there are databases with identical name in a project for the same environment.
+ marked := make(map[int]struct{})
+ for _, database := range filteredDatabases {
+ if _, ok := marked[database.Instance.EnvironmentID]; ok {
+ return nil, errors.Errorf("project %d has multiple databases %q for environment %q", projectID, dbName, envName)
+ }
+ marked[database.Instance.EnvironmentID] = struct{}{}
+ }
+ return filteredDatabases, nil
+}
+
func (s *Server) createSchemaUpdateIssue(ctx context.Context, repository *api.Repository, mi *db.MigrationInfo, vcsPushEvent vcs.PushEvent, added string, statement string) (string, error) {
// Find matching database list
databaseFind := &api.DatabaseFind{
@@ -440,11 +699,144 @@ func createTenantSchemaUpdateIssue(mi *db.MigrationInfo, vcsPushEvent vcs.PushEv
return string(createContext), nil
}
+// createIgnoredFileActivity creates a warning project activity for the ignored file with given error.
+func (s *Server) createIgnoredFileActivity(ctx context.Context, projectID int, pushEvent vcs.PushEvent, file string, err error) {
+ log.Warn("Ignored file",
+ zap.String("file", file),
+ zap.Error(err),
+ )
+
+ payload, marshalErr := json.Marshal(
+ api.ActivityProjectRepositoryPushPayload{
+ VCSPushEvent: pushEvent,
+ },
+ )
+ if marshalErr != nil {
+ log.Warn("Failed to construct project activity payload for the ignored repository file",
+ zap.Error(marshalErr),
+ )
+ return
+ }
+
+ activityCreate := &api.ActivityCreate{
+ CreatorID: api.SystemBotID,
+ ContainerID: projectID,
+ Type: api.ActivityProjectRepositoryPush,
+ Level: api.ActivityWarn,
+ Comment: fmt.Sprintf("Ignored file %q, %v.", file, err),
+ Payload: string(payload),
+ }
+ if _, err = s.ActivityManager.CreateActivity(ctx, activityCreate, &ActivityMeta{}); err != nil {
+ log.Warn("Failed to create project activity for the ignored repository file",
+ zap.Error(err),
+ )
+ }
+}
+
// createIssueFromPushEvent attempts to create a new issue for the given file of
// the push event. It returns "created=true" when a new issue has been created,
// along with the creation message to be presented in the UI. An *echo.HTTPError
// is returned in case of the error during the process.
-func (s *Server) createIssueFromPushEvent(ctx context.Context, repo *api.Repository, pushEvent vcs.PushEvent, file, webhookEndpointID string) (message string, created bool, _ error) {
+func (s *Server) createIssueFromPushEvent(ctx context.Context, pushEvent vcs.PushEvent, repo *api.Repository, file string, mi *db.MigrationInfo, updateSchemaDetails []*api.UpdateSchemaDetail) (message string, created bool, err error) {
+ if len(updateSchemaDetails) == 0 {
+ return "", false, nil
+ }
+
+ // Create schema update issue
+ creatorID := api.SystemBotID
+ if pushEvent.FileCommit.AuthorEmail != "" {
+ committerPrincipal, err := s.store.GetPrincipalByEmail(ctx, pushEvent.FileCommit.AuthorEmail)
+ if err != nil {
+ log.Error("Failed to find the principal with committer email",
+ zap.String("email", common.EscapeForLogging(pushEvent.FileCommit.AuthorEmail)),
+ zap.Error(err),
+ )
+ }
+ if committerPrincipal == nil {
+ log.Debug("Failed to find the principal with committer email, use system bot instead",
+ zap.String("email", common.EscapeForLogging(pushEvent.FileCommit.AuthorEmail)),
+ )
+ } else {
+ creatorID = committerPrincipal.ID
+ }
+ }
+
+ if repo.Project.TenantMode == api.TenantModeTenant {
+ if !s.feature(api.FeatureMultiTenancy) {
+ return "", false, echo.NewHTTPError(http.StatusForbidden, api.FeatureMultiTenancy.AccessErrorMessage())
+ }
+
+ // We don't take environment for tenant mode project because the databases
+ // needing schema update are determined by database name and deployment
+ // configuration.
+ if mi.Environment != "" {
+ return "", false, echo.NewHTTPError(http.StatusInternalServerError, "Environment isn't accepted in schema update for tenant mode project")
+ }
+ }
+
+ createContext, err := json.Marshal(
+ &api.UpdateSchemaContext{
+ MigrationType: db.Migrate,
+ VCSPushEvent: &pushEvent,
+ DetailList: updateSchemaDetails,
+ },
+ )
+ if err != nil {
+ return "", false, echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal update schema context").SetInternal(err)
+ }
+
+ issueType := api.IssueDatabaseSchemaUpdate
+ if mi.Type == db.Data {
+ issueType = api.IssueDatabaseDataUpdate
+ }
+ issueCreate := &api.IssueCreate{
+ ProjectID: repo.ProjectID,
+ Name: fmt.Sprintf("%s by %s", mi.Description, strings.TrimPrefix(file, repo.BaseDirectory+"/")),
+ Type: issueType,
+ Description: pushEvent.FileCommit.Message,
+ AssigneeID: api.SystemBotID,
+ CreateContext: string(createContext),
+ }
+ issue, err := s.createIssue(ctx, issueCreate, creatorID)
+ if err != nil {
+ errMsg := "Failed to create schema update issue"
+ if issueType == api.IssueDatabaseDataUpdate {
+ errMsg = "Failed to create data update issue"
+ }
+ return "", false, echo.NewHTTPError(http.StatusInternalServerError, errMsg).SetInternal(err)
+ }
+
+ // Create a project activity after successfully creating the issue as the result of the push event
+ payload, err := json.Marshal(
+ api.ActivityProjectRepositoryPushPayload{
+ VCSPushEvent: pushEvent,
+ IssueID: issue.ID,
+ IssueName: issue.Name,
+ },
+ )
+ if err != nil {
+ return "", false, echo.NewHTTPError(http.StatusInternalServerError, "Failed to construct activity payload").SetInternal(err)
+ }
+
+ activityCreate := &api.ActivityCreate{
+ CreatorID: creatorID,
+ ContainerID: repo.ProjectID,
+ Type: api.ActivityProjectRepositoryPush,
+ Level: api.ActivityInfo,
+ Comment: fmt.Sprintf("Created issue %q.", issue.Name),
+ Payload: string(payload),
+ }
+ if _, err = s.ActivityManager.CreateActivity(ctx, activityCreate, &ActivityMeta{}); err != nil {
+ return "", false, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to create project activity after creating issue from repository push event: %d", issue.ID)).SetInternal(err)
+ }
+
+ return fmt.Sprintf("Created issue %q on adding %s", issue.Name, file), true, nil
+}
+
+// Deprecated: Use createIssueFromPushEvent instead.
+//
+// TODO(jc): Delete this method once refactored webhook handler logic for GitHub.
+func (s *Server) createIssueFromPushEventLegacy(ctx context.Context, repo *api.Repository, pushEvent vcs.PushEvent, file, webhookEndpointID string) (message string, created bool, _ error) {
fileEscaped := common.EscapeForLogging(file)
log.Debug("Processing added file...",
zap.String("file", fileEscaped),
@@ -623,6 +1015,8 @@ func (s *Server) createIssueFromPushEvent(ctx context.Context, repo *api.Reposit
// We may write back the latest schema file to the repository after migration and we need to ignore
// this file from the webhook push event.
+//
+// Deprecated: Use parseSchemaFileInfo instead.
func isSkipGeneratedSchemaFile(repository *api.Repository, added string) bool {
if repository.SchemaPathTemplate != "" {
placeholderList := []string{
@@ -648,3 +1042,87 @@ func isSkipGeneratedSchemaFile(repository *api.Repository, added string) bool {
}
return false
}
+
+// parseSchemaFileInfo attempts to parse the given schema file path to extract
+// the schema file info. It returns (nil, nil) if it doesn't looks like a schema
+// file path.
+//
+// The possible keys for the returned map are: "ENV_NAME", "DB_NAME".
+func parseSchemaFileInfo(baseDirectory, schemaPathTemplate, file string) (map[string]string, error) {
+ if schemaPathTemplate == "" {
+ return nil, nil
+ }
+
+ // Escape "." characters to match literals instead of using it as a wildcard.
+ schemaFilePathRegex := strings.ReplaceAll(schemaPathTemplate, ".", `\.`)
+
+ placeholders := []string{
+ "ENV_NAME",
+ "DB_NAME",
+ }
+ for _, placeholder := range placeholders {
+ schemaFilePathRegex = strings.ReplaceAll(schemaFilePathRegex, fmt.Sprintf("{{%s}}", placeholder), fmt.Sprintf("(?P<%s>[a-zA-Z0-9+-=/_#?!$. ]+)", placeholder))
+ }
+
+ // NOTE: We do not want to use filepath.Join here because we always need "/" as the path separator.
+ re, err := regexp.Compile(path.Join(baseDirectory, schemaFilePathRegex))
+ if err != nil {
+ return nil, errors.Wrap(err, "compile schema file path regex")
+ }
+ match := re.FindStringSubmatch(file)
+ if len(match) == 0 {
+ return nil, nil
+ }
+
+ info := make(map[string]string)
+ // Skip the first item because it is always the empty string, see docstring of
+ // the SubexpNames() method.
+ for i, name := range re.SubexpNames()[1:] {
+ info[name] = match[i+1]
+ }
+ return info, nil
+}
+
+// computeDatabaseSchemaDiff computes the diff between current database schema
+// and the given schema. It returns an empty string if there is no applicable
+// diff.
+func (s *Server) computeDatabaseSchemaDiff(ctx context.Context, database *api.Database, newSchemaStr string) (string, error) {
+ driver, err := s.getAdminDatabaseDriver(ctx, database.Instance, database.Name)
+ if err != nil {
+ return "", errors.Wrap(err, "get admin driver")
+ }
+ defer func() {
+ _ = driver.Close(ctx)
+ }()
+
+ var schema bytes.Buffer
+ _, err = driver.Dump(ctx, database.Name, &schema, true /* schemaOnly */)
+ if err != nil {
+ return "", errors.Wrap(err, "dump old schema")
+ }
+
+ var engine parser.EngineType
+ switch database.Instance.Engine {
+ case db.Postgres:
+ engine = parser.Postgres
+ case db.MySQL:
+ engine = parser.MySQL
+ default:
+ return "", errors.Errorf("unsupported database engine %q", database.Instance.Engine)
+ }
+ oldSchema, err := parser.Parse(engine, parser.ParseContext{}, schema.String())
+ if err != nil {
+ return "", errors.Wrap(err, "parse old schema")
+ }
+
+ newSchema, err := parser.Parse(engine, parser.ParseContext{}, newSchemaStr)
+ if err != nil {
+ return "", errors.Wrap(err, "parse new schema")
+ }
+
+ diff, err := parser.SchemaDiff(oldSchema, newSchema)
+ if err != nil {
+ return "", errors.New("compute schema diff")
+ }
+ return diff, nil
+}
diff --git a/server/webhook_test.go b/server/webhook_test.go
index 614abee0ba..355bc6dd2f 100644
--- a/server/webhook_test.go
+++ b/server/webhook_test.go
@@ -5,6 +5,7 @@ import (
"time"
"github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
"github.com/bytebase/bytebase/api"
"github.com/bytebase/bytebase/plugin/vcs/gitlab"
@@ -63,6 +64,7 @@ func TestDedupMigrationFiles(t *testing.T) {
},
},
fileName: "v1.sql",
+ itemType: fileItemTypeAdded,
},
},
},
@@ -102,6 +104,7 @@ func TestDedupMigrationFiles(t *testing.T) {
},
},
fileName: "v1.sql",
+ itemType: fileItemTypeAdded,
},
{
createdTime: time1,
@@ -120,6 +123,7 @@ func TestDedupMigrationFiles(t *testing.T) {
},
},
fileName: "v2.sql",
+ itemType: fileItemTypeAdded,
},
},
},
@@ -170,6 +174,7 @@ func TestDedupMigrationFiles(t *testing.T) {
},
},
fileName: "v1.sql",
+ itemType: fileItemTypeAdded,
},
},
},
@@ -240,6 +245,7 @@ func TestDedupMigrationFiles(t *testing.T) {
ModifiedList: []string{"v4.sql"},
},
fileName: "v1.sql",
+ itemType: fileItemTypeAdded,
},
{
createdTime: time3,
@@ -260,6 +266,7 @@ func TestDedupMigrationFiles(t *testing.T) {
ModifiedList: []string{"v4.sql"},
},
fileName: "v2.sql",
+ itemType: fileItemTypeAdded,
},
{
createdTime: time3,
@@ -280,6 +287,7 @@ func TestDedupMigrationFiles(t *testing.T) {
ModifiedList: []string{"v4.sql"},
},
fileName: "v3.sql",
+ itemType: fileItemTypeAdded,
},
},
},
@@ -351,6 +359,7 @@ func TestDedupMigrationFiles(t *testing.T) {
ModifiedList: []string{"v4.sql"},
},
fileName: "v1.sql",
+ itemType: fileItemTypeAdded,
},
{
createdTime: time3,
@@ -371,6 +380,7 @@ func TestDedupMigrationFiles(t *testing.T) {
ModifiedList: []string{"v4.sql"},
},
fileName: "v2.sql",
+ itemType: fileItemTypeAdded,
},
{
createdTime: time3,
@@ -391,6 +401,7 @@ func TestDedupMigrationFiles(t *testing.T) {
ModifiedList: []string{"v4.sql"},
},
fileName: "v3.sql",
+ itemType: fileItemTypeAdded,
},
{
createdTime: time3,
@@ -411,6 +422,7 @@ func TestDedupMigrationFiles(t *testing.T) {
ModifiedList: []string{"v4.sql"},
},
fileName: "v4.sql",
+ itemType: fileItemTypeModified,
},
},
},
@@ -522,3 +534,65 @@ func TestIsSkipGeneratedSchemaFile(t *testing.T) {
})
}
}
+
+func TestParseSchemaFileInfo(t *testing.T) {
+ tests := []struct {
+ name string
+ baseDirectory string
+ schemaPathTemplate string
+ file string
+ schemaInfo map[string]string
+ }{
+ {
+ name: "no schemaPathTemplate",
+ baseDirectory: "",
+ schemaPathTemplate: "",
+ file: "Test/testdb__LATEST.sql",
+ schemaInfo: nil,
+ },
+ {
+ name: "only has DB_NAME",
+ baseDirectory: "",
+ schemaPathTemplate: "{{DB_NAME}}__LATEST.sql",
+ file: "testdb__LATEST.sql",
+ schemaInfo: map[string]string{
+ "DB_NAME": "testdb",
+ },
+ },
+ {
+ name: "has both ENV_NAME and DB_NAME",
+ baseDirectory: "",
+ schemaPathTemplate: "{{ENV_NAME}}/{{DB_NAME}}__LATEST.sql",
+ file: "Test/testdb__LATEST.sql",
+ schemaInfo: map[string]string{
+ "ENV_NAME": "Test",
+ "DB_NAME": "testdb",
+ },
+ },
+
+ {
+ name: "baseDirectory does not match",
+ baseDirectory: "bytebase",
+ schemaPathTemplate: "{{ENV_NAME}}/{{DB_NAME}}__LATEST.sql",
+ file: "Test/testdb__LATEST.sql",
+ schemaInfo: nil,
+ },
+ {
+ name: "baseDirectory with both ENV_NAME and DB_NAME",
+ baseDirectory: "bytebase",
+ schemaPathTemplate: "{{ENV_NAME}}/{{DB_NAME}}__LATEST.sql",
+ file: "bytebase/Test/testdb__LATEST.sql",
+ schemaInfo: map[string]string{
+ "ENV_NAME": "Test",
+ "DB_NAME": "testdb",
+ },
+ },
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ got, err := parseSchemaFileInfo(test.baseDirectory, test.schemaPathTemplate, test.file)
+ require.NoError(t, err)
+ assert.Equal(t, test.schemaInfo, got)
+ })
+ }
+}
diff --git a/tests/schema_update_test.go b/tests/schema_update_test.go
index 68ccc41009..8a1bb22076 100644
--- a/tests/schema_update_test.go
+++ b/tests/schema_update_test.go
@@ -2,6 +2,7 @@ package tests
import (
"context"
+ "database/sql"
"encoding/json"
"fmt"
"os"
@@ -18,6 +19,7 @@ import (
"github.com/bytebase/bytebase/plugin/vcs/github"
"github.com/bytebase/bytebase/plugin/vcs/gitlab"
resourcemysql "github.com/bytebase/bytebase/resources/mysql"
+ "github.com/bytebase/bytebase/resources/postgres"
"github.com/bytebase/bytebase/tests/fake"
)
@@ -546,6 +548,299 @@ func TestVCS(t *testing.T) {
}
}
+func TestVCS_SDL(t *testing.T) {
+ tests := []struct {
+ name string
+ vcsProviderCreator fake.VCSProviderCreator
+ vcsType vcs.Type
+ externalID string
+ repositoryFullPath string
+ newWebhookPushEvent func(gitFile string) interface{}
+ }{
+ {
+ name: "GitLab",
+ vcsProviderCreator: fake.NewGitLab,
+ vcsType: vcs.GitLabSelfHost,
+ externalID: "121",
+ repositoryFullPath: "test/schemaUpdate",
+ newWebhookPushEvent: func(gitFile string) interface{} {
+ return gitlab.WebhookPushEvent{
+ ObjectKind: gitlab.WebhookPush,
+ Ref: "refs/heads/feature/foo",
+ Project: gitlab.WebhookProject{
+ ID: 121,
+ },
+ CommitList: []gitlab.WebhookCommit{
+ {
+ Timestamp: "2021-01-13T13:14:00Z",
+ AddedList: []string{gitFile},
+ },
+ },
+ }
+ },
+ },
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ t.Parallel()
+
+ 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 table in the database
+ schemaFileContent := `CREATE TABLE projects (id serial PRIMARY KEY);`
+ _, err = pgDB.Exec(schemaFileContent)
+ a.NoError(err)
+
+ // Create a VCS
+ vcs, 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",
+ SchemaMigrationType: api.ProjectSchemaMigrationTypeSDL,
+ },
+ )
+ a.NoError(err)
+
+ // Create a repository
+ ctl.vcsProvider.CreateRepository(test.externalID)
+ _, err = ctl.createRepository(
+ api.RepositoryCreate{
+ VCSID: vcs.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",
+ },
+ )
+ 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 /* labelMap */)
+ a.NoError(err)
+
+ // Simulate Git commits for schema update to create a new table "book".
+ const gitFile = "bbtest/Prod/.testVCSSchemaUpdate__LATEST.sql"
+ schemaFileContent += "\nCREATE TABLE users (id serial PRIMARY KEY);"
+ err = ctl.vcsProvider.AddFiles(test.externalID, map[string]string{
+ gitFile: schemaFileContent,
+ })
+ a.NoError(err)
+
+ payload, err := json.Marshal(test.newWebhookPushEvent(gitFile))
+ a.NoError(err)
+ err = ctl.vcsProvider.SendWebhookPush(test.externalID, payload)
+ a.NoError(err)
+
+ // Get schema update issue
+ openStatus := []api.IssueStatus{api.IssueOpen}
+ issues, err := ctl.getIssues(
+ api.IssueFind{
+ ProjectID: &project.ID,
+ StatusList: openStatus,
+ },
+ )
+ a.NoError(err)
+ a.Len(issues, 1)
+ issue := issues[0]
+ status, err := ctl.waitIssuePipeline(issue.ID)
+ a.NoError(err)
+ a.Equal(api.TaskDone, status)
+ _, err = ctl.patchIssueStatus(
+ api.IssueStatusPatch{
+ ID: issue.ID,
+ Status: api.IssueDone,
+ },
+ )
+ a.NoError(err)
+
+ // Query list of tables
+ result, err := ctl.query(instance, databaseName, `
+SELECT table_name
+ FROM information_schema.tables
+WHERE table_type = 'BASE TABLE'
+ AND table_schema NOT IN
+ ('pg_catalog', 'information_schema');
+`)
+ a.NoError(err)
+ a.Equal(`[["table_name"],["NAME"],[["projects"],["users"]]]`, result)
+
+ // Get migration history
+ const initialSchema = `SET statement_timeout = 0;
+SET lock_timeout = 0;
+SET idle_in_transaction_session_timeout = 0;
+SET client_encoding = 'UTF8';
+SET standard_conforming_strings = on;
+SELECT pg_catalog.set_config('search_path', '', false);
+SET check_function_bodies = false;
+SET xmloption = content;
+SET client_min_messages = warning;
+SET row_security = off;
+
+`
+ histories, err := ctl.getInstanceMigrationHistory(db.MigrationHistoryFind{ID: &instance.ID})
+ a.NoError(err)
+ wantHistories := []api.MigrationHistory{
+ {
+ Database: databaseName,
+ Source: db.VCS,
+ Type: db.Migrate,
+ Status: db.Done,
+ Schema: `SET statement_timeout = 0;
+SET lock_timeout = 0;
+SET idle_in_transaction_session_timeout = 0;
+SET client_encoding = 'UTF8';
+SET standard_conforming_strings = on;
+SELECT pg_catalog.set_config('search_path', '', false);
+SET check_function_bodies = false;
+SET xmloption = content;
+SET client_min_messages = warning;
+SET row_security = off;
+
+SET default_tablespace = '';
+
+SET default_table_access_method = heap;
+
+CREATE TABLE public.projects (
+ id integer NOT NULL
+);
+
+CREATE SEQUENCE public.projects_id_seq
+ AS integer
+ START WITH 1
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+
+ALTER SEQUENCE public.projects_id_seq OWNED BY public.projects.id;
+
+CREATE TABLE public.users (
+ id integer NOT NULL
+);
+
+CREATE SEQUENCE public.users_id_seq
+ AS integer
+ START WITH 1
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+
+ALTER SEQUENCE public.users_id_seq OWNED BY public.users.id;
+
+ALTER TABLE ONLY public.projects ALTER COLUMN id SET DEFAULT nextval('public.projects_id_seq'::regclass);
+
+ALTER TABLE ONLY public.users ALTER COLUMN id SET DEFAULT nextval('public.users_id_seq'::regclass);
+
+ALTER TABLE ONLY public.projects
+ ADD CONSTRAINT projects_pkey PRIMARY KEY (id);
+
+ALTER TABLE ONLY public.users
+ ADD CONSTRAINT users_pkey PRIMARY KEY (id);
+
+`,
+ SchemaPrev: initialSchema,
+ },
+ {
+ Database: databaseName,
+ Source: db.UI,
+ Type: db.Migrate,
+ Status: db.Done,
+ Schema: initialSchema,
+ SchemaPrev: "",
+ },
+ }
+ a.Equal(len(wantHistories), len(histories))
+
+ for i, history := range histories {
+ got := api.MigrationHistory{
+ Database: history.Database,
+ Source: history.Source,
+ Type: history.Type,
+ Status: history.Status,
+ Schema: history.Schema,
+ SchemaPrev: history.SchemaPrev,
+ }
+ a.Equal(wantHistories[i], got, i)
+ a.NotEmpty(history.Version)
+ }
+ })
+ }
+}
+
func TestWildcardInVCSFilePathTemplate(t *testing.T) {
branchFilter := "feature/foo"
dbName := "db"
diff --git a/tests/tests.go b/tests/tests.go
index 55b511f57b..6818b742f2 100644
--- a/tests/tests.go
+++ b/tests/tests.go
@@ -120,6 +120,7 @@ func getTestPort(testName string) int {
"TestSchemaAndDataUpdate",
"TestVCS/GitLab",
"TestVCS/GitHub",
+ "TestVCS_SDL/GitLab",
"TestWildcardInVCSFilePathTemplate/emptyBaseAndMixAsterisks",
"TestWildcardInVCSFilePathTemplate/singleAsterisk",
"TestWildcardInVCSFilePathTemplate/doubleAsterisks",