Skip to content

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

feat(comment): add the store-level thread surface and statement anchor (#21307)

boojack6d4e528d6bb1
diff --git a/backend/api/v1/issue_service.go b/backend/api/v1/issue_service.go
index 7d229c6603..c07dbbdaca 100644
--- a/backend/api/v1/issue_service.go
+++ b/backend/api/v1/issue_service.go
@@ -1245,8 +1245,12 @@ func (s *IssueService) ListIssueComments(ctx context.Context, req *connect.Reque
issueComments, err := s.store.ListIssueComment(ctx, &store.FindIssueCommentMessage{
ProjectID: projectID,
IssueUID: &issue.UID,
- Limit: &limitPlusOne,
- Offset: &offset.offset,
+ // The activity timeline holds events and root comments only. The v1
+ // message cannot represent a reply yet, and a reply must not consume
+ // a page slot; replies are read per thread through ParentIDs.
+ TopLevelOnly: true,
+ Limit: &limitPlusOne,
+ Offset: &offset.offset,
})
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to list issue comments, err: %v", err))
@@ -1370,6 +1374,9 @@ func (s *IssueService) UpdateIssueComment(ctx context.Context, req *connect.Requ
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to get issue comment: %v", err))
}
+ if issueComment == nil {
+ return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("issue comment not found"))
+ }
return connect.NewResponse(convertToIssueComment(req.Msg.Parent, issueComment)), nil
}
diff --git a/backend/api/v1/issue_service_test.go b/backend/api/v1/issue_service_test.go
index 0470905c71..90d0368ca1 100644
--- a/backend/api/v1/issue_service_test.go
+++ b/backend/api/v1/issue_service_test.go
@@ -63,6 +63,46 @@ func TestUpdateIssueCommentRejectsEmptyComment(t *testing.T) {
require.Equal(t, "keep me", comments[0].Payload.GetComment())
}
+// TestListIssueCommentsExcludesReplies pins the activity timeline to events
+// and root comments: the v1 message cannot represent a reply, so a reply must
+// neither render as a top-level row nor consume a page slot.
+func TestListIssueCommentsExcludesReplies(t *testing.T) {
+ ctx := issueServiceTestContext()
+ stores := setupIssueServiceTestStore(ctx, t)
+ service := newIssueServiceForTest(t, stores)
+ _, issue := createIssueServiceApprovalIssue(ctx, t, stores)
+ parent := common.FormatIssue(issue.ProjectID, issue.UID)
+
+ created, err := service.CreateIssueComment(ctx, connect.NewRequest(&v1pb.CreateIssueCommentRequest{
+ Parent: parent,
+ IssueComment: &v1pb.IssueComment{
+ Comment: "root",
+ },
+ }))
+ require.NoError(t, err)
+
+ _, _, rootID, err := common.GetProjectIDIssueUIDIssueCommentID(created.Msg.Name)
+ require.NoError(t, err)
+ _, err = stores.CreateIssueCommentReply(ctx, "users/[email protected]", &store.IssueCommentMessage{
+ ProjectID: issue.ProjectID,
+ IssueUID: issue.UID,
+ ParentID: &rootID,
+ Payload: &storepb.IssueCommentPayload{Comment: "reply body"},
+ })
+ require.NoError(t, err)
+
+ resp, err := service.ListIssueComments(ctx, connect.NewRequest(&v1pb.ListIssueCommentsRequest{
+ Parent: parent,
+ }))
+ require.NoError(t, err)
+ names := make([]string, 0, len(resp.Msg.IssueComments))
+ for _, comment := range resp.Msg.IssueComments {
+ require.NotEqual(t, "reply body", comment.Comment, "replies must not appear in the activity timeline")
+ names = append(names, comment.Name)
+ }
+ require.Contains(t, names, created.Msg.Name, "the thread root stays in the timeline")
+}
+
func TestDraftLabelUpdateConflictsWithConcurrentSubmission(t *testing.T) {
ctx := issueServiceTestContext()
stores := setupIssueServiceTestStore(ctx, t)
diff --git a/backend/generated-go/store/issue_comment.pb.go b/backend/generated-go/store/issue_comment.pb.go
index a30e64a36a..c30fcedb46 100644
--- a/backend/generated-go/store/issue_comment.pb.go
+++ b/backend/generated-go/store/issue_comment.pb.go
@@ -30,9 +30,12 @@ type IssueCommentPayload struct {
// *IssueCommentPayload_IssueUpdate_
// *IssueCommentPayload_PlanUpdate_
// *IssueCommentPayload_ReviewSubmission_
- Event isIssueCommentPayload_Event `protobuf_oneof:"event"`
- unknownFields protoimpl.UnknownFields
- sizeCache protoimpl.SizeCache
+ Event isIssueCommentPayload_Event `protobuf_oneof:"event"`
+ // The statement context an inline comment references. Set at creation and
+ // immutable afterward; never set together with an event.
+ StatementAnchor *IssueCommentPayload_StatementAnchor `protobuf:"bytes,9,opt,name=statement_anchor,json=statementAnchor,proto3" json:"statement_anchor,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
}
func (x *IssueCommentPayload) Reset() {
@@ -115,6 +118,13 @@ func (x *IssueCommentPayload) GetReviewSubmission() *IssueCommentPayload_ReviewS
return nil
}
+func (x *IssueCommentPayload) GetStatementAnchor() *IssueCommentPayload_StatementAnchor {
+ if x != nil {
+ return x.StatementAnchor
+ }
+ return nil
+}
+
type isIssueCommentPayload_Event interface {
isIssueCommentPayload_Event()
}
@@ -380,18 +390,99 @@ func (x *IssueCommentPayload_PlanUpdate) GetToSpecs() []*PlanConfig_Spec {
return nil
}
+// StatementAnchor records the anchored statement revision and range.
+// The SQL excerpt and current/changed/unavailable state are computed on
+// read against the anchored sheet and the current plan, not stored.
+type IssueCommentPayload_StatementAnchor struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // UUID of the anchored plan spec (PlanConfig.Spec.id); may no longer
+ // resolve after the spec is deleted from the plan.
+ SpecId string `protobuf:"bytes,1,opt,name=spec_id,json=specId,proto3" json:"spec_id,omitempty"`
+ // SHA256 hex of the anchored sheet revision.
+ SheetSha256 string `protobuf:"bytes,2,opt,name=sheet_sha256,json=sheetSha256,proto3" json:"sheet_sha256,omitempty"`
+ // The anchored range. When both columns are 0, the anchor spans whole
+ // lines from start_position.line to end_position.line inclusive —
+ // overriding Position's "column 0 means unknown" convention. When both
+ // columns are set, start_position is inclusive and end_position is
+ // exclusive, in one-based lines and code-point columns (see Position).
+ // Setting exactly one column to 0 is invalid.
+ StartPosition *Position `protobuf:"bytes,3,opt,name=start_position,json=startPosition,proto3" json:"start_position,omitempty"`
+ EndPosition *Position `protobuf:"bytes,4,opt,name=end_position,json=endPosition,proto3" json:"end_position,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *IssueCommentPayload_StatementAnchor) Reset() {
+ *x = IssueCommentPayload_StatementAnchor{}
+ mi := &file_store_issue_comment_proto_msgTypes[5]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *IssueCommentPayload_StatementAnchor) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*IssueCommentPayload_StatementAnchor) ProtoMessage() {}
+
+func (x *IssueCommentPayload_StatementAnchor) ProtoReflect() protoreflect.Message {
+ mi := &file_store_issue_comment_proto_msgTypes[5]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use IssueCommentPayload_StatementAnchor.ProtoReflect.Descriptor instead.
+func (*IssueCommentPayload_StatementAnchor) Descriptor() ([]byte, []int) {
+ return file_store_issue_comment_proto_rawDescGZIP(), []int{0, 4}
+}
+
+func (x *IssueCommentPayload_StatementAnchor) GetSpecId() string {
+ if x != nil {
+ return x.SpecId
+ }
+ return ""
+}
+
+func (x *IssueCommentPayload_StatementAnchor) GetSheetSha256() string {
+ if x != nil {
+ return x.SheetSha256
+ }
+ return ""
+}
+
+func (x *IssueCommentPayload_StatementAnchor) GetStartPosition() *Position {
+ if x != nil {
+ return x.StartPosition
+ }
+ return nil
+}
+
+func (x *IssueCommentPayload_StatementAnchor) GetEndPosition() *Position {
+ if x != nil {
+ return x.EndPosition
+ }
+ return nil
+}
+
var File_store_issue_comment_proto protoreflect.FileDescriptor
const file_store_issue_comment_proto_rawDesc = "" +
"\n" +
- "\x19store/issue_comment.proto\x12\x0ebytebase.store\x1a\x14store/approval.proto\x1a\x11store/issue.proto\x1a\x10store/plan.proto\"\xe5\b\n" +
+ "\x19store/issue_comment.proto\x12\x0ebytebase.store\x1a\x14store/approval.proto\x1a\x12store/common.proto\x1a\x11store/issue.proto\x1a\x10store/plan.proto\"\x93\v\n" +
"\x13IssueCommentPayload\x12\x18\n" +
"\acomment\x18\x01 \x01(\tR\acomment\x12J\n" +
"\bapproval\x18\x02 \x01(\v2,.bytebase.store.IssueCommentPayload.ApprovalH\x00R\bapproval\x12T\n" +
"\fissue_update\x18\x03 \x01(\v2/.bytebase.store.IssueCommentPayload.IssueUpdateH\x00R\vissueUpdate\x12Q\n" +
"\vplan_update\x18\a \x01(\v2..bytebase.store.IssueCommentPayload.PlanUpdateH\x00R\n" +
"planUpdate\x12c\n" +
- "\x11review_submission\x18\b \x01(\v24.bytebase.store.IssueCommentPayload.ReviewSubmissionH\x00R\x10reviewSubmission\x1aX\n" +
+ "\x11review_submission\x18\b \x01(\v24.bytebase.store.IssueCommentPayload.ReviewSubmissionH\x00R\x10reviewSubmission\x12^\n" +
+ "\x10statement_anchor\x18\t \x01(\v23.bytebase.store.IssueCommentPayload.StatementAnchorR\x0fstatementAnchor\x1aX\n" +
"\bApproval\x12L\n" +
"\x06status\x18\x01 \x01(\x0e24.bytebase.store.IssuePayloadApproval.Approver.StatusR\x06status\x1a\xd1\x03\n" +
"\vIssueUpdate\x12\"\n" +
@@ -418,7 +509,12 @@ const file_store_issue_comment_proto_rawDesc = "" +
"PlanUpdate\x12>\n" +
"\n" +
"from_specs\x18\x01 \x03(\v2\x1f.bytebase.store.PlanConfig.SpecR\tfromSpecs\x12:\n" +
- "\bto_specs\x18\x02 \x03(\v2\x1f.bytebase.store.PlanConfig.SpecR\atoSpecsB\a\n" +
+ "\bto_specs\x18\x02 \x03(\v2\x1f.bytebase.store.PlanConfig.SpecR\atoSpecs\x1a\xcb\x01\n" +
+ "\x0fStatementAnchor\x12\x17\n" +
+ "\aspec_id\x18\x01 \x01(\tR\x06specId\x12!\n" +
+ "\fsheet_sha256\x18\x02 \x01(\tR\vsheetSha256\x12?\n" +
+ "\x0estart_position\x18\x03 \x01(\v2\x18.bytebase.store.PositionR\rstartPosition\x12;\n" +
+ "\fend_position\x18\x04 \x01(\v2\x18.bytebase.store.PositionR\vendPositionB\a\n" +
"\x05eventJ\x04\b\x04\x10\aB\x94\x01\n" +
"\x12com.bytebase.storeB\x11IssueCommentProtoP\x01Z\x12generated-go/store\xa2\x02\x03BSX\xaa\x02\x0eBytebase.Store\xca\x02\x0eBytebase\\Store\xe2\x02\x1aBytebase\\Store\\GPBMetadata\xea\x02\x0fBytebase::Storeb\x06proto3"
@@ -434,32 +530,37 @@ func file_store_issue_comment_proto_rawDescGZIP() []byte {
return file_store_issue_comment_proto_rawDescData
}
-var file_store_issue_comment_proto_msgTypes = make([]protoimpl.MessageInfo, 5)
+var file_store_issue_comment_proto_msgTypes = make([]protoimpl.MessageInfo, 6)
var file_store_issue_comment_proto_goTypes = []any{
(*IssueCommentPayload)(nil), // 0: bytebase.store.IssueCommentPayload
(*IssueCommentPayload_Approval)(nil), // 1: bytebase.store.IssueCommentPayload.Approval
(*IssueCommentPayload_IssueUpdate)(nil), // 2: bytebase.store.IssueCommentPayload.IssueUpdate
(*IssueCommentPayload_ReviewSubmission)(nil), // 3: bytebase.store.IssueCommentPayload.ReviewSubmission
(*IssueCommentPayload_PlanUpdate)(nil), // 4: bytebase.store.IssueCommentPayload.PlanUpdate
- (IssuePayloadApproval_Approver_Status)(0), // 5: bytebase.store.IssuePayloadApproval.Approver.Status
- (Issue_Status)(0), // 6: bytebase.store.Issue.Status
- (*PlanConfig_Spec)(nil), // 7: bytebase.store.PlanConfig.Spec
+ (*IssueCommentPayload_StatementAnchor)(nil), // 5: bytebase.store.IssueCommentPayload.StatementAnchor
+ (IssuePayloadApproval_Approver_Status)(0), // 6: bytebase.store.IssuePayloadApproval.Approver.Status
+ (Issue_Status)(0), // 7: bytebase.store.Issue.Status
+ (*PlanConfig_Spec)(nil), // 8: bytebase.store.PlanConfig.Spec
+ (*Position)(nil), // 9: bytebase.store.Position
}
var file_store_issue_comment_proto_depIdxs = []int32{
- 1, // 0: bytebase.store.IssueCommentPayload.approval:type_name -> bytebase.store.IssueCommentPayload.Approval
- 2, // 1: bytebase.store.IssueCommentPayload.issue_update:type_name -> bytebase.store.IssueCommentPayload.IssueUpdate
- 4, // 2: bytebase.store.IssueCommentPayload.plan_update:type_name -> bytebase.store.IssueCommentPayload.PlanUpdate
- 3, // 3: bytebase.store.IssueCommentPayload.review_submission:type_name -> bytebase.store.IssueCommentPayload.ReviewSubmission
- 5, // 4: bytebase.store.IssueCommentPayload.Approval.status:type_name -> bytebase.store.IssuePayloadApproval.Approver.Status
- 6, // 5: bytebase.store.IssueCommentPayload.IssueUpdate.from_status:type_name -> bytebase.store.Issue.Status
- 6, // 6: bytebase.store.IssueCommentPayload.IssueUpdate.to_status:type_name -> bytebase.store.Issue.Status
- 7, // 7: bytebase.store.IssueCommentPayload.PlanUpdate.from_specs:type_name -> bytebase.store.PlanConfig.Spec
- 7, // 8: bytebase.store.IssueCommentPayload.PlanUpdate.to_specs:type_name -> bytebase.store.PlanConfig.Spec
- 9, // [9:9] is the sub-list for method output_type
- 9, // [9:9] is the sub-list for method input_type
- 9, // [9:9] is the sub-list for extension type_name
- 9, // [9:9] is the sub-list for extension extendee
- 0, // [0:9] is the sub-list for field type_name
+ 1, // 0: bytebase.store.IssueCommentPayload.approval:type_name -> bytebase.store.IssueCommentPayload.Approval
+ 2, // 1: bytebase.store.IssueCommentPayload.issue_update:type_name -> bytebase.store.IssueCommentPayload.IssueUpdate
+ 4, // 2: bytebase.store.IssueCommentPayload.plan_update:type_name -> bytebase.store.IssueCommentPayload.PlanUpdate
+ 3, // 3: bytebase.store.IssueCommentPayload.review_submission:type_name -> bytebase.store.IssueCommentPayload.ReviewSubmission
+ 5, // 4: bytebase.store.IssueCommentPayload.statement_anchor:type_name -> bytebase.store.IssueCommentPayload.StatementAnchor
+ 6, // 5: bytebase.store.IssueCommentPayload.Approval.status:type_name -> bytebase.store.IssuePayloadApproval.Approver.Status
+ 7, // 6: bytebase.store.IssueCommentPayload.IssueUpdate.from_status:type_name -> bytebase.store.Issue.Status
+ 7, // 7: bytebase.store.IssueCommentPayload.IssueUpdate.to_status:type_name -> bytebase.store.Issue.Status
+ 8, // 8: bytebase.store.IssueCommentPayload.PlanUpdate.from_specs:type_name -> bytebase.store.PlanConfig.Spec
+ 8, // 9: bytebase.store.IssueCommentPayload.PlanUpdate.to_specs:type_name -> bytebase.store.PlanConfig.Spec
+ 9, // 10: bytebase.store.IssueCommentPayload.StatementAnchor.start_position:type_name -> bytebase.store.Position
+ 9, // 11: bytebase.store.IssueCommentPayload.StatementAnchor.end_position:type_name -> bytebase.store.Position
+ 12, // [12:12] is the sub-list for method output_type
+ 12, // [12:12] is the sub-list for method input_type
+ 12, // [12:12] is the sub-list for extension type_name
+ 12, // [12:12] is the sub-list for extension extendee
+ 0, // [0:12] is the sub-list for field type_name
}
func init() { file_store_issue_comment_proto_init() }
@@ -468,6 +569,7 @@ func file_store_issue_comment_proto_init() {
return
}
file_store_approval_proto_init()
+ file_store_common_proto_init()
file_store_issue_proto_init()
file_store_plan_proto_init()
file_store_issue_comment_proto_msgTypes[0].OneofWrappers = []any{
@@ -483,7 +585,7 @@ func file_store_issue_comment_proto_init() {
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_store_issue_comment_proto_rawDesc), len(file_store_issue_comment_proto_rawDesc)),
NumEnums: 0,
- NumMessages: 5,
+ NumMessages: 6,
NumExtensions: 0,
NumServices: 0,
},
diff --git a/backend/generated-go/store/issue_comment_equal.pb.go b/backend/generated-go/store/issue_comment_equal.pb.go
index ee81fd40ca..ae1dbfdc8c 100644
--- a/backend/generated-go/store/issue_comment_equal.pb.go
+++ b/backend/generated-go/store/issue_comment_equal.pb.go
@@ -96,6 +96,28 @@ func (x *IssueCommentPayload_PlanUpdate) Equal(y *IssueCommentPayload_PlanUpdate
return true
}
+func (x *IssueCommentPayload_StatementAnchor) Equal(y *IssueCommentPayload_StatementAnchor) bool {
+ if x == y {
+ return true
+ }
+ if x == nil || y == nil {
+ return x == nil && y == nil
+ }
+ if x.SpecId != y.SpecId {
+ return false
+ }
+ if x.SheetSha256 != y.SheetSha256 {
+ return false
+ }
+ if !x.StartPosition.Equal(y.StartPosition) {
+ return false
+ }
+ if !x.EndPosition.Equal(y.EndPosition) {
+ return false
+ }
+ return true
+}
+
func (x *IssueCommentPayload) Equal(y *IssueCommentPayload) bool {
if x == y {
return true
@@ -118,5 +140,8 @@ func (x *IssueCommentPayload) Equal(y *IssueCommentPayload) bool {
if !x.GetReviewSubmission().Equal(y.GetReviewSubmission()) {
return false
}
+ if !x.StatementAnchor.Equal(y.StatementAnchor) {
+ return false
+ }
return true
}
diff --git a/backend/store/issue_comment.go b/backend/store/issue_comment.go
index d477d621ec..178d7a057c 100644
--- a/backend/store/issue_comment.go
+++ b/backend/store/issue_comment.go
@@ -2,6 +2,9 @@ package store
import (
"context"
+ "database/sql"
+ "encoding/hex"
+ "strings"
"time"
"github.com/pkg/errors"
@@ -12,6 +15,15 @@ import (
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
)
+// ThreadState is the resolvable state carried by a thread's root comment.
+// Events and replies have no state (NULL thread_state).
+type ThreadState string
+
+const (
+ ThreadStateOpen ThreadState = "OPEN"
+ ThreadStateResolved ThreadState = "RESOLVED"
+)
+
type IssueCommentMessage struct {
ProjectID string
ResourceID string
@@ -20,12 +32,24 @@ type IssueCommentMessage struct {
IssueUID int64
Payload *storepb.IssueCommentPayload
CreatorEmail string
+ // ParentID names the thread's root comment on a reply; nil on root
+ // comments and events.
+ ParentID *string
+ // ThreadState is set on thread roots; nil on replies and events.
+ ThreadState *ThreadState
}
type FindIssueCommentMessage struct {
ProjectID string
ResourceID *string
IssueUID *int64
+ // ParentIDs limits the result to replies of these root comments.
+ ParentIDs *[]string
+ // TopLevelOnly limits the result to events and root comments — the
+ // activity timeline entries.
+ TopLevelOnly bool
+ // ThreadState limits the result to thread roots in this state.
+ ThreadState *ThreadState
Limit *int
Offset *int
@@ -36,6 +60,65 @@ type UpdateIssueCommentMessage struct {
ResourceID string
Comment *string
+ // ThreadState resolves or reopens a thread; the target must be a root
+ // comment. Replying never changes it.
+ ThreadState *ThreadState
+}
+
+func (s ThreadState) valid() bool {
+ return s == ThreadStateOpen || s == ThreadStateResolved
+}
+
+// threadStatePredicate appends a literal thread_state predicate. The literal
+// (never a bind parameter) is what lets the planner match the
+// idx_issue_comment_open_thread partial index; valid() makes the
+// interpolation safe.
+func threadStatePredicate(q *qb.Query, state ThreadState) error {
+ if !state.valid() {
+ return common.Errorf(common.Invalid, "invalid thread state %q", state)
+ }
+ q.And("thread_state = '" + string(state) + "'")
+ return nil
+}
+
+// validateIssueCommentPayload pins the statement anchor invariants shared by
+// both writers. The anchor is write-once, so a malformed one is permanent.
+func validateIssueCommentPayload(payload *storepb.IssueCommentPayload) error {
+ anchor := payload.GetStatementAnchor()
+ if anchor == nil {
+ return nil
+ }
+ if payload.GetEvent() != nil {
+ return common.Errorf(common.Invalid, "an event cannot carry a statement anchor")
+ }
+ if anchor.SpecId == "" {
+ return common.Errorf(common.Invalid, "a statement anchor requires a spec id")
+ }
+ if len(anchor.SheetSha256) != 64 || strings.ToLower(anchor.SheetSha256) != anchor.SheetSha256 {
+ return common.Errorf(common.Invalid, "a statement anchor requires the sheet sha256 as 64 lowercase hex characters")
+ }
+ if _, err := hex.DecodeString(anchor.SheetSha256); err != nil {
+ return common.Errorf(common.Invalid, "a statement anchor requires the sheet sha256 as 64 lowercase hex characters")
+ }
+ start, end := anchor.StartPosition, anchor.EndPosition
+ if start == nil || end == nil {
+ return common.Errorf(common.Invalid, "a statement anchor requires start and end positions")
+ }
+ switch {
+ case start.Column == 0 && end.Column == 0:
+ // Whole-line anchor; the end line is inclusive.
+ if start.Line < 1 || end.Line < start.Line {
+ return common.Errorf(common.Invalid, "invalid whole-line anchor range %d-%d", start.Line, end.Line)
+ }
+ case start.Column > 0 && end.Column > 0:
+ // Code-point range; the end position is exclusive.
+ if start.Line < 1 || end.Line < start.Line || (end.Line == start.Line && end.Column <= start.Column) {
+ return common.Errorf(common.Invalid, "invalid anchor range %d:%d-%d:%d", start.Line, start.Column, end.Line, end.Column)
+ }
+ default:
+ return common.Errorf(common.Invalid, "an anchor range must set both columns or neither")
+ }
+ return nil
}
func (s *Store) GetIssueComment(ctx context.Context, find *FindIssueCommentMessage) (*IssueCommentMessage, error) {
@@ -61,7 +144,9 @@ func (s *Store) ListIssueComment(ctx context.Context, find *FindIssueCommentMess
created_at,
updated_at,
issue_id,
- payload
+ payload,
+ parent_id,
+ thread_state
FROM
issue_comment
WHERE project = ?
@@ -73,6 +158,17 @@ func (s *Store) ListIssueComment(ctx context.Context, find *FindIssueCommentMess
if v := find.IssueUID; v != nil {
q.And("issue_id = ?", *v)
}
+ if v := find.ParentIDs; v != nil {
+ q.And("parent_id = ANY(?)", *v)
+ }
+ if find.TopLevelOnly {
+ q.And("parent_id IS NULL")
+ }
+ if v := find.ThreadState; v != nil {
+ if err := threadStatePredicate(q, *v); err != nil {
+ return nil, err
+ }
+ }
// resource_id is the primary key. created_at alone would not be total —
// it defaults to now(), the transaction timestamp — so CreateIssueComments
@@ -103,6 +199,7 @@ func (s *Store) ListIssueComment(ctx context.Context, find *FindIssueCommentMess
Payload: &storepb.IssueCommentPayload{},
}
var p []byte
+ var parentID, threadState sql.NullString
if err := rows.Scan(
&ic.ProjectID,
&ic.ResourceID,
@@ -111,9 +208,18 @@ func (s *Store) ListIssueComment(ctx context.Context, find *FindIssueCommentMess
&ic.UpdatedAt,
&ic.IssueUID,
&p,
+ &parentID,
+ &threadState,
); err != nil {
return nil, errors.Wrapf(err, "failed to scan")
}
+ if parentID.Valid {
+ ic.ParentID = &parentID.String
+ }
+ if threadState.Valid {
+ state := ThreadState(threadState.String)
+ ic.ThreadState = &state
+ }
if err := common.ProtojsonUnmarshaler.Unmarshal(p, ic.Payload); err != nil {
return nil, errors.Wrapf(err, "failed to unmarshal")
}
@@ -128,7 +234,7 @@ func (s *Store) ListIssueComment(ctx context.Context, find *FindIssueCommentMess
}
// CreateIssueComments creates one or more root comments or events.
-// Reply creation is not supported by this writer yet.
+// Replies go through CreateIssueCommentReply.
// For a single comment, it returns the created comment with UID, CreatedAt, and UpdatedAt filled in.
// For multiple comments, it performs a batch insert and returns nil.
func (s *Store) CreateIssueComments(ctx context.Context, creator string, creates ...*IssueCommentMessage) (*IssueCommentMessage, error) {
@@ -142,6 +248,15 @@ func (s *Store) CreateIssueComments(ctx context.Context, creator string, creates
payloads := make([][]byte, 0, len(creates))
threadRoots := make([]bool, 0, len(creates))
for _, create := range creates {
+ if create.ParentID != nil {
+ return nil, common.Errorf(common.Invalid, "replies must be created through CreateIssueCommentReply")
+ }
+ if create.ThreadState != nil {
+ return nil, common.Errorf(common.Invalid, "thread state is derived on create; a new root starts OPEN")
+ }
+ if err := validateIssueCommentPayload(create.Payload); err != nil {
+ return nil, err
+ }
payload, err := protojson.Marshal(create.Payload)
if err != nil {
return nil, errors.Wrapf(err, "failed to marshal payload")
@@ -149,8 +264,7 @@ func (s *Store) CreateIssueComments(ctx context.Context, creator string, creates
projectIDs = append(projectIDs, create.ProjectID)
issueIDs = append(issueIDs, create.IssueUID)
payloads = append(payloads, payload)
- // Current event-less writes are roots. Event and hybrid rows remain
- // outside threads; replies will additionally require parent_id handling.
+ // Event-less writes are roots. Event and hybrid rows remain outside threads.
threadRoots = append(threadRoots, create.Payload.GetEvent() == nil)
}
@@ -182,6 +296,10 @@ func (s *Store) CreateIssueComments(ctx context.Context, creator string, creates
if err := s.GetDB().QueryRowContext(ctx, query, args...).Scan(&create.ResourceID, &create.CreatedAt, &create.UpdatedAt); err != nil {
return nil, errors.Wrapf(err, "failed to insert")
}
+ if threadRoots[0] {
+ state := ThreadStateOpen
+ create.ThreadState = &state
+ }
create.CreatorEmail = creator
return create, nil
}
@@ -199,22 +317,131 @@ func (s *Store) CreateIssueComments(ctx context.Context, creator string, creates
return nil, nil
}
+// CreateIssueCommentReply creates a reply in the thread rooted at
+// create.ParentID and returns it with ResourceID, CreatedAt, and UpdatedAt
+// filled in. The insert-select pins every reply invariant in one statement:
+// the parent is a root comment (thread_state set, so never an event or a
+// reply) in the same project and issue, and replying never changes the
+// thread state. Like CreateIssueComments, it requires only the referenced
+// rows to exist, regardless of project lifecycle.
+func (s *Store) CreateIssueCommentReply(ctx context.Context, creator string, create *IssueCommentMessage) (*IssueCommentMessage, error) {
+ if create.ParentID == nil {
+ return nil, common.Errorf(common.Invalid, "a reply must name its thread root")
+ }
+ if create.ThreadState != nil {
+ return nil, common.Errorf(common.Invalid, "replies carry no thread state")
+ }
+ if create.Payload.GetEvent() != nil {
+ return nil, common.Errorf(common.Invalid, "a reply cannot carry an event")
+ }
+ if err := validateIssueCommentPayload(create.Payload); err != nil {
+ return nil, err
+ }
+ payload, err := protojson.Marshal(create.Payload)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to marshal payload")
+ }
+
+ q := qb.Q().Space(`
+ INSERT INTO issue_comment (creator, project, issue_id, payload, parent_id)
+ SELECT ?, root.project, root.issue_id, ?, root.resource_id
+ FROM issue_comment AS root
+ WHERE root.project = ? AND root.resource_id = ? AND root.issue_id = ?
+ AND root.parent_id IS NULL AND root.thread_state IS NOT NULL
+ RETURNING resource_id, created_at, updated_at
+ `, creator, payload, create.ProjectID, *create.ParentID, create.IssueUID)
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to build sql")
+ }
+ if err := s.GetDB().QueryRowContext(ctx, query, args...).Scan(&create.ResourceID, &create.CreatedAt, &create.UpdatedAt); err != nil {
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, s.replyTargetError(ctx, create)
+ }
+ return nil, errors.Wrapf(err, "failed to insert reply")
+ }
+ create.CreatorEmail = creator
+ return create, nil
+}
+
+// replyTargetError explains why the reply insert matched no thread root.
+func (s *Store) replyTargetError(ctx context.Context, create *IssueCommentMessage) error {
+ var issueUID int64
+ var parentID, threadState sql.NullString
+ err := s.GetDB().QueryRowContext(ctx,
+ "SELECT issue_id, parent_id, thread_state FROM issue_comment WHERE project = $1 AND resource_id = $2",
+ create.ProjectID, *create.ParentID).Scan(&issueUID, &parentID, &threadState)
+ if errors.Is(err, sql.ErrNoRows) {
+ return common.Errorf(common.NotFound, "comment %s not found in project %s", *create.ParentID, create.ProjectID)
+ }
+ if err != nil {
+ return errors.Wrapf(err, "failed to read reply target %s", *create.ParentID)
+ }
+ switch {
+ case issueUID != create.IssueUID:
+ return common.Errorf(common.NotFound, "comment %s not found in issue %d", *create.ParentID, create.IssueUID)
+ case parentID.Valid:
+ return common.Errorf(common.Invalid, "comment %s is a reply; a reply must name the thread root", *create.ParentID)
+ case threadState.Valid:
+ // The row satisfies every insert predicate on re-read, so a
+ // concurrent write landed between the insert and this diagnosis.
+ return common.Errorf(common.Conflict, "comment %s changed concurrently; retry the reply", *create.ParentID)
+ default:
+ // Events, hybrid comment+event rows, and unclassified legacy rows
+ // all carry NULL thread_state.
+ return common.Errorf(common.Invalid, "comment %s is not a thread root and cannot be replied to", *create.ParentID)
+ }
+}
+
func (s *Store) UpdateIssueComment(ctx context.Context, patch *UpdateIssueCommentMessage) error {
- q := qb.Q().Space("UPDATE issue_comment SET updated_at = ?", time.Now())
+ if patch.Comment == nil && patch.ThreadState == nil {
+ return common.Errorf(common.Invalid, "no fields to update")
+ }
+ set := qb.Q()
if v := patch.Comment; v != nil {
- q.Join(", ", "payload = payload || jsonb_build_object('comment',?::TEXT)", *v)
+ // updated_at marks content edits; a thread state change alone must
+ // not make the comment render as edited.
+ set.Comma("updated_at = ?", time.Now())
+ set.Comma("payload = payload || jsonb_build_object('comment',?::TEXT)", *v)
+ }
+ if v := patch.ThreadState; v != nil {
+ if !v.valid() {
+ return common.Errorf(common.Invalid, "invalid thread state %q", *v)
+ }
+ set.Comma("thread_state = ?", string(*v))
}
+ q := qb.Q().Space("UPDATE issue_comment SET ?", set)
q.Space("WHERE project = ? AND resource_id = ?", patch.ProjectID, patch.ResourceID)
+ // Only thread roots carry a state; events and replies must keep NULL.
+ if patch.ThreadState != nil {
+ q.And("thread_state IS NOT NULL")
+ }
+ // Text edits apply to rows that already render text: roots, replies, and
+ // hybrid event+comment rows — never to pure events.
+ if patch.Comment != nil {
+ q.And("(payload ?? 'comment' OR thread_state IS NOT NULL OR parent_id IS NOT NULL)")
+ }
query, args, err := q.ToSQL()
if err != nil {
return errors.Wrapf(err, "failed to build sql")
}
- if _, err := s.GetDB().ExecContext(ctx, query, args...); err != nil {
+ result, err := s.GetDB().ExecContext(ctx, query, args...)
+ if err != nil {
return errors.Wrapf(err, "failed to update issue comment")
}
+ rows, err := result.RowsAffected()
+ if err != nil {
+ return errors.Wrapf(err, "failed to get affected rows")
+ }
+ if rows == 0 {
+ if patch.ThreadState != nil {
+ return common.Errorf(common.NotFound, "comment %s in project %s is missing or not a thread root; nothing was updated", patch.ResourceID, patch.ProjectID)
+ }
+ return common.Errorf(common.NotFound, "comment %s in project %s is missing or a pure event; nothing was updated", patch.ResourceID, patch.ProjectID)
+ }
return nil
}
diff --git a/backend/store/issue_comment_thread_test.go b/backend/store/issue_comment_thread_test.go
new file mode 100644
index 0000000000..0adcdac368
--- /dev/null
+++ b/backend/store/issue_comment_thread_test.go
@@ -0,0 +1,376 @@
+package store_test
+
+import (
+ "context"
+ "fmt"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/bytebase/bytebase/backend/common"
+ "github.com/bytebase/bytebase/backend/common/testcontainer"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ "github.com/bytebase/bytebase/backend/migrator"
+ "github.com/bytebase/bytebase/backend/store"
+
+ _ "github.com/bytebase/bytebase/backend/plugin/db/pg"
+)
+
+// TestIssueCommentThreads covers the store-level thread surface: reply
+// creation with its root invariants, resolve/reopen on the root only, the
+// timeline and reply list filters, and statement anchor round-trips.
+func TestIssueCommentThreads(t *testing.T) {
+ const (
+ workspaceID = "thread-ws"
+ projectID = "thread-p"
+ otherProject = "thread-p2"
+ issueUID = int64(101)
+ otherIssue = int64(102)
+ creator = "users/[email protected]"
+ )
+
+ ctx := context.Background()
+ container := testcontainer.GetTestPgContainer(ctx, t)
+ t.Cleanup(func() { container.Close(ctx) })
+ db := container.GetDB()
+ require.NoError(t, migrator.MigrateSchema(ctx, db))
+
+ _, err := db.ExecContext(ctx,
+ `INSERT INTO workspace (resource_id) VALUES ($1)`, workspaceID)
+ require.NoError(t, err)
+ for _, p := range []string{projectID, otherProject} {
+ _, err = db.ExecContext(ctx,
+ `INSERT INTO project (resource_id, workspace, name) VALUES ($1, $2, $1)`,
+ p, workspaceID)
+ require.NoError(t, err)
+ }
+ for _, id := range []int64{issueUID, otherIssue} {
+ _, err = db.ExecContext(ctx, `
+ INSERT INTO issue (id, project, creator, name, status, type, description)
+ VALUES ($1, $2, $3, 'issue', 'OPEN', 'DATABASE_CHANGE', '')`,
+ id, projectID, creator)
+ require.NoError(t, err)
+ }
+
+ pgURL := fmt.Sprintf(
+ "host=%s port=%s user=postgres password=root-password database=postgres",
+ container.GetHost(), container.GetPort(),
+ )
+ stores, err := store.New(ctx, pgURL, false)
+ require.NoError(t, err)
+ t.Cleanup(func() { require.NoError(t, stores.Close()) })
+
+ anchor := &storepb.IssueCommentPayload_StatementAnchor{
+ SpecId: "spec-1",
+ SheetSha256: "0be1f01d6ee8e6f6c6a2ce9b418ba10ea9d16c9b9bfae5548b8fa0e26c04a5e0",
+ StartPosition: &storepb.Position{Line: 5},
+ EndPosition: &storepb.Position{Line: 8},
+ }
+ root, err := stores.CreateIssueComments(ctx, creator, &store.IssueCommentMessage{
+ ProjectID: projectID,
+ IssueUID: issueUID,
+ Payload: &storepb.IssueCommentPayload{Comment: "root", StatementAnchor: anchor},
+ })
+ require.NoError(t, err)
+ require.Nil(t, root.ParentID)
+ require.NotNil(t, root.ThreadState)
+ require.Equal(t, store.ThreadStateOpen, *root.ThreadState)
+
+ event, err := stores.CreateIssueComments(ctx, creator, &store.IssueCommentMessage{
+ ProjectID: projectID,
+ IssueUID: issueUID,
+ Payload: &storepb.IssueCommentPayload{
+ Event: &storepb.IssueCommentPayload_IssueUpdate_{
+ IssueUpdate: &storepb.IssueCommentPayload_IssueUpdate{},
+ },
+ },
+ })
+ require.NoError(t, err)
+ require.Nil(t, event.ThreadState, "events must stay outside threads")
+
+ // Reply invariants.
+ reply, err := stores.CreateIssueCommentReply(ctx, creator, &store.IssueCommentMessage{
+ ProjectID: projectID,
+ IssueUID: issueUID,
+ ParentID: &root.ResourceID,
+ Payload: &storepb.IssueCommentPayload{Comment: "re"},
+ })
+ require.NoError(t, err)
+ require.Equal(t, root.ResourceID, *reply.ParentID)
+ require.Nil(t, reply.ThreadState, "replies carry no thread state")
+ storedReply, err := stores.GetIssueComment(ctx, &store.FindIssueCommentMessage{
+ ProjectID: projectID,
+ ResourceID: &reply.ResourceID,
+ })
+ require.NoError(t, err)
+ require.Equal(t, root.ResourceID, *storedReply.ParentID, "the stored row must reference the root")
+ require.Nil(t, storedReply.ThreadState)
+
+ _, err = stores.CreateIssueCommentReply(ctx, creator, &store.IssueCommentMessage{
+ ProjectID: projectID,
+ IssueUID: issueUID,
+ ParentID: &reply.ResourceID,
+ Payload: &storepb.IssueCommentPayload{Comment: "nested"},
+ })
+ require.Equal(t, common.Invalid, common.ErrorCode(err), "a reply to a reply must be rejected, not re-rooted")
+
+ _, err = stores.CreateIssueCommentReply(ctx, creator, &store.IssueCommentMessage{
+ ProjectID: projectID,
+ IssueUID: issueUID,
+ ParentID: &event.ResourceID,
+ Payload: &storepb.IssueCommentPayload{Comment: "on event"},
+ })
+ require.Equal(t, common.Invalid, common.ErrorCode(err), "events cannot be replied to")
+
+ missing := "no-such-comment"
+ _, err = stores.CreateIssueCommentReply(ctx, creator, &store.IssueCommentMessage{
+ ProjectID: projectID,
+ IssueUID: issueUID,
+ ParentID: &missing,
+ Payload: &storepb.IssueCommentPayload{Comment: "orphan"},
+ })
+ require.Equal(t, common.NotFound, common.ErrorCode(err))
+
+ _, err = stores.CreateIssueCommentReply(ctx, creator, &store.IssueCommentMessage{
+ ProjectID: projectID,
+ IssueUID: otherIssue,
+ ParentID: &root.ResourceID,
+ Payload: &storepb.IssueCommentPayload{Comment: "cross-issue"},
+ })
+ require.Equal(t, common.NotFound, common.ErrorCode(err), "a reply must target a root in its own issue")
+
+ _, err = stores.CreateIssueCommentReply(ctx, creator, &store.IssueCommentMessage{
+ ProjectID: otherProject,
+ IssueUID: issueUID,
+ ParentID: &root.ResourceID,
+ Payload: &storepb.IssueCommentPayload{Comment: "cross-project"},
+ })
+ require.Equal(t, common.NotFound, common.ErrorCode(err), "a reply must target a root in its own project")
+
+ _, err = stores.CreateIssueCommentReply(ctx, creator, &store.IssueCommentMessage{
+ ProjectID: projectID,
+ IssueUID: issueUID,
+ ParentID: &root.ResourceID,
+ Payload: &storepb.IssueCommentPayload{
+ Event: &storepb.IssueCommentPayload_IssueUpdate_{
+ IssueUpdate: &storepb.IssueCommentPayload_IssueUpdate{},
+ },
+ },
+ })
+ require.Equal(t, common.Invalid, common.ErrorCode(err), "a reply cannot carry an event")
+
+ preset := store.ThreadStateResolved
+ _, err = stores.CreateIssueComments(ctx, creator, &store.IssueCommentMessage{
+ ProjectID: projectID,
+ IssueUID: issueUID,
+ Payload: &storepb.IssueCommentPayload{Comment: "preset"},
+ ThreadState: &preset,
+ })
+ require.Equal(t, common.Invalid, common.ErrorCode(err), "thread state is not settable on create")
+ _, err = stores.CreateIssueCommentReply(ctx, creator, &store.IssueCommentMessage{
+ ProjectID: projectID,
+ IssueUID: issueUID,
+ ParentID: &root.ResourceID,
+ ThreadState: &preset,
+ Payload: &storepb.IssueCommentPayload{Comment: "re"},
+ })
+ require.Equal(t, common.Invalid, common.ErrorCode(err), "thread state is not settable on a reply")
+
+ _, err = stores.CreateIssueComments(ctx, creator, &store.IssueCommentMessage{
+ ProjectID: projectID,
+ IssueUID: issueUID,
+ ParentID: &root.ResourceID,
+ Payload: &storepb.IssueCommentPayload{Comment: "misrouted"},
+ })
+ require.Equal(t, common.Invalid, common.ErrorCode(err), "CreateIssueComments must not create replies")
+
+ _, err = stores.CreateIssueComments(ctx, creator, &store.IssueCommentMessage{
+ ProjectID: projectID,
+ IssueUID: issueUID,
+ Payload: &storepb.IssueCommentPayload{
+ StatementAnchor: anchor,
+ Event: &storepb.IssueCommentPayload_IssueUpdate_{
+ IssueUpdate: &storepb.IssueCommentPayload_IssueUpdate{},
+ },
+ },
+ })
+ require.Equal(t, common.Invalid, common.ErrorCode(err), "an event cannot carry a statement anchor")
+
+ _, err = stores.CreateIssueComments(ctx, creator, &store.IssueCommentMessage{
+ ProjectID: projectID,
+ IssueUID: issueUID,
+ Payload: &storepb.IssueCommentPayload{
+ Comment: "bad anchor",
+ StatementAnchor: &storepb.IssueCommentPayload_StatementAnchor{
+ SpecId: "spec-1",
+ SheetSha256: anchor.SheetSha256,
+ StartPosition: &storepb.Position{Line: 5},
+ EndPosition: &storepb.Position{Line: 8, Column: 4},
+ },
+ },
+ })
+ require.Equal(t, common.Invalid, common.ErrorCode(err), "an anchor range must set both columns or neither")
+
+ // List filters.
+ uid := issueUID
+ all, err := stores.ListIssueComment(ctx, &store.FindIssueCommentMessage{
+ ProjectID: projectID,
+ IssueUID: &uid,
+ })
+ require.NoError(t, err)
+ require.Len(t, all, 3, "unfiltered list returns roots, events, and replies")
+
+ topLevel, err := stores.ListIssueComment(ctx, &store.FindIssueCommentMessage{
+ ProjectID: projectID,
+ IssueUID: &uid,
+ TopLevelOnly: true,
+ })
+ require.NoError(t, err)
+ require.Len(t, topLevel, 2, "timeline entries are the root and the event")
+ for _, comment := range topLevel {
+ require.Nil(t, comment.ParentID)
+ }
+
+ parentIDs := []string{root.ResourceID}
+ replies, err := stores.ListIssueComment(ctx, &store.FindIssueCommentMessage{
+ ProjectID: projectID,
+ ParentIDs: &parentIDs,
+ })
+ require.NoError(t, err)
+ require.Len(t, replies, 1)
+ require.Equal(t, reply.ResourceID, replies[0].ResourceID)
+
+ crossProjectReplies, err := stores.ListIssueComment(ctx, &store.FindIssueCommentMessage{
+ ProjectID: otherProject,
+ ParentIDs: &parentIDs,
+ })
+ require.NoError(t, err)
+ require.Empty(t, crossProjectReplies, "reply reads are project-scoped")
+
+ // Anchor round-trip through the jsonb payload.
+ fetched, err := stores.GetIssueComment(ctx, &store.FindIssueCommentMessage{
+ ProjectID: projectID,
+ ResourceID: &root.ResourceID,
+ })
+ require.NoError(t, err)
+ got := fetched.Payload.GetStatementAnchor()
+ require.NotNil(t, got)
+ require.Equal(t, anchor.SpecId, got.SpecId)
+ require.Equal(t, anchor.SheetSha256, got.SheetSha256)
+ require.Equal(t, anchor.StartPosition.Line, got.StartPosition.Line)
+ require.Equal(t, anchor.EndPosition.Line, got.EndPosition.Line)
+
+ // Resolve and reopen live on the root only.
+ resolved := store.ThreadStateResolved
+ require.NoError(t, stores.UpdateIssueComment(ctx, &store.UpdateIssueCommentMessage{
+ ProjectID: projectID,
+ ResourceID: root.ResourceID,
+ ThreadState: &resolved,
+ }))
+ fetched, err = stores.GetIssueComment(ctx, &store.FindIssueCommentMessage{
+ ProjectID: projectID,
+ ResourceID: &root.ResourceID,
+ })
+ require.NoError(t, err)
+ require.Equal(t, store.ThreadStateResolved, *fetched.ThreadState)
+
+ // Replying to a resolved thread must not reopen it.
+ _, err = stores.CreateIssueCommentReply(ctx, creator, &store.IssueCommentMessage{
+ ProjectID: projectID,
+ IssueUID: issueUID,
+ ParentID: &root.ResourceID,
+ Payload: &storepb.IssueCommentPayload{Comment: "late reply"},
+ })
+ require.NoError(t, err)
+ fetched, err = stores.GetIssueComment(ctx, &store.FindIssueCommentMessage{
+ ProjectID: projectID,
+ ResourceID: &root.ResourceID,
+ })
+ require.NoError(t, err)
+ require.Equal(t, store.ThreadStateResolved, *fetched.ThreadState)
+ replies, err = stores.ListIssueComment(ctx, &store.FindIssueCommentMessage{
+ ProjectID: projectID,
+ ParentIDs: &parentIDs,
+ })
+ require.NoError(t, err)
+ require.Len(t, replies, 2, "the late reply must land in the thread")
+ for _, r := range replies {
+ require.Equal(t, root.ResourceID, *r.ParentID)
+ }
+
+ // A text edit leaves the anchor and thread state alone; only text edits
+ // bump updated_at.
+ edited := "root (edited)"
+ require.NoError(t, stores.UpdateIssueComment(ctx, &store.UpdateIssueCommentMessage{
+ ProjectID: projectID,
+ ResourceID: root.ResourceID,
+ Comment: &edited,
+ }))
+ fetched, err = stores.GetIssueComment(ctx, &store.FindIssueCommentMessage{
+ ProjectID: projectID,
+ ResourceID: &root.ResourceID,
+ })
+ require.NoError(t, err)
+ require.Equal(t, edited, fetched.Payload.GetComment())
+ require.Equal(t, anchor.SpecId, fetched.Payload.GetStatementAnchor().GetSpecId(), "a comment patch must not touch the anchor")
+ require.Equal(t, anchor.SheetSha256, fetched.Payload.GetStatementAnchor().GetSheetSha256())
+ require.Equal(t, store.ThreadStateResolved, *fetched.ThreadState)
+ editStamp := fetched.UpdatedAt
+
+ nope := "text on event"
+ err = stores.UpdateIssueComment(ctx, &store.UpdateIssueCommentMessage{
+ ProjectID: projectID,
+ ResourceID: event.ResourceID,
+ Comment: &nope,
+ })
+ require.Equal(t, common.NotFound, common.ErrorCode(err), "a pure event cannot gain comment text")
+
+ hybrid, err := stores.CreateIssueComments(ctx, creator, &store.IssueCommentMessage{
+ ProjectID: projectID,
+ IssueUID: issueUID,
+ Payload: &storepb.IssueCommentPayload{
+ Comment: "approved",
+ Event: &storepb.IssueCommentPayload_Approval_{
+ Approval: &storepb.IssueCommentPayload_Approval{},
+ },
+ },
+ })
+ require.NoError(t, err)
+ require.Nil(t, hybrid.ThreadState)
+ hybridEdit := "approved (edited)"
+ require.NoError(t, stores.UpdateIssueComment(ctx, &store.UpdateIssueCommentMessage{
+ ProjectID: projectID,
+ ResourceID: hybrid.ResourceID,
+ Comment: &hybridEdit,
+ }), "hybrid event+comment rows keep their text editable")
+
+ err = stores.UpdateIssueComment(ctx, &store.UpdateIssueCommentMessage{
+ ProjectID: projectID,
+ ResourceID: reply.ResourceID,
+ ThreadState: &resolved,
+ })
+ require.Equal(t, common.NotFound, common.ErrorCode(err), "replies carry no thread state")
+ err = stores.UpdateIssueComment(ctx, &store.UpdateIssueCommentMessage{
+ ProjectID: projectID,
+ ResourceID: event.ResourceID,
+ ThreadState: &resolved,
+ })
+ require.Equal(t, common.NotFound, common.ErrorCode(err), "events carry no thread state")
+
+ open := store.ThreadStateOpen
+ require.NoError(t, stores.UpdateIssueComment(ctx, &store.UpdateIssueCommentMessage{
+ ProjectID: projectID,
+ ResourceID: root.ResourceID,
+ ThreadState: &open,
+ }))
+ openRoots, err := stores.ListIssueComment(ctx, &store.FindIssueCommentMessage{
+ ProjectID: projectID,
+ IssueUID: &uid,
+ ThreadState: &open,
+ })
+ require.NoError(t, err)
+ require.Len(t, openRoots, 1)
+ require.Equal(t, root.ResourceID, openRoots[0].ResourceID)
+ require.True(t, editStamp.Equal(openRoots[0].UpdatedAt),
+ "resolve and reopen must not mark the comment as edited")
+}
diff --git a/proto/gen/grpc-doc/store/README.md b/proto/gen/grpc-doc/store/README.md
index 8f9808cf04..b2559af0c5 100644
--- a/proto/gen/grpc-doc/store/README.md
+++ b/proto/gen/grpc-doc/store/README.md
@@ -171,6 +171,7 @@
- [IssueCommentPayload.IssueUpdate](#bytebase-store-IssueCommentPayload-IssueUpdate)
- [IssueCommentPayload.PlanUpdate](#bytebase-store-IssueCommentPayload-PlanUpdate)
- [IssueCommentPayload.ReviewSubmission](#bytebase-store-IssueCommentPayload-ReviewSubmission)
+ - [IssueCommentPayload.StatementAnchor](#bytebase-store-IssueCommentPayload-StatementAnchor)
- [store/oauth2.proto](#store_oauth2-proto)
- [OAuth2AuthorizationCodeConfig](#bytebase-store-OAuth2AuthorizationCodeConfig)
@@ -3037,6 +3038,7 @@ Type represents the category of issue.
| issue_update | [IssueCommentPayload.IssueUpdate](#bytebase-store-IssueCommentPayload-IssueUpdate) | | |
| plan_update | [IssueCommentPayload.PlanUpdate](#bytebase-store-IssueCommentPayload-PlanUpdate) | | |
| review_submission | [IssueCommentPayload.ReviewSubmission](#bytebase-store-IssueCommentPayload-ReviewSubmission) | | |
+| statement_anchor | [IssueCommentPayload.StatementAnchor](#bytebase-store-IssueCommentPayload-StatementAnchor) | | The statement context an inline comment references. Set at creation and immutable afterward; never set together with an event. |
@@ -3108,6 +3110,26 @@ ReviewSubmission records that an issue entered review.
+
+<a name="bytebase-store-IssueCommentPayload-StatementAnchor"></a>
+
+### IssueCommentPayload.StatementAnchor
+StatementAnchor records the anchored statement revision and range.
+The SQL excerpt and current/changed/unavailable state are computed on
+read against the anchored sheet and the current plan, not stored.
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| spec_id | [string](#string) | | UUID of the anchored plan spec (PlanConfig.Spec.id); may no longer resolve after the spec is deleted from the plan. |
+| sheet_sha256 | [string](#string) | | SHA256 hex of the anchored sheet revision. |
+| start_position | [Position](#bytebase-store-Position) | | The anchored range. When both columns are 0, the anchor spans whole lines from start_position.line to end_position.line inclusive — overriding Position&#39;s &#34;column 0 means unknown&#34; convention. When both columns are set, start_position is inclusive and end_position is exclusive, in one-based lines and code-point columns (see Position). Setting exactly one column to 0 is invalid. |
+| end_position | [Position](#bytebase-store-Position) | | |
+
+
+
+
+
diff --git a/proto/gen/grpc-doc/store/index.html b/proto/gen/grpc-doc/store/index.html
index 894c7e282f..765483a974 100644
--- a/proto/gen/grpc-doc/store/index.html
+++ b/proto/gen/grpc-doc/store/index.html
@@ -845,6 +845,10 @@
<a href="#bytebase.store.IssueCommentPayload.ReviewSubmission"><span class="badge">M</span>IssueCommentPayload.ReviewSubmission</a>
</li>
+ <li>
+ <a href="#bytebase.store.IssueCommentPayload.StatementAnchor"><span class="badge">M</span>IssueCommentPayload.StatementAnchor</a>
+ </li>
+
@@ -9116,6 +9120,14 @@ Format: environments/prod where prod is the environment resource ID. </p></td>
<td><p> </p></td>
</tr>
+ <tr>
+ <td>statement_anchor</td>
+ <td><a href="#bytebase.store.IssueCommentPayload.StatementAnchor">IssueCommentPayload.StatementAnchor</a></td>
+ <td></td>
+ <td><p>The statement context an inline comment references. Set at creation and
+immutable afterward; never set together with an event. </p></td>
+ </tr>
+
</tbody>
</table>
@@ -9258,6 +9270,57 @@ Format: environments/prod where prod is the environment resource ID. </p></td>
+ <h3 id="bytebase.store.IssueCommentPayload.StatementAnchor">IssueCommentPayload.StatementAnchor</h3>
+ <p>StatementAnchor records the anchored statement revision and range.</p><p>The SQL excerpt and current/changed/unavailable state are computed on</p><p>read against the anchored sheet and the current plan, not stored.</p>
+
+
+ <table class="field-table">
+ <thead>
+ <tr><td>Field</td><td>Type</td><td>Label</td><td>Description</td></tr>
+ </thead>
+ <tbody>
+
+ <tr>
+ <td>spec_id</td>
+ <td><a href="#string">string</a></td>
+ <td></td>
+ <td><p>UUID of the anchored plan spec (PlanConfig.Spec.id); may no longer
+resolve after the spec is deleted from the plan. </p></td>
+ </tr>
+
+ <tr>
+ <td>sheet_sha256</td>
+ <td><a href="#string">string</a></td>
+ <td></td>
+ <td><p>SHA256 hex of the anchored sheet revision. </p></td>
+ </tr>
+
+ <tr>
+ <td>start_position</td>
+ <td><a href="#bytebase.store.Position">Position</a></td>
+ <td></td>
+ <td><p>The anchored range. When both columns are 0, the anchor spans whole
+lines from start_position.line to end_position.line inclusive —
+overriding Position&#39;s &#34;column 0 means unknown&#34; convention. When both
+columns are set, start_position is inclusive and end_position is
+exclusive, in one-based lines and code-point columns (see Position).
+Setting exactly one column to 0 is invalid. </p></td>
+ </tr>
+
+ <tr>
+ <td>end_position</td>
+ <td><a href="#bytebase.store.Position">Position</a></td>
+ <td></td>
+ <td><p> </p></td>
+ </tr>
+
+ </tbody>
+ </table>
+
+
+
+
+
diff --git a/proto/store/store/issue_comment.proto b/proto/store/store/issue_comment.proto
index a5467eb637..924678c1cf 100644
--- a/proto/store/store/issue_comment.proto
+++ b/proto/store/store/issue_comment.proto
@@ -3,6 +3,7 @@ syntax = "proto3";
package bytebase.store;
import "store/approval.proto";
+import "store/common.proto";
import "store/issue.proto";
import "store/plan.proto";
@@ -19,6 +20,10 @@ message IssueCommentPayload {
ReviewSubmission review_submission = 8;
}
+ // The statement context an inline comment references. Set at creation and
+ // immutable afterward; never set together with an event.
+ StatementAnchor statement_anchor = 9;
+
message Approval {
IssuePayloadApproval.Approver.Status status = 1;
}
@@ -45,4 +50,23 @@ message IssueCommentPayload {
repeated PlanConfig.Spec from_specs = 1;
repeated PlanConfig.Spec to_specs = 2;
}
+
+ // StatementAnchor records the anchored statement revision and range.
+ // The SQL excerpt and current/changed/unavailable state are computed on
+ // read against the anchored sheet and the current plan, not stored.
+ message StatementAnchor {
+ // UUID of the anchored plan spec (PlanConfig.Spec.id); may no longer
+ // resolve after the spec is deleted from the plan.
+ string spec_id = 1;
+ // SHA256 hex of the anchored sheet revision.
+ string sheet_sha256 = 2;
+ // The anchored range. When both columns are 0, the anchor spans whole
+ // lines from start_position.line to end_position.line inclusive —
+ // overriding Position's "column 0 means unknown" convention. When both
+ // columns are set, start_position is inclusive and end_position is
+ // exclusive, in one-based lines and code-point columns (see Position).
+ // Setting exactly one column to 0 is invalid.
+ Position start_position = 3;
+ Position end_position = 4;
+ }
}