-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
120 lines (106 loc) · 2.32 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
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
package sqlparser
import (
"errors"
"fmt"
"github.com/binlaniua/kitgo"
"github.com/xwb1989/sqlparser"
"reflect"
"regexp"
)
var (
pattern_chinese = regexp.MustCompile("[\u4E00-\u9FA5]+")
pattern_as = regexp.MustCompile(`(?i)as ('|")([^'"]+)('|")`)
)
//-------------------------------------
//
//
//
//-------------------------------------
type SQLParser struct {
sql string
chineseFieldMap map[string]string
result *SQLParserResult
}
//
//
//
//
//
func NewSQLParser(sqlString string) *SQLParser {
//
sp := &SQLParser{
sql: sqlString,
chineseFieldMap: map[string]string{},
result: NewSQLparserResult(),
}
//
sp.cleanSql()
return sp
}
//
//
// 获取解析结果
//
//
func (sp *SQLParser) GetResult() *SQLParserResult {
return sp.result
}
//
//
//
//
//
func (sp *SQLParser) DoParser() (*SQLParserResult, error) {
ast, err := sqlparser.Parse(sp.sql)
if err != nil {
return nil, err
}
switch node := ast.(type) {
//
case *sqlparser.Select:
sp.result.sqlType = SQL_TYPE_SELECT
err = newSelectSql(sp.result, "", node).doParser()
//
case *sqlparser.Union:
sp.result.sqlType = SQL_TYPE_UNION
err = newUnionSql(sp.result, "", node).doParser()
//
case *sqlparser.Insert:
sp.result.sqlType = SQL_TYPE_INSERT
err = newInsertSql(sp.result, node).doParser()
//
case *sqlparser.Update:
sp.result.sqlType = SQL_TYPE_UPDATE
err = newUpdateSql(sp.result, node).doParser()
//
case *sqlparser.Delete:
sp.result.sqlType = SQL_TYPE_DEL
err = newDeleteSql(sp.result, node).doParser()
//
default:
return nil, errors.New(fmt.Sprintf("不支持类型 => %s", reflect.TypeOf(ast)))
}
return sp.result, nil
}
//
//
// 清理SQL
// 1. 不支持中文 not support chinese
// 2. 不支持函数 not support database function
// 3. AS 后面不能更引号 not support "as 'xxx'", support "as xxxx"
// 4. 不支持(+)连接 not support left join use (+)
//
//
func (sp *SQLParser) cleanSql() {
count := 0
sp.sql = pattern_chinese.ReplaceAllStringFunc(sp.sql, func(src string) string {
alias := fmt.Sprintf("__r%d", count)
sp.chineseFieldMap[alias] = src
count++
return alias
})
sp.sql = pattern_as.ReplaceAllStringFunc(sp.sql, func(src string) string {
return kitgo.StringReplace(src, `"|'`, "")
})
sp.sql = kitgo.StringReplace(sp.sql, ";|\\(\\+\\)", "")
}