-
Notifications
You must be signed in to change notification settings - Fork 198
/
select_agg_handler.go
319 lines (269 loc) · 7.62 KB
/
select_agg_handler.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
package elasticsql
import (
"encoding/json"
"errors"
"strings"
"github.com/xwb1989/sqlparser"
)
// msi stands for map[string]interface{}
type msi map[string]interface{}
func handleFuncInSelectAgg(funcExprArr []*sqlparser.FuncExpr) msi {
var innerAggMap = make(msi)
for _, v := range funcExprArr {
//func expressions will use the same parent bucket
aggName := strings.ToUpper(v.Name.String()) + `(` + sqlparser.String(v.Exprs) + `)`
switch v.Name.Lowered() {
case "count":
//count need to distinguish * and normal field name
if sqlparser.String(v.Exprs) == "*" {
innerAggMap[aggName] = msi{
"value_count": msi{
"field": "_index",
},
}
} else {
// support count(distinct field)
if v.Distinct {
innerAggMap[aggName] = msi{
"cardinality": msi{
"field": sqlparser.String(v.Exprs),
},
}
} else {
innerAggMap[aggName] = msi{
"value_count": msi{
"field": sqlparser.String(v.Exprs),
},
}
}
}
default:
// support min/avg/max/stats
// extended_stats/percentiles
innerAggMap[aggName] = msi{
v.Name.String(): msi{
"field": sqlparser.String(v.Exprs),
},
}
}
}
return innerAggMap
}
func handleGroupByColName(colName *sqlparser.ColName, index int, child msi) msi {
innerMap := make(msi)
if index == 0 {
innerMap["terms"] = msi{
"field": colName.Name.String(),
"size": 200, // this size may need to change ?
}
} else {
innerMap["terms"] = msi{
"field": colName.Name.String(),
"size": 0,
}
}
if len(child) > 0 {
innerMap["aggregations"] = child
}
return msi{colName.Name.String(): innerMap}
}
func handleGroupByFuncExprDateHisto(funcExpr *sqlparser.FuncExpr) (msi, error) {
innerMap := make(msi)
var (
// default
field = ""
interval = "1h"
format = "yyyy-MM-dd HH:mm:ss"
)
//get field/interval and format
for _, expr := range funcExpr.Exprs {
// the expression in date_histogram must be like a = b format
switch item := expr.(type) {
case *sqlparser.AliasedExpr:
//nonStarExpr := expr.(*sqlparser.NonStarExpr)
comparisonExpr, ok := item.Expr.(*sqlparser.ComparisonExpr)
if !ok {
return nil, errors.New("elasticsql: unsupported expression in date_histogram")
}
left, ok := comparisonExpr.Left.(*sqlparser.ColName)
if !ok {
return nil, errors.New("elaticsql: param error in date_histogram")
}
rightStr := sqlparser.String(comparisonExpr.Right)
rightStr = strings.Replace(rightStr, `'`, ``, -1)
if left.Name.Lowered() == "field" {
field = rightStr
}
if left.Name.Lowered() == "value" || left.Name.Lowered() == "interval" {
interval = rightStr
}
if left.Name.Lowered() == "format" {
format = rightStr
}
innerMap["date_histogram"] = msi{
"field": field,
"interval": interval,
"format": format,
}
default:
return nil, errors.New("elasticsql: unsupported expression in date_histogram")
}
}
return innerMap, nil
}
func handleGroupByFuncExprRange(funcExpr *sqlparser.FuncExpr) (msi, error) {
if len(funcExpr.Exprs) < 3 {
return nil, errors.New("elasticsql: length of function range params must be > 3")
}
var innerMap = make(msi)
rangeMapList := make([]msi, len(funcExpr.Exprs)-2)
for i := 1; i < len(funcExpr.Exprs)-1; i++ {
valFrom := sqlparser.String(funcExpr.Exprs[i])
valTo := sqlparser.String(funcExpr.Exprs[i+1])
rangeMapList[i-1] = msi{
"from": valFrom,
"to": valTo,
}
}
innerMap[funcExpr.Name.String()] = msi{
"field": sqlparser.String(funcExpr.Exprs[0]),
"ranges": rangeMapList,
}
return innerMap, nil
}
func handleGroupByFuncExprDateRange(funcExpr *sqlparser.FuncExpr) (msi, error) {
var innerMap msi
var (
field string
format = "yyyy-MM-dd HH:mm:ss"
rangeList = []string{}
rangeMapList = []msi{}
)
for _, expr := range funcExpr.Exprs {
nonStarExpr, ok := expr.(*sqlparser.AliasedExpr)
if !ok {
return nil, errors.New("elasticsql: unsupported star expression in function date_range")
}
switch item := nonStarExpr.Expr.(type) {
case *sqlparser.ComparisonExpr:
colName := sqlparser.String(item.Left)
equalVal := sqlparser.String(item.Right.(*sqlparser.SQLVal))
//fmt.Printf("%#v", sqlparser.String(item.Right))
equalVal = strings.Trim(equalVal, `'`)
switch colName {
case "field":
field = equalVal
case "format":
format = equalVal
default:
return nil, errors.New("elasticsql: unsupported column name " + colName)
}
case *sqlparser.SQLVal:
skippedString := strings.Trim(sqlparser.String(item), "`")
rangeList = append(rangeList, skippedString)
default:
return nil, errors.New("elasticsql: unsupported expression " + sqlparser.String(expr))
}
}
if len(field) == 0 {
return nil, errors.New("elasticsql: lack field of date_range")
}
for i := 0; i < len(rangeList)-1; i++ {
tmpMap := msi{
"from": strings.Trim(rangeList[i], `'`),
"to": strings.Trim(rangeList[i+1], `'`),
}
rangeMapList = append(rangeMapList, tmpMap)
}
innerMap = msi{
"date_range": msi{
"field": field,
"ranges": rangeMapList,
"format": format,
},
}
return innerMap, nil
}
func handleGroupByFuncExpr(funcExpr *sqlparser.FuncExpr, child msi) (msi, error) {
var innerMap msi
var err error
switch funcExpr.Name.Lowered() {
case "date_histogram":
innerMap, err = handleGroupByFuncExprDateHisto(funcExpr)
case "range":
innerMap, err = handleGroupByFuncExprRange(funcExpr)
case "date_range":
innerMap, err = handleGroupByFuncExprDateRange(funcExpr)
default:
return nil, errors.New("elasticsql: unsupported group by functions" + sqlparser.String(funcExpr))
}
if err != nil {
return nil, err
}
if len(child) > 0 && innerMap != nil {
innerMap["aggregations"] = child
}
stripedFuncExpr := sqlparser.String(funcExpr)
stripedFuncExpr = strings.Replace(stripedFuncExpr, " ", "", -1)
stripedFuncExpr = strings.Replace(stripedFuncExpr, "'", "", -1)
return msi{stripedFuncExpr: innerMap}, nil
}
func handleGroupByAgg(groupBy sqlparser.GroupBy, innerMap msi) (msi, error) {
var aggMap = make(msi)
var child = innerMap
for i := len(groupBy) - 1; i >= 0; i-- {
v := groupBy[i]
switch item := v.(type) {
case *sqlparser.ColName:
currentMap := handleGroupByColName(item, i, child)
child = currentMap
case *sqlparser.FuncExpr:
currentMap, err := handleGroupByFuncExpr(item, child)
if err != nil {
return nil, err
}
child = currentMap
}
}
aggMap = child
return aggMap, nil
}
func buildAggs(sel *sqlparser.Select) (string, error) {
funcExprArr, _, funcErr := extractFuncAndColFromSelect(sel.SelectExprs)
innerAggMap := handleFuncInSelectAgg(funcExprArr)
if funcErr != nil {
}
aggMap, err := handleGroupByAgg(sel.GroupBy, innerAggMap)
if err != nil {
return "", err
}
mapJSON, _ := json.Marshal(aggMap)
return string(mapJSON), nil
}
// extract func expressions from select exprs
func extractFuncAndColFromSelect(sqlSelect sqlparser.SelectExprs) ([]*sqlparser.FuncExpr, []*sqlparser.ColName, error) {
var colArr []*sqlparser.ColName
var funcArr []*sqlparser.FuncExpr
for _, v := range sqlSelect {
// non star expressioin means column name
// or some aggregation functions
expr, ok := v.(*sqlparser.AliasedExpr)
if !ok {
// no need to handle, star expression * just skip is ok
continue
}
// NonStarExpr start
switch expr.Expr.(type) {
case *sqlparser.FuncExpr:
funcExpr := expr.Expr.(*sqlparser.FuncExpr)
funcArr = append(funcArr, funcExpr)
case *sqlparser.ColName:
continue
default:
//ignore
}
//starExpression like *, table.* should be ignored
//'cause it is meaningless to set fields in elasticsearch aggs
}
return funcArr, colArr, nil
}