Fix panic when batch creating from slice contains invalid data, close #3385
This commit is contained in:
		
							parent
							
								
									6a86646469
								
							
						
					
					
						commit
						28121d4455
					
				| @ -1,6 +1,7 @@ | ||||
| package callbacks | ||||
| 
 | ||||
| import ( | ||||
| 	"fmt" | ||||
| 	"reflect" | ||||
| 
 | ||||
| 	"gorm.io/gorm" | ||||
| @ -259,6 +260,11 @@ func ConvertToCreateValues(stmt *gorm.Statement) (values clause.Values) { | ||||
| 
 | ||||
| 			for i := 0; i < stmt.ReflectValue.Len(); i++ { | ||||
| 				rv := reflect.Indirect(stmt.ReflectValue.Index(i)) | ||||
| 				if !rv.IsValid() { | ||||
| 					stmt.AddError(fmt.Errorf("slice data #%v is invalid: %w", i, gorm.ErrInvalidData)) | ||||
| 					return | ||||
| 				} | ||||
| 
 | ||||
| 				values.Values[i] = make([]interface{}, len(values.Columns)) | ||||
| 				for idx, column := range values.Columns { | ||||
| 					field := stmt.Schema.FieldsByDBName[column.Name] | ||||
|  | ||||
| @ -1,6 +1,7 @@ | ||||
| package tests_test | ||||
| 
 | ||||
| import ( | ||||
| 	"errors" | ||||
| 	"testing" | ||||
| 	"time" | ||||
| 
 | ||||
| @ -299,6 +300,18 @@ func TestCreateEmptySlice(t *testing.T) { | ||||
| 	} | ||||
| } | ||||
| 
 | ||||
| func TestCreateInvalidSlice(t *testing.T) { | ||||
| 	users := []*User{ | ||||
| 		GetUser("invalid_slice_1", Config{}), | ||||
| 		GetUser("invalid_slice_2", Config{}), | ||||
| 		nil, | ||||
| 	} | ||||
| 
 | ||||
| 	if err := DB.Create(&users).Error; !errors.Is(err, gorm.ErrInvalidData) { | ||||
| 		t.Errorf("should returns error invalid data when creating from slice that contains invalid data") | ||||
| 	} | ||||
| } | ||||
| 
 | ||||
| func TestCreateWithExistingTimestamp(t *testing.T) { | ||||
| 	user := User{Name: "CreateUserExistingTimestamp"} | ||||
| 	curTime := now.MustParse("2016-01-01") | ||||
|  | ||||
		Loading…
	
	
			
			x
			
			
		
	
		Reference in New Issue
	
	Block a user
	 Jinzhu
						Jinzhu