forked from cch123/elasticsql
-
Notifications
You must be signed in to change notification settings - Fork 1
/
select_handler.go
339 lines (290 loc) · 9.9 KB
/
select_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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
package elasticsql
import (
"errors"
"fmt"
"strings"
"github.com/xwb1989/sqlparser"
)
func handleSelect(sel *sqlparser.Select) (dsl string, esType string, err error) {
// Handle where
// top level node pass in an empty interface
// to tell the children this is root
// is there any better way?
var rootParent sqlparser.Expr
var defaultQueryMapStr = `{"bool" : {"must": [{"match_all" : {}}]}}`
var queryMapStr string
// use may not pass where clauses
if sel.Where != nil {
queryMapStr, err = handleSelectWhere(&sel.Where.Expr, true, &rootParent)
if err != nil {
return "", "", err
}
}
if queryMapStr == "" {
queryMapStr = defaultQueryMapStr
}
//TODO support multiple tables
//for i, fromExpr := range sel.From {
// fmt.Printf("the %d of from is %#v\n", i, sqlparser.String(fromExpr))
//}
//Handle from
if len(sel.From) != 1 {
return "", "", errors.New("elasticsql: multiple from currently not supported")
}
esType = sqlparser.String(sel.From)
esType = strings.Replace(esType, "`", "", -1)
queryFrom, querySize := "0", "1"
aggFlag := false
// if the request is to aggregation
// then set aggFlag to true, and querySize to 0
// to not return any query result
var aggStr string
if len(sel.GroupBy) > 0 || checkNeedAgg(sel.SelectExprs) {
aggFlag = true
querySize = "0"
aggStr, err = buildAggs(sel)
if err != nil {
//aggStr = ""
return "", "", err
}
}
// Handle limit
if sel.Limit != nil {
if sel.Limit.Offset != nil {
queryFrom = sqlparser.String(sel.Limit.Offset)
}
querySize = sqlparser.String(sel.Limit.Rowcount)
}
// Handle order by
// when executating aggregations, order by is useless
var orderByArr []string
if aggFlag == false {
for _, orderByExpr := range sel.OrderBy {
orderByStr := fmt.Sprintf(`{"%v": "%v"}`, strings.Replace(sqlparser.String(orderByExpr.Expr), "`", "", -1), orderByExpr.Direction)
orderByArr = append(orderByArr, orderByStr)
}
}
resultMap := make(map[string]interface{})
resultMap["query"] = queryMapStr
resultMap["from"] = queryFrom
resultMap["size"] = querySize
if len(aggStr) > 0 {
resultMap["aggregations"] = aggStr
}
if len(orderByArr) > 0 {
resultMap["sort"] = fmt.Sprintf("[%v]", strings.Join(orderByArr, ","))
}
// keep the travesal in order, avoid unpredicted json
var keySlice = []string{"query", "from", "size", "sort", "aggregations"}
var resultArr []string
for _, mapKey := range keySlice {
if val, ok := resultMap[mapKey]; ok {
resultArr = append(resultArr, fmt.Sprintf(`"%v" : %v`, mapKey, val))
}
}
dsl = "{" + strings.Join(resultArr, ",") + "}"
return dsl, esType, nil
}
// if the where is empty, need to check whether to agg or not
func checkNeedAgg(sqlSelect sqlparser.SelectExprs) bool {
for _, v := range sqlSelect {
expr, ok := v.(*sqlparser.AliasedExpr)
if !ok {
// no need to handle, star expression * just skip is ok
continue
}
//TODO more precise
if _, ok := expr.Expr.(*sqlparser.FuncExpr); ok {
return true
}
}
return false
}
func buildNestedFuncStrValue(nestedFunc *sqlparser.FuncExpr) (string, error) {
return "", errors.New("elasticsql: unsupported function" + nestedFunc.Name.String())
}
func handleSelectWhereAndExpr(expr *sqlparser.Expr, topLevel bool, parent *sqlparser.Expr) (string, error) {
andExpr := (*expr).(*sqlparser.AndExpr)
leftExpr := andExpr.Left
rightExpr := andExpr.Right
leftStr, err := handleSelectWhere(&leftExpr, false, expr)
if err != nil {
return "", err
}
rightStr, err := handleSelectWhere(&rightExpr, false, expr)
if err != nil {
return "", err
}
// not toplevel
// if the parent node is also and, then the result can be merged
var resultStr string
if leftStr == "" || rightStr == "" {
resultStr = leftStr + rightStr
} else {
resultStr = leftStr + `,` + rightStr
}
if _, ok := (*parent).(*sqlparser.AndExpr); ok {
return resultStr, nil
}
return fmt.Sprintf(`{"bool" : {"must" : [%v]}}`, resultStr), nil
}
func handleSelectWhereOrExpr(expr *sqlparser.Expr, topLevel bool, parent *sqlparser.Expr) (string, error) {
orExpr := (*expr).(*sqlparser.OrExpr)
leftExpr := orExpr.Left
rightExpr := orExpr.Right
leftStr, err := handleSelectWhere(&leftExpr, false, expr)
if err != nil {
return "", err
}
rightStr, err := handleSelectWhere(&rightExpr, false, expr)
if err != nil {
return "", err
}
var resultStr string
if leftStr == "" || rightStr == "" {
resultStr = leftStr + rightStr
} else {
resultStr = leftStr + `,` + rightStr
}
// not toplevel
// if the parent node is also or node, then merge the query param
if _, ok := (*parent).(*sqlparser.OrExpr); ok {
return resultStr, nil
}
return fmt.Sprintf(`{"bool" : {"should" : [%v]}}`, resultStr), nil
}
func buildComparisonExprRightStr(expr sqlparser.Expr) (string, bool, error) {
var rightStr string
var err error
var missingCheck = false
switch expr.(type) {
case *sqlparser.SQLVal:
rightStr = sqlparser.String(expr)
rightStr = strings.Trim(rightStr, `'`)
case *sqlparser.GroupConcatExpr:
return "", missingCheck, errors.New("elasticsql: group_concat not supported")
case *sqlparser.FuncExpr:
// parse nested
funcExpr := expr.(*sqlparser.FuncExpr)
rightStr, err = buildNestedFuncStrValue(funcExpr)
if err != nil {
return "", missingCheck, err
}
case *sqlparser.ColName:
if sqlparser.String(expr) == "missing" {
missingCheck = true
return "", missingCheck, nil
}
return "", missingCheck, errors.New("elasticsql: column name on the right side of compare operator is not supported")
case sqlparser.ValTuple:
rightStr = sqlparser.String(expr)
default:
// cannot reach here
}
return rightStr, missingCheck, err
}
func handleSelectWhereComparisonExpr(expr *sqlparser.Expr, topLevel bool, parent *sqlparser.Expr) (string, error) {
comparisonExpr := (*expr).(*sqlparser.ComparisonExpr)
colName, ok := comparisonExpr.Left.(*sqlparser.ColName)
if !ok {
return "", errors.New("elasticsql: invalid comparison expression, the left must be a column name")
}
colNameStr := sqlparser.String(colName)
colNameStr = strings.Replace(colNameStr, "`", "", -1)
rightStr, missingCheck, err := buildComparisonExprRightStr(comparisonExpr.Right)
if err != nil {
return "", err
}
resultStr := ""
switch comparisonExpr.Operator {
case ">=":
resultStr = fmt.Sprintf(`{"range" : {"%v" : {"from" : "%v"}}}`, colNameStr, rightStr)
case "<=":
resultStr = fmt.Sprintf(`{"range" : {"%v" : {"to" : "%v"}}}`, colNameStr, rightStr)
case "=":
// field is missing
if missingCheck {
resultStr = fmt.Sprintf(`{"missing":{"field":"%v"}}`, colNameStr)
} else {
resultStr = fmt.Sprintf(`{"match_phrase" : {"%v" : {"query" : "%v"}}}`, colNameStr, rightStr)
}
case ">":
resultStr = fmt.Sprintf(`{"range" : {"%v" : {"gt" : "%v"}}}`, colNameStr, rightStr)
case "<":
resultStr = fmt.Sprintf(`{"range" : {"%v" : {"lt" : "%v"}}}`, colNameStr, rightStr)
case "!=":
if missingCheck {
resultStr = fmt.Sprintf(`{"bool" : {"must_not" : [{"missing":{"field":"%v"}}]}}`, colNameStr)
} else {
resultStr = fmt.Sprintf(`{"bool" : {"must_not" : [{"match_phrase" : {"%v" : {"query" : "%v"}}}]}}`, colNameStr, rightStr)
}
case "in":
// the default valTuple is ('1', '2', '3') like
// so need to drop the () and replace ' to "
rightStr = strings.Replace(rightStr, `'`, `"`, -1)
rightStr = strings.Trim(rightStr, "(")
rightStr = strings.Trim(rightStr, ")")
resultStr = fmt.Sprintf(`{"terms" : {"%v" : [%v]}}`, colNameStr, rightStr)
case "like":
rightStr = strings.Replace(rightStr, `%`, ``, -1)
resultStr = fmt.Sprintf(`{"match_phrase" : {"%v" : {"query" : "%v"}}}`, colNameStr, rightStr)
case "not like":
rightStr = strings.Replace(rightStr, `%`, ``, -1)
resultStr = fmt.Sprintf(`{"bool" : {"must_not" : {"match_phrase" : {"%v" : {"query" : "%v"}}}}}`, colNameStr, rightStr)
case "not in":
// the default valTuple is ('1', '2', '3') like
// so need to drop the () and replace ' to "
rightStr = strings.Replace(rightStr, `'`, `"`, -1)
rightStr = strings.Trim(rightStr, "(")
rightStr = strings.Trim(rightStr, ")")
resultStr = fmt.Sprintf(`{"bool" : {"must_not" : {"terms" : {"%v" : [%v]}}}}`, colNameStr, rightStr)
}
// the root node need to have bool and must
if topLevel {
resultStr = fmt.Sprintf(`{"bool" : {"must" : [%v]}}`, resultStr)
}
return resultStr, nil
}
func handleSelectWhere(expr *sqlparser.Expr, topLevel bool, parent *sqlparser.Expr) (string, error) {
if expr == nil {
return "", errors.New("elasticsql: error expression cannot be nil here")
}
switch (*expr).(type) {
case *sqlparser.AndExpr:
return handleSelectWhereAndExpr(expr, topLevel, parent)
case *sqlparser.OrExpr:
return handleSelectWhereOrExpr(expr, topLevel, parent)
case *sqlparser.ComparisonExpr:
return handleSelectWhereComparisonExpr(expr, topLevel, parent)
case *sqlparser.IsExpr:
return "", errors.New("elasticsql: is expression currently not supported")
case *sqlparser.RangeCond:
// between a and b
// the meaning is equal to range query
rangeCond := (*expr).(*sqlparser.RangeCond)
colName, ok := rangeCond.Left.(*sqlparser.ColName)
if !ok {
return "", errors.New("elasticsql: range column name missing")
}
colNameStr := sqlparser.String(colName)
fromStr := strings.Trim(sqlparser.String(rangeCond.From), `'`)
toStr := strings.Trim(sqlparser.String(rangeCond.To), `'`)
resultStr := fmt.Sprintf(`{"range" : {"%v" : {"from" : "%v", "to" : "%v"}}}`, colNameStr, fromStr, toStr)
if topLevel {
resultStr = fmt.Sprintf(`{"bool" : {"must" : [%v]}}`, resultStr)
}
return resultStr, nil
case *sqlparser.ParenExpr:
parentBoolExpr := (*expr).(*sqlparser.ParenExpr)
boolExpr := parentBoolExpr.Expr
// if paren is the top level, bool must is needed
var isThisTopLevel = false
if topLevel {
isThisTopLevel = true
}
return handleSelectWhere(&boolExpr, isThisTopLevel, parent)
case *sqlparser.NotExpr:
return "", errors.New("elasticsql: not expression currently not supported")
}
return "", errors.New("elaticsql: logically cannot reached here")
}