Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: update UpdatePlan (#12068)
boojack328f72edb052
diff --git a/backend/api/v1/plan_service.go b/backend/api/v1/plan_service.goindex 6f7eb89e04..315cebecea 100644--- a/backend/api/v1/plan_service.go+++ b/backend/api/v1/plan_service.go@@ -229,16 +229,6 @@ func (s *PlanService) UpdatePlan(ctx context.Context, request *v1pb.UpdatePlanReif project == nil {return nil, status.Errorf(codes.NotFound, "project %q not found", oldPlan.ProjectID)}- for _, path := range request.UpdateMask.Paths {- switch path {- case "steps":- if _, err := GetPipelineCreate(ctx, s.store, s.licenseService, s.dbFactory, convertPlanSteps(request.Plan.GetSteps()), project); err != nil {- return nil, status.Errorf(codes.InvalidArgument, "failed to get pipeline from the plan, please check you request, error: %v", err)- }- default:- return nil, status.Errorf(codes.InvalidArgument, "invalid update_mask path %q", path)- }- }ok, err = func() (bool, error) {if oldPlan.CreatorUID == user.ID {@@ -253,398 +243,478 @@ func (s *PlanService) UpdatePlan(ctx context.Context, request *v1pb.UpdatePlanRereturn nil, status.Errorf(codes.PermissionDenied, "permission denied to update plan")}- oldSteps := convertToPlanSteps(oldPlan.Config.Steps)-- issue, err := s.store.GetIssueV2(ctx, &store.FindIssueMessage{PlanUID: &oldPlan.UID})- if err != nil {- return nil, status.Errorf(codes.Internal, "failed to get issue: %v", err)- }-- removed, added, updated := diffSpecs(oldSteps, request.Plan.Steps)- if len(removed) > 0 {- return nil, status.Errorf(codes.InvalidArgument, "cannot remove specs from plan")- }- if len(added) > 0 {- return nil, status.Errorf(codes.InvalidArgument, "cannot add specs to plan")- }- if len(updated) == 0 {- return nil, status.Errorf(codes.InvalidArgument, "no specs updated")- }-- oldSpecsByID := make(map[string]*v1pb.Plan_Spec)- for _, step := range oldSteps {- for _, spec := range step.Specs {- oldSpecsByID[spec.Id] = spec- }- }-- updatedByID := make(map[string]*v1pb.Plan_Spec)- for _, spec := range updated {- updatedByID[spec.Id] = spec- }-- tasksMap := map[int]*store.TaskMessage{}- var taskPatchList []*api.TaskPatch- var statementUpdates []api.ActivityPipelineTaskStatementUpdatePayload- var earliestUpdates []api.ActivityPipelineTaskEarliestAllowedTimeUpdatePayload- var taskDAGRebuildList []struct {- fromTaskIDs []int- toTaskID int+ planUpdate := &store.UpdatePlanMessage{+ UID: oldPlan.UID,+ UpdaterID: user.ID,}- if oldPlan.PipelineUID != nil {- tasks, err := s.store.ListTasks(ctx, &api.TaskFind{PipelineID: oldPlan.PipelineUID})- if err != nil {- return nil, status.Errorf(codes.Internal, "failed to list tasks: %v", err)- }- tasksBySpecID := make(map[string][]*store.TaskMessage)- for _, task := range tasks {- var taskSpecID struct {- SpecID string `json:"specId"`- }- if err := json.Unmarshal([]byte(task.Payload), &taskSpecID); err != nil {- return nil, status.Errorf(codes.Internal, "failed to unmarshal task payload: %v", err)+ var doUpdateSheet bool+ for _, path := range request.UpdateMask.Paths {+ switch path {+ case "title":+ title := request.Plan.Title+ planUpdate.Name = &title+ case "description":+ description := request.Plan.Description+ planUpdate.Description = &description+ case "steps":+ if _, err := GetPipelineCreate(ctx, s.store, s.licenseService, s.dbFactory, convertPlanSteps(request.Plan.GetSteps()), project); err != nil {+ return nil, status.Errorf(codes.InvalidArgument, "failed to get pipeline from the plan, please check you request, error: %v", err)}- tasksBySpecID[taskSpecID.SpecID] = append(tasksBySpecID[taskSpecID.SpecID], task)- }- for _, task := range tasks {- doUpdate := false- taskPatch := &api.TaskPatch{- ID: task.ID,- UpdaterID: user.ID,++ oldSteps := convertToPlanSteps(oldPlan.Config.Steps)+ issue, err := s.store.GetIssueV2(ctx, &store.FindIssueMessage{PlanUID: &oldPlan.UID})+ if err != nil {+ return nil, status.Errorf(codes.Internal, "failed to get issue: %v", err)}- tasksMap[task.ID] = task- var taskSpecID struct {- SpecID string `json:"specId"`+ removed, added, updated := diffSpecs(oldSteps, request.Plan.Steps)+ if len(removed) > 0 {+ return nil, status.Errorf(codes.InvalidArgument, "cannot remove specs from plan")}- if err := json.Unmarshal([]byte(task.Payload), &taskSpecID); err != nil {- return nil, status.Errorf(codes.Internal, "failed to unmarshal task payload: %v", err)+ if len(added) > 0 {+ return nil, status.Errorf(codes.InvalidArgument, "cannot add specs to plan")}- spec, ok := updatedByID[taskSpecID.SpecID]- if !ok {- continue+ if len(updated) == 0 {+ return nil, status.Errorf(codes.InvalidArgument, "no specs updated")}- // Flags for gh-ost.- if err := func() error {- if task.Type != api.TaskDatabaseSchemaUpdateGhostSync {- return nil+ oldSpecsByID := make(map[string]*v1pb.Plan_Spec)+ for _, step := range oldSteps {+ for _, spec := range step.Specs {+ oldSpecsByID[spec.Id] = spec}- payload := &api.TaskDatabaseSchemaUpdateGhostSyncPayload{}- if err := json.Unmarshal([]byte(task.Payload), payload); err != nil {- return status.Errorf(codes.Internal, "failed to unmarshal task payload: %v", err)- }- newFlags := spec.GetChangeDatabaseConfig().GetGhostFlags()- if _, err := ghost.GetUserFlags(newFlags); err != nil {- return status.Errorf(codes.InvalidArgument, "invalid ghost flags %q, error %v", newFlags, err)- }- oldFlags := payload.Flags- if cmp.Equal(oldFlags, newFlags) {- return nil- }- taskPatch.Flags = &newFlags- doUpdate = true- return nil- }(); err != nil {- return nil, err}- // EarliestAllowedTs- if spec.EarliestAllowedTime.GetSeconds() != task.EarliestAllowedTs {- seconds := spec.EarliestAllowedTime.GetSeconds()- taskPatch.EarliestAllowedTs = &seconds- doUpdate = true- earliestUpdates = append(earliestUpdates, api.ActivityPipelineTaskEarliestAllowedTimeUpdatePayload{- TaskID: task.ID,- OldEarliestAllowedTs: task.EarliestAllowedTs,- NewEarliestAllowedTs: seconds,- IssueName: issue.Title,- TaskName: task.Name,- })+ updatedByID := make(map[string]*v1pb.Plan_Spec)+ for _, spec := range updated {+ updatedByID[spec.Id] = spec}- // RollbackEnabled- if err := func() error {- if task.Type != api.TaskDatabaseDataUpdate {- return nil- }- payload := &api.TaskDatabaseDataUpdatePayload{}- if err := json.Unmarshal([]byte(task.Payload), payload); err != nil {- return status.Errorf(codes.Internal, "failed to unmarshal task payload: %v", err)- }- config, ok := spec.Config.(*v1pb.Plan_Spec_ChangeDatabaseConfig)- if !ok {- return nil- }- if config.ChangeDatabaseConfig.RollbackEnabled != payload.RollbackEnabled {- taskPatch.RollbackEnabled = &config.ChangeDatabaseConfig.RollbackEnabled- doUpdate = true- }- return nil- }(); err != nil {- return nil, err+ tasksMap := map[int]*store.TaskMessage{}+ var taskPatchList []*api.TaskPatch+ var statementUpdates []api.ActivityPipelineTaskStatementUpdatePayload+ var earliestUpdates []api.ActivityPipelineTaskEarliestAllowedTimeUpdatePayload+ var taskDAGRebuildList []struct {+ fromTaskIDs []int+ toTaskID int}- // PreUpdateBackupDetail- if err := func() error {- if task.Type != api.TaskDatabaseDataUpdate {- return nil+ if oldPlan.PipelineUID != nil {+ tasks, err := s.store.ListTasks(ctx, &api.TaskFind{PipelineID: oldPlan.PipelineUID})+ if err != nil {+ return nil, status.Errorf(codes.Internal, "failed to list tasks: %v", err)}- payload := &api.TaskDatabaseDataUpdatePayload{}- if err := json.Unmarshal([]byte(task.Payload), payload); err != nil {- return status.Errorf(codes.Internal, "failed to unmarshal task payload: %v", err)- }- config, ok := spec.Config.(*v1pb.Plan_Spec_ChangeDatabaseConfig)- if !ok {- return nil+ tasksBySpecID := make(map[string][]*store.TaskMessage)+ for _, task := range tasks {+ var taskSpecID struct {+ SpecID string `json:"specId"`+ }+ if err := json.Unmarshal([]byte(task.Payload), &taskSpecID); err != nil {+ return nil, status.Errorf(codes.Internal, "failed to unmarshal task payload: %v", err)+ }+ tasksBySpecID[taskSpecID.SpecID] = append(tasksBySpecID[taskSpecID.SpecID], task)}+ for _, task := range tasks {+ doUpdate := false+ taskPatch := &api.TaskPatch{+ ID: task.ID,+ UpdaterID: user.ID,+ }+ tasksMap[task.ID] = task- var databaseName *string- if config.ChangeDatabaseConfig.PreUpdateBackupDetail == nil {- if payload.PreUpdateBackupDetail.Database != "" {- emptyValue := ""- databaseName = &emptyValue+ var taskSpecID struct {+ SpecID string `json:"specId"`}- } else {- if config.ChangeDatabaseConfig.PreUpdateBackupDetail.Database != payload.PreUpdateBackupDetail.Database {- databaseName = &config.ChangeDatabaseConfig.PreUpdateBackupDetail.Database+ if err := json.Unmarshal([]byte(task.Payload), &taskSpecID); err != nil {+ return nil, status.Errorf(codes.Internal, "failed to unmarshal task payload: %v", err)}- }- if databaseName != nil {- taskPatch.PreUpdateBackupDetail = &api.PreUpdateBackupDetail{- Database: *databaseName,+ spec, ok := updatedByID[taskSpecID.SpecID]+ if !ok {+ continue}- doUpdate = true- }- return nil- }(); err != nil {- return nil, err- }- // Sheet- if err := func() error {- switch task.Type {- case api.TaskDatabaseSchemaUpdate, api.TaskDatabaseSchemaUpdateSDL, api.TaskDatabaseSchemaUpdateGhostSync, api.TaskDatabaseDataUpdate, api.TaskDatabaseDataExport:- var taskPayload struct {- SheetID int `json:"sheetId"`+ // Flags for gh-ost.+ if err := func() error {+ if task.Type != api.TaskDatabaseSchemaUpdateGhostSync {+ return nil+ }+ payload := &api.TaskDatabaseSchemaUpdateGhostSyncPayload{}+ if err := json.Unmarshal([]byte(task.Payload), payload); err != nil {+ return status.Errorf(codes.Internal, "failed to unmarshal task payload: %v", err)+ }+ newFlags := spec.GetChangeDatabaseConfig().GetGhostFlags()+ if _, err := ghost.GetUserFlags(newFlags); err != nil {+ return status.Errorf(codes.InvalidArgument, "invalid ghost flags %q, error %v", newFlags, err)+ }+ oldFlags := payload.Flags+ if cmp.Equal(oldFlags, newFlags) {+ return nil+ }+ taskPatch.Flags = &newFlags+ doUpdate = true+ return nil+ }(); err != nil {+ return nil, err}- if err := json.Unmarshal([]byte(task.Payload), &taskPayload); err != nil {- return status.Errorf(codes.Internal, "failed to unmarshal task payload: %v", err)++ // EarliestAllowedTs+ if spec.EarliestAllowedTime.GetSeconds() != task.EarliestAllowedTs {+ seconds := spec.EarliestAllowedTime.GetSeconds()+ taskPatch.EarliestAllowedTs = &seconds+ doUpdate = true+ earliestUpdates = append(earliestUpdates, api.ActivityPipelineTaskEarliestAllowedTimeUpdatePayload{+ TaskID: task.ID,+ OldEarliestAllowedTs: task.EarliestAllowedTs,+ NewEarliestAllowedTs: seconds,+ IssueName: issue.Title,+ TaskName: task.Name,+ })}- var oldSheetName string- if task.Type == api.TaskDatabaseDataExport {- config, ok := spec.Config.(*v1pb.Plan_Spec_ExportDataConfig)+ // RollbackEnabled+ if err := func() error {+ if task.Type != api.TaskDatabaseDataUpdate {+ return nil+ }+ payload := &api.TaskDatabaseDataUpdatePayload{}+ if err := json.Unmarshal([]byte(task.Payload), payload); err != nil {+ return status.Errorf(codes.Internal, "failed to unmarshal task payload: %v", err)+ }+ config, ok := spec.Config.(*v1pb.Plan_Spec_ChangeDatabaseConfig)if !ok {return nil}- oldSheetName = config.ExportDataConfig.Sheet- } else {+ if config.ChangeDatabaseConfig.RollbackEnabled != payload.RollbackEnabled {+ taskPatch.RollbackEnabled = &config.ChangeDatabaseConfig.RollbackEnabled+ doUpdate = true+ }+ return nil+ }(); err != nil {+ return nil, err+ }++ // PreUpdateBackupDetail+ if err := func() error {+ if task.Type != api.TaskDatabaseDataUpdate {+ return nil+ }+ payload := &api.TaskDatabaseDataUpdatePayload{}+ if err := json.Unmarshal([]byte(task.Payload), payload); err != nil {+ return status.Errorf(codes.Internal, "failed to unmarshal task payload: %v", err)+ }config, ok := spec.Config.(*v1pb.Plan_Spec_ChangeDatabaseConfig)if !ok {return nil}- oldSheetName = config.ChangeDatabaseConfig.Sheet++ var databaseName *string+ if config.ChangeDatabaseConfig.PreUpdateBackupDetail == nil {+ if payload.PreUpdateBackupDetail.Database != "" {+ emptyValue := ""+ databaseName = &emptyValue+ }+ } else {+ if config.ChangeDatabaseConfig.PreUpdateBackupDetail.Database != payload.PreUpdateBackupDetail.Database {+ databaseName = &config.ChangeDatabaseConfig.PreUpdateBackupDetail.Database+ }+ }+ if databaseName != nil {+ taskPatch.PreUpdateBackupDetail = &api.PreUpdateBackupDetail{+ Database: *databaseName,+ }+ doUpdate = true+ }+ return nil+ }(); err != nil {+ return nil, err}- _, sheetUID, err := common.GetProjectResourceIDSheetUID(oldSheetName)- if err != nil {- return status.Errorf(codes.Internal, "failed to get sheet id from %q, error: %v", oldSheetName, err)++ // Sheet+ if err := func() error {+ switch task.Type {+ case api.TaskDatabaseSchemaUpdate, api.TaskDatabaseSchemaUpdateSDL, api.TaskDatabaseSchemaUpdateGhostSync, api.TaskDatabaseDataUpdate, api.TaskDatabaseDataExport:+ var taskPayload struct {+ SheetID int `json:"sheetId"`+ }+ if err := json.Unmarshal([]byte(task.Payload), &taskPayload); err != nil {+ return status.Errorf(codes.Internal, "failed to unmarshal task payload: %v", err)+ }++ var oldSheetName string+ if task.Type == api.TaskDatabaseDataExport {+ config, ok := spec.Config.(*v1pb.Plan_Spec_ExportDataConfig)+ if !ok {+ return nil+ }+ oldSheetName = config.ExportDataConfig.Sheet+ } else {+ config, ok := spec.Config.(*v1pb.Plan_Spec_ChangeDatabaseConfig)+ if !ok {+ return nil+ }+ oldSheetName = config.ChangeDatabaseConfig.Sheet+ }+ _, sheetUID, err := common.GetProjectResourceIDSheetUID(oldSheetName)+ if err != nil {+ return status.Errorf(codes.Internal, "failed to get sheet id from %q, error: %v", oldSheetName, err)+ }+ if taskPayload.SheetID == sheetUID {+ return nil+ }++ sheet, err := s.store.GetSheet(ctx, &store.FindSheetMessage{+ UID: &sheetUID,+ })+ if err != nil {+ return status.Errorf(codes.Internal, "failed to get sheet %q: %v", oldSheetName, err)+ }+ if sheet == nil {+ return status.Errorf(codes.NotFound, "sheet %q not found", oldSheetName)+ }+ doUpdate = true+ // TODO(p0ny): update schema version+ taskPatch.SheetID = &sheet.UID+ statementUpdates = append(statementUpdates, api.ActivityPipelineTaskStatementUpdatePayload{+ TaskID: task.ID,+ OldSheetID: taskPayload.SheetID,+ NewSheetID: sheet.UID,+ TaskName: task.Name,+ IssueName: issue.Title,+ })+ }+ return nil+ }(); err != nil {+ return nil, err}- if taskPayload.SheetID == sheetUID {++ // ExportDataConfig+ if err := func() error {+ if task.Type != api.TaskDatabaseDataExport {+ return nil+ }+ payload := &api.TaskDatabaseDataExportPayload{}+ if err := json.Unmarshal([]byte(task.Payload), payload); err != nil {+ return status.Errorf(codes.Internal, "failed to unmarshal task payload: %v", err)+ }+ config, ok := spec.Config.(*v1pb.Plan_Spec_ExportDataConfig)+ if !ok {+ return nil+ }+ if config.ExportDataConfig.Format != convertExportFormat(payload.Format) {+ format := convertToExportFormat(config.ExportDataConfig.Format)+ taskPatch.ExportFormat = &format+ doUpdate = true+ }+ if (config.ExportDataConfig.Password == nil && payload.Password != "") || (config.ExportDataConfig.Password != nil && *config.ExportDataConfig.Password != payload.Password) {+ taskPatch.ExportPassword = config.ExportDataConfig.Password+ doUpdate = true+ }return nil+ }(); err != nil {+ return nil, err}- sheet, err := s.store.GetSheet(ctx, &store.FindSheetMessage{- UID: &sheetUID,- })- if err != nil {- return status.Errorf(codes.Internal, "failed to get sheet %q: %v", oldSheetName, err)+ // version+ if err := func() error {+ switch task.Type {+ case api.TaskDatabaseSchemaBaseline, api.TaskDatabaseSchemaUpdate, api.TaskDatabaseSchemaUpdateSDL, api.TaskDatabaseSchemaUpdateGhostSync, api.TaskDatabaseDataUpdate:+ default:+ return nil+ }+ var taskPayload struct {+ SchemaVersion string `json:"schemaVersion"`+ }+ if err := json.Unmarshal([]byte(task.Payload), &taskPayload); err != nil {+ return errors.Wrapf(err, "failed to unmarshal task payload")+ }+ if v := spec.GetChangeDatabaseConfig().GetSchemaVersion(); v != "" && v != taskPayload.SchemaVersion {+ taskPatch.SchemaVersion = &v+ doUpdate = true+ }+ return nil+ }(); err != nil {+ return nil, err}- if sheet == nil {- return status.Errorf(codes.NotFound, "sheet %q not found", oldSheetName)++ // task dag+ if err := func() error {+ oldSpec, ok := oldSpecsByID[taskSpecID.SpecID]+ if !ok {+ return nil+ }++ sort.Slice(oldSpec.DependsOnSpecs, func(i, j int) bool {+ return oldSpec.DependsOnSpecs[i] < oldSpec.DependsOnSpecs[j]+ })+ sort.Slice(spec.DependsOnSpecs, func(i, j int) bool {+ return spec.DependsOnSpecs[i] < spec.DependsOnSpecs[j]+ })+ if slices.Equal(oldSpec.GetDependsOnSpecs(), spec.GetDependsOnSpecs()) {+ return nil+ }++ // rebuild the task dag+ var fromTaskIDs []int+ for _, dependsOnSpec := range spec.GetDependsOnSpecs() {+ for _, dependsOnTask := range tasksBySpecID[dependsOnSpec] {+ fromTaskIDs = append(fromTaskIDs, dependsOnTask.ID)+ }+ }+ taskDAGRebuildList = append(taskDAGRebuildList, struct {+ fromTaskIDs []int+ toTaskID int+ }{+ fromTaskIDs: fromTaskIDs,+ toTaskID: task.ID,+ })+ return nil+ }(); err != nil {+ return nil, err+ }++ if !doUpdate {+ continue}- doUpdate = true- // TODO(p0ny): update schema version- taskPatch.SheetID = &sheet.UID- statementUpdates = append(statementUpdates, api.ActivityPipelineTaskStatementUpdatePayload{- TaskID: task.ID,- OldSheetID: taskPayload.SheetID,- NewSheetID: sheet.UID,- TaskName: task.Name,- IssueName: issue.Title,- })++ taskPatchList = append(taskPatchList, taskPatch)}- return nil- }(); err != nil {- return nil, err}- // ExportDataConfig- if err := func() error {- if task.Type != api.TaskDatabaseDataExport {- return nil- }- payload := &api.TaskDatabaseDataExportPayload{}- if err := json.Unmarshal([]byte(task.Payload), payload); err != nil {- return status.Errorf(codes.Internal, "failed to unmarshal task payload: %v", err)- }- config, ok := spec.Config.(*v1pb.Plan_Spec_ExportDataConfig)- if !ok {- return nil- }- if config.ExportDataConfig.Format != convertExportFormat(payload.Format) {- format := convertToExportFormat(config.ExportDataConfig.Format)- taskPatch.ExportFormat = &format- doUpdate = true- }- if (config.ExportDataConfig.Password == nil && payload.Password != "") || (config.ExportDataConfig.Password != nil && *config.ExportDataConfig.Password != payload.Password) {- taskPatch.ExportPassword = config.ExportDataConfig.Password- doUpdate = true+ for _, taskPatch := range taskPatchList {+ if taskPatch.SheetID != nil || taskPatch.EarliestAllowedTs != nil {+ task := tasksMap[taskPatch.ID]+ if task.LatestTaskRunStatus == api.TaskRunPending || task.LatestTaskRunStatus == api.TaskRunRunning {+ return nil, status.Errorf(codes.FailedPrecondition, "cannot update plan because task %q is %s", task.Name, task.LatestTaskRunStatus)+ }}- return nil- }(); err != nil {- return nil, err}- // version- if err := func() error {- switch task.Type {- case api.TaskDatabaseSchemaBaseline, api.TaskDatabaseSchemaUpdate, api.TaskDatabaseSchemaUpdateSDL, api.TaskDatabaseSchemaUpdateGhostSync, api.TaskDatabaseDataUpdate:- default:- return nil- }- var taskPayload struct {- SchemaVersion string `json:"schemaVersion"`- }- if err := json.Unmarshal([]byte(task.Payload), &taskPayload); err != nil {- return errors.Wrapf(err, "failed to unmarshal task payload")+ for _, taskPatch := range taskPatchList {+ if taskPatch.SheetID != nil {+ doUpdateSheet = true+ break}- if v := spec.GetChangeDatabaseConfig().GetSchemaVersion(); v != "" && v != taskPayload.SchemaVersion {- taskPatch.SchemaVersion = &v- doUpdate = true+ }++ // For the plan without pipeline, we need to check if the sheet is updated in related specs.+ if oldPlan.PipelineUID == nil {+ for _, specPatch := range updated {+ oldSpec := oldSpecsByID[specPatch.Id]+ if oldSpec.GetChangeDatabaseConfig() != nil && specPatch.GetChangeDatabaseConfig() != nil {+ oldConfig, newConfig := oldSpec.GetChangeDatabaseConfig(), specPatch.GetChangeDatabaseConfig()+ if oldConfig.Sheet != newConfig.Sheet {+ doUpdateSheet = true+ break+ }+ }}- return nil- }(); err != nil {- return nil, err}- // task dag- if err := func() error {- oldSpec, ok := oldSpecsByID[taskSpecID.SpecID]- if !ok {- return nil+ for _, taskPatch := range taskPatchList {+ task := tasksMap[taskPatch.ID]+ if _, err := s.store.UpdateTaskV2(ctx, taskPatch); err != nil {+ return nil, status.Errorf(codes.Internal, "failed to update task %q: %v", task.Name, err)}- sort.Slice(oldSpec.DependsOnSpecs, func(i, j int) bool {- return oldSpec.DependsOnSpecs[i] < oldSpec.DependsOnSpecs[j]- })- sort.Slice(spec.DependsOnSpecs, func(i, j int) bool {- return spec.DependsOnSpecs[i] < spec.DependsOnSpecs[j]- })- if slices.Equal(oldSpec.GetDependsOnSpecs(), spec.GetDependsOnSpecs()) {- return nil+ taskPatched, err := s.store.GetTaskV2ByID(ctx, task.ID)+ if err != nil {+ return nil, status.Errorf(codes.Internal, "failed to get updated task %q: %v", task.Name, err)}- // rebuild the task dag- var fromTaskIDs []int- for _, dependsOnSpec := range spec.GetDependsOnSpecs() {- for _, dependsOnTask := range tasksBySpecID[dependsOnSpec] {- fromTaskIDs = append(fromTaskIDs, dependsOnTask.ID)+ // enqueue or cancel after it's written to the database.+ if taskPatch.RollbackEnabled != nil {+ // Enqueue the rollback sql generation if the task done.+ if *taskPatch.RollbackEnabled && taskPatched.LatestTaskRunStatus == api.TaskRunDone {+ s.stateCfg.RollbackGenerate.Store(taskPatched.ID, taskPatched)+ } else if !*taskPatch.RollbackEnabled {+ // Cancel running rollback sql generation.+ if v, ok := s.stateCfg.RollbackCancel.Load(taskPatched.ID); ok {+ if cancel, ok := v.(context.CancelFunc); ok {+ cancel()+ }+ // We don't erase the keys for RollbackCancel and RollbackGenerate here because they will eventually be erased by the rollback runner.+ }}}- taskDAGRebuildList = append(taskDAGRebuildList, struct {- fromTaskIDs []int- toTaskID int- }{- fromTaskIDs: fromTaskIDs,- toTaskID: task.ID,- })- return nil- }(); err != nil {- return nil, err}- if !doUpdate {- continue+ for _, taskDAGRebuild := range taskDAGRebuildList {+ if err := s.store.RebuildTaskDAG(ctx, taskDAGRebuild.fromTaskIDs, taskDAGRebuild.toTaskID); err != nil {+ return nil, status.Errorf(codes.Internal, "failed to rebuild task dag: %v", err)+ }}- taskPatchList = append(taskPatchList, taskPatch)- }- }-- for _, taskPatch := range taskPatchList {- if taskPatch.SheetID != nil || taskPatch.EarliestAllowedTs != nil {- task := tasksMap[taskPatch.ID]- if task.LatestTaskRunStatus == api.TaskRunPending || task.LatestTaskRunStatus == api.TaskRunRunning {- return nil, status.Errorf(codes.FailedPrecondition, "cannot update plan because task %q is %s", task.Name, task.LatestTaskRunStatus)+ for _, statementUpdate := range statementUpdates {+ task := tasksMap[statementUpdate.TaskID]++ if err := func() error {+ oldSheet := common.FormatSheet(issue.Project.ResourceID, statementUpdate.OldSheetID)+ newSheet := common.FormatSheet(issue.Project.ResourceID, statementUpdate.NewSheetID)+ return s.store.CreateIssueComment(ctx, &store.IssueCommentMessage{+ IssueUID: issue.UID,+ Payload: &storepb.IssueCommentPayload{+ Event: &storepb.IssueCommentPayload_TaskUpdate_{+ TaskUpdate: &storepb.IssueCommentPayload_TaskUpdate{+ Tasks: []string{common.FormatTask(issue.Project.ResourceID, task.PipelineID, task.StageID, task.ID)},+ FromSheet: &oldSheet,+ ToSheet: &newSheet,+ },+ },+ },+ }, user.ID)+ }(); err != nil {+ slog.Warn("failed to create issue comments for statement update", "issueUID", issue.UID, log.BBError(err))+ }}- }- }-- var doUpdateSheet bool- for _, taskPatch := range taskPatchList {- if taskPatch.SheetID != nil {- doUpdateSheet = true- break- }- }-- // For the plan without pipeline, we need to check if the sheet is updated in related specs.- if oldPlan.PipelineUID == nil {- for _, specPatch := range updated {- oldSpec := oldSpecsByID[specPatch.Id]- if oldSpec.GetChangeDatabaseConfig() != nil && specPatch.GetChangeDatabaseConfig() != nil {- oldConfig, newConfig := oldSpec.GetChangeDatabaseConfig(), specPatch.GetChangeDatabaseConfig()- if oldConfig.Sheet != newConfig.Sheet {- doUpdateSheet = true- break+ for _, earliestUpdate := range earliestUpdates {+ task := tasksMap[earliestUpdate.TaskID]++ if err := func() error {+ return s.store.CreateIssueComment(ctx, &store.IssueCommentMessage{+ IssueUID: issue.UID,+ Payload: &storepb.IssueCommentPayload{+ Event: &storepb.IssueCommentPayload_TaskUpdate_{+ TaskUpdate: &storepb.IssueCommentPayload_TaskUpdate{+ Tasks: []string{common.FormatTask(issue.Project.ResourceID, task.PipelineID, task.StageID, task.ID)},+ FromEarliestAllowedTime: timestamppb.New(time.Unix(earliestUpdate.OldEarliestAllowedTs, 0)),+ ToEarliestAllowedTime: timestamppb.New(time.Unix(earliestUpdate.NewEarliestAllowedTs, 0)),+ },+ },+ },+ }, user.ID)+ }(); err != nil {+ slog.Warn("failed to create issue comments for earliest allowed time update", "issueUID", issue.UID, log.BBError(err))}}- }- }-- for _, taskPatch := range taskPatchList {- task := tasksMap[taskPatch.ID]- if _, err := s.store.UpdateTaskV2(ctx, taskPatch); err != nil {- return nil, status.Errorf(codes.Internal, "failed to update task %q: %v", task.Name, err)- }- taskPatched, err := s.store.GetTaskV2ByID(ctx, task.ID)- if err != nil {- return nil, status.Errorf(codes.Internal, "failed to get updated task %q: %v", task.Name, err)- }-- // enqueue or cancel after it's written to the database.- if taskPatch.RollbackEnabled != nil {- // Enqueue the rollback sql generation if the task done.- if *taskPatch.RollbackEnabled && taskPatched.LatestTaskRunStatus == api.TaskRunDone {- s.stateCfg.RollbackGenerate.Store(taskPatched.ID, taskPatched)- } else if !*taskPatch.RollbackEnabled {- // Cancel running rollback sql generation.- if v, ok := s.stateCfg.RollbackCancel.Load(taskPatched.ID); ok {- if cancel, ok := v.(context.CancelFunc); ok {- cancel()+ if issue != nil && doUpdateSheet {+ if err := func() error {+ issue, err := s.store.UpdateIssueV2(ctx, issue.UID, &store.UpdateIssueMessage{+ PayloadUpsert: &storepb.IssuePayload{+ Approval: &storepb.IssuePayloadApproval{+ ApprovalFindingDone: false,+ },+ },+ }, api.SystemBotID)+ if err != nil {+ return errors.Errorf("failed to update issue: %v", err)}- // We don't erase the keys for RollbackCancel and RollbackGenerate here because they will eventually be erased by the rollback runner.+ s.stateCfg.ApprovalFinding.Store(issue.UID, issue)+ return nil+ }(); err != nil {+ slog.Error("failed to update issue to refind approval", log.BBError(err))}}+ default:+ return nil, status.Errorf(codes.InvalidArgument, "invalid update_mask path %q", path)}}- for _, taskDAGRebuild := range taskDAGRebuildList {- if err := s.store.RebuildTaskDAG(ctx, taskDAGRebuild.fromTaskIDs, taskDAGRebuild.toTaskID); err != nil {- return nil, status.Errorf(codes.Internal, "failed to rebuild task dag: %v", err)- }+ planUpdate.Config = &storepb.PlanConfig{+ Steps: convertPlanSteps(request.Plan.Steps),}-- if err := s.store.UpdatePlan(ctx, &store.UpdatePlanMessage{- UID: oldPlan.UID,- UpdaterID: user.ID,- Config: &storepb.PlanConfig{- Steps: convertPlanSteps(request.Plan.Steps),- },- }); err != nil {+ if err := s.store.UpdatePlan(ctx, planUpdate); err != nil {return nil, status.Errorf(codes.Internal, "failed to update plan %q: %v", request.Plan.Name, err)}@@ -666,68 +736,6 @@ func (s *PlanService) UpdatePlan(ctx context.Context, request *v1pb.UpdatePlanRe}}- for _, statementUpdate := range statementUpdates {- task := tasksMap[statementUpdate.TaskID]-- if err := func() error {- oldSheet := common.FormatSheet(issue.Project.ResourceID, statementUpdate.OldSheetID)- newSheet := common.FormatSheet(issue.Project.ResourceID, statementUpdate.NewSheetID)- return s.store.CreateIssueComment(ctx, &store.IssueCommentMessage{- IssueUID: issue.UID,- Payload: &storepb.IssueCommentPayload{- Event: &storepb.IssueCommentPayload_TaskUpdate_{- TaskUpdate: &storepb.IssueCommentPayload_TaskUpdate{- Tasks: []string{common.FormatTask(issue.Project.ResourceID, task.PipelineID, task.StageID, task.ID)},- FromSheet: &oldSheet,- ToSheet: &newSheet,- },- },- },- }, user.ID)- }(); err != nil {- slog.Warn("failed to create issue comments for statement update", "issueUID", issue.UID, log.BBError(err))- }- }- for _, earliestUpdate := range earliestUpdates {- task := tasksMap[earliestUpdate.TaskID]-- if err := func() error {- return s.store.CreateIssueComment(ctx, &store.IssueCommentMessage{- IssueUID: issue.UID,- Payload: &storepb.IssueCommentPayload{- Event: &storepb.IssueCommentPayload_TaskUpdate_{- TaskUpdate: &storepb.IssueCommentPayload_TaskUpdate{- Tasks: []string{common.FormatTask(issue.Project.ResourceID, task.PipelineID, task.StageID, task.ID)},- FromEarliestAllowedTime: timestamppb.New(time.Unix(earliestUpdate.OldEarliestAllowedTs, 0)),- ToEarliestAllowedTime: timestamppb.New(time.Unix(earliestUpdate.NewEarliestAllowedTs, 0)),- },- },- },- }, user.ID)- }(); err != nil {- slog.Warn("failed to create issue comments for earliest allowed time update", "issueUID", issue.UID, log.BBError(err))- }- }-- if issue != nil && doUpdateSheet {- if err := func() error {- issue, err := s.store.UpdateIssueV2(ctx, issue.UID, &store.UpdateIssueMessage{- PayloadUpsert: &storepb.IssuePayload{- Approval: &storepb.IssuePayloadApproval{- ApprovalFindingDone: false,- },- },- }, api.SystemBotID)- if err != nil {- return errors.Errorf("failed to update issue: %v", err)- }- s.stateCfg.ApprovalFinding.Store(issue.UID, issue)- return nil- }(); err != nil {- slog.Error("failed to update issue to refind approval", log.BBError(err))- }- }-convertedPlan, err := convertToPlan(ctx, s.store, updatedPlan)if err != nil {return nil, status.Errorf(codes.Internal, "failed to convert to plan, error: %v", err)diff --git a/backend/store/plan.go b/backend/store/plan.goindex 41618e21b0..2ab8331a68 100644--- a/backend/store/plan.go+++ b/backend/store/plan.go@@ -43,6 +43,8 @@ type FindPlanMessage struct {type UpdatePlanMessage struct {UID int64PipelineUID *int+ Name *string+ Description *stringConfig *storepb.PlanConfigUpdaterID int}@@ -209,6 +211,12 @@ func (s *Store) ListPlans(ctx context.Context, find *FindPlanMessage) ([]*PlanMe// UpdatePlan updates an existing plan.func (s *Store) UpdatePlan(ctx context.Context, patch *UpdatePlanMessage) error {set, args := []string{"updater_id = $1", "updated_ts = $2"}, []any{patch.UpdaterID, time.Now().Unix()}+ if v := patch.Name; v != nil {+ set, args = append(set, fmt.Sprintf("name = $%d", len(args)+1)), append(args, *v)+ }+ if v := patch.Description; v != nil {+ set, args = append(set, fmt.Sprintf("description = $%d", len(args)+1)), append(args, *v)+ }if v := patch.Config; v != nil {config, err := protojson.Marshal(v)if err != nil {