| 1 |
package gorm |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"reflect" |
| 6 |
"strings" |
| 7 |
|
| 8 |
"gorm.io/gorm/clause" |
| 9 |
"gorm.io/gorm/schema" |
| 10 |
"gorm.io/gorm/utils" |
| 11 |
) |
| 12 |
|
| 13 |
// Association Mode contains some helper methods to handle relationship things easily. |
| 14 |
type Association struct { |
| 15 |
DB *DB |
| 16 |
Relationship *schema.Relationship |
| 17 |
Unscope bool |
| 18 |
Error error |
| 19 |
} |
| 20 |
|
| 21 |
func (db *DB) Association(column string) *Association { |
| 22 |
association := &Association{DB: db, Unscope: db.Statement.Unscoped} |
| 23 |
table := db.Statement.Table |
| 24 |
|
| 25 |
if association.Error = db.Statement.Parse(db.Statement.Model); association.Error == nil { |
| 26 |
db.Statement.Table = table |
| 27 |
association.Relationship = db.Statement.Schema.Relationships.Relations[column] |
| 28 |
|
| 29 |
if association.Relationship == nil { |
| 30 |
association.Error = fmt.Errorf("%w: %s", ErrUnsupportedRelation, column) |
| 31 |
} |
| 32 |
|
| 33 |
db.Statement.ReflectValue = reflect.ValueOf(db.Statement.Model) |
| 34 |
for db.Statement.ReflectValue.Kind() == reflect.Ptr { |
| 35 |
db.Statement.ReflectValue = db.Statement.ReflectValue.Elem() |
| 36 |
} |
| 37 |
} |
| 38 |
|
| 39 |
return association |
| 40 |
} |
| 41 |
|
| 42 |
func (association *Association) Unscoped() *Association { |
| 43 |
return &Association{ |
| 44 |
DB: association.DB, |
| 45 |
Relationship: association.Relationship, |
| 46 |
Error: association.Error, |
| 47 |
Unscope: true, |
| 48 |
} |
| 49 |
} |
| 50 |
|
| 51 |
func (association *Association) Find(out interface{}, conds ...interface{}) error { |
| 52 |
if association.Error == nil { |
| 53 |
association.Error = association.buildCondition().Find(out, conds...).Error |
| 54 |
} |
| 55 |
return association.Error |
| 56 |
} |
| 57 |
|
| 58 |
func (association *Association) Append(values ...interface{}) error { |
| 59 |
values = expandValues(values) |
| 60 |
|
| 61 |
if association.Error == nil { |
| 62 |
switch association.Relationship.Type { |
| 63 |
case schema.HasOne, schema.BelongsTo: |
| 64 |
if len(values) > 0 { |
| 65 |
association.Error = association.Replace(values...) |
| 66 |
} |
| 67 |
default: |
| 68 |
association.saveAssociation( /*clear*/ false, values...) |
| 69 |
} |
| 70 |
} |
| 71 |
|
| 72 |
return association.Error |
| 73 |
} |
| 74 |
|
| 75 |
func (association *Association) Replace(values ...interface{}) error { |
| 76 |
values = expandValues(values) |
| 77 |
|
| 78 |
if association.Error == nil { |
| 79 |
reflectValue := association.DB.Statement.ReflectValue |
| 80 |
rel := association.Relationship |
| 81 |
|
| 82 |
var oldBelongsToExpr clause.Expression |
| 83 |
// we have to record the old BelongsTo value |
| 84 |
if association.Unscope && rel.Type == schema.BelongsTo { |
| 85 |
var foreignFields []*schema.Field |
| 86 |
for _, ref := range rel.References { |
| 87 |
if !ref.OwnPrimaryKey { |
| 88 |
foreignFields = append(foreignFields, ref.ForeignKey) |
| 89 |
} |
| 90 |
} |
| 91 |
if _, fvs := schema.GetIdentityFieldValuesMap(association.DB.Statement.Context, reflectValue, foreignFields); len(fvs) > 0 { |
| 92 |
column, values := schema.ToQueryValues(rel.FieldSchema.Table, rel.FieldSchema.PrimaryFieldDBNames, fvs) |
| 93 |
oldBelongsToExpr = clause.IN{Column: column, Values: values} |
| 94 |
} |
| 95 |
} |
| 96 |
|
| 97 |
// save associations |
| 98 |
if association.saveAssociation( /*clear*/ true, values...); association.Error != nil { |
| 99 |
return association.Error |
| 100 |
} |
| 101 |
|
| 102 |
// set old association's foreign key to null |
| 103 |
switch rel.Type { |
| 104 |
case schema.BelongsTo: |
| 105 |
if len(values) == 0 { |
| 106 |
updateMap := map[string]interface{}{} |
| 107 |
switch reflectValue.Kind() { |
| 108 |
case reflect.Slice, reflect.Array: |
| 109 |
for i := 0; i < reflectValue.Len(); i++ { |
| 110 |
association.Error = rel.Field.Set(association.DB.Statement.Context, reflectValue.Index(i), reflect.Zero(rel.Field.FieldType).Interface()) |
| 111 |
} |
| 112 |
case reflect.Struct: |
| 113 |
association.Error = rel.Field.Set(association.DB.Statement.Context, reflectValue, reflect.Zero(rel.Field.FieldType).Interface()) |
| 114 |
} |
| 115 |
|
| 116 |
for _, ref := range rel.References { |
| 117 |
updateMap[ref.ForeignKey.DBName] = nil |
| 118 |
} |
| 119 |
|
| 120 |
association.Error = association.DB.UpdateColumns(updateMap).Error |
| 121 |
} |
| 122 |
if association.Unscope && oldBelongsToExpr != nil { |
| 123 |
association.Error = association.DB.Model(nil).Where(oldBelongsToExpr).Delete(reflect.New(rel.FieldSchema.ModelType).Interface()).Error |
| 124 |
} |
| 125 |
case schema.HasOne, schema.HasMany: |
| 126 |
var ( |
| 127 |
primaryFields []*schema.Field |
| 128 |
foreignKeys []string |
| 129 |
updateMap = map[string]interface{}{} |
| 130 |
relValues = schema.GetRelationsValues(association.DB.Statement.Context, reflectValue, []*schema.Relationship{rel}) |
| 131 |
modelValue = reflect.New(rel.FieldSchema.ModelType).Interface() |
| 132 |
tx = association.DB.Model(modelValue) |
| 133 |
) |
| 134 |
|
| 135 |
if _, rvs := schema.GetIdentityFieldValuesMap(association.DB.Statement.Context, relValues, rel.FieldSchema.PrimaryFields); len(rvs) > 0 { |
| 136 |
if column, values := schema.ToQueryValues(rel.FieldSchema.Table, rel.FieldSchema.PrimaryFieldDBNames, rvs); len(values) > 0 { |
| 137 |
tx.Not(clause.IN{Column: column, Values: values}) |
| 138 |
} |
| 139 |
} |
| 140 |
|
| 141 |
for _, ref := range rel.References { |
| 142 |
if ref.OwnPrimaryKey { |
| 143 |
primaryFields = append(primaryFields, ref.PrimaryKey) |
| 144 |
foreignKeys = append(foreignKeys, ref.ForeignKey.DBName) |
| 145 |
updateMap[ref.ForeignKey.DBName] = nil |
| 146 |
} else if ref.PrimaryValue != "" { |
| 147 |
tx.Where(clause.Eq{Column: ref.ForeignKey.DBName, Value: ref.PrimaryValue}) |
| 148 |
} |
| 149 |
} |
| 150 |
|
| 151 |
if _, pvs := schema.GetIdentityFieldValuesMap(association.DB.Statement.Context, reflectValue, primaryFields); len(pvs) > 0 { |
| 152 |
column, values := schema.ToQueryValues(rel.FieldSchema.Table, foreignKeys, pvs) |
| 153 |
if association.Unscope { |
| 154 |
association.Error = tx.Where(clause.IN{Column: column, Values: values}).Delete(modelValue).Error |
| 155 |
} else { |
| 156 |
association.Error = tx.Where(clause.IN{Column: column, Values: values}).UpdateColumns(updateMap).Error |
| 157 |
} |
| 158 |
} |
| 159 |
case schema.Many2Many: |
| 160 |
var ( |
| 161 |
primaryFields, relPrimaryFields []*schema.Field |
| 162 |
joinPrimaryKeys, joinRelPrimaryKeys []string |
| 163 |
modelValue = reflect.New(rel.JoinTable.ModelType).Interface() |
| 164 |
tx = association.DB.Model(modelValue) |
| 165 |
) |
| 166 |
|
| 167 |
for _, ref := range rel.References { |
| 168 |
if ref.PrimaryValue == "" { |
| 169 |
if ref.OwnPrimaryKey { |
| 170 |
primaryFields = append(primaryFields, ref.PrimaryKey) |
| 171 |
joinPrimaryKeys = append(joinPrimaryKeys, ref.ForeignKey.DBName) |
| 172 |
} else { |
| 173 |
relPrimaryFields = append(relPrimaryFields, ref.PrimaryKey) |
| 174 |
joinRelPrimaryKeys = append(joinRelPrimaryKeys, ref.ForeignKey.DBName) |
| 175 |
} |
| 176 |
} else { |
| 177 |
tx.Clauses(clause.Eq{Column: ref.ForeignKey.DBName, Value: ref.PrimaryValue}) |
| 178 |
} |
| 179 |
} |
| 180 |
|
| 181 |
_, pvs := schema.GetIdentityFieldValuesMap(association.DB.Statement.Context, reflectValue, primaryFields) |
| 182 |
if column, values := schema.ToQueryValues(rel.JoinTable.Table, joinPrimaryKeys, pvs); len(values) > 0 { |
| 183 |
tx.Where(clause.IN{Column: column, Values: values}) |
| 184 |
} else { |
| 185 |
return ErrPrimaryKeyRequired |
| 186 |
} |
| 187 |
|
| 188 |
_, rvs := schema.GetIdentityFieldValuesMapFromValues(association.DB.Statement.Context, values, relPrimaryFields) |
| 189 |
if relColumn, relValues := schema.ToQueryValues(rel.JoinTable.Table, joinRelPrimaryKeys, rvs); len(relValues) > 0 { |
| 190 |
tx.Where(clause.Not(clause.IN{Column: relColumn, Values: relValues})) |
| 191 |
} |
| 192 |
|
| 193 |
association.Error = tx.Delete(modelValue).Error |
| 194 |
} |
| 195 |
} |
| 196 |
return association.Error |
| 197 |
} |
| 198 |
|
| 199 |
func (association *Association) Delete(values ...interface{}) error { |
| 200 |
values = expandValues(values) |
| 201 |
|
| 202 |
if association.Error == nil { |
| 203 |
var ( |
| 204 |
reflectValue = association.DB.Statement.ReflectValue |
| 205 |
rel = association.Relationship |
| 206 |
primaryFields []*schema.Field |
| 207 |
foreignKeys []string |
| 208 |
updateAttrs = map[string]interface{}{} |
| 209 |
conds []clause.Expression |
| 210 |
) |
| 211 |
|
| 212 |
for _, ref := range rel.References { |
| 213 |
if ref.PrimaryValue == "" { |
| 214 |
primaryFields = append(primaryFields, ref.PrimaryKey) |
| 215 |
foreignKeys = append(foreignKeys, ref.ForeignKey.DBName) |
| 216 |
updateAttrs[ref.ForeignKey.DBName] = nil |
| 217 |
} else { |
| 218 |
conds = append(conds, clause.Eq{Column: ref.ForeignKey.DBName, Value: ref.PrimaryValue}) |
| 219 |
} |
| 220 |
} |
| 221 |
|
| 222 |
switch rel.Type { |
| 223 |
case schema.BelongsTo: |
| 224 |
associationDB := association.DB.Session(&Session{}) |
| 225 |
tx := associationDB.Model(reflect.New(rel.Schema.ModelType).Interface()) |
| 226 |
|
| 227 |
_, pvs := schema.GetIdentityFieldValuesMap(association.DB.Statement.Context, reflectValue, rel.Schema.PrimaryFields) |
| 228 |
if pcolumn, pvalues := schema.ToQueryValues(rel.Schema.Table, rel.Schema.PrimaryFieldDBNames, pvs); len(pvalues) > 0 { |
| 229 |
conds = append(conds, clause.IN{Column: pcolumn, Values: pvalues}) |
| 230 |
} else { |
| 231 |
return ErrPrimaryKeyRequired |
| 232 |
} |
| 233 |
|
| 234 |
_, rvs := schema.GetIdentityFieldValuesMapFromValues(association.DB.Statement.Context, values, primaryFields) |
| 235 |
relColumn, relValues := schema.ToQueryValues(rel.Schema.Table, foreignKeys, rvs) |
| 236 |
conds = append(conds, clause.IN{Column: relColumn, Values: relValues}) |
| 237 |
|
| 238 |
association.Error = tx.Clauses(conds...).UpdateColumns(updateAttrs).Error |
| 239 |
if association.Unscope { |
| 240 |
var foreignFields []*schema.Field |
| 241 |
for _, ref := range rel.References { |
| 242 |
if !ref.OwnPrimaryKey { |
| 243 |
foreignFields = append(foreignFields, ref.ForeignKey) |
| 244 |
} |
| 245 |
} |
| 246 |
if _, fvs := schema.GetIdentityFieldValuesMap(association.DB.Statement.Context, reflectValue, foreignFields); len(fvs) > 0 { |
| 247 |
column, values := schema.ToQueryValues(rel.FieldSchema.Table, rel.FieldSchema.PrimaryFieldDBNames, fvs) |
| 248 |
association.Error = associationDB.Model(nil).Where(clause.IN{Column: column, Values: values}).Delete(reflect.New(rel.FieldSchema.ModelType).Interface()).Error |
| 249 |
} |
| 250 |
} |
| 251 |
case schema.HasOne, schema.HasMany: |
| 252 |
model := reflect.New(rel.FieldSchema.ModelType).Interface() |
| 253 |
tx := association.DB.Model(model) |
| 254 |
|
| 255 |
_, pvs := schema.GetIdentityFieldValuesMap(association.DB.Statement.Context, reflectValue, primaryFields) |
| 256 |
if pcolumn, pvalues := schema.ToQueryValues(rel.FieldSchema.Table, foreignKeys, pvs); len(pvalues) > 0 { |
| 257 |
conds = append(conds, clause.IN{Column: pcolumn, Values: pvalues}) |
| 258 |
} else { |
| 259 |
return ErrPrimaryKeyRequired |
| 260 |
} |
| 261 |
|
| 262 |
_, rvs := schema.GetIdentityFieldValuesMapFromValues(association.DB.Statement.Context, values, rel.FieldSchema.PrimaryFields) |
| 263 |
relColumn, relValues := schema.ToQueryValues(rel.FieldSchema.Table, rel.FieldSchema.PrimaryFieldDBNames, rvs) |
| 264 |
conds = append(conds, clause.IN{Column: relColumn, Values: relValues}) |
| 265 |
|
| 266 |
if association.Unscope { |
| 267 |
association.Error = tx.Clauses(conds...).Delete(model).Error |
| 268 |
} else { |
| 269 |
association.Error = tx.Clauses(conds...).UpdateColumns(updateAttrs).Error |
| 270 |
} |
| 271 |
case schema.Many2Many: |
| 272 |
var ( |
| 273 |
primaryFields, relPrimaryFields []*schema.Field |
| 274 |
joinPrimaryKeys, joinRelPrimaryKeys []string |
| 275 |
joinValue = reflect.New(rel.JoinTable.ModelType).Interface() |
| 276 |
) |
| 277 |
|
| 278 |
for _, ref := range rel.References { |
| 279 |
if ref.PrimaryValue == "" { |
| 280 |
if ref.OwnPrimaryKey { |
| 281 |
primaryFields = append(primaryFields, ref.PrimaryKey) |
| 282 |
joinPrimaryKeys = append(joinPrimaryKeys, ref.ForeignKey.DBName) |
| 283 |
} else { |
| 284 |
relPrimaryFields = append(relPrimaryFields, ref.PrimaryKey) |
| 285 |
joinRelPrimaryKeys = append(joinRelPrimaryKeys, ref.ForeignKey.DBName) |
| 286 |
} |
| 287 |
} else { |
| 288 |
conds = append(conds, clause.Eq{Column: ref.ForeignKey.DBName, Value: ref.PrimaryValue}) |
| 289 |
} |
| 290 |
} |
| 291 |
|
| 292 |
_, pvs := schema.GetIdentityFieldValuesMap(association.DB.Statement.Context, reflectValue, primaryFields) |
| 293 |
if pcolumn, pvalues := schema.ToQueryValues(rel.JoinTable.Table, joinPrimaryKeys, pvs); len(pvalues) > 0 { |
| 294 |
conds = append(conds, clause.IN{Column: pcolumn, Values: pvalues}) |
| 295 |
} else { |
| 296 |
return ErrPrimaryKeyRequired |
| 297 |
} |
| 298 |
|
| 299 |
_, rvs := schema.GetIdentityFieldValuesMapFromValues(association.DB.Statement.Context, values, relPrimaryFields) |
| 300 |
relColumn, relValues := schema.ToQueryValues(rel.JoinTable.Table, joinRelPrimaryKeys, rvs) |
| 301 |
conds = append(conds, clause.IN{Column: relColumn, Values: relValues}) |
| 302 |
|
| 303 |
association.Error = association.DB.Where(clause.Where{Exprs: conds}).Model(nil).Delete(joinValue).Error |
| 304 |
} |
| 305 |
|
| 306 |
if association.Error == nil { |
| 307 |
// clean up deleted values' foreign key |
| 308 |
relValuesMap, _ := schema.GetIdentityFieldValuesMapFromValues(association.DB.Statement.Context, values, rel.FieldSchema.PrimaryFields) |
| 309 |
|
| 310 |
cleanUpDeletedRelations := func(data reflect.Value) { |
| 311 |
if _, zero := rel.Field.ValueOf(association.DB.Statement.Context, data); !zero { |
| 312 |
fieldValue := reflect.Indirect(rel.Field.ReflectValueOf(association.DB.Statement.Context, data)) |
| 313 |
primaryValues := make([]interface{}, len(rel.FieldSchema.PrimaryFields)) |
| 314 |
|
| 315 |
switch fieldValue.Kind() { |
| 316 |
case reflect.Slice, reflect.Array: |
| 317 |
validFieldValues := reflect.Zero(rel.Field.IndirectFieldType) |
| 318 |
for i := 0; i < fieldValue.Len(); i++ { |
| 319 |
for idx, field := range rel.FieldSchema.PrimaryFields { |
| 320 |
primaryValues[idx], _ = field.ValueOf(association.DB.Statement.Context, fieldValue.Index(i)) |
| 321 |
} |
| 322 |
|
| 323 |
if _, ok := relValuesMap[utils.ToStringKey(primaryValues...)]; !ok { |
| 324 |
validFieldValues = reflect.Append(validFieldValues, fieldValue.Index(i)) |
| 325 |
} |
| 326 |
} |
| 327 |
|
| 328 |
association.Error = rel.Field.Set(association.DB.Statement.Context, data, validFieldValues.Interface()) |
| 329 |
case reflect.Struct: |
| 330 |
for idx, field := range rel.FieldSchema.PrimaryFields { |
| 331 |
primaryValues[idx], _ = field.ValueOf(association.DB.Statement.Context, fieldValue) |
| 332 |
} |
| 333 |
|
| 334 |
if _, ok := relValuesMap[utils.ToStringKey(primaryValues...)]; ok { |
| 335 |
if association.Error = rel.Field.Set(association.DB.Statement.Context, data, reflect.Zero(rel.FieldSchema.ModelType).Interface()); association.Error != nil { |
| 336 |
break |
| 337 |
} |
| 338 |
|
| 339 |
if rel.JoinTable == nil { |
| 340 |
for _, ref := range rel.References { |
| 341 |
if ref.OwnPrimaryKey || ref.PrimaryValue != "" { |
| 342 |
association.Error = ref.ForeignKey.Set(association.DB.Statement.Context, fieldValue, reflect.Zero(ref.ForeignKey.FieldType).Interface()) |
| 343 |
} else { |
| 344 |
association.Error = ref.ForeignKey.Set(association.DB.Statement.Context, data, reflect.Zero(ref.ForeignKey.FieldType).Interface()) |
| 345 |
} |
| 346 |
} |
| 347 |
} |
| 348 |
} |
| 349 |
} |
| 350 |
} |
| 351 |
} |
| 352 |
|
| 353 |
switch reflectValue.Kind() { |
| 354 |
case reflect.Slice, reflect.Array: |
| 355 |
for i := 0; i < reflectValue.Len(); i++ { |
| 356 |
cleanUpDeletedRelations(reflect.Indirect(reflectValue.Index(i))) |
| 357 |
} |
| 358 |
case reflect.Struct: |
| 359 |
cleanUpDeletedRelations(reflectValue) |
| 360 |
} |
| 361 |
} |
| 362 |
} |
| 363 |
|
| 364 |
return association.Error |
| 365 |
} |
| 366 |
|
| 367 |
func (association *Association) Clear() error { |
| 368 |
return association.Replace() |
| 369 |
} |
| 370 |
|
| 371 |
func (association *Association) Count() (count int64) { |
| 372 |
if association.Error == nil { |
| 373 |
association.Error = association.buildCondition().Count(&count).Error |
| 374 |
} |
| 375 |
return |
| 376 |
} |
| 377 |
|
| 378 |
type assignBack struct { |
| 379 |
Source reflect.Value |
| 380 |
Index int |
| 381 |
Dest reflect.Value |
| 382 |
} |
| 383 |
|
| 384 |
func (association *Association) saveAssociation(clear bool, values ...interface{}) { |
| 385 |
var ( |
| 386 |
reflectValue = association.DB.Statement.ReflectValue |
| 387 |
assignBacks []assignBack // assign association values back to arguments after save |
| 388 |
) |
| 389 |
|
| 390 |
appendToRelations := func(source, rv reflect.Value, clear bool) { |
| 391 |
switch association.Relationship.Type { |
| 392 |
case schema.HasOne, schema.BelongsTo: |
| 393 |
switch rv.Kind() { |
| 394 |
case reflect.Slice, reflect.Array: |
| 395 |
if rv.Len() > 0 { |
| 396 |
association.Error = association.Relationship.Field.Set(association.DB.Statement.Context, source, rv.Index(0).Addr().Interface()) |
| 397 |
|
| 398 |
if association.Relationship.Field.FieldType.Kind() == reflect.Struct { |
| 399 |
assignBacks = append(assignBacks, assignBack{Source: source, Dest: rv.Index(0)}) |
| 400 |
} |
| 401 |
} |
| 402 |
case reflect.Struct: |
| 403 |
if !rv.CanAddr() { |
| 404 |
association.Error = ErrInvalidValue |
| 405 |
return |
| 406 |
} |
| 407 |
association.Error = association.Relationship.Field.Set(association.DB.Statement.Context, source, rv.Addr().Interface()) |
| 408 |
|
| 409 |
if association.Relationship.Field.FieldType.Kind() == reflect.Struct { |
| 410 |
assignBacks = append(assignBacks, assignBack{Source: source, Dest: rv}) |
| 411 |
} |
| 412 |
} |
| 413 |
case schema.HasMany, schema.Many2Many: |
| 414 |
elemType := association.Relationship.Field.IndirectFieldType.Elem() |
| 415 |
oldFieldValue := reflect.Indirect(association.Relationship.Field.ReflectValueOf(association.DB.Statement.Context, source)) |
| 416 |
var fieldValue reflect.Value |
| 417 |
if clear { |
| 418 |
fieldValue = reflect.MakeSlice(oldFieldValue.Type(), 0, oldFieldValue.Cap()) |
| 419 |
} else { |
| 420 |
fieldValue = reflect.MakeSlice(oldFieldValue.Type(), oldFieldValue.Len(), oldFieldValue.Cap()) |
| 421 |
reflect.Copy(fieldValue, oldFieldValue) |
| 422 |
} |
| 423 |
|
| 424 |
appendToFieldValues := func(ev reflect.Value) { |
| 425 |
if ev.Type().AssignableTo(elemType) { |
| 426 |
fieldValue = reflect.Append(fieldValue, ev) |
| 427 |
} else if ev.Type().Elem().AssignableTo(elemType) { |
| 428 |
fieldValue = reflect.Append(fieldValue, ev.Elem()) |
| 429 |
} else { |
| 430 |
association.Error = fmt.Errorf("unsupported data type: %v for relation %s", ev.Type(), association.Relationship.Name) |
| 431 |
} |
| 432 |
|
| 433 |
if elemType.Kind() == reflect.Struct { |
| 434 |
assignBacks = append(assignBacks, assignBack{Source: source, Dest: ev, Index: fieldValue.Len()}) |
| 435 |
} |
| 436 |
} |
| 437 |
|
| 438 |
processMap := func(mapv reflect.Value) { |
| 439 |
child := reflect.New(association.Relationship.FieldSchema.ModelType) |
| 440 |
|
| 441 |
switch association.Relationship.Type { |
| 442 |
case schema.HasMany: |
| 443 |
for _, ref := range association.Relationship.References { |
| 444 |
key := reflect.ValueOf(ref.ForeignKey.DBName) |
| 445 |
if ref.OwnPrimaryKey { |
| 446 |
v := ref.PrimaryKey.ReflectValueOf(association.DB.Statement.Context, source) |
| 447 |
mapv.SetMapIndex(key, v) |
| 448 |
} else if ref.PrimaryValue != "" { |
| 449 |
mapv.SetMapIndex(key, reflect.ValueOf(ref.PrimaryValue)) |
| 450 |
} |
| 451 |
} |
| 452 |
association.Error = association.DB.Session(&Session{ |
| 453 |
NewDB: true, |
| 454 |
}).Model(child.Interface()).Create(mapv.Interface()).Error |
| 455 |
case schema.Many2Many: |
| 456 |
association.Error = association.DB.Session(&Session{ |
| 457 |
NewDB: true, |
| 458 |
}).Model(child.Interface()).Create(mapv.Interface()).Error |
| 459 |
|
| 460 |
for _, key := range mapv.MapKeys() { |
| 461 |
k := strings.ToLower(key.String()) |
| 462 |
if f, ok := association.Relationship.FieldSchema.FieldsByDBName[k]; ok { |
| 463 |
_ = f.Set(association.DB.Statement.Context, child, mapv.MapIndex(key).Interface()) |
| 464 |
} |
| 465 |
} |
| 466 |
appendToFieldValues(child) |
| 467 |
} |
| 468 |
} |
| 469 |
|
| 470 |
switch rv.Kind() { |
| 471 |
case reflect.Map: |
| 472 |
processMap(rv) |
| 473 |
case reflect.Slice, reflect.Array: |
| 474 |
for i := 0; i < rv.Len(); i++ { |
| 475 |
elem := reflect.Indirect(rv.Index(i)) |
| 476 |
if elem.Kind() == reflect.Map { |
| 477 |
processMap(elem) |
| 478 |
continue |
| 479 |
} |
| 480 |
appendToFieldValues(elem.Addr()) |
| 481 |
} |
| 482 |
case reflect.Struct: |
| 483 |
if !rv.CanAddr() { |
| 484 |
association.Error = ErrInvalidValue |
| 485 |
return |
| 486 |
} |
| 487 |
appendToFieldValues(rv.Addr()) |
| 488 |
} |
| 489 |
|
| 490 |
if association.Error == nil { |
| 491 |
association.Error = association.Relationship.Field.Set(association.DB.Statement.Context, source, fieldValue.Interface()) |
| 492 |
} |
| 493 |
} |
| 494 |
} |
| 495 |
|
| 496 |
selectedSaveColumns := []string{association.Relationship.Name} |
| 497 |
omitColumns := []string{} |
| 498 |
selectColumns, _ := association.DB.Statement.SelectAndOmitColumns(true, false) |
| 499 |
for name, ok := range selectColumns { |
| 500 |
columnName := "" |
| 501 |
if strings.HasPrefix(name, association.Relationship.Name) { |
| 502 |
if columnName = strings.TrimPrefix(name, association.Relationship.Name); columnName == ".*" { |
| 503 |
columnName = name |
| 504 |
} |
| 505 |
} else if strings.HasPrefix(name, clause.Associations) { |
| 506 |
columnName = name |
| 507 |
} |
| 508 |
|
| 509 |
if columnName != "" { |
| 510 |
if ok { |
| 511 |
selectedSaveColumns = append(selectedSaveColumns, columnName) |
| 512 |
} else { |
| 513 |
omitColumns = append(omitColumns, columnName) |
| 514 |
} |
| 515 |
} |
| 516 |
} |
| 517 |
|
| 518 |
for _, ref := range association.Relationship.References { |
| 519 |
if !ref.OwnPrimaryKey { |
| 520 |
selectedSaveColumns = append(selectedSaveColumns, ref.ForeignKey.Name) |
| 521 |
} |
| 522 |
} |
| 523 |
|
| 524 |
associationDB := association.DB.Session(&Session{}).Model(nil) |
| 525 |
if !association.DB.FullSaveAssociations { |
| 526 |
associationDB.Select(selectedSaveColumns) |
| 527 |
} |
| 528 |
if len(omitColumns) > 0 { |
| 529 |
associationDB.Omit(omitColumns...) |
| 530 |
} |
| 531 |
associationDB = associationDB.Session(&Session{}) |
| 532 |
|
| 533 |
switch reflectValue.Kind() { |
| 534 |
case reflect.Slice, reflect.Array: |
| 535 |
if len(values) != reflectValue.Len() { |
| 536 |
// clear old data |
| 537 |
if clear && len(values) == 0 { |
| 538 |
for i := 0; i < reflectValue.Len(); i++ { |
| 539 |
if err := association.Relationship.Field.Set(association.DB.Statement.Context, reflectValue.Index(i), reflect.New(association.Relationship.Field.IndirectFieldType).Interface()); err != nil { |
| 540 |
association.Error = err |
| 541 |
break |
| 542 |
} |
| 543 |
|
| 544 |
if association.Relationship.JoinTable == nil { |
| 545 |
for _, ref := range association.Relationship.References { |
| 546 |
if !ref.OwnPrimaryKey && ref.PrimaryValue == "" { |
| 547 |
if err := ref.ForeignKey.Set(association.DB.Statement.Context, reflectValue.Index(i), reflect.Zero(ref.ForeignKey.FieldType).Interface()); err != nil { |
| 548 |
association.Error = err |
| 549 |
break |
| 550 |
} |
| 551 |
} |
| 552 |
} |
| 553 |
} |
| 554 |
} |
| 555 |
break |
| 556 |
} |
| 557 |
|
| 558 |
association.Error = ErrInvalidValueOfLength |
| 559 |
return |
| 560 |
} |
| 561 |
|
| 562 |
for i := 0; i < reflectValue.Len(); i++ { |
| 563 |
appendToRelations(reflectValue.Index(i), reflect.Indirect(reflect.ValueOf(values[i])), clear) |
| 564 |
if association.Error != nil { |
| 565 |
return |
| 566 |
} |
| 567 |
|
| 568 |
// TODO support save slice data, sql with case? |
| 569 |
association.Error = associationDB.Updates(reflectValue.Index(i).Addr().Interface()).Error |
| 570 |
} |
| 571 |
case reflect.Struct: |
| 572 |
// clear old data |
| 573 |
if clear && len(values) == 0 { |
| 574 |
association.Error = association.Relationship.Field.Set(association.DB.Statement.Context, reflectValue, reflect.New(association.Relationship.Field.IndirectFieldType).Interface()) |
| 575 |
|
| 576 |
if association.Relationship.JoinTable == nil && association.Error == nil { |
| 577 |
for _, ref := range association.Relationship.References { |
| 578 |
if !ref.OwnPrimaryKey && ref.PrimaryValue == "" { |
| 579 |
association.Error = ref.ForeignKey.Set(association.DB.Statement.Context, reflectValue, reflect.Zero(ref.ForeignKey.FieldType).Interface()) |
| 580 |
} |
| 581 |
} |
| 582 |
} |
| 583 |
} |
| 584 |
|
| 585 |
for idx, value := range values { |
| 586 |
rv := reflect.Indirect(reflect.ValueOf(value)) |
| 587 |
appendToRelations(reflectValue, rv, clear && idx == 0) |
| 588 |
if association.Error != nil { |
| 589 |
return |
| 590 |
} |
| 591 |
} |
| 592 |
|
| 593 |
if len(values) > 0 { |
| 594 |
association.Error = associationDB.Updates(reflectValue.Addr().Interface()).Error |
| 595 |
} |
| 596 |
} |
| 597 |
|
| 598 |
for _, assignBack := range assignBacks { |
| 599 |
fieldValue := reflect.Indirect(association.Relationship.Field.ReflectValueOf(association.DB.Statement.Context, assignBack.Source)) |
| 600 |
if assignBack.Index > 0 { |
| 601 |
reflect.Indirect(assignBack.Dest).Set(fieldValue.Index(assignBack.Index - 1)) |
| 602 |
} else { |
| 603 |
reflect.Indirect(assignBack.Dest).Set(fieldValue) |
| 604 |
} |
| 605 |
} |
| 606 |
} |
| 607 |
|
| 608 |
func (association *Association) buildCondition() *DB { |
| 609 |
var ( |
| 610 |
queryConds = association.Relationship.ToQueryConditions(association.DB.Statement.Context, association.DB.Statement.ReflectValue) |
| 611 |
modelValue = reflect.New(association.Relationship.FieldSchema.ModelType).Interface() |
| 612 |
tx = association.DB.Model(modelValue) |
| 613 |
) |
| 614 |
|
| 615 |
if association.Relationship.JoinTable != nil { |
| 616 |
if !tx.Statement.Unscoped && len(association.Relationship.JoinTable.QueryClauses) > 0 { |
| 617 |
joinStmt := Statement{DB: tx, Context: tx.Statement.Context, Schema: association.Relationship.JoinTable, Table: association.Relationship.JoinTable.Table, Clauses: map[string]clause.Clause{}} |
| 618 |
for _, queryClause := range association.Relationship.JoinTable.QueryClauses { |
| 619 |
joinStmt.AddClause(queryClause) |
| 620 |
} |
| 621 |
joinStmt.Build("WHERE") |
| 622 |
if len(joinStmt.SQL.String()) > 0 { |
| 623 |
tx.Clauses(clause.Expr{SQL: strings.Replace(joinStmt.SQL.String(), "WHERE ", "", 1), Vars: joinStmt.Vars}) |
| 624 |
} |
| 625 |
} |
| 626 |
|
| 627 |
tx = tx.Session(&Session{QueryFields: true}).Clauses(clause.From{Joins: []clause.Join{{ |
| 628 |
Table: clause.Table{Name: association.Relationship.JoinTable.Table}, |
| 629 |
ON: clause.Where{Exprs: queryConds}, |
| 630 |
}}}) |
| 631 |
} else { |
| 632 |
tx.Clauses(clause.Where{Exprs: queryConds}) |
| 633 |
} |
| 634 |
|
| 635 |
return tx |
| 636 |
} |
| 637 |
|
| 638 |
func expandValues(values ...any) (results []any) { |
| 639 |
appendToResult := func(rv reflect.Value) { |
| 640 |
// unwrap interface |
| 641 |
if rv.IsValid() && rv.Kind() == reflect.Interface { |
| 642 |
rv = rv.Elem() |
| 643 |
} |
| 644 |
if rv.IsValid() && rv.Kind() == reflect.Struct { |
| 645 |
p := reflect.New(rv.Type()) |
| 646 |
p.Elem().Set(rv) |
| 647 |
results = append(results, p.Interface()) |
| 648 |
} else if rv.IsValid() { |
| 649 |
results = append(results, rv.Interface()) |
| 650 |
} |
| 651 |
} |
| 652 |
|
| 653 |
// Process each argument; if an argument is a slice/array, expand its elements |
| 654 |
for _, value := range values { |
| 655 |
rv := reflect.ValueOf(value) |
| 656 |
if rv.Kind() == reflect.Slice || rv.Kind() == reflect.Array { |
| 657 |
for i := 0; i < rv.Len(); i++ { |
| 658 |
appendToResult(rv.Index(i)) |
| 659 |
} |
| 660 |
} else { |
| 661 |
appendToResult(rv) |
| 662 |
} |
| 663 |
} |
| 664 |
return |
| 665 |
} |