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: migrate issue update to v1 store (#4397)
Danny Xu3467c4accea6
diff --git a/backend/runner/taskrun/scheduler.go b/backend/runner/taskrun/scheduler.goindex 8c1e1d15b3..d7f364e982 100644--- a/backend/runner/taskrun/scheduler.go+++ b/backend/runner/taskrun/scheduler.go@@ -311,18 +311,13 @@ func (s *Scheduler) Run(ctx context.Context, wg *sync.WaitGroup) {}if !ok {// reassign the issue to a new assignee if the current one doesn't fit.- assigneeID, err := s.GetDefaultAssigneeID(ctx, environmentID, issue.ProjectID, issue.Type)+ assignee, err := s.GetDefaultAssignee(ctx, environmentID, issue.ProjectID, issue.Type)if err != nil {log.Error("failed to get a default assignee", zap.Error(err))return}- patch := &api.IssuePatch{- ID: issue.ID,- UpdaterID: api.SystemBotID,- AssigneeID: &assigneeID,- }- if _, err := s.store.PatchIssue(ctx, patch); err != nil {- log.Error("failed to update the issue assignee", zap.Any("issuePatch", patch))+ if _, err := s.store.UpdateIssueV2(ctx, issue.ID, &store.UpdateIssueMessage{Assignee: assignee}, api.SystemBotID); err != nil {+ log.Error("failed to update the issue assignee", zap.Error(err))return}}@@ -370,12 +365,7 @@ func (s *Scheduler) PatchTaskStatement(ctx context.Context, task *api.Task, task}if issue.AssigneeNeedAttention && issue.Project.WorkflowType == api.UIWorkflow {needAttention := false- patch := &api.IssuePatch{- ID: issue.ID,- UpdaterID: api.SystemBotID,- AssigneeNeedAttention: &needAttention,- }- if _, err := s.store.PatchIssue(ctx, patch); err != nil {+ if _, err := s.store.UpdateIssueV2(ctx, issue.ID, &store.UpdateIssueMessage{NeedAttention: &needAttention}, api.SystemBotID); err != nil {return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to try to patch issue assignee_need_attention after updating task statement").SetInternal(err)}}@@ -1119,15 +1109,19 @@ func areAllTasksDone(pipeline *api.Pipeline) bool {return true}-// GetDefaultAssigneeID gets the default assignee for an issue.-func (s *Scheduler) GetDefaultAssigneeID(ctx context.Context, environmentID int, projectID int, issueType api.IssueType) (int, error) {+// GetDefaultAssignee gets the default assignee for an issue.+func (s *Scheduler) GetDefaultAssignee(ctx context.Context, environmentID int, projectID int, issueType api.IssueType) (*store.UserMessage, error) {policy, err := s.store.GetPipelineApprovalPolicy(ctx, environmentID)if err != nil {- return api.UnknownID, errors.Wrapf(err, "failed to GetPipelineApprovalPolicy for environmentID %d", environmentID)+ return nil, errors.Wrapf(err, "failed to GetPipelineApprovalPolicy for environmentID %d", environmentID)}if policy.Value == api.PipelineApprovalValueManualNever {// use SystemBot for auto approval tasks.- return api.SystemBotID, nil+ systemBot, err := s.store.GetUserByID(ctx, api.SystemBotID)+ if err != nil {+ return nil, err+ }+ return systemBot, nil}var groupValue *api.AssigneeGroupValue@@ -1140,18 +1134,18 @@ func (s *Scheduler) GetDefaultAssigneeID(ctx context.Context, environmentID int,if groupValue == nil || *groupValue == api.AssigneeGroupValueWorkspaceOwnerOrDBA {user, err := s.getAnyWorkspaceOwner(ctx)if err != nil {- return api.UnknownID, errors.Wrap(err, "failed to get a workspace owner or DBA")+ return nil, errors.Wrap(err, "failed to get a workspace owner or DBA")}- return user.ID, nil+ return user, nil} else if *groupValue == api.AssigneeGroupValueProjectOwner {projectOwner, err := s.getAnyProjectOwner(ctx, projectID)if err != nil {- return api.UnknownID, errors.Wrap(err, "failed to get a project owner")+ return nil, errors.Wrap(err, "failed to get a project owner")}- return projectOwner.ID, nil+ return projectOwner, nil}// never reached- return api.UnknownID, errors.New("invalid assigneeGroupValue")+ return nil, errors.New("invalid assigneeGroupValue")}// getAnyWorkspaceOwner finds a default assignee from the workspace owners.@@ -1286,19 +1280,19 @@ func (s *Scheduler) ChangeIssueStatus(ctx context.Context, issue *store.IssueMesreturn 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.UID,- UpdaterID: updaterID,- Status: &newStatus,- }+ updateIssueMessage := &store.UpdateIssueMessage{Status: &newStatus}if newStatus != api.IssueOpen && issue.Project.Workflow == api.UIWorkflow {// for UI workflow, set assigneeNeedAttention to false if we are closing the issue.needAttention := false- issuePatch.AssigneeNeedAttention = &needAttention+ updateIssueMessage.NeedAttention = &needAttention+ }+ updatedIssue, err := s.store.UpdateIssueV2(ctx, issue.UID, updateIssueMessage, updaterID)+ if err != nil {+ return nil, errors.Wrapf(err, "failed to update issue %q's status", issue.Title)}- updatedIssue, err := s.store.PatchIssue(ctx, issuePatch)+ composedIssue, err := s.store.GetIssueByID(ctx, issue.UID)if err != nil {- return nil, errors.Wrapf(err, "failed to update issue %q's status with patch %v", issue.Title, issuePatch)+ return nil, err}// Cancel external approval, it's ok if we failed.@@ -1311,7 +1305,7 @@ func (s *Scheduler) ChangeIssueStatus(ctx context.Context, issue *store.IssueMespayload, err := json.Marshal(api.ActivityIssueStatusUpdatePayload{OldStatus: issue.Status,NewStatus: newStatus,- IssueName: updatedIssue.Name,+ IssueName: updatedIssue.Title,})if err != nil {return nil, errors.Wrapf(err, "failed to marshal activity after changing the issue status: %v", issue.Title)@@ -1327,12 +1321,12 @@ func (s *Scheduler) ChangeIssueStatus(ctx context.Context, issue *store.IssueMes}if _, err := s.activityManager.CreateActivity(ctx, activityCreate, &activity.Metadata{- Issue: updatedIssue,+ Issue: composedIssue,}); err != nil {return nil, errors.Wrapf(err, "failed to create activity after changing the issue status: %v", issue.Title)}- return updatedIssue, nil+ return composedIssue, nil}func (s *Scheduler) onTaskPatched(ctx context.Context, issue *api.Issue, taskPatched *api.Task) error {@@ -1435,13 +1429,8 @@ func (s *Scheduler) onTaskPatched(ctx context.Context, issue *api.Issue, taskPat// we need to set issue.AssigneeNeedAttention to false for UI workflow.if taskPatched.Status == api.TaskPending && issue.Project.WorkflowType == api.UIWorkflow && !stageTaskHasPendingApproval {needAttention := false- patch := &api.IssuePatch{- ID: issue.ID,- UpdaterID: api.SystemBotID,- AssigneeNeedAttention: &needAttention,- }- if _, err := s.store.PatchIssue(ctx, patch); err != nil {- return errors.Wrapf(err, "failed to patch issue assigneeNeedAttention after finding out that there isn't any pendingApproval task in the stage, issuePatch: %+v", patch)+ if _, err := s.store.UpdateIssueV2(ctx, issue.ID, &store.UpdateIssueMessage{NeedAttention: &needAttention}, api.SystemBotID); err != nil {+ return errors.Wrapf(err, "failed to patch issue assigneeNeedAttention after finding out that there isn't any pendingApproval task in the stage")}}diff --git a/backend/server/issue.go b/backend/server/issue.goindex 765c5c8a57..d39e0da2ef 100644--- a/backend/server/issue.go+++ b/backend/server/issue.go@@ -172,10 +172,11 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {if err != nil {return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("issueID"))).SetInternal(err)}+ updaterID := c.Get(getPrincipalIDContextKey()).(int)issuePatch := &api.IssuePatch{ID: id,- UpdaterID: c.Get(getPrincipalIDContextKey()).(int),+ UpdaterID: updaterID,}if err := jsonapi.UnmarshalPayload(c.Request().Body, issuePatch); err != nil {return echo.NewHTTPError(http.StatusBadRequest, "Malformed update issue request").SetInternal(err)@@ -192,11 +193,19 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {if issue == nil {return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Unable to find issue ID to update: %d", id))}+ updateIssueMessage := &store.UpdateIssueMessage{+ Title: issuePatch.Name,+ Description: issuePatch.Description,+ NeedAttention: issuePatch.AssigneeNeedAttention,+ Payload: issuePatch.Payload,+ }if issuePatch.AssigneeID != nil {- 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))+ assignee, err := s.store.GetUserByID(ctx, *issuePatch.AssigneeID)+ if err != nil {+ return err}+ updateIssueMessage.Assignee = assigneecomposedPipeline, err := s.store.GetPipelineByID(ctx, issue.PipelineUID)if err != nil {return err@@ -206,7 +215,7 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {// all stages have finished, use the last stagestage = composedPipeline.StageList[len(composedPipeline.StageList)-1]}- ok, err := s.TaskScheduler.CanPrincipalBeAssignee(ctx, *issuePatch.AssigneeID, stage.EnvironmentID, issue.Project.UID, issue.Type)+ ok, err := s.TaskScheduler.CanPrincipalBeAssignee(ctx, assignee.ID, 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)}@@ -217,14 +226,18 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {// set AssigneeNeedAttention to false on assignee changeif issue.Project.Workflow == api.UIWorkflow {needAttention := false- issuePatch.AssigneeNeedAttention = &needAttention+ updateIssueMessage.NeedAttention = &needAttention}}- updatedIssue, err := s.store.PatchIssue(ctx, issuePatch)+ updatedIssue, err := s.store.UpdateIssueV2(ctx, id, updateIssueMessage, updaterID)if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to update issue with ID %d", id)).SetInternal(err)}+ composedIssue, err := s.store.GetIssueByID(ctx, id)+ if err != nil {+ return err+ }// cancel external approval on assignee changeif issuePatch.AssigneeID != nil {@@ -242,7 +255,7 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {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)+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal activity after changing issue name: %v", updatedIssue.Title)).SetInternal(err)}payloadList = append(payloadList, payload)}@@ -254,7 +267,7 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {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)+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal activity after changing issue description: %v", updatedIssue.Title)).SetInternal(err)}payloadList = append(payloadList, payload)}@@ -266,7 +279,7 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {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)+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal activity after changing issue assignee: %v", updatedIssue.Title)).SetInternal(err)}payloadList = append(payloadList, payload)}@@ -280,15 +293,15 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {Payload: string(payload),}if _, err := s.ActivityManager.CreateActivity(ctx, activityCreate, &activity.Metadata{- Issue: updatedIssue,+ Issue: composedIssue,}); err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to create activity after updating issue: %v", updatedIssue.Name)).SetInternal(err)+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to create activity after updating issue: %v", updatedIssue.Title)).SetInternal(err)}}c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)- if err := jsonapi.MarshalPayload(c.Response().Writer, updatedIssue); err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal update issue response: %v", updatedIssue.Name)).SetInternal(err)+ if err := jsonapi.MarshalPayload(c.Response().Writer, composedIssue); err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal update issue response: %v", updatedIssue.Title)).SetInternal(err)}return nil})@@ -357,11 +370,11 @@ func (s *Server) createIssue(ctx context.Context, issueCreate *api.IssueCreate,}// Try to find a more appropriate assignee if the current assignee is the system bot, indicating that the caller might not be sure about who should be the assignee.if issueCreate.AssigneeID == api.SystemBotID {- assigneeID, err := s.TaskScheduler.GetDefaultAssigneeID(ctx, firstEnvironmentID, issueCreate.ProjectID, issueCreate.Type)+ assignee, err := s.TaskScheduler.GetDefaultAssignee(ctx, firstEnvironmentID, issueCreate.ProjectID, issueCreate.Type)if err != nil {return nil, echo.NewHTTPError(http.StatusInternalServerError, "Failed to find a default assignee").SetInternal(err)}- issueCreate.AssigneeID = assigneeID+ issueCreate.AssigneeID = assignee.ID}ok, err := s.TaskScheduler.CanPrincipalBeAssignee(ctx, issueCreate.AssigneeID, firstEnvironmentID, issueCreate.ProjectID, issueCreate.Type)if err != nil {diff --git a/backend/store/issue.go b/backend/store/issue.goindex 4f010be7d2..6472a67aaa 100644--- a/backend/store/issue.go+++ b/backend/store/issue.go@@ -3,7 +3,6 @@ package storeimport ("context""database/sql"- "encoding/json""fmt""strconv""strings"@@ -143,19 +142,6 @@ func (s *Store) FindIssueStripped(ctx context.Context, find *api.IssueFind) ([]*return issueList, nil}-// PatchIssue patches an instance of Issue.-func (s *Store) PatchIssue(ctx context.Context, patch *api.IssuePatch) (*api.Issue, error) {- issueRaw, err := s.patchIssueRaw(ctx, patch)- if err != nil {- return nil, errors.Wrapf(err, "failed to patch Issue with IssuePatch[%+v]", patch)- }- issue, err := s.composeIssue(ctx, issueRaw)- if err != nil {- return nil, errors.Wrapf(err, "failed to compose Issue with issueRaw[%+v]", issueRaw)- }- return issue, nil-}-// CreateIssueValidateOnly creates an issue for validation purpose// Do NOT write to the database.func (s *Store) CreateIssueValidateOnly(ctx context.Context, pipelineCreate *api.PipelineCreate, create *IssueMessage, creatorID int) (*api.Issue, error) {@@ -510,31 +496,6 @@ func (s *Store) getIssueRaw(ctx context.Context, find *api.IssueFind) (*issueRawreturn list[0], nil}-// patchIssueRaw updates an existing issue by ID.-// Returns ENOTFOUND if issue does not exist.-func (s *Store) patchIssueRaw(ctx context.Context, patch *api.IssuePatch) (*issueRaw, error) {- tx, err := s.db.BeginTx(ctx, nil)- if err != nil {- return nil, FormatError(err)- }- defer tx.Rollback()-- issue, err := s.patchIssueImpl(ctx, tx, patch)- if err != nil {- return nil, FormatError(err)- }-- if err := tx.Commit(); err != nil {- return nil, FormatError(err)- }-- if err := s.cache.UpsertCache(issueCacheNamespace, issue.ID, issue); err != nil {- return nil, err- }-- return issue, nil-}-func (*Store) findIssueImpl(ctx context.Context, tx *Tx, find *api.IssueFind) ([]*issueRaw, error) {// Build WHERE clause.where, args := []string{"TRUE"}, []interface{}{}@@ -642,68 +603,6 @@ func (*Store) findIssueImpl(ctx context.Context, tx *Tx, find *api.IssueFind) ([return issuerRawList, nil}-// patchIssueImpl updates a issue by ID. Returns the new state of the issue after update.-func (*Store) patchIssueImpl(ctx context.Context, tx *Tx, patch *api.IssuePatch) (*issueRaw, error) {- // Build UPDATE clause.- set, args := []string{"updater_id = $1"}, []interface{}{patch.UpdaterID}- if v := patch.Name; v != nil {- set, args = append(set, fmt.Sprintf("name = $%d", len(args)+1)), append(args, *v)- }- if v := patch.Status; v != nil {- set, args = append(set, fmt.Sprintf("status = $%d", len(args)+1)), append(args, api.IssueStatus(*v))- }- if v := patch.Description; v != nil {- set, args = append(set, fmt.Sprintf("description = $%d", len(args)+1)), append(args, *v)- }- if v := patch.AssigneeID; v != nil {- set, args = append(set, fmt.Sprintf("assignee_id = $%d", len(args)+1)), append(args, *v)- }- if v := patch.AssigneeNeedAttention; v != nil {- set, args = append(set, fmt.Sprintf("assignee_need_attention = $%d", len(args)+1)), append(args, *v)- }- if v := patch.Payload; v != nil {- payload, err := json.Marshal(*patch.Payload)- if err != nil {- return nil, FormatError(err)- }- set, args = append(set, fmt.Sprintf("payload = $%d", len(args)+1)), append(args, payload)- }-- args = append(args, patch.ID)-- var issueRaw issueRaw- // Execute update query with RETURNING.- if err := tx.QueryRowContext(ctx, fmt.Sprintf(`- UPDATE issue- SET `+strings.Join(set, ", ")+`- WHERE id = $%d- RETURNING id, creator_id, created_ts, updater_id, updated_ts, project_id, pipeline_id, name, status, type, description, assignee_id, assignee_need_attention, payload- `, len(args)),- args...,- ).Scan(- &issueRaw.ID,- &issueRaw.CreatorID,- &issueRaw.CreatedTs,- &issueRaw.UpdaterID,- &issueRaw.UpdatedTs,- &issueRaw.ProjectID,- &issueRaw.PipelineID,- &issueRaw.Name,- &issueRaw.Status,- &issueRaw.Type,- &issueRaw.Description,- &issueRaw.AssigneeID,- &issueRaw.AssigneeNeedAttention,- &issueRaw.Payload,- ); err != nil {- if err == sql.ErrNoRows {- return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("unable to find issue ID to update: %d", patch.ID)}- }- return nil, FormatError(err)- }- return &issueRaw, nil-}-// IssueMessage is the mssage for issues.type IssueMessage struct {Project *ProjectMessage@@ -734,6 +633,17 @@ type IssueMessage struct {updatedTs int64}+// UpdateIssueMessage is the mssage for updating an issue.+type UpdateIssueMessage struct {+ Title *string+ Status *api.IssueStatus+ Description *string+ Assignee *UserMessage+ NeedAttention *bool+ Payload *string+ Subscribers *[]*UserMessage+}+// FindIssueMessage is the message to find issues.type FindIssueMessage struct {UID *int@@ -824,6 +734,51 @@ func (s *Store) CreateIssueV2(ctx context.Context, create *IssueMessage, creatorreturn create, nil}+// UpdateIssueV2 updates an issue.+func (s *Store) UpdateIssueV2(ctx context.Context, uid int, patch *UpdateIssueMessage, updaterID int) (*IssueMessage, error) {+ set, args := []string{"updater_id = $1"}, []interface{}{updaterID}+ if v := patch.Title; v != nil {+ set, args = append(set, fmt.Sprintf("name = $%d", len(args)+1)), append(args, *v)+ }+ if v := patch.Status; v != nil {+ set, args = append(set, fmt.Sprintf("status = $%d", len(args)+1)), append(args, api.IssueStatus(*v))+ }+ if v := patch.Description; v != nil {+ set, args = append(set, fmt.Sprintf("description = $%d", len(args)+1)), append(args, *v)+ }+ if v := patch.Assignee; v != nil {+ set, args = append(set, fmt.Sprintf("assignee_id = $%d", len(args)+1)), append(args, v.ID)+ }+ if v := patch.NeedAttention; v != nil {+ set, args = append(set, fmt.Sprintf("assignee_need_attention = $%d", len(args)+1)), append(args, *v)+ }+ if v := patch.Payload; v != nil {+ set, args = append(set, fmt.Sprintf("payload = $%d", len(args)+1)), append(args, *v)+ }+ args = append(args, uid)++ tx, err := s.db.BeginTx(ctx, nil)+ if err != nil {+ return nil, FormatError(err)+ }+ defer tx.Rollback()++ if _, err := tx.ExecContext(ctx, fmt.Sprintf(`+ UPDATE issue+ SET `+strings.Join(set, ", ")+`+ WHERE id = $%d`, len(args)),+ args...,+ ); err != nil {+ return nil, FormatError(err)+ }++ if err := tx.Commit(); err != nil {+ return nil, FormatError(err)+ }++ return s.GetIssueByUID(ctx, uid)+}+func (s *Store) listIssueImplV2(ctx context.Context, find *FindIssueMessage) ([]*IssueMessage, error) {where, args := []string{"TRUE"}, []interface{}{}if v := find.UID; v != nil {