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(VCS): modified file changes existing issue statement (#2635)
Yilong Lif0c56f7c47ad
diff --git a/api/task.go b/api/task.goindex e1856461ed..b66d8fb535 100644--- a/api/task.go+++ b/api/task.go@@ -217,9 +217,14 @@ type TaskFind struct {// Related fieldsPipelineID *intStageID *int+ DatabaseID *int// Domain specific fieldsStatusList *[]TaskStatus+ TypeList *[]TaskType+ // Payload contains JSONB expressions+ // Ref: https://www.postgresql.org/docs/current/functions-json.html+ Payload string}func (find *TaskFind) String() string {diff --git a/server/task.go b/server/task.goindex 9d1e0236a0..aa620394da 100644--- a/server/task.go+++ b/server/task.go@@ -249,8 +249,8 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {}func (s *Server) patchTask(ctx context.Context, task *api.Task, taskPatch *api.TaskPatch, issue *api.Issue) (*api.Task, *echo.HTTPError) {- oldStatement := ""- newStatement := ""+ var oldStatement string+ var newStatement stringif taskPatch.Statement != nil {if httpErr := s.canUpdateTaskStatement(ctx, task); httpErr != nil {return nil, httpErr@@ -265,9 +265,14 @@ func (s *Server) patchTask(ctx context.Context, task *api.Task, taskPatch *api.T}oldStatement = payload.Statementpayload.Statement = *taskPatch.Statement- // We should update the schema version if we've updated the SQL, otherwise we will- // get migration history version conflict if the previous task has been attempted.- payload.SchemaVersion = common.DefaultMigrationVersion()+ // 1. For VCS workflows, patchTask only happens when we modify the same file.+ // In that case, we want to use the same schema version parsed from the file name.+ // The task executor will force retry using the new SQL statement.+ // 2. We should update the schema version if we've updated the SQL in the UI workflow, otherwise we will+ // get migration history version conflict if the previous task has been attempted.+ if issue.Project.WorkflowType == api.UIWorkflow {+ payload.SchemaVersion = common.DefaultMigrationVersion()+ }bytes, err := json.Marshal(payload)if err != nil {return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to construct updated task payload").SetInternal(err)@@ -281,9 +286,14 @@ func (s *Server) patchTask(ctx context.Context, task *api.Task, taskPatch *api.T}oldStatement = payload.Statementpayload.Statement = *taskPatch.Statement- // We should update the schema version if we've updated the SQL, otherwise we will- // get migration history version conflict if the previous task has been attempted.- payload.SchemaVersion = common.DefaultMigrationVersion()+ // 1. For VCS workflows, patchTask only happens when we modify the same file.+ // In that case, we want to use the same schema version parsed from the file name.+ // The task executor will force retry using the new SQL statement.+ // 2. We should update the schema version if we've updated the SQL in the UI workflow, otherwise we will+ // get migration history version conflict if the previous task has been attempted.+ if issue.Project.WorkflowType == api.UIWorkflow {+ payload.SchemaVersion = common.DefaultMigrationVersion()+ }bytes, err := json.Marshal(payload)if err != nil {return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to construct updated task payload").SetInternal(err)diff --git a/server/task_executor.go b/server/task_executor.goindex 4af51384ed..f86a9fbb48 100644--- a/server/task_executor.go+++ b/server/task_executor.go@@ -113,7 +113,8 @@ func preMigration(ctx context.Context, server *Server, task *api.Task, migration}// We will force migration for baseline and migrate type of migrations.// This usually happens when the previous attempt fails and the client retries the migration.- if mi.Type == db.Baseline || mi.Type == db.Migrate {+ // We also force migration for VCS migrations, which is usually a modified file to correct a former wrong migration commit.+ if mi.Type == db.Baseline || mi.Type == db.Migrate || mi.Type == db.Data {mi.Force = true}diff --git a/server/webhook.go b/server/webhook.goindex f1333ff31d..404e040b6d 100644--- a/server/webhook.go+++ b/server/webhook.go@@ -216,16 +216,13 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {},)}-- if repo.Project.SchemaChangeType == api.ProjectSchemaChangeTypeSDL {- for _, modified := range commit.Modified {- files = append(files,- fileItem{- name: modified,- itemType: fileItemTypeModified,- },- )- }+ for _, modified := range commit.Modified {+ files = append(files,+ fileItem{+ name: modified,+ itemType: fileItemTypeModified,+ },+ )}for _, file := range files {@@ -640,9 +637,8 @@ func (s *Server) prepareIssueFromPushEventSDL(ctx context.Context, repo *api.Rep// 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",+ if schemaInfo != nil {+ log.Debug("Ignored schema file for non-SDL",zap.String("file", file),zap.String("type", string(fileType)),)@@ -662,6 +658,8 @@ func (s *Server) prepareIssueFromPushEventDDL(ctx context.Context, repo *api.Rep}var updateSchemaDetails []*api.UpdateSchemaDetail++ // TODO(dragonly): handle modified file for tenant mode.if repo.Project.TenantMode == api.TenantModeTenant {updateSchemaDetails = append(updateSchemaDetails,&api.UpdateSchemaDetail{@@ -670,8 +668,43 @@ func (s *Server) prepareIssueFromPushEventDDL(ctx context.Context, repo *api.RepSchemaVersion: migrationInfo.Version,},)- } else {- databases, err := s.findProjectDatabases(ctx, repo.ProjectID, repo.Project.TenantMode, migrationInfo.Database, migrationInfo.Environment)+ return updateSchemaDetails+ }++ databases, err := s.findProjectDatabases(ctx, repo.ProjectID, repo.Project.TenantMode, migrationInfo.Database, migrationInfo.Environment)+ if err != nil {+ s.createIgnoredFileActivity(+ ctx,+ repo.ProjectID,+ pushEvent,+ file,+ errors.Wrap(err, "Failed to find project databases"),+ )+ return nil+ }++ if fileType == fileItemTypeAdded {+ for _, database := range databases {+ updateSchemaDetails = append(updateSchemaDetails,+ &api.UpdateSchemaDetail{+ DatabaseID: database.ID,+ Statement: content,+ SchemaVersion: migrationInfo.Version,+ },+ )+ }+ return updateSchemaDetails+ }++ // For modified files, we try to update the existing issue's statement.+ for _, database := range databases {+ find := &api.TaskFind{+ DatabaseID: &database.ID,+ StatusList: &[]api.TaskStatus{api.TaskPendingApproval, api.TaskFailed},+ TypeList: &[]api.TaskType{api.TaskDatabaseSchemaUpdate, api.TaskDatabaseDataUpdate},+ Payload: fmt.Sprintf("payload->>'schemaVersion' = '%s'", migrationInfo.Version),+ }+ taskList, err := s.store.FindTask(ctx, find, true)if err != nil {s.createIgnoredFileActivity(ctx,@@ -682,18 +715,33 @@ func (s *Server) prepareIssueFromPushEventDDL(ctx context.Context, repo *api.Rep)return nil}-- for _, database := range databases {- updateSchemaDetails = append(updateSchemaDetails,- &api.UpdateSchemaDetail{- DatabaseID: database.ID,- Statement: content,- SchemaVersion: migrationInfo.Version,- },- )+ if len(taskList) == 0 {+ continue+ }+ if len(taskList) > 1 {+ log.Error("Found more than one pending approval or failed tasks for modified VCS file, should be only one task.", zap.Int("databaseID", database.ID), zap.String("schemaVersion", migrationInfo.Version))+ return nil+ }+ task := taskList[0]+ taskPatch := api.TaskPatch{+ ID: task.ID,+ Statement: &content,+ UpdaterID: api.SystemBotID,+ }+ issue, err := s.store.GetIssueByPipelineID(ctx, task.PipelineID)+ if err != nil {+ log.Error(fmt.Sprintf("Failed to get issue by pipeline ID %d", task.PipelineID), zap.Error(err))+ return nil+ }+ // TODO(dragonly): Try to patch the failed migration history record to pending, and the statement to the current modified file content.+ log.Debug("Patching task for modified file VCS push event", zap.String("fileName", file), zap.Int("issueID", issue.ID), zap.Int("taskID", task.ID))+ if _, err := s.patchTask(ctx, task, &taskPatch, issue); err != nil {+ log.Error("Failed to patch task with the same migration version", zap.Int("issueID", issue.ID), zap.Int("taskID", task.ID), zap.Error(err))+ return nil}}- return updateSchemaDetails++ return nil}// createIssueFromPushEvent attempts to create a new issue for the given file ofdiff --git a/store/task.go b/store/task.goindex b8f3438b4a..592d8007c1 100644--- a/store/task.go+++ b/store/task.go@@ -490,6 +490,9 @@ func (s *Store) findTaskImpl(ctx context.Context, tx *Tx, find *api.TaskFind) ([if v := find.StageID; v != nil {where, args = append(where, fmt.Sprintf("stage_id = $%d", len(args)+1)), append(args, *v)}+ if v := find.DatabaseID; v != nil {+ where, args = append(where, fmt.Sprintf("database_id = $%d", len(args)+1)), append(args, *v)+ }if v := find.StatusList; v != nil {list := []string{}for _, status := range *v {@@ -498,6 +501,17 @@ func (s *Store) findTaskImpl(ctx context.Context, tx *Tx, find *api.TaskFind) ([}where = append(where, fmt.Sprintf("status in (%s)", strings.Join(list, ",")))}+ if v := find.TypeList; v != nil {+ var list []string+ for _, taskType := range *v {+ list = append(list, fmt.Sprintf("$%d", len(args)+1))+ args = append(args, taskType)+ }+ where = append(where, fmt.Sprintf("type in (%s)", strings.Join(list, ",")))+ }+ if v := find.Payload; v != "" {+ where = append(where, v)+ }rows, err := tx.QueryContext(ctx, `SELECTdiff --git a/tests/schema_update_test.go b/tests/schema_update_test.goindex 77dacc5faf..633d29d2b6 100644--- a/tests/schema_update_test.go+++ b/tests/schema_update_test.go@@ -287,7 +287,7 @@ func TestVCS(t *testing.T) {vcsType vcs.TypeexternalID stringrepositoryFullPath string- newWebhookPushEvent func(gitFile string) interface{}+ newWebhookPushEvent func(added []string, modified []string) interface{}}{{name: "GitLab",@@ -295,7 +295,7 @@ func TestVCS(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",@@ -304,8 +304,9 @@ func TestVCS(t *testing.T) {},CommitList: []gitlab.WebhookCommit{{- Timestamp: "2021-01-13T13:14:00Z",- AddedList: []string{gitFile},+ Timestamp: "2021-01-13T13:14:00Z",+ AddedList: added,+ ModifiedList: modified,},},}@@ -317,7 +318,7 @@ func TestVCS(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{@@ -339,7 +340,8 @@ func TestVCS(t *testing.T) {Name: "fake_github_author",Email: "fake_github_author@localhost",},- Added: []string{gitFile},+ Added: added,+ Modified: modified,},},}@@ -435,7 +437,7 @@ func TestVCS(t *testing.T) {err = ctl.vcsProvider.AddFiles(test.externalID, map[string]string{gitFile: migrationStatement})a.NoError(err)- payload, err := json.Marshal(test.newWebhookPushEvent(gitFile))+ payload, err := json.Marshal(test.newWebhookPushEvent([]string{gitFile}, nil))a.NoError(err)err = ctl.vcsProvider.SendWebhookPush(test.externalID, payload)a.NoError(err)@@ -467,12 +469,35 @@ func TestVCS(t *testing.T) {a.NoError(err)a.Equal(bookSchemaSQLResult, result)- // Simulate Git commits for schema update.+ // Simulate Git commits for failed data update.gitFile = "bbtest/Prod/testVCSSchemaUpdate__ver2__data__insert_data.sql"- err = ctl.vcsProvider.AddFiles(test.externalID, map[string]string{gitFile: dataUpdateStatement})+ err = ctl.vcsProvider.AddFiles(test.externalID, map[string]string{gitFile: dataUpdateStatementWrong})a.NoError(err)- payload, err = json.Marshal(test.newWebhookPushEvent(gitFile))+ payload, err = json.Marshal(test.newWebhookPushEvent([]string{gitFile}, nil))+ 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.Error(err)+ a.Equal(api.TaskFailed, status)++ // Simulate Git commits for a correct modified date update.+ err = ctl.vcsProvider.AddFiles(test.externalID, map[string]string{gitFile: dataUpdateStatement})+ a.NoError(err)+ payload, err = json.Marshal(test.newWebhookPushEvent(nil, []string{gitFile}))a.NoError(err)err = ctl.vcsProvider.SendWebhookPush(test.externalID, payload)a.NoError(err)@@ -491,6 +516,7 @@ func TestVCS(t *testing.T) {status, err = ctl.waitIssuePipeline(issue.ID)a.NoError(err)a.Equal(api.TaskDone, status)+_, err = ctl.patchIssueStatus(api.IssueStatusPatch{ID: issue.ID,diff --git a/tests/tests.go b/tests/tests.goindex da18af2509..574ae088a4 100644--- a/tests/tests.go+++ b/tests/tests.go@@ -46,7 +46,8 @@ var (bookDataQuery = `SELECT * FROM book;`bookDataSQLResult = `[["id","name"],["INTEGER","TEXT"],[[1,"byte"],[2,null]]]`- dataUpdateStatement = `+ dataUpdateStatementWrong = "INSERT INTO book(name) xxx"+ dataUpdateStatement = `INSERT INTO book(name) VALUES("byte"),(NULL);