Add test for second insert error (#1527)

Add test for second insert error

Reviewed-on: https://gitea.com/xorm/xorm/pulls/1527
This commit is contained in:
Lunny Xiao 2020-02-20 07:52:44 +00:00
parent 189e272774
commit 2513e09caa
3 changed files with 52 additions and 12 deletions

View File

@ -27,7 +27,7 @@ var (
// ErrConditionType condition type unsupported
ErrConditionType = errors.New("Unsupported condition type")
// ErrUnSupportedSQLType parameter of SQL is not supported
ErrUnSupportedSQLType = errors.New("unsupported sql type")
ErrUnSupportedSQLType = errors.New("Unsupported sql type")
)
// ErrFieldIsNotExist columns does not exist

View File

@ -16,6 +16,9 @@ import (
"xorm.io/core"
)
// ErrNoElementsOnSlice represents an error there is no element when insert
var ErrNoElementsOnSlice = errors.New("No element on slice when insert")
// Insert insert one or more beans
func (session *Session) Insert(beans ...interface{}) (int64, error) {
var affected int64
@ -67,7 +70,10 @@ func (session *Session) Insert(beans ...interface{}) (int64, error) {
sliceValue := reflect.Indirect(reflect.ValueOf(bean))
if sliceValue.Kind() == reflect.Slice {
size := sliceValue.Len()
if size > 0 {
if size <= 0 {
return 0, ErrNoElementsOnSlice
}
if session.engine.SupportInsertMany() {
cnt, err := session.innerInsertMulti(bean)
if err != nil {
@ -83,7 +89,6 @@ func (session *Session) Insert(beans ...interface{}) (int64, error) {
affected += cnt
}
}
}
} else {
cnt, err := session.innerInsert(bean)
if err != nil {

View File

@ -1067,3 +1067,38 @@ func TestInsertMultiWithOmit(t *testing.T) {
assert.EqualValues(t, 3, num)
check()
}
func TestInsertTwice(t *testing.T) {
assert.NoError(t, prepareEngine())
type InsertStructA struct {
FieldA int
}
type InsertStructB struct {
FieldB int
}
assert.NoError(t, testEngine.Sync2(new(InsertStructA), new(InsertStructB)))
var sliceA []InsertStructA // sliceA is empty
sliceB := []InsertStructB{
InsertStructB{
FieldB: 1,
},
}
ssn := testEngine.NewSession()
defer ssn.Close()
err := ssn.Begin()
assert.NoError(t, err)
_, err = ssn.Insert(sliceA)
assert.EqualValues(t, ErrNoElementsOnSlice, err)
_, err = ssn.Insert(sliceB)
assert.NoError(t, err)
assert.NoError(t, ssn.Commit())
}