/
db.go
496 lines (466 loc) · 14.4 KB
/
db.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
package kivik
import (
"context"
"encoding/json"
"io"
"io/ioutil"
"strings"
"github.com/flimzy/kivik/driver"
"github.com/flimzy/kivik/errors"
)
// DB is a handle to a specific database.
type DB struct {
client *Client
name string
driverDB driver.DB
}
// Client returns the Client used to connect to the database.
func (db *DB) Client() *Client {
return db.client
}
// Name returns the database name as passed when creating the DB connection.
func (db *DB) Name() string {
return db.name
}
// AllDocs returns a list of all documents in the database.
func (db *DB) AllDocs(ctx context.Context, options ...Options) (*Rows, error) {
opts, err := mergeOptions(options...)
if err != nil {
return nil, err
}
rowsi, err := db.driverDB.AllDocs(ctx, opts)
if err != nil {
return nil, err
}
return newRows(ctx, rowsi), nil
}
// Query executes the specified view function from the specified design
// document. ddoc and view may or may not be be prefixed with '_design/'
// and '_view/' respectively. No other
func (db *DB) Query(ctx context.Context, ddoc, view string, options ...Options) (*Rows, error) {
opts, err := mergeOptions(options...)
if err != nil {
return nil, err
}
ddoc = strings.TrimPrefix(ddoc, "_design/")
view = strings.TrimPrefix(view, "_view/")
rowsi, err := db.driverDB.Query(ctx, ddoc, view, opts)
if err != nil {
return nil, err
}
return newRows(ctx, rowsi), nil
}
// Row is the result of calling Get for a single document.
type Row struct {
doc json.RawMessage
}
// ScanDoc unmarshals the data from the fetched row into dest. See documentation
// on Rows.ScanDoc for details.
func (r *Row) ScanDoc(dest interface{}) error {
return scan(dest, r.doc)
}
// Get fetches the requested document.
func (db *DB) Get(ctx context.Context, docID string, options ...Options) (*Row, error) {
opts, err := mergeOptions(options...)
if err != nil {
return nil, err
}
row, err := db.driverDB.Get(ctx, docID, opts)
if err != nil {
return nil, err
}
return &Row{doc: row}, nil
}
// CreateDoc creates a new doc with an auto-generated unique ID. The generated
// docID and new rev are returned.
func (db *DB) CreateDoc(ctx context.Context, doc interface{}, options ...Options) (docID, rev string, err error) {
if dbopt, ok := db.driverDB.(driver.DBOpts); ok {
opts, err := mergeOptions(options...)
if err != nil {
return "", "", err
}
return dbopt.CreateDocOpts(ctx, doc, opts)
}
return db.driverDB.CreateDoc(ctx, doc)
}
// normalizeFromJSON unmarshals a []byte, json.RawMessage or io.Reader to a
// map[string]interface{}, or passed through any other types.
func normalizeFromJSON(i interface{}) (interface{}, error) {
var body []byte
switch t := i.(type) {
case []byte:
body = t
case json.RawMessage:
body = t
default:
r, ok := i.(io.Reader)
if !ok {
return i, nil
}
var err error
body, err = ioutil.ReadAll(r)
if err != nil {
return nil, errors.WrapStatus(StatusUnknownError, err)
}
}
var x map[string]interface{}
if err := json.Unmarshal(body, &x); err != nil {
return nil, errors.WrapStatus(StatusBadRequest, err)
}
return x, nil
}
func extractDocID(i interface{}) (string, bool) {
if i == nil {
return "", false
}
var id string
var ok bool
switch t := i.(type) {
case map[string]interface{}:
id, ok = t["_id"].(string)
case map[string]string:
id, ok = t["_id"]
default:
data, err := json.Marshal(i)
if err != nil {
return "", false
}
var result struct {
ID string `json:"_id"`
}
if err := json.Unmarshal(data, &result); err != nil {
return "", false
}
id = result.ID
ok = result.ID != ""
}
if !ok {
return "", false
}
return id, true
}
// Put creates a new doc or updates an existing one, with the specified docID.
// If the document already exists, the current revision must be included in doc,
// with JSON key '_rev', otherwise a conflict will occur. The new rev is
// returned.
//
// doc may be one of:
//
// - An object to be marshaled to JSON. The resulting JSON structure must
// conform to CouchDB standards.
// - A []byte value, containing a valid JSON document
// - A json.RawMessage value containing a valid JSON document
// - An io.Reader, from which a valid JSON document may be read.
func (db *DB) Put(ctx context.Context, docID string, doc interface{}, options ...Options) (rev string, err error) {
if docID == "" {
return "", missingArg("docID")
}
i, err := normalizeFromJSON(doc)
if err != nil {
return "", err
}
if dbopt, ok := db.driverDB.(driver.DBOpts); ok {
opts, err := mergeOptions(options...)
if err != nil {
return "", err
}
return dbopt.PutOpts(ctx, docID, i, opts)
}
return db.driverDB.Put(ctx, docID, i)
}
// Delete marks the specified document as deleted.
func (db *DB) Delete(ctx context.Context, docID, rev string, options ...Options) (newRev string, err error) {
if docID == "" {
return "", missingArg("docID")
}
if dbopt, ok := db.driverDB.(driver.DBOpts); ok {
opts, err := mergeOptions(options...)
if err != nil {
return "", err
}
return dbopt.DeleteOpts(ctx, docID, rev, opts)
}
return db.driverDB.Delete(ctx, docID, rev)
}
// Flush requests a flush of disk cache to disk or other permanent storage.
//
// See http://docs.couchdb.org/en/2.0.0/api/database/compact.html#db-ensure-full-commit
func (db *DB) Flush(ctx context.Context) error {
if flusher, ok := db.driverDB.(driver.DBFlusher); ok {
return flusher.Flush(ctx)
}
return errors.Status(StatusNotImplemented, "kivik: flush not supported by driver")
}
// DBStats contains database statistics..
type DBStats struct {
// Name is the name of the database.
Name string `json:"db_name"`
// CompactRunning is true if the database is currently being compacted.
CompactRunning bool `json:"compact_running"`
// DocCount is the number of documents are currently stored in the database.
DocCount int64 `json:"doc_count"`
// DeletedCount is a count of documents which have been deleted from the
// database.
DeletedCount int64 `json:"doc_del_count"`
// UpdateSeq is the current update sequence for the database.
UpdateSeq string `json:"update_seq"`
// DiskSize is the number of bytes used on-disk to store the database.
DiskSize int64 `json:"disk_size"`
// ActiveSize is the number of bytes used on-disk to store active documents.
// If this number is lower than DiskSize, then compaction would free disk
// space.
ActiveSize int64 `json:"data_size"`
// ExternalSize is the size of the documents in the database, as represented
// as JSON, before compression.
ExternalSize int64 `json:"-"`
// Cluster reports the cluster replication configuration variables.
Cluster *ClusterConfig `json:"cluster,omitempty"`
// RawResponse is the raw response body returned by the server, useful if
// you need additional backend-specific information.
//
// For the format of this document, see
// http://docs.couchdb.org/en/2.1.1/api/database/common.html#get--db
RawResponse json.RawMessage `json:"-"`
}
// ClusterConfig contains the cluster configuration for the database.
type ClusterConfig struct {
Replicas int `json:"n"`
Shards int `json:"q"`
ReadQuorum int `json:"r"`
WriteQuorum int `json:"w"`
}
// Stats returns database statistics.
func (db *DB) Stats(ctx context.Context) (*DBStats, error) {
i, err := db.driverDB.Stats(ctx)
if err != nil {
return nil, err
}
var cluster *ClusterConfig
if i.Cluster != nil {
c := ClusterConfig(*i.Cluster)
cluster = &c
}
return &DBStats{
Name: i.Name,
CompactRunning: i.CompactRunning,
DocCount: i.DocCount,
DeletedCount: i.DeletedCount,
UpdateSeq: i.UpdateSeq,
DiskSize: i.DiskSize,
ActiveSize: i.ActiveSize,
ExternalSize: i.ExternalSize,
Cluster: cluster,
RawResponse: i.RawResponse,
}, nil
}
// Compact begins compaction of the database. Check the CompactRunning field
// returned by Info() to see if the compaction has completed.
// See http://docs.couchdb.org/en/2.0.0/api/database/compact.html#db-compact
func (db *DB) Compact(ctx context.Context) error {
return db.driverDB.Compact(ctx)
}
// CompactView compats the view indexes associated with the specified design
// document.
// See http://docs.couchdb.org/en/2.0.0/api/database/compact.html#db-compact-design-doc
func (db *DB) CompactView(ctx context.Context, ddocID string) error {
return db.driverDB.CompactView(ctx, ddocID)
}
// ViewCleanup removes view index files that are no longer required as a result
// of changed views within design documents.
// See http://docs.couchdb.org/en/2.0.0/api/database/compact.html#db-view-cleanup
func (db *DB) ViewCleanup(ctx context.Context) error {
return db.driverDB.ViewCleanup(ctx)
}
// Security returns the database's security document.
// See http://couchdb.readthedocs.io/en/latest/api/database/security.html#get--db-_security
func (db *DB) Security(ctx context.Context) (*Security, error) {
s, err := db.driverDB.Security(ctx)
if err != nil {
return nil, err
}
return &Security{
Admins: Members(s.Admins),
Members: Members(s.Members),
}, err
}
// SetSecurity sets the database's security document.
// See http://couchdb.readthedocs.io/en/latest/api/database/security.html#put--db-_security
func (db *DB) SetSecurity(ctx context.Context, security *Security) error {
if security == nil {
return missingArg("security")
}
sec := &driver.Security{
Admins: driver.Members(security.Admins),
Members: driver.Members(security.Members),
}
return db.driverDB.SetSecurity(ctx, sec)
}
// Rev returns the most current rev of the requested document. This can
// be more efficient than a full document fetch, because only the rev is
// fetched from the server.
func (db *DB) Rev(ctx context.Context, docID string) (rev string, err error) {
if r, ok := db.driverDB.(driver.Rever); ok {
return r.Rev(ctx, docID)
}
row, err := db.Get(ctx, docID, nil)
if err != nil {
return "", err
}
var doc struct {
Rev string `json:"_rev"`
}
// These last two lines cannot be combined for GopherJS due to a bug.
// See https://github.com/gopherjs/gopherjs/issues/608
if err = row.ScanDoc(&doc); err != nil {
return "", err
}
return doc.Rev, nil
}
// Copy copies the source document to a new document with an ID of targetID. If
// the database backend does not support COPY directly, the operation will be
// emulated with a Get followed by Put. The target will be an exact copy of the
// source, with only the ID and revision changed.
//
// See http://docs.couchdb.org/en/2.0.0/api/document/common.html#copy--db-docid
func (db *DB) Copy(ctx context.Context, targetID, sourceID string, options ...Options) (targetRev string, err error) {
if targetID == "" {
return "", missingArg("targetID")
}
if sourceID == "" {
return "", missingArg("sourceID")
}
opts, err := mergeOptions(options...)
if err != nil {
return "", err
}
if copier, ok := db.driverDB.(driver.Copier); ok {
targetRev, err = copier.Copy(ctx, targetID, sourceID, opts)
if StatusCode(err) != StatusNotImplemented {
return targetRev, err
}
}
row, err := db.Get(ctx, sourceID, opts)
if err != nil {
return "", err
}
var doc map[string]interface{}
if err = row.ScanDoc(&doc); err != nil {
return "", err
}
delete(doc, "_rev")
doc["_id"] = targetID
return db.Put(ctx, targetID, doc)
}
// PutAttachment uploads the supplied content as an attachment to the specified
// document.
func (db *DB) PutAttachment(ctx context.Context, docID, rev string, att *Attachment, options ...Options) (newRev string, err error) {
if docID == "" {
return "", missingArg("docID")
}
if e := att.validate(); e != nil {
return "", e
}
if dbopt, ok := db.driverDB.(driver.DBOpts); ok {
opts, err := mergeOptions(options...)
if err != nil {
return "", err
}
return dbopt.PutAttachmentOpts(ctx, docID, rev, att.Filename, att.ContentType, att, opts)
}
return db.driverDB.PutAttachment(ctx, docID, rev, att.Filename, att.ContentType, att)
}
// GetAttachment returns a file attachment associated with the document.
func (db *DB) GetAttachment(ctx context.Context, docID, rev, filename string, options ...Options) (*Attachment, error) {
if docID == "" {
return nil, missingArg("docID")
}
if filename == "" {
return nil, missingArg("filename")
}
var cType string
var md5sum driver.MD5sum
var body io.ReadCloser
var err error
if dbopt, ok := db.driverDB.(driver.DBOpts); ok {
opts, e := mergeOptions(options...)
if e != nil {
return nil, e
}
cType, md5sum, body, err = dbopt.GetAttachmentOpts(ctx, docID, rev, filename, opts)
} else {
cType, md5sum, body, err = db.driverDB.GetAttachment(ctx, docID, rev, filename)
}
if err != nil {
return nil, err
}
return &Attachment{
ReadCloser: body,
Filename: filename,
ContentType: cType,
MD5: MD5sum(md5sum),
}, nil
}
// GetAttachmentMeta returns meta data about an attachment. The attachment
// content returned will be empty.
func (db *DB) GetAttachmentMeta(ctx context.Context, docID, rev, filename string, options ...Options) (*Attachment, error) {
if docID == "" {
return nil, missingArg("docID")
}
if filename == "" {
return nil, missingArg("filename")
}
if metaer, ok := db.driverDB.(driver.AttachmentMetaer); ok {
opts, err := mergeOptions(options...)
if err != nil {
return nil, err
}
cType, md5sum, err := metaer.GetAttachmentMeta(ctx, docID, rev, filename, opts)
if err != nil {
return nil, err
}
return &Attachment{
Filename: filename,
ContentType: cType,
MD5: MD5sum(md5sum),
}, nil
}
if metaer, ok := db.driverDB.(driver.OldAttachmentMetaer); ok {
cType, md5sum, err := metaer.GetAttachmentMeta(ctx, docID, rev, filename)
if err != nil {
return nil, err
}
return &Attachment{
Filename: filename,
ContentType: cType,
MD5: MD5sum(md5sum),
}, nil
}
att, err := db.GetAttachment(ctx, docID, rev, filename, options...)
if err != nil {
return nil, err
}
_ = att.Close()
return &Attachment{
Filename: att.Filename,
ContentType: att.ContentType,
MD5: att.MD5,
}, nil
}
// DeleteAttachment delets an attachment from a document, returning the
// document's new revision.
func (db *DB) DeleteAttachment(ctx context.Context, docID, rev, filename string, options ...Options) (newRev string, err error) {
if docID == "" {
return "", missingArg("docID")
}
if filename == "" {
return "", missingArg("filename")
}
if dbopt, ok := db.driverDB.(driver.DBOpts); ok {
opts, err := mergeOptions(options...)
if err != nil {
return "", err
}
return dbopt.DeleteAttachmentOpts(ctx, docID, rev, filename, opts)
}
return db.driverDB.DeleteAttachment(ctx, docID, rev, filename)
}