From ec58e3319feef549f3f0b01235e3254559b5828c Mon Sep 17 00:00:00 2001 From: kinggo <30891428+longlihale@users.noreply.github.com> Date: Tue, 12 Oct 2021 21:19:08 +0800 Subject: [PATCH] fixed:panic when create value from nil struct pointer. (#4771) * fixed:create nil pointer * fixed:panic when create value from nil struct pointer. --- schema/schema.go | 7 ++++++- tests/create_test.go | 9 +++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/schema/schema.go b/schema/schema.go index c425070b..60a434fa 100644 --- a/schema/schema.go +++ b/schema/schema.go @@ -77,7 +77,12 @@ func Parse(dest interface{}, cacheStore *sync.Map, namer Namer) (*Schema, error) 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 { modelType = reflect.Indirect(reflect.ValueOf(dest)).Elem().Type() } diff --git a/tests/create_test.go b/tests/create_test.go index bd968ea8..060f78af 100644 --- a/tests/create_test.go +++ b/tests/create_test.go @@ -517,3 +517,12 @@ func TestCreateFromSubQuery(t *testing.T) { 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") + } +}