-
Notifications
You must be signed in to change notification settings - Fork 3
/
update.go
86 lines (72 loc) · 2.11 KB
/
update.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
package sqlbuilder
import (
"bytes"
"strings"
)
//
// Author: 陈永佳 [email protected], [email protected]
//
type UpdateBuilder struct {
ctx *SQLContext
table string
columnAndValues *List
ensure bool
}
func newUpdateBuilder(ctx *SQLContext, table string) *UpdateBuilder {
return &UpdateBuilder{
ctx: ctx,
table: table,
columnAndValues: newItems(),
}
}
func (slf *UpdateBuilder) Table(table string) *UpdateBuilder {
slf.table = table
return slf
}
func (slf *UpdateBuilder) Columns(column string, otherColumns ...string) *UpdateBuilder {
slf.columnAndValues.Add(escapeWith(slf.ctx, column))
for _, col := range otherColumns {
slf.columnAndValues.Add(escapeWith(slf.ctx, col))
}
return slf
}
func (slf *UpdateBuilder) AddColumnValue(column string, value interface{}) *UpdateBuilder {
slf.columnAndValues.Add(slf.ctx.escapeName(column) + "=" + slf.ctx.escapeValue(value))
return slf
}
func (slf *UpdateBuilder) compile() *bytes.Buffer {
if "" == slf.table {
panic("Table name not found, you should call 'Table(table)' method to set it")
}
buf := new(bytes.Buffer)
buf.WriteString("UPDATE ")
buf.WriteString(slf.ctx.escapeName(slf.table))
buf.WriteString(" SET ")
// 此处Columns不需要转义处理
buf.WriteString(strings.Join(slf.columnAndValues.AvailableStrItems(), SQLComma))
return buf
}
func (slf *UpdateBuilder) YesImSureUpdateTable() *UpdateBuilder {
slf.ensure = true
return slf
}
func (slf *UpdateBuilder) Where(conditions SQLStatement) *WhereBuilder {
return newWhereBuilder(slf.ctx, slf.Compile(), conditions)
}
func (slf *UpdateBuilder) Compile() string {
return slf.compile().String()
}
func (slf *UpdateBuilder) ToSQL() string {
sqlTxt := sqlEndpoint(slf.compile())
if slf.ensure {
return sqlTxt
} else {
panic("Warning for FULL-UPDATE, you should call 'YesImSureUpdateTable(bool)' to ensure. SQLText: " + sqlTxt)
}
}
func (slf *UpdateBuilder) Execute() *Executor {
return newExecute(slf.ToSQL(), slf.ctx.prepare)
}
func escapeWith(ctx *SQLContext, column string) string {
return ctx.escapeName(column) + "=?"
}