190 lines
7.0 KiB
Go
190 lines
7.0 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
)
|
|
|
|
const (
|
|
defaultPageSize = 200
|
|
maxPageSize = 500
|
|
)
|
|
|
|
type pageCursor struct {
|
|
Kind string `json:"kind"`
|
|
Key int64 `json:"key"`
|
|
ID string `json:"id"`
|
|
}
|
|
|
|
type pageRequest struct {
|
|
Limit int
|
|
Cursor *pageCursor
|
|
}
|
|
|
|
func parsePageRequest(r *http.Request, kind string) (pageRequest, error) {
|
|
page := pageRequest{Limit: defaultPageSize}
|
|
if rawLimit := r.URL.Query().Get("limit"); rawLimit != "" {
|
|
limit, err := strconv.Atoi(rawLimit)
|
|
if err != nil || limit < 1 || limit > maxPageSize {
|
|
return pageRequest{}, fmt.Errorf("limit must be between 1 and %d", maxPageSize)
|
|
}
|
|
page.Limit = limit
|
|
}
|
|
if rawCursor := r.URL.Query().Get("cursor"); rawCursor != "" {
|
|
decoded, err := base64.RawURLEncoding.DecodeString(rawCursor)
|
|
if err != nil {
|
|
return pageRequest{}, errors.New("cursor is invalid")
|
|
}
|
|
var cursor pageCursor
|
|
if err := json.Unmarshal(decoded, &cursor); err != nil || cursor.Kind != kind || cursor.ID == "" {
|
|
return pageRequest{}, errors.New("cursor is invalid")
|
|
}
|
|
page.Cursor = &cursor
|
|
}
|
|
return page, nil
|
|
}
|
|
|
|
func requestPage(w http.ResponseWriter, r *http.Request, kind string) (pageRequest, bool) {
|
|
page, err := parsePageRequest(r, kind)
|
|
if err != nil {
|
|
writeJSONError(w, http.StatusBadRequest, err.Error())
|
|
return pageRequest{}, false
|
|
}
|
|
return page, true
|
|
}
|
|
|
|
func encodePageCursor(cursor pageCursor) string {
|
|
encoded, _ := json.Marshal(cursor)
|
|
return base64.RawURLEncoding.EncodeToString(encoded)
|
|
}
|
|
|
|
func readPage[T any](rows pgx.Rows, request pageRequest, kind string, scan func(rowScanner) (T, error), key func(T) int64, id func(T) string) (PageResponse[T], error) {
|
|
defer rows.Close()
|
|
items := make([]T, 0, request.Limit+1)
|
|
for rows.Next() {
|
|
item, err := scan(rows)
|
|
if err != nil {
|
|
return PageResponse[T]{}, err
|
|
}
|
|
items = append(items, item)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return PageResponse[T]{}, err
|
|
}
|
|
hasMore := len(items) > request.Limit
|
|
if hasMore {
|
|
items = items[:request.Limit]
|
|
}
|
|
response := PageResponse[T]{Items: items, HasMore: hasMore}
|
|
if hasMore {
|
|
last := items[len(items)-1]
|
|
response.NextCursor = encodePageCursor(pageCursor{Kind: kind, Key: key(last), ID: id(last)})
|
|
}
|
|
return response, nil
|
|
}
|
|
|
|
func addPageCursor(conditions *[]string, args *[]any, column string, direction string, cursor *pageCursor) {
|
|
if cursor == nil {
|
|
return
|
|
}
|
|
*args = append(*args, cursor.Key)
|
|
keyParam := len(*args)
|
|
*args = append(*args, cursor.ID)
|
|
idParam := len(*args)
|
|
comparison := ">"
|
|
if direction == "desc" {
|
|
comparison = "<"
|
|
}
|
|
*conditions = append(*conditions, fmt.Sprintf("(%s %s $%d OR (%s = $%d AND id > $%d))", column, comparison, keyParam, column, keyParam, idParam))
|
|
}
|
|
|
|
func (d *DB) queryListPage(ctx context.Context, userID int64, includeDeleted bool, request pageRequest) (PageResponse[List], error) {
|
|
conditions := make([]string, 0, 3)
|
|
args := make([]any, 0, 4)
|
|
args = append(args, userID)
|
|
conditions = append(conditions, fmt.Sprintf("EXISTS (SELECT 1 FROM list_memberships m WHERE m.listid = lists.id AND m.user_id = $%d)", len(args)))
|
|
if !includeDeleted {
|
|
conditions = append(conditions, "isdeleted = 0")
|
|
}
|
|
addPageCursor(&conditions, &args, "updatedat", "desc", request.Cursor)
|
|
args = append(args, request.Limit+1)
|
|
query := `SELECT ` + listColumns + ` FROM lists`
|
|
if len(conditions) > 0 {
|
|
query += " WHERE " + strings.Join(conditions, " AND ")
|
|
}
|
|
query += fmt.Sprintf(" ORDER BY updatedat DESC, id ASC LIMIT $%d", len(args))
|
|
rows, err := d.pool.Query(ctx, query, args...)
|
|
if err != nil {
|
|
return PageResponse[List]{}, err
|
|
}
|
|
return readPage(rows, request, "lists", scanList, func(item List) int64 { return int64(item.UpdatedAt) }, func(item List) string { return item.ID })
|
|
}
|
|
|
|
func (d *DB) queryFieldsPage(ctx context.Context, userID int64, includeDeleted bool, listID string, request pageRequest) (PageResponse[Field], error) {
|
|
conditions := make([]string, 0, 4)
|
|
args := make([]any, 0, 5)
|
|
if !includeDeleted {
|
|
conditions = append(conditions, "isdeleted = 0")
|
|
}
|
|
args = append(args, listID)
|
|
conditions = append(conditions, fmt.Sprintf("listid = $%d", len(args)))
|
|
args = append(args, userID)
|
|
conditions = append(conditions, fmt.Sprintf("EXISTS (SELECT 1 FROM list_memberships m WHERE m.listid = fields.listid AND m.user_id = $%d)", len(args)))
|
|
addPageCursor(&conditions, &args, `"order"`, "asc", request.Cursor)
|
|
args = append(args, request.Limit+1)
|
|
query := `SELECT ` + fieldColumns + ` FROM fields WHERE ` + strings.Join(conditions, " AND ")
|
|
query += fmt.Sprintf(` ORDER BY "order" ASC, id ASC LIMIT $%d`, len(args))
|
|
rows, err := d.pool.Query(ctx, query, args...)
|
|
if err != nil {
|
|
return PageResponse[Field]{}, err
|
|
}
|
|
return readPage(rows, request, "fields", scanField, func(item Field) int64 { return int64(item.Order) }, func(item Field) string { return item.ID })
|
|
}
|
|
|
|
func (d *DB) queryItemsPage(ctx context.Context, userID int64, includeDeleted bool, listID string, request pageRequest) (PageResponse[Item], error) {
|
|
conditions := make([]string, 0, 4)
|
|
args := make([]any, 0, 5)
|
|
if !includeDeleted {
|
|
conditions = append(conditions, "isdeleted = 0")
|
|
}
|
|
args = append(args, listID)
|
|
conditions = append(conditions, fmt.Sprintf("listid = $%d", len(args)))
|
|
args = append(args, userID)
|
|
conditions = append(conditions, fmt.Sprintf("EXISTS (SELECT 1 FROM list_memberships m WHERE m.listid = items.listid AND m.user_id = $%d)", len(args)))
|
|
addPageCursor(&conditions, &args, "updatedat", "desc", request.Cursor)
|
|
args = append(args, request.Limit+1)
|
|
query := `SELECT ` + itemColumns + ` FROM items WHERE ` + strings.Join(conditions, " AND ")
|
|
query += fmt.Sprintf(" ORDER BY updatedat DESC, id ASC LIMIT $%d", len(args))
|
|
rows, err := d.pool.Query(ctx, query, args...)
|
|
if err != nil {
|
|
return PageResponse[Item]{}, err
|
|
}
|
|
return readPage(rows, request, "items", scanItem, func(item Item) int64 { return int64(item.UpdatedAt) }, func(item Item) string { return item.ID })
|
|
}
|
|
|
|
func (d *DB) queryValuesPage(ctx context.Context, userID int64, itemID string, request pageRequest) (PageResponse[ItemValue], error) {
|
|
conditions := make([]string, 0, 2)
|
|
args := make([]any, 0, 4)
|
|
args = append(args, itemID)
|
|
conditions = append(conditions, fmt.Sprintf("itemid = $%d", len(args)))
|
|
args = append(args, userID)
|
|
conditions = append(conditions, fmt.Sprintf("EXISTS (SELECT 1 FROM items i JOIN list_memberships m ON m.listid = i.listid WHERE i.id = item_values.itemid AND m.user_id = $%d)", len(args)))
|
|
addPageCursor(&conditions, &args, "updatedat", "asc", request.Cursor)
|
|
args = append(args, request.Limit+1)
|
|
query := `SELECT ` + valueColumns + ` FROM item_values WHERE ` + strings.Join(conditions, " AND ")
|
|
query += fmt.Sprintf(" ORDER BY updatedat ASC, id ASC LIMIT $%d", len(args))
|
|
rows, err := d.pool.Query(ctx, query, args...)
|
|
if err != nil {
|
|
return PageResponse[ItemValue]{}, err
|
|
}
|
|
return readPage(rows, request, "values", scanItemValue, func(item ItemValue) int64 { return int64(item.UpdatedAt) }, func(item ItemValue) string { return item.ID })
|
|
}
|