mirror of https://github.com/go-gorm/gorm.git
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
|
package callbacks
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"reflect"
|
"reflect"
|
||||||
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
|
@ -259,6 +260,11 @@ func ConvertToCreateValues(stmt *gorm.Statement) (values clause.Values) {
|
||||||
|
|
||||||
for i := 0; i < stmt.ReflectValue.Len(); i++ {
|
for i := 0; i < stmt.ReflectValue.Len(); i++ {
|
||||||
rv := reflect.Indirect(stmt.ReflectValue.Index(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))
|
values.Values[i] = make([]interface{}, len(values.Columns))
|
||||||
for idx, column := range values.Columns {
|
for idx, column := range values.Columns {
|
||||||
field := stmt.Schema.FieldsByDBName[column.Name]
|
field := stmt.Schema.FieldsByDBName[column.Name]
|
||||||
|
|
|
@ -1,6 +1,7 @@
|
||||||
package tests_test
|
package tests_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"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) {
|
func TestCreateWithExistingTimestamp(t *testing.T) {
|
||||||
user := User{Name: "CreateUserExistingTimestamp"}
|
user := User{Name: "CreateUserExistingTimestamp"}
|
||||||
curTime := now.MustParse("2016-01-01")
|
curTime := now.MustParse("2016-01-01")
|
||||||
|
|
Loading…
Reference in New Issue