/
read.go
369 lines (314 loc) · 10.2 KB
/
read.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
package mgo
import (
"context"
"errors"
"fmt"
"strings"
"time"
"github.com/spaceuptech/helpers"
"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/spaceuptech/space-cloud/gateway/model"
"github.com/spaceuptech/space-cloud/gateway/utils"
)
// Read queries document(s) from the database
func (m *Mongo) Read(ctx context.Context, col string, req *model.ReadRequest) (int64, interface{}, map[string]map[string]string, *model.SQLMetaData, error) {
if req.Options != nil && len(req.Options.Join) > 0 {
return 0, nil, nil, nil, errors.New("cannot perform joins in mongo db")
}
collection := m.getClient().Database(m.dbName).Collection(col)
req.Find = sanitizeWhereClause(ctx, col, req.Find)
if req.Options == nil {
req.Options = &model.ReadOptions{}
}
if req.Options.Limit == nil {
req.Options.Limit = m.queryFetchLimit
req.Options.HasOptions = true
}
switch req.Operation {
case utils.Count:
countOptions := options.Count()
count, err := collection.CountDocuments(ctx, req.Find, countOptions)
if err != nil {
return 0, nil, nil, nil, err
}
return count, count, nil, nil, nil
case utils.Distinct:
distinct := req.Options.Distinct
if distinct == nil {
return 0, nil, nil, nil, utils.ErrInvalidParams
}
result, err := collection.Distinct(ctx, *distinct, req.Find)
if err != nil {
return 0, nil, nil, nil, err
}
// convert result []string to []map[string]interface
finalResult := []interface{}{}
for _, value := range result {
doc := map[string]interface{}{}
doc[*distinct] = value
finalResult = append(finalResult, doc)
}
return int64(len(result)), finalResult, nil, nil, nil
case utils.All:
findOptions := options.Find()
if req.Options != nil {
if req.Options.Select != nil {
findOptions = findOptions.SetProjection(req.Options.Select)
}
if req.Options.Skip != nil {
findOptions = findOptions.SetSkip(*req.Options.Skip)
}
if req.Options.Limit != nil {
findOptions = findOptions.SetLimit(*req.Options.Limit)
}
if req.Options.Sort != nil {
findOptions = findOptions.SetSort(generateSortOptions(req.Options.Sort))
}
}
pipeline := make([]bson.M, 0)
if len(req.Aggregate) > 0 {
if len(req.Find) > 0 {
pipeline = append(pipeline, bson.M{"$match": req.Find})
}
sortFields := make([]string, 0)
functionsMap := make(bson.M)
for function, colArray := range req.Aggregate {
for _, column := range colArray {
asColumnName := getAggregateAsColumnName(function, column)
switch function {
case "sum":
getGroupByStageFunctionsMap(functionsMap, asColumnName, function, getAggregateColumnName(column))
case "min":
getGroupByStageFunctionsMap(functionsMap, asColumnName, function, getAggregateColumnName(column))
case "max":
getGroupByStageFunctionsMap(functionsMap, asColumnName, function, getAggregateColumnName(column))
case "avg":
getGroupByStageFunctionsMap(functionsMap, asColumnName, function, getAggregateColumnName(column))
case "count":
getGroupByStageFunctionsMap(functionsMap, asColumnName, function, "*")
default:
return 0, nil, nil, nil, helpers.Logger.LogError(helpers.GetRequestID(ctx), fmt.Sprintf(`Unknown aggregate funcion %s`, function), nil, map[string]interface{}{})
}
for _, field := range req.Options.Sort {
if sortValue := generateSortFields(field, column, asColumnName); sortValue != "" {
sortFields = append(sortFields, sortValue)
}
}
}
}
groupStage, sortArr := createGroupByStage(functionsMap, req.GroupBy, req.Options.Sort)
sortFields = append(sortFields, sortArr...)
pipeline = append(pipeline, groupStage)
if req.Options != nil {
pipeline = append(pipeline, getOptionStage(req.Options, sortFields)...)
}
}
var cur *mongo.Cursor
var err error
results := []interface{}{}
if len(req.Aggregate) > 0 {
helpers.Logger.LogDebug(helpers.GetRequestID(ctx), "Mongo aggregate", map[string]interface{}{"col": col, "pipeline": pipeline})
cur, err = collection.Aggregate(ctx, pipeline)
} else {
helpers.Logger.LogDebug(helpers.GetRequestID(ctx), "Mongo query", map[string]interface{}{"col": col, "find": req.Find, "options": findOptions})
cur, err = collection.Find(ctx, req.Find, findOptions)
}
if err != nil {
return 0, nil, nil, nil, err
}
defer func() { _ = cur.Close(ctx) }()
var count int64
// Finding multiple documents returns a cursor
// Iterating through the cursor allows us to decode documents one at a time
for cur.Next(ctx) {
// Increment the counter
count++
// Read the document
var doc map[string]interface{}
err := cur.Decode(&doc)
if err != nil {
return 0, nil, nil, nil, err
}
if req.Options.Debug {
doc["_dbFetchTs"] = time.Now().Format(time.RFC3339Nano)
}
// doc["_dbFetchTs"] = time.Now().Format(time.RFC3339Nano)
if len(req.Aggregate) > 0 {
getNestedObject(doc)
}
results = append(results, doc)
}
if err := cur.Err(); err != nil {
return 0, nil, nil, nil, err
}
return count, results, nil, nil, nil
case utils.One:
findOneOptions := options.FindOne()
if req.Options != nil {
if req.Options.Select != nil {
findOneOptions = findOneOptions.SetProjection(req.Options.Select)
}
if req.Options.Skip != nil {
findOneOptions = findOneOptions.SetSkip(*req.Options.Skip)
}
if req.Options.Sort != nil {
findOneOptions = findOneOptions.SetSort(generateSortOptions(req.Options.Sort))
}
}
var res map[string]interface{}
err := collection.FindOne(ctx, req.Find, findOneOptions).Decode(&res)
if err != nil {
return 0, nil, nil, nil, err
}
if req.Options.Debug {
res["_dbFetchTs"] = time.Now().Format(time.RFC3339Nano)
}
return 1, res, nil, nil, nil
default:
return 0, nil, nil, nil, utils.ErrInvalidParams
}
}
func generateSortFields(sortColumn, currentColumn, newColumnName string) string {
isDescending := false
if strings.HasPrefix(sortColumn, "-") {
isDescending = true
sortColumn = strings.TrimPrefix(sortColumn, "-")
}
if sortColumn == currentColumn {
if isDescending {
return "-" + newColumnName
}
return newColumnName
}
return ""
}
func generateSortOptions(array []string) bson.D {
sort := bson.D{}
for _, value := range array {
if strings.HasPrefix(value, "-") {
sort = append(sort, primitive.E{Key: strings.TrimPrefix(value, "-"), Value: -1})
} else {
sort = append(sort, primitive.E{Key: value, Value: 1})
}
}
return sort
}
func getGroupByStageFunctionsMap(functionsMap bson.M, asColumnName, function, column string) {
if column != "*" {
functionsMap[asColumnName] = bson.M{
fmt.Sprintf("$%s", function): fmt.Sprintf("$%s", column),
}
} else {
functionsMap[asColumnName] = bson.M{
"$sum": 1,
}
}
}
func createGroupByStage(functionsMap bson.M, groupBy []interface{}, sort []string) (bson.M, []string) {
groupByMap := make(map[string]interface{})
groupStage := bson.M{
"$group": bson.M{"_id": bson.M{}},
}
sortArr := make([]string, 0)
if len(groupBy) > 0 {
for _, val := range groupBy {
key := fmt.Sprintf("%v", val)
value := fmt.Sprintf("$%v", val)
groupByMap[key] = value
for _, sortKey := range sort {
if sortValue := generateSortFields(sortKey, key, "_id."+key); sortValue != "" {
sortArr = append(sortArr, sortValue)
}
}
}
groupStage["$group"].(bson.M)["_id"] = groupByMap
}
for key, value := range functionsMap {
groupStage["$group"].(bson.M)[key] = value
}
return groupStage, sortArr
}
func generateAggregateSortOptions(array []string) bson.M {
sort := bson.M{}
for _, value := range array {
if strings.HasPrefix(value, "-") {
sort[strings.TrimPrefix(value, "-")] = -1
} else {
sort[value] = 1
}
}
return sort
}
func getOptionStage(options *model.ReadOptions, sortFields []string) []bson.M {
var optionStage []bson.M
if options.Skip != nil {
// NOTE: we are sorting the result before skip operation to give a consistent $skip result
optionStage = append(optionStage, bson.M{"$sort": generateAggregateSortOptions([]string{"_id"})})
optionStage = append(optionStage, bson.M{"$skip": options.Skip})
}
if options.Limit != nil {
optionStage = append(optionStage, bson.M{"$sort": generateAggregateSortOptions([]string{"_id"})})
optionStage = append(optionStage, bson.M{"$limit": options.Limit})
}
if options.Sort != nil {
optionStage = append(optionStage, bson.M{"$sort": generateAggregateSortOptions(sortFields)})
}
return optionStage
}
func getAggregateColumnName(column string) string {
return strings.Split(column, ":")[1]
}
func getAggregateAsColumnName(function, column string) string {
format := "nested"
arr := strings.Split(column, ":")
returnField := arr[0]
column = arr[1]
if len(arr) == 3 && arr[2] == "table" {
format = "table"
}
return fmt.Sprintf("%s___%s___%s___%s___%s", utils.GraphQLAggregate, format, returnField, function, strings.Join(strings.Split(column, "."), "__"))
}
func splitAggregateAsColumnName(asColumnName string) (format, returnField, functionName, columnName string, isAggregateColumn bool) {
v := strings.Split(asColumnName, "___")
if len(v) != 5 || !strings.HasPrefix(asColumnName, utils.GraphQLAggregate) {
return "", "", "", "", false
}
return v[1], v[2], v[3], v[4], true
}
func getNestedObject(doc map[string]interface{}) {
resultObj := make(map[string]interface{})
for asColumnName, value := range doc {
format, returnField, functionName, columnName, isAggregateColumn := splitAggregateAsColumnName(asColumnName)
if isAggregateColumn {
delete(doc, asColumnName)
if format == "table" {
doc[returnField] = value
continue
}
funcValue, ok := resultObj[functionName]
if !ok {
// NOTE: This case occurs for count function with no column name (using * operator instead)
if columnName == "" {
resultObj[functionName] = value
} else {
resultObj[functionName] = map[string]interface{}{columnName: value}
}
continue
}
funcValue.(map[string]interface{})[columnName] = value
}
groupDoc, ok := doc["_id"]
if ok {
for key, value := range groupDoc.(map[string]interface{}) {
doc[key] = value
}
}
}
if len(resultObj) > 0 {
doc[utils.GraphQLAggregate] = resultObj
}
delete(doc, "_id")
}