forked from cch123/elasticsql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
52 lines (41 loc) · 1.13 KB
/
main.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
package elasticsql
import (
"bytes"
"encoding/json"
"github.com/xwb1989/sqlparser"
)
// ConvertPretty will transform sql to elasticsearch dsl, and prettify the output json
func ConvertPretty(sql string) (dsl string, table string, err error) {
dsl, table, err = Convert(sql)
if err != nil {
return dsl, table, err
}
var prettifiedDSLBytes bytes.Buffer
err = json.Indent(&prettifiedDSLBytes, []byte(dsl), "", " ")
if err != nil {
return "", table, err
}
return string(prettifiedDSLBytes.Bytes()), table, err
}
// Convert will transform sql to elasticsearch dsl string
func Convert(sql string) (dsl string, table string, err error) {
stmt, err := sqlparser.Parse(sql)
if err != nil {
return "", "", err
}
//sql valid, start to handle
switch stmt.(type) {
case *sqlparser.Select:
dsl, table, err = handleSelect(stmt.(*sqlparser.Select))
case *sqlparser.Update:
return handleUpdate(stmt.(*sqlparser.Update))
case *sqlparser.Insert:
return handleInsert(stmt.(*sqlparser.Insert))
case *sqlparser.Delete:
return handleDelete(stmt.(*sqlparser.Delete))
}
if err != nil {
return "", "", err
}
return dsl, table, nil
}