-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathdatabase.go
1506 lines (1347 loc) · 40.7 KB
/
database.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
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package couchdb
import (
"bytes"
"crypto/rand"
"encoding/json"
"errors"
"fmt"
"go/ast"
"go/parser"
"go/token"
"math"
"net/http"
"net/url"
"os"
"reflect"
"strconv"
"strings"
)
const (
// DefaultBaseURL is the default address of CouchDB server.
DefaultBaseURL = "http://localhost:5984"
)
var (
// ErrBatchValue for invalid batch parameter of IterView
ErrBatchValue = errors.New("batch must be 1 or more")
// ErrLimitValue for invalid limit parameter of IterView
ErrLimitValue = errors.New("limit must be 1 or more")
)
// getDefaultCouchDBURL returns the default CouchDB server url.
func getDefaultCouchDBURL() string {
var couchdbURLEnviron string
for _, couchdbURLEnviron = range os.Environ() {
if strings.HasPrefix(couchdbURLEnviron, "COUCHDB_URL") {
break
}
}
if len(couchdbURLEnviron) == 0 {
couchdbURLEnviron = DefaultBaseURL
} else {
couchdbURLEnviron = strings.Split(couchdbURLEnviron, "=")[1]
}
return couchdbURLEnviron
}
// Database represents a CouchDB database instance.
type Database struct {
resource *Resource
}
// NewDatabase returns a CouchDB database instance.
func NewDatabase(urlStr string) (*Database, error) {
var dbURLStr string
if !strings.HasPrefix(urlStr, "http") {
base, err := url.Parse(getDefaultCouchDBURL())
if err != nil {
return nil, err
}
dbURL, err := base.Parse(urlStr)
if err != nil {
return nil, err
}
dbURLStr = dbURL.String()
} else {
dbURLStr = urlStr
}
res, err := NewResource(dbURLStr, nil)
if err != nil {
return nil, err
}
return newDatabase(res)
}
// NewDatabaseWithResource returns a CouchDB database instance with resource obj.
func NewDatabaseWithResource(res *Resource) (*Database, error) {
return newDatabase(res)
}
func newDatabase(res *Resource) (*Database, error) {
return &Database{
resource: res,
}, nil
}
// Available returns error if the database is not good to go.
func (d *Database) Available() error {
_, _, err := d.resource.Head("", nil, nil)
return err
}
// Save creates a new document or update an existing document.
// If doc has no _id the server will generate a random UUID and a new document will be created.
// Otherwise the doc's _id will be used to identify the document to create or update.
// Trying to update an existing document with an incorrect _rev will cause failure.
// *NOTE* It is recommended to avoid saving doc without _id and instead generate document ID on client side.
// To avoid such problems you can generate a UUID on the client side.
// GenerateUUID provides a simple, platform-independent implementation.
// You can also use other third-party packages instead.
// doc: the document to create or update.
func (d *Database) Save(doc map[string]interface{}, options url.Values) (string, string, error) {
var id, rev string
var httpFunc func(string, http.Header, map[string]interface{}, url.Values) (http.Header, []byte, error)
if v, ok := doc["_id"]; ok {
httpFunc = docResource(d.resource, v.(string)).PutJSON
} else {
httpFunc = d.resource.PostJSON
}
_, data, err := httpFunc("", nil, doc, options)
if err != nil {
return id, rev, err
}
var jsonMap map[string]interface{}
jsonMap, err = parseData(data)
if err != nil {
return id, rev, err
}
if v, ok := jsonMap["id"]; ok {
id = v.(string)
doc["_id"] = id
}
if v, ok := jsonMap["rev"]; ok {
rev = v.(string)
doc["_rev"] = rev
}
return id, rev, nil
}
// Get returns the document with the specified ID.
func (d *Database) Get(docid string, options url.Values) (map[string]interface{}, error) {
docRes := docResource(d.resource, docid)
_, data, err := docRes.GetJSON("", nil, options)
if err != nil {
return nil, err
}
var doc map[string]interface{}
doc, err = parseData(data)
if err != nil {
return nil, err
}
return doc, nil
}
// Delete deletes the document with the specified ID.
func (d *Database) Delete(docid string) error {
docRes := docResource(d.resource, docid)
header, _, err := docRes.Head("", nil, nil)
if err != nil {
return err
}
rev := strings.Trim(header.Get("ETag"), `"`)
return deleteDoc(docRes, rev)
}
// DeleteDoc deletes the specified document
func (d *Database) DeleteDoc(doc map[string]interface{}) error {
id, ok := doc["_id"]
if !ok || id == nil {
return errors.New("document ID not existed")
}
rev, ok := doc["_rev"]
if !ok || rev == nil {
return errors.New("document rev not existed")
}
docRes := docResource(d.resource, id.(string))
return deleteDoc(docRes, rev.(string))
}
func deleteDoc(docRes *Resource, rev string) error {
_, _, err := docRes.DeleteJSON("", nil, url.Values{"rev": []string{rev}})
return err
}
// Set creates or updates a document with the specified ID.
func (d *Database) Set(docid string, doc map[string]interface{}) error {
docRes := docResource(d.resource, docid)
_, data, err := docRes.PutJSON("", nil, doc, nil)
if err != nil {
return err
}
result, err := parseData(data)
if err != nil {
return err
}
doc["_id"] = result["id"].(string)
doc["_rev"] = result["rev"].(string)
return nil
}
// Contains returns true if the database contains a document with the specified ID.
func (d *Database) Contains(docid string) error {
docRes := docResource(d.resource, docid)
_, _, err := docRes.Head("", nil, nil)
return err
}
// UpdateResult represents result of an update.
type UpdateResult struct {
ID, Rev string
Err error
}
// Update performs a bulk update or creation of the given documents in a single HTTP request.
// It returns a 3-tuple (id, rev, error)
func (d *Database) Update(docs []map[string]interface{}, options map[string]interface{}) ([]UpdateResult, error) {
results := make([]UpdateResult, len(docs))
body := map[string]interface{}{}
if options != nil {
for k, v := range options {
body[k] = v
}
}
body["docs"] = docs
_, data, err := d.resource.PostJSON("_bulk_docs", nil, body, nil)
if err != nil {
return nil, err
}
var jsonArr []map[string]interface{}
err = json.Unmarshal(data, &jsonArr)
if err != nil {
return nil, err
}
for i, v := range jsonArr {
var retErr error
var result UpdateResult
if val, ok := v["error"]; ok {
errMsg := val.(string)
switch errMsg {
case "conflict":
retErr = ErrConflict
case "forbidden":
retErr = ErrForbidden
default:
retErr = ErrInternalServerError
}
result = UpdateResult{
ID: v["id"].(string),
Rev: "",
Err: retErr,
}
} else {
id, rev := v["id"].(string), v["rev"].(string)
result = UpdateResult{
ID: id,
Rev: rev,
Err: retErr,
}
doc := docs[i]
doc["_id"] = id
doc["_rev"] = rev
}
results[i] = result
}
return results, nil
}
// DocIDs returns the IDs of all documents in database.
func (d *Database) DocIDs() ([]string, error) {
docRes := docResource(d.resource, "_all_docs")
_, data, err := docRes.GetJSON("", nil, nil)
if err != nil {
return nil, err
}
var jsonMap map[string]*json.RawMessage
err = json.Unmarshal(data, &jsonMap)
if err != nil {
return nil, err
}
var jsonArr []*json.RawMessage
json.Unmarshal(*jsonMap["rows"], &jsonArr)
ids := make([]string, len(jsonArr))
for i, v := range jsonArr {
var row map[string]interface{}
err = json.Unmarshal(*v, &row)
if err != nil {
return ids, err
}
ids[i] = row["id"].(string)
}
return ids, nil
}
// Name returns the name of database.
func (d *Database) Name() (string, error) {
var name string
info, err := d.Info("")
if err != nil {
return name, err
}
return info["db_name"].(string), nil
}
// Info returns the information about the database or design document
func (d *Database) Info(ddoc string) (map[string]interface{}, error) {
var data []byte
var err error
if ddoc == "" {
_, data, err = d.resource.GetJSON("", nil, url.Values{})
if err != nil {
return nil, err
}
} else {
_, data, err = d.resource.GetJSON(fmt.Sprintf("_design/%s/_info", ddoc), nil, nil)
if err != nil {
return nil, err
}
}
var info map[string]interface{}
err = json.Unmarshal(data, &info)
if err != nil {
return nil, err
}
return info, nil
}
func (d *Database) String() string {
return fmt.Sprintf("Database %s", d.resource.base)
}
// Commit flushes any recent changes to the specified database to disk.
// If the server is configured to delay commits or previous requests use the special
// "X-Couch-Full-Commit: false" header to disable immediate commits, this method
// can be used to ensure that non-commited changes are commited to physical storage.
func (d *Database) Commit() error {
_, _, err := d.resource.PostJSON("_ensure_full_commit", nil, nil, nil)
return err
}
// Compact compacts the database by compressing the disk database file.
func (d *Database) Compact() error {
_, _, err := d.resource.PostJSON("_compact", nil, nil, nil)
return err
}
// Revisions returns all available revisions of the given document in reverse
// order, e.g. latest first.
func (d *Database) Revisions(docid string, options url.Values) ([]map[string]interface{}, error) {
docRes := docResource(d.resource, docid)
_, data, err := docRes.GetJSON("", nil, url.Values{"revs": []string{"true"}})
if err != nil {
return nil, err
}
var jsonMap map[string]*json.RawMessage
err = json.Unmarshal(data, &jsonMap)
if err != nil {
return nil, err
}
var revsMap map[string]interface{}
err = json.Unmarshal(*jsonMap["_revisions"], &revsMap)
if err != nil {
return nil, err
}
startRev := int(revsMap["start"].(float64))
val := reflect.ValueOf(revsMap["ids"])
if options == nil {
options = url.Values{}
}
docs := make([]map[string]interface{}, val.Len())
for i := 0; i < val.Len(); i++ {
rev := fmt.Sprintf("%d-%s", startRev-i, val.Index(i).Interface().(string))
options.Set("rev", rev)
doc, err := d.Get(docid, options)
if err != nil {
return nil, err
}
docs[i] = doc
}
return docs, nil
}
// GetAttachment returns the file attachment associated with the document.
// The raw data is returned as a []byte.
func (d *Database) GetAttachment(doc map[string]interface{}, name string) ([]byte, error) {
docid, ok := doc["_id"]
if !ok {
return nil, errors.New("doc _id not existed")
}
return d.getAttachment(docid.(string), name)
}
// GetAttachmentID returns the file attachment associated with the document ID.
// The raw data is returned as []byte.
func (d *Database) GetAttachmentID(docid, name string) ([]byte, error) {
return d.getAttachment(docid, name)
}
func (d *Database) getAttachment(docid, name string) ([]byte, error) {
docRes := docResource(docResource(d.resource, docid), name)
_, data, err := docRes.Get("", nil, nil)
return data, err
}
// PutAttachment uploads the supplied []byte as an attachment to the specified document.
// doc: the document that the attachment belongs to. Must have _id and _rev inside.
// content: the data to be attached to doc.
// name: name of attachment.
// mimeType: MIME type of content.
func (d *Database) PutAttachment(doc map[string]interface{}, content []byte, name, mimeType string) error {
if id, ok := doc["_id"]; !ok || id.(string) == "" {
return errors.New("doc _id not existed")
}
if rev, ok := doc["_rev"]; !ok || rev.(string) == "" {
return errors.New("doc _rev not extisted")
}
id, rev := doc["_id"].(string), doc["_rev"].(string)
docRes := docResource(docResource(d.resource, id), name)
header := http.Header{}
header.Set("Content-Type", mimeType)
params := url.Values{}
params.Set("rev", rev)
_, data, err := docRes.Put("", header, content, params)
if err != nil {
return err
}
result, err := parseData(data)
if err != nil {
return err
}
doc["_rev"] = result["rev"].(string)
return nil
}
// DeleteAttachment deletes the specified attachment
func (d *Database) DeleteAttachment(doc map[string]interface{}, name string) error {
if id, ok := doc["_id"]; !ok || id.(string) == "" {
return errors.New("doc _id not existed")
}
if rev, ok := doc["_rev"]; !ok || rev.(string) == "" {
return errors.New("doc _rev not extisted")
}
id, rev := doc["_id"].(string), doc["_rev"].(string)
params := url.Values{}
params.Set("rev", rev)
docRes := docResource(docResource(d.resource, id), name)
_, data, err := docRes.DeleteJSON("", nil, params)
if err != nil {
return err
}
result, err := parseData(data)
if err != nil {
return err
}
doc["_rev"] = result["rev"]
return nil
}
// Copy copies an existing document to a new or existing document.
func (d *Database) Copy(srcID, destID, destRev string) (string, error) {
docRes := docResource(d.resource, srcID)
var destination string
if destRev != "" {
destination = fmt.Sprintf("%s?rev=%s", destID, destRev)
} else {
destination = destID
}
header := http.Header{
"Destination": []string{destination},
}
_, data, err := request("COPY", docRes.base, header, nil, nil)
var rev string
if err != nil {
return rev, err
}
result, err := parseData(data)
if err != nil {
return rev, err
}
rev = result["rev"].(string)
return rev, nil
}
// Changes returns a sorted list of changes feed made to documents in the database.
func (d *Database) Changes(options url.Values) (map[string]interface{}, error) {
_, data, err := d.resource.GetJSON("_changes", nil, options)
if err != nil {
return nil, err
}
result, err := parseData(data)
return result, err
}
// Purge performs complete removing of the given documents.
func (d *Database) Purge(docs []map[string]interface{}) (map[string]interface{}, error) {
revs := map[string][]string{}
for _, doc := range docs {
id, rev := doc["_id"].(string), doc["_rev"].(string)
if _, ok := revs[id]; !ok {
revs[id] = []string{}
}
revs[id] = append(revs[id], rev)
}
body := map[string]interface{}{}
for k, v := range revs {
body[k] = v
}
_, data, err := d.resource.PostJSON("_purge", nil, body, nil)
if err != nil {
return nil, err
}
return parseData(data)
}
func parseData(data []byte) (map[string]interface{}, error) {
result := map[string]interface{}{}
err := json.Unmarshal(data, &result)
if err != nil {
return result, err
}
if _, ok := result["error"]; ok {
reason := result["reason"].(string)
return result, errors.New(reason)
}
return result, nil
}
func parseRaw(data []byte) (map[string]*json.RawMessage, error) {
result := map[string]*json.RawMessage{}
err := json.Unmarshal(data, &result)
if err != nil {
return result, err
}
if _, ok := result["error"]; ok {
var reason string
json.Unmarshal(*result["reason"], &reason)
return result, errors.New(reason)
}
return result, nil
}
// GenerateUUID returns a random 128-bit UUID
func GenerateUUID() string {
b := make([]byte, 16)
_, err := rand.Read(b)
if err != nil {
return ""
}
uuid := fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
return uuid
}
// SetSecurity sets the security object for the given database.
func (d *Database) SetSecurity(securityDoc map[string]interface{}) error {
_, _, err := d.resource.PutJSON("_security", nil, securityDoc, nil)
return err
}
// GetSecurity returns the current security object from the given database.
func (d *Database) GetSecurity() (map[string]interface{}, error) {
_, data, err := d.resource.GetJSON("_security", nil, nil)
if err != nil {
return nil, err
}
return parseData(data)
}
// Len returns the number of documents stored in it.
func (d *Database) Len() (int, error) {
info, err := d.Info("")
if err != nil {
return 0, err
}
return int(info["doc_count"].(float64)), nil
}
// GetRevsLimit gets the current revs_limit(revision limit) setting.
func (d *Database) GetRevsLimit() (int, error) {
_, data, err := d.resource.Get("_revs_limit", nil, nil)
if err != nil {
return 0, err
}
limit, err := strconv.Atoi(strings.Trim(string(data), "\n"))
if err != nil {
return limit, err
}
return limit, nil
}
// SetRevsLimit sets the maximum number of document revisions that will be
// tracked by CouchDB.
func (d *Database) SetRevsLimit(limit int) error {
_, _, err := d.resource.Put("_revs_limit", nil, []byte(strconv.Itoa(limit)), nil)
return err
}
// docResource returns a Resource instance for docID
func docResource(res *Resource, docID string) *Resource {
if len(docID) == 0 {
return res
}
docRes := res
if docID[:1] == "_" {
paths := strings.SplitN(docID, "/", 2)
for _, p := range paths {
docRes, _ = docRes.NewResourceWithURL(p)
}
return docRes
}
docRes, _ = res.NewResourceWithURL(url.QueryEscape(docID))
return docRes
}
// Cleanup removes all view index files no longer required by CouchDB.
func (d *Database) Cleanup() error {
_, _, err := d.resource.PostJSON("_view_cleanup", nil, nil, nil)
return err
}
// Query returns documents using a conditional selector statement in Golang.
//
// selector: A filter string declaring which documents to return, formatted as a Golang statement.
//
// fields: Specifying which fields to be returned, if passing nil the entire
// is returned, no automatic inclusion of _id or other metadata fields.
//
// sorts: How to order the documents returned, formatted as ["desc(fieldName1)", "desc(fieldName2)"]
// or ["fieldNameA", "fieldNameB"] of which "asc" is used by default, passing nil to disable ordering.
//
// limit: Maximum number of results returned, passing nil to use default value(25).
//
// skip: Skip the first 'n' results, where 'n' is the number specified, passing nil for no-skip.
//
// index: Instruct a query to use a specific index, specified either as "<design_document>" or
// ["<design_document>", "<index_name>"], passing nil to use primary index(_all_docs) by default.
//
// Inner functions for selector syntax
//
// nor(condexprs...) matches if none of the conditions in condexprs match($nor).
//
// For example: nor(year == 1990, year == 1989, year == 1997) returns all documents
// whose year field not in 1989, 1990 and 1997.
//
// all(field, array) matches an array value if it contains all the elements of the argument array($all).
//
// For example: all(genre, []string{"Comedy", "Short"} returns all documents whose
// genre field contains "Comedy" and "Short".
//
// any(field, condexpr) matches an array field with at least one element meets the specified condition($elemMatch).
//
// For example: any(genre, genre == "Short" || genre == "Horror") returns all documents whose
// genre field contains "Short" or "Horror" or both.
//
// exists(field, boolean) checks whether the field exists or not, regardless of its value($exists).
//
// For example: exists(director, false) returns all documents who does not have a director field.
//
// typeof(field, type) checks the document field's type, valid types are
// "null", "boolean", "number", "string", "array", "object"($type).
//
// For example: typeof(genre, "array") returns all documents whose genre field is of array type.
//
// in(field, array) the field must exist in the array provided($in).
//
// For example: in(director, []string{"Mike Portnoy", "Vitali Kanevsky"}) returns all documents
// whose director field is "Mike Portnoy" or "Vitali Kanevsky".
//
// nin(field, array) the document field must not exist in the array provided($nin).
//
// For example: nin(year, []int{1990, 1992, 1998}) returns all documents whose year field is not
// in 1990, 1992 or 1998.
//
// size(field, int) matches the length of an array field in a document($size).
//
// For example: size(genre, 2) returns all documents whose genre field is of length 2.
//
// mod(field, divisor, remainder) matches documents where field % divisor == remainder($mod).
//
// For example: mod(year, 2, 1) returns all documents whose year field is an odd number.
//
// regex(field, regexstr) a regular expression pattern to match against the document field.
//
// For example: regex(title, "^A") returns all documents whose title is begin with an "A".
//
// Inner functions for sort syntax
//
// asc(field) sorts the field in ascending order, this is the default option while
// desc(field) sorts the field in descending order.
func (d *Database) Query(fields []string, selector string, sorts []string, limit, skip, index interface{}) ([]map[string]interface{}, error) {
selectorJSON, err := parseSelectorSyntax(selector)
if err != nil {
return nil, err
}
find := map[string]interface{}{
"selector": selectorJSON,
}
if limitVal, ok := limit.(int); ok {
find["limit"] = limitVal
}
if skipVal, ok := skip.(int); ok {
find["skip"] = skipVal
}
if sorts != nil {
sortsJSON, err := parseSortSyntax(sorts)
if err != nil {
return nil, err
}
find["sort"] = sortsJSON
}
if fields != nil {
find["fields"] = fields
}
if index != nil {
find["use_index"] = index
}
return d.queryJSON(find)
}
// QueryJSON returns documents using a declarative JSON querying syntax.
func (d *Database) QueryJSON(query string) ([]map[string]interface{}, error) {
queryMap := map[string]interface{}{}
err := json.Unmarshal([]byte(query), &queryMap)
if err != nil {
return nil, err
}
return d.queryJSON(queryMap)
}
func (d *Database) queryJSON(queryMap map[string]interface{}) ([]map[string]interface{}, error) {
_, data, err := d.resource.PostJSON("_find", nil, queryMap, nil)
if err != nil {
return nil, err
}
result, err := parseRaw(data)
if err != nil {
return nil, err
}
docs := []map[string]interface{}{}
err = json.Unmarshal(*result["docs"], &docs)
if err != nil {
return nil, err
}
return docs, nil
}
// parseSelectorSyntax returns a map representing the selector JSON struct.
func parseSelectorSyntax(selector string) (interface{}, error) {
// protect selector against query selector injection attacks
if strings.Contains(selector, "$") {
return nil, fmt.Errorf("no $s are allowed in selector: %s", selector)
}
// parse selector into abstract syntax tree (ast)
expr, err := parser.ParseExpr(selector)
if err != nil {
return nil, err
}
// recursively processing ast into json object
selectObj, err := parseAST(expr)
if err != nil {
return nil, err
}
return selectObj, nil
}
// parseSortSyntax returns a slice of sort JSON struct.
func parseSortSyntax(sorts []string) (interface{}, error) {
if sorts == nil {
return nil, nil
}
sortObjs := []interface{}{}
for _, sort := range sorts {
sortExpr, err := parser.ParseExpr(sort)
if err != nil {
return nil, err
}
sortObj, err := parseAST(sortExpr)
if err != nil {
return nil, err
}
sortObjs = append(sortObjs, sortObj)
}
return sortObjs, nil
}
// parseAST converts and returns a JSON struct according to
// CouchDB mango query syntax for the abstract syntax tree represented by expr.
func parseAST(expr ast.Expr) (interface{}, error) {
switch expr := expr.(type) {
case *ast.BinaryExpr:
// fmt.Println("BinaryExpr", expr)
return parseBinary(expr.Op, expr.X, expr.Y)
case *ast.UnaryExpr:
// fmt.Println("UnaryExpr", expr)
return parseUnary(expr.Op, expr.X)
case *ast.CallExpr:
// fmt.Println("CallExpr", expr, expr.Fun, expr.Args)
return parseFuncCall(expr.Fun, expr.Args)
case *ast.Ident:
// fmt.Println("Ident", expr)
switch expr.Name {
case "nil": // for nil value such as _id > nil
return nil, nil
case "true": // for boolean value true
return true, nil
case "false":
return false, nil // for boolean value false
default:
return expr.Name, nil
}
case *ast.BasicLit:
// fmt.Println("BasicLit", expr)
switch expr.Kind {
case token.INT:
intVal, err := strconv.Atoi(expr.Value)
if err != nil {
return nil, err
}
return intVal, nil
case token.FLOAT:
floatVal, err := strconv.ParseFloat(expr.Value, 64)
if err != nil {
return nil, err
}
return floatVal, nil
case token.STRING:
return strings.Trim(expr.Value, `"`), nil
default:
return nil, fmt.Errorf("token type %s not supported", expr.Kind.String())
}
case *ast.SelectorExpr:
// fmt.Println("SelectorExpr", expr.X, expr.Sel)
xExpr, err := parseAST(expr.X)
if err != nil {
return nil, err
}
return fmt.Sprintf("%s.%s", xExpr, expr.Sel.Name), nil
case *ast.ParenExpr:
pExpr, err := parseAST(expr.X)
if err != nil {
return nil, err
}
return pExpr, nil
case *ast.CompositeLit:
if _, ok := expr.Type.(*ast.ArrayType); !ok {
return nil, fmt.Errorf("not an ArrayType for a composite literal %v", expr.Type)
}
elements := make([]interface{}, len(expr.Elts))
for idx, elt := range expr.Elts {
e, err := parseAST(elt)
if err != nil {
return nil, err
}
elements[idx] = e
}
return elements, nil
default:
return nil, fmt.Errorf("expressions other than unary, binary and function call are not allowed %v", expr)
}
}
// parseBinary parses and returns a JSON struct according to
// CouchDB mango query syntax for the supported binary operators.
func parseBinary(operator token.Token, leftOperand, rightOperand ast.Expr) (interface{}, error) {
left, err := parseAST(leftOperand)
if err != nil {
return nil, err
}
right, err := parseAST(rightOperand)
if err != nil {
return nil, err
}
// <, <=, ==, !=, >=, >, &&, ||
switch operator {
case token.LSS:
return map[string]interface{}{
left.(string): map[string]interface{}{"$lt": right},
}, nil
case token.LEQ:
return map[string]interface{}{
left.(string): map[string]interface{}{"$lte": right},
}, nil
case token.EQL:
return map[string]interface{}{
left.(string): map[string]interface{}{"$eq": right},
}, nil
case token.NEQ:
return map[string]interface{}{
left.(string): map[string]interface{}{"$ne": right},
}, nil
case token.GEQ:
return map[string]interface{}{
left.(string): map[string]interface{}{"$gte": right},
}, nil
case token.GTR:
return map[string]interface{}{
left.(string): map[string]interface{}{"$gt": right},
}, nil
case token.LAND:
return map[string]interface{}{
"$and": []interface{}{left, right},
}, nil
case token.LOR:
return map[string]interface{}{
"$or": []interface{}{left, right},
}, nil
}
return nil, fmt.Errorf("binary operator %s not supported", operator)
}
// parseUnary parses and returns a JSON struct according to
// CouchDB mango query syntax for supported unary operators.
func parseUnary(operator token.Token, operandExpr ast.Expr) (interface{}, error) {
operand, err := parseAST(operandExpr)
if err != nil {
return nil, err
}
switch operator {
case token.NOT:
return map[string]interface{}{
"$not": operand,
}, nil
}
return nil, fmt.Errorf("unary operator %s not supported", operator)
}
// parseFuncCall parses and returns a JSON struct according to
// CouchDB mango query syntax for supported meta functions.
func parseFuncCall(funcExpr ast.Expr, args []ast.Expr) (interface{}, error) {
funcIdent := funcExpr.(*ast.Ident)
functionName := funcIdent.Name
switch functionName {
case "nor":
if len(args) < 1 {
return nil, fmt.Errorf("function nor(exprs...) need at least 1 arguments, not %d", len(args))
}
selectors := make([]interface{}, len(args))
for idx, arg := range args {
selector, err := parseAST(arg)
if err != nil {
return nil, err
}
selectors[idx] = selector
}
return map[string]interface{}{
"$nor": selectors,
}, nil
case "all":
if len(args) != 2 {
return nil, fmt.Errorf("function all(field, array) need 2 arguments, not %d", len(args))
}
fieldExpr, err := parseAST(args[0])
if err != nil {
return nil, err
}
if _, ok := fieldExpr.(string); !ok {
return nil, fmt.Errorf("invalid field expression type %s", fieldExpr)
}
arrayExpr, err := parseAST(args[1])
if err != nil {
return nil, err