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: introduce issue v1 store (#4392)
Danny Xu9b546806788a
diff --git a/backend/runner/taskrun/scheduler.go b/backend/runner/taskrun/scheduler.goindex 834dc67a3e..8c1e1d15b3 100644--- a/backend/runner/taskrun/scheduler.go+++ b/backend/runner/taskrun/scheduler.go@@ -1238,17 +1238,21 @@ func (s *Scheduler) CanPrincipalBeAssignee(ctx context.Context, principalID int,}// ChangeIssueStatus changes the status of an issue.-func (s *Scheduler) ChangeIssueStatus(ctx context.Context, issue *api.Issue, newStatus api.IssueStatus, updaterID int, comment string) (*api.Issue, error) {+func (s *Scheduler) ChangeIssueStatus(ctx context.Context, issue *store.IssueMessage, newStatus api.IssueStatus, updaterID int, comment string) (*api.Issue, error) {+ composedPipeline, err := s.store.GetPipelineByID(ctx, issue.PipelineUID)+ if err != nil {+ return nil, err+ }var pipelineStatus api.PipelineStatusswitch newStatus {case api.IssueOpen:pipelineStatus = api.PipelineOpencase api.IssueDone:// Returns error if any of the tasks is not DONE.- for _, stage := range issue.Pipeline.StageList {+ for _, stage := range composedPipeline.StageList {for _, task := range stage.TaskList {if task.Status != api.TaskDone {- return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("failed to resolve issue: %v, task %v has not finished", issue.Name, task.Name)}+ return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("failed to resolve issue: %v, task %v has not finished", issue.Title, task.Name)}}}}@@ -1257,7 +1261,7 @@ func (s *Scheduler) ChangeIssueStatus(ctx context.Context, issue *api.Issue, new// If we want to cancel the issue, we find the current running tasks, mark each of them CANCELED.// We keep PENDING and FAILED tasks as is since the issue maybe reopened later, and it's better to// keep those tasks in the same state before the issue was canceled.- for _, stage := range issue.Pipeline.StageList {+ for _, stage := range composedPipeline.StageList {for _, task := range stage.TaskList {if task.Status == api.TaskRunning {if _, err := s.PatchTaskStatus(ctx, task, &api.TaskStatusPatch{@@ -1265,7 +1269,7 @@ func (s *Scheduler) ChangeIssueStatus(ctx context.Context, issue *api.Issue, newUpdaterID: updaterID,Status: api.TaskCanceled,}); err != nil {- return nil, errors.Wrapf(err, "failed to cancel issue: %v, failed to cancel task: %v", issue.Name, task.Name)+ return nil, errors.Wrapf(err, "failed to cancel issue: %v, failed to cancel task: %v", issue.Title, task.Name)}}}@@ -1274,32 +1278,32 @@ func (s *Scheduler) ChangeIssueStatus(ctx context.Context, issue *api.Issue, new}pipelinePatch := &api.PipelinePatch{- ID: issue.PipelineID,+ ID: issue.PipelineUID,UpdaterID: updaterID,Status: &pipelineStatus,}if _, err := s.store.PatchPipeline(ctx, pipelinePatch); err != nil {- return nil, errors.Wrapf(err, "failed to update issue %q's status, failed to update pipeline status with patch %+v", issue.Name, pipelinePatch)+ return nil, errors.Wrapf(err, "failed to update issue %q's status, failed to update pipeline status with patch %+v", issue.Title, pipelinePatch)}issuePatch := &api.IssuePatch{- ID: issue.ID,+ ID: issue.UID,UpdaterID: updaterID,Status: &newStatus,}- if newStatus != api.IssueOpen && issue.Project.WorkflowType == api.UIWorkflow {+ if newStatus != api.IssueOpen && issue.Project.Workflow == api.UIWorkflow {// for UI workflow, set assigneeNeedAttention to false if we are closing the issue.needAttention := falseissuePatch.AssigneeNeedAttention = &needAttention}updatedIssue, err := s.store.PatchIssue(ctx, issuePatch)if err != nil {- return nil, errors.Wrapf(err, "failed to update issue %q's status with patch %v", issue.Name, issuePatch)+ return nil, errors.Wrapf(err, "failed to update issue %q's status with patch %v", issue.Title, issuePatch)}// Cancel external approval, it's ok if we failed.if newStatus != api.IssueOpen {- if err := s.applicationRunner.CancelExternalApproval(ctx, issue.ID, api.ExternalApprovalCancelReasonIssueNotOpen); err != nil {+ if err := s.applicationRunner.CancelExternalApproval(ctx, issue.UID, api.ExternalApprovalCancelReasonIssueNotOpen); err != nil {log.Error("failed to cancel external approval on issue cancellation or completion", zap.Error(err))}}@@ -1310,12 +1314,12 @@ func (s *Scheduler) ChangeIssueStatus(ctx context.Context, issue *api.Issue, newIssueName: updatedIssue.Name,})if err != nil {- return nil, errors.Wrapf(err, "failed to marshal activity after changing the issue status: %v", issue.Name)+ return nil, errors.Wrapf(err, "failed to marshal activity after changing the issue status: %v", issue.Title)}activityCreate := &api.ActivityCreate{CreatorID: updaterID,- ContainerID: issue.ID,+ ContainerID: issue.UID,Type: api.ActivityIssueStatusUpdate,Level: api.ActivityInfo,Comment: comment,@@ -1325,7 +1329,7 @@ func (s *Scheduler) ChangeIssueStatus(ctx context.Context, issue *api.Issue, newif _, err := s.activityManager.CreateActivity(ctx, activityCreate, &activity.Metadata{Issue: updatedIssue,}); err != nil {- return nil, errors.Wrapf(err, "failed to create activity after changing the issue status: %v", issue.Name)+ return nil, errors.Wrapf(err, "failed to create activity after changing the issue status: %v", issue.Title)}return updatedIssue, nildiff --git a/backend/server/issue.go b/backend/server/issue.goindex 217c641636..d95086798f 100644--- a/backend/server/issue.go+++ b/backend/server/issue.go@@ -187,7 +187,7 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusBadRequest, "Cannot set assigneeNeedAttention to false")}- issue, err := s.store.GetIssueByID(ctx, id)+ issue, err := s.store.GetIssueByUID(ctx, id)if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch issue ID when updating issue: %v", id)).SetInternal(err)}@@ -196,15 +196,19 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {}if issuePatch.AssigneeID != nil {- if *issuePatch.AssigneeID == issue.AssigneeID {+ if *issuePatch.AssigneeID == issue.Assignee.ID {return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Cannot set assignee with user id %d because it's already the case", *issuePatch.AssigneeID))}- stage := utils.GetActiveStage(issue.Pipeline)+ composedPipeline, err := s.store.GetPipelineByID(ctx, issue.PipelineUID)+ if err != nil {+ return err+ }+ stage := utils.GetActiveStage(composedPipeline)if stage == nil {// all stages have finished, use the last stage- stage = issue.Pipeline.StageList[len(issue.Pipeline.StageList)-1]+ stage = composedPipeline.StageList[len(composedPipeline.StageList)-1]}- ok, err := s.TaskScheduler.CanPrincipalBeAssignee(ctx, *issuePatch.AssigneeID, stage.EnvironmentID, issue.ProjectID, issue.Type)+ ok, err := s.TaskScheduler.CanPrincipalBeAssignee(ctx, *issuePatch.AssigneeID, stage.EnvironmentID, issue.Project.UID, issue.Type)if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to check if the assignee can be changed").SetInternal(err)}@@ -213,7 +217,7 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {}// set AssigneeNeedAttention to false on assignee change- if issue.Project.WorkflowType == api.UIWorkflow {+ if issue.Project.Workflow == api.UIWorkflow {needAttention := falseissuePatch.AssigneeNeedAttention = &needAttention}@@ -226,18 +230,18 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {// cancel external approval on assignee changeif issuePatch.AssigneeID != nil {- if err := s.ApplicationRunner.CancelExternalApproval(ctx, issue.ID, api.ExternalApprovalCancelReasonReassigned); err != nil {- log.Error("failed to cancel external approval on assignee change", zap.Int("issue_id", issue.ID), zap.Error(err))+ if err := s.ApplicationRunner.CancelExternalApproval(ctx, issue.UID, api.ExternalApprovalCancelReasonReassigned); err != nil {+ log.Error("failed to cancel external approval on assignee change", zap.Int("issue_id", issue.UID), zap.Error(err))}}payloadList := [][]byte{}- if issuePatch.Name != nil && *issuePatch.Name != issue.Name {+ if issuePatch.Name != nil && *issuePatch.Name != issue.Title {payload, err := json.Marshal(api.ActivityIssueFieldUpdatePayload{FieldID: api.IssueFieldName,- OldValue: issue.Name,+ OldValue: issue.Title,NewValue: *issuePatch.Name,- IssueName: issue.Name,+ IssueName: issue.Title,})if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal activity after changing issue name: %v", updatedIssue.Name)).SetInternal(err)@@ -249,19 +253,19 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {FieldID: api.IssueFieldDescription,OldValue: issue.Description,NewValue: *issuePatch.Description,- IssueName: issue.Name,+ IssueName: issue.Title,})if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal activity after changing issue description: %v", updatedIssue.Name)).SetInternal(err)}payloadList = append(payloadList, payload)}- if issuePatch.AssigneeID != nil && *issuePatch.AssigneeID != issue.AssigneeID {+ if issuePatch.AssigneeID != nil && *issuePatch.AssigneeID != issue.Assignee.ID {payload, err := json.Marshal(api.ActivityIssueFieldUpdatePayload{FieldID: api.IssueFieldAssignee,- OldValue: strconv.Itoa(issue.AssigneeID),+ OldValue: strconv.Itoa(issue.Assignee.ID),NewValue: strconv.Itoa(*issuePatch.AssigneeID),- IssueName: issue.Name,+ IssueName: issue.Title,})if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal activity after changing issue assignee: %v", updatedIssue.Name)).SetInternal(err)@@ -272,7 +276,7 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {for _, payload := range payloadList {activityCreate := &api.ActivityCreate{CreatorID: c.Get(getPrincipalIDContextKey()).(int),- ContainerID: issue.ID,+ ContainerID: issue.UID,Type: api.ActivityIssueFieldUpdate,Level: api.ActivityInfo,Payload: string(payload),@@ -306,7 +310,7 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusBadRequest, "Malformed update issue status request").SetInternal(err)}- issue, err := s.store.GetIssueByID(ctx, id)+ issue, err := s.store.GetIssueByUID(ctx, id)if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch issue ID: %v", id)).SetInternal(err)}@@ -530,7 +534,7 @@ func (s *Server) getPipelineCreateForDatabaseRollback(ctx context.Context, issuereturn nil, echo.NewHTTPError(http.StatusBadRequest, "The task ID list must have exactly one element")}taskID := c.TaskIDList[0]- issue, err := s.store.GetIssueByID(ctx, issueID)+ issue, err := s.store.GetIssueByUID(ctx, issueID)if err != nil {return nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch issue with ID %d", issueID)).SetInternal(err)}@@ -550,8 +554,8 @@ func (s *Server) getPipelineCreateForDatabaseRollback(ctx context.Context, issueif task.Database.Instance.Engine != db.MySQL {return nil, echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Only support rollback for MySQL now, but got %s", task.Database.Instance.Engine))}- if task.PipelineID != issue.PipelineID {- return nil, echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Task %d is not in issue %d", taskID, issue.ID))+ if task.PipelineID != issue.PipelineUID {+ return nil, echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Task %d is not in issue %d", taskID, issue.UID))}if task.Status != api.TaskDone && task.Status != api.TaskFailed {return nil, echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Task %d has status %s, must be %s or %s", taskID, task.Status, api.TaskDone, api.TaskFailed))diff --git a/backend/store/issue.go b/backend/store/issue.goindex 7024edc1a7..e9f0c4212e 100644--- a/backend/store/issue.go+++ b/backend/store/issue.go@@ -9,6 +9,7 @@ import ("strings""time"+ "github.com/lib/pq""github.com/pkg/errors""github.com/bytebase/bytebase/backend/common"@@ -797,3 +798,168 @@ func (*Store) patchIssueImpl(ctx context.Context, tx *Tx, patch *api.IssuePatch)}return &issueRaw, nil}++// IssueMessage is the mssage for issues.+type IssueMessage struct {+ Project *ProjectMessage+ Title string+ Status api.IssueStatus+ Type api.IssueType+ Description string+ Assignee *UserMessage+ NeedAttention bool+ Payload string+ Subscribers []*UserMessage+ PipelineUID int++ // The following fields are output only and not used for create().+ UID int+ Creator *UserMessage+ CreatedTime time.Time+ Updater *UserMessage+ UpdatedTime time.Time++ // Internal fields.+ projectUID int+ assigneeUID int+ subscriberUIDs []int+ creatorUID int+ createdTs int64+ updaterUID int+ updatedTs int64+}++// FindIssueMessage is the message to find issues.+type FindIssueMessage struct {+ UID *int+}++// GetIssueByUID gets issue by issue UID.+func (s *Store) GetIssueByUID(ctx context.Context, uid int) (*IssueMessage, error) {+ issues, err := s.listIssueImplV2(ctx, &FindIssueMessage{UID: &uid})+ if err != nil {+ return nil, err+ }+ if len(issues) == 0 {+ return nil, nil+ }+ if len(issues) > 1 {+ return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d issues with UID %d, expect 1", len(issues), uid)}+ }+ issue := issues[0]++ return issue, nil+}++func (s *Store) listIssueImplV2(ctx context.Context, find *FindIssueMessage) ([]*IssueMessage, error) {+ where, args := []string{"TRUE"}, []interface{}{}+ if v := find.UID; v != nil {+ where, args = append(where, fmt.Sprintf("issue.id = $%d", len(args)+1)), append(args, *v)+ }++ var issues []*IssueMessage++ tx, err := s.db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})+ if err != nil {+ return nil, FormatError(err)+ }+ defer tx.Rollback()++ rows, err := tx.QueryContext(ctx, fmt.Sprintf(`+ SELECT+ issue.id,+ issue.creator_id,+ issue.created_ts,+ issue.updater_id,+ issue.updated_ts,+ issue.project_id,+ issue.pipeline_id,+ issue.name,+ issue.status,+ issue.type,+ issue.description,+ issue.assignee_id,+ issue.assignee_need_attention,+ issue.payload,+ ARRAY_AGG (+ issue_subscriber.subscriber_id+ ) subscribers+ FROM issue+ LEFT JOIN issue_subscriber ON issue.id = issue_subscriber.issue_id+ WHERE %s+ GROUP BY issue.id`, strings.Join(where, " AND ")),+ args...,+ )+ if err != nil {+ return nil, FormatError(err)+ }+ defer rows.Close()+ for rows.Next() {+ var issue IssueMessage+ var subscribers []sql.NullInt32+ if err := rows.Scan(+ &issue.UID,+ &issue.creatorUID,+ &issue.createdTs,+ &issue.updaterUID,+ &issue.updatedTs,+ &issue.projectUID,+ &issue.PipelineUID,+ &issue.Title,+ &issue.Status,+ &issue.Type,+ &issue.Description,+ &issue.assigneeUID,+ &issue.NeedAttention,+ &issue.Payload,+ pq.Array(&subscribers),+ ); err != nil {+ return nil, FormatError(err)+ }+ for _, subscriber := range subscribers {+ if !subscriber.Valid {+ continue+ }+ issue.subscriberUIDs = append(issue.subscriberUIDs, int(subscriber.Int32))+ }+ issues = append(issues, &issue)+ }++ if err := tx.Commit(); err != nil {+ return nil, FormatError(err)+ }++ // Populate from internal fields.+ for _, issue := range issues {+ project, err := s.GetProjectV2(ctx, &FindProjectMessage{UID: &issue.projectUID})+ if err != nil {+ return nil, err+ }+ issue.Project = project+ assignee, err := s.GetUserByID(ctx, issue.assigneeUID)+ if err != nil {+ return nil, err+ }+ issue.Assignee = assignee+ creator, err := s.GetUserByID(ctx, issue.creatorUID)+ if err != nil {+ return nil, err+ }+ issue.Creator = creator+ updater, err := s.GetUserByID(ctx, issue.updaterUID)+ if err != nil {+ return nil, err+ }+ issue.Updater = updater+ for _, subscriberUID := range issue.subscriberUIDs {+ subscriber, err := s.GetUserByID(ctx, subscriberUID)+ if err != nil {+ return nil, err+ }+ issue.Subscribers = append(issue.Subscribers, subscriber)+ }+ issue.CreatedTime = time.Unix(issue.createdTs, 0)+ issue.UpdatedTime = time.Unix(issue.updatedTs, 0)+ }+ return issues, nil+}