80 lines
2.6 KiB
Go
80 lines
2.6 KiB
Go
package store
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"time"
|
|
)
|
|
|
|
var ErrRevisionCursor = errors.New("invalid revision cursor")
|
|
|
|
type RevisionPage struct {
|
|
Items []RevisionListItem
|
|
Next string
|
|
}
|
|
|
|
// ListRevisionPage is metadata-only. SQLite keeps rowid tie breaking; native
|
|
// PostgreSQL uses UUID with monotonically increasing per-language save times.
|
|
// The cursor is a visible Revision UUID in the same Object, never a global
|
|
// row counter or an OFFSET that shifts when newer revisions arrive.
|
|
func (s *Store) ListRevisionPage(ctx context.Context, objectUUID, before string, limit int) (_ RevisionPage, resultErr error) {
|
|
defer func() { resultErr = s.sqlError("revision history page", resultErr) }()
|
|
page := RevisionPage{Items: []RevisionListItem{}}
|
|
if limit <= 0 {
|
|
limit = 100
|
|
}
|
|
if limit > 200 {
|
|
limit = 200
|
|
}
|
|
ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
|
|
defer cancel()
|
|
tx, err := s.DB.BeginTx(ctx, s.policyReadOptions())
|
|
if err != nil {
|
|
return page, err
|
|
}
|
|
defer tx.Rollback()
|
|
where := ""
|
|
tieColumn := "rowid"
|
|
if s.sqlBackend == storePostgreSQL {
|
|
tieColumn = "uuid"
|
|
}
|
|
args := []any{objectUUID}
|
|
if before != "" {
|
|
var createdMS int64
|
|
var tie any
|
|
if err := tx.QueryRowContext(ctx, `SELECT created_at_ms,`+tieColumn+` FROM revisions WHERE uuid=`+s.sqlParam(1)+` AND object_uuid=`+s.sqlParam(2), before, objectUUID).Scan(&createdMS, &tie); err != nil {
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return page, ErrRevisionCursor
|
|
}
|
|
return page, err
|
|
}
|
|
where = ` AND (created_at_ms,` + tieColumn + `) < (` + s.sqlParam(2) + `,` + s.sqlParam(3) + `)`
|
|
args = append(args, createdMS, tie)
|
|
}
|
|
args = append(args, limit+1)
|
|
rows, err := tx.QueryContext(ctx, `SELECT uuid,object_uuid,COALESCE(document_hash,''),COALESCE(NULLIF(lang,''),'und'),
|
|
COALESCE(NULLIF(content_type,''),'text/html; charset=utf-8'),substr(COALESCE(filename,''),1,4096),
|
|
substr(COALESCE(message,''),1,4096),COALESCE(created_at,0),created_at_ms
|
|
FROM revisions WHERE object_uuid=`+s.sqlParam(1)+where+` ORDER BY created_at_ms DESC,`+tieColumn+` DESC LIMIT `+s.sqlParam(len(args)), args...)
|
|
if err != nil {
|
|
return page, err
|
|
}
|
|
defer rows.Close()
|
|
for rows.Next() {
|
|
var item RevisionListItem
|
|
if err := rows.Scan(&item.UUID, &item.ObjectUUID, &item.DocumentHash, &item.Language, &item.ContentType, &item.Filename, &item.Message, &item.CreatedAt, &item.CreatedAtMS); err != nil {
|
|
return page, err
|
|
}
|
|
page.Items = append(page.Items, item)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return page, err
|
|
}
|
|
if len(page.Items) > limit {
|
|
page.Items = page.Items[:limit]
|
|
page.Next = page.Items[len(page.Items)-1].UUID
|
|
}
|
|
return page, nil
|
|
}
|