| 1 |
package callbacks |
| 2 |
|
| 3 |
import ( |
| 4 |
"reflect" |
| 5 |
"strings" |
| 6 |
|
| 7 |
"gorm.io/gorm" |
| 8 |
"gorm.io/gorm/clause" |
| 9 |
"gorm.io/gorm/schema" |
| 10 |
"gorm.io/gorm/utils" |
| 11 |
) |
| 12 |
|
| 13 |
func SaveBeforeAssociations(create bool) func(db *gorm.DB) { |
| 14 |
return func(db *gorm.DB) { |
| 15 |
if db.Error == nil && db.Statement.Schema != nil { |
| 16 |
selectColumns, restricted := db.Statement.SelectAndOmitColumns(create, !create) |
| 17 |
|
| 18 |
// Save Belongs To associations |
| 19 |
for _, rel := range db.Statement.Schema.Relationships.BelongsTo { |
| 20 |
if v, ok := selectColumns[rel.Name]; (ok && !v) || (!ok && restricted) { |
| 21 |
continue |
| 22 |
} |
| 23 |
|
| 24 |
setupReferences := func(obj reflect.Value, elem reflect.Value) { |
| 25 |
for _, ref := range rel.References { |
| 26 |
if !ref.OwnPrimaryKey { |
| 27 |
pv, _ := ref.PrimaryKey.ValueOf(db.Statement.Context, elem) |
| 28 |
db.AddError(ref.ForeignKey.Set(db.Statement.Context, obj, pv)) |
| 29 |
|
| 30 |
if dest, ok := db.Statement.Dest.(map[string]interface{}); ok { |
| 31 |
dest[ref.ForeignKey.DBName] = pv |
| 32 |
if _, ok := dest[rel.Name]; ok { |
| 33 |
dest[rel.Name] = elem.Interface() |
| 34 |
} |
| 35 |
} |
| 36 |
} |
| 37 |
} |
| 38 |
} |
| 39 |
|
| 40 |
switch db.Statement.ReflectValue.Kind() { |
| 41 |
case reflect.Slice, reflect.Array: |
| 42 |
var ( |
| 43 |
rValLen = db.Statement.ReflectValue.Len() |
| 44 |
objs = make([]reflect.Value, 0, rValLen) |
| 45 |
fieldType = rel.Field.FieldType |
| 46 |
isPtr = fieldType.Kind() == reflect.Ptr |
| 47 |
) |
| 48 |
|
| 49 |
if !isPtr { |
| 50 |
fieldType = reflect.PointerTo(fieldType) |
| 51 |
} |
| 52 |
|
| 53 |
elems := reflect.MakeSlice(reflect.SliceOf(fieldType), 0, 10) |
| 54 |
distinctElems := reflect.MakeSlice(reflect.SliceOf(fieldType), 0, 10) |
| 55 |
identityMap := map[string]bool{} |
| 56 |
for i := 0; i < rValLen; i++ { |
| 57 |
obj := db.Statement.ReflectValue.Index(i) |
| 58 |
if reflect.Indirect(obj).Kind() != reflect.Struct { |
| 59 |
break |
| 60 |
} |
| 61 |
if _, zero := rel.Field.ValueOf(db.Statement.Context, obj); !zero { // check belongs to relation value |
| 62 |
rv := rel.Field.ReflectValueOf(db.Statement.Context, obj) // relation reflect value |
| 63 |
if !isPtr { |
| 64 |
rv = rv.Addr() |
| 65 |
} |
| 66 |
objs = append(objs, obj) |
| 67 |
elems = reflect.Append(elems, rv) |
| 68 |
|
| 69 |
relPrimaryValues := make([]interface{}, 0, len(rel.FieldSchema.PrimaryFields)) |
| 70 |
for _, pf := range rel.FieldSchema.PrimaryFields { |
| 71 |
if pfv, ok := pf.ValueOf(db.Statement.Context, rv); !ok { |
| 72 |
relPrimaryValues = append(relPrimaryValues, pfv) |
| 73 |
} |
| 74 |
} |
| 75 |
cacheKey := utils.ToStringKey(relPrimaryValues...) |
| 76 |
if len(relPrimaryValues) != len(rel.FieldSchema.PrimaryFields) || !identityMap[cacheKey] { |
| 77 |
if cacheKey != "" { // has primary fields |
| 78 |
identityMap[cacheKey] = true |
| 79 |
} |
| 80 |
|
| 81 |
distinctElems = reflect.Append(distinctElems, rv) |
| 82 |
} |
| 83 |
} |
| 84 |
} |
| 85 |
|
| 86 |
if elems.Len() > 0 { |
| 87 |
if saveAssociations(db, rel, distinctElems, selectColumns, restricted, nil) == nil { |
| 88 |
for i := 0; i < elems.Len(); i++ { |
| 89 |
setupReferences(objs[i], elems.Index(i)) |
| 90 |
} |
| 91 |
} |
| 92 |
} |
| 93 |
case reflect.Struct: |
| 94 |
if _, zero := rel.Field.ValueOf(db.Statement.Context, db.Statement.ReflectValue); !zero { |
| 95 |
rv := rel.Field.ReflectValueOf(db.Statement.Context, db.Statement.ReflectValue) // relation reflect value |
| 96 |
if rv.Kind() != reflect.Ptr { |
| 97 |
rv = rv.Addr() |
| 98 |
} |
| 99 |
|
| 100 |
if saveAssociations(db, rel, rv, selectColumns, restricted, nil) == nil { |
| 101 |
setupReferences(db.Statement.ReflectValue, rv) |
| 102 |
} |
| 103 |
} |
| 104 |
} |
| 105 |
} |
| 106 |
} |
| 107 |
} |
| 108 |
} |
| 109 |
|
| 110 |
func SaveAfterAssociations(create bool) func(db *gorm.DB) { |
| 111 |
return func(db *gorm.DB) { |
| 112 |
if db.Error == nil && db.Statement.Schema != nil { |
| 113 |
selectColumns, restricted := db.Statement.SelectAndOmitColumns(create, !create) |
| 114 |
|
| 115 |
// Save Has One associations |
| 116 |
for _, rel := range db.Statement.Schema.Relationships.HasOne { |
| 117 |
if v, ok := selectColumns[rel.Name]; (ok && !v) || (!ok && restricted) { |
| 118 |
continue |
| 119 |
} |
| 120 |
|
| 121 |
switch db.Statement.ReflectValue.Kind() { |
| 122 |
case reflect.Slice, reflect.Array: |
| 123 |
var ( |
| 124 |
fieldType = rel.Field.FieldType |
| 125 |
isPtr = fieldType.Kind() == reflect.Ptr |
| 126 |
) |
| 127 |
|
| 128 |
if !isPtr { |
| 129 |
fieldType = reflect.PointerTo(fieldType) |
| 130 |
} |
| 131 |
|
| 132 |
elems := reflect.MakeSlice(reflect.SliceOf(fieldType), 0, 10) |
| 133 |
|
| 134 |
for i := 0; i < db.Statement.ReflectValue.Len(); i++ { |
| 135 |
obj := db.Statement.ReflectValue.Index(i) |
| 136 |
|
| 137 |
if reflect.Indirect(obj).Kind() == reflect.Struct { |
| 138 |
if _, zero := rel.Field.ValueOf(db.Statement.Context, obj); !zero { |
| 139 |
rv := rel.Field.ReflectValueOf(db.Statement.Context, obj) |
| 140 |
if rv.Kind() != reflect.Ptr { |
| 141 |
rv = rv.Addr() |
| 142 |
} |
| 143 |
|
| 144 |
for _, ref := range rel.References { |
| 145 |
if ref.OwnPrimaryKey { |
| 146 |
fv, _ := ref.PrimaryKey.ValueOf(db.Statement.Context, obj) |
| 147 |
db.AddError(ref.ForeignKey.Set(db.Statement.Context, rv, fv)) |
| 148 |
} else if ref.PrimaryValue != "" { |
| 149 |
db.AddError(ref.ForeignKey.Set(db.Statement.Context, rv, ref.PrimaryValue)) |
| 150 |
} |
| 151 |
} |
| 152 |
|
| 153 |
elems = reflect.Append(elems, rv) |
| 154 |
} |
| 155 |
} |
| 156 |
} |
| 157 |
|
| 158 |
if elems.Len() > 0 { |
| 159 |
assignmentColumns := make([]string, 0, len(rel.References)) |
| 160 |
for _, ref := range rel.References { |
| 161 |
assignmentColumns = append(assignmentColumns, ref.ForeignKey.DBName) |
| 162 |
} |
| 163 |
|
| 164 |
saveAssociations(db, rel, elems, selectColumns, restricted, assignmentColumns) |
| 165 |
} |
| 166 |
case reflect.Struct: |
| 167 |
if _, zero := rel.Field.ValueOf(db.Statement.Context, db.Statement.ReflectValue); !zero { |
| 168 |
f := rel.Field.ReflectValueOf(db.Statement.Context, db.Statement.ReflectValue) |
| 169 |
if f.Kind() != reflect.Ptr { |
| 170 |
f = f.Addr() |
| 171 |
} |
| 172 |
|
| 173 |
assignmentColumns := make([]string, 0, len(rel.References)) |
| 174 |
for _, ref := range rel.References { |
| 175 |
if ref.OwnPrimaryKey { |
| 176 |
fv, _ := ref.PrimaryKey.ValueOf(db.Statement.Context, db.Statement.ReflectValue) |
| 177 |
db.AddError(ref.ForeignKey.Set(db.Statement.Context, f, fv)) |
| 178 |
} else if ref.PrimaryValue != "" { |
| 179 |
db.AddError(ref.ForeignKey.Set(db.Statement.Context, f, ref.PrimaryValue)) |
| 180 |
} |
| 181 |
assignmentColumns = append(assignmentColumns, ref.ForeignKey.DBName) |
| 182 |
} |
| 183 |
|
| 184 |
saveAssociations(db, rel, f, selectColumns, restricted, assignmentColumns) |
| 185 |
} |
| 186 |
} |
| 187 |
} |
| 188 |
|
| 189 |
// Save Has Many associations |
| 190 |
for _, rel := range db.Statement.Schema.Relationships.HasMany { |
| 191 |
if v, ok := selectColumns[rel.Name]; (ok && !v) || (!ok && restricted) { |
| 192 |
continue |
| 193 |
} |
| 194 |
|
| 195 |
fieldType := rel.Field.IndirectFieldType.Elem() |
| 196 |
isPtr := fieldType.Kind() == reflect.Ptr |
| 197 |
if !isPtr { |
| 198 |
fieldType = reflect.PointerTo(fieldType) |
| 199 |
} |
| 200 |
elems := reflect.MakeSlice(reflect.SliceOf(fieldType), 0, 10) |
| 201 |
identityMap := map[string]bool{} |
| 202 |
appendToElems := func(v reflect.Value) { |
| 203 |
if _, zero := rel.Field.ValueOf(db.Statement.Context, v); !zero { |
| 204 |
f := reflect.Indirect(rel.Field.ReflectValueOf(db.Statement.Context, v)) |
| 205 |
|
| 206 |
for i := 0; i < f.Len(); i++ { |
| 207 |
elem := f.Index(i) |
| 208 |
for _, ref := range rel.References { |
| 209 |
if ref.OwnPrimaryKey { |
| 210 |
pv, _ := ref.PrimaryKey.ValueOf(db.Statement.Context, v) |
| 211 |
db.AddError(ref.ForeignKey.Set(db.Statement.Context, elem, pv)) |
| 212 |
} else if ref.PrimaryValue != "" { |
| 213 |
db.AddError(ref.ForeignKey.Set(db.Statement.Context, elem, ref.PrimaryValue)) |
| 214 |
} |
| 215 |
} |
| 216 |
|
| 217 |
relPrimaryValues := make([]interface{}, 0, len(rel.FieldSchema.PrimaryFields)) |
| 218 |
for _, pf := range rel.FieldSchema.PrimaryFields { |
| 219 |
if pfv, ok := pf.ValueOf(db.Statement.Context, elem); !ok { |
| 220 |
relPrimaryValues = append(relPrimaryValues, pfv) |
| 221 |
} |
| 222 |
} |
| 223 |
|
| 224 |
cacheKey := utils.ToStringKey(relPrimaryValues...) |
| 225 |
if len(relPrimaryValues) != len(rel.FieldSchema.PrimaryFields) || !identityMap[cacheKey] { |
| 226 |
if cacheKey != "" { // has primary fields |
| 227 |
identityMap[cacheKey] = true |
| 228 |
} |
| 229 |
|
| 230 |
if isPtr { |
| 231 |
elems = reflect.Append(elems, elem) |
| 232 |
} else { |
| 233 |
elems = reflect.Append(elems, elem.Addr()) |
| 234 |
} |
| 235 |
} |
| 236 |
} |
| 237 |
} |
| 238 |
} |
| 239 |
|
| 240 |
switch db.Statement.ReflectValue.Kind() { |
| 241 |
case reflect.Slice, reflect.Array: |
| 242 |
for i := 0; i < db.Statement.ReflectValue.Len(); i++ { |
| 243 |
obj := db.Statement.ReflectValue.Index(i) |
| 244 |
if reflect.Indirect(obj).Kind() == reflect.Struct { |
| 245 |
appendToElems(obj) |
| 246 |
} |
| 247 |
} |
| 248 |
case reflect.Struct: |
| 249 |
appendToElems(db.Statement.ReflectValue) |
| 250 |
} |
| 251 |
|
| 252 |
if elems.Len() > 0 { |
| 253 |
assignmentColumns := make([]string, 0, len(rel.References)) |
| 254 |
for _, ref := range rel.References { |
| 255 |
assignmentColumns = append(assignmentColumns, ref.ForeignKey.DBName) |
| 256 |
} |
| 257 |
|
| 258 |
saveAssociations(db, rel, elems, selectColumns, restricted, assignmentColumns) |
| 259 |
} |
| 260 |
} |
| 261 |
|
| 262 |
// Save Many2Many associations |
| 263 |
for _, rel := range db.Statement.Schema.Relationships.Many2Many { |
| 264 |
if v, ok := selectColumns[rel.Name]; (ok && !v) || (!ok && restricted) { |
| 265 |
continue |
| 266 |
} |
| 267 |
|
| 268 |
fieldType := rel.Field.IndirectFieldType.Elem() |
| 269 |
isPtr := fieldType.Kind() == reflect.Ptr |
| 270 |
if !isPtr { |
| 271 |
fieldType = reflect.PointerTo(fieldType) |
| 272 |
} |
| 273 |
elems := reflect.MakeSlice(reflect.SliceOf(fieldType), 0, 10) |
| 274 |
distinctElems := reflect.MakeSlice(reflect.SliceOf(fieldType), 0, 10) |
| 275 |
joins := reflect.MakeSlice(reflect.SliceOf(reflect.PointerTo(rel.JoinTable.ModelType)), 0, 10) |
| 276 |
objs := []reflect.Value{} |
| 277 |
|
| 278 |
appendToJoins := func(obj reflect.Value, elem reflect.Value) { |
| 279 |
joinValue := reflect.New(rel.JoinTable.ModelType) |
| 280 |
for _, ref := range rel.References { |
| 281 |
if ref.OwnPrimaryKey { |
| 282 |
fv, _ := ref.PrimaryKey.ValueOf(db.Statement.Context, obj) |
| 283 |
db.AddError(ref.ForeignKey.Set(db.Statement.Context, joinValue, fv)) |
| 284 |
} else if ref.PrimaryValue != "" { |
| 285 |
db.AddError(ref.ForeignKey.Set(db.Statement.Context, joinValue, ref.PrimaryValue)) |
| 286 |
} else { |
| 287 |
fv, _ := ref.PrimaryKey.ValueOf(db.Statement.Context, elem) |
| 288 |
db.AddError(ref.ForeignKey.Set(db.Statement.Context, joinValue, fv)) |
| 289 |
} |
| 290 |
} |
| 291 |
joins = reflect.Append(joins, joinValue) |
| 292 |
} |
| 293 |
|
| 294 |
identityMap := map[string]bool{} |
| 295 |
appendToElems := func(v reflect.Value) { |
| 296 |
if _, zero := rel.Field.ValueOf(db.Statement.Context, v); !zero { |
| 297 |
f := reflect.Indirect(rel.Field.ReflectValueOf(db.Statement.Context, v)) |
| 298 |
for i := 0; i < f.Len(); i++ { |
| 299 |
elem := f.Index(i) |
| 300 |
if !isPtr { |
| 301 |
elem = elem.Addr() |
| 302 |
} |
| 303 |
objs = append(objs, v) |
| 304 |
elems = reflect.Append(elems, elem) |
| 305 |
|
| 306 |
relPrimaryValues := make([]interface{}, 0, len(rel.FieldSchema.PrimaryFields)) |
| 307 |
for _, pf := range rel.FieldSchema.PrimaryFields { |
| 308 |
if pfv, ok := pf.ValueOf(db.Statement.Context, elem); !ok { |
| 309 |
relPrimaryValues = append(relPrimaryValues, pfv) |
| 310 |
} |
| 311 |
} |
| 312 |
|
| 313 |
cacheKey := utils.ToStringKey(relPrimaryValues...) |
| 314 |
if len(relPrimaryValues) != len(rel.FieldSchema.PrimaryFields) || !identityMap[cacheKey] { |
| 315 |
if cacheKey != "" { // has primary fields |
| 316 |
identityMap[cacheKey] = true |
| 317 |
} |
| 318 |
|
| 319 |
distinctElems = reflect.Append(distinctElems, elem) |
| 320 |
} |
| 321 |
|
| 322 |
} |
| 323 |
} |
| 324 |
} |
| 325 |
|
| 326 |
switch db.Statement.ReflectValue.Kind() { |
| 327 |
case reflect.Slice, reflect.Array: |
| 328 |
for i := 0; i < db.Statement.ReflectValue.Len(); i++ { |
| 329 |
obj := db.Statement.ReflectValue.Index(i) |
| 330 |
if reflect.Indirect(obj).Kind() == reflect.Struct { |
| 331 |
appendToElems(obj) |
| 332 |
} |
| 333 |
} |
| 334 |
case reflect.Struct: |
| 335 |
appendToElems(db.Statement.ReflectValue) |
| 336 |
} |
| 337 |
|
| 338 |
// optimize elems of reflect value length |
| 339 |
if elemLen := elems.Len(); elemLen > 0 { |
| 340 |
if v, ok := selectColumns[rel.Name+".*"]; !ok || v { |
| 341 |
saveAssociations(db, rel, distinctElems, selectColumns, restricted, nil) |
| 342 |
} |
| 343 |
|
| 344 |
for i := 0; i < elemLen; i++ { |
| 345 |
appendToJoins(objs[i], elems.Index(i)) |
| 346 |
} |
| 347 |
} |
| 348 |
|
| 349 |
if joins.Len() > 0 { |
| 350 |
db.AddError(db.Session(&gorm.Session{NewDB: true}).Clauses(clause.OnConflict{DoNothing: true}).Session(&gorm.Session{ |
| 351 |
SkipHooks: db.Statement.SkipHooks, |
| 352 |
DisableNestedTransaction: true, |
| 353 |
}).Create(joins.Interface()).Error) |
| 354 |
} |
| 355 |
} |
| 356 |
} |
| 357 |
} |
| 358 |
} |
| 359 |
|
| 360 |
func onConflictOption(stmt *gorm.Statement, s *schema.Schema, defaultUpdatingColumns []string) (onConflict clause.OnConflict) { |
| 361 |
if len(defaultUpdatingColumns) > 0 || stmt.DB.FullSaveAssociations { |
| 362 |
onConflict.Columns = make([]clause.Column, 0, len(s.PrimaryFieldDBNames)) |
| 363 |
for _, dbName := range s.PrimaryFieldDBNames { |
| 364 |
onConflict.Columns = append(onConflict.Columns, clause.Column{Name: dbName}) |
| 365 |
} |
| 366 |
|
| 367 |
onConflict.UpdateAll = stmt.DB.FullSaveAssociations |
| 368 |
if !onConflict.UpdateAll { |
| 369 |
onConflict.DoUpdates = clause.AssignmentColumns(defaultUpdatingColumns) |
| 370 |
} |
| 371 |
} else { |
| 372 |
onConflict.DoNothing = true |
| 373 |
} |
| 374 |
|
| 375 |
return |
| 376 |
} |
| 377 |
|
| 378 |
func saveAssociations(db *gorm.DB, rel *schema.Relationship, rValues reflect.Value, selectColumns map[string]bool, restricted bool, defaultUpdatingColumns []string) error { |
| 379 |
// stop save association loop |
| 380 |
if checkAssociationsSaved(db, rValues) { |
| 381 |
return nil |
| 382 |
} |
| 383 |
|
| 384 |
var ( |
| 385 |
selects, omits []string |
| 386 |
onConflict = onConflictOption(db.Statement, rel.FieldSchema, defaultUpdatingColumns) |
| 387 |
refName = rel.Name + "." |
| 388 |
values = rValues.Interface() |
| 389 |
) |
| 390 |
|
| 391 |
for name, ok := range selectColumns { |
| 392 |
columnName := "" |
| 393 |
if strings.HasPrefix(name, refName) { |
| 394 |
columnName = strings.TrimPrefix(name, refName) |
| 395 |
} |
| 396 |
|
| 397 |
if columnName != "" { |
| 398 |
if ok { |
| 399 |
selects = append(selects, columnName) |
| 400 |
} else { |
| 401 |
omits = append(omits, columnName) |
| 402 |
} |
| 403 |
} |
| 404 |
} |
| 405 |
|
| 406 |
tx := db.Session(&gorm.Session{NewDB: true}).Clauses(onConflict).Session(&gorm.Session{ |
| 407 |
FullSaveAssociations: db.FullSaveAssociations, |
| 408 |
SkipHooks: db.Statement.SkipHooks, |
| 409 |
DisableNestedTransaction: true, |
| 410 |
}) |
| 411 |
|
| 412 |
db.Statement.Settings.Range(func(k, v interface{}) bool { |
| 413 |
tx.Statement.Settings.Store(k, v) |
| 414 |
return true |
| 415 |
}) |
| 416 |
|
| 417 |
if tx.Statement.FullSaveAssociations { |
| 418 |
tx = tx.Set("gorm:update_track_time", true) |
| 419 |
} |
| 420 |
|
| 421 |
if len(selects) > 0 { |
| 422 |
tx = tx.Select(selects) |
| 423 |
} else if restricted && len(omits) == 0 { |
| 424 |
tx = tx.Omit(clause.Associations) |
| 425 |
} |
| 426 |
|
| 427 |
if len(omits) > 0 { |
| 428 |
tx = tx.Omit(omits...) |
| 429 |
} |
| 430 |
|
| 431 |
return db.AddError(tx.Create(values).Error) |
| 432 |
} |
| 433 |
|
| 434 |
// check association values has been saved |
| 435 |
// if values kind is Struct, check it has been saved |
| 436 |
// if values kind is Slice/Array, check all items have been saved |
| 437 |
var visitMapStoreKey = "gorm:saved_association_map" |
| 438 |
|
| 439 |
func checkAssociationsSaved(db *gorm.DB, values reflect.Value) bool { |
| 440 |
if visit, ok := db.Get(visitMapStoreKey); ok { |
| 441 |
if v, ok := visit.(*visitMap); ok { |
| 442 |
if loadOrStoreVisitMap(v, values) { |
| 443 |
return true |
| 444 |
} |
| 445 |
} |
| 446 |
} else { |
| 447 |
vistMap := make(visitMap) |
| 448 |
loadOrStoreVisitMap(&vistMap, values) |
| 449 |
db.Set(visitMapStoreKey, &vistMap) |
| 450 |
} |
| 451 |
|
| 452 |
return false |
| 453 |
} |