Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

refactor: add composite PKs for issue chain (#19609)

ecmadaocfe413aff8e8
diff --git a/backend/api/v1/issue_hook.go b/backend/api/v1/issue_hook.go
index 4722732680..b1995bee8a 100644
--- a/backend/api/v1/issue_hook.go
+++ b/backend/api/v1/issue_hook.go
@@ -51,7 +51,7 @@ func postCreateIssue(
if err := approval.FindAndApplyApprovalTemplate(ctx, stores, webhookManager, licenseService, issue); err != nil {
slog.Error("failed to find approval template",
- slog.Int("issue_uid", issue.UID),
+ slog.String("project", issue.ProjectID), slog.Int("issue_uid", issue.UID),
slog.String("issue_title", issue.Title),
log.BBError(err))
}
@@ -59,7 +59,7 @@ func postCreateIssue(
// Refresh issue to get updated approval payload.
uid := issue.UID
var err error
- issue, err = stores.GetIssue(ctx, &store.FindIssueMessage{UID: &uid})
+ issue, err = stores.GetIssue(ctx, &store.FindIssueMessage{ProjectIDs: []string{issue.ProjectID}, UID: &uid})
if err != nil {
return nil, errors.Wrapf(err, "failed to refresh issue")
}
@@ -81,7 +81,7 @@ func postCreateIssue(
return nil, errors.Wrapf(err, "failed to complete role grant")
}
case storepb.Issue_DATABASE_CHANGE:
- b.ApprovalCheckChan <- int64(issue.UID)
+ b.ApprovalCheckChan <- bus.IssueRef{ProjectID: issue.ProjectID, UID: issue.UID}
default:
}
@@ -110,13 +110,14 @@ func completeAccessRequestIssue(ctx context.Context, stores *store.Store, userEm
}
newStatus := storepb.Issue_DONE
- updatedIssue, err := stores.UpdateIssue(ctx, issue.UID, &store.UpdateIssueMessage{Status: &newStatus})
+ updatedIssue, err := stores.UpdateIssue(ctx, issue.ProjectID, issue.UID, &store.UpdateIssueMessage{Status: &newStatus})
if err != nil {
return nil, errors.Wrapf(err, "failed to update issue %q's status", issue.Title)
}
if _, err := stores.CreateIssueComments(ctx, userEmail, &store.IssueCommentMessage{
- IssueUID: issue.UID,
+ ProjectID: issue.ProjectID,
+ IssueUID: issue.UID,
Payload: &storepb.IssueCommentPayload{
Event: &storepb.IssueCommentPayload_IssueUpdate_{
IssueUpdate: &storepb.IssueCommentPayload_IssueUpdate{
diff --git a/backend/api/v1/issue_service.go b/backend/api/v1/issue_service.go
index 4b81e6e882..4c6578e69b 100644
--- a/backend/api/v1/issue_service.go
+++ b/backend/api/v1/issue_service.go
@@ -253,7 +253,7 @@ func (s *IssueService) ListIssues(ctx context.Context, req *connect.Request[v1pb
if err != nil {
return nil, err
}
- issueFind.ProjectID = &projectID
+ issueFind.ProjectIDs = []string{projectID}
orderByKeys, err := store.GetIssueOrders(req.Msg.OrderBy)
if err != nil {
@@ -315,10 +315,11 @@ func (s *IssueService) SearchIssues(ctx context.Context, req *connect.Request[v1
}
issueFind.OrderByKeys = orderByKeys
+ var projectIDs []string
if projectID != "-" {
- issueFind.ProjectID = &projectID
- }
- if issueFind.ProjectID == nil {
+ projectIDs = append(projectIDs, projectID)
+ } else {
+ // Cross-project search
user, ok := GetUserFromContext(ctx)
if !ok {
return nil, connect.NewError(connect.CodeInternal, errors.Errorf("user not found"))
@@ -327,8 +328,11 @@ func (s *IssueService) SearchIssues(ctx context.Context, req *connect.Request[v1
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get projectIDs"))
}
- issueFind.ProjectIDs = projectIDsFilter
+ if projectIDsFilter != nil {
+ projectIDs = *projectIDsFilter
+ }
}
+ issueFind.ProjectIDs = projectIDs
issues, err := s.store.ListIssues(ctx, issueFind)
if err != nil {
@@ -594,7 +598,7 @@ func (s *IssueService) ApproveIssue(ctx context.Context, req *connect.Request[v1
return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to check if the approval is approved"))
}
- issue, err = s.store.UpdateIssue(ctx, issue.UID, &store.UpdateIssueMessage{
+ issue, err = s.store.UpdateIssue(ctx, issue.ProjectID, issue.UID, &store.UpdateIssueMessage{
PayloadUpsert: &storepb.Issue{
Approval: payload.Approval,
},
@@ -604,7 +608,8 @@ func (s *IssueService) ApproveIssue(ctx context.Context, req *connect.Request[v1
}
if _, err := s.store.CreateIssueComments(ctx, user.Email, &store.IssueCommentMessage{
- IssueUID: issue.UID,
+ ProjectID: issue.ProjectID,
+ IssueUID: issue.UID,
Payload: &storepb.IssueCommentPayload{
Comment: req.Msg.Comment,
Event: &storepb.IssueCommentPayload_Approval_{
@@ -695,7 +700,7 @@ func (s *IssueService) RejectIssue(ctx context.Context, req *connect.Request[v1p
Principal: common.FormatUserEmail(user.Email),
})
- issue, err = s.store.UpdateIssue(ctx, issue.UID, &store.UpdateIssueMessage{
+ issue, err = s.store.UpdateIssue(ctx, issue.ProjectID, issue.UID, &store.UpdateIssueMessage{
PayloadUpsert: &storepb.Issue{
Approval: payload.Approval,
},
@@ -705,7 +710,8 @@ func (s *IssueService) RejectIssue(ctx context.Context, req *connect.Request[v1p
}
if _, err := s.store.CreateIssueComments(ctx, user.Email, &store.IssueCommentMessage{
- IssueUID: issue.UID,
+ ProjectID: issue.ProjectID,
+ IssueUID: issue.UID,
Payload: &storepb.IssueCommentPayload{
Comment: req.Msg.Comment,
Event: &storepb.IssueCommentPayload_Approval_{
@@ -798,7 +804,7 @@ func (s *IssueService) RequestIssue(ctx context.Context, req *connect.Request[v1
}
payload.Approval.Approvers = updatedApprovers
- issue, err = s.store.UpdateIssue(ctx, issue.UID, &store.UpdateIssueMessage{
+ issue, err = s.store.UpdateIssue(ctx, issue.ProjectID, issue.UID, &store.UpdateIssueMessage{
PayloadUpsert: &storepb.Issue{
Approval: payload.Approval,
},
@@ -810,7 +816,8 @@ func (s *IssueService) RequestIssue(ctx context.Context, req *connect.Request[v1
approval.NotifyApprovalRequested(ctx, s.store, s.webhookManager, issue, project)
if _, err := s.store.CreateIssueComments(ctx, user.Email, &store.IssueCommentMessage{
- IssueUID: issue.UID,
+ ProjectID: issue.ProjectID,
+ IssueUID: issue.UID,
Payload: &storepb.IssueCommentPayload{
Comment: req.Msg.Comment,
Event: &storepb.IssueCommentPayload_Approval_{
@@ -940,11 +947,14 @@ func (s *IssueService) UpdateIssue(ctx context.Context, req *connect.Request[v1p
}
}
- issue, err = s.store.UpdateIssue(ctx, issue.UID, patch)
+ issue, err = s.store.UpdateIssue(ctx, issue.ProjectID, issue.UID, patch)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to update issue"))
}
+ for _, ic := range issueCommentCreates {
+ ic.ProjectID = issue.ProjectID
+ }
if _, err := s.store.CreateIssueComments(ctx, user.Email, issueCommentCreates...); err != nil {
slog.Warn("failed to create issue comments", "issue id", issue.UID, log.BBError(err))
}
@@ -1014,7 +1024,8 @@ func (s *IssueService) BatchUpdateIssuesStatus(ctx context.Context, req *connect
for _, issueUID := range issueUIDs {
oldStatus := oldIssueStatuses[issueUID]
issueComments = append(issueComments, &store.IssueCommentMessage{
- IssueUID: issueUID,
+ ProjectID: projectID,
+ IssueUID: issueUID,
Payload: &storepb.IssueCommentPayload{
Comment: req.Msg.Reason,
Event: &storepb.IssueCommentPayload_IssueUpdate_{
@@ -1042,8 +1053,8 @@ func (s *IssueService) ListIssueComments(ctx context.Context, req *connect.Reque
return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("%v", err.Error()))
}
issue, err := s.store.GetIssue(ctx, &store.FindIssueMessage{
- UID: &issueUID,
- ProjectID: &projectID,
+ UID: &issueUID,
+ ProjectIDs: []string{projectID},
})
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to get issue, err: %v", err))
@@ -1063,9 +1074,10 @@ func (s *IssueService) ListIssueComments(ctx context.Context, req *connect.Reque
limitPlusOne := offset.limit + 1
issueComments, err := s.store.ListIssueComment(ctx, &store.FindIssueCommentMessage{
- IssueUID: &issue.UID,
- Limit: &limitPlusOne,
- Offset: &offset.offset,
+ ProjectID: projectID,
+ IssueUID: &issue.UID,
+ Limit: &limitPlusOne,
+ Offset: &offset.offset,
})
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to list issue comments, err: %v", err))
@@ -1107,7 +1119,8 @@ func (s *IssueService) CreateIssueComment(ctx context.Context, req *connect.Requ
}
ic, err := s.store.CreateIssueComments(ctx, user.Email, &store.IssueCommentMessage{
- IssueUID: issue.UID,
+ ProjectID: issue.ProjectID,
+ IssueUID: issue.UID,
Payload: &storepb.IssueCommentPayload{
Comment: req.Msg.IssueComment.Comment,
},
@@ -1130,7 +1143,7 @@ func (s *IssueService) UpdateIssueComment(ctx context.Context, req *connect.Requ
return nil, connect.NewError(connect.CodeInternal, errors.Errorf("user not found"))
}
- _, parentIssueUID, err := common.GetProjectIDIssueUID(req.Msg.Parent)
+ parentProjectID, parentIssueUID, err := common.GetProjectIDIssueUID(req.Msg.Parent)
if err != nil {
return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("invalid parent %q: %v", req.Msg.Parent, err))
}
@@ -1142,7 +1155,7 @@ func (s *IssueService) UpdateIssueComment(ctx context.Context, req *connect.Requ
if parentIssueUID != commentIssueUID {
return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("issue comment %q does not belong to parent %q", req.Msg.IssueComment.Name, req.Msg.Parent))
}
- issueComment, err := s.store.GetIssueComment(ctx, &store.FindIssueCommentMessage{ResourceID: &issueCommentID, IssueUID: &parentIssueUID})
+ issueComment, err := s.store.GetIssueComment(ctx, &store.FindIssueCommentMessage{ProjectID: parentProjectID, ResourceID: &issueCommentID, IssueUID: &parentIssueUID})
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to get issue comment: %v", err))
}
@@ -1163,6 +1176,7 @@ func (s *IssueService) UpdateIssueComment(ctx context.Context, req *connect.Requ
return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("issue comment not found"))
}
update := &store.UpdateIssueCommentMessage{
+ ProjectID: parentProjectID,
ResourceID: issueCommentID,
}
for _, path := range req.Msg.UpdateMask.Paths {
@@ -1180,7 +1194,7 @@ func (s *IssueService) UpdateIssueComment(ctx context.Context, req *connect.Requ
}
return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to update the issue comment with error: %v", err.Error()))
}
- issueComment, err = s.store.GetIssueComment(ctx, &store.FindIssueCommentMessage{ResourceID: &issueCommentID})
+ issueComment, err = s.store.GetIssueComment(ctx, &store.FindIssueCommentMessage{ProjectID: parentProjectID, ResourceID: &issueCommentID})
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to get issue comment: %v", err))
}
@@ -1194,8 +1208,8 @@ func (s *IssueService) getIssueMessage(ctx context.Context, name string) (*store
return nil, connect.NewError(connect.CodeInvalidArgument, err)
}
issue, err := s.store.GetIssue(ctx, &store.FindIssueMessage{
- UID: &issueUID,
- ProjectID: &projectID,
+ UID: &issueUID,
+ ProjectIDs: []string{projectID},
})
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get issue"))
diff --git a/backend/api/v1/plan_service.go b/backend/api/v1/plan_service.go
index b3ec75b0aa..b4e097d13e 100644
--- a/backend/api/v1/plan_service.go
+++ b/backend/api/v1/plan_service.go
@@ -322,13 +322,13 @@ func (s *PlanService) UpdatePlan(ctx context.Context, request *connect.Request[v
planCheckRunsTrigger = true
// Evict approvals if issue exists to request re-approval.
- issue, err := s.store.GetIssue(ctx, &store.FindIssueMessage{PlanUID: &oldPlan.UID})
+ issue, err := s.store.GetIssue(ctx, &store.FindIssueMessage{ProjectIDs: []string{projectID}, PlanUID: &oldPlan.UID})
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to get issue: %v", err))
}
if issue != nil {
// Reset approval finding status
- updatedIssue, err := s.store.UpdateIssue(ctx, issue.UID, &store.UpdateIssueMessage{
+ updatedIssue, err := s.store.UpdateIssue(ctx, issue.ProjectID, issue.UID, &store.UpdateIssueMessage{
PayloadUpsert: &storepb.Issue{
Approval: &storepb.IssuePayloadApproval{
ApprovalFindingDone: false,
@@ -345,7 +345,7 @@ func (s *PlanService) UpdatePlan(ctx context.Context, request *connect.Request[v
if updatedIssue.Type == storepb.Issue_DATABASE_EXPORT {
if err := approval.FindAndApplyApprovalTemplate(ctx, s.store, s.webhookManager, s.licenseService, updatedIssue); err != nil {
slog.Error("failed to find approval template after plan update",
- slog.Int("issue_uid", updatedIssue.UID),
+ slog.String("project", updatedIssue.ProjectID), slog.Int("issue_uid", updatedIssue.UID),
slog.String("issue_title", updatedIssue.Title),
log.BBError(err))
// Continue anyway - non-fatal error
@@ -765,7 +765,7 @@ func convertToPlans(ctx context.Context, s *store.Store, plans []*store.PlanMess
planUIDs[i] = int64(p.UID)
}
- issues, err := s.ListIssues(ctx, &store.FindIssueMessage{PlanUIDs: &planUIDs})
+ issues, err := s.ListIssues(ctx, &store.FindIssueMessage{ProjectIDs: []string{plans[0].ProjectID}, PlanUIDs: &planUIDs})
if err != nil {
return nil, errors.Wrap(err, "failed to batch list issues")
}
@@ -794,7 +794,7 @@ func convertToPlans(ctx context.Context, s *store.Store, plans []*store.PlanMess
}
func convertToPlan(ctx context.Context, s *store.Store, plan *store.PlanMessage) (*v1pb.Plan, error) {
- issue, err := s.GetIssue(ctx, &store.FindIssueMessage{PlanUID: &plan.UID})
+ issue, err := s.GetIssue(ctx, &store.FindIssueMessage{ProjectIDs: []string{plan.ProjectID}, PlanUID: &plan.UID})
if err != nil {
return nil, errors.Wrapf(err, "failed to get issue by plan uid %d", plan.UID)
}
diff --git a/backend/api/v1/rollout_service.go b/backend/api/v1/rollout_service.go
index 5e1522b965..3c43eebc05 100644
--- a/backend/api/v1/rollout_service.go
+++ b/backend/api/v1/rollout_service.go
@@ -252,8 +252,8 @@ func (s *RolloutService) CreateRollout(ctx context.Context, req *connect.Request
// Fetch issue associated with this plan (if any)
issue, err := s.store.GetIssue(ctx, &store.FindIssueMessage{
- ProjectID: &projectID,
- PlanUID: &planID,
+ ProjectIDs: []string{projectID},
+ PlanUID: &planID,
})
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to find issue"))
@@ -399,13 +399,14 @@ func CreateRolloutAndPendingTasks(
// Update issue status to DONE when rollout is created
if issue != nil {
newStatus := storepb.Issue_DONE
- updatedIssue, err := s.UpdateIssue(ctx, issue.UID, &store.UpdateIssueMessage{Status: &newStatus})
+ updatedIssue, err := s.UpdateIssue(ctx, issue.ProjectID, issue.UID, &store.UpdateIssueMessage{Status: &newStatus})
if err != nil {
return errors.Wrapf(err, "failed to update issue %q's status", issue.Title)
}
if _, err := s.CreateIssueComments(ctx, userEmail, &store.IssueCommentMessage{
- IssueUID: issue.UID,
+ ProjectID: issue.ProjectID,
+ IssueUID: issue.UID,
Payload: &storepb.IssueCommentPayload{
Event: &storepb.IssueCommentPayload_IssueUpdate_{
IssueUpdate: &storepb.IssueCommentPayload_IssueUpdate{
@@ -731,8 +732,8 @@ func (s *RolloutService) BatchRunTasks(ctx context.Context, req *connect.Request
}
issueN, err := s.store.GetIssue(ctx, &store.FindIssueMessage{
- ProjectID: &projectID,
- PlanUID: &planID,
+ ProjectIDs: []string{projectID},
+ PlanUID: &planID,
})
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to find issue"))
@@ -858,8 +859,8 @@ func (s *RolloutService) BatchSkipTasks(ctx context.Context, req *connect.Reques
}
issueN, err := s.store.GetIssue(ctx, &store.FindIssueMessage{
- ProjectID: &projectID,
- PlanUID: &planID,
+ ProjectIDs: []string{projectID},
+ PlanUID: &planID,
})
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to find issue"))
@@ -948,8 +949,8 @@ func (s *RolloutService) BatchCancelTaskRuns(ctx context.Context, req *connect.R
}
issueN, err := s.store.GetIssue(ctx, &store.FindIssueMessage{
- ProjectID: &projectID,
- PlanUID: &planID,
+ ProjectIDs: []string{projectID},
+ PlanUID: &planID,
})
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to find issue"))
diff --git a/backend/component/bus/bus.go b/backend/component/bus/bus.go
index 22409515e9..dcbf673e83 100644
--- a/backend/component/bus/bus.go
+++ b/backend/component/bus/bus.go
@@ -17,6 +17,12 @@ type TaskRunRef struct {
ID int
}
+// IssueRef identifies an issue by project and UID.
+type IssueRef struct {
+ ProjectID string
+ UID int
+}
+
// PlanCheckRunRef identifies a plan check run by project and UID.
type PlanCheckRunRef struct {
ProjectID string
@@ -27,7 +33,7 @@ type PlanCheckRunRef struct {
type Bus struct {
// ApprovalCheckChan signals when an issue needs approval template finding.
// Triggered by plan check completion, issue creation (if checks already done).
- ApprovalCheckChan chan int64 // issue UID
+ ApprovalCheckChan chan IssueRef
// RunningTaskRunsCancelFunc is the cancelFunc of running taskruns.
RunningTaskRunsCancelFunc sync.Map // map[TaskRunRef]context.CancelFunc
@@ -49,7 +55,7 @@ type Bus struct {
func New() (*Bus, error) {
return &Bus{
- ApprovalCheckChan: make(chan int64, 1000),
+ ApprovalCheckChan: make(chan IssueRef, 1000),
PlanCheckTickleChan: make(chan int, 1000),
TaskRunTickleChan: make(chan int, 1000),
RolloutCreationChan: make(chan PlanRef, 100),
diff --git a/backend/migrator/migration/3.16/0005##add_project_to_plan_chain.sql b/backend/migrator/migration/3.16/0005##add_project_to_plan_chain.sql
deleted file mode 100644
index 94de316f7c..0000000000
--- a/backend/migrator/migration/3.16/0005##add_project_to_plan_chain.sql
+++ /dev/null
@@ -1,94 +0,0 @@
--- Phase A: Drop all FKs referencing plan chain tables
-
--- FKs referencing plan(id)
-ALTER TABLE plan_check_run DROP CONSTRAINT plan_check_run_plan_id_fkey;
-ALTER TABLE plan_webhook_delivery DROP CONSTRAINT plan_webhook_delivery_plan_id_fkey;
-ALTER TABLE task DROP CONSTRAINT task_plan_id_fkey;
-ALTER TABLE issue DROP CONSTRAINT issue_plan_id_fkey;
--- FKs referencing task(id)
-ALTER TABLE task_run DROP CONSTRAINT task_run_task_id_fkey;
--- FKs referencing task_run(id)
-ALTER TABLE task_run_log DROP CONSTRAINT task_run_log_task_run_id_fkey;
-
--- Phase B: Add project columns and change PKs (top-down)
-
--- plan (already has project, just change PK)
-ALTER TABLE plan DROP CONSTRAINT plan_pkey;
-ALTER TABLE plan ADD PRIMARY KEY (project, id);
-
--- task
-ALTER TABLE task ADD COLUMN project TEXT;
-UPDATE task SET project = plan.project FROM plan WHERE task.plan_id = plan.id;
-ALTER TABLE task ALTER COLUMN project SET NOT NULL;
-ALTER TABLE task DROP CONSTRAINT task_pkey;
-ALTER TABLE task ADD PRIMARY KEY (project, id);
-
--- task_run
-ALTER TABLE task_run ADD COLUMN project TEXT;
-UPDATE task_run SET project = task.project FROM task WHERE task_run.task_id = task.id;
-ALTER TABLE task_run ALTER COLUMN project SET NOT NULL;
-ALTER TABLE task_run DROP CONSTRAINT task_run_pkey;
-ALTER TABLE task_run ADD PRIMARY KEY (project, id);
-
--- task_run_log
-ALTER TABLE task_run_log ADD COLUMN project TEXT;
-UPDATE task_run_log SET project = task_run.project FROM task_run WHERE task_run_log.task_run_id = task_run.id;
-ALTER TABLE task_run_log ALTER COLUMN project SET NOT NULL;
-ALTER TABLE task_run_log DROP CONSTRAINT task_run_log_pkey;
-ALTER TABLE task_run_log ADD PRIMARY KEY (project, task_run_id, created_at);
-
--- plan_check_run
-ALTER TABLE plan_check_run ADD COLUMN project TEXT;
-UPDATE plan_check_run SET project = plan.project FROM plan WHERE plan_check_run.plan_id = plan.id;
-ALTER TABLE plan_check_run ALTER COLUMN project SET NOT NULL;
-ALTER TABLE plan_check_run DROP CONSTRAINT plan_check_run_pkey;
-ALTER TABLE plan_check_run ADD PRIMARY KEY (project, id);
-
--- plan_webhook_delivery
-ALTER TABLE plan_webhook_delivery ADD COLUMN project TEXT;
-UPDATE plan_webhook_delivery SET project = plan.project FROM plan WHERE plan_webhook_delivery.plan_id = plan.id;
--- Handle orphan rows (plan_id with no matching plan)
-DELETE FROM plan_webhook_delivery WHERE project IS NULL;
-ALTER TABLE plan_webhook_delivery ALTER COLUMN project SET NOT NULL;
-ALTER TABLE plan_webhook_delivery DROP CONSTRAINT plan_webhook_delivery_pkey;
-ALTER TABLE plan_webhook_delivery ADD PRIMARY KEY (project, plan_id);
-
--- Phase C: Re-add composite FKs and update indexes
-
--- task -> plan
-ALTER TABLE task ADD CONSTRAINT task_plan_id_fkey
- FOREIGN KEY (project, plan_id) REFERENCES plan(project, id);
-
--- task_run -> task
-ALTER TABLE task_run ADD CONSTRAINT task_run_task_id_fkey
- FOREIGN KEY (project, task_id) REFERENCES task(project, id);
-
--- task_run_log -> task_run
-ALTER TABLE task_run_log ADD CONSTRAINT task_run_log_task_run_id_fkey
- FOREIGN KEY (project, task_run_id) REFERENCES task_run(project, id);
-
--- plan_check_run -> plan
-ALTER TABLE plan_check_run ADD CONSTRAINT plan_check_run_plan_id_fkey
- FOREIGN KEY (project, plan_id) REFERENCES plan(project, id);
-
--- plan_webhook_delivery -> plan
-ALTER TABLE plan_webhook_delivery ADD CONSTRAINT plan_webhook_delivery_plan_id_fkey
- FOREIGN KEY (project, plan_id) REFERENCES plan(project, id);
-
--- issue -> plan (cross-chain, issue already has project column)
-ALTER TABLE issue ADD CONSTRAINT issue_plan_id_fkey
- FOREIGN KEY (project, plan_id) REFERENCES plan(project, id);
-
--- Update indexes to include project
-DROP INDEX idx_task_plan_id_environment;
-CREATE INDEX idx_task_plan_id_environment ON task(project, plan_id, environment);
-
-DROP INDEX uk_task_run_task_id_attempt;
-CREATE UNIQUE INDEX uk_task_run_task_id_attempt ON task_run(project, task_id, attempt);
-
-DROP INDEX idx_plan_check_run_unique_plan_id;
-CREATE UNIQUE INDEX idx_plan_check_run_unique_plan_id ON plan_check_run(project, plan_id);
-
--- issue unique plan_id index
-DROP INDEX idx_issue_unique_plan_id;
-CREATE UNIQUE INDEX idx_issue_unique_plan_id ON issue(project, plan_id);
diff --git a/backend/migrator/migration/3.17/0001##add_project_to_plan_chain.sql b/backend/migrator/migration/3.17/0001##add_project_to_plan_chain.sql
new file mode 100644
index 0000000000..d5ad44828f
--- /dev/null
+++ b/backend/migrator/migration/3.17/0001##add_project_to_plan_chain.sql
@@ -0,0 +1,160 @@
+-- Phase A: Drop all FKs referencing plan chain tables
+ALTER TABLE plan_check_run DROP CONSTRAINT IF EXISTS plan_check_run_plan_id_fkey;
+ALTER TABLE plan_webhook_delivery DROP CONSTRAINT IF EXISTS plan_webhook_delivery_plan_id_fkey;
+ALTER TABLE task DROP CONSTRAINT IF EXISTS task_plan_id_fkey;
+ALTER TABLE issue DROP CONSTRAINT IF EXISTS issue_plan_id_fkey;
+ALTER TABLE task_run DROP CONSTRAINT IF EXISTS task_run_task_id_fkey;
+ALTER TABLE task_run_log DROP CONSTRAINT IF EXISTS task_run_log_task_run_id_fkey;
+
+-- Phase B: Add project columns and change PKs (top-down)
+
+-- plan (already has project, just change PK)
+DO $$ BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_constraint
+ WHERE conname = 'plan_pkey'
+ AND conrelid = 'plan'::regclass
+ AND array_length(conkey, 1) = 2
+ ) THEN
+ ALTER TABLE plan DROP CONSTRAINT IF EXISTS plan_pkey;
+ ALTER TABLE plan ADD PRIMARY KEY (project, id);
+ END IF;
+END $$;
+
+-- task
+ALTER TABLE task ADD COLUMN IF NOT EXISTS project TEXT;
+UPDATE task SET project = plan.project FROM plan WHERE task.project IS NULL AND task.plan_id = plan.id;
+ALTER TABLE task ALTER COLUMN project SET NOT NULL;
+DO $$ BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_constraint
+ WHERE conname = 'task_pkey'
+ AND conrelid = 'task'::regclass
+ AND array_length(conkey, 1) = 2
+ ) THEN
+ ALTER TABLE task DROP CONSTRAINT IF EXISTS task_pkey;
+ ALTER TABLE task ADD PRIMARY KEY (project, id);
+ END IF;
+END $$;
+
+-- task_run
+ALTER TABLE task_run ADD COLUMN IF NOT EXISTS project TEXT;
+UPDATE task_run SET project = task.project FROM task WHERE task_run.project IS NULL AND task_run.task_id = task.id;
+ALTER TABLE task_run ALTER COLUMN project SET NOT NULL;
+DO $$ BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_constraint
+ WHERE conname = 'task_run_pkey'
+ AND conrelid = 'task_run'::regclass
+ AND array_length(conkey, 1) = 2
+ ) THEN
+ ALTER TABLE task_run DROP CONSTRAINT IF EXISTS task_run_pkey;
+ ALTER TABLE task_run ADD PRIMARY KEY (project, id);
+ END IF;
+END $$;
+
+-- task_run_log
+ALTER TABLE task_run_log ADD COLUMN IF NOT EXISTS project TEXT;
+UPDATE task_run_log SET project = task_run.project FROM task_run WHERE task_run_log.project IS NULL AND task_run_log.task_run_id = task_run.id;
+ALTER TABLE task_run_log ALTER COLUMN project SET NOT NULL;
+DO $$ BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_constraint
+ WHERE conname = 'task_run_log_pkey'
+ AND conrelid = 'task_run_log'::regclass
+ AND array_length(conkey, 1) > 1
+ ) THEN
+ ALTER TABLE task_run_log DROP CONSTRAINT IF EXISTS task_run_log_pkey;
+ ALTER TABLE task_run_log ADD PRIMARY KEY (project, task_run_id, created_at);
+ END IF;
+END $$;
+
+-- plan_check_run
+ALTER TABLE plan_check_run ADD COLUMN IF NOT EXISTS project TEXT;
+UPDATE plan_check_run SET project = plan.project FROM plan WHERE plan_check_run.project IS NULL AND plan_check_run.plan_id = plan.id;
+ALTER TABLE plan_check_run ALTER COLUMN project SET NOT NULL;
+DO $$ BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_constraint
+ WHERE conname = 'plan_check_run_pkey'
+ AND conrelid = 'plan_check_run'::regclass
+ AND array_length(conkey, 1) = 2
+ ) THEN
+ ALTER TABLE plan_check_run DROP CONSTRAINT IF EXISTS plan_check_run_pkey;
+ ALTER TABLE plan_check_run ADD PRIMARY KEY (project, id);
+ END IF;
+END $$;
+
+-- plan_webhook_delivery
+ALTER TABLE plan_webhook_delivery ADD COLUMN IF NOT EXISTS project TEXT;
+UPDATE plan_webhook_delivery SET project = plan.project FROM plan WHERE plan_webhook_delivery.project IS NULL AND plan_webhook_delivery.plan_id = plan.id;
+DELETE FROM plan_webhook_delivery WHERE project IS NULL;
+ALTER TABLE plan_webhook_delivery ALTER COLUMN project SET NOT NULL;
+DO $$ BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_constraint
+ WHERE conname = 'plan_webhook_delivery_pkey'
+ AND conrelid = 'plan_webhook_delivery'::regclass
+ AND array_length(conkey, 1) = 2
+ ) THEN
+ ALTER TABLE plan_webhook_delivery DROP CONSTRAINT IF EXISTS plan_webhook_delivery_pkey;
+ ALTER TABLE plan_webhook_delivery ADD PRIMARY KEY (project, plan_id);
+ END IF;
+END $$;
+
+-- Phase C: Re-add composite FKs and update indexes
+
+DO $$ BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'task_plan_id_fkey' AND conrelid = 'task'::regclass) THEN
+ ALTER TABLE task ADD CONSTRAINT task_plan_id_fkey
+ FOREIGN KEY (project, plan_id) REFERENCES plan(project, id);
+ END IF;
+END $$;
+
+DO $$ BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'task_run_task_id_fkey' AND conrelid = 'task_run'::regclass) THEN
+ ALTER TABLE task_run ADD CONSTRAINT task_run_task_id_fkey
+ FOREIGN KEY (project, task_id) REFERENCES task(project, id);
+ END IF;
+END $$;
+
+DO $$ BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'task_run_log_task_run_id_fkey' AND conrelid = 'task_run_log'::regclass) THEN
+ ALTER TABLE task_run_log ADD CONSTRAINT task_run_log_task_run_id_fkey
+ FOREIGN KEY (project, task_run_id) REFERENCES task_run(project, id);
+ END IF;
+END $$;
+
+DO $$ BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'plan_check_run_plan_id_fkey' AND conrelid = 'plan_check_run'::regclass) THEN
+ ALTER TABLE plan_check_run ADD CONSTRAINT plan_check_run_plan_id_fkey
+ FOREIGN KEY (project, plan_id) REFERENCES plan(project, id);
+ END IF;
+END $$;
+
+DO $$ BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'plan_webhook_delivery_plan_id_fkey' AND conrelid = 'plan_webhook_delivery'::regclass) THEN
+ ALTER TABLE plan_webhook_delivery ADD CONSTRAINT plan_webhook_delivery_plan_id_fkey
+ FOREIGN KEY (project, plan_id) REFERENCES plan(project, id);
+ END IF;
+END $$;
+
+DO $$ BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'issue_plan_id_fkey' AND conrelid = 'issue'::regclass) THEN
+ ALTER TABLE issue ADD CONSTRAINT issue_plan_id_fkey
+ FOREIGN KEY (project, plan_id) REFERENCES plan(project, id);
+ END IF;
+END $$;
+
+-- Update indexes to include project
+DROP INDEX IF EXISTS idx_task_plan_id_environment;
+CREATE INDEX IF NOT EXISTS idx_task_plan_id_environment ON task(project, plan_id, environment);
+
+DROP INDEX IF EXISTS uk_task_run_task_id_attempt;
+CREATE UNIQUE INDEX IF NOT EXISTS uk_task_run_task_id_attempt ON task_run(project, task_id, attempt);
+
+DROP INDEX IF EXISTS idx_plan_check_run_unique_plan_id;
+CREATE UNIQUE INDEX IF NOT EXISTS idx_plan_check_run_unique_plan_id ON plan_check_run(project, plan_id);
+
+DROP INDEX IF EXISTS idx_issue_unique_plan_id;
+CREATE UNIQUE INDEX IF NOT EXISTS idx_issue_unique_plan_id ON issue(project, plan_id);
diff --git a/backend/migrator/migration/3.17/0002##add_project_to_issue_chain.sql b/backend/migrator/migration/3.17/0002##add_project_to_issue_chain.sql
new file mode 100644
index 0000000000..4dbe78e919
--- /dev/null
+++ b/backend/migrator/migration/3.17/0002##add_project_to_issue_chain.sql
@@ -0,0 +1,57 @@
+-- Phase A: Drop FKs
+ALTER TABLE issue_comment DROP CONSTRAINT IF EXISTS issue_comment_issue_id_fkey;
+
+-- Phase B: Change issue PK
+DO $$ BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_constraint
+ WHERE conname = 'issue_pkey'
+ AND conrelid = 'issue'::regclass
+ AND array_length(conkey, 1) = 2
+ ) THEN
+ ALTER TABLE issue DROP CONSTRAINT IF EXISTS issue_pkey;
+ ALTER TABLE issue ADD PRIMARY KEY (project, id);
+ END IF;
+END $$;
+
+-- Phase C: Modify issue_comment
+-- Drop id column (unused — all lookups use resource_id)
+DO $$ BEGIN
+ IF EXISTS (
+ SELECT 1 FROM information_schema.columns
+ WHERE table_name = 'issue_comment' AND column_name = 'id'
+ ) THEN
+ ALTER TABLE issue_comment DROP CONSTRAINT IF EXISTS issue_comment_pkey;
+ ALTER TABLE issue_comment DROP COLUMN id;
+ END IF;
+END $$;
+
+-- Add project column, backfill from issue
+ALTER TABLE issue_comment ADD COLUMN IF NOT EXISTS project text;
+UPDATE issue_comment SET project = issue.project FROM issue WHERE issue_comment.project IS NULL AND issue_comment.issue_id = issue.id;
+DELETE FROM issue_comment WHERE project IS NULL;
+ALTER TABLE issue_comment ALTER COLUMN project SET NOT NULL;
+
+-- Use resource_id as PK
+DO $$ BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_constraint
+ WHERE conname = 'issue_comment_pkey'
+ AND conrelid = 'issue_comment'::regclass
+ ) THEN
+ ALTER TABLE issue_comment ADD PRIMARY KEY (resource_id);
+ END IF;
+END $$;
+
+-- Phase D: Re-add FKs and update indexes
+DO $$ BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'issue_comment_issue_id_fkey' AND conrelid = 'issue_comment'::regclass) THEN
+ ALTER TABLE issue_comment ADD CONSTRAINT issue_comment_issue_id_fkey
+ FOREIGN KEY (project, issue_id) REFERENCES issue(project, id);
+ END IF;
+END $$;
+
+DROP INDEX IF EXISTS idx_issue_comment_issue_id;
+CREATE INDEX IF NOT EXISTS idx_issue_comment_issue_id ON issue_comment(project, issue_id);
+
+DROP SEQUENCE IF EXISTS issue_comment_id_seq;
diff --git a/backend/migrator/migration/LATEST.sql b/backend/migrator/migration/LATEST.sql
index a18c630801..dba5e9ee62 100644
--- a/backend/migrator/migration/LATEST.sql
+++ b/backend/migrator/migration/LATEST.sql
@@ -298,7 +298,7 @@ CREATE TABLE task_run_log (
-----------------------
-- issue
CREATE TABLE issue (
- id serial PRIMARY KEY,
+ id serial,
resource_id text NOT NULL DEFAULT gen_random_uuid()::text,
creator text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
@@ -314,6 +314,7 @@ CREATE TABLE issue (
-- Stored as Issue (proto/store/store/issue.proto)
payload jsonb NOT NULL DEFAULT '{}',
ts_vector tsvector,
+ PRIMARY KEY (project, id),
FOREIGN KEY (project, plan_id) REFERENCES plan(project, id)
);
@@ -358,21 +359,21 @@ CREATE INDEX idx_audit_log_payload_user ON audit_log((payload->>'user'));
ALTER SEQUENCE audit_log_id_seq RESTART WITH 101;
CREATE TABLE issue_comment (
- id bigserial PRIMARY KEY,
resource_id text NOT NULL DEFAULT gen_random_uuid()::text,
creator text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
- issue_id integer NOT NULL REFERENCES issue(id),
+ project text NOT NULL,
+ issue_id integer NOT NULL,
-- Stored as IssueCommentPayload (proto/store/store/issue_comment.proto)
- payload jsonb NOT NULL DEFAULT '{}'
+ payload jsonb NOT NULL DEFAULT '{}',
+ PRIMARY KEY (resource_id),
+ FOREIGN KEY (project, issue_id) REFERENCES issue(project, id)
);
-CREATE INDEX idx_issue_comment_issue_id ON issue_comment(issue_id);
+CREATE INDEX idx_issue_comment_issue_id ON issue_comment(project, issue_id);
CREATE UNIQUE INDEX idx_issue_comment_unique_resource_id ON issue_comment(resource_id);
-ALTER SEQUENCE issue_comment_id_seq RESTART WITH 101;
-
CREATE TABLE query_history (
id bigserial PRIMARY KEY,
creator text NOT NULL,
diff --git a/backend/migrator/migrator_test.go b/backend/migrator/migrator_test.go
index 4d4dcca846..ab92f6fa9f 100644
--- a/backend/migrator/migrator_test.go
+++ b/backend/migrator/migrator_test.go
@@ -15,8 +15,8 @@ import (
func TestLatestVersion(t *testing.T) {
files, err := getSortedVersionedFiles()
require.NoError(t, err)
- require.Equal(t, semver.MustParse("3.17.0"), *files[len(files)-1].version)
- require.Equal(t, "migration/3.17/0000##rename_grant_request_to_role_grant.sql", files[len(files)-1].path)
+ require.Equal(t, semver.MustParse("3.17.2"), *files[len(files)-1].version)
+ require.Equal(t, "migration/3.17/0002##add_project_to_issue_chain.sql", files[len(files)-1].path)
}
func TestVersionUnique(t *testing.T) {
diff --git a/backend/runner/approval/runner.go b/backend/runner/approval/runner.go
index d5609d5abc..f2b2635c29 100644
--- a/backend/runner/approval/runner.go
+++ b/backend/runner/approval/runner.go
@@ -48,12 +48,12 @@ func (r *Runner) Run(ctx context.Context, wg *sync.WaitGroup) {
for {
select {
- case issueUID := <-r.bus.ApprovalCheckChan:
+ case ref := <-r.bus.ApprovalCheckChan:
if err := r.licenseService.CheckReplicaLimit(ctx); err != nil {
slog.Warn("Approval runner skipped due to HA license restriction", log.BBError(err))
continue
}
- r.processIssue(ctx, issueUID)
+ r.processIssue(ctx, ref)
case <-ctx.Done():
return
}
@@ -77,13 +77,13 @@ func FindAndApplyApprovalTemplate(ctx context.Context, stores *store.Store, webh
return nil
}
-func (r *Runner) processIssue(ctx context.Context, issueUID int64) {
+func (r *Runner) processIssue(ctx context.Context, ref bus.IssueRef) {
// Get fresh issue from database
- uid := int(issueUID)
- issue, err := r.store.GetIssue(ctx, &store.FindIssueMessage{UID: &uid})
+ uid := ref.UID
+ issue, err := r.store.GetIssue(ctx, &store.FindIssueMessage{ProjectIDs: []string{ref.ProjectID}, UID: &uid})
if err != nil {
slog.Error("failed to get issue for approval check",
- slog.Int64("issue_uid", issueUID), log.BBError(err))
+ slog.String("project", ref.ProjectID), slog.Int("issue_uid", ref.UID), log.BBError(err))
return
}
if issue == nil {
@@ -98,7 +98,7 @@ func (r *Runner) processIssue(ctx context.Context, issueUID int64) {
if err := findApprovalTemplateForIssue(ctx, r.store, r.webhookManager, r.licenseService, issue, approvalSetting); err != nil {
slog.Error("failed to find approval template",
- slog.Int64("issue_uid", issueUID),
+ slog.String("project", ref.ProjectID), slog.Int("issue_uid", ref.UID),
slog.String("issue_title", issue.Title),
log.BBError(err))
// Don't persist error - user can rerun plan check to retry
@@ -110,10 +110,10 @@ func (r *Runner) processIssue(ctx context.Context, issueUID int64) {
// If approved, trigger rollout creation.
if issue.PlanUID != nil {
// Re-fetch issue to get updated approval state
- issue, err = r.store.GetIssue(ctx, &store.FindIssueMessage{UID: &uid})
+ issue, err = r.store.GetIssue(ctx, &store.FindIssueMessage{ProjectIDs: []string{ref.ProjectID}, UID: &uid})
if err != nil {
slog.Error("failed to re-fetch issue after approval finding",
- slog.Int64("issue_uid", issueUID), log.BBError(err))
+ slog.String("project", ref.ProjectID), slog.Int("issue_uid", ref.UID), log.BBError(err))
return
}
if issue == nil {
@@ -123,7 +123,7 @@ func (r *Runner) processIssue(ctx context.Context, issueUID int64) {
approved, err := utils.CheckIssueApproved(issue)
if err != nil {
slog.Error("failed to check if issue is approved",
- slog.Int64("issue_uid", issueUID), log.BBError(err))
+ slog.String("project", ref.ProjectID), slog.Int("issue_uid", ref.UID), log.BBError(err))
return
}
if approved {
@@ -209,7 +209,7 @@ func findApprovalTemplateForIssue(ctx context.Context, stores *store.Store, webh
}
payload.RiskLevel = riskLevel
- if _, err := stores.UpdateIssue(ctx, issue.UID, &store.UpdateIssueMessage{
+ if _, err := stores.UpdateIssue(ctx, issue.ProjectID, issue.UID, &store.UpdateIssueMessage{
PayloadUpsert: &storepb.Issue{
Approval: payload.Approval,
RiskLevel: riskLevel,
diff --git a/backend/runner/plancheck/scheduler.go b/backend/runner/plancheck/scheduler.go
index ac58279504..9d5a0804b9 100644
--- a/backend/runner/plancheck/scheduler.go
+++ b/backend/runner/plancheck/scheduler.go
@@ -168,16 +168,16 @@ func (s *Scheduler) markPlanCheckRunDone(ctx context.Context, projectID string,
// Trigger approval finding after plan checks complete.
// The approval runner will trigger rollout creation after it finishes.
- issue, err := s.store.GetIssue(ctx, &store.FindIssueMessage{PlanUID: &planUID})
+ issue, err := s.store.GetIssue(ctx, &store.FindIssueMessage{ProjectIDs: []string{projectID}, PlanUID: &planUID})
if err != nil {
slog.Error("failed to get issue for approval check after plan check",
- slog.Int("plan_id", int(planUID)),
+ slog.String("project", projectID), slog.Int("plan_id", int(planUID)),
log.BBError(err))
return
}
if issue != nil && issue.PlanUID != nil {
// Trigger approval finding.
- s.bus.ApprovalCheckChan <- int64(issue.UID)
+ s.bus.ApprovalCheckChan <- bus.IssueRef{ProjectID: projectID, UID: issue.UID}
}
}
diff --git a/backend/runner/taskrun/data_export_executor.go b/backend/runner/taskrun/data_export_executor.go
index 1ba724e2b8..a1b61bb7a0 100644
--- a/backend/runner/taskrun/data_export_executor.go
+++ b/backend/runner/taskrun/data_export_executor.go
@@ -46,7 +46,7 @@ type DataExportExecutor struct {
// RunOnce will run the data export task executor once.
func (exec *DataExportExecutor) RunOnce(ctx context.Context, _ context.Context, task *store.TaskMessage, _ int) (*storepb.TaskRunResult, error) {
- issue, err := exec.store.GetIssue(ctx, &store.FindIssueMessage{PlanUID: &task.PlanID})
+ issue, err := exec.store.GetIssue(ctx, &store.FindIssueMessage{ProjectIDs: []string{task.ProjectID}, PlanUID: &task.PlanID})
if err != nil {
return nil, errors.Wrapf(err, "failed to get issue")
}
diff --git a/backend/runner/taskrun/rollout_creator.go b/backend/runner/taskrun/rollout_creator.go
index 1543b279b6..d04c8364e0 100644
--- a/backend/runner/taskrun/rollout_creator.go
+++ b/backend/runner/taskrun/rollout_creator.go
@@ -53,18 +53,20 @@ func (rc *RolloutCreator) tryCreateRollout(ctx context.Context, ref bus.PlanRef)
plan, err := rc.store.GetPlan(ctx, &store.FindPlanMessage{ProjectID: ref.ProjectID, UID: &planID})
if err != nil {
slog.Error("failed to get plan for rollout creation",
+ slog.String("project", ref.ProjectID),
slog.Int("plan_id", int(planID)),
log.BBError(err))
return
}
if plan == nil {
- slog.Debug("plan not found for rollout creation", slog.Int("plan_id", int(planID)))
+ slog.Debug("plan not found for rollout creation", slog.String("project", ref.ProjectID), slog.Int("plan_id", int(planID)))
return
}
// Skip deleted (closed) plans
if plan.Deleted {
slog.Debug("plan is deleted, skipping rollout creation",
+ slog.String("project", ref.ProjectID),
slog.Int("plan_id", int(planID)))
return
}
@@ -72,6 +74,7 @@ func (rc *RolloutCreator) tryCreateRollout(ctx context.Context, ref bus.PlanRef)
// Idempotency: skip if rollout already exists
if plan.Config != nil && plan.Config.HasRollout {
slog.Debug("rollout already exists, skipping creation",
+ slog.String("project", ref.ProjectID),
slog.Int("plan_id", int(planID)))
return
}
@@ -79,25 +82,28 @@ func (rc *RolloutCreator) tryCreateRollout(ctx context.Context, ref bus.PlanRef)
// Only auto-create rollout for plans with change database specs
if !hasOnlyChangeDatabaseSpecs(plan) {
slog.Debug("plan has non-change-database specs, skipping auto-creation",
+ slog.String("project", ref.ProjectID),
slog.Int("plan_id", int(planID)))
return
}
- issue, err := rc.store.GetIssue(ctx, &store.FindIssueMessage{PlanUID: &planID})
+ issue, err := rc.store.GetIssue(ctx, &store.FindIssueMessage{ProjectIDs: []string{ref.ProjectID}, PlanUID: &planID})
if err != nil {
slog.Error("failed to get issue for rollout creation",
+ slog.String("project", ref.ProjectID),
slog.Int("plan_id", int(planID)),
log.BBError(err))
return
}
if issue == nil {
- slog.Debug("issue not found for rollout creation", slog.Int("plan_id", int(planID)))
+ slog.Debug("issue not found for rollout creation", slog.String("project", ref.ProjectID), slog.Int("plan_id", int(planID)))
return
}
// Skip canceled issues
if issue.Status == storepb.Issue_CANCELED {
slog.Debug("issue is canceled, skipping rollout creation",
+ slog.String("project", ref.ProjectID),
slog.Int("plan_id", int(planID)))
return
}
@@ -118,12 +124,14 @@ func (rc *RolloutCreator) tryCreateRollout(ctx context.Context, ref bus.PlanRef)
approved, err := utils.CheckIssueApproved(issue)
if err != nil {
slog.Error("failed to check if the issue is approved",
+ slog.String("project", ref.ProjectID),
slog.Int("plan_id", int(planID)),
log.BBError(err))
return
}
if !approved {
slog.Debug("issue not approved, skipping rollout creation",
+ slog.String("project", ref.ProjectID),
slog.Int("plan_id", int(planID)))
return
}
@@ -132,6 +140,7 @@ func (rc *RolloutCreator) tryCreateRollout(ctx context.Context, ref bus.PlanRef)
planCheckRun, err := rc.store.GetPlanCheckRun(ctx, plan.ProjectID, planID)
if err != nil {
slog.Error("failed to get plan check run for rollout creation",
+ slog.String("project", ref.ProjectID),
slog.Int("plan_id", int(planID)),
log.BBError(err))
return
@@ -142,6 +151,7 @@ func (rc *RolloutCreator) tryCreateRollout(ctx context.Context, ref bus.PlanRef)
// Check if plan checks are in DONE status
if planCheckRun.Status != store.PlanCheckRunStatusDone {
slog.Debug("plan checks not in DONE status, skipping rollout creation",
+ slog.String("project", ref.ProjectID),
slog.Int("plan_id", int(planID)),
slog.String("status", string(planCheckRun.Status)))
return
@@ -152,6 +162,7 @@ func (rc *RolloutCreator) tryCreateRollout(ctx context.Context, ref bus.PlanRef)
for _, result := range planCheckRun.Result.Results {
if result.Status == storepb.Advice_ERROR {
slog.Debug("plan checks have errors, skipping rollout creation",
+ slog.String("project", ref.ProjectID),
slog.Int("plan_id", int(planID)))
return
}
@@ -160,12 +171,13 @@ func (rc *RolloutCreator) tryCreateRollout(ctx context.Context, ref bus.PlanRef)
}
// All conditions met - create the rollout
- slog.Info("auto-creating rollout", slog.Int("plan_id", int(planID)))
+ slog.Info("auto-creating rollout", slog.String("project", ref.ProjectID), slog.Int("plan_id", int(planID)))
// Create rollout and pending tasks
// Use issue creator's email since this is auto-rollout for their issue
if err := apiv1.CreateRolloutAndPendingTasks(ctx, rc.store, issue.CreatorEmail, plan, issue, project, nil); err != nil {
slog.Error("failed to create rollout and pending tasks",
+ slog.String("project", ref.ProjectID),
slog.Int("plan_id", int(planID)),
log.BBError(err))
return
@@ -174,7 +186,7 @@ func (rc *RolloutCreator) tryCreateRollout(ctx context.Context, ref bus.PlanRef)
// Tickle task run scheduler
rc.bus.TaskRunTickleChan <- 0
- slog.Info("successfully auto-created rollout", slog.Int("plan_id", int(planID)))
+ slog.Info("successfully auto-created rollout", slog.String("project", ref.ProjectID), slog.Int("plan_id", int(planID)))
}
// hasOnlyChangeDatabaseSpecs checks if every spec in the plan is a change database spec.
diff --git a/backend/runner/taskrun/scheduler.go b/backend/runner/taskrun/scheduler.go
index c148a59670..234bbe6869 100644
--- a/backend/runner/taskrun/scheduler.go
+++ b/backend/runner/taskrun/scheduler.go
@@ -170,7 +170,7 @@ func (s *Scheduler) checkPlanCompletion(ctx context.Context, ref bus.PlanRef) {
// Deferred rollout plans are those with only exportDataConfig or createDatabaseConfig specs.
// These are simple single-phase operations that don't require manual resolution.
if isDeferredRolloutPlan(plan) {
- s.autoResolveIssue(ctx, planID)
+ s.autoResolveIssue(ctx, ref.ProjectID, planID)
}
}
@@ -190,8 +190,8 @@ func isDeferredRolloutPlan(plan *store.PlanMessage) bool {
}
// autoResolveIssue automatically resolves the issue associated with a plan by setting its status to DONE.
-func (s *Scheduler) autoResolveIssue(ctx context.Context, planID int64) {
- issue, err := s.store.GetIssue(ctx, &store.FindIssueMessage{PlanUID: &planID})
+func (s *Scheduler) autoResolveIssue(ctx context.Context, projectID string, planID int64) {
+ issue, err := s.store.GetIssue(ctx, &store.FindIssueMessage{ProjectIDs: []string{projectID}, PlanUID: &planID})
if err != nil {
slog.Error("failed to get issue for auto-resolve", log.BBError(err))
return
@@ -204,9 +204,9 @@ func (s *Scheduler) autoResolveIssue(ctx context.Context, planID int64) {
}
newStatus := storepb.Issue_DONE
- if _, err := s.store.UpdateIssue(ctx, issue.UID, &store.UpdateIssueMessage{Status: &newStatus}); err != nil {
- slog.Error("failed to auto-resolve issue", slog.Int("issueUID", issue.UID), log.BBError(err))
+ if _, err := s.store.UpdateIssue(ctx, issue.ProjectID, issue.UID, &store.UpdateIssueMessage{Status: &newStatus}); err != nil {
+ slog.Error("failed to auto-resolve issue", slog.String("project", projectID), slog.Int("issueUID", issue.UID), log.BBError(err))
return
}
- slog.Info("auto-resolved deferred rollout issue", slog.Int("issueUID", issue.UID), slog.Int64("planID", planID))
+ slog.Info("auto-resolved deferred rollout issue", slog.String("project", projectID), slog.Int("issueUID", issue.UID), slog.Int64("planID", planID))
}
diff --git a/backend/store/issue.go b/backend/store/issue.go
index 80042a23f4..12b099e3ca 100644
--- a/backend/store/issue.go
+++ b/backend/store/issue.go
@@ -58,12 +58,14 @@ type UpdateIssueMessage struct {
// FindIssueMessage is the message to find issues.
type FindIssueMessage struct {
- UID *int
- ProjectID *string
- ProjectIDs *[]string
- PlanUID *int64
- PlanUIDs *[]int64
- CreatorID *string
+ // Required field
+ ProjectIDs []string
+
+ UID *int
+ PlanUID *int64
+ PlanUIDs *[]int64
+ CreatorID *string
+
CreatedAtBefore *time.Time
CreatedAtAfter *time.Time
Types *[]storepb.Issue_Type
@@ -165,12 +167,12 @@ func (s *Store) CreateIssue(ctx context.Context, create *IssueMessage) (*IssueMe
return nil, err
}
- return s.GetIssue(ctx, &FindIssueMessage{UID: &create.UID})
+ return s.GetIssue(ctx, &FindIssueMessage{ProjectIDs: []string{create.ProjectID}, UID: &create.UID})
}
// UpdateIssue updates an issue.
-func (s *Store) UpdateIssue(ctx context.Context, uid int, patch *UpdateIssueMessage) (*IssueMessage, error) {
- oldIssue, err := s.GetIssue(ctx, &FindIssueMessage{UID: &uid})
+func (s *Store) UpdateIssue(ctx context.Context, projectID string, uid int, patch *UpdateIssueMessage) (*IssueMessage, error) {
+ oldIssue, err := s.GetIssue(ctx, &FindIssueMessage{ProjectIDs: []string{projectID}, UID: &uid})
if err != nil {
return nil, err
}
@@ -211,7 +213,7 @@ func (s *Store) UpdateIssue(ctx context.Context, uid int, patch *UpdateIssueMess
set.Comma("ts_vector = ?", tsVector)
}
- q := qb.Q().Space("UPDATE issue SET ? WHERE id = ?", set, uid)
+ q := qb.Q().Space("UPDATE issue SET ? WHERE project = ? AND id = ?", set, projectID, uid)
query, args, err := q.ToSQL()
if err != nil {
@@ -222,7 +224,7 @@ func (s *Store) UpdateIssue(ctx context.Context, uid int, patch *UpdateIssueMess
return nil, err
}
- return s.GetIssue(ctx, &FindIssueMessage{UID: &uid})
+ return s.GetIssue(ctx, &FindIssueMessage{ProjectIDs: []string{projectID}, UID: &uid})
}
// ListIssues returns the list of issues by find query.
@@ -231,6 +233,15 @@ func (s *Store) ListIssues(ctx context.Context, find *FindIssueMessage) ([]*Issu
from := qb.Q().Space("issue")
where := qb.Q()
+ if len(find.ProjectIDs) == 0 {
+ return nil, errors.Errorf("empty project filter")
+ }
+ if len(find.ProjectIDs) == 1 {
+ where.And("issue.project = ?", find.ProjectIDs[0])
+ } else {
+ where.And("issue.project = ANY(?)", find.ProjectIDs)
+ }
+
if v := find.UID; v != nil {
where.And("issue.id = ?", *v)
}
@@ -240,12 +251,7 @@ func (s *Store) ListIssues(ctx context.Context, find *FindIssueMessage) ([]*Issu
if v := find.PlanUIDs; v != nil {
where.And("issue.plan_id = ANY(?)", *v)
}
- if v := find.ProjectID; v != nil {
- where.And("issue.project = ?", *v)
- }
- if v := find.ProjectIDs; v != nil {
- where.And("issue.project = ANY(?)", *v)
- }
+
if v := find.CreatorID; v != nil {
where.And("issue.creator = ?", *v)
}
diff --git a/backend/store/issue_comment.go b/backend/store/issue_comment.go
index fd3f302ff3..fd606cce68 100644
--- a/backend/store/issue_comment.go
+++ b/backend/store/issue_comment.go
@@ -13,6 +13,7 @@ import (
)
type IssueCommentMessage struct {
+ ProjectID string
ResourceID string
CreatedAt time.Time
UpdatedAt time.Time
@@ -22,6 +23,7 @@ type IssueCommentMessage struct {
}
type FindIssueCommentMessage struct {
+ ProjectID string
ResourceID *string
IssueUID *int
@@ -30,6 +32,7 @@ type FindIssueCommentMessage struct {
}
type UpdateIssueCommentMessage struct {
+ ProjectID string
ResourceID string
Comment *string
@@ -52,6 +55,7 @@ func (s *Store) GetIssueComment(ctx context.Context, find *FindIssueCommentMessa
func (s *Store) ListIssueComment(ctx context.Context, find *FindIssueCommentMessage) ([]*IssueCommentMessage, error) {
q := qb.Q().Space(`
SELECT
+ project,
resource_id,
creator,
created_at,
@@ -60,8 +64,8 @@ func (s *Store) ListIssueComment(ctx context.Context, find *FindIssueCommentMess
payload
FROM
issue_comment
- WHERE TRUE
- `)
+ WHERE project = ?
+ `, find.ProjectID)
if v := find.ResourceID; v != nil {
q.And("resource_id = ?", *v)
@@ -96,6 +100,7 @@ func (s *Store) ListIssueComment(ctx context.Context, find *FindIssueCommentMess
}
var p []byte
if err := rows.Scan(
+ &ic.ProjectID,
&ic.ResourceID,
&ic.CreatorEmail,
&ic.CreatedAt,
@@ -127,6 +132,7 @@ func (s *Store) CreateIssueComments(ctx context.Context, creator string, creates
}
// Prepare all payloads.
+ projectIDs := make([]string, 0, len(creates))
issueIDs := make([]int, 0, len(creates))
payloads := make([][]byte, 0, len(creates))
for _, create := range creates {
@@ -134,15 +140,16 @@ func (s *Store) CreateIssueComments(ctx context.Context, creator string, creates
if err != nil {
return nil, errors.Wrapf(err, "failed to marshal payload")
}
+ projectIDs = append(projectIDs, create.ProjectID)
issueIDs = append(issueIDs, create.IssueUID)
payloads = append(payloads, payload)
}
// Use UNNEST to insert all comments in one query.
q := qb.Q().Space(`
- INSERT INTO issue_comment (creator, issue_id, payload)
- SELECT ?, unnest(?::INT[]), unnest(?::JSONB[])
- `, creator, issueIDs, payloads)
+ INSERT INTO issue_comment (creator, project, issue_id, payload)
+ SELECT ?, unnest(?::TEXT[]), unnest(?::INT[]), unnest(?::JSONB[])
+ `, creator, projectIDs, issueIDs, payloads)
// For single comment, use RETURNING to get the created comment details.
if len(creates) == 1 {
@@ -180,7 +187,7 @@ func (s *Store) UpdateIssueComment(ctx context.Context, patch *UpdateIssueCommen
q.Join(", ", "payload = payload || jsonb_build_object('comment',?::TEXT)", *v)
}
- q.Space("WHERE resource_id = ?", patch.ResourceID)
+ q.Space("WHERE project = ? AND resource_id = ?", patch.ProjectID, patch.ResourceID)
query, args, err := q.ToSQL()
if err != nil {