@@ -19,6 +19,7 @@ func Create(db *gorm.DB) {
1919 }
2020 }
2121
22+ hasOutput := false
2223 if db .Statement .SQL .String () == "" {
2324 var (
2425 values = callbacks .ConvertToCreateValues (db .Statement )
@@ -44,7 +45,7 @@ func Create(db *gorm.DB) {
4445 }
4546
4647 if hasConflict {
47- MergeCreate (db , onConflict , values )
48+ hasOutput = MergeCreate (db , onConflict , values )
4849 } else {
4950 setIdentityInsert := false
5051
@@ -89,7 +90,7 @@ func Create(db *gorm.DB) {
8990 }
9091 db .Statement .WriteByte (')' )
9192
92- outputInserted (db )
93+ hasOutput = outputInserted (db )
9394
9495 db .Statement .WriteString (" VALUES " )
9596
@@ -118,7 +119,7 @@ func Create(db *gorm.DB) {
118119 }
119120
120121 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 {
122123 rows , err := db .Statement .ConnPool .QueryContext (db .Statement .Context , db .Statement .SQL .String (), db .Statement .Vars ... )
123124 if db .AddError (err ) == nil {
124125 defer rows .Close ()
@@ -140,7 +141,7 @@ func Create(db *gorm.DB) {
140141 }
141142}
142143
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 {
144145 db .Statement .WriteString ("MERGE INTO " )
145146 db .Statement .WriteQuoted (db .Statement .Table )
146147 db .Statement .WriteString (" USING (VALUES" )
@@ -207,19 +208,27 @@ func MergeCreate(db *gorm.DB, onConflict clause.OnConflict, values clause.Values
207208 }
208209
209210 db .Statement .WriteString (")" )
210- outputInserted (db )
211+ hasOutput := outputInserted (db )
211212 db .Statement .WriteString (";" )
213+ return hasOutput
212214}
213215
214- func outputInserted (db * gorm.DB ) {
216+ func outputInserted (db * gorm.DB ) ( hasOutput bool ) {
215217 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 {
219220 db .Statement .WriteString ("," )
220221 }
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+ }
223231 }
224232 }
233+ return hasOutput
225234}
0 commit comments