-
Notifications
You must be signed in to change notification settings - Fork 5
/
update.go
230 lines (197 loc) · 5.67 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
package dat
import (
"reflect"
"strconv"
)
// UpdateBuilder contains the clauses for an UPDATE statement
type UpdateBuilder struct {
Execer
isInterpolated bool
table string
setClauses []*setClause
whereFragments []*whereFragment
orderBys []string
limitCount uint64
limitValid bool
offsetCount uint64
offsetValid bool
returnings []string
scope Scope
}
type setClause struct {
column string
value interface{}
}
// NewUpdateBuilder creates a new UpdateBuilder for the given table
func NewUpdateBuilder(table string) *UpdateBuilder {
if table == "" {
logger.Error("Update requires a table name")
return nil
}
return &UpdateBuilder{table: table, isInterpolated: EnableInterpolation}
}
// Set appends a column/value pair for the statement
func (b *UpdateBuilder) Set(column string, value interface{}) *UpdateBuilder {
b.setClauses = append(b.setClauses, &setClause{column: column, value: value})
return b
}
// SetMap appends the elements of the map as column/value pairs for the statement
func (b *UpdateBuilder) SetMap(clauses map[string]interface{}) *UpdateBuilder {
for col, val := range clauses {
b = b.Set(col, val)
}
return b
}
// SetBlacklist creates SET clause(s) using a record and blacklist of columns
func (b *UpdateBuilder) SetBlacklist(rec interface{}, blacklist ...string) *UpdateBuilder {
if len(blacklist) == 0 {
panic("SetBlacklist requires a list of columns names")
}
columns := reflectExcludeColumns(rec, blacklist)
ind := reflect.Indirect(reflect.ValueOf(rec))
vals, err := valuesFor(ind.Type(), ind, columns)
if err != nil {
panic(err)
}
for i, val := range vals {
b.Set(columns[i], val)
}
return b
}
// SetWhitelist creates SET clause(s) using a record and whitelist of columns.
// To specify all columns, use "*".
func (b *UpdateBuilder) SetWhitelist(rec interface{}, whitelist ...string) *UpdateBuilder {
var columns []string
if len(whitelist) == 0 || whitelist[0] == "*" {
columns = reflectColumns(rec)
} else {
columns = whitelist
}
ind := reflect.Indirect(reflect.ValueOf(rec))
vals, err := valuesFor(ind.Type(), ind, columns)
if err != nil {
panic(err)
}
for i, val := range vals {
b.Set(columns[i], val)
}
return b
}
// ScopeMap uses a predefined scope in place of WHERE.
func (b *UpdateBuilder) ScopeMap(mapScope *MapScope, m M) *UpdateBuilder {
b.scope = mapScope.mergeClone(m)
return b
}
// Scope uses a predefined scope in place of WHERE.
func (b *UpdateBuilder) Scope(sql string, args ...interface{}) *UpdateBuilder {
b.scope = ScopeFunc(func(table string) (string, []interface{}) {
return escapeScopeTable(sql, table), args
})
return b
}
// Where appends a WHERE clause to the statement
func (b *UpdateBuilder) Where(whereSQLOrMap interface{}, args ...interface{}) *UpdateBuilder {
b.whereFragments = append(b.whereFragments, newWhereFragment(whereSQLOrMap, args))
return b
}
// OrderBy appends a column to ORDER the statement by
func (b *UpdateBuilder) OrderBy(ord string) *UpdateBuilder {
b.orderBys = append(b.orderBys, ord)
return b
}
// Limit sets a limit for the statement; overrides any existing LIMIT
func (b *UpdateBuilder) Limit(limit uint64) *UpdateBuilder {
b.limitCount = limit
b.limitValid = true
return b
}
// Offset sets an offset for the statement; overrides any existing OFFSET
func (b *UpdateBuilder) Offset(offset uint64) *UpdateBuilder {
b.offsetCount = offset
b.offsetValid = true
return b
}
// Returning sets the columns for the RETURNING clause
func (b *UpdateBuilder) Returning(columns ...string) *UpdateBuilder {
b.returnings = columns
return b
}
// ToSQL serialized the UpdateBuilder to a SQL string
// It returns the string with placeholders and a slice of query arguments
func (b *UpdateBuilder) ToSQL() (string, []interface{}) {
if len(b.table) == 0 {
panic("no table specified")
}
if len(b.setClauses) == 0 {
panic("no set clauses specified")
}
buf := bufPool.Get()
defer bufPool.Put(buf)
var args []interface{}
buf.WriteString("UPDATE ")
writeIdentifier(buf, b.table)
buf.WriteString(" SET ")
var placeholderStartPos int64 = 1
// Build SET clause SQL with placeholders and add values to args
for i, c := range b.setClauses {
if i > 0 {
buf.WriteString(", ")
}
Dialect.WriteIdentifier(buf, c.column)
if e, ok := c.value.(*Expression); ok {
start := placeholderStartPos
buf.WriteString(" = ")
// map relative $1, $2 placeholders to absolute
remapPlaceholders(buf, e.Sql, start)
args = append(args, e.Args...)
placeholderStartPos += int64(len(e.Args))
} else {
// TOOD
if placeholderStartPos < maxLookup {
buf.WriteString(equalsPlaceholderTab[placeholderStartPos])
} else {
buf.WriteString(" = $")
buf.WriteString(strconv.FormatInt(placeholderStartPos, 10))
}
placeholderStartPos++
args = append(args, c.value)
}
}
if b.scope == nil {
if len(b.whereFragments) > 0 {
buf.WriteString(" WHERE ")
writeAndFragmentsToSQL(buf, b.whereFragments, &args, &placeholderStartPos)
}
} else {
whereFragment := newWhereFragment(b.scope.ToSQL(b.table))
writeScopeCondition(buf, whereFragment, &args, &placeholderStartPos)
}
// Ordering and limiting
if len(b.orderBys) > 0 {
buf.WriteString(" ORDER BY ")
for i, s := range b.orderBys {
if i > 0 {
buf.WriteString(", ")
}
buf.WriteString(s)
}
}
if b.limitValid {
buf.WriteString(" LIMIT ")
writeUint64(buf, b.limitCount)
}
if b.offsetValid {
buf.WriteString(" OFFSET ")
writeUint64(buf, b.offsetCount)
}
// Go thru the returning clauses
for i, c := range b.returnings {
if i == 0 {
buf.WriteString(" RETURNING ")
} else {
buf.WriteRune(',')
}
Dialect.WriteIdentifier(buf, c)
}
return buf.String(), args
}