forked from dapr/components-contrib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmongodb_query.go
176 lines (158 loc) · 4.11 KB
/
mongodb_query.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
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation and Dapr Contributors.
// Licensed under the MIT License.
// ------------------------------------------------------------
package mongodb
import (
"context"
"encoding/json"
"fmt"
"strconv"
"strings"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"github.com/dapr/components-contrib/state"
"github.com/dapr/components-contrib/state/query"
)
type Query struct {
query string
filter interface{}
opts *options.FindOptions
}
func (q *Query) VisitEQ(f *query.EQ) (string, error) {
// { <key>: <val> }
return fmt.Sprintf("{ %q: %q }", f.Key, f.Val), nil
}
func (q *Query) VisitIN(f *query.IN) (string, error) {
// { $in: [ <val1>, <val2>, ... , <valN> ] }
if len(f.Vals) == 0 {
return "", fmt.Errorf("empty IN operator for key %q", f.Key)
}
str := fmt.Sprintf(`{ %q: { "$in": [ %q`, f.Key, f.Vals[0])
for _, v := range f.Vals[1:] {
str += fmt.Sprintf(", %q", v)
}
str += " ] } }"
return str, nil
}
func (q *Query) visitFilters(op string, filters []query.Filter) (string, error) {
var (
arr []string
str string
err error
)
for _, fil := range filters {
switch f := fil.(type) {
case *query.EQ:
if str, err = q.VisitEQ(f); err != nil {
return "", err
}
arr = append(arr, str)
case *query.IN:
if str, err = q.VisitIN(f); err != nil {
return "", err
}
arr = append(arr, str)
case *query.OR:
if str, err = q.VisitOR(f); err != nil {
return "", err
}
arr = append(arr, str)
case *query.AND:
if str, err = q.VisitAND(f); err != nil {
return "", err
}
arr = append(arr, str)
default:
return "", fmt.Errorf("unsupported filter type %#v", f)
}
}
return fmt.Sprintf(`{ "%s": [ %s ] }`, op, strings.Join(arr, ", ")), nil
}
func (q *Query) VisitAND(f *query.AND) (string, error) {
// { $and: [ { <expression1> }, { <expression2> } , ... , { <expressionN> } ] }
return q.visitFilters("$and", f.Filters)
}
func (q *Query) VisitOR(f *query.OR) (string, error) {
// { $or: [ { <expression1> }, { <expression2> } , ... , { <expressionN> } ] }
return q.visitFilters("$or", f.Filters)
}
func (q *Query) Finalize(filters string, qq *query.Query) error {
q.query = filters
if len(filters) == 0 {
q.filter = bson.D{}
} else if err := bson.UnmarshalExtJSON([]byte(filters), false, &q.filter); err != nil {
return err
}
q.opts = options.Find()
// sorting
if len(qq.Sort) > 0 {
sort := bson.D{}
for _, s := range qq.Sort {
order := 1 // ascending
if s.Order == query.DESC {
order = -1
}
sort = append(sort, bson.E{Key: s.Key, Value: order})
}
q.opts.SetSort(sort)
}
// pagination
if qq.Page.Limit > 0 {
q.opts.SetLimit(int64(qq.Page.Limit))
}
if len(qq.Page.Token) != 0 {
skip, err := strconv.ParseInt(qq.Page.Token, 10, 64)
if err != nil {
return err
}
q.opts.SetSkip(skip)
}
return nil
}
func (q *Query) execute(ctx context.Context, collection *mongo.Collection) ([]state.QueryItem, string, error) {
cur, err := collection.Find(ctx, q.filter, []*options.FindOptions{q.opts}...)
if err != nil {
return nil, "", err
}
defer cur.Close(ctx)
ret := []state.QueryItem{}
for cur.Next(ctx) {
var item Item
if err = cur.Decode(&item); err != nil {
return nil, "", err
}
result := state.QueryItem{
Key: item.Key,
ETag: &item.Etag,
}
switch obj := item.Value.(type) {
case string:
result.Data = []byte(obj)
case primitive.D:
if result.Data, err = bson.MarshalExtJSON(obj, true, true); err != nil {
result.Error = err.Error()
}
default:
if result.Data, err = json.Marshal(item.Value); err != nil {
result.Error = err.Error()
}
}
ret = append(ret, result)
}
if err = cur.Err(); err != nil {
return nil, "", err
}
// set next query token only if limit is specified
var token string
if q.opts.Limit != nil && *q.opts.Limit != 0 {
var skip int64
if q.opts.Skip != nil {
skip = *q.opts.Skip
}
token = strconv.FormatInt(skip+int64(len(ret)), 10)
}
return ret, token, nil
}