Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
Extend VCS support for supporting different schema file organization patterns
天舟4728a7c1cdb7
diff --git a/api/vcs.go b/api/vcs.goindex 3f7f7ff63b..1ccf1b369a 100644--- a/api/vcs.go+++ b/api/vcs.go@@ -112,6 +112,7 @@ type VCSFileCommit struct {type VCSPushEvent struct {VCSType VCSType `json:"vcsType"`+ BaseDirectory string `json:"baseDir"`Ref string `json:"ref"`RepositoryID string `json:"repoId"`RepositoryURL string `json:"repoUrl"`diff --git a/db/driver.go b/db/driver.goindex 05924bad34..847e6e63f9 100644--- a/db/driver.go+++ b/db/driver.go@@ -3,6 +3,7 @@ package dbimport ("context""fmt"+ "path/filepath""strings""sync"@@ -73,25 +74,35 @@ type MigrationInfo struct {Version stringNamespace stringDatabase string+ Environment stringType MigrationTypeDescription stringCreator string}-// Expected filename example, {{version}} can be arbitrary string without "_"-// - {{version}}_db1 (a normal migration without description)-// - {{version}}_db1_create_t1 (a normal migration with "create t1" as description)-// - {{version}}_db1_baseline (a baseline migration without description)-// - {{version}}_db1_baseline_create_t1 (a baseline migration with "create t1" as description)-func ParseMigrationInfo(filename string) (*MigrationInfo, error) {- parts := strings.Split(strings.TrimSuffix(filename, ".sql"), "_")+// ParseMigrationInfo derives MigrationInfo from fullPath and baseDir+// filepath is the full file path in the repository. The format is {{baseDir}}/[{{subdir}}/]/{{filename}}+// Expected filename example, {{version}} can be arbitrary string without "__"+// - {{version}}__db1 (a normal migration without description)+// - {{version}}__db1__create_t1 (a normal migration with "create t1" as description)+// - {{version}}__db1__baseline (a baseline migration without description)+// - {{version}}__db1__baseline__create_t1 (a baseline migration with "create t1" as description)+func ParseMigrationInfo(fullPath string, baseDir string) (*MigrationInfo, error) {+ filename := filepath.Base(fullPath)+ parentDir := filepath.Base(filepath.Clean(filepath.Dir(strings.TrimPrefix(fullPath, baseDir))))+ if parentDir == "." || parentDir == "/" {+ parentDir = ""+ }+ parts := strings.Split(strings.TrimSuffix(filename, ".sql"), "__")if len(parts) < 2 {- return nil, fmt.Errorf("invalid filename format, got %v, want {{version}}_{{dbname}}[_{{type}}][_{{description}}].sql", filename)+ return nil, fmt.Errorf("invalid filename format, got %v, want {{version}}__{{dbname}}[__{{type}}][__{{description}}].sql", filename)}+mi := &MigrationInfo{- Version: parts[0],- Namespace: parts[1],- Database: parts[1],+ Version: parts[0],+ Namespace: parts[1],+ Database: parts[1],+ Environment: parentDir,}migrationType := Sql@@ -114,6 +125,8 @@ func ParseMigrationInfo(filename string) (*MigrationInfo, error) {}}mi.Type = migrationType+ // Replace _ with space+ description = strings.ReplaceAll(description, "_", " ")// Capitalize first lettermi.Description = strings.ToUpper(description[:1]) + description[1:]diff --git a/db/driver_test.go b/db/driver_test.gonew file mode 100644index 0000000000..ca6d958078--- /dev/null+++ b/db/driver_test.go@@ -0,0 +1,161 @@+package db++import (+ "reflect"+ "strings"+ "testing"+)++func TestParseMigrationInfo(t *testing.T) {+ type test struct {+ fullPath string+ baseDir string+ want MigrationInfo+ wantErr string+ }++ tests := []test{+ {+ fullPath: "001foo__db1",+ baseDir: "",+ want: MigrationInfo{+ Version: "001foo",+ Namespace: "db1",+ Database: "db1",+ Environment: "",+ Type: "SQL",+ Description: "Create db1 migration",+ Creator: "",+ },+ wantErr: "",+ },+ {+ fullPath: "bytebase/001foo__db1",+ baseDir: "bytebase",+ want: MigrationInfo{+ Version: "001foo",+ Namespace: "db1",+ Database: "db1",+ Environment: "",+ Type: "SQL",+ Description: "Create db1 migration",+ Creator: "",+ },+ wantErr: "",+ },+ {+ fullPath: "bytebase/dev/001foo__db1",+ baseDir: "dev",+ want: MigrationInfo{+ Version: "001foo",+ Namespace: "db1",+ Database: "db1",+ Environment: "dev",+ Type: "SQL",+ Description: "Create db1 migration",+ Creator: "",+ },+ wantErr: "",+ },+ {+ fullPath: "bytebase/dev/001foo__db1",+ baseDir: "",+ want: MigrationInfo{+ Version: "001foo",+ Namespace: "db1",+ Database: "db1",+ Environment: "dev",+ Type: "SQL",+ Description: "Create db1 migration",+ Creator: "",+ },+ wantErr: "",+ },+ {+ fullPath: "001foo__db1__create_t1",+ baseDir: "",+ want: MigrationInfo{+ Version: "001foo",+ Namespace: "db1",+ Database: "db1",+ Environment: "",+ Type: "SQL",+ Description: "Create t1",+ Creator: "",+ },+ wantErr: "",+ },+ {+ fullPath: "001foo__db1__baseline",+ baseDir: "",+ want: MigrationInfo{+ Version: "001foo",+ Namespace: "db1",+ Database: "db1",+ Environment: "",+ Type: "BASELINE",+ Description: "Create db1 baseline",+ Creator: "",+ },+ wantErr: "",+ },+ {+ fullPath: "001foo__db1__baseline__create_t1",+ baseDir: "",+ want: MigrationInfo{+ Version: "001foo",+ Namespace: "db1",+ Database: "db1",+ Environment: "",+ Type: "BASELINE",+ Description: "Create t1",+ Creator: "",+ },+ wantErr: "",+ },+ {+ fullPath: "001foo__db_shop1__baseline__create_t1",+ baseDir: "",+ want: MigrationInfo{+ Version: "001foo",+ Namespace: "db_shop1",+ Database: "db_shop1",+ Environment: "",+ Type: "BASELINE",+ Description: "Create t1",+ Creator: "",+ },+ wantErr: "",+ },+ {+ fullPath: "001foo_db",+ baseDir: "",+ want: MigrationInfo{+ Version: "",+ Namespace: "",+ Database: "",+ Environment: "",+ Type: "",+ Description: "",+ Creator: "",+ },+ wantErr: "invalid filename format",+ },+ }++ for _, tc := range tests {+ mi, err := ParseMigrationInfo(tc.fullPath, tc.baseDir)+ if err != nil {+ if tc.wantErr == "" {+ t.Errorf("fullPath=%s, baseDir=%s: expected no error, got %w", tc.fullPath, tc.baseDir, err)+ } else if !strings.Contains(err.Error(), tc.wantErr) {+ t.Errorf("fullPath=%s, baseDir=%s: expected error %s, got %w", tc.fullPath, tc.baseDir, tc.wantErr, err)+ }+ } else {+ if !reflect.DeepEqual(tc.want, *mi) {+ t.Errorf("fullPath=%s, baseDir=%s: expected %+v, got %+v", tc.fullPath, tc.baseDir, tc.want, *mi)+ }+ }++ }+}diff --git a/server/task_executor_schema_update.go b/server/task_executor_schema_update.goindex 5e4e993c3c..c61cf299ad 100644--- a/server/task_executor_schema_update.go+++ b/server/task_executor_schema_update.go@@ -4,7 +4,6 @@ import ("context""encoding/json""fmt"- "path/filepath""strings""github.com/bytebase/bytebase/api"@@ -44,8 +43,7 @@ func (exec *SchemaUpdateTaskExecutor) RunOnce(ctx context.Context, server *ServeType: db.Sql,}if payload.VCSPushEvent != nil {- filename := filepath.Base(payload.VCSPushEvent.FileCommit.Added)- mi, err = db.ParseMigrationInfo(filename)+ mi, err = db.ParseMigrationInfo(payload.VCSPushEvent.FileCommit.Added, payload.VCSPushEvent.BaseDirectory)// This should not happen normally as we already check this when creating the issue. Just in case.if err != nil {return true, fmt.Errorf("failed to start schema migration, error: %w", err)diff --git a/server/webhook.go b/server/webhook.goindex 7c92ed9117..25fbae920b 100644--- a/server/webhook.go+++ b/server/webhook.go@@ -72,10 +72,9 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {for _, commit := range pushEvent.CommitList {for _, added := range commit.AddedList {if strings.HasPrefix(added, repository.BaseDirectory) && filepath.Ext(added) == ".sql" {- filename := filepath.Base(added)- mi, err := db.ParseMigrationInfo(filename)+ mi, err := db.ParseMigrationInfo(added, repository.BaseDirectory)if err != nil {- s.l.Warn("invalid migration filename. Ignored", zap.Error(err))+ s.l.Warn("Invalid migration filename. Ignored", zap.Error(err))continue}@@ -86,42 +85,73 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {repository.VCS.AccessToken,)if err != nil {- s.l.Warn("Failed to read file. Ignored", zap.String("filename", filename), zap.Error(err))+ s.l.Warn("Failed to read file. Ignored", zap.String("file", added), zap.Error(err))continue}b, err := io.ReadAll(resp.Body)if err != nil {- s.l.Warn("Failed to read file response. Ignored", zap.String("filename", filename), zap.Error(err))+ s.l.Warn("Failed to read file response. Ignored", zap.String("file", added), zap.Error(err))continue}- // Find matching database+ // Find matching database listdatabaseFind := &api.DatabaseFind{ProjectId: &repository.ProjectId,Name: &mi.Database,}- database, err := s.ComposeDatabaseByFind(context.Background(), databaseFind, []string{})+ databaseList, err := s.ComposeDatabaseListByFind(context.Background(), databaseFind, []string{})if err != nil {- if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {- s.l.Warn(fmt.Sprintf("Project ID %d does not contain database %s. Ignored", repository.ProjectId, mi.Database),+ s.l.Warn("Failed to find database. Ignored", zap.String("file", added), zap.Error(err))+ continue+ } else if len(databaseList) == 0 {+ s.l.Warn(fmt.Sprintf("Project ID %d does not contain database %s. Ignored", repository.ProjectId, mi.Database),+ zap.Int("project_id", repository.ProjectId),+ zap.String("file", added),+ )+ continue+ }++ // 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.+ filterdDatabaseList := []*api.Database{}+ if mi.Environment != "" {+ for _, database := range databaseList {+ // Environment name comparision is case insensitive+ if strings.EqualFold(database.Instance.Environment.Name, mi.Environment) {+ filterdDatabaseList = append(filterdDatabaseList, database)+ }+ }+ if len(filterdDatabaseList) == 0 {+ s.l.Warn(fmt.Sprintf("Project ID %d does not contain database %s for environment %s. Ignored", repository.ProjectId, mi.Database, mi.Environment),zap.Int("project_id", repository.ProjectId),- zap.String("filename", filename),+ zap.String("environment", mi.Environment),+ zap.String("file", added),)-- } else {- s.l.Warn("Failed to find database. Ignored", zap.String("filename", filename), zap.Error(err))+ continue}- continue+ } else {+ filterdDatabaseList = databaseList}// Compose the new issuecreatedTime, err := time.Parse(time.RFC3339, commit.Timestamp)if err != nil {- s.l.Warn("Failed to parse timestamp. Ignored", zap.String("filename", filename), zap.Error(err))+ s.l.Warn("Failed to parse timestamp. Ignored", zap.String("file", added), zap.Error(err))}vcsPushEvent := api.VCSPushEvent{VCSType: repository.VCS.Type,+ BaseDirectory: repository.BaseDirectory,Ref: pushEvent.Ref,RepositoryID: strconv.Itoa(pushEvent.Project.ID),RepositoryURL: pushEvent.Project.WebURL,@@ -137,27 +167,31 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {Added: added,},}- databaseID := database.ID- task := &api.TaskCreate{- InstanceId: database.InstanceId,- DatabaseId: &databaseID,- Name: mi.Description,- Status: "PENDING",- Type: api.TaskDatabaseSchemaUpdate,- Statement: string(b),- VCSPushEvent: &vcsPushEvent,- }- stage := &api.StageCreate{- EnvironmentId: database.Instance.EnvironmentId,- TaskList: []api.TaskCreate{*task},- Name: database.Instance.Environment.Name,++ stageList := []api.StageCreate{}+ for _, database := range filterdDatabaseList {+ databaseID := database.ID+ task := &api.TaskCreate{+ InstanceId: database.InstanceId,+ DatabaseId: &databaseID,+ Name: mi.Description,+ Status: "PENDING",+ Type: api.TaskDatabaseSchemaUpdate,+ Statement: string(b),+ VCSPushEvent: &vcsPushEvent,+ }+ stageList = append(stageList, api.StageCreate{+ EnvironmentId: database.Instance.EnvironmentId,+ TaskList: []api.TaskCreate{*task},+ Name: database.Instance.Environment.Name,+ })}pipeline := &api.PipelineCreate{- StageList: []api.StageCreate{*stage},+ StageList: stageList,Name: fmt.Sprintf("Pipeline - %s", commit.Title),}issueCreate := &api.IssueCreate{- ProjectId: database.ProjectId,+ ProjectId: repository.ProjectId,Pipeline: *pipeline,Name: commit.Title,Type: api.IssueDatabaseSchemaUpdate,@@ -167,11 +201,11 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {issue, err := s.CreateIssue(context.Background(), issueCreate, api.SYSTEM_BOT_ID)if err != nil {- s.l.Warn(fmt.Sprintf("Failed to create update schema task after adding %s", filename), zap.Error(err),- zap.String("filename", filename))+ s.l.Warn(fmt.Sprintf("Failed to create update schema task after adding %s", added), zap.Error(err),+ zap.String("file", added))continue}- createdMessageList = append(createdMessageList, fmt.Sprintf("Created issue '%s' on adding %s", issue.Name, filename))+ createdMessageList = append(createdMessageList, fmt.Sprintf("Created issue '%s' on adding %s", issue.Name, added))}}}