Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(sbm): allow data type migration files (#2628)
Joe Chenc5cd2d20a33a
diff --git a/frontend/src/components/RepositoryForm.vue b/frontend/src/components/RepositoryForm.vueindex 49ef5581e8..d39a67b04d 100644--- a/frontend/src/components/RepositoryForm.vue+++ b/frontend/src/components/RepositoryForm.vue@@ -98,7 +98,7 @@</template></BBSelect></div>- <div v-if="isProjectSchemaMigrationTypeDDL">+ <div><div class="textlabel">{{ $t("repository.file-path-template") }}<span class="text-red-600">*</span>diff --git a/server/webhook.go b/server/webhook.goindex 8b5e419f66..17ca3aa588 100644--- a/server/webhook.go+++ b/server/webhook.go@@ -514,12 +514,35 @@ func (s *Server) readFileContent(ctx context.Context, pushEvent *vcs.PushEvent,// prepareIssueFromPushEventSDL returns the migration info and a list of update// schema details derived from the given push event for SDL.-func (s *Server) prepareIssueFromPushEventSDL(ctx context.Context, repo *api.Repository, pushEvent *vcs.PushEvent, schemaInfo map[string]string, file, webhookEndpointID string) (*db.MigrationInfo, []*api.UpdateSchemaDetail) {+func (s *Server) prepareIssueFromPushEventSDL(ctx context.Context, repo *api.Repository, pushEvent *vcs.PushEvent, schemaInfo map[string]string, file string, fileType fileItemType, webhookEndpointID string) (*db.MigrationInfo, []*api.UpdateSchemaDetail) {+ // Having no schema info indicates that the file is not a schema file (e.g.+ // "*__LATEST.sql"), try to parse the migration info see if it is a data update.if schemaInfo == nil {- log.Debug("Ignored non-schema file for SDL",- zap.String("file", file),- )- return nil, nil+ // NOTE: We do not want to use filepath.Join here because we always need "/" as the path separator.+ migrationInfo, err := db.ParseMigrationInfo(file, path.Join(repo.BaseDirectory, repo.FilePathTemplate))+ if err != nil {+ log.Error("Failed to parse migration info",+ zap.Int("project", repo.ProjectID),+ zap.Any("pushEvent", pushEvent),+ zap.String("file", file),+ zap.Error(err),+ )+ return nil, nil+ }++ // We only allow DML files when the project uses the state-based migration.+ if migrationInfo.Type != db.Data {+ s.createIgnoredFileActivity(+ ctx,+ repo.ProjectID,+ pushEvent,+ file,+ errors.Errorf("Only DATA type migration scripts are allowed but got %q", migrationInfo.Type),+ )+ return nil, nil+ }++ return migrationInfo, s.prepareIssueFromPushEventDDL(ctx, repo, pushEvent, nil, file, fileType, webhookEndpointID, migrationInfo)}dbName := schemaInfo["DB_NAME"]@@ -608,29 +631,18 @@ func (s *Server) prepareIssueFromPushEventSDL(ctx context.Context, repo *api.Repreturn migrationInfo, updateSchemaDetails}-// prepareIssueFromPushEventDDL returns the migration info and a list of update-// schema details derived from the given push event for DDL.-func (s *Server) prepareIssueFromPushEventDDL(ctx context.Context, repo *api.Repository, pushEvent *vcs.PushEvent, schemaInfo map[string]string, file string, fileType fileItemType, webhookEndpointID string) (*db.MigrationInfo, []*api.UpdateSchemaDetail) {+// prepareIssueFromPushEventDDL returns a list of update schema details derived+// from the given push event for DDL.+func (s *Server) prepareIssueFromPushEventDDL(ctx context.Context, repo *api.Repository, pushEvent *vcs.PushEvent, schemaInfo map[string]string, file string, fileType fileItemType, webhookEndpointID string, migrationInfo *db.MigrationInfo) []*api.UpdateSchemaDetail {// TODO(dragonly): handle modified file, try to update issue's SQL statement if the task is pending/failed.if fileType != fileItemTypeAdded || schemaInfo != nil {log.Debug("Ignored non-added or schema file for non-SDL",zap.String("file", file),zap.String("type", string(fileType)),)- return nil, nil+ return nil}- // NOTE: We do not want to use filepath.Join here because we always need "/" as the path separator.- migrationInfo, err := db.ParseMigrationInfo(file, path.Join(repo.BaseDirectory, repo.FilePathTemplate))- if err != nil {- log.Error("Failed to parse migration info",- zap.Int("project", repo.ProjectID),- zap.Any("pushEvent", pushEvent),- zap.String("file", file),- zap.Error(err),- )- return nil, nil- }migrationInfo.Creator = pushEvent.FileCommit.AuthorNamemiPayload := &db.MigrationInfoPayload{VCSPushEvent: pushEvent,@@ -643,7 +655,7 @@ func (s *Server) prepareIssueFromPushEventDDL(ctx context.Context, repo *api.Repzap.String("file", file),zap.Error(err),)- return nil, nil+ return nil}migrationInfo.Payload = string(bytes)@@ -656,7 +668,7 @@ func (s *Server) prepareIssueFromPushEventDDL(ctx context.Context, repo *api.Repfile,errors.Wrap(err, "Failed to read file content"),)- return nil, nil+ return nil}var updateSchemaDetails []*api.UpdateSchemaDetail@@ -677,7 +689,7 @@ func (s *Server) prepareIssueFromPushEventDDL(ctx context.Context, repo *api.Repfile,errors.Wrap(err, "Failed to find project databases"),)- return nil, nil+ return nil}for _, database := range databases {@@ -689,7 +701,7 @@ func (s *Server) prepareIssueFromPushEventDDL(ctx context.Context, repo *api.Rep)}}- return migrationInfo, updateSchemaDetails+ return updateSchemaDetails}// createIssueFromPushEvent attempts to create a new issue for the given file of@@ -729,9 +741,20 @@ func (s *Server) createIssueFromPushEvent(ctx context.Context, pushEvent *vcs.Puvar migrationInfo *db.MigrationInfovar updateSchemaDetails []*api.UpdateSchemaDetailif repo.Project.SchemaMigrationType == api.ProjectSchemaMigrationTypeSDL {- migrationInfo, updateSchemaDetails = s.prepareIssueFromPushEventSDL(ctx, repo, pushEvent, schemaInfo, file, webhookEndpointID)+ migrationInfo, updateSchemaDetails = s.prepareIssueFromPushEventSDL(ctx, repo, pushEvent, schemaInfo, file, fileType, webhookEndpointID)} else {- migrationInfo, updateSchemaDetails = s.prepareIssueFromPushEventDDL(ctx, repo, pushEvent, schemaInfo, file, fileType, webhookEndpointID)+ // NOTE: We do not want to use filepath.Join here because we always need "/" as the path separator.+ migrationInfo, err = db.ParseMigrationInfo(file, path.Join(repo.BaseDirectory, repo.FilePathTemplate))+ if err != nil {+ log.Error("Failed to parse migration info",+ zap.Int("project", repo.ProjectID),+ zap.Any("pushEvent", pushEvent),+ zap.String("file", file),+ zap.Error(err),+ )+ return "", false, nil+ }+ updateSchemaDetails = s.prepareIssueFromPushEventDDL(ctx, repo, pushEvent, schemaInfo, file, fileType, webhookEndpointID, migrationInfo)}if migrationInfo == nil || len(updateSchemaDetails) == 0 {diff --git a/tests/schema_update_test.go b/tests/schema_update_test.goindex 59284cd322..c296833bf7 100644--- a/tests/schema_update_test.go+++ b/tests/schema_update_test.go@@ -555,7 +555,7 @@ func TestVCS_SDL(t *testing.T) {vcsType vcs.TypeexternalID stringrepositoryFullPath string- newWebhookPushEvent func(gitFile string) interface{}+ newWebhookPushEvent func(added []string, modified []string) interface{}}{{name: "GitLab",@@ -563,7 +563,7 @@ func TestVCS_SDL(t *testing.T) {vcsType: vcs.GitLabSelfHost,externalID: "121",repositoryFullPath: "test/schemaUpdate",- newWebhookPushEvent: func(gitFile string) interface{} {+ newWebhookPushEvent: func(added []string, modified []string) interface{} {return gitlab.WebhookPushEvent{ObjectKind: gitlab.WebhookPush,Ref: "refs/heads/feature/foo",@@ -573,7 +573,8 @@ func TestVCS_SDL(t *testing.T) {CommitList: []gitlab.WebhookCommit{{Timestamp: "2021-01-13T13:14:00Z",- ModifiedList: []string{gitFile},+ AddedList: added,+ ModifiedList: modified,},},}@@ -585,7 +586,7 @@ func TestVCS_SDL(t *testing.T) {vcsType: vcs.GitHubCom,externalID: "octocat/Hello-World",repositoryFullPath: "octocat/Hello-World",- newWebhookPushEvent: func(gitFile string) interface{} {+ newWebhookPushEvent: func(added []string, modified []string) interface{} {return github.WebhookPushEvent{Ref: "refs/heads/feature/foo",Repository: github.WebhookRepository{@@ -607,7 +608,8 @@ func TestVCS_SDL(t *testing.T) {Name: "fake_github_author",Email: "fake_github_author@localhost",},- Modified: []string{gitFile},+ Added: added,+ Modified: modified,},},}@@ -725,15 +727,15 @@ func TestVCS_SDL(t *testing.T) {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"+ // Simulate Git commits for schema update to create a new table "users".+ const schemaFile = "bbtest/Prod/.testVCSSchemaUpdate__LATEST.sql"schemaFileContent += "\nCREATE TABLE users (id serial PRIMARY KEY);"err = ctl.vcsProvider.AddFiles(test.externalID, map[string]string{- gitFile: schemaFileContent,+ schemaFile: schemaFileContent,})a.NoError(err)- payload, err := json.Marshal(test.newWebhookPushEvent(gitFile))+ payload, err := json.Marshal(test.newWebhookPushEvent(nil /* added */, []string{schemaFile}))a.NoError(err)err = ctl.vcsProvider.SendWebhookPush(test.externalID, payload)a.NoError(err)@@ -760,6 +762,40 @@ func TestVCS_SDL(t *testing.T) {)a.NoError(err)+ // Simulate Git commits for data update to the table "users".+ const dataFile = "bbtest/Prod/testVCSSchemaUpdate__ver2__data__insert_data.sql"+ err = ctl.vcsProvider.AddFiles(test.externalID, map[string]string{+ dataFile: `INSERT INTO users (id) VALUES (1);`,+ })+ a.NoError(err)++ payload, err = json.Marshal(test.newWebhookPushEvent([]string{dataFile}, nil /* modified */))+ a.NoError(err)+ err = ctl.vcsProvider.SendWebhookPush(test.externalID, payload)+ a.NoError(err)++ // Get data 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 tablesresult, err := ctl.query(instance, databaseName, `SELECT table_name@@ -784,15 +820,7 @@ 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;+ const updatedSchema = `SET statement_timeout = 0;SET lock_timeout = 0;SET idle_in_transaction_session_timeout = 0;SET client_encoding = 'UTF8';@@ -845,7 +873,25 @@ ALTER TABLE ONLY public.projectsALTER TABLE ONLY public.usersADD CONSTRAINT users_pkey PRIMARY KEY (id);-`,+`++ histories, err := ctl.getInstanceMigrationHistory(db.MigrationHistoryFind{ID: &instance.ID})+ a.NoError(err)+ wantHistories := []api.MigrationHistory{+ {+ Database: databaseName,+ Source: db.VCS,+ Type: db.Data,+ Status: db.Done,+ Schema: updatedSchema,+ SchemaPrev: updatedSchema,+ },+ {+ Database: databaseName,+ Source: db.VCS,+ Type: db.Migrate,+ Status: db.Done,+ Schema: updatedSchema,SchemaPrev: initialSchema,},{