/
model.go
82 lines (76 loc) · 1.7 KB
/
model.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
package model
import (
"fmt"
"strings"
)
// NullType 空字节类型
type NullType byte
const (
_ NullType = iota
// IsNull the same as `is null`
IsNull
// IsNotNull the same as `is not null`
IsNotNull
)
// WhereBuild sql build where
// see: https://github.com/jinzhu/gorm/issues/2055
func WhereBuild(where map[string]interface{}) (whereSQL string, vals []interface{}, err error) {
for k, v := range where {
ks := strings.Split(k, " ")
if len(ks) > 2 {
return "", nil, fmt.Errorf("Error in query condition: %s. ", k)
}
if whereSQL != "" {
whereSQL += " AND "
}
fmt.Println(strings.Join(ks, ","))
switch len(ks) {
case 1:
//fmt.Println(reflect.TypeOf(v))
switch v := v.(type) {
case NullType:
fmt.Println()
if v == IsNotNull {
whereSQL += fmt.Sprint(k, " IS NOT NULL")
} else {
whereSQL += fmt.Sprint(k, " IS NULL")
}
default:
whereSQL += fmt.Sprint(k, "=?")
vals = append(vals, v)
}
case 2:
k = ks[0]
switch ks[1] {
case "=":
whereSQL += fmt.Sprint(k, "=?")
vals = append(vals, v)
case ">":
whereSQL += fmt.Sprint(k, ">?")
vals = append(vals, v)
case ">=":
whereSQL += fmt.Sprint(k, ">=?")
vals = append(vals, v)
case "<":
whereSQL += fmt.Sprint(k, "<?")
vals = append(vals, v)
case "<=":
whereSQL += fmt.Sprint(k, "<=?")
vals = append(vals, v)
case "!=":
whereSQL += fmt.Sprint(k, "!=?")
vals = append(vals, v)
case "<>":
whereSQL += fmt.Sprint(k, "!=?")
vals = append(vals, v)
case "in":
whereSQL += fmt.Sprint(k, " in (?)")
vals = append(vals, v)
case "like":
whereSQL += fmt.Sprint(k, " like ?")
vals = append(vals, v)
}
}
}
return
}