@@ -19,6 +19,7 @@ func Create(db *gorm.DB) {
19
19
}
20
20
}
21
21
22
+ hasOutput := false
22
23
if db .Statement .SQL .String () == "" {
23
24
var (
24
25
values = callbacks .ConvertToCreateValues (db .Statement )
@@ -44,7 +45,7 @@ func Create(db *gorm.DB) {
44
45
}
45
46
46
47
if hasConflict {
47
- MergeCreate (db , onConflict , values )
48
+ hasOutput = MergeCreate (db , onConflict , values )
48
49
} else {
49
50
setIdentityInsert := false
50
51
@@ -89,7 +90,7 @@ func Create(db *gorm.DB) {
89
90
}
90
91
db .Statement .WriteByte (')' )
91
92
92
- outputInserted (db )
93
+ hasOutput = outputInserted (db )
93
94
94
95
db .Statement .WriteString (" VALUES " )
95
96
@@ -118,7 +119,7 @@ func Create(db *gorm.DB) {
118
119
}
119
120
120
121
if ! db .DryRun && db .Error == nil {
121
- if db .Statement .Schema != nil && len ( db . Statement . Schema . FieldsWithDefaultDBValue ) > 0 {
122
+ if db .Statement .Schema != nil && hasOutput {
122
123
rows , err := db .Statement .ConnPool .QueryContext (db .Statement .Context , db .Statement .SQL .String (), db .Statement .Vars ... )
123
124
if db .AddError (err ) == nil {
124
125
defer rows .Close ()
@@ -140,7 +141,7 @@ func Create(db *gorm.DB) {
140
141
}
141
142
}
142
143
143
- func MergeCreate (db * gorm.DB , onConflict clause.OnConflict , values clause.Values ) {
144
+ func MergeCreate (db * gorm.DB , onConflict clause.OnConflict , values clause.Values ) bool {
144
145
db .Statement .WriteString ("MERGE INTO " )
145
146
db .Statement .WriteQuoted (db .Statement .Table )
146
147
db .Statement .WriteString (" USING (VALUES" )
@@ -207,19 +208,27 @@ func MergeCreate(db *gorm.DB, onConflict clause.OnConflict, values clause.Values
207
208
}
208
209
209
210
db .Statement .WriteString (")" )
210
- outputInserted (db )
211
+ hasOutput := outputInserted (db )
211
212
db .Statement .WriteString (";" )
213
+ return hasOutput
212
214
}
213
215
214
- func outputInserted (db * gorm.DB ) {
216
+ func outputInserted (db * gorm.DB ) ( hasOutput bool ) {
215
217
if db .Statement .Schema != nil && len (db .Statement .Schema .FieldsWithDefaultDBValue ) > 0 {
216
- db .Statement .WriteString (" OUTPUT" )
217
- for idx , field := range db .Statement .Schema .FieldsWithDefaultDBValue {
218
- if idx > 0 {
218
+ for _ , field := range db .Statement .Schema .FieldsWithDefaultDBValue {
219
+ if hasOutput {
219
220
db .Statement .WriteString ("," )
220
221
}
221
- db .Statement .WriteString (" INSERTED." )
222
- db .Statement .AddVar (db .Statement , clause.Column {Name : field .DBName })
222
+ if field .Readable {
223
+ if ! hasOutput {
224
+ db .Statement .WriteString (" OUTPUT INSERTED." )
225
+ hasOutput = true
226
+ } else {
227
+ db .Statement .WriteString (" INSERTED." )
228
+ }
229
+ db .Statement .AddVar (db .Statement , clause.Column {Name : field .DBName })
230
+ }
223
231
}
224
232
}
233
+ return hasOutput
225
234
}
0 commit comments