-
Notifications
You must be signed in to change notification settings - Fork 15
/
db.go
917 lines (840 loc) · 23.3 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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
package couchdb
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"mime"
"mime/multipart"
"net/http"
"net/textproto"
"net/url"
"os"
"path"
"path/filepath"
"reflect"
"sort"
"strconv"
"strings"
"sync"
"github.com/go-kivik/couchdb/v4/chttp"
kivik "github.com/go-kivik/kivik/v4"
"github.com/go-kivik/kivik/v4/driver"
)
type db struct {
*client
dbName string
}
var (
_ driver.DB = &db{}
_ driver.Finder = &db{}
_ driver.RevGetter = &db{}
_ driver.AttachmentMetaGetter = &db{}
_ driver.PartitionedDB = &db{}
)
func (d *db) path(path string) string {
url, err := url.Parse(d.dbName + "/" + strings.TrimPrefix(path, "/"))
if err != nil {
panic("THIS IS A BUG: d.path failed: " + err.Error())
}
return url.String()
}
func optionsToParams(opts ...map[string]interface{}) (url.Values, error) {
params := url.Values{}
for _, optsSet := range opts {
if err := encodeKeys(optsSet); err != nil {
return nil, err
}
for key, i := range optsSet {
var values []string
switch v := i.(type) {
case string:
values = []string{v}
case []string:
values = v
case bool:
values = []string{fmt.Sprintf("%t", v)}
case int, uint, uint8, uint16, uint32, uint64, int8, int16, int32, int64:
values = []string{fmt.Sprintf("%d", v)}
default:
return nil, &kivik.Error{Status: http.StatusBadRequest, Err: fmt.Errorf("kivik: invalid type %T for options", i)}
}
for _, value := range values {
params.Add(key, value)
}
}
}
return params, nil
}
// rowsQuery performs a query that returns a rows iterator.
func (d *db) rowsQuery(ctx context.Context, path string, opts map[string]interface{}) (driver.Rows, error) {
payload := make(map[string]interface{})
if keys := opts["keys"]; keys != nil {
delete(opts, "keys")
payload["keys"] = keys
}
rowsInit := newRows
if queries := opts["queries"]; queries != nil {
rowsInit = newMultiQueriesRows
delete(opts, "queries")
payload["queries"] = queries
// Funny that this works even in CouchDB 1.x. It seems 1.x just ignores
// extra path elements beyond the view name. So yay for accidental
// backward compatibility!
path = filepath.Join(path, "queries")
}
query, err := optionsToParams(opts)
if err != nil {
return nil, err
}
options := &chttp.Options{Query: query}
method := http.MethodGet
if len(payload) > 0 {
method = http.MethodPost
options.GetBody = chttp.BodyEncoder(payload)
options.Header = http.Header{
chttp.HeaderIdempotencyKey: []string{},
}
}
resp, err := d.Client.DoReq(ctx, method, d.path(path), options)
if err != nil {
return nil, err
}
if err = chttp.ResponseError(resp); err != nil {
return nil, err
}
return rowsInit(ctx, resp.Body), nil
}
// AllDocs returns all of the documents in the database.
func (d *db) AllDocs(ctx context.Context, opts map[string]interface{}) (driver.Rows, error) {
reqPath := "_all_docs"
if part, ok := opts[OptionPartition].(string); ok {
delete(opts, OptionPartition)
reqPath = path.Join("_partition", part, reqPath)
}
return d.rowsQuery(ctx, reqPath, opts)
}
// DesignDocs returns all of the documents in the database.
func (d *db) DesignDocs(ctx context.Context, opts map[string]interface{}) (driver.Rows, error) {
return d.rowsQuery(ctx, "_design_docs", opts)
}
// LocalDocs returns all of the documents in the database.
func (d *db) LocalDocs(ctx context.Context, opts map[string]interface{}) (driver.Rows, error) {
return d.rowsQuery(ctx, "_local_docs", opts)
}
// Query queries a view.
func (d *db) Query(ctx context.Context, ddoc, view string, opts map[string]interface{}) (driver.Rows, error) {
reqPath := fmt.Sprintf("_design/%s/_view/%s", chttp.EncodeDocID(ddoc), chttp.EncodeDocID(view))
if part, ok := opts[OptionPartition].(string); ok {
delete(opts, OptionPartition)
reqPath = path.Join("_partition", part, reqPath)
}
return d.rowsQuery(ctx, reqPath, opts)
}
// Get fetches the requested document.
func (d *db) Get(ctx context.Context, docID string, options map[string]interface{}) (*driver.Document, error) {
resp, err := d.get(ctx, http.MethodGet, docID, options)
if err != nil {
return nil, err
}
ct, params, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
if err != nil {
return nil, &kivik.Error{Status: http.StatusBadGateway, Err: err}
}
switch ct {
case typeJSON:
rev, err := chttp.GetRev(resp)
if err != nil {
return nil, err
}
return &driver.Document{
Rev: rev,
Body: resp.Body,
}, nil
case typeMPRelated:
// I'm unsure whether it's ever possible to get a multipart/related
// response with no ETag. If this is possible, this needs to be improved
// to parse the JSON part of the mp/related response to extract the rev,
// similar to how chttp.GetRev works.
rev, _ := chttp.ETag(resp)
boundary := strings.Trim(params["boundary"], "\"")
if boundary == "" {
return nil, &kivik.Error{Status: http.StatusBadGateway, Err: errors.New("kivik: boundary missing for multipart/related response")}
}
mpReader := multipart.NewReader(resp.Body, boundary)
body, err := mpReader.NextPart()
if err != nil {
return nil, &kivik.Error{Status: http.StatusBadGateway, Err: err}
}
// TODO: Use a TeeReader here, to avoid slurping the entire body into memory at once
content, err := io.ReadAll(body)
if err != nil {
return nil, &kivik.Error{Status: http.StatusBadGateway, Err: err}
}
var metaDoc struct {
Attachments map[string]attMeta `json:"_attachments"`
}
if err := json.Unmarshal(content, &metaDoc); err != nil {
return nil, &kivik.Error{Status: http.StatusBadGateway, Err: err}
}
return &driver.Document{
Rev: rev,
Body: io.NopCloser(bytes.NewBuffer(content)),
Attachments: &multipartAttachments{
content: resp.Body,
mpReader: mpReader,
meta: metaDoc.Attachments,
},
}, nil
default:
return nil, &kivik.Error{Status: http.StatusBadGateway, Err: fmt.Errorf("kivik: invalid content type in response: %s", ct)}
}
}
type attMeta struct {
ContentType string `json:"content_type"`
Size *int64 `json:"length"`
Follows bool `json:"follows"`
}
type multipartAttachments struct {
content io.ReadCloser
mpReader *multipart.Reader
meta map[string]attMeta
}
var _ driver.Attachments = &multipartAttachments{}
func (a *multipartAttachments) Next(att *driver.Attachment) error {
part, err := a.mpReader.NextPart()
switch err {
case io.EOF:
return err
case nil:
// fall through
default:
return &kivik.Error{Status: http.StatusBadGateway, Err: err}
}
disp, dispositionParams, err := mime.ParseMediaType(part.Header.Get("Content-Disposition"))
if err != nil {
return &kivik.Error{Status: http.StatusBadGateway, Err: fmt.Errorf("Content-Disposition: %s", err)}
}
if disp != "attachment" {
return &kivik.Error{Status: http.StatusBadGateway, Err: fmt.Errorf("Unexpected Content-Disposition: %s", disp)}
}
filename := dispositionParams["filename"]
meta := a.meta[filename]
if !meta.Follows {
return &kivik.Error{Status: http.StatusBadGateway, Err: fmt.Errorf("File '%s' not in manifest", filename)}
}
size := int64(-1)
if meta.Size != nil {
size = *meta.Size
} else if cl, e := strconv.ParseInt(part.Header.Get("Content-Length"), 10, 64); e == nil { // nolint:gomnd
size = cl
}
var cType string
if ctHeader, ok := part.Header["Content-Type"]; ok {
cType, _, err = mime.ParseMediaType(ctHeader[0])
if err != nil {
return &kivik.Error{Status: http.StatusBadGateway, Err: err}
}
} else {
cType = meta.ContentType
}
*att = driver.Attachment{
Filename: filename,
Size: size,
ContentType: cType,
Content: part,
ContentEncoding: part.Header.Get("Content-Encoding"),
}
return nil
}
func (a *multipartAttachments) Close() error {
return a.content.Close()
}
// Rev returns the most current rev of the requested document.
func (d *db) GetRev(ctx context.Context, docID string, options map[string]interface{}) (string, error) {
resp, err := d.get(ctx, http.MethodHead, docID, options)
if err != nil {
return "", err
}
rev, err := chttp.GetRev(resp)
if err != nil {
return "", err
}
_ = resp.Body.Close()
return rev, err
}
func (d *db) get(ctx context.Context, method, docID string, options map[string]interface{}) (*http.Response, error) {
if docID == "" {
return nil, missingArg("docID")
}
opts, err := chttp.NewOptions(options)
if err != nil {
return nil, err
}
opts.Accept = typeMPRelated + "," + typeJSON
opts.Query, err = optionsToParams(options)
if err != nil {
return nil, err
}
if _, ok := options[OptionNoMultipartGet]; ok {
opts.Accept = typeJSON
}
resp, err := d.Client.DoReq(ctx, method, d.path(chttp.EncodeDocID(docID)), opts)
if err != nil {
return nil, err
}
err = chttp.ResponseError(resp)
return resp, err
}
func (d *db) CreateDoc(ctx context.Context, doc interface{}, options map[string]interface{}) (docID, rev string, err error) {
result := struct {
ID string `json:"id"`
Rev string `json:"rev"`
}{}
opts, err := chttp.NewOptions(options)
if err != nil {
return "", "", err
}
path := d.dbName
if len(options) > 0 {
params, e := optionsToParams(options)
if e != nil {
return "", "", e
}
path += "?" + params.Encode()
}
opts.Body = chttp.EncodeBody(doc)
err = d.Client.DoJSON(ctx, http.MethodPost, path, opts, &result)
return result.ID, result.Rev, err
}
func putOpts(doc interface{}, options map[string]interface{}) (*chttp.Options, error) {
opts, err := chttp.NewOptions(options)
if err != nil {
return nil, err
}
opts.Query, err = optionsToParams(options)
if err != nil {
return nil, err
}
if _, ok := options[OptionNoMultipartPut]; !ok {
if atts, ok := extractAttachments(doc); ok {
boundary, size, multipartBody, err := newMultipartAttachments(chttp.EncodeBody(doc), atts)
if err != nil {
return nil, err
}
opts.Body = multipartBody
opts.ContentLength = size
opts.ContentType = fmt.Sprintf(typeMPRelated+"; boundary=%q", boundary)
return opts, nil
}
}
opts.Body = chttp.EncodeBody(doc)
return opts, nil
}
func (d *db) Put(ctx context.Context, docID string, doc interface{}, options map[string]interface{}) (rev string, err error) {
if docID == "" {
return "", missingArg("docID")
}
opts, err := putOpts(doc, options)
if err != nil {
return "", err
}
var result struct {
ID string `json:"id"`
Rev string `json:"rev"`
}
err = d.Client.DoJSON(ctx, http.MethodPut, d.path(chttp.EncodeDocID(docID)), opts, &result)
if err != nil {
return "", err
}
return result.Rev, nil
}
const attachmentsKey = "_attachments"
func extractAttachments(doc interface{}) (*kivik.Attachments, bool) {
if doc == nil {
return nil, false
}
v := reflect.ValueOf(doc)
if v.Type().Kind() == reflect.Ptr {
return extractAttachments(v.Elem().Interface())
}
if stdMap, ok := doc.(map[string]interface{}); ok {
return interfaceToAttachments(stdMap[attachmentsKey])
}
if v.Kind() != reflect.Struct {
return nil, false
}
for i := 0; i < v.NumField(); i++ {
if v.Type().Field(i).Tag.Get("json") == attachmentsKey {
return interfaceToAttachments(v.Field(i).Interface())
}
}
return nil, false
}
func interfaceToAttachments(i interface{}) (*kivik.Attachments, bool) {
switch t := i.(type) {
case kivik.Attachments:
atts := make(kivik.Attachments, len(t))
for k, v := range t {
atts[k] = v
delete(t, k)
}
return &atts, true
case *kivik.Attachments:
atts := new(kivik.Attachments)
*atts = *t
*t = nil
return atts, true
}
return nil, false
}
// newMultipartAttachments reads a json stream on in, and produces a
// multipart/related output suitable for a PUT request.
func newMultipartAttachments(in io.ReadCloser, att *kivik.Attachments) (boundary string, size int64, content io.ReadCloser, err error) {
tmp, err := os.CreateTemp("", "kivik-multipart-*")
if err != nil {
return "", 0, nil, err
}
body := multipart.NewWriter(tmp)
w := sync.WaitGroup{}
w.Add(1)
go func() {
err = createMultipart(body, in, att)
e := in.Close()
if err == nil {
err = e
}
w.Done()
}()
w.Wait()
if e := tmp.Sync(); err == nil {
err = e
}
if info, e := tmp.Stat(); e == nil {
size = info.Size()
} else if err == nil {
err = e
}
if _, e := tmp.Seek(0, 0); e != nil && err == nil {
err = e
}
return body.Boundary(),
size,
tmp,
err
}
func createMultipart(w *multipart.Writer, r io.ReadCloser, atts *kivik.Attachments) error {
doc, err := w.CreatePart(textproto.MIMEHeader{
"Content-Type": {typeJSON},
})
if err != nil {
return err
}
attJSON := replaceAttachments(r, atts)
if _, e := io.Copy(doc, attJSON); e != nil {
return e
}
// Sort the filenames to ensure order consistent with json.Marshal's ordering
// of the stubs in the body
filenames := make([]string, 0, len(*atts))
for filename := range *atts {
filenames = append(filenames, filename)
}
sort.Strings(filenames)
for _, filename := range filenames {
att := (*atts)[filename]
file, err := w.CreatePart(textproto.MIMEHeader{
// "Content-Type": {att.ContentType},
// "Content-Disposition": {fmt.Sprintf(`attachment; filename=%q`, filename)},
// "Content-Length": {strconv.FormatInt(att.Size, 10)},
})
if err != nil {
return err
}
if _, err := io.Copy(file, att.Content); err != nil {
return err
}
_ = att.Content.Close()
}
return w.Close()
}
type lener interface {
Len() int
}
type stater interface {
Stat() (os.FileInfo, error)
}
// attachmentSize determines the size of the `in` stream by reading the entire
// stream first. This method is a no-op if att.Size is already > , and sets the Size
// parameter accordingly. If Size is already set, this function does nothing.
// It attempts the following methods:
//
// 1. Calls `Len()`, if implemented by `in` (i.e. `*bytes.Buffer`)
// 2. Calls `Stat()`, if implemented by `in` (i.e. `*os.File`) then returns
// the file's size
// 3. Read the entire stream to determine the size, and replace att.Content
// to be replayed.
func attachmentSize(att *kivik.Attachment) error {
if att.Size > 0 {
return nil
}
size, r, err := readerSize(att.Content)
if err != nil {
return err
}
rc, ok := r.(io.ReadCloser)
if !ok {
rc = io.NopCloser(r)
}
att.Content = rc
att.Size = size
return nil
}
func readerSize(in io.Reader) (int64, io.Reader, error) {
if ln, ok := in.(lener); ok {
return int64(ln.Len()), in, nil
}
if st, ok := in.(stater); ok {
info, err := st.Stat()
if err != nil {
return 0, nil, err
}
return info.Size(), in, nil
}
content, err := io.ReadAll(in)
if err != nil {
return 0, nil, err
}
buf := bytes.NewBuffer(content)
return int64(buf.Len()), io.NopCloser(buf), nil
}
// NewAttachment is a convenience function, which sets the size of the attachment
// based on content. This is intended for creating attachments to be uploaded
// using multipart/related capabilities of Put(). The attachment size will be
// set to the first of the following found:
//
// 1. `size`, if present. Only the first value is considered
// 2. content.Len(), if implemented (i.e. *bytes.Buffer)
// 3. content.Stat().Size(), if implemented (i.e. *os.File)
// 4. Read the entire content into memory, to determine the size. This can
// use a lot of memory for large attachments. Please use a file, or
// specify the size directly instead.
func NewAttachment(filename, contentType string, content io.Reader, size ...int64) (*kivik.Attachment, error) {
var filesize int64
if len(size) > 0 {
filesize = size[0]
} else {
var err error
filesize, content, err = readerSize(content)
if err != nil {
return nil, err
}
}
rc, ok := content.(io.ReadCloser)
if !ok {
rc = io.NopCloser(content)
}
return &kivik.Attachment{
Filename: filename,
ContentType: contentType,
Content: rc,
Size: filesize,
}, nil
}
// replaceAttachments reads a json stream on in, looking for the _attachments
// key, then replaces its value with the marshaled version of att.
func replaceAttachments(in io.ReadCloser, atts *kivik.Attachments) io.ReadCloser {
r, w := io.Pipe()
go func() {
stubs, err := attachmentStubs(atts)
if err != nil {
_ = w.CloseWithError(err)
_ = in.Close()
return
}
err = copyWithAttachmentStubs(w, in, stubs)
e := in.Close()
if err == nil {
err = e
}
_ = w.CloseWithError(err)
}()
return r
}
type stub struct {
ContentType string `json:"content_type"`
Size int64 `json:"length"`
}
func (s *stub) MarshalJSON() ([]byte, error) {
type attJSON struct {
stub
Follows bool `json:"follows"`
}
att := attJSON{
stub: *s,
Follows: true,
}
return json.Marshal(att)
}
func attachmentStubs(atts *kivik.Attachments) (map[string]*stub, error) {
if atts == nil {
return nil, nil
}
result := make(map[string]*stub, len(*atts))
for filename, att := range *atts {
if err := attachmentSize(att); err != nil {
return nil, err
}
result[filename] = &stub{
ContentType: att.ContentType,
Size: att.Size,
}
}
return result, nil
}
// copyWithAttachmentStubs copies r to w, replacing the _attachment value with the
// marshaled version of atts.
func copyWithAttachmentStubs(w io.Writer, r io.Reader, atts map[string]*stub) error {
dec := json.NewDecoder(r)
t, err := dec.Token()
if err == nil {
if t != json.Delim('{') {
return &kivik.Error{Status: http.StatusBadRequest, Err: fmt.Errorf("expected '{', found '%v'", t)}
}
}
if err != nil {
if err != io.EOF {
return err
}
}
if _, err := fmt.Fprintf(w, "%v", t); err != nil {
return err
}
first := true
for {
t, err := dec.Token()
if err == io.EOF {
break
}
if err != nil {
return &kivik.Error{Status: http.StatusBadRequest, Err: err}
}
switch tp := t.(type) {
case string:
if !first {
if _, e := w.Write([]byte(",")); e != nil {
return e
}
}
first = false
if _, e := fmt.Fprintf(w, `"%s":`, tp); e != nil {
return e
}
var val json.RawMessage
if e := dec.Decode(&val); e != nil {
return e
}
if tp == attachmentsKey {
if e := json.NewEncoder(w).Encode(atts); e != nil {
return e
}
// Once we're here, we can just stream the rest of the input
// unaltered.
if _, e := io.Copy(w, dec.Buffered()); e != nil {
return e
}
_, e := io.Copy(w, r)
return e
}
if _, e := w.Write(val); e != nil {
return e
}
case json.Delim:
if tp != json.Delim('}') {
return fmt.Errorf("expected '}', found '%v'", t)
}
if _, err := fmt.Fprintf(w, "%v", t); err != nil {
return err
}
}
}
return nil
}
func (d *db) Delete(ctx context.Context, docID string, options map[string]interface{}) (string, error) {
if docID == "" {
return "", missingArg("docID")
}
if rev, _ := options["rev"].(string); rev == "" {
return "", missingArg("rev")
}
opts, err := chttp.NewOptions(options)
if err != nil {
return "", err
}
opts.Query, err = optionsToParams(options)
if err != nil {
return "", err
}
resp, err := d.Client.DoReq(ctx, http.MethodDelete, d.path(chttp.EncodeDocID(docID)), opts)
if err != nil {
return "", err
}
defer chttp.CloseBody(resp.Body)
return chttp.GetRev(resp)
}
func (d *db) Flush(ctx context.Context) error {
opts := &chttp.Options{
Header: http.Header{
chttp.HeaderIdempotencyKey: []string{},
},
}
_, err := d.Client.DoError(ctx, http.MethodPost, d.path("/_ensure_full_commit"), opts)
return err
}
func (d *db) Compact(ctx context.Context) error {
opts := &chttp.Options{
Header: http.Header{
chttp.HeaderIdempotencyKey: []string{},
},
}
res, err := d.Client.DoReq(ctx, http.MethodPost, d.path("/_compact"), opts)
if err != nil {
return err
}
defer chttp.CloseBody(res.Body)
return chttp.ResponseError(res)
}
func (d *db) CompactView(ctx context.Context, ddocID string) error {
if ddocID == "" {
return missingArg("ddocID")
}
opts := &chttp.Options{
Header: http.Header{
chttp.HeaderIdempotencyKey: []string{},
},
}
res, err := d.Client.DoReq(ctx, http.MethodPost, d.path("/_compact/"+ddocID), opts)
if err != nil {
return err
}
defer chttp.CloseBody(res.Body)
return chttp.ResponseError(res)
}
func (d *db) ViewCleanup(ctx context.Context) error {
opts := &chttp.Options{
Header: http.Header{
chttp.HeaderIdempotencyKey: []string{},
},
}
res, err := d.Client.DoReq(ctx, http.MethodPost, d.path("/_view_cleanup"), opts)
if err != nil {
return err
}
defer chttp.CloseBody(res.Body)
return chttp.ResponseError(res)
}
func (d *db) Security(ctx context.Context) (*driver.Security, error) {
var sec *driver.Security
err := d.Client.DoJSON(ctx, http.MethodGet, d.path("/_security"), nil, &sec)
return sec, err
}
func (d *db) SetSecurity(ctx context.Context, security *driver.Security) error {
opts := &chttp.Options{
GetBody: chttp.BodyEncoder(security),
Header: http.Header{
chttp.HeaderIdempotencyKey: []string{},
},
}
res, err := d.Client.DoReq(ctx, http.MethodPut, d.path("/_security"), opts)
if err != nil {
return err
}
defer chttp.CloseBody(res.Body)
return chttp.ResponseError(res)
}
func (d *db) Copy(ctx context.Context, targetID, sourceID string, options map[string]interface{}) (targetRev string, err error) {
if sourceID == "" {
return "", missingArg("sourceID")
}
if targetID == "" {
return "", missingArg("targetID")
}
opts, err := chttp.NewOptions(options)
if err != nil {
return "", err
}
opts.Query, err = optionsToParams(options)
if err != nil {
return "", err
}
opts.Header = http.Header{
chttp.HeaderDestination: []string{targetID},
}
resp, err := d.Client.DoReq(ctx, "COPY", d.path(chttp.EncodeDocID(sourceID)), opts)
if err != nil {
return "", err
}
defer chttp.CloseBody(resp.Body)
return chttp.GetRev(resp)
}
func (d *db) Purge(ctx context.Context, docMap map[string][]string) (*driver.PurgeResult, error) {
result := &driver.PurgeResult{}
options := &chttp.Options{
GetBody: chttp.BodyEncoder(docMap),
Header: http.Header{
chttp.HeaderIdempotencyKey: []string{},
},
}
err := d.Client.DoJSON(ctx, http.MethodPost, d.path("_purge"), options, &result)
return result, err
}
var _ driver.RevsDiffer = &db{}
func (d *db) RevsDiff(ctx context.Context, revMap interface{}) (driver.Rows, error) {
options := &chttp.Options{
GetBody: chttp.BodyEncoder(revMap),
Header: http.Header{
chttp.HeaderIdempotencyKey: []string{},
},
}
resp, err := d.Client.DoReq(ctx, http.MethodPost, d.path("_revs_diff"), options)
if err != nil {
return nil, err
}
if err = chttp.ResponseError(resp); err != nil {
return nil, err
}
return newRevsDiffRows(ctx, resp.Body), nil
}
type revsDiffParser struct{}
func (p *revsDiffParser) decodeItem(i interface{}, dec *json.Decoder) error {
t, err := dec.Token()
if err != nil {
return err
}
var value json.RawMessage
if err := dec.Decode(&value); err != nil {
return err
}
row := i.(*driver.Row)
row.ID = t.(string)
row.Value = bytes.NewReader(value)
return nil
}
func newRevsDiffRows(ctx context.Context, in io.ReadCloser) driver.Rows {
iter := newIter(ctx, nil, "", in, &revsDiffParser{})
iter.objMode = true
return &rows{iter: iter}
}