expr.go
6.6 KB
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
package advance
import (
"bytes"
"fmt"
"regexp"
"strconv"
"strings"
)
type (
Model struct {
mc MapColumn
name string
}
AdvancedQuery struct {
Column Column `json:"column"`
Exprs []Expr `json:"exprs"`
}
ColumnExprResult struct {
Column Column
Result []ExprResult
}
// 高级查询参数
AdvancedQueries []AdvancedQuery
)
var registerModels = make(map[string]Model)
func RegisModel(m Model) {
if _, ok := registerModels[m.name]; ok {
panic("register modes exists:" + m.name)
}
registerModels[m.name] = m
}
func NewModel(name string, columns []Column) Model {
return Model{
name: name,
mc: NewMapColumn(columns),
}
}
func ComputeColumnExpr(queries []AdvancedQuery) []ColumnExprResult {
var result = make([]ColumnExprResult, 0)
queries = mergeQuery(queries)
for i := range queries {
q := queries[i]
var tmpResult []ExprResult
switch q.Column.ValueType {
case ValueNumber:
tmpResult = append(JoinColumnExprNumber(q.Exprs))
case ValueChars:
tmpResult = append(JoinColumnExprChars(q.Exprs))
case ValueDate:
tmpResult = append(JoinColumnExprDate(q.Exprs))
}
if len(tmpResult) == 0 {
continue
}
result = append(result, ColumnExprResult{
Column: q.Column,
Result: tmpResult,
})
}
return result
}
func JoinColumnExprNumber(expr []Expr) []ExprResult {
var ec = []exprCompute{NewInExprCompute(expr, ValueNumber), NewRangeExprCompute(expr, ValueNumber), NewLessGreaterExprCompute(expr, ValueNumber), NewNotEqualExprCompute(expr, ValueNumber), NewLikeExprCompute(expr, ValueNumber)}
return joinExprResult(ec)
}
func JoinColumnExprDate(expr []Expr) []ExprResult {
var ec = []exprCompute{NewRangeExprCompute(expr, ValueDate), NewRecentDateExprCompute(expr, ValueDate), NewNotEqualExprCompute(expr, ValueChars)}
return joinExprResult(ec)
}
func JoinColumnExprChars(expr []Expr) []ExprResult {
var ec = []exprCompute{NewInExprCompute(expr, ValueChars), NewLikeExprCompute(expr, ValueChars), NewNotEqualExprCompute(expr, ValueChars)}
return joinExprResult(ec)
}
type MapColumn map[string]Column
func NewMapColumn(cols []Column) MapColumn {
mapColumn := make(map[string]Column)
for i := range cols {
mapColumn[cols[i].Column] = cols[i]
}
return mapColumn
}
func (m MapColumn) FindItem(col string) Column {
if item, ok := m[col]; ok {
return item
}
return Column{}
}
type PgSqlGenerator struct{}
func (p PgSqlGenerator) SqlGen(q ColumnExprResult) (string, error) {
sql := bytes.NewBuffer(nil)
sql.WriteString("(")
var wheres []string
for i := range q.Result {
item := q.Result[i]
if err := p.PreCheckAndFormat(&item); err != nil {
return "", err
}
var where string
switch item.OpChar {
case In:
where = p.In(q.Column, item.Value)
case NotIn:
where = p.NotIn(q.Column, item.Value)
case Like:
where = p.Like(q.Column, item.Value)
case Range:
where = p.Range(q.Column, item)
default:
where = fmt.Sprintf(" %s %s %v ", q.Column.DbAlias, item.OpChar, item.Value[0])
}
if len(where) == 0 {
continue
}
wheres = append(wheres, where)
}
sql.WriteString(strings.Join(wheres, sepOr))
sql.WriteString(")")
return sql.String(), nil
}
func (p PgSqlGenerator) PreCheckAndFormat(rs *ExprResult) error {
if rs.ValueType == ValueNumber || rs.ValueType == ValueDate {
for i := range rs.Value {
v := rs.Value[i]
if isInfinity(v) {
continue
}
if _, err := strconv.ParseFloat(fmt.Sprintf("%v", v), 64); err != nil {
return fmt.Errorf("不是有效的数值类型:%v", v)
}
}
}
if rs.ValueType == ValueChars {
for i := range rs.Value {
v, ok := rs.Value[i].(string)
err := fmt.Errorf("不是有效的字符串类型:%v", v)
if !ok {
return err
}
if ok, e := regexp.MatchString("[!%&()*+,-/=?^`'{|}~]", v); ok || e != nil {
return fmt.Errorf("非法字符:%v", v)
}
}
}
return nil
}
func (p PgSqlGenerator) In(c Column, values []interface{}) string {
if len(values) < 1 {
return ""
}
var ret []string
for i := range values {
if c.ValueType == ValueNumber {
ret = append(ret, fmt.Sprintf("%v", values[i]))
} else {
ret = append(ret, fmt.Sprintf("'%v'", values[i]))
}
}
return fmt.Sprintf("%s in (%s)", c.DbAlias, strings.Join(ret, ","))
}
func (p PgSqlGenerator) NotIn(c Column, values []interface{}) string {
if len(values) < 1 {
return ""
}
var ret []string
for i := range values {
if c.ValueType == ValueNumber {
ret = append(ret, fmt.Sprintf("%v", values[i]))
} else {
ret = append(ret, fmt.Sprintf("'%v'", values[i]))
}
}
return fmt.Sprintf("%s not in (%s)", c.DbAlias, strings.Join(ret, ","))
}
func (p PgSqlGenerator) Like(c Column, values []interface{}) string {
if len(values) < 1 {
return ""
}
sql := bytes.NewBuffer(nil)
sql.WriteString("(")
var wheres []string
for i := range values {
if c.ValueType == ValueNumber {
wheres = append(wheres, fmt.Sprintf("%s::text like '%%%v%%'", c.DbAlias, values[i]))
} else {
wheres = append(wheres, fmt.Sprintf("%s like '%%%v%%'", c.DbAlias, values[i]))
}
}
sql.WriteString(strings.Join(wheres, sepOr))
sql.WriteString(")")
return sql.String()
}
func (p PgSqlGenerator) Range(c Column, res ExprResult) string {
if len(res.Value) != 2 {
return ""
}
sql := bytes.NewBuffer(nil)
sql.WriteString("(")
var wheres []string
if !isInfinity(res.Value[0]) {
wheres = append(wheres, fmt.Sprintf(" %s %s %v ", c.DbAlias, res.LeftOp, res.Value[0]))
}
if !isInfinity(res.Value[1]) {
wheres = append(wheres, fmt.Sprintf(" %s %s %v ", c.DbAlias, res.RightOp, res.Value[1]))
}
sql.WriteString(strings.Join(wheres, sepAnd))
sql.WriteString(")")
return sql.String()
}
// AdvancedQuerySql 高级查询Sql生成器
func AdvancedQuerySql(queries []AdvancedQuery) (string, error) {
if len(queries) == 0 {
return "", nil
}
gen := PgSqlGenerator{}
results := ComputeColumnExpr(queries)
if len(results) == 0 {
return "", nil
}
sql := bytes.NewBuffer(nil)
var wheres []string
for i := range results {
condition, err := gen.SqlGen(results[i])
if err != nil {
return "", err
}
wheres = append(wheres, condition)
}
sql.WriteString(strings.Join(wheres, sepAnd))
// 空条件 ()
if sql.String() == "()" {
return "", nil
}
if sql.String() == "(())" {
return "", nil
}
return sql.String(), nil
}
func mergeQuery(queries []AdvancedQuery) []AdvancedQuery {
var rsp = make([]AdvancedQuery, 0)
var mapColumn = make(map[string]AdvancedQuery)
for i := range queries {
var item AdvancedQuery
var ok bool
if item, ok = mapColumn[queries[i].Column.Column]; !ok {
mapColumn[queries[i].Column.Column] = queries[i]
} else {
item.Exprs = append(item.Exprs, queries[i].Exprs...)
}
}
for _, v := range mapColumn {
rsp = append(rsp, v)
}
return rsp
}