-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpredicate_builder.go
92 lines (82 loc) · 2.23 KB
/
predicate_builder.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
package hzgorm
import (
"fmt"
"github.com/jinzhu/gorm"
"regexp"
"strconv"
"strings"
)
const (
asc = "asc"
desc = "desc"
limit = "LIMIT"
)
// TODO: REMOVE - GROUP BY - HAVING - JOIN etc.
func (hz *hzGorm) predicateBuilder(tableName string, sql string, sqlVars []interface{}, fieldNames []string) string {
sql = sql + "===end==="
predicate := hz.utils.stringBetween(sql, "(", ")===end===")
if predicate == "" {
return predicate
}
predicate = hz.predicateNormalize(predicate, fieldNames)
for i, sv := range sqlVars {
i = i + 1
comma := ","
if len(sqlVars) == i || len(sqlVars) == 1 {
comma = ""
}
iStr := fmt.Sprint(i)
iStr = "\\$" + iStr + "(\\,|\\))"
r, _ := regexp.Compile(iStr)
sqlVar := fmt.Sprintf("%v", sv)
predicate = r.ReplaceAllLiteralString(predicate, sqlVar+comma)
predicate = strings.Replace(predicate, "(", "", -1)
}
predicate = strings.ReplaceAll(predicate, "IN ", "IN (")
predicate = strings.ReplaceAll(predicate, "IN ((", "IN(")
predicate = strings.ReplaceAll(predicate, "\""+tableName+"\".", "")
predicate = strings.ReplaceAll(predicate, ", OR", " OR")
return predicate
}
func (hz *hzGorm) predicateNormalize(predicate string, fieldNames []string) string {
for _, fieldName := range fieldNames {
columnName := gorm.ToColumnName(fieldName)
predicate = strings.ReplaceAll(predicate, columnName, fieldName)
predicate = strings.ReplaceAll(predicate, "\""+fieldName+"\"", fieldName)
}
return predicate
}
func (hz *hzGorm) parseLimitAndOrder(predicate string) (string, int) {
if strings.Contains(predicate, limit) {
limitValue := strings.TrimSpace(hz.utils.stringAfter(predicate, limit))
if limitValue != "" {
lv, err := strconv.Atoi(limitValue)
if err != nil {
return "", -1
}
if strings.Contains(predicate, asc) {
return asc, lv
} else if strings.Contains(predicate, desc) {
return desc, lv
} else {
return "", lv
}
} else {
if strings.Contains(predicate, asc) {
return asc, -1
} else if strings.Contains(predicate, desc) {
return desc, -1
} else {
return "", -1
}
}
} else {
if strings.Contains(predicate, asc) {
return asc, -1
} else if strings.Contains(predicate, desc) {
return desc, -1
} else {
return "", -1
}
}
}