forked from go-gorm/sqlserver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate.go
More file actions
340 lines (301 loc) · 9.59 KB
/
create.go
File metadata and controls
340 lines (301 loc) · 9.59 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
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
package sqlserver
import (
"reflect"
"gorm.io/gorm"
"gorm.io/gorm/callbacks"
"gorm.io/gorm/clause"
"gorm.io/gorm/schema"
)
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)
}
}
hasOutput := false
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(onConflict.Columns) > 0 {
columnsMap := map[string]bool{}
for _, column := range values.Columns {
columnsMap[column.Name] = true
}
for _, conflictColumn := range onConflict.Columns {
if _, ok := columnsMap[conflictColumn.Name]; !ok {
hasConflict = false
break
}
}
} else 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
break
}
}
} else {
hasConflict = false
}
}
if hasConflict {
hasOutput = 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(); i++ {
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
}
}
if setIdentityInsert {
db.Statement.WriteString("SET IDENTITY_INSERT ")
db.Statement.WriteQuoted(db.Statement.Table)
db.Statement.WriteString(" ON;")
}
}
}
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(')')
hasOutput = 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 setIdentityInsert {
db.Statement.WriteString("SET IDENTITY_INSERT ")
db.Statement.WriteQuoted(db.Statement.Table)
db.Statement.WriteString(" OFF;")
}
}
}
if !db.DryRun && db.Error == nil {
if db.Statement.Schema != nil && hasOutput {
rows, err := db.Statement.ConnPool.QueryContext(db.Statement.Context, db.Statement.SQL.String(), db.Statement.Vars...)
if db.AddError(err) == nil {
defer rows.Close()
gorm.Scan(rows, db, gorm.ScanUpdate|gorm.ScanOnConflictDoNothing)
if db.Statement.Result != nil {
db.Statement.Result.RowsAffected = db.RowsAffected
}
}
} else {
result, err := db.Statement.ConnPool.ExecContext(db.Statement.Context, db.Statement.SQL.String(), db.Statement.Vars...)
if db.AddError(err) == nil {
db.RowsAffected, _ = result.RowsAffected()
if db.Statement.Result != nil {
db.Statement.Result.Result = result
db.Statement.Result.RowsAffected = db.RowsAffected
}
}
}
}
}
func MergeCreate(db *gorm.DB, onConflict clause.OnConflict, values clause.Values) bool {
db.Statement.WriteString("MERGE INTO ")
db.Statement.WriteQuoted(db.Statement.Table)
db.Statement.WriteString(" USING (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(") 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
if len(onConflict.Columns) > 0 {
for _, conflictColumn := range onConflict.Columns {
where.Exprs = append(where.Exprs, clause.Eq{
Column: clause.Column{Table: db.Statement.Table, Name: conflictColumn.Name},
Value: clause.Column{Table: "excluded", Name: conflictColumn.Name},
})
}
} else if len(db.Statement.Schema.PrimaryFields) > 0 {
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 !onConflict.DoNothing && (len(onConflict.DoUpdates) > 0 || onConflict.UpdateAll) {
if onConflict.UpdateAll {
conflictColumnMap := make(map[string]bool)
for _, conflictColumn := range onConflict.Columns {
conflictColumnMap[conflictColumn.Name] = true
}
// Get select and omit columns with requireUpdate=true to respect field.Updatable
selectColumns, restricted := db.Statement.SelectAndOmitColumns(true, true)
curTime := db.Statement.DB.NowFunc()
// Collect columns to update and check if there are any
type updateColumn struct {
name string
useCurrentTime bool
autoUpdateTime schema.TimeType
}
var updateColumns []updateColumn
for _, column := range values.Columns {
if conflictColumnMap[column.Name] {
continue
}
// Check if the field should be updated based on SelectAndOmitColumns result
if v, ok := selectColumns[column.Name]; (ok && !v) || (restricted && !ok) {
continue
}
// Get the field to check additional properties
if field := db.Statement.Schema.LookUpField(column.Name); field != nil {
// Skip primary keys, autoCreateTime fields
if field.PrimaryKey || field.AutoCreateTime > 0 {
continue
}
// Handle AutoUpdateTime fields with current time
if field.AutoUpdateTime > 0 {
updateColumns = append(updateColumns, updateColumn{
name: column.Name,
useCurrentTime: true,
autoUpdateTime: field.AutoUpdateTime,
})
continue
}
}
updateColumns = append(updateColumns, updateColumn{
name: column.Name,
useCurrentTime: false,
})
}
// Only generate WHEN MATCHED clause if there are columns to update
if len(updateColumns) > 0 {
db.Statement.WriteString(" WHEN MATCHED THEN UPDATE SET ")
for i, col := range updateColumns {
if i > 0 {
db.Statement.WriteString(", ")
}
db.Statement.WriteQuoted(col.name)
db.Statement.WriteString(" = ")
if col.useCurrentTime {
// Use current time for AutoUpdateTime fields
var timeValue interface{}
switch col.autoUpdateTime {
case schema.UnixNanosecond:
timeValue = curTime.UnixNano()
case schema.UnixMillisecond:
timeValue = curTime.UnixMilli()
case schema.UnixSecond:
timeValue = curTime.Unix()
default:
timeValue = curTime
}
db.Statement.AddVar(db.Statement, timeValue)
} else {
db.Statement.WriteString("excluded.")
db.Statement.WriteQuoted(col.name)
}
}
}
} else {
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(")")
hasOutput := outputInserted(db)
db.Statement.WriteString(";")
return hasOutput
}
func outputInserted(db *gorm.DB) (hasOutput bool) {
if db.Statement.Schema != nil && len(db.Statement.Schema.FieldsWithDefaultDBValue) > 0 {
for _, field := range db.Statement.Schema.FieldsWithDefaultDBValue {
if hasOutput {
db.Statement.WriteString(",")
}
if field.Readable {
if !hasOutput {
db.Statement.WriteString(" OUTPUT INSERTED.")
hasOutput = true
} else {
db.Statement.WriteString(" INSERTED.")
}
db.Statement.AddVar(db.Statement, clause.Column{Name: field.DBName})
}
}
}
return hasOutput
}