Don't use value's first field to guess data type for struct implements GormDataTypeInterface

This commit is contained in:
Jinzhu 2020-07-17 12:02:00 +08:00
parent 362779575c
commit 6dc583869b
1 changed files with 21 additions and 19 deletions

View File

@ -105,28 +105,30 @@ func (schema *Schema) ParseField(fieldStruct reflect.StructField) *Field {
// if field is valuer, used its value or first fields as data type // if field is valuer, used its value or first fields as data type
valuer, isValuer := fieldValue.Interface().(driver.Valuer) valuer, isValuer := fieldValue.Interface().(driver.Valuer)
if isValuer { if isValuer {
var overrideFieldValue bool if _, ok := fieldValue.Interface().(GormDataTypeInterface); !ok {
if v, err := valuer.Value(); v != nil && err == nil { var overrideFieldValue bool
overrideFieldValue = true if v, err := valuer.Value(); v != nil && err == nil {
fieldValue = reflect.ValueOf(v) overrideFieldValue = true
} fieldValue = reflect.ValueOf(v)
}
if field.IndirectFieldType.Kind() == reflect.Struct { if field.IndirectFieldType.Kind() == reflect.Struct {
for i := 0; i < field.IndirectFieldType.NumField(); i++ { for i := 0; i < field.IndirectFieldType.NumField(); i++ {
if !overrideFieldValue { if !overrideFieldValue {
newFieldType := field.IndirectFieldType.Field(i).Type newFieldType := field.IndirectFieldType.Field(i).Type
for newFieldType.Kind() == reflect.Ptr { for newFieldType.Kind() == reflect.Ptr {
newFieldType = newFieldType.Elem() newFieldType = newFieldType.Elem()
}
fieldValue = reflect.New(newFieldType)
overrideFieldValue = true
} }
fieldValue = reflect.New(newFieldType) // copy tag settings from valuer
overrideFieldValue = true for key, value := range ParseTagSetting(field.IndirectFieldType.Field(i).Tag.Get("gorm"), ";") {
} if _, ok := field.TagSettings[key]; !ok {
field.TagSettings[key] = value
// copy tag settings from valuer }
for key, value := range ParseTagSetting(field.IndirectFieldType.Field(i).Tag.Get("gorm"), ";") {
if _, ok := field.TagSettings[key]; !ok {
field.TagSettings[key] = value
} }
} }
} }