forked from rolandhe/daog
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodifier.go
More file actions
74 lines (63 loc) · 1.72 KB
/
modifier.go
File metadata and controls
74 lines (63 loc) · 1.72 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
// A quickly mysql access component.
//
// Copyright 2023 The daog Authors. All rights reserved.
package daog
import (
"strings"
)
const (
selfAdd = 1
selfMinus = 2
)
type pair struct {
column string
value any
self int
}
// NewModifier 创建 Modifier 对象
func NewModifier() Modifier {
return &internalModifier{}
}
// Modifier 描述 update 语义中set cause的生成,通过 Modifier 来避免自己拼接sql片段,降低出错概率,
// 最终生成 update tab set xx=?,bb=? 的 sql 片段
type Modifier interface {
// Add 增加一个字段的修改,比如 id = 100
Add(column string, value any) Modifier
SelfAdd(column string, value any) Modifier
SelfMinus(column string, value any) Modifier
toSQL(tableName string) (string, []any)
}
type internalModifier struct {
modifies []*pair
}
func (m *internalModifier) Add(column string, value any) Modifier {
m.modifies = append(m.modifies, &pair{column, value, 0})
return m
}
func (m *internalModifier) SelfAdd(column string, value any) Modifier {
m.modifies = append(m.modifies, &pair{column, value, 1})
return m
}
func (m *internalModifier) SelfMinus(column string, value any) Modifier {
m.modifies = append(m.modifies, &pair{column, value, 2})
return m
}
func (m *internalModifier) toSQL(tableName string) (string, []any) {
l := len(m.modifies)
if l == 0 {
return "", nil
}
modStmt := make([]string, l)
args := make([]any, l)
for i, p := range m.modifies {
if p.self == selfAdd {
modStmt[i] = p.column + "=" + p.column + "+?"
} else if p.self == selfMinus {
modStmt[i] = p.column + "=" + p.column + "-?"
} else {
modStmt[i] = p.column + "=?"
}
args[i] = p.value
}
return "update " + tableName + " set " + strings.Join(modStmt, ","), args
}