| 1 |
package callbacks |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"reflect" |
| 6 |
"strings" |
| 7 |
|
| 8 |
"gorm.io/gorm" |
| 9 |
"gorm.io/gorm/clause" |
| 10 |
"gorm.io/gorm/schema" |
| 11 |
"gorm.io/gorm/utils" |
| 12 |
) |
| 13 |
|
| 14 |
// BeforeCreate before create hooks |
| 15 |
func BeforeCreate(db *gorm.DB) { |
| 16 |
if db.Error == nil && db.Statement.Schema != nil && !db.Statement.SkipHooks && (db.Statement.Schema.BeforeSave || db.Statement.Schema.BeforeCreate) { |
| 17 |
callMethod(db, func(value interface{}, tx *gorm.DB) (called bool) { |
| 18 |
if db.Statement.Schema.BeforeSave { |
| 19 |
if i, ok := value.(BeforeSaveInterface); ok { |
| 20 |
called = true |
| 21 |
db.AddError(i.BeforeSave(tx)) |
| 22 |
} |
| 23 |
} |
| 24 |
|
| 25 |
if db.Statement.Schema.BeforeCreate { |
| 26 |
if i, ok := value.(BeforeCreateInterface); ok { |
| 27 |
called = true |
| 28 |
db.AddError(i.BeforeCreate(tx)) |
| 29 |
} |
| 30 |
} |
| 31 |
return called |
| 32 |
}) |
| 33 |
} |
| 34 |
} |
| 35 |
|
| 36 |
// Create create hook |
| 37 |
func Create(config *Config) func(db *gorm.DB) { |
| 38 |
supportReturning := utils.Contains(config.CreateClauses, "RETURNING") |
| 39 |
|
| 40 |
return func(db *gorm.DB) { |
| 41 |
if db.Error != nil { |
| 42 |
return |
| 43 |
} |
| 44 |
|
| 45 |
if db.Statement.Schema != nil { |
| 46 |
if !db.Statement.Unscoped { |
| 47 |
for _, c := range db.Statement.Schema.CreateClauses { |
| 48 |
db.Statement.AddClause(c) |
| 49 |
} |
| 50 |
} |
| 51 |
|
| 52 |
if supportReturning && len(db.Statement.Schema.FieldsWithDefaultDBValue) > 0 { |
| 53 |
if _, ok := db.Statement.Clauses["RETURNING"]; !ok { |
| 54 |
fromColumns := make([]clause.Column, 0, len(db.Statement.Schema.FieldsWithDefaultDBValue)) |
| 55 |
for _, field := range db.Statement.Schema.FieldsWithDefaultDBValue { |
| 56 |
if field.Readable { |
| 57 |
fromColumns = append(fromColumns, clause.Column{Name: field.DBName}) |
| 58 |
} |
| 59 |
} |
| 60 |
if len(fromColumns) > 0 { |
| 61 |
db.Statement.AddClause(clause.Returning{Columns: fromColumns}) |
| 62 |
} |
| 63 |
} |
| 64 |
} |
| 65 |
} |
| 66 |
|
| 67 |
if db.Statement.SQL.Len() == 0 { |
| 68 |
db.Statement.SQL.Grow(180) |
| 69 |
db.Statement.AddClauseIfNotExists(clause.Insert{}) |
| 70 |
db.Statement.AddClause(ConvertToCreateValues(db.Statement)) |
| 71 |
|
| 72 |
db.Statement.Build(db.Statement.BuildClauses...) |
| 73 |
} |
| 74 |
|
| 75 |
isDryRun := !db.DryRun && db.Error == nil |
| 76 |
if !isDryRun { |
| 77 |
return |
| 78 |
} |
| 79 |
|
| 80 |
ok, mode := hasReturning(db, supportReturning) |
| 81 |
if ok { |
| 82 |
if c, ok := db.Statement.Clauses["ON CONFLICT"]; ok { |
| 83 |
onConflict, _ := c.Expression.(clause.OnConflict) |
| 84 |
if onConflict.DoNothing { |
| 85 |
mode |= gorm.ScanOnConflictDoNothing |
| 86 |
} else if len(onConflict.DoUpdates) > 0 || onConflict.UpdateAll { |
| 87 |
mode |= gorm.ScanUpdate |
| 88 |
} |
| 89 |
} |
| 90 |
|
| 91 |
rows, err := db.Statement.ConnPool.QueryContext( |
| 92 |
db.Statement.Context, db.Statement.SQL.String(), db.Statement.Vars..., |
| 93 |
) |
| 94 |
if db.AddError(err) == nil { |
| 95 |
defer func() { |
| 96 |
db.AddError(rows.Close()) |
| 97 |
}() |
| 98 |
gorm.Scan(rows, db, mode) |
| 99 |
|
| 100 |
if db.Statement.Result != nil { |
| 101 |
db.Statement.Result.RowsAffected = db.RowsAffected |
| 102 |
} |
| 103 |
} |
| 104 |
|
| 105 |
return |
| 106 |
} |
| 107 |
|
| 108 |
result, err := db.Statement.ConnPool.ExecContext( |
| 109 |
db.Statement.Context, db.Statement.SQL.String(), db.Statement.Vars..., |
| 110 |
) |
| 111 |
if err != nil { |
| 112 |
db.AddError(err) |
| 113 |
return |
| 114 |
} |
| 115 |
|
| 116 |
db.RowsAffected, _ = result.RowsAffected() |
| 117 |
|
| 118 |
if db.Statement.Result != nil { |
| 119 |
db.Statement.Result.Result = result |
| 120 |
db.Statement.Result.RowsAffected = db.RowsAffected |
| 121 |
} |
| 122 |
|
| 123 |
if db.RowsAffected == 0 { |
| 124 |
return |
| 125 |
} |
| 126 |
|
| 127 |
var ( |
| 128 |
pkField *schema.Field |
| 129 |
pkFieldName = "@id" |
| 130 |
) |
| 131 |
|
| 132 |
if db.Statement.Schema != nil { |
| 133 |
if db.Statement.Schema.PrioritizedPrimaryField == nil || |
| 134 |
!db.Statement.Schema.PrioritizedPrimaryField.HasDefaultValue || |
| 135 |
!db.Statement.Schema.PrioritizedPrimaryField.Readable { |
| 136 |
return |
| 137 |
} |
| 138 |
pkField = db.Statement.Schema.PrioritizedPrimaryField |
| 139 |
pkFieldName = db.Statement.Schema.PrioritizedPrimaryField.DBName |
| 140 |
} |
| 141 |
|
| 142 |
insertID, err := result.LastInsertId() |
| 143 |
insertOk := err == nil && insertID > 0 |
| 144 |
|
| 145 |
if !insertOk { |
| 146 |
if !supportReturning { |
| 147 |
db.AddError(err) |
| 148 |
} |
| 149 |
return |
| 150 |
} |
| 151 |
|
| 152 |
// append @id column with value for auto-increment primary key |
| 153 |
// the @id value is correct, when: 1. without setting auto-increment primary key, 2. database AutoIncrementIncrement = 1 |
| 154 |
switch values := db.Statement.Dest.(type) { |
| 155 |
case map[string]interface{}: |
| 156 |
values[pkFieldName] = insertID |
| 157 |
case *map[string]interface{}: |
| 158 |
(*values)[pkFieldName] = insertID |
| 159 |
case []map[string]interface{}, *[]map[string]interface{}: |
| 160 |
mapValues, ok := values.([]map[string]interface{}) |
| 161 |
if !ok { |
| 162 |
if v, ok := values.(*[]map[string]interface{}); ok { |
| 163 |
if *v != nil { |
| 164 |
mapValues = *v |
| 165 |
} |
| 166 |
} |
| 167 |
} |
| 168 |
|
| 169 |
if config.LastInsertIDReversed { |
| 170 |
insertID -= int64(len(mapValues)-1) * schema.DefaultAutoIncrementIncrement |
| 171 |
} |
| 172 |
|
| 173 |
for _, mapValue := range mapValues { |
| 174 |
if mapValue != nil { |
| 175 |
mapValue[pkFieldName] = insertID |
| 176 |
} |
| 177 |
insertID += schema.DefaultAutoIncrementIncrement |
| 178 |
} |
| 179 |
default: |
| 180 |
if pkField == nil { |
| 181 |
return |
| 182 |
} |
| 183 |
|
| 184 |
switch db.Statement.ReflectValue.Kind() { |
| 185 |
case reflect.Slice, reflect.Array: |
| 186 |
if config.LastInsertIDReversed { |
| 187 |
for i := db.Statement.ReflectValue.Len() - 1; i >= 0; i-- { |
| 188 |
rv := db.Statement.ReflectValue.Index(i) |
| 189 |
if reflect.Indirect(rv).Kind() != reflect.Struct { |
| 190 |
break |
| 191 |
} |
| 192 |
|
| 193 |
_, isZero := pkField.ValueOf(db.Statement.Context, rv) |
| 194 |
if isZero { |
| 195 |
db.AddError(pkField.Set(db.Statement.Context, rv, insertID)) |
| 196 |
insertID -= pkField.AutoIncrementIncrement |
| 197 |
} |
| 198 |
} |
| 199 |
} else { |
| 200 |
for i := 0; i < db.Statement.ReflectValue.Len(); i++ { |
| 201 |
rv := db.Statement.ReflectValue.Index(i) |
| 202 |
if reflect.Indirect(rv).Kind() != reflect.Struct { |
| 203 |
break |
| 204 |
} |
| 205 |
|
| 206 |
if _, isZero := pkField.ValueOf(db.Statement.Context, rv); isZero { |
| 207 |
db.AddError(pkField.Set(db.Statement.Context, rv, insertID)) |
| 208 |
insertID += pkField.AutoIncrementIncrement |
| 209 |
} |
| 210 |
} |
| 211 |
} |
| 212 |
case reflect.Struct: |
| 213 |
_, isZero := pkField.ValueOf(db.Statement.Context, db.Statement.ReflectValue) |
| 214 |
if isZero { |
| 215 |
db.AddError(pkField.Set(db.Statement.Context, db.Statement.ReflectValue, insertID)) |
| 216 |
} |
| 217 |
} |
| 218 |
} |
| 219 |
} |
| 220 |
} |
| 221 |
|
| 222 |
// AfterCreate after create hooks |
| 223 |
func AfterCreate(db *gorm.DB) { |
| 224 |
if db.Error == nil && db.Statement.Schema != nil && !db.Statement.SkipHooks && (db.Statement.Schema.AfterSave || db.Statement.Schema.AfterCreate) { |
| 225 |
callMethod(db, func(value interface{}, tx *gorm.DB) (called bool) { |
| 226 |
if db.Statement.Schema.AfterCreate { |
| 227 |
if i, ok := value.(AfterCreateInterface); ok { |
| 228 |
called = true |
| 229 |
db.AddError(i.AfterCreate(tx)) |
| 230 |
} |
| 231 |
} |
| 232 |
|
| 233 |
if db.Statement.Schema.AfterSave { |
| 234 |
if i, ok := value.(AfterSaveInterface); ok { |
| 235 |
called = true |
| 236 |
db.AddError(i.AfterSave(tx)) |
| 237 |
} |
| 238 |
} |
| 239 |
return called |
| 240 |
}) |
| 241 |
} |
| 242 |
} |
| 243 |
|
| 244 |
// ConvertToCreateValues convert to create values |
| 245 |
func ConvertToCreateValues(stmt *gorm.Statement) (values clause.Values) { |
| 246 |
curTime := stmt.DB.NowFunc() |
| 247 |
|
| 248 |
switch value := stmt.Dest.(type) { |
| 249 |
case map[string]interface{}: |
| 250 |
values = ConvertMapToValuesForCreate(stmt, value) |
| 251 |
case *map[string]interface{}: |
| 252 |
values = ConvertMapToValuesForCreate(stmt, *value) |
| 253 |
case []map[string]interface{}: |
| 254 |
values = ConvertSliceOfMapToValuesForCreate(stmt, value) |
| 255 |
case *[]map[string]interface{}: |
| 256 |
values = ConvertSliceOfMapToValuesForCreate(stmt, *value) |
| 257 |
default: |
| 258 |
var ( |
| 259 |
selectColumns, restricted = stmt.SelectAndOmitColumns(true, false) |
| 260 |
_, updateTrackTime = stmt.Get("gorm:update_track_time") |
| 261 |
isZero bool |
| 262 |
) |
| 263 |
stmt.Settings.Delete("gorm:update_track_time") |
| 264 |
|
| 265 |
values = clause.Values{Columns: make([]clause.Column, 0, len(stmt.Schema.DBNames))} |
| 266 |
|
| 267 |
for _, db := range stmt.Schema.DBNames { |
| 268 |
if field := stmt.Schema.FieldsByDBName[db]; !field.HasDefaultValue || field.DefaultValueInterface != nil { |
| 269 |
if v, ok := selectColumns[db]; (ok && v) || (!ok && (!restricted || field.AutoCreateTime > 0 || field.AutoUpdateTime > 0)) { |
| 270 |
values.Columns = append(values.Columns, clause.Column{Name: db}) |
| 271 |
} |
| 272 |
} |
| 273 |
} |
| 274 |
|
| 275 |
switch stmt.ReflectValue.Kind() { |
| 276 |
case reflect.Slice, reflect.Array: |
| 277 |
rValLen := stmt.ReflectValue.Len() |
| 278 |
if rValLen == 0 { |
| 279 |
stmt.AddError(gorm.ErrEmptySlice) |
| 280 |
return |
| 281 |
} |
| 282 |
|
| 283 |
stmt.SQL.Grow(rValLen * 18) |
| 284 |
stmt.Vars = make([]interface{}, 0, rValLen*len(values.Columns)) |
| 285 |
values.Values = make([][]interface{}, rValLen) |
| 286 |
|
| 287 |
defaultValueFieldsHavingValue := map[*schema.Field][]interface{}{} |
| 288 |
for i := 0; i < rValLen; i++ { |
| 289 |
rv := reflect.Indirect(stmt.ReflectValue.Index(i)) |
| 290 |
if !rv.IsValid() { |
| 291 |
stmt.AddError(fmt.Errorf("slice data #%v is invalid: %w", i, gorm.ErrInvalidData)) |
| 292 |
return |
| 293 |
} |
| 294 |
|
| 295 |
values.Values[i] = make([]interface{}, len(values.Columns)) |
| 296 |
for idx, column := range values.Columns { |
| 297 |
field := stmt.Schema.FieldsByDBName[column.Name] |
| 298 |
if values.Values[i][idx], isZero = field.ValueOf(stmt.Context, rv); isZero { |
| 299 |
if field.DefaultValueInterface != nil { |
| 300 |
values.Values[i][idx] = field.DefaultValueInterface |
| 301 |
stmt.AddError(field.Set(stmt.Context, rv, field.DefaultValueInterface)) |
| 302 |
} else if field.AutoCreateTime > 0 || field.AutoUpdateTime > 0 { |
| 303 |
stmt.AddError(field.Set(stmt.Context, rv, curTime)) |
| 304 |
values.Values[i][idx], _ = field.ValueOf(stmt.Context, rv) |
| 305 |
} |
| 306 |
} else if field.AutoUpdateTime > 0 && updateTrackTime { |
| 307 |
stmt.AddError(field.Set(stmt.Context, rv, curTime)) |
| 308 |
values.Values[i][idx], _ = field.ValueOf(stmt.Context, rv) |
| 309 |
} |
| 310 |
} |
| 311 |
|
| 312 |
for _, field := range stmt.Schema.FieldsWithDefaultDBValue { |
| 313 |
if v, ok := selectColumns[field.DBName]; (ok && v) || (!ok && !restricted) { |
| 314 |
if rvOfvalue, isZero := field.ValueOf(stmt.Context, rv); !isZero { |
| 315 |
if len(defaultValueFieldsHavingValue[field]) == 0 { |
| 316 |
defaultValueFieldsHavingValue[field] = make([]interface{}, rValLen) |
| 317 |
} |
| 318 |
defaultValueFieldsHavingValue[field][i] = rvOfvalue |
| 319 |
} |
| 320 |
} |
| 321 |
} |
| 322 |
} |
| 323 |
|
| 324 |
for _, field := range stmt.Schema.FieldsWithDefaultDBValue { |
| 325 |
if vs, ok := defaultValueFieldsHavingValue[field]; ok { |
| 326 |
values.Columns = append(values.Columns, clause.Column{Name: field.DBName}) |
| 327 |
for idx := range values.Values { |
| 328 |
if vs[idx] == nil { |
| 329 |
values.Values[idx] = append(values.Values[idx], stmt.DefaultValueOf(field)) |
| 330 |
} else { |
| 331 |
values.Values[idx] = append(values.Values[idx], vs[idx]) |
| 332 |
} |
| 333 |
} |
| 334 |
} |
| 335 |
} |
| 336 |
case reflect.Struct: |
| 337 |
values.Values = [][]interface{}{make([]interface{}, len(values.Columns))} |
| 338 |
for idx, column := range values.Columns { |
| 339 |
field := stmt.Schema.FieldsByDBName[column.Name] |
| 340 |
if values.Values[0][idx], isZero = field.ValueOf(stmt.Context, stmt.ReflectValue); isZero { |
| 341 |
if field.DefaultValueInterface != nil { |
| 342 |
values.Values[0][idx] = field.DefaultValueInterface |
| 343 |
stmt.AddError(field.Set(stmt.Context, stmt.ReflectValue, field.DefaultValueInterface)) |
| 344 |
} else if field.AutoCreateTime > 0 || field.AutoUpdateTime > 0 { |
| 345 |
stmt.AddError(field.Set(stmt.Context, stmt.ReflectValue, curTime)) |
| 346 |
values.Values[0][idx], _ = field.ValueOf(stmt.Context, stmt.ReflectValue) |
| 347 |
} |
| 348 |
} else if field.AutoUpdateTime > 0 && updateTrackTime { |
| 349 |
stmt.AddError(field.Set(stmt.Context, stmt.ReflectValue, curTime)) |
| 350 |
values.Values[0][idx], _ = field.ValueOf(stmt.Context, stmt.ReflectValue) |
| 351 |
} |
| 352 |
} |
| 353 |
|
| 354 |
for _, field := range stmt.Schema.FieldsWithDefaultDBValue { |
| 355 |
if v, ok := selectColumns[field.DBName]; (ok && v) || (!ok && !restricted) && field.DefaultValueInterface == nil { |
| 356 |
if rvOfvalue, isZero := field.ValueOf(stmt.Context, stmt.ReflectValue); !isZero { |
| 357 |
values.Columns = append(values.Columns, clause.Column{Name: field.DBName}) |
| 358 |
values.Values[0] = append(values.Values[0], rvOfvalue) |
| 359 |
} |
| 360 |
} |
| 361 |
} |
| 362 |
default: |
| 363 |
stmt.AddError(gorm.ErrInvalidData) |
| 364 |
} |
| 365 |
} |
| 366 |
|
| 367 |
if c, ok := stmt.Clauses["ON CONFLICT"]; ok { |
| 368 |
if onConflict, _ := c.Expression.(clause.OnConflict); onConflict.UpdateAll { |
| 369 |
if stmt.Schema != nil && len(values.Columns) >= 1 { |
| 370 |
selectColumns, restricted := stmt.SelectAndOmitColumns(true, true) |
| 371 |
|
| 372 |
columns := make([]string, 0, len(values.Columns)-1) |
| 373 |
for _, column := range values.Columns { |
| 374 |
if field := stmt.Schema.LookUpField(column.Name); field != nil { |
| 375 |
if v, ok := selectColumns[field.DBName]; (ok && v) || (!ok && !restricted) { |
| 376 |
if !field.PrimaryKey && (!field.HasDefaultValue || field.DefaultValueInterface != nil || |
| 377 |
strings.EqualFold(field.DefaultValue, "NULL")) && field.AutoCreateTime == 0 { |
| 378 |
if field.AutoUpdateTime > 0 { |
| 379 |
assignment := clause.Assignment{Column: clause.Column{Name: field.DBName}, Value: curTime} |
| 380 |
switch field.AutoUpdateTime { |
| 381 |
case schema.UnixNanosecond: |
| 382 |
assignment.Value = curTime.UnixNano() |
| 383 |
case schema.UnixMillisecond: |
| 384 |
assignment.Value = curTime.UnixMilli() |
| 385 |
case schema.UnixSecond: |
| 386 |
assignment.Value = curTime.Unix() |
| 387 |
} |
| 388 |
|
| 389 |
onConflict.DoUpdates = append(onConflict.DoUpdates, assignment) |
| 390 |
} else { |
| 391 |
columns = append(columns, column.Name) |
| 392 |
} |
| 393 |
} |
| 394 |
} |
| 395 |
} |
| 396 |
} |
| 397 |
|
| 398 |
onConflict.DoUpdates = append(onConflict.DoUpdates, clause.AssignmentColumns(columns)...) |
| 399 |
if len(onConflict.DoUpdates) == 0 { |
| 400 |
onConflict.DoNothing = true |
| 401 |
} |
| 402 |
|
| 403 |
// use primary fields as default OnConflict columns |
| 404 |
if len(onConflict.Columns) == 0 { |
| 405 |
for _, field := range stmt.Schema.PrimaryFields { |
| 406 |
onConflict.Columns = append(onConflict.Columns, clause.Column{Name: field.DBName}) |
| 407 |
} |
| 408 |
} |
| 409 |
stmt.AddClause(onConflict) |
| 410 |
} |
| 411 |
} |
| 412 |
} |
| 413 |
|
| 414 |
return values |
| 415 |
} |