Skip to content

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

feat: support issue pagination (#2381)

h3n4l37e0ba18c567
diff --git a/api/api.go b/api/api.go
index d930ca1200..f41f7e9580 100644
--- a/api/api.go
+++ b/api/api.go
@@ -30,6 +30,11 @@ const (
DESC SortOrder = "DESC"
)
+const (
+ // DefaultPageSize is the default number of items in a page.
+ DefaultPageSize = 1000
+)
+
// StringToSortOrder converts a valid string to SortOrder.
func StringToSortOrder(s string) (SortOrder, error) {
switch strings.ToUpper(s) {
diff --git a/api/issue.go b/api/issue.go
index 6f2845435f..77ec929703 100644
--- a/api/issue.go
+++ b/api/issue.go
@@ -89,6 +89,12 @@ type Issue struct {
Payload string `jsonapi:"attr,payload"`
}
+// IssueResponse is the API message for an issue response.
+type IssueResponse struct {
+ Issues []*Issue `jsonapi:"relation,issues"`
+ NextToken string `jsonapi:"attr,nextToken"`
+}
+
// IssueCreate is the API message for creating an issue.
type IssueCreate struct {
// Standard fields
@@ -213,7 +219,15 @@ type IssueFind struct {
PipelineID *int
// Find issue where principalID is either creator, assignee or subscriber
PrincipalID *int
- StatusList []IssueStatus
+ // To support pagination, we add into creator, assignee and subscriber.
+ // Only principleID or one of the following three fields can be set.
+ CreatorID *int
+ AssigneeID *int
+ SubscriberID *int
+
+ StatusList []IssueStatus
+ // If specified, only find issues whose ID is smaller that SinceID.
+ SinceID *int
// If specified, then it will only fetch "Limit" most recently updated issues
Limit *int
}
diff --git a/server/issue.go b/server/issue.go
index 7fdcafc528..7b309d46df 100644
--- a/server/issue.go
+++ b/server/issue.go
@@ -3,8 +3,10 @@ package server
import (
"bytes"
"context"
+ "encoding/base64"
"encoding/json"
"fmt"
+ "math"
"net/http"
"sort"
"strconv"
@@ -44,6 +46,15 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {
g.GET("/issue", func(c echo.Context) error {
ctx := c.Request().Context()
issueFind := &api.IssueFind{}
+
+ pageToken := c.QueryParams().Get("token")
+ // We use descending order by default for issues.
+ sinceID, err := unmarshalPageToken(pageToken, api.DESC)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, "Malformed page token").SetInternal(err)
+ }
+ issueFind.SinceID = &sinceID
+
projectIDStr := c.QueryParams().Get("project")
if projectIDStr != "" {
projectID, err := strconv.Atoi(projectIDStr)
@@ -65,15 +76,39 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("limit query parameter is not a number: %s", limitStr)).SetInternal(err)
}
issueFind.Limit = &limit
+ } else {
+ limit := api.DefaultPageSize
+ issueFind.Limit = &limit
}
- userIDStr := c.QueryParams().Get("user")
- if userIDStr != "" {
+
+ if userIDStr := c.QueryParam("user"); userIDStr != "" {
userID, err := strconv.Atoi(userIDStr)
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("user query parameter is not a number: %s", userIDStr)).SetInternal(err)
}
issueFind.PrincipalID = &userID
}
+ if creatorIDStr := c.QueryParam("creator"); creatorIDStr != "" {
+ creatorID, err := strconv.Atoi(creatorIDStr)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("creator query parameter is not a number: %s", creatorIDStr)).SetInternal(err)
+ }
+ issueFind.CreatorID = &creatorID
+ }
+ if assigneeIDStr := c.QueryParam("assignee"); assigneeIDStr != "" {
+ assigneeID, err := strconv.Atoi(assigneeIDStr)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("assignee query parameter is not a number: %s", assigneeIDStr)).SetInternal(err)
+ }
+ issueFind.AssigneeID = &assigneeID
+ }
+ if subscriberIDStr := c.QueryParam("subscriber"); subscriberIDStr != "" {
+ subscriberID, err := strconv.Atoi(subscriberIDStr)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("subscriber query parameter is not a number: %s", subscriberIDStr)).SetInternal(err)
+ }
+ issueFind.SubscriberID = &subscriberID
+ }
issueList, err := s.store.FindIssueStripped(ctx, issueFind)
if err != nil {
@@ -84,8 +119,20 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {
s.setTaskProgressForIssue(issue)
}
+ issueResponse := &api.IssueResponse{}
+ issueResponse.Issues = issueList
+
+ nextSinceID := sinceID
+ if len(issueList) > 0 {
+ // Decrement the ID as we use decreasing order by default.
+ nextSinceID = issueList[len(issueList)-1].ID - 1
+ }
+ if issueResponse.NextToken, err = marshalPageToken(nextSinceID); err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal page token").SetInternal(err)
+ }
+
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
- if err := jsonapi.MarshalPayload(c.Response().Writer, issueList); err != nil {
+ if err := jsonapi.MarshalPayload(c.Response().Writer, issueResponse); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal issue list response").SetInternal(err)
}
return nil
@@ -1360,3 +1407,33 @@ func (s *Server) setTaskProgressForIssue(issue *api.Issue) {
}
}
}
+
+func marshalPageToken(id int) (string, error) {
+ b, err := json.Marshal(id)
+ if err != nil {
+ return "", errors.Wrap(err, "failed to marshal page token")
+ }
+ return base64.StdEncoding.EncodeToString(b), nil
+}
+
+// unmarshalPageToken unmarshals the page token, and returns the last issue ID. If the page token nil empty, it returns MaxInt32.
+func unmarshalPageToken(pageToken string, sortOrder api.SortOrder) (int, error) {
+ if pageToken == "" {
+ if sortOrder == api.ASC {
+ return 0, nil
+ }
+ return math.MaxInt32, nil
+ }
+
+ bs, err := base64.StdEncoding.DecodeString(pageToken)
+ if err != nil {
+ return 0, errors.Wrap(err, "failed to decode page token")
+ }
+
+ var id int
+ if err := json.Unmarshal(bs, &id); err != nil {
+ return 0, errors.Wrap(err, "failed to unmarshal page token")
+ }
+
+ return id, nil
+}
diff --git a/store/issue.go b/store/issue.go
index c0537329e1..7f03a45780 100644
--- a/store/issue.go
+++ b/store/issue.go
@@ -624,11 +624,27 @@ func (*Store) findIssueImpl(ctx context.Context, tx *sql.Tx, find *api.IssueFind
where, args = append(where, fmt.Sprintf("project_id = $%d", len(args)+1)), append(args, *v)
}
if v := find.PrincipalID; v != nil {
+ if find.CreatorID != nil || find.AssigneeID != nil || find.SubscriberID != nil {
+ return nil, &common.Error{Code: common.Invalid, Err: errors.New("principal_id cannot be used with creator_id, assignee_id, or subscriber_id")}
+ }
where = append(where, fmt.Sprintf("(creator_id = $%d OR assignee_id = $%d OR EXISTS (SELECT 1 FROM issue_subscriber WHERE issue_id = issue.id AND subscriber_id = $%d))", len(args)+1, len(args)+2, len(args)+3))
args = append(args, *v)
args = append(args, *v)
args = append(args, *v)
}
+ if v := find.CreatorID; v != nil {
+ where, args = append(where, fmt.Sprintf("creator_id = $%d", len(args)+1)), append(args, *v)
+ }
+ if v := find.AssigneeID; v != nil {
+ where, args = append(where, fmt.Sprintf("assignee_id = $%d", len(args)+1)), append(args, *v)
+ }
+ if v := find.SubscriberID; v != nil {
+ where, args = append(where, fmt.Sprintf("EXISTS (SELECT 1 FROM issue_subscriber WHERE issue_id = issue.id AND subscriber_id = $%d)", len(args)+1)), append(args, *v)
+ }
+ if v := find.SinceID; v != nil {
+ where, args = append(where, fmt.Sprintf("id <= $%d", len(args)+1)), append(args, *v)
+ }
+
if len(find.StatusList) != 0 {
list := []string{}
for _, status := range find.StatusList {
@@ -655,7 +671,7 @@ func (*Store) findIssueImpl(ctx context.Context, tx *sql.Tx, find *api.IssueFind
payload
FROM issue
WHERE ` + strings.Join(where, " AND ")
- query += " ORDER BY updated_ts DESC"
+ query += " ORDER BY id DESC"
if v := find.Limit; v != nil {
query += fmt.Sprintf(" LIMIT %d", *v)
}
diff --git a/tests/tests.go b/tests/tests.go
index 0deaab43e1..4e56ebbf9a 100644
--- a/tests/tests.go
+++ b/tests/tests.go
@@ -689,6 +689,24 @@ func (ctl *controller) getIssue(id int) (*api.Issue, error) {
// getIssue gets the issue with given ID.
func (ctl *controller) getIssues(issueFind api.IssueFind) ([]*api.Issue, error) {
+ var ret []*api.Issue
+ // call getOnePageIssuesWithToken until no more issues.
+ token := ""
+ for {
+ issues, nextToken, err := ctl.getOnePageIssuesWithToken(issueFind, token)
+ if err != nil {
+ return nil, err
+ }
+ if len(issues) == 0 {
+ break
+ }
+ ret = append(ret, issues...)
+ token = nextToken
+ }
+ return ret, nil
+}
+
+func (ctl *controller) getOnePageIssuesWithToken(issueFind api.IssueFind, token string) ([]*api.Issue, string, error) {
params := make(map[string]string)
if issueFind.ProjectID != nil {
params["project"] = fmt.Sprintf("%d", *issueFind.ProjectID)
@@ -700,24 +718,19 @@ func (ctl *controller) getIssues(issueFind api.IssueFind) ([]*api.Issue, error)
}
params["status"] = strings.Join(sl, ",")
}
+ if token != "" {
+ params["token"] = token
+ }
body, err := ctl.get("/issue", params)
if err != nil {
- return nil, err
+ return nil, "", err
}
-
- var issues []*api.Issue
- ps, err := jsonapi.UnmarshalManyPayload(body, reflect.TypeOf(new(api.Issue)))
+ issueResp := new(api.IssueResponse)
+ err = jsonapi.UnmarshalPayload(body, issueResp)
if err != nil {
- return nil, errors.Wrap(err, "fail to unmarshal get issue response")
- }
- for _, p := range ps {
- issue, ok := p.(*api.Issue)
- if !ok {
- return nil, errors.Errorf("fail to convert issue")
- }
- issues = append(issues, issue)
+ return nil, "", errors.Wrap(err, "fail to unmarshal get issue response")
}
- return issues, nil
+ return issueResp.Issues, issueResp.NextToken, nil
}
// patchIssue patches the issue with given ID.