-
Notifications
You must be signed in to change notification settings - Fork 209
/
insert.go
264 lines (223 loc) · 5.67 KB
/
insert.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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
package dbr
import (
"context"
"database/sql"
"reflect"
"strings"
"github.com/gocraft/dbr/v2/dialect"
)
// InsertStmt builds `INSERT INTO ...`.
type InsertStmt struct {
Runner
EventReceiver
Dialect
raw
Table string
Column []string
Value [][]interface{}
Ignored bool
ReturnColumn []string
RecordID *int64
comments Comments
}
type InsertBuilder = InsertStmt
func (b *InsertStmt) Build(d Dialect, buf Buffer) error {
if b.raw.Query != "" {
return b.raw.Build(d, buf)
}
if b.Table == "" {
return ErrTableNotSpecified
}
if len(b.Column) == 0 {
return ErrColumnNotSpecified
}
err := b.comments.Build(d, buf)
if err != nil {
return err
}
if b.Ignored {
buf.WriteString("INSERT IGNORE INTO ")
} else {
buf.WriteString("INSERT INTO ")
}
buf.WriteString(d.QuoteIdent(b.Table))
var placeholderBuf strings.Builder
placeholderBuf.WriteString("(")
buf.WriteString(" (")
for i, col := range b.Column {
if i > 0 {
buf.WriteString(",")
placeholderBuf.WriteString(",")
}
buf.WriteString(d.QuoteIdent(col))
placeholderBuf.WriteString(placeholder)
}
buf.WriteString(")")
if d == dialect.MSSQL && len(b.ReturnColumn) > 0 {
buf.WriteString(" OUTPUT ")
for i, col := range b.ReturnColumn {
if i > 0 {
buf.WriteString(",")
}
buf.WriteString("INSERTED." + d.QuoteIdent(col))
}
}
buf.WriteString(" VALUES ")
placeholderBuf.WriteString(")")
placeholderStr := placeholderBuf.String()
for i, tuple := range b.Value {
if i > 0 {
buf.WriteString(", ")
}
buf.WriteString(placeholderStr)
buf.WriteValue(tuple...)
}
if d != dialect.MSSQL && len(b.ReturnColumn) > 0 {
buf.WriteString(" RETURNING ")
for i, col := range b.ReturnColumn {
if i > 0 {
buf.WriteString(",")
}
buf.WriteString(d.QuoteIdent(col))
}
}
return nil
}
// InsertInto creates an InsertStmt.
func InsertInto(table string) *InsertStmt {
return &InsertStmt{
Table: table,
}
}
// InsertInto creates an InsertStmt.
func (sess *Session) InsertInto(table string) *InsertStmt {
b := InsertInto(table)
b.Runner = sess
b.EventReceiver = sess.EventReceiver
b.Dialect = sess.Dialect
return b
}
// InsertInto creates an InsertStmt.
func (tx *Tx) InsertInto(table string) *InsertStmt {
b := InsertInto(table)
b.Runner = tx
b.EventReceiver = tx.EventReceiver
b.Dialect = tx.Dialect
return b
}
// InsertBySql creates an InsertStmt from raw query.
func InsertBySql(query string, value ...interface{}) *InsertStmt {
return &InsertStmt{
raw: raw{
Query: query,
Value: value,
},
}
}
// InsertBySql creates an InsertStmt from raw query.
func (sess *Session) InsertBySql(query string, value ...interface{}) *InsertStmt {
b := InsertBySql(query, value...)
b.Runner = sess
b.EventReceiver = sess.EventReceiver
b.Dialect = sess.Dialect
return b
}
// InsertBySql creates an InsertStmt from raw query.
func (tx *Tx) InsertBySql(query string, value ...interface{}) *InsertStmt {
b := InsertBySql(query, value...)
b.Runner = tx
b.EventReceiver = tx.EventReceiver
b.Dialect = tx.Dialect
return b
}
func (b *InsertStmt) Columns(column ...string) *InsertStmt {
b.Column = column
return b
}
// Comment adds a comment to prepended. All multi-line sql comment characters are stripped
func (b *InsertStmt) Comment(comment string) *InsertStmt {
b.comments = b.comments.Append(comment)
return b
}
// Ignore any insertion errors
func (b *InsertStmt) Ignore() *InsertStmt {
b.Ignored = true
return b
}
// Values adds a tuple to be inserted.
// The order of the tuple should match Columns.
func (b *InsertStmt) Values(value ...interface{}) *InsertStmt {
b.Value = append(b.Value, value)
return b
}
// Record adds a tuple for columns from a struct.
//
// If there is a field called "Id" or "ID" in the struct,
// it will be set to LastInsertId.
func (b *InsertStmt) Record(structValue interface{}) *InsertStmt {
v := reflect.Indirect(reflect.ValueOf(structValue))
if v.Kind() == reflect.Struct {
found := make([]interface{}, len(b.Column)+1)
// ID is recommended by golint here
s := newTagStore()
s.findValueByName(v, append(b.Column, "id"), found, false)
value := found[:len(found)-1]
for i, v := range value {
if v != nil {
value[i] = v.(reflect.Value).Interface()
}
}
if v.CanSet() {
switch idField := found[len(found)-1].(type) {
case reflect.Value:
if idField.Kind() == reflect.Int64 {
b.RecordID = idField.Addr().Interface().(*int64)
}
}
}
b.Values(value...)
}
return b
}
// Returning specifies the returning columns for postgres/mssql.
func (b *InsertStmt) Returning(column ...string) *InsertStmt {
b.ReturnColumn = column
return b
}
// Pair adds (column, value) to be inserted.
// It is an error to mix Pair with Values and Record.
func (b *InsertStmt) Pair(column string, value interface{}) *InsertStmt {
b.Column = append(b.Column, column)
switch len(b.Value) {
case 0:
b.Values(value)
case 1:
b.Value[0] = append(b.Value[0], value)
default:
panic("pair only allows one record to insert")
}
return b
}
func (b *InsertStmt) Exec() (sql.Result, error) {
return b.ExecContext(context.Background())
}
func (b *InsertStmt) ExecContext(ctx context.Context) (sql.Result, error) {
result, err := exec(ctx, b.Runner, b.EventReceiver, b, b.Dialect)
if err != nil {
return nil, err
}
if b.RecordID != nil {
if id, err := result.LastInsertId(); err == nil {
*b.RecordID = id
}
b.RecordID = nil
}
return result, nil
}
func (b *InsertStmt) LoadContext(ctx context.Context, value interface{}) error {
_, err := query(ctx, b.Runner, b.EventReceiver, b, b.Dialect, value)
return err
}
func (b *InsertStmt) Load(value interface{}) error {
return b.LoadContext(context.Background(), value)
}