fixed:panic when create value from nil struct pointer. ()

* fixed:create nil pointer

* fixed:panic when create value from nil struct pointer.
This commit is contained in:
kinggo 2021-10-12 21:19:08 +08:00 committed by GitHub
parent 418c60c83c
commit ec58e3319f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 15 additions and 1 deletions

View File

@ -77,7 +77,12 @@ func Parse(dest interface{}, cacheStore *sync.Map, namer Namer) (*Schema, error)
return nil, fmt.Errorf("%w: %+v", ErrUnsupportedDataType, dest) return nil, fmt.Errorf("%w: %+v", ErrUnsupportedDataType, dest)
} }
modelType := reflect.Indirect(reflect.ValueOf(dest)).Type() value := reflect.ValueOf(dest)
if value.Kind() == reflect.Ptr && value.IsNil() {
value = reflect.New(value.Type().Elem())
}
modelType := reflect.Indirect(value).Type()
if modelType.Kind() == reflect.Interface { if modelType.Kind() == reflect.Interface {
modelType = reflect.Indirect(reflect.ValueOf(dest)).Elem().Type() modelType = reflect.Indirect(reflect.ValueOf(dest)).Elem().Type()
} }

View File

@ -517,3 +517,12 @@ func TestCreateFromSubQuery(t *testing.T) {
t.Errorf("invalid insert SQL, got %v", result.Statement.SQL.String()) t.Errorf("invalid insert SQL, got %v", result.Statement.SQL.String())
} }
} }
func TestCreateNilPointer(t *testing.T) {
var user *User
err := DB.Create(user).Error
if err == nil || err != gorm.ErrInvalidValue {
t.Fatalf("it is not ErrInvalidValue")
}
}