-
Notifications
You must be signed in to change notification settings - Fork 0
/
builder.go
52 lines (44 loc) · 1.25 KB
/
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
package mysql
import (
"strings"
)
// WhereBuilder用来构建xorm的engine所需的where模块
// 使用方法很easy
// mysql.NewWhereBuilder()
// mysql.Add("id",1)
// 然后使用的时候直接mysql.Select()
type WhereBuilder struct {
data map[string]interface{}
}
func NewWhereBuilder(args ...map[string]interface{}) *WhereBuilder {
wb := &WhereBuilder{
data: make(map[string]interface{}),
}
if len(args) > 0 {
wb.data = args[0]
}
return wb
}
// 添加参数,需要注意的是,原来的xorm中where条件是id>? AND id
func (wb *WhereBuilder) Add(condition string, args interface{}) *WhereBuilder {
wb.data[condition] = args
return wb
}
// 解析相关的参数
func (wb *WhereBuilder) parseState(input string) string {
input = strings.TrimSpace(input)
if i := strings.LastIndexAny(input, "<>="); i == len(input)-1 {
return input
}
return input + "="
}
// Encode用来生成xorm的engine.Where()条件的两个参数
func (wb *WhereBuilder) Encode() (whereStr string, beans []interface{}) {
whereArr := make([]string, 0, len(wb.data))
beans = make([]interface{}, 0, len(wb.data))
for k, v := range wb.data {
whereArr = append(whereArr, wb.parseState(k)+"?")
beans = append(beans, v)
}
return strings.Join(whereArr, " AND "), beans
}