-
Notifications
You must be signed in to change notification settings - Fork 375
/
operators.go
299 lines (276 loc) · 7.81 KB
/
operators.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
// Copyright 2021 FerretDB Inc.
//
// 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 operators provides aggregation operators.
// Operators are used in aggregation stages to filter and model data.
// This package contains all operators apart from the accumulation operators,
// which are stored and described in accumulators package.
//
// Accumulators that can be used outside of accumulation with different behaviour (like `$sum`),
// should be stored in both operators and accumulators packages.
package operators
import (
"errors"
"fmt"
"strings"
"github.com/FerretDB/FerretDB/internal/types"
"github.com/FerretDB/FerretDB/internal/util/iterator"
"github.com/FerretDB/FerretDB/internal/util/lazyerrors"
"github.com/FerretDB/FerretDB/internal/util/must"
)
// newOperatorFunc is a type for a function that creates a standard aggregation operator.
//
// By standard aggregation operator we mean any operator that is not accumulator.
// While accumulators perform operations on multiple documents
// (for example `$count` can count documents in each `$group` group),
// standard operators perform operations on a single document.
// It takes the arguments extracted from the document, and not the
// whole array/document.
type newOperatorFunc func(args ...any) (Operator, error)
// Operator is a common interface for standard aggregation operators.
type Operator interface {
// Process document and returns the result of applying operator.
Process(in *types.Document) (any, error)
}
// IsOperator returns true if provided document should be
// treated as operator document.
func IsOperator(doc *types.Document) bool {
iter := doc.Iterator()
defer iter.Close()
for {
key, _, err := iter.Next()
if err != nil {
if errors.Is(err, iterator.ErrIteratorDone) {
break
}
return false
}
if strings.HasPrefix(key, "$") {
return true
}
}
return false
}
// NewOperator returns operator from provided document.
// The document should look like: `{<$operator>: <operator-value>}`.
//
// Before calling NewOperator on document it's recommended to validate
// document before by using IsOperator on it.
func NewOperator(doc *types.Document) (Operator, error) {
if doc.Len() == 0 {
return nil, lazyerrors.New(
"The operator field is empty",
)
}
if doc.Len() > 1 {
return nil, newOperatorError(
ErrTooManyFields,
doc.Command(),
"The operator field specifies more than one operator",
)
}
operator := doc.Command()
newOperator, supported := Operators[operator]
_, unsupported := unsupportedOperators[operator]
expr := must.NotFail(doc.Get(operator))
var args []any
if arr, ok := expr.(*types.Array); ok {
iter := arr.Iterator()
defer iter.Close()
for {
_, v, err := iter.Next()
if errors.Is(err, iterator.ErrIteratorDone) {
break
}
args = append(args, v)
}
} else {
args = append(args, expr)
}
switch {
case supported:
return newOperator(args...)
case unsupported:
return nil, newOperatorError(
ErrNotImplemented,
operator,
fmt.Sprintf("The operator %s is not implemented yet", operator),
)
default:
return nil, newOperatorError(
ErrInvalidExpression,
operator,
fmt.Sprintf("Unrecognized expression '%s'", operator),
)
}
}
// Operators maps all standard aggregation operators.
var Operators = map[string]newOperatorFunc{
// sorted alphabetically
"$sum": newSum,
"$type": newType,
// please keep sorted alphabetically
}
// unsupportedOperators maps all unsupported yet operators.
var unsupportedOperators = map[string]struct{}{
// sorted alphabetically
"$abs": {},
"$acos": {},
"$acosh": {},
"$add": {},
"$allElementsTrue": {},
"$and": {},
"$anyElementTrue": {},
"$arrayElemAt": {},
"$arrayToObject": {},
"$asin": {},
"$asinh": {},
"$atan": {},
"$atan2": {},
"$atanh": {},
"$avg": {},
"$binarySize": {},
"$bsonSize": {},
"$ceil": {},
"$cmp": {},
"$concat": {},
"$concatArrays": {},
"$cond": {},
"$convert": {},
"$cos": {},
"$cosh": {},
"$covariancePop": {},
"$covarianceSamp": {},
"$dateAdd": {},
"$dateDiff": {},
"$dateFromParts": {},
"$dateSubtract": {},
"$dateTrunc": {},
"$dateToParts": {},
"$dateFromString": {},
"$dateToString": {},
"$dayOfMonth": {},
"$dayOfWeek": {},
"$dayOfYear": {},
"$degreesToRadians": {},
"$denseRank": {},
"$derivative": {},
"$divide": {},
"$documentNumber": {},
"$eq": {},
"$exp": {},
"$expMovingAvg": {},
"$filter": {},
"$floor": {},
"$function": {},
"$getField": {},
"$gt": {},
"$gte": {},
"$hour": {},
"$ifNull": {},
"$in": {},
"$indexOfArray": {},
"$indexOfBytes": {},
"$indexOfCP": {},
"$integral": {},
"$isArray": {},
"$isNumber": {},
"$isoDayOfWeek": {},
"$isoWeek": {},
"$isoWeekYear": {},
"$let": {},
"$linearFill": {},
"$literal": {},
"$ln": {},
"$locf": {},
"$log": {},
"$log10": {},
"$lt": {},
"$lte": {},
"$ltrim": {},
"$map": {},
"$max": {},
"$meta": {},
"$min": {},
"$minN": {},
"$millisecond": {},
"$minute": {},
"$mod": {},
"$month": {},
"$multiply": {},
"$ne": {},
"$not": {},
"$objectToArray": {},
"$or": {},
"$pow": {},
"$radiansToDegrees": {},
"$rand": {},
"$range": {},
"$rank": {},
"$reduce": {},
"$regexFind": {},
"$regexFindAll": {},
"$regexMatch": {},
"$replaceOne": {},
"$replaceAll": {},
"$reverseArray": {},
"$round": {},
"$rtrim": {},
"$sampleRate": {},
"$second": {},
"$setDifference": {},
"$setEquals": {},
"$setField": {},
"$setIntersection": {},
"$setIsSubset": {},
"$setUnion": {},
"$shift": {},
"$size": {},
"$sin": {},
"$sinh": {},
"$slice": {},
"$sortArray": {},
"$split": {},
"$sqrt": {},
"$stdDevPop": {},
"$stdDevSamp": {},
"$strcasecmp": {},
"$strLenBytes": {},
"$strLenCP": {},
"$substr": {},
"$substrBytes": {},
"$substrCP": {},
"$subtract": {},
"$switch": {},
"$tan": {},
"$tanh": {},
"$toBool": {},
"$toDate": {},
"$toDecimal": {},
"$toDouble": {},
"$toInt": {},
"$toLong": {},
"$toObjectId": {},
"$toString": {},
"$toLower": {},
"$toUpper": {},
"$trim": {},
"$trunc": {},
"$tsIncrement": {},
"$tsSecond": {},
"$unsetField": {},
"$week": {},
"$year": {},
"$zip": {},
// please keep sorted alphabetically
}