...
1
2
3
4
5
6
7
8
9
10
11
12
13 package memorydb
14
15 import (
16 "bytes"
17 "context"
18 "encoding/json"
19 "errors"
20 "fmt"
21 "io"
22 "net/http"
23
24 "github.com/go-kivik/kivik/v4"
25 "github.com/go-kivik/kivik/v4/driver"
26 )
27
28 func (d *db) AllDocs(ctx context.Context, _ driver.Options) (driver.Rows, error) {
29 if exists, _ := d.DBExists(ctx, d.dbName, kivik.Params(nil)); !exists {
30 return nil, statusError{status: http.StatusNotFound, error: errors.New("database does not exist")}
31 }
32 rows := &alldocsResults{
33 resultSet{
34 docIDs: make([]string, 0),
35 revs: make([]*revision, 0),
36 },
37 }
38 for docID := range d.db.docs {
39 if doc, found := d.db.latestRevision(docID); found {
40 rows.docIDs = append(rows.docIDs, docID)
41 rows.revs = append(rows.revs, doc)
42 }
43 }
44 rows.offset = 0
45 rows.totalRows = int64(len(rows.docIDs))
46 return rows, nil
47 }
48
49 type resultSet struct {
50 docIDs []string
51 revs []*revision
52 offset, totalRows int64
53 updateSeq string
54 }
55
56 func (r *resultSet) Close() error {
57 r.revs = nil
58 return nil
59 }
60
61 func (r *resultSet) UpdateSeq() string { return r.updateSeq }
62 func (r *resultSet) TotalRows() int64 { return r.totalRows }
63 func (r *resultSet) Offset() int64 { return r.offset }
64
65 type alldocsResults struct {
66 resultSet
67 }
68
69 var _ driver.Rows = &alldocsResults{}
70
71 func (r *alldocsResults) Next(row *driver.Row) error {
72 if r.revs == nil || len(r.revs) == 0 {
73 return io.EOF
74 }
75 row.ID, r.docIDs = r.docIDs[0], r.docIDs[1:]
76 var next *revision
77 next, r.revs = r.revs[0], r.revs[1:]
78 row.Key = []byte(fmt.Sprintf(`"%s"`, row.ID))
79 value, err := json.Marshal(map[string]string{
80 "rev": fmt.Sprintf("%d-%s", next.ID, next.Rev),
81 })
82 if err != nil {
83 panic(err)
84 }
85 row.Value = bytes.NewReader(value)
86 return nil
87 }
88
View as plain text