(db *gorm.DB)
| 24 | } |
| 25 | |
| 26 | func DeleteBeforeAssociations(db *gorm.DB) { |
| 27 | if db.Error == nil && db.Statement.Schema != nil { |
| 28 | selectColumns, restricted := db.Statement.SelectAndOmitColumns(true, false) |
| 29 | if !restricted { |
| 30 | return |
| 31 | } |
| 32 | |
| 33 | for column, v := range selectColumns { |
| 34 | if !v { |
| 35 | continue |
| 36 | } |
| 37 | |
| 38 | rel, ok := db.Statement.Schema.Relationships.Relations[column] |
| 39 | if !ok { |
| 40 | continue |
| 41 | } |
| 42 | |
| 43 | switch rel.Type { |
| 44 | case schema.HasOne, schema.HasMany: |
| 45 | queryConds := rel.ToQueryConditions(db.Statement.Context, db.Statement.ReflectValue) |
| 46 | modelValue := reflect.New(rel.FieldSchema.ModelType).Interface() |
| 47 | tx := db.Session(&gorm.Session{NewDB: true}).Model(modelValue) |
| 48 | withoutConditions := false |
| 49 | if db.Statement.Unscoped { |
| 50 | tx = tx.Unscoped() |
| 51 | } |
| 52 | |
| 53 | if len(db.Statement.Selects) > 0 { |
| 54 | selects := make([]string, 0, len(db.Statement.Selects)) |
| 55 | for _, s := range db.Statement.Selects { |
| 56 | if s == clause.Associations { |
| 57 | selects = append(selects, s) |
| 58 | } else if columnPrefix := column + "."; strings.HasPrefix(s, columnPrefix) { |
| 59 | selects = append(selects, strings.TrimPrefix(s, columnPrefix)) |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | if len(selects) > 0 { |
| 64 | tx = tx.Select(selects) |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | for _, cond := range queryConds { |
| 69 | if c, ok := cond.(clause.IN); ok && len(c.Values) == 0 { |
| 70 | withoutConditions = true |
| 71 | break |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | if !withoutConditions && db.AddError(tx.Clauses(clause.Where{Exprs: queryConds}).Delete(modelValue).Error) != nil { |
| 76 | return |
| 77 | } |
| 78 | case schema.Many2Many: |
| 79 | var ( |
| 80 | queryConds = make([]clause.Expression, 0, len(rel.References)) |
| 81 | foreignFields = make([]*schema.Field, 0, len(rel.References)) |
| 82 | relForeignKeys = make([]string, 0, len(rel.References)) |
| 83 | modelValue = reflect.New(rel.JoinTable.ModelType).Interface() |
nothing calls this directly
no test coverage detected