2020-05-07 05:03:48 +03:00
|
|
|
package callbacks
|
|
|
|
|
|
|
|
import (
|
2021-07-13 16:00:13 +03:00
|
|
|
"fmt"
|
2020-05-14 07:19:12 +03:00
|
|
|
"reflect"
|
2023-04-11 08:10:38 +03:00
|
|
|
"strings"
|
2020-05-14 07:19:12 +03:00
|
|
|
|
2020-06-02 04:16:07 +03:00
|
|
|
"gorm.io/gorm"
|
|
|
|
"gorm.io/gorm/clause"
|
|
|
|
"gorm.io/gorm/schema"
|
|
|
|
"gorm.io/gorm/utils"
|
2020-05-07 05:03:48 +03:00
|
|
|
)
|
|
|
|
|
2023-04-11 08:10:38 +03:00
|
|
|
// parsePreloadMap extracts nested preloads. e.g.
|
|
|
|
//
|
|
|
|
// // schema has a "k0" relation and a "k7.k8" embedded relation
|
|
|
|
// parsePreloadMap(schema, map[string][]interface{}{
|
|
|
|
// clause.Associations: {"arg1"},
|
|
|
|
// "k1": {"arg2"},
|
|
|
|
// "k2.k3": {"arg3"},
|
|
|
|
// "k4.k5.k6": {"arg4"},
|
|
|
|
// })
|
|
|
|
// // preloadMap is
|
|
|
|
// map[string]map[string][]interface{}{
|
|
|
|
// "k0": {},
|
|
|
|
// "k7": {
|
|
|
|
// "k8": {},
|
|
|
|
// },
|
|
|
|
// "k1": {},
|
|
|
|
// "k2": {
|
|
|
|
// "k3": {"arg3"},
|
|
|
|
// },
|
|
|
|
// "k4": {
|
|
|
|
// "k5.k6": {"arg4"},
|
|
|
|
// },
|
|
|
|
// }
|
|
|
|
func parsePreloadMap(s *schema.Schema, preloads map[string][]interface{}) map[string]map[string][]interface{} {
|
|
|
|
preloadMap := map[string]map[string][]interface{}{}
|
|
|
|
setPreloadMap := func(name, value string, args []interface{}) {
|
|
|
|
if _, ok := preloadMap[name]; !ok {
|
|
|
|
preloadMap[name] = map[string][]interface{}{}
|
|
|
|
}
|
|
|
|
if value != "" {
|
|
|
|
preloadMap[name][value] = args
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
for name, args := range preloads {
|
|
|
|
preloadFields := strings.Split(name, ".")
|
|
|
|
value := strings.TrimPrefix(strings.TrimPrefix(name, preloadFields[0]), ".")
|
|
|
|
if preloadFields[0] == clause.Associations {
|
|
|
|
for _, relation := range s.Relationships.Relations {
|
|
|
|
if relation.Schema == s {
|
|
|
|
setPreloadMap(relation.Name, value, args)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
for embedded, embeddedRelations := range s.Relationships.EmbeddedRelations {
|
|
|
|
for _, value := range embeddedValues(embeddedRelations) {
|
|
|
|
setPreloadMap(embedded, value, args)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
setPreloadMap(preloadFields[0], value, args)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return preloadMap
|
|
|
|
}
|
|
|
|
|
|
|
|
func embeddedValues(embeddedRelations *schema.Relationships) []string {
|
|
|
|
if embeddedRelations == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
names := make([]string, 0, len(embeddedRelations.Relations)+len(embeddedRelations.EmbeddedRelations))
|
|
|
|
for _, relation := range embeddedRelations.Relations {
|
|
|
|
// skip first struct name
|
|
|
|
names = append(names, strings.Join(relation.Field.BindNames[1:], "."))
|
|
|
|
}
|
|
|
|
for _, relations := range embeddedRelations.EmbeddedRelations {
|
|
|
|
names = append(names, embeddedValues(relations)...)
|
|
|
|
}
|
|
|
|
return names
|
|
|
|
}
|
|
|
|
|
|
|
|
func preloadEmbedded(tx *gorm.DB, relationships *schema.Relationships, s *schema.Schema, preloads map[string][]interface{}, as []interface{}) error {
|
|
|
|
if relationships == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
preloadMap := parsePreloadMap(s, preloads)
|
|
|
|
for name := range preloadMap {
|
|
|
|
if embeddedRelations := relationships.EmbeddedRelations[name]; embeddedRelations != nil {
|
|
|
|
if err := preloadEmbedded(tx, embeddedRelations, s, preloadMap[name], as); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
} else if rel := relationships.Relations[name]; rel != nil {
|
|
|
|
if err := preload(tx, rel, append(preloads[name], as), preloadMap[name]); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
return fmt.Errorf("%s: %w (embedded) for schema %s", name, gorm.ErrUnsupportedRelation, s.Name)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-03-18 08:38:46 +03:00
|
|
|
func preload(tx *gorm.DB, rel *schema.Relationship, conds []interface{}, preloads map[string][]interface{}) error {
|
2020-05-14 07:19:12 +03:00
|
|
|
var (
|
2022-03-18 08:38:46 +03:00
|
|
|
reflectValue = tx.Statement.ReflectValue
|
2020-05-14 07:19:12 +03:00
|
|
|
relForeignKeys []string
|
|
|
|
relForeignFields []*schema.Field
|
|
|
|
foreignFields []*schema.Field
|
|
|
|
foreignValues [][]interface{}
|
|
|
|
identityMap = map[string][]reflect.Value{}
|
2020-06-01 19:44:48 +03:00
|
|
|
inlineConds []interface{}
|
2020-05-14 07:19:12 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
if rel.JoinTable != nil {
|
2021-03-04 14:44:15 +03:00
|
|
|
var (
|
|
|
|
joinForeignFields = make([]*schema.Field, 0, len(rel.References))
|
|
|
|
joinRelForeignFields = make([]*schema.Field, 0, len(rel.References))
|
|
|
|
joinForeignKeys = make([]string, 0, len(rel.References))
|
|
|
|
)
|
|
|
|
|
2020-05-14 07:19:12 +03:00
|
|
|
for _, ref := range rel.References {
|
|
|
|
if ref.OwnPrimaryKey {
|
|
|
|
joinForeignKeys = append(joinForeignKeys, ref.ForeignKey.DBName)
|
|
|
|
joinForeignFields = append(joinForeignFields, ref.ForeignKey)
|
|
|
|
foreignFields = append(foreignFields, ref.PrimaryKey)
|
|
|
|
} else if ref.PrimaryValue != "" {
|
2020-05-31 09:41:45 +03:00
|
|
|
tx = tx.Where(clause.Eq{Column: ref.ForeignKey.DBName, Value: ref.PrimaryValue})
|
2020-05-14 07:19:12 +03:00
|
|
|
} else {
|
|
|
|
joinRelForeignFields = append(joinRelForeignFields, ref.ForeignKey)
|
|
|
|
relForeignKeys = append(relForeignKeys, ref.PrimaryKey.DBName)
|
|
|
|
relForeignFields = append(relForeignFields, ref.PrimaryKey)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-18 08:38:46 +03:00
|
|
|
joinIdentityMap, joinForeignValues := schema.GetIdentityFieldValuesMap(tx.Statement.Context, reflectValue, foreignFields)
|
2020-05-23 16:03:28 +03:00
|
|
|
if len(joinForeignValues) == 0 {
|
2022-03-18 08:38:46 +03:00
|
|
|
return nil
|
2020-05-23 16:03:28 +03:00
|
|
|
}
|
2020-05-18 08:07:11 +03:00
|
|
|
|
|
|
|
joinResults := rel.JoinTable.MakeSlice().Elem()
|
2021-01-10 09:58:54 +03:00
|
|
|
column, values := schema.ToQueryValues(clause.CurrentTable, joinForeignKeys, joinForeignValues)
|
2022-03-18 08:38:46 +03:00
|
|
|
if err := tx.Where(clause.IN{Column: column, Values: values}).Find(joinResults.Addr().Interface()).Error; err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2020-05-14 07:19:12 +03:00
|
|
|
|
|
|
|
// convert join identity map to relation identity map
|
2020-06-01 03:12:44 +03:00
|
|
|
fieldValues := make([]interface{}, len(joinForeignFields))
|
|
|
|
joinFieldValues := make([]interface{}, len(joinRelForeignFields))
|
2020-05-14 07:19:12 +03:00
|
|
|
for i := 0; i < joinResults.Len(); i++ {
|
2021-11-29 04:33:20 +03:00
|
|
|
joinIndexValue := joinResults.Index(i)
|
2020-05-23 16:03:28 +03:00
|
|
|
for idx, field := range joinForeignFields {
|
2022-03-18 08:38:46 +03:00
|
|
|
fieldValues[idx], _ = field.ValueOf(tx.Statement.Context, joinIndexValue)
|
2020-05-14 07:19:12 +03:00
|
|
|
}
|
|
|
|
|
2020-05-23 16:03:28 +03:00
|
|
|
for idx, field := range joinRelForeignFields {
|
2022-03-18 08:38:46 +03:00
|
|
|
joinFieldValues[idx], _ = field.ValueOf(tx.Statement.Context, joinIndexValue)
|
2020-05-14 07:19:12 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
if results, ok := joinIdentityMap[utils.ToStringKey(fieldValues...)]; ok {
|
2020-06-01 19:44:48 +03:00
|
|
|
joinKey := utils.ToStringKey(joinFieldValues...)
|
|
|
|
identityMap[joinKey] = append(identityMap[joinKey], results...)
|
2020-05-14 07:19:12 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-18 08:38:46 +03:00
|
|
|
_, foreignValues = schema.GetIdentityFieldValuesMap(tx.Statement.Context, joinResults, joinRelForeignFields)
|
2020-05-14 07:19:12 +03:00
|
|
|
} else {
|
|
|
|
for _, ref := range rel.References {
|
|
|
|
if ref.OwnPrimaryKey {
|
|
|
|
relForeignKeys = append(relForeignKeys, ref.ForeignKey.DBName)
|
|
|
|
relForeignFields = append(relForeignFields, ref.ForeignKey)
|
|
|
|
foreignFields = append(foreignFields, ref.PrimaryKey)
|
|
|
|
} else if ref.PrimaryValue != "" {
|
2020-05-31 09:41:45 +03:00
|
|
|
tx = tx.Where(clause.Eq{Column: ref.ForeignKey.DBName, Value: ref.PrimaryValue})
|
2020-05-14 07:19:12 +03:00
|
|
|
} else {
|
|
|
|
relForeignKeys = append(relForeignKeys, ref.PrimaryKey.DBName)
|
|
|
|
relForeignFields = append(relForeignFields, ref.PrimaryKey)
|
|
|
|
foreignFields = append(foreignFields, ref.ForeignKey)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-18 08:38:46 +03:00
|
|
|
identityMap, foreignValues = schema.GetIdentityFieldValuesMap(tx.Statement.Context, reflectValue, foreignFields)
|
2020-05-23 16:03:28 +03:00
|
|
|
if len(foreignValues) == 0 {
|
2022-03-18 08:38:46 +03:00
|
|
|
return nil
|
2020-05-23 16:03:28 +03:00
|
|
|
}
|
2020-05-14 07:19:12 +03:00
|
|
|
}
|
|
|
|
|
2021-01-26 11:33:19 +03:00
|
|
|
// nested preload
|
|
|
|
for p, pvs := range preloads {
|
|
|
|
tx = tx.Preload(p, pvs...)
|
|
|
|
}
|
|
|
|
|
2020-05-18 08:07:11 +03:00
|
|
|
reflectResults := rel.FieldSchema.MakeSlice().Elem()
|
2020-08-25 13:59:19 +03:00
|
|
|
column, values := schema.ToQueryValues(clause.CurrentTable, relForeignKeys, foreignValues)
|
2020-06-01 19:44:48 +03:00
|
|
|
|
2021-07-13 15:23:05 +03:00
|
|
|
if len(values) != 0 {
|
|
|
|
for _, cond := range conds {
|
|
|
|
if fc, ok := cond.(func(*gorm.DB) *gorm.DB); ok {
|
|
|
|
tx = fc(tx)
|
|
|
|
} else {
|
|
|
|
inlineConds = append(inlineConds, cond)
|
|
|
|
}
|
2020-06-01 19:44:48 +03:00
|
|
|
}
|
|
|
|
|
2022-03-18 08:38:46 +03:00
|
|
|
if err := tx.Where(clause.IN{Column: column, Values: values}).Find(reflectResults.Addr().Interface(), inlineConds...).Error; err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-07-13 15:23:05 +03:00
|
|
|
}
|
2020-05-14 07:19:12 +03:00
|
|
|
|
2020-06-01 03:12:44 +03:00
|
|
|
fieldValues := make([]interface{}, len(relForeignFields))
|
2020-06-01 19:44:48 +03:00
|
|
|
|
2020-09-01 08:48:37 +03:00
|
|
|
// clean up old values before preloading
|
|
|
|
switch reflectValue.Kind() {
|
|
|
|
case reflect.Struct:
|
2020-09-04 14:02:37 +03:00
|
|
|
switch rel.Type {
|
|
|
|
case schema.HasMany, schema.Many2Many:
|
2022-03-23 12:24:25 +03:00
|
|
|
tx.AddError(rel.Field.Set(tx.Statement.Context, reflectValue, reflect.MakeSlice(rel.Field.IndirectFieldType, 0, 10).Interface()))
|
2020-09-04 14:02:37 +03:00
|
|
|
default:
|
2022-03-23 12:24:25 +03:00
|
|
|
tx.AddError(rel.Field.Set(tx.Statement.Context, reflectValue, reflect.New(rel.Field.FieldType).Interface()))
|
2020-09-04 14:02:37 +03:00
|
|
|
}
|
2020-09-01 08:48:37 +03:00
|
|
|
case reflect.Slice, reflect.Array:
|
|
|
|
for i := 0; i < reflectValue.Len(); i++ {
|
2020-09-04 14:02:37 +03:00
|
|
|
switch rel.Type {
|
|
|
|
case schema.HasMany, schema.Many2Many:
|
2022-03-23 12:24:25 +03:00
|
|
|
tx.AddError(rel.Field.Set(tx.Statement.Context, reflectValue.Index(i), reflect.MakeSlice(rel.Field.IndirectFieldType, 0, 10).Interface()))
|
2020-09-04 14:02:37 +03:00
|
|
|
default:
|
2022-03-23 12:24:25 +03:00
|
|
|
tx.AddError(rel.Field.Set(tx.Statement.Context, reflectValue.Index(i), reflect.New(rel.Field.FieldType).Interface()))
|
2020-09-04 14:02:37 +03:00
|
|
|
}
|
2020-09-01 08:48:37 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-14 07:19:12 +03:00
|
|
|
for i := 0; i < reflectResults.Len(); i++ {
|
2020-06-01 19:44:48 +03:00
|
|
|
elem := reflectResults.Index(i)
|
2020-05-14 08:48:51 +03:00
|
|
|
for idx, field := range relForeignFields {
|
2022-03-18 08:38:46 +03:00
|
|
|
fieldValues[idx], _ = field.ValueOf(tx.Statement.Context, elem)
|
2020-05-14 07:19:12 +03:00
|
|
|
}
|
|
|
|
|
2021-11-04 08:45:44 +03:00
|
|
|
datas, ok := identityMap[utils.ToStringKey(fieldValues...)]
|
|
|
|
if !ok {
|
2022-03-18 08:38:46 +03:00
|
|
|
return fmt.Errorf("failed to assign association %#v, make sure foreign fields exists", elem.Interface())
|
2021-11-04 08:45:44 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
for _, data := range datas {
|
2022-03-18 08:38:46 +03:00
|
|
|
reflectFieldValue := rel.Field.ReflectValueOf(tx.Statement.Context, data)
|
2021-11-04 08:45:44 +03:00
|
|
|
if reflectFieldValue.Kind() == reflect.Ptr && reflectFieldValue.IsNil() {
|
|
|
|
reflectFieldValue.Set(reflect.New(rel.Field.FieldType.Elem()))
|
|
|
|
}
|
2020-06-01 19:44:48 +03:00
|
|
|
|
2021-11-04 08:45:44 +03:00
|
|
|
reflectFieldValue = reflect.Indirect(reflectFieldValue)
|
|
|
|
switch reflectFieldValue.Kind() {
|
|
|
|
case reflect.Struct:
|
2022-03-23 12:24:25 +03:00
|
|
|
tx.AddError(rel.Field.Set(tx.Statement.Context, data, elem.Interface()))
|
2021-11-04 08:45:44 +03:00
|
|
|
case reflect.Slice, reflect.Array:
|
|
|
|
if reflectFieldValue.Type().Elem().Kind() == reflect.Ptr {
|
2022-03-23 12:24:25 +03:00
|
|
|
tx.AddError(rel.Field.Set(tx.Statement.Context, data, reflect.Append(reflectFieldValue, elem).Interface()))
|
2021-11-04 08:45:44 +03:00
|
|
|
} else {
|
2022-03-23 12:24:25 +03:00
|
|
|
tx.AddError(rel.Field.Set(tx.Statement.Context, data, reflect.Append(reflectFieldValue, elem.Elem()).Interface()))
|
2020-05-14 08:48:51 +03:00
|
|
|
}
|
2020-05-14 07:19:12 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-03-18 08:38:46 +03:00
|
|
|
|
|
|
|
return tx.Error
|
2020-05-07 05:03:48 +03:00
|
|
|
}
|