-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
create.go
306 lines (275 loc) · 9.42 KB
/
create.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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
package dameng
import (
"database/sql"
"reflect"
"gorm.io/gorm"
"gorm.io/gorm/callbacks"
"gorm.io/gorm/clause"
)
func Create(db *gorm.DB) {
if db.Error != nil {
return
}
if db.Statement.Schema != nil && !db.Statement.Unscoped {
for _, c := range db.Statement.Schema.CreateClauses {
db.Statement.AddClause(c)
}
}
var onConflict clause.OnConflict
var hasConflict bool
if db.Statement.SQL.String() == "" {
var (
values = callbacks.ConvertToCreateValues(db.Statement)
c = db.Statement.Clauses["ON CONFLICT"]
)
onConflict, hasConflict = c.Expression.(clause.OnConflict)
if hasConflict {
if len(db.Statement.Schema.PrimaryFields) > 0 {
columnsMap := map[string]bool{}
for _, column := range values.Columns {
columnsMap[column.Name] = true
}
for _, field := range db.Statement.Schema.PrimaryFields {
if _, ok := columnsMap[field.DBName]; !ok {
hasConflict = false
}
}
} else {
hasConflict = false
}
}
if hasConflict {
MergeCreate(db, onConflict, values)
} else {
setIdentityInsert := false
if db.Statement.Schema != nil {
if field := db.Statement.Schema.PrioritizedPrimaryField; field != nil && field.AutoIncrement {
switch db.Statement.ReflectValue.Kind() {
case reflect.Struct:
_, isZero := field.ValueOf(db.Statement.Context, db.Statement.ReflectValue)
setIdentityInsert = !isZero
case reflect.Slice, reflect.Array:
for i := 0; i < db.Statement.ReflectValue.Len(); {
obj := db.Statement.ReflectValue.Index(i)
if reflect.Indirect(obj).Kind() == reflect.Struct {
_, isZero := field.ValueOf(db.Statement.Context, db.Statement.ReflectValue.Index(i))
setIdentityInsert = !isZero
}
break
}
default:
}
if setIdentityInsert && !db.DryRun && db.Error == nil {
db.Statement.SQL.Reset()
_, _ = db.Statement.WriteString("SET IDENTITY_INSERT ")
db.Statement.WriteQuoted(db.Statement.Table)
_, _ = db.Statement.WriteString(" ON;")
_, err := db.Statement.ConnPool.ExecContext(db.Statement.Context, db.Statement.SQL.String(), db.Statement.Vars...)
if db.AddError(err) != nil {
return
}
defer func() {
db.Statement.SQL.Reset()
_, _ = db.Statement.WriteString("SET IDENTITY_INSERT ")
db.Statement.WriteQuoted(db.Statement.Table)
_, _ = db.Statement.WriteString(" OFF;")
_, _ = db.Statement.ConnPool.ExecContext(db.Statement.Context, db.Statement.SQL.String(), db.Statement.Vars...)
}()
}
}
}
db.Statement.SQL.Reset()
db.Statement.AddClauseIfNotExists(clause.Insert{})
db.Statement.Build("INSERT")
_ = db.Statement.WriteByte(' ')
db.Statement.AddClause(values)
if values, ok := db.Statement.Clauses["VALUES"].Expression.(clause.Values); ok {
if len(values.Columns) > 0 {
_ = db.Statement.WriteByte('(')
for idx, column := range values.Columns {
if idx > 0 {
_ = db.Statement.WriteByte(',')
}
db.Statement.WriteQuoted(column)
}
_ = db.Statement.WriteByte(')')
//outputInserted(db)
_, _ = db.Statement.WriteString(" VALUES ")
for idx, value := range values.Values {
if idx > 0 {
_ = db.Statement.WriteByte(',')
}
_ = db.Statement.WriteByte('(')
db.Statement.AddVar(db.Statement, value...)
_ = db.Statement.WriteByte(')')
}
_, _ = db.Statement.WriteString(";")
} else {
_, _ = db.Statement.WriteString("DEFAULT VALUES;")
}
}
}
}
if !db.DryRun && db.Error == nil {
var (
rows *sql.Rows
result sql.Result
err error
updateInsertID bool // 是否需要更新主键自增列
insertID int64 // 主键自增列最新值
)
if hasConflict {
rows, err = db.Statement.ConnPool.QueryContext(db.Statement.Context, db.Statement.SQL.String(), db.Statement.Vars...)
if db.AddError(err) != nil {
return
}
defer func(rows *sql.Rows) {
_ = rows.Close()
}(rows)
if rows.Next() {
_ = rows.Scan(&insertID)
if insertID > 0 {
updateInsertID = true
}
}
} else {
result, err = db.Statement.ConnPool.ExecContext(db.Statement.Context, db.Statement.SQL.String(), db.Statement.Vars...)
if db.AddError(err) != nil {
return
}
db.RowsAffected, _ = result.RowsAffected()
if db.RowsAffected != 0 && db.Statement.Schema != nil &&
db.Statement.Schema.PrioritizedPrimaryField != nil &&
db.Statement.Schema.PrioritizedPrimaryField.HasDefaultValue {
insertID, err = result.LastInsertId()
insertOk := err == nil && insertID > 0
if !insertOk {
_ = db.AddError(err)
return
}
updateInsertID = true
}
}
if updateInsertID {
switch db.Statement.ReflectValue.Kind() {
case reflect.Slice, reflect.Array:
//if config.LastInsertIDReversed {
for i := db.Statement.ReflectValue.Len() - 1; i >= 0; i-- {
rv := db.Statement.ReflectValue.Index(i)
if reflect.Indirect(rv).Kind() != reflect.Struct {
break
}
_, isZero := db.Statement.Schema.PrioritizedPrimaryField.ValueOf(db.Statement.Context, rv)
if isZero {
_ = db.AddError(db.Statement.Schema.PrioritizedPrimaryField.Set(db.Statement.Context, rv, insertID))
insertID -= db.Statement.Schema.PrioritizedPrimaryField.AutoIncrementIncrement
}
}
//} else {
// for i := 0; i < db.Statement.ReflectValue.Len(); i++ {
// rv := db.Statement.ReflectValue.Index(i)
// if reflect.Indirect(rv).Kind() != reflect.Struct {
// break
// }
//
// if _, isZero := db.Statement.Schema.PrioritizedPrimaryField.ValueOf(db.Statement.Context, rv); isZero {
// db.AddError(db.Statement.Schema.PrioritizedPrimaryField.Set(db.Statement.Context, rv, insertID))
// insertID += db.Statement.Schema.PrioritizedPrimaryField.AutoIncrementIncrement
// }
// }
//}
case reflect.Struct:
_, isZero := db.Statement.Schema.PrioritizedPrimaryField.ValueOf(db.Statement.Context, db.Statement.ReflectValue)
if isZero {
_ = db.AddError(db.Statement.Schema.PrioritizedPrimaryField.Set(db.Statement.Context, db.Statement.ReflectValue, insertID))
}
default:
}
}
}
}
func MergeCreate(db *gorm.DB, onConflict clause.OnConflict, values clause.Values) {
_, _ = db.Statement.WriteString("MERGE INTO ")
db.Statement.WriteQuoted(db.Statement.Table)
_, _ = db.Statement.WriteString(" USING (")
for idx, value := range values.Values {
if idx > 0 {
_, _ = db.Statement.WriteString(" UNION ALL ")
}
_, _ = db.Statement.WriteString("SELECT ")
db.Statement.AddVar(db.Statement, value...)
_, _ = db.Statement.WriteString(" FROM DUAL")
}
_, _ = db.Statement.WriteString(`) AS "excluded" (`)
for idx, column := range values.Columns {
if idx > 0 {
_ = db.Statement.WriteByte(',')
}
db.Statement.WriteQuoted(column.Name)
}
_, _ = db.Statement.WriteString(") ON ")
var where clause.Where
for _, field := range db.Statement.Schema.PrimaryFields {
where.Exprs = append(where.Exprs, clause.Eq{
Column: clause.Column{Table: db.Statement.Table, Name: field.DBName},
Value: clause.Column{Table: "excluded", Name: field.DBName},
})
}
where.Build(db.Statement)
if len(onConflict.DoUpdates) > 0 {
// 将UPDATE子句中出现在关联条件中的列去除(即上面的ON子句),否则会报错:-4064:不能更新关联条件中的列
var withoutOnColumns = make([]clause.Assignment, 0, len(onConflict.DoUpdates))
a:
for _, assignment := range onConflict.DoUpdates {
for _, field := range db.Statement.Schema.PrimaryFields {
if assignment.Column.Name == field.DBName {
continue a
}
}
withoutOnColumns = append(withoutOnColumns, assignment)
}
onConflict.DoUpdates = withoutOnColumns
if len(onConflict.DoUpdates) > 0 {
_, _ = db.Statement.WriteString(" WHEN MATCHED THEN UPDATE SET ")
onConflict.DoUpdates.Build(db.Statement)
}
}
_, _ = db.Statement.WriteString(" WHEN NOT MATCHED THEN INSERT (")
written := false
for _, column := range values.Columns {
if db.Statement.Schema.PrioritizedPrimaryField == nil || !db.Statement.Schema.PrioritizedPrimaryField.AutoIncrement || db.Statement.Schema.PrioritizedPrimaryField.DBName != column.Name {
if written {
_ = db.Statement.WriteByte(',')
}
written = true
db.Statement.WriteQuoted(column.Name)
}
}
_, _ = db.Statement.WriteString(") VALUES (")
written = false
for _, column := range values.Columns {
if db.Statement.Schema.PrioritizedPrimaryField == nil || !db.Statement.Schema.PrioritizedPrimaryField.AutoIncrement || db.Statement.Schema.PrioritizedPrimaryField.DBName != column.Name {
if written {
_ = db.Statement.WriteByte(',')
}
written = true
db.Statement.WriteQuoted(clause.Column{
Table: "excluded",
Name: column.Name,
})
}
}
_, _ = db.Statement.WriteString(")")
//outputInserted(db)
_, _ = db.Statement.WriteString(";")
// merge into 语句插入的记录,无法通过LastInsertID获取
if db.Statement.Schema.PrioritizedPrimaryField != nil && db.Statement.Schema.PrioritizedPrimaryField.AutoIncrement {
_, _ = db.Statement.WriteString("SELECT ")
db.Statement.WriteQuoted(db.Statement.Schema.PrioritizedPrimaryField.DBName)
_, _ = db.Statement.WriteString(" FROM ")
db.Statement.WriteQuoted(db.Statement.Table)
_, _ = db.Statement.WriteString(" ORDER BY ")
db.Statement.WriteQuoted(db.Statement.Schema.PrioritizedPrimaryField.DBName)
_, _ = db.Statement.WriteString(" DESC LIMIT 1;")
}
}