From 48b395b760d86fddad7480972791444494a8ae68 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Thu, 3 Sep 2020 11:32:30 +0800 Subject: [PATCH] returns ErrEmptySlice when creating with zero length slice --- callbacks/create.go | 5 +++++ callbacks/helper.go | 5 +++++ errors.go | 2 ++ tests/create_test.go | 12 ++++++++++++ tests/go.mod | 2 ++ 5 files changed, 26 insertions(+) diff --git a/callbacks/create.go b/callbacks/create.go index 5de19d35..e37c2c60 100644 --- a/callbacks/create.go +++ b/callbacks/create.go @@ -252,6 +252,11 @@ func ConvertToCreateValues(stmt *gorm.Statement) (values clause.Values) { stmt.SQL.Grow(stmt.ReflectValue.Len() * 15) values.Values = make([][]interface{}, stmt.ReflectValue.Len()) defaultValueFieldsHavingValue := map[*schema.Field][]interface{}{} + if stmt.ReflectValue.Len() == 0 { + stmt.AddError(gorm.ErrEmptySlice) + return + } + for i := 0; i < stmt.ReflectValue.Len(); i++ { rv := reflect.Indirect(stmt.ReflectValue.Index(i)) values.Values[i] = make([]interface{}, len(values.Columns)) diff --git a/callbacks/helper.go b/callbacks/helper.go index e0a66dd2..09ec4582 100644 --- a/callbacks/helper.go +++ b/callbacks/helper.go @@ -46,6 +46,11 @@ func ConvertSliceOfMapToValuesForCreate(stmt *gorm.Statement, mapValues []map[st selectColumns, restricted = stmt.SelectAndOmitColumns(true, false) ) + if len(mapValues) == 0 { + stmt.AddError(gorm.ErrEmptySlice) + return + } + for idx, mapValue := range mapValues { for k, v := range mapValue { if stmt.Schema != nil { diff --git a/errors.go b/errors.go index 32ff8ec1..508f6957 100644 --- a/errors.go +++ b/errors.go @@ -27,4 +27,6 @@ var ( ErrRegistered = errors.New("registered") // ErrInvalidField invalid field ErrInvalidField = errors.New("invalid field") + // ErrEmptySlice empty slice found + ErrEmptySlice = errors.New("empty slice found") ) diff --git a/tests/create_test.go b/tests/create_test.go index ab0a78d4..59fdd8f1 100644 --- a/tests/create_test.go +++ b/tests/create_test.go @@ -287,6 +287,18 @@ func TestCreateEmptyStruct(t *testing.T) { } } +func TestCreateEmptySlice(t *testing.T) { + var data = []User{} + if err := DB.Create(&data).Error; err != gorm.ErrEmptySlice { + t.Errorf("no data should be created, got %v", err) + } + + var sliceMap = []map[string]interface{}{} + if err := DB.Model(&User{}).Create(&sliceMap).Error; err != gorm.ErrEmptySlice { + t.Errorf("no data should be created, got %v", err) + } +} + func TestCreateWithExistingTimestamp(t *testing.T) { user := User{Name: "CreateUserExistingTimestamp"} curTime := now.MustParse("2016-01-01") diff --git a/tests/go.mod b/tests/go.mod index 30a7dda7..2b336850 100644 --- a/tests/go.mod +++ b/tests/go.mod @@ -16,3 +16,5 @@ require ( replace gorm.io/gorm => ../ replace github.com/jackc/pgx/v4 => github.com/jinzhu/pgx/v4 v4.8.2 + +replace gorm.io/driver/sqlserver => /Users/jinzhu/Projects/jinzhu/sqlserver